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.
n_oscillators
property
¶
Number of oscillators/qubits represented by the problem.
K
property
¶
Alias for the validated coupling matrix.
__post_init__()
¶
Validate inputs and freeze defensive copies after construction.
validate()
¶
Re-run the public validation contract for this problem.
to_metadata()
¶
Return serialisable metadata for result artifacts.
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
¶
omega_for_oscillators(n_oscillators)
¶
Return deterministic natural frequencies for n_oscillators.
The first 16 entries are the canonical Paper 27 values in
:data:OMEGA_N_16. Larger synthetic networks use a periodic extension of
that measured table so scalable classical, co-simulation, and partitioned
examples receive a full-length vector without fabricating new Paper 27 data.
Parameters¶
n_oscillators: Number of oscillator frequencies to return; must be at least one.
Returns¶
numpy.ndarray
A fresh float64 vector of length n_oscillators.
Raises¶
TypeError
If n_oscillators is not an integer.
ValueError
If n_oscillators is below one.
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 boost constants.
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.
Attributes¶
domain
Application domain that produced the oscillator data.
source_name
Human-readable source dataset or stream name.
source_mode
Provenance mode from ALL_SOURCE_MODES.
K_nm
Finite symmetric non-negative coupling matrix with zero diagonal.
omega
Finite natural-frequency vector aligned with K_nm.
theta0
Optional finite initial-phase vector aligned with omega.
layer_assignments
Optional oscillator-to-layer labels.
normalization
Description of the applied normalization.
extraction_method
Description of the source-to-oscillator extraction method.
source_timestamp
Optional source acquisition timestamp.
replay_id
Optional reproducible source-run identifier.
metadata
Recursively immutable JSON-compatible provenance metadata.
hashes
SHA-256 digests of the canonical numeric arrays.
n_oscillators
property
¶
Number of oscillators/qubits implied by the artifact.
is_synthetic
property
¶
Whether this artifact is non-publication synthetic data.
__post_init__()
¶
Validate, hash, copy, and freeze all artifact fields.
require_publication_safe()
¶
Reject synthetic or insufficiently traceable artifacts.
Raises¶
ValueError If the source mode is synthetic or lacks a timestamp and replay ID.
to_dict()
¶
Serialise to a JSON-compatible hash-locked mapping.
Returns¶
dict[str, Any]
Canonical artifact payload with an artifact_sha256 digest.
to_json(*, indent=2)
¶
from_dict(data)
classmethod
¶
from_json(payload)
classmethod
¶
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'.
Parameters¶
payload
Canonical sc-neurocore.scpn.datastream.v1 payload.
source_mode
Smoke-test provenance mode for the adapted artifact.
domain
Domain label assigned to the artifact.
source_name
Source stream name assigned to the artifact.
normalization
Normalization description assigned to the artifact.
extraction_method
Extraction-method description assigned to the artifact.
Returns¶
QPUDataArtifact Hash-locked synthetic artifact with deterministic replay identity.
Raises¶
ValueError If the stream schema, replay fields, arrays, or identity fields are invalid, or if a non-smoke-test provenance mode is requested.
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)
¶
Construct a QPU data artifact from oscillator arrays.
Parameters¶
domain
Application domain that produced the oscillator data.
source_name
Source dataset or stream name.
source_mode
Provenance mode from ALL_SOURCE_MODES.
K_nm
Coupling matrix.
omega
Natural-frequency vector.
normalization
Applied normalization description.
extraction_method
Source-to-oscillator extraction description.
theta0
Optional initial-phase vector.
layer_assignments
Optional oscillator-to-layer labels.
source_timestamp
Optional source acquisition timestamp.
replay_id
Optional reproducible source-run identifier.
metadata
Optional JSON-compatible provenance metadata.
Returns¶
QPUDataArtifact Validated immutable and hash-locked 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.
validate_qpu_data_artifact(artifact, *, require_publication_safe=True)
¶
Validate a QPU artifact and optionally enforce publication safety.
Parameters¶
artifact Existing artifact or versioned artifact mapping. require_publication_safe Whether to reject synthetic or insufficiently traceable provenance.
Returns¶
QPUDataArtifact Validated immutable artifact.
Raises¶
ValueError If artifact validation or the requested publication-safety gate fails.
read_qpu_data_artifact(path)
¶
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 of any numeric dtype; integer spike trains are accepted and coerced to float64. 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 of any numeric dtype; the integer spike trains an SNN produces are accepted and coerced to float64. 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, deadline_monotonic=None, cancelled=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 cap all declared live state, evolution,
measurement and trajectory buffers before Qiskit allocation. History
admission also includes the Python time list. Snapshot admission is
not a bound on undeclared third-party workspaces. The local reservation
serializes cooperating calls in this process. deadline_monotonic
and cancelled are checked at evolution/history checkpoints; native
calls already in progress are not forcibly terminated.
energy_expectation(sv)
¶
Compute
scpn_quantum_control.phase.kuramoto_variants
¶
Higher-order, monitored, and PT-symmetric Kuramoto trajectories.
KuramotoVariant
¶
Bases: StrEnum
Supported Kuramoto trajectory variants.
KuramotoVariantResult
dataclass
¶
Trajectory and diagnostics for one Kuramoto variant run.
HigherOrderKuramotoSpec
dataclass
¶
Pairwise Kuramoto system plus anchored triadic simplicial couplings.
__post_init__()
¶
Validate and defensively freeze the higher-order specification.
MonitoredKuramotoSpec
dataclass
¶
Kuramoto trajectory with deterministic measurement-feedback closure.
__post_init__()
¶
Validate and defensively freeze the monitored specification.
PTSymmetricKuramotoSpec
dataclass
¶
Complex Kuramoto oscillator system with balanced gain/loss channels.
__post_init__()
¶
Validate balanced gain/loss data and freeze the PT specification.
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).
PhaseVQEResult
¶
Bases: TypedDict
Structured result returned by :meth:PhaseVQE.solve.
scpn_quantum_control.phase.coupling_learning
¶
Parameter-shift coupling learning for oscillator observation models.
CouplingGradientVerificationResult
dataclass
¶
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.coupling_time_series_recovery
¶
Recover bounded Kuramoto/XY coupling matrices from synthetic time series.
COUPLING_RECOVERY_CLAIM_BOUNDARY = 'bounded synthetic Kuramoto phase and XY pair-energy time-series recovery with known ground truth; not hardware Hamiltonian learning, provider execution, isolated timing, or arbitrary partial-observation inference'
module-attribute
¶
Claim boundary attached to bounded coupling-recovery records.
COUPLING_RECOVERY_EVIDENCE_CLASS = 'functional_non_isolated'
module-attribute
¶
Evidence class for local synthetic recovery runs.
CouplingRecoveryBoundaryRow
dataclass
¶
CouplingRecoveryCase
dataclass
¶
Synthetic known-ground-truth recovery case.
Parameters¶
case_id:
Stable case identifier used in evidence artefacts.
family:
Recovery family: "kuramoto_phase" or "xy_pair_energy".
true_couplings:
Symmetric zero-diagonal ground-truth coupling matrix.
omega:
Natural frequencies for the phase trajectory generator.
theta0:
Initial phases for the phase trajectory generator.
dt:
Fixed time step for synthetic trajectory generation.
n_steps:
Number of integration steps.
noise_std:
Additive Gaussian observation-noise standard deviation.
missing_fraction:
Fraction of observations replaced by NaN.
seed:
Seed used for the noise/missing mask.
tolerance:
Maximum allowed absolute coupling error for the case.
CouplingRecoveryRecord
dataclass
¶
CouplingRecoverySuiteResult
dataclass
¶
Result of the bounded coupling-recovery evidence suite.
coupling_recovery_boundary_rows()
¶
Return fail-closed boundaries for unsupported recovery routes.
default_coupling_recovery_cases()
¶
Return deterministic known-ground-truth recovery cases.
inject_time_series_noise_and_missing(values, *, noise_std, missing_fraction, seed)
¶
Add deterministic Gaussian noise and NaN missing observations.
recover_kuramoto_couplings_from_time_series(phases, omega, true_couplings, *, dt, case_id='kuramoto_time_series', edges=None, ridge=1e-09, noise_std=0.0, missing_fraction=0.0, tolerance=0.01)
¶
Recover Kuramoto couplings from phase time series with known truth.
recover_xy_couplings_from_pair_energy_series(pair_energy, phases, true_couplings, *, case_id='xy_pair_energy', edges=None, ridge=1e-09, noise_std=0.0, missing_fraction=0.0, tolerance=0.01)
¶
Recover XY couplings from edge-resolved pair-energy observations.
run_coupling_recovery_suite(cases=None)
¶
Run the deterministic bounded coupling-recovery evidence suite.
simulate_kuramoto_phase_time_series(couplings, omega, theta0, *, dt, n_steps)
¶
Generate a fixed-step RK4 Kuramoto phase trajectory.
simulate_xy_pair_energy_time_series(couplings, phases)
¶
Generate synthetic edge-resolved XY pair-energy observations.
scpn_quantum_control.phase.synchronisation_witness
¶
Order-parameter and persistent-homology synchronisation witnesses.
Provides bounded synchronisation witnesses over synthetic phase clouds: harmonic
Kuramoto order parameters, exact Vietoris--Rips persistent homology (Betti curves
and persistence diagrams in dimensions 0 and 1) over geodesic phase
distances, bootstrap uncertainty on the order parameter, and deterministic
synchronised, desynchronised, and clustered reference regimes. The persistence
computation is the standard reduction of the boundary matrix over GF(2) and
is exact for the small phase clouds used here; it is not an accelerated timing
kernel, hardware phase tomography, or high-dimensional manifold inference.
SYNC_WITNESS_CLAIM_BOUNDARY = 'bounded synthetic phase-cloud synchronisation witnesses (harmonic Kuramoto order parameters and exact Vietoris-Rips persistent homology in dimensions 0 and 1 over geodesic phase distances) with known reference regimes; not hardware phase tomography, provider execution, isolated timing, or high-dimensional manifold inference'
module-attribute
¶
Claim boundary attached to synchronisation-witness records.
SYNC_WITNESS_EVIDENCE_CLASS = 'functional_non_isolated'
module-attribute
¶
Evidence class for local synthetic synchronisation-witness runs.
PhaseCloudRegime = Literal['synchronised', 'desynchronised', 'clustered']
module-attribute
¶
SyncWitnessBoundaryRow
dataclass
¶
SyncWitnessCase
dataclass
¶
Deterministic synchronisation-witness reference case.
Parameters¶
case_id : str
Stable identifier used in evidence artefacts.
regime : str
Reference regime: "synchronised", "desynchronised", or
"clustered".
phases : numpy.ndarray
Base phase cloud in radians.
thresholds : numpy.ndarray
Strictly increasing filtration thresholds for the Betti curves.
reference_scale : float
Filtration scale at which the persistent component count is read.
noise_std : float
Standard deviation of the bootstrap phase perturbation.
n_bootstrap : int
Number of bootstrap perturbations used for the order-parameter
uncertainty. 0 disables the bootstrap.
seed : int
Seed for the deterministic bootstrap perturbation.
min_order_parameter : float
Lower bound the first-harmonic order parameter must satisfy.
max_order_parameter : float
Upper bound the first-harmonic order parameter must satisfy.
expected_components : int
Expected persistent component count at reference_scale.
min_dominant_h1 : float
Lower bound on the dominant H1 persistence lifetime.
max_dominant_h1 : float
Upper bound on the dominant H1 persistence lifetime.
SyncWitnessRecord
dataclass
¶
SyncWitnessSuiteResult
dataclass
¶
Result of a bounded synchronisation-witness evidence suite.
betti_curve(persistence_pairs, thresholds)
¶
Return the Betti curve of one homology dimension over thresholds.
Parameters¶
persistence_pairs : array_like
(k, 2) array of (birth, death) pairs for a single dimension.
An empty array yields an all-zero curve.
thresholds : array_like
Strictly increasing non-negative filtration thresholds.
Returns¶
numpy.ndarray
Integer Betti number alive at each threshold, birth <= t < death.
default_sync_witness_cases()
¶
Return deterministic synchronisation-witness reference cases.
geodesic_phase_distance_matrix(phases)
¶
harmonic_order_parameter(phases, *, harmonic=1)
¶
Return the magnitude of the harmonic-th Kuramoto order parameter.
Parameters¶
phases : array_like
One-dimensional array of oscillator phases in radians.
harmonic : int, optional
Positive harmonic index m of the Daido order parameter
|mean(exp(i * m * phases))|. harmonic=1 recovers the global
Kuramoto order parameter; harmonic=2 witnesses two-cluster
(anti-phase) structure.
Returns¶
float
The order-parameter magnitude in [0, 1].
phase_cloud_synchronisation_witness(phases, *, thresholds, reference_scale, case_id='phase_cloud', regime='synchronised', noise_std=0.0, n_bootstrap=0, seed=0, min_order_parameter=0.0, max_order_parameter=1.0, expected_components=1, min_dominant_h1=0.0, max_dominant_h1=float(np.pi))
¶
Compute the synchronisation witness for one phase cloud.
Parameters¶
phases : array_like
One-dimensional array of oscillator phases in radians.
thresholds : array_like
Strictly increasing filtration thresholds for the Betti curves.
reference_scale : float
Filtration scale at which the persistent component count is read.
case_id : str, optional
Stable identifier used in the returned record.
regime : str, optional
Reference regime the witness is checked against.
noise_std : float, optional
Standard deviation of the bootstrap phase perturbation.
n_bootstrap : int, optional
Number of bootstrap perturbations for the order-parameter uncertainty.
seed : int, optional
Seed for the deterministic bootstrap.
min_order_parameter, max_order_parameter : float, optional
Inclusive bounds the first-harmonic order parameter must satisfy.
expected_components : int, optional
Expected persistent component count at reference_scale.
min_dominant_h1, max_dominant_h1 : float, optional
Inclusive bounds on the dominant H1 persistence lifetime.
Returns¶
SyncWitnessRecord The order-parameter and persistent-homology witness certificate.
run_sync_witness_suite(cases=None)
¶
Run the deterministic synchronisation-witness evidence suite.
sync_witness_boundary_rows()
¶
Return fail-closed synchronisation-witness boundary rows.
vietoris_rips_persistence(distance, *, max_dimension=1)
¶
Return exact Vietoris--Rips persistence pairs by homology dimension.
The boundary matrix over the filtered Rips complex is reduced over GF(2)
with the standard lowest-one algorithm. Essential classes (never filled by a
higher simplex) are reported with an infinite death. The result is exact for
the small point clouds used by the synchronisation-witness suite.
Parameters¶
distance : array_like
Symmetric zero-diagonal non-negative pairwise distance matrix.
max_dimension : int, optional
Highest homology dimension to certify. 0 builds edges only (H0);
1 also builds triangles so that H1 loops can be filled.
Returns¶
dict of int to numpy.ndarray
Mapping from homology dimension to an (k, 2) array of
(birth, death) pairs. Deaths may be inf for essential classes.
scpn_quantum_control.phase.differentiable_audit
¶
Reviewer-facing differentiable quantum gradient audit reports.
DifferentiableQuantumAuditReport
dataclass
¶
DifferentiableWorkflowAuditSuiteResult
dataclass
¶
Aggregate evidence across supported differentiable quantum workflows.
worst_gradient_error
property
¶
The largest gradient error across all audit workflows.
best_training_values
property
¶
Best training values for phase and coupling-training lanes.
__post_init__()
¶
Validate workflow labels, unsupported cases, and claim metadata.
to_dict()
¶
Return JSON-ready workflow-audit evidence.
FiniteShotGradientAuditResult
dataclass
¶
MLFrameworkGradientAuditRecord
dataclass
¶
MLFrameworkGradientAuditSuiteResult
dataclass
¶
Fail-closed parity report for optional ML gradient adapters.
executed_frameworks
property
¶
Frameworks whose adapters were executed.
unavailable_frameworks
property
¶
Frameworks whose optional dependencies were unavailable.
blocked_frameworks
property
¶
Frameworks available but not executable without caller-owned objects.
failed_frameworks
property
¶
Frameworks that executed and failed parity.
worst_executed_error
property
¶
The largest error across executed ML adapters.
__post_init__()
¶
Validate framework uniqueness and aggregate claim metadata.
to_dict()
¶
Return JSON-ready ML framework parity evidence.
ParameterShiftAnalyticAgreement
dataclass
¶
PhaseGradientBenchmarkSuiteResult
dataclass
¶
Aggregate result for the built-in phase-gradient conformance suite.
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.
NaturalGradientRegularizationPolicy
dataclass
¶
Regularisation controls for singular or ill-conditioned metric solves.
to_dict()
¶
Return JSON-ready regularisation controls.
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, eigenvalue_floor=0.0, max_condition_number=1000000000000.0, degeneracy_tolerance=1e-10)
¶
Solve a regularised metric system fail-closed.
The returned direction is a preconditioned descent direction for
minimisation steps of the form params - step_size * direction. Singular
or ill-conditioned positive-semidefinite metrics receive the smallest
diagonal shift required by the damping, eigenvalue-floor, and condition
policy. Indefinite metrics fail closed instead of being silently repaired.
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, eigenvalue_floor=0.0, max_condition_number=1000000000000.0, degeneracy_tolerance=1e-10, 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.trainability
¶
Barren-plateau diagnostics and finite-shot dry-run planning.
TRAINABILITY_CLAIM_BOUNDARY = 'local parameter-shift trainability diagnostic and finite-shot dry-run only; no hardware execution, provider submission, convergence guarantee, or benchmark promotion is implied'
module-attribute
¶
TrainabilityGradientSample
dataclass
¶
One parameter-shift gradient sample used by a trainability report.
Parameters¶
index
Zero-based sample index from the caller-supplied parameter matrix.
params
Parameter vector evaluated for this sample.
value
Scalar objective value at params.
gradient
Parameter-shift gradient at params.
gradient_norm
Euclidean norm of gradient.
evaluations
Objective evaluations consumed by the parameter-shift rule.
method
Gradient method reported by the differentiable core.
AdaptiveShotAllocationDryRun
dataclass
¶
Finite-shot allocation and cost estimate without backend execution.
Parameters¶
allocation
Variance-aware plus/minus shot allocation returned by the stochastic
differentiable estimator.
backend_plan
Gradient backend plan used only for dry-run evaluation accounting.
variance_source
Source of the plus/minus variances, either caller-supplied or derived
from sampled gradient variance.
estimated_shift_evaluations
Number of shifted circuit evaluations required by the backend plan.
estimated_quantum_shots
Sum of all planned plus/minus shot counts.
estimated_cost
estimated_quantum_shots * cost_per_shot in cost_unit.
cost_unit
Caller-supplied unit label for the dry-run cost estimate.
capped
Whether a shot cap prevented the target standard error.
hardware_execution
Always False for this dry-run record.
BarrenPlateauTrainabilityReport
dataclass
¶
Aggregate trainability diagnostics for a bounded phase objective.
Parameters¶
samples
Parameter-shift gradient samples used to compute the diagnostics.
gradient_mean
Per-parameter empirical mean of the sampled gradients.
gradient_variance
Per-parameter unbiased empirical gradient variance.
mean_gradient_norm
Mean Euclidean gradient norm across samples.
gradient_norm_variance
Unbiased empirical variance of gradient norms.
barren_plateau_detected
True when both sampled gradient norm and variance sit below the
configured thresholds.
status
Compact trainability classification derived from the diagnostics.
warnings
Machine-readable warning labels for low norm, low variance, and shot
caps.
shot_dry_run
Adaptive shot-allocation dry run for finite-shot parameter-shift use.
claim_boundary
Explicit non-hardware and non-promotion boundary for the report.
run_barren_plateau_trainability_report(objective, sample_params, *, parameters=None, rule=None, plus_variances=None, minus_variances=None, target_standard_error=0.02, gradient_variance_threshold=1e-08, gradient_norm_threshold=1e-06, min_shots=16, max_shots_per_evaluation=None, backend='finite_shot_simulator', cost_per_shot=0.0, cost_unit='abstract_shot_cost')
¶
Build a trainability report and finite-shot dry-run allocation.
Parameters¶
objective
Scalar objective accepting a one-dimensional float64 parameter
vector.
sample_params
Matrix of parameter vectors. At least two samples are required so the
empirical gradient variance is defined.
parameters
Optional parameter metadata controlling names and trainable masks.
rule
Optional single- or multi-frequency parameter-shift rule.
plus_variances, minus_variances
Optional caller-supplied finite-shot measurement variances. When absent,
the report derives a conservative variance tensor from sampled gradient
variance and gradient_variance_threshold.
target_standard_error
Desired standard error for each trainable gradient component.
gradient_variance_threshold
Low-variance threshold and variance floor for derived shot allocation.
gradient_norm_threshold
Low-gradient-norm threshold for barren-plateau classification.
min_shots
Minimum shots for each plus/minus shifted evaluation.
max_shots_per_evaluation
Optional cap for each shifted evaluation.
backend
Backend name passed to the quantum-gradient planner. Hardware backends
fail closed because this function never requests hardware approval.
cost_per_shot
Non-negative dry-run cost multiplier.
cost_unit
Non-empty label for estimated_cost.
Returns¶
BarrenPlateauTrainabilityReport Gradient-variance diagnostics and a zero-execution shot-allocation dry run.
Raises¶
ValueError If inputs are malformed or if the backend planner reports a fail-closed route.
The report samples parameter-shift gradients across caller-supplied parameter vectors, flags flat low-variance landscapes, and uses the existing finite-shot allocator to estimate shot counts before any backend execution.
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.optimizer_convergence_suite
¶
Convergence certificates for small phase ground-state objectives.
GROUND_STATE_OPTIMIZER_CLAIM_BOUNDARY = 'local functional optimizer-convergence evidence on deterministic small phase ground-state objectives; not isolated-core timing evidence, not hardware execution, and not a global optimality claim'
module-attribute
¶
GROUND_STATE_OPTIMIZER_EVIDENCE_CLASS = 'functional_non_isolated'
module-attribute
¶
KnownGroundStateObjective
dataclass
¶
One deterministic small phase objective with a known ground state.
width
property
¶
The number of trainable phase parameters.
__post_init__()
¶
Validate and freeze the ground-state objective arrays.
value(params)
¶
Return the exact phase objective value at params.
metric_tensor(params)
¶
Return the diagonal local metric used for natural-gradient runs.
wrapped_parameter_distance(params)
¶
Return the Euclidean distance to the target modulo 2π.
to_dict()
¶
Return JSON-ready objective metadata.
GroundStateConvergenceCertificate
dataclass
¶
Machine-checkable convergence certificate for one optimizer run.
to_dict()
¶
Return JSON-ready certificate evidence.
GroundStateOptimizerRunRecord
dataclass
¶
GroundStateOptimizerBoundaryRow
dataclass
¶
GroundStateOptimizerConvergenceSuiteResult
dataclass
¶
Ground-state optimizer comparison suite with benchmark rows.
passed
property
¶
Whether every executable optimizer certificate passed.
optimizer_names
property
¶
Optimizer names in first-seen order.
case_count
property
¶
The number of ground-state objective cases.
record_count
property
¶
The number of executable optimizer rows.
records_for_case(case_id)
¶
Return executable records for one objective case.
best_record_for_case(case_id)
¶
Return the lowest-energy executable record for one objective case.
to_dict()
¶
Return JSON-ready suite evidence.
default_ground_state_optimizer_objectives()
¶
Return deterministic small ground-state optimizer objectives.
run_ground_state_optimizer_convergence_suite(objectives=None, *, optimizers=('natural_gradient', 'adam', 'lbfgs', 'spsa', 'cobyla'), learning_rate=0.45, max_steps=96, spsa_perturbation=0.12, spsa_seed=17, include_qng_qjit_boundary=True, parameters=None, rule=None)
¶
Run optimizer convergence evidence on known small ground states.
scpn_quantum_control.phase.open_system_objectives
¶
Bounded Lindblad and MCWF objective certificates.
OPEN_SYSTEM_OBJECTIVE_CLAIM_BOUNDARY = 'Bounded open-system objective evidence uses scipy Lindblad density-matrix evolution and seeded MCWF trajectory ensembles on small local systems. Gradients are deterministic central finite differences over scalar coupling and damping scales; they are not hardware gradients, adjoint Lindblad gradients, unbiased stochastic-gradient estimators, or isolated performance benchmarks.'
module-attribute
¶
OPEN_SYSTEM_OBJECTIVE_EVIDENCE_CLASS = 'functional_non_isolated'
module-attribute
¶
BoundedOpenSystemObjectiveCase
dataclass
¶
DensityMatrixInvariantCertificate
dataclass
¶
Trace, Hermiticity, and positivity certificate for a density matrix.
to_dict()
¶
Return JSON-ready density-matrix invariant evidence.
MCWFReproducibilityCertificate
dataclass
¶
Seeded trajectory-batch reproducibility certificate.
to_dict()
¶
Return JSON-ready trajectory reproducibility evidence.
OpenSystemObjectiveRecord
dataclass
¶
OpenSystemObjectiveBoundaryRow
dataclass
¶
OpenSystemObjectiveSuiteResult
dataclass
¶
Bounded open-system objective suite result.
passed
property
¶
Whether all executable objective records passed.
case_count
property
¶
The number of objective cases.
record_count
property
¶
The number of executable objective rows.
backend_names
property
¶
The backend names present in executable rows.
records_for_case(case_id)
¶
Return all executable records for case_id.
to_dict()
¶
Return JSON-ready suite evidence.
certify_density_matrix_invariants(case, rho)
¶
Certify trace preservation, Hermiticity, and positivity for rho.
certify_mcwf_reproducibility(case, first, second)
¶
Certify same-seed MCWF ensemble replay and trajectory batching.
default_open_system_objective_cases()
¶
Return deterministic bounded open-system objective cases.
evaluate_lindblad_objective(case, params)
¶
Evaluate one density-matrix Lindblad objective.
evaluate_mcwf_objective(case, params)
¶
Evaluate one seeded MCWF trajectory-ensemble objective.
open_system_objective_boundary_rows()
¶
Return approximation and promotion rows for open-system objectives.
run_open_system_objective_suite(cases=None, *, backends=('lindblad_density', 'mcwf_ensemble'), include_boundary_rows=True)
¶
Run bounded Lindblad and MCWF objective evidence rows.
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
¶
Weighted differentiable objective term with explicit gradient semantics.
ComposedPhaseObjective
dataclass
¶
Named weighted sum of differentiable phase-control objective terms.
parameter_shift_compatible
property
¶
Whether every term is compatible with parameter-shift.
term_names
property
¶
Objective term names.
__post_init__()
¶
Validate the objective identity and uniqueness of its 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_backend
¶
Backend-aware quantum-gradient planning for phase objectives.
QuantumGradientBackendCapability
dataclass
¶
Declared gradient capabilities for one execution backend family.
QuantumGradientPlan
dataclass
¶
Fail-closed gradient execution plan for a supported or unsupported backend.
fail_closed
property
¶
Whether this plan intentionally refuses execution.
QuantumGradientRejectedMethod
dataclass
¶
Rejected method candidate from a deterministic backend planner explanation.
Parameters¶
method Candidate method that was considered and not selected. reasons Deterministic reasons the candidate was not selected. supported_if_requested Whether the candidate would be executable if requested directly with the same backend capability and shot controls.
to_dict()
¶
Return JSON-ready rejected-method metadata.
QuantumGradientShotPolicy
dataclass
¶
Shot and uncertainty policy attached to a planner explanation.
Parameters¶
finite_shot Whether the selected plan consumes finite-shot samples. requested_shots Caller-supplied shot count before planner defaults are applied. planned_shots Shot count in the selected plan after defaults and validation. defaulted Whether the planner supplied a backend default shot count. confidence_level Confidence level used by finite-shot uncertainty metadata. seed Optional deterministic seed for stochastic planners. reasons Human-readable shot-policy explanation.
to_dict()
¶
Return JSON-ready shot-policy metadata.
QuantumGradientMethodExplanation
dataclass
¶
Deterministic explanation of a backend gradient-method decision.
Parameters¶
capability
Normalised backend capability used by the planner.
selected_plan
Existing execution plan selected by
:func:plan_quantum_gradient_backend.
rejected_methods
Ordered method candidates that were not selected.
shot_policy
Shot, confidence, and seed policy for the selected plan.
fallback_path
Ordered safe fallback routes for unsupported or degraded execution.
requested_method
Normalised method requested by the caller.
claim_boundary
Claim boundary for this explanation object.
quantum_gradient_backend_capability(backend)
¶
Return declared gradient capabilities for a known backend family.
plan_quantum_gradient_backend(backend, *, n_params, shift_terms=1, method='auto', shots=None, seed=None, finite_shot=False, confidence_level=None, allow_hardware=False)
¶
Plan a quantum-gradient method with fail-closed backend boundaries.
explain_quantum_gradient_method(backend, *, n_params, shift_terms=1, method='auto', shots=None, seed=None, finite_shot=False, confidence_level=None, allow_hardware=False)
¶
Explain a backend gradient-method decision without executing gradients.
Parameters¶
backend
Backend family or alias to plan against.
n_params
Number of trainable scalar parameters.
shift_terms
Number of parameter-shift terms per trainable parameter.
method
Requested method, or "auto" for planner selection.
shots
Optional finite-shot budget.
seed
Optional deterministic seed for stochastic routes.
finite_shot
Whether the caller requires finite-shot planning.
confidence_level
Optional finite-shot confidence level.
allow_hardware
Whether policy-gated hardware routes may plan execution.
Returns¶
QuantumGradientMethodExplanation Deterministic selected method, rejected alternatives, shot policy, and fallback path for the requested backend capability combination.
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.gradient_tape
¶
Context-managed quantum-gradient tape for phase objectives.
GRADIENT_TAPE_CONTRACT_CLAIM_BOUNDARY = 'Phase gradient-tape contract audit only; supported records are local phase parameter-shift or materialised finite-shot replay, while arbitrary Python mutation semantics, provider execution, hardware gradients, and benchmark promotion remain outside this tape contract'
module-attribute
¶
Claim boundary for the executable gradient-tape contract audit.
TapeGradientRecord
dataclass
¶
One recorded quantum-gradient evaluation.
gradient
property
¶
The recorded gradient vector.
value
property
¶
The recorded objective value.
evaluations
property
¶
Planned quantum objective evaluations, excluding tape bookkeeping.
method
property
¶
The replay method recorded by the gradient result.
shift_terms
property
¶
The number of parameter-shift terms used per parameter.
standard_error
property
¶
Finite-shot standard errors when the record is stochastic.
confidence_radius
property
¶
Finite-shot confidence radii when the record is stochastic.
to_dict()
¶
Return JSON-ready replay provenance for audit logs and notebooks.
GradientTapeContractCheck
dataclass
¶
One phase gradient-tape contract check.
Parameters¶
name
Stable check identifier.
status
"supported" when the behaviour executes, or "fail_closed"
when the unsupported route is intentionally rejected.
evidence
Human-readable evidence collected by the executable audit.
blocked_reason
Rejection reason for fail-closed checks, or None for supported
checks.
GradientTapeContractAuditResult
dataclass
¶
Executable contract audit for the phase gradient tape.
Parameters¶
checks Ordered supported and fail-closed contract checks. passed Whether every expected contract check produced evidence. claim_boundary Boundary text limiting the audit to local tape replay semantics.
QuantumGradientTape
¶
Context manager that records supported phase-gradient evaluations.
records
property
¶
Immutable view of recorded gradient evaluations.
__init__(*, backend='statevector', shots=None, seed=None, confidence_level=0.95, allow_hardware=False)
¶
Create a tape with backend policy shared by all records.
__enter__()
¶
Activate the tape context.
__exit__(exc_type, exc, traceback)
¶
Deactivate the tape context.
clear()
¶
Clear recorded evaluations while preserving backend policy.
record_parameter_shift(name, objective, params, *, parameters=None, rule=None)
¶
Record deterministic parameter-shift value and gradient.
record_finite_shot_parameter_shift(name, *, plus_values, minus_values, plus_variances, minus_variances, sample_provenance=None, value=0.0, parameters=None, rule=None, confidence_z=1.959963984540054)
¶
Record finite-shot parameter-shift gradient with uncertainty.
Parameters¶
name:
Non-empty record label.
plus_values, minus_values:
Materialised plus/minus shifted objective estimates.
plus_variances, minus_variances:
Per-estimate finite-shot variances matching the shifted values.
sample_provenance:
Source metadata for the materialised finite-shot tensors. The
mapping or record must include sample_seed, shot_batch_id,
and source_class.
value:
Scalar objective value associated with the gradient record.
parameters:
Optional parameter metadata and trainable mask.
rule:
Optional parameter-shift rule.
confidence_z:
Normal-approximation multiplier used for confidence radii.
Returns¶
TapeGradientRecord Tape record containing the stochastic gradient result.
gradient_tape(*, backend='statevector', shots=None, seed=None, confidence_level=0.95, allow_hardware=False)
¶
Return a context-managed quantum-gradient tape.
scpn_quantum_control.phase.provider_gradient_audit
¶
Executable readiness audit for provider-safe quantum gradients.
ProviderGradientReadinessScenario
dataclass
¶
ProviderGradientReadinessRecord
dataclass
¶
ProviderGradientReadinessAuditResult
dataclass
¶
Executable support matrix for provider-gradient readiness.
supported_records
property
¶
Scenarios that executed and matched their gradient references.
blocked_records
property
¶
Scenarios that fail closed by plan or execution guard.
failing_records
property
¶
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 optimisation.
Discretises the MPC action space to binary (coil on/off per timestep),
maps the quadratic tracking cost to an Ising Hamiltonian, then solves via QAOA.
The cost keeps the vector residual u_t * (B @ ones) - target; collapsing it
to norms would discard the target's sign and its direction relative to B.
QAOA_MPC
¶
QAOA-based model predictive controller.
Cost: C = sum_t ||u_t * (B @ ones) - target||^2 with binary
u_t in {0, 1}, one coil on/off decision per timestep. The residual stays
a vector, so a sign flip or rotation of target changes the optimum. This
quadratic-in-binary form is equivalent to an Ising Hamiltonian.
__init__(B_matrix, target_state, horizon, p_layers=2)
¶
Initialize the binary model-predictive controller.
Parameters¶
B_matrix Linear map from binary actions to the controlled state. target_state State vector used to construct the quadratic tracking cost. horizon Positive number of binary control timesteps and circuit qubits. p_layers Positive number of alternating QAOA cost and mixer layers.
Raises¶
ValueError
If horizon or p_layers is not positive.
build_cost_hamiltonian()
¶
Map per-timestep quadratic binary cost to Ising Hamiltonian.
The tracking cost is C(u) = sum_t ||u_t * v - r||^2 with
v = B @ ones and r the target. Using u_t^2 = u_t for binary
u_t and u_t = (1 - Z_t)/2::
q = ||v||^2 - 2 * (v . r)
C = H*q/2 + H*||r||^2 - (q/2) * sum_t Z_t
so h_z = -q/2. There are no ZZ terms because the timesteps are
independent; the coupling this mapping preserves is the v . r
cross-term inside the norm, which a norm-only surrogate discards along
with the target's sign.
Returns¶
qiskit.quantum_info.SparsePauliOp Diagonal identity-and-Z cost Hamiltonian for the control horizon.
optimize(seed=None, *, max_dense_gib=None)
¶
Run QAOA optimization, return binary action sequence.
The circuit is simulated densely, so the horizon sets a 2**horizon
statevector. Admission is checked once here, before the optimiser runs,
rather than inside the cost function that the optimiser calls up to two
hundred times: a budget that cannot hold the state should refuse before
any allocator is entered, not on the first iteration.
Two objects of the statevector's size are accounted for. The state
itself is live throughout, and the expectation value against the cost
Hamiltonian, and later probabilities(), each need a second array of
the same dimension while the first is still held.
Parameters¶
seed
Optional seed for the variational parameter initialization.
max_dense_gib
Optional dense-allocation budget in GiB. None uses the active
process budget.
Returns¶
numpy.ndarray
Integer array of zero/one actions shaped (horizon,).
Raises¶
DenseAllocationError
If the statevector for horizon qubits exceeds the budget.
RuntimeError
If the cost Hamiltonian could not be constructed.
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)
The layer encodes clipped inputs with Ry rotations, applies learned
controlled rotations, entangles adjacent neuron qubits, and thresholds
exact marginal probabilities into binary spikes.
__init__(n_neurons, n_inputs, weights=None, spike_threshold=0.5, seed=None)
¶
Initialize a quantum dense layer.
Parameters¶
n_neurons
Number of output neuron qubits.
n_inputs
Number of input qubits.
weights
Synaptic weight matrix with shape (n_neurons, n_inputs). When
omitted, weights are sampled uniformly from [0, 1].
spike_threshold
Strict marginal-probability threshold used to emit a spike.
seed
Seed for random weight initialization when weights is omitted.
forward(input_values, *, max_dense_gib=None)
¶
Evolve the dense state in-place and threshold neuron probabilities.
Parameters¶
input_values
Input vector with shape (n_inputs,). Values are clipped to
[0, 1] before angle encoding.
max_dense_gib
Optional statevector budget in GiB; otherwise the current process
budget applies. Checked before allocating the dense state.
Returns¶
NDArray[np.int64]
Binary spike vector with shape (n_neurons,).
Raises¶
DenseAllocationError If the statevector exceeds the active budget.
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.
__init__(layer, lr=0.01, *, max_dense_gib=None)
¶
Bind a layer to the parameter-shift trainer.
Every forward pass simulates the layer densely, so the qubit count fixes
a 2**n_qubits statevector. Admission is checked at construction and
again before each forward-pass circuit is built, since the layer and
active process budget may change. The saved explicit budget, when given,
applies to later passes too. Two complex-vector equivalents account for
the state and the real absolute-value/square probability buffers.
Parameters¶
layer
Quantum dense layer to train.
lr
Learning rate for the descent optimiser.
max_dense_gib
Optional dense-allocation budget in GiB. None uses the active
process budget.
Raises¶
DenseAllocationError If a forward-pass statevector for the layer exceeds the budget.
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
¶
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.
gradient_method:
Canonical gradient method used by :meth:value_and_grad when callers
do not override the method explicitly.
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
¶
Current fail-closed support plan for this circuit.
capability
property
¶
Public capability metadata for the current route.
diagnostics
property
¶
Fail-closed diagnostics for the current route.
fail_closed
property
¶
Whether 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=None, parameters=None, step=None)
¶
Evaluate objective value and gradient through the canonical transform.
grad(values, *, method=None, 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
¶
DifferentiableCircuitContractCheck
dataclass
¶
One differentiable-circuit contract check.
Parameters¶
name:
Stable check identifier.
status:
"supported" when the audited behaviour executes, or
"fail_closed" when the unsupported route is intentionally rejected.
evidence:
Human-readable evidence collected through public circuit APIs.
blocked_reason:
Rejection reason for fail-closed checks, or None for supported
checks.
DifferentiableCircuitContractAuditResult
dataclass
¶
Executable result for the differentiable-circuit abstraction audit.
passed
property
¶
Whether all checks carry evidence and expected status.
supported_checks
property
¶
Supported audit checks.
fail_closed_checks
property
¶
Fail-closed audit checks.
failing_checks
property
¶
Checks that lack the evidence required by the audit.
to_dict()
¶
Return JSON-ready audit metadata.
differentiable_circuit(objective, *, name='differentiable_circuit', parameter_names=(), gate='ry', observable='pauli_expectation', backend='statevector', transform='grad', adapter='native', gradient_method='parameter_shift', 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.
run_differentiable_circuit_contract_audit()
¶
Run the executable audit through public diff namespace surfaces.
Returns¶
DifferentiableCircuitContractAuditResult Supported and fail-closed checks for call semantics, transform composition, backend capability metadata, and serialization provenance.
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.
ParameterBounds
dataclass
¶
Closed interval constraint for one differentiable scalar parameter.
__post_init__()
¶
Validate finite interval and periodic-bound metadata.
ParameterShiftRule
dataclass
¶
ParameterShiftSampleRecord
dataclass
¶
DualNumber
dataclass
¶
Forward-mode automatic differentiation scalar with one tangent lane.
Parameters¶
primal Real primal scalar carried by the differentiable expression. tangent Real derivative with respect to the active scalar seed.
Attributes¶
primal Validated real primal scalar. tangent Validated real tangent scalar for the active derivative lane.
__post_init__()
¶
Validate the stored primal and tangent as real scalar values.
coerce(value)
staticmethod
¶
__add__(other)
¶
Return the forward-mode addition rule.
__radd__(other)
¶
Return reflected forward-mode addition.
__sub__(other)
¶
Return the forward-mode subtraction rule.
__rsub__(other)
¶
Return reflected forward-mode subtraction.
__mul__(other)
¶
Return the forward-mode product rule.
__rmul__(other)
¶
Return reflected forward-mode multiplication.
__truediv__(other)
¶
Return the forward-mode quotient rule.
__rtruediv__(other)
¶
Return reflected forward-mode division.
__neg__()
¶
Return the negated primal and tangent.
__pow__(other)
¶
Return the forward-mode scalar power rule.
__rpow__(other)
¶
Return reflected forward-mode scalar exponentiation.
ReverseNode
¶
Reverse-mode automatic differentiation scalar with local pullbacks.
Parameters¶
primal Real primal scalar represented by the node. parents Parent nodes paired with local derivative coefficients.
Attributes¶
primal Validated real primal scalar. parents Tuple of upstream nodes and pullback coefficients. adjoint Reverse accumulation slot seeded by a downstream traversal.
coerce(value)
staticmethod
¶
__add__(other)
¶
Return the reverse-mode addition pullback.
__radd__(other)
¶
Return reflected reverse-mode addition.
__sub__(other)
¶
Return the reverse-mode subtraction pullback.
__rsub__(other)
¶
Return reflected reverse-mode subtraction.
__mul__(other)
¶
Return the reverse-mode product pullback.
__rmul__(other)
¶
Return reflected reverse-mode multiplication.
__truediv__(other)
¶
Return the reverse-mode quotient pullback.
__rtruediv__(other)
¶
Return reflected reverse-mode division.
__neg__()
¶
Return the reverse-mode negation pullback.
__pow__(other)
¶
Return the reverse-mode scalar power pullback.
__rpow__(other)
¶
Return reflected reverse-mode scalar exponentiation.
GradientResult
dataclass
¶
Value, gradient, and provenance returned by a differentiable backend.
The gradient is an owned, read-only snapshot. Parameter names and trainable flags are copied to tuples so caller mutation cannot invalidate the record. Consumers needing a writable gradient must explicitly copy it.
Parameters¶
value
Finite scalar objective value, in the objective's units.
gradient
Finite shape (n_parameters,) derivative values, in objective units
per corresponding parameter unit. Frozen parameters must have zero
entries. Construction copies the array without modifying its source.
method
Non-blank string naming the differentiation method actually executed.
shift
Positive finite parameter perturbation, or None if not applicable.
coefficient
Finite shift-rule coefficient, or None if not applicable.
evaluations
Non-negative integer objective evaluation count reported by the backend.
Boolean and floating-point values are not counts.
parameter_names
Ordered, non-empty names matching the gradient length.
trainable
Boolean mask matching the gradient length.
claim_boundary
Non-empty statement limiting the result's evidence claims.
Raises¶
ValueError If values, dimensions, trainability or provenance violate the contract.
__post_init__()
¶
Validate scalar value, gradient shape, trainability, and provenance.
StochasticGradientResult
dataclass
¶
ShotAllocationResult
dataclass
¶
Per-parameter shot allocation for stochastic parameter-shift gradients.
__post_init__()
¶
Validate shot-allocation shapes, totals, and parameter metadata.
SparseMatrixResult
dataclass
¶
ImplicitSensitivityResult
dataclass
¶
Implicit-function sensitivity for a stationary differentiable system.
__post_init__()
¶
Validate implicit-function sensitivity operands and metadata.
FixedPointSensitivityResult
dataclass
¶
Implicit sensitivity for a converged fixed-point map.
__post_init__()
¶
Validate fixed-point sensitivity operands and metadata.
CustomDerivativeRule
dataclass
¶
Exact derivative rule set for one differentiable vector primitive.
Parameters¶
name:
Non-empty registry-local rule name.
value_fn:
Callable that evaluates the primitive on a float64 vector payload.
jvp_rule:
Optional Jacobian-vector product rule for forward-mode dispatch.
vjp_rule:
Optional vector-Jacobian product rule for reverse-mode dispatch.
parameter_names:
Optional parameter names exposed by the primitive.
trainable:
Optional trainability mask aligned with parameter_names.
Raises¶
ValueError If the name is empty, if callables are malformed, if neither JVP nor VJP is provided, or if parameter metadata is inconsistent.
__post_init__()
¶
Validate immutable custom-derivative rule fields.
PrimitiveIdentity
dataclass
¶
Stable typed identity for a differentiable primitive implementation.
Parameters¶
namespace:
Registry namespace, such as scpn.program_ad.shape.
name:
Primitive name inside the namespace.
version:
Version token for the primitive contract, defaulting to "1".
Raises¶
ValueError
If any identity token is empty, contains whitespace, or contains :
or @.
key
property
¶
Canonical registry key for this primitive identity.
Returns¶
str
Canonical namespace:name@version key.
__post_init__()
¶
Normalise identity tokens after dataclass construction.
parse(identity)
staticmethod
¶
Return a typed identity from an existing identity or key string.
Parameters¶
identity:
Existing PrimitiveIdentity or a namespace:name[@version]
string.
Returns¶
PrimitiveIdentity
Parsed identity with version "1" when the string omits an
explicit version.
Raises¶
ValueError If the input is not a primitive identity or non-empty key string, or if the key does not contain a namespace/name separator.
PrimitiveTransformRule
dataclass
¶
Combined transform binding for one differentiable primitive identity.
Parameters¶
identity: Primitive identity that owns the transform binding. derivative_rule: Exact derivative rule registered for the primitive. batching_rule: Optional vmap/batching rule. lowering_rule: Optional executable compiler lowering rule. lowering_metadata: Optional lowering evidence and claim-boundary metadata. shape_rule: Optional static shape contract. dtype_rule: Optional dtype contract. static_argument_rule: Optional static-argument normalisation contract. nondifferentiable_policy: Fail-closed policy name for nondifferentiable boundaries. effect: Primitive effect classification.
Raises¶
ValueError If identity or derivative metadata has the wrong type, optional rules are non-callable, or string/metadata fields are empty.
__post_init__()
¶
Validate transform metadata and canonicalise lowering metadata.
CustomDerivativeRegistry
¶
Conflict-safe registry binding primitive identities to exact rules.
Parameters¶
rules: Optional initial derivative-rule mapping keyed by primitive identity.
Raises¶
ValueError If any initial rule cannot be registered under its identity.
register(identity, rule, *, overwrite=False)
¶
Register an exact derivative rule for a primitive identity.
Parameters¶
identity: Primitive identity object or canonical identity key. rule: Custom derivative rule to bind. overwrite: Whether an existing different rule may be replaced.
Returns¶
CustomDerivativeRule The registered rule.
Raises¶
ValueError
If identity is malformed, if rule has the wrong type, or if
an existing conflicting rule is present and overwrite is disabled.
decorator(identity, *, overwrite=False)
¶
Return a decorator that registers a custom derivative rule.
Parameters¶
identity: Primitive identity object or canonical identity key. overwrite: Whether an existing different rule may be replaced.
Returns¶
Callable[[CustomDerivativeRule], CustomDerivativeRule] Decorator that registers and returns the supplied rule.
register_transform(transform, *, overwrite=False)
¶
Register derivative, batching, and lowering metadata for one primitive.
Parameters¶
transform: Combined primitive transform binding to register. overwrite: Whether an existing different transform may be replaced.
Returns¶
PrimitiveTransformRule The registered transform binding.
Raises¶
ValueError
If transform has the wrong type or conflicts with an existing
binding while overwrite is disabled.
register_batching_rule(identity, batching_rule, *, overwrite=False)
¶
Attach a primitive-specific batching rule to an existing identity.
Parameters¶
identity: Primitive identity object or canonical identity key. batching_rule: Callable that implements primitive-specific batching. overwrite: Whether an existing batching rule may be replaced.
Returns¶
PrimitiveBatchingRule The registered batching rule.
Raises¶
ValueError
If identity is malformed, if batching_rule is non-callable,
if no derivative rule exists, or if a batching rule already exists
while overwrite is disabled.
register_lowering_rule(identity, lowering_rule, *, overwrite=False)
¶
Attach an executable compiler lowering rule to an existing identity.
Parameters¶
identity: Primitive identity object or canonical identity key. lowering_rule: Callable that emits executable compiler lowering artefacts. overwrite: Whether an existing lowering rule may be replaced.
Returns¶
PrimitiveLoweringRule The registered lowering rule.
Raises¶
ValueError
If identity is malformed, if lowering_rule is non-callable,
if no derivative rule exists, or if a lowering rule already exists
while overwrite is disabled.
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/vectorisation-ready primitive contract or fail closed.
Parameters¶
identity: Primitive identity object or canonical identity key.
Returns¶
PrimitiveContract Contract with derivative, batching, lowering metadata, shape, dtype, static-argument, nondifferentiability, and effect facets present.
Raises¶
ValueError If no contract exists or if any complete-contract facet is missing.
transform_snapshot()
¶
Return a copy of registered primitive transform bindings.
lookup(identity)
¶
Return the registered rule for an identity, if present.
require(identity)
¶
unregister(identity)
¶
snapshot()
¶
Return an immutable-by-copy snapshot of registered primitive rules.
CustomDerivativeCheckResult
dataclass
¶
Consistency audit for exact custom JVP/VJP derivative rules.
__post_init__()
¶
Validate custom JVP/VJP comparisons against reference products.
OptimizationResult
dataclass
¶
Bounded gradient-descent result with convergence provenance.
__post_init__()
¶
Validate deterministic optimisation traces and best-state metadata.
ArmijoLineSearchResult
dataclass
¶
Backtracking line-search result with sufficient-decrease provenance.
__post_init__()
¶
Validate Armijo line-search state and sufficient-decrease metadata.
GradientCheckResult
dataclass
¶
Consistency check between two differentiable gradient estimators.
__post_init__()
¶
Validate gradient-check operand shapes and error metrics.
JacobianResult
dataclass
¶
Value, Jacobian, and provenance for a vector-valued objective.
__post_init__()
¶
Validate vector value, Jacobian shape, and parameter provenance.
JVPResult
dataclass
¶
Jacobian-vector product with directional finite-difference provenance.
__post_init__()
¶
Validate JVP value, tangent, product, and claim boundary.
VJPResult
dataclass
¶
Vector-Jacobian product with cotangent provenance.
__post_init__()
¶
Validate VJP value, cotangent, product, and claim boundary.
HessianResult
dataclass
¶
Value, Hessian, and provenance for a scalar objective.
__post_init__()
¶
Validate scalar Hessian shape, symmetry, and trainable mask.
HVPResult
dataclass
¶
Hessian-vector product with nested finite-difference provenance.
__post_init__()
¶
Validate Hessian-vector product, tangent, and parameter metadata.
LeastSquaresCovarianceResult
dataclass
¶
Parameter uncertainty estimate from a residual-map Fisher metric.
__post_init__()
¶
Validate least-squares covariance and parameter uncertainties.
FisherVectorProductResult
dataclass
¶
Matrix-free empirical-Fisher vector product with provenance.
__post_init__()
¶
Validate empirical-Fisher vector-product operands.
FisherConjugateGradientResult
dataclass
¶
Matrix-free empirical-Fisher conjugate-gradient solve result.
__post_init__()
¶
Validate empirical-Fisher conjugate-gradient solve history.
NaturalGradientResult
dataclass
¶
Metric-preconditioned gradient with solve provenance.
__post_init__()
¶
Validate metric-preconditioned gradient solve metadata.
NaturalGradientOptimizationResult
dataclass
¶
Bounded natural-gradient optimization trace and final state.
__post_init__()
¶
Validate natural-gradient optimisation history and best 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.
__post_init__()
¶
Validate damping update action after an LM trial.
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.
__post_init__()
¶
Validate the full Levenberg-Marquardt result trace.
LevenbergMarquardtStep
dataclass
¶
Bounded Levenberg-Marquardt candidate step with model diagnostics.
__post_init__()
¶
Validate one Levenberg-Marquardt step proposal.
LevenbergMarquardtTrial
dataclass
¶
Actual-vs-predicted Levenberg-Marquardt acceptance diagnostic.
__post_init__()
¶
Validate one Levenberg-Marquardt trial outcome.
WeightedGradientResult
dataclass
¶
Weighted scalarisation of multiple scalar gradient results.
__post_init__()
¶
Validate a weighted scalarisation of gradient components.
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, frontend gate, adjoint replay contract, and AD status.
Notes¶
Results produced by the whole-program runtime retain captured_state,
an in-memory callable and numeric-state binding checked by adjoint access.
The attached adjoint shares the same binding, so result replacement cannot
remove it or substitute another objective's state. It keeps the callable
alive for the result's lifetime and never changes the historical effect IR
serialization. None preserves construction of standalone historical
tape records whose adjoint also has no live callable binding.
Runtime capture also binds primal, buffers, typed/raw IR and adjoint content;
replacement or later mutation of these artifacts refuses derivative access.
__post_init__()
¶
Validate whole-program AD result metadata at construction time.
WholeProgramBytecodeInstruction
dataclass
¶
One Python bytecode instruction captured for whole-program AD frontend IR.
__post_init__()
¶
Validate bytecode offsets, operation name, and source line.
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.
WholeProgramSourceIRFeature
dataclass
¶
One source-level semantic feature captured for whole-program AD.
__post_init__()
¶
Validate the source feature description and line number.
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.
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.
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.
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.
WholeProgramSemanticsReport
dataclass
¶
Static semantics summary for whole-program AD graph capture.
__post_init__()
¶
Validate semantic flags and accepted or unsupported labels.
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
¶
The number of bytecode instructions in the frontend report.
source_feature_count
property
¶
The number of source IR feature rows in the frontend report.
frontend_ready
property
¶
Whether bytecode and source frontend metadata passed preflight.
bytecode_basic_block_count
property
¶
The number of bytecode basic blocks in the frontend report.
source_region_count
property
¶
The number of source regions in the frontend report.
source_bytecode_line_map_count
property
¶
The number of source-bytecode crosswalk rows in the report.
symbol_scope_entry_count
property
¶
The number of static symbol-scope entries in the report.
unsupported_semantic_diagnostic_count
property
¶
The number of unsupported-semantics diagnostics in the report.
__post_init__()
¶
Validate all static frontend records, digests, and hard gaps.
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 ranked array for whole-program AD.
Parameters¶
items:
Row-major scalar trace values carried by the array.
shape:
Static NumPy-compatible shape whose element count matches items.
context:
Trace context shared by every scalar item.
source_indices:
Optional original parameter slots retained through alias-preserving
views; None entries identify constants or overwritten elements.
Notes¶
Supported NumPy functions dispatch through __array_function__ and
supported ufuncs through __array_ufunc__. Raw ndarray coercion fails
closed because it would discard derivative and alias metadata.
ndim
property
¶
The rank of the derivative-carrying array.
size
property
¶
The total number of derivative-carrying elements.
T
property
¶
The NumPy-compatible reversed-axis transpose.
__len__()
¶
Return the leading-axis length of a ranked trace array.
__iter__()
¶
Iterate over trace scalars or rank-one row views.
__array__(dtype=None, *, copy=None)
¶
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.
__getitem__(index)
¶
Return a derivative-preserving indexed scalar or array view.
__setitem__(index, value)
¶
Assign traced values while recording deterministic mutation metadata.
__array_ufunc__(ufunc, method, *inputs, **kwargs)
¶
Dispatch direct ufuncs or bounded unbuffered np.add.at mutations.
__array_function__(func, types, args, kwargs)
¶
Dispatch a supported NumPy function through fail-closed trace semantics.
__add__(other)
¶
Return the derivative-preserving elementwise sum.
__radd__(other)
¶
Return the derivative-preserving reflected elementwise sum.
__sub__(other)
¶
Return the derivative-preserving elementwise difference.
__rsub__(other)
¶
Return the derivative-preserving reflected elementwise difference.
__mul__(other)
¶
Return the derivative-preserving elementwise product.
__rmul__(other)
¶
Return the derivative-preserving reflected elementwise product.
__truediv__(other)
¶
Return the derivative-preserving elementwise quotient.
__rtruediv__(other)
¶
Return the derivative-preserving reflected elementwise quotient.
__pow__(other)
¶
Return the derivative-preserving elementwise power.
__rpow__(other)
¶
Return the derivative-preserving reflected elementwise power.
__neg__()
¶
Return the derivative-preserving elementwise additive inverse.
__matmul__(other)
¶
Return the derivative-preserving matrix product.
__rmatmul__(other)
¶
Return the derivative-preserving reflected matrix product.
__gt__(other)
¶
Return the traced elementwise strict-greater-than predicate.
__ge__(other)
¶
Return the traced elementwise greater-than-or-equal predicate.
__lt__(other)
¶
Return the traced elementwise strict-less-than predicate.
__le__(other)
¶
Return the traced elementwise less-than-or-equal predicate.
__eq__(other)
¶
Return the traced elementwise equality predicate.
__ne__(other)
¶
Return the traced elementwise inequality predicate.
TraceADScalar
¶
Operator-intercepted scalar for exact executed-path whole-program AD.
Parameters¶
primal: Finite real value carried by the trace. tangent: One-dimensional derivative vector aligned with the trace parameters. context: Trace context that owns the value and records derived operations. name: Stable SSA-style label used by trace and adjoint metadata.
Notes¶
Arithmetic, comparisons, and supported NumPy ufuncs preserve the owning
context. Conversion to a Python float fails closed because it would
discard derivative information.
__float__()
¶
Reject conversion that would discard derivative information.
__int__()
¶
Reject parameter-dependent integer conversion.
Raises¶
ValueError Integer conversion would discard the active derivative and could turn a traced parameter into an unqualified dynamic shape or index.
__index__()
¶
Reject using a traced parameter as an integer shape or index.
Raises¶
ValueError A derivative-carrying scalar has no static integer indexing contract.
__add__(other)
¶
Return the derivative-preserving scalar sum.
__radd__(other)
¶
Return the derivative-preserving reflected scalar sum.
__sub__(other)
¶
Return the derivative-preserving scalar difference.
__rsub__(other)
¶
Return the derivative-preserving reflected scalar difference.
__mul__(other)
¶
Return the derivative-preserving scalar product.
__rmul__(other)
¶
Return the derivative-preserving reflected scalar product.
__truediv__(other)
¶
Return the derivative-preserving scalar quotient.
__rtruediv__(other)
¶
Return the derivative-preserving reflected scalar quotient.
__pow__(other)
¶
Return the derivative-preserving scalar power.
__rpow__(other)
¶
Return the derivative-preserving reflected scalar power.
__neg__()
¶
Return the derivative-preserving additive inverse.
__abs__()
¶
Return the derivative-preserving absolute value.
__gt__(other)
¶
Return the traced strict-greater-than predicate.
__ge__(other)
¶
Return the traced greater-than-or-equal predicate.
__lt__(other)
¶
Return the traced strict-less-than predicate.
__le__(other)
¶
Return the traced less-than-or-equal predicate.
__eq__(other)
¶
Return the traced equality predicate.
__ne__(other)
¶
Return the traced inequality predicate.
__array_ufunc__(ufunc, method, *inputs, **kwargs)
¶
Dispatch a supported NumPy ufunc through scalar trace semantics.
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)
¶
dual_cos(value)
¶
dual_exp(value)
¶
dual_log(value)
¶
reverse_sin(value)
¶
reverse_cos(value)
¶
reverse_exp(value)
¶
reverse_log(value)
¶
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.
Parameters¶
identity: Primitive identity object or canonical identity key. rule: Custom derivative rule to register. overwrite: Whether an existing different rule may be replaced. registry: Optional registry override; the default registry is used when omitted.
Returns¶
CustomDerivativeRule The registered rule.
Raises¶
ValueError If identity/rule validation fails or if a conflicting rule exists and overwrite is disabled.
register_primitive_transform_rule(transform, *, overwrite=False, registry=None)
¶
Register a combined derivative, batching, and lowering transform binding.
Parameters¶
transform: Primitive transform binding to register. overwrite: Whether an existing different transform may be replaced. registry: Optional registry override; the default registry is used when omitted.
Returns¶
PrimitiveTransformRule The registered transform binding.
Raises¶
ValueError If transform validation fails or if a conflicting transform exists and overwrite is disabled.
register_primitive_batching_rule(identity, batching_rule, *, overwrite=False, registry=None)
¶
Register a batching rule for an existing primitive derivative rule.
Parameters¶
identity: Primitive identity object or canonical identity key. batching_rule: Callable implementing batching for the primitive. overwrite: Whether an existing batching rule may be replaced. registry: Optional registry override; the default registry is used when omitted.
Returns¶
PrimitiveBatchingRule The registered batching rule.
Raises¶
ValueError If identity/rule validation fails, if no derivative rule exists, or if a batching rule already exists and overwrite is disabled.
custom_derivative_rule_for(identity, *, registry=None)
¶
Resolve a custom derivative rule for a primitive identity.
Parameters¶
identity: Primitive identity object or canonical identity key. registry: Optional registry override; the default registry is used when omitted.
Returns¶
CustomDerivativeRule Registered derivative rule.
Raises¶
ValueError
If identity is malformed or no derivative rule is registered.
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, *, sample_provenance=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.
sample_provenance:
Source metadata for the materialised plus/minus finite-shot tensors.
The mapping or record must include sample_seed, shot_batch_id,
and source_class.
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, max_execution_gib=None, deadline_monotonic=None, cancelled=None)
¶
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.
max_execution_gib:
Optional declared numeric-buffer cap forwarded to the owned AD scope.
deadline_monotonic:
Absolute monotonic deadline forwarded to the owned AD scope.
cancelled:
Optional cancellation event forwarded to the owned AD scope.
Returns¶
numpy.ndarray
Exact whole-program AD gradient as float64 values.
whole_program_value_and_grad(objective, values, parameters=None, *, trace=True, max_execution_gib=None, deadline_monotonic=None, cancelled=None)
¶
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: One-dimensional real numeric values supplied as a plain NumPy ndarray, list, tuple or range. Opaque array protocols and subclasses refuse before conversion because their allocation behavior is not bounded here. parameters: Optional plain list or tuple of exact Parameter records with plain string names and boolean trainability. Metadata copies and name storage are admitted before copying; opaque sequences and record subclasses refuse without invoking their iteration or attribute protocols. trace: Whether to collect runtime trace events in addition to IR metadata. max_execution_gib: Optional cap for declared input/conversion, parameter, tangent, retained tape, gradient and trace-record buffers. Input storage is admitted before NumPy conversion; capacity is observed before initial tangent allocation; retained tangent and alias growth refuse before their materialisation. Frontend/serialization workspaces, general allocator overhead and undeclared user/third-party allocations are not fully covered by this cap. deadline_monotonic: Absolute monotonic deadline checked before frontend inspection, after source inspection and at retained-node checkpoints. cancelled: Optional cancellation event observed before frontend inspection, after source inspection and at retained-node checkpoints.
Returns¶
WholeProgramADResult Exact executed-program value, gradient, source/bytecode metadata, IR nodes, frontend report, semantics report, and scalar adjoint replay provenance. An in-memory binding checks callable code and captured numeric state, and retains the primal, numeric buffers, typed/raw IR and adjoint content together. Derivative access refuses changed artifacts.
Raises¶
ValueError If the objective is not callable, fails the source/bytecode frontend execution gate, uses unsupported Python semantics, or does not return a traceable scalar; also if captured state has unsupported storage or changes while the objective is evaluated.
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, has no attached
adjoint metadata, or its live captured state or derivative tape changed.
program_adjoint_gradient(result, *, max_execution_gib=None, deadline_monotonic=None, cancelled=None)
¶
Return a supported reverse-mode adjoint gradient or fail closed.
Parameters¶
result: Whole-program AD result whose attached reverse-adjoint metadata should be supported. max_execution_gib: Optional cap for captured-state inspection and retained/copied gradient buffers. deadline_monotonic: Absolute monotonic deadline checked during state inspection and copying. cancelled: Cancellation event checked before state inspection and during copying.
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, or its mutable gradient storage no longer has the captured float64 shape or finite values, or a frozen coordinate is nonzero, or its live captured state or derivative tape changed.
program_adjoint_grad(objective, values, parameters=None, *, trace=True, max_execution_gib=None, deadline_monotonic=None, cancelled=None)
¶
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. max_execution_gib: Optional whole-program numeric-buffer cap, including retained tangent tape. deadline_monotonic: Absolute monotonic deadline forwarded to the owned trace operation. cancelled: Optional cancellation event forwarded to the owned trace operation.
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, max_execution_gib=None, deadline_monotonic=None, cancelled=None)
¶
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. max_execution_gib: Optional whole-program numeric-buffer cap, including retained tangent tape. deadline_monotonic: Absolute monotonic deadline forwarded to the owned trace operation. cancelled: Optional cancellation event forwarded to the owned trace operation.
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.
Parameters¶
objective Scalar objective evaluated on a real parameter vector. values Real parameter vector for the diagnostic probe. parameters Optional parameter metadata. Non-trainable entries receive zero gradient components and are not perturbed. step Positive central-difference displacement.
Returns¶
numpy.ndarray
Gradient vector with the same length as values.
Raises¶
ValueError If parameters, objective values, or the finite-difference step violate the diagnostic contract.
value_and_finite_difference_grad(objective, values, *, parameters=None, step=1e-06)
¶
Evaluate a scalar objective and central finite-difference gradient.
Parameters¶
objective Scalar objective evaluated on a real parameter vector. values Real parameter vector for the central-difference probes. parameters Optional parameter metadata. Non-trainable entries receive zero gradient components and are not perturbed. step Positive central-difference displacement.
Returns¶
GradientResult Objective value, gradient, metadata, and diagnostic claim boundary.
Raises¶
ValueError If the step, parameters, or objective result violate the scalar diagnostic contract.
batch_value_and_finite_difference_grad(objectives, values, *, parameters=None, step=1e-06)
¶
Return full finite-difference results for multiple scalar objectives.
Parameters¶
objectives Non-empty sequence of scalar objectives evaluated against the same parameter vector. values Real parameter vector for every objective. parameters Optional parameter metadata applied to each objective. step Positive central-difference displacement.
Returns¶
tuple[GradientResult, ...] One value-and-gradient result per objective.
Raises¶
ValueError If no objectives are provided or a delegated gradient evaluation fails validation.
complex_step_gradient(objective, values, *, parameters=None, step=1e-30)
¶
Return a complex-step gradient for real-analytic scalar objectives.
Parameters¶
objective Scalar objective that accepts complex-valued perturbations and returns a real base value. values Real parameter vector that seeds the complex-step probes. parameters Optional parameter metadata. Non-trainable entries receive zero gradient components and are not perturbed. step Positive imaginary displacement for each trainable component.
Returns¶
numpy.ndarray
Complex-step gradient vector with the same length as values.
Raises¶
ValueError If the step is invalid, the objective is not scalar, or the base value has a non-zero imaginary component.
value_and_complex_step_grad(objective, values, *, parameters=None, step=1e-30)
¶
Evaluate a real-analytic scalar objective and complex-step gradient.
Parameters¶
objective Scalar objective that accepts complex-valued perturbations and returns a real base value. values Real parameter vector that seeds the complex-step probes. parameters Optional parameter metadata. Non-trainable entries receive zero gradient components and are not perturbed. step Positive imaginary displacement for trainable components.
Returns¶
GradientResult Objective value, complex-step gradient, metadata, and claim boundary.
Raises¶
ValueError If the step is invalid, parameters are malformed, the objective is not scalar, or the base value has a non-zero imaginary component.
batch_complex_step_gradient(objectives, values, *, parameters=None, step=1e-30)
¶
Return stacked complex-step gradients for real-analytic objectives.
Parameters¶
objectives Non-empty sequence of scalar objectives that support complex-step perturbations. values Real parameter vector shared by every objective. parameters Optional parameter metadata applied to each objective. step Positive imaginary displacement for trainable components.
Returns¶
numpy.ndarray Matrix whose rows are objective gradients.
Raises¶
ValueError If no objectives are provided or a delegated complex-step evaluation fails validation.
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.
Parameters¶
objectives Non-empty sequence of scalar objectives that support complex-step perturbations. values Real parameter vector shared by every objective. parameters Optional parameter metadata applied to each objective. step Positive imaginary displacement for trainable components.
Returns¶
tuple[GradientResult, ...] One value-and-gradient result per objective.
Raises¶
ValueError If no objectives are provided or a delegated complex-step evaluation fails validation.
finite_difference_jacobian(objective, values, *, parameters=None, step=1e-06)
¶
Return a central finite-difference Jacobian for vector objectives.
Parameters¶
objective Vector-valued objective evaluated on a real parameter vector. values Real parameter vector for the central-difference probes. parameters Optional parameter metadata. Non-trainable columns are zeroed. step Positive central-difference displacement.
Returns¶
numpy.ndarray
Dense Jacobian with shape (output_size, parameter_count).
Raises¶
ValueError If parameters, objective values, output shape, or the step violate the vector diagnostic contract.
value_and_finite_difference_jacobian(objective, values, *, parameters=None, step=1e-06)
¶
Evaluate a vector objective and its central finite-difference Jacobian.
Parameters¶
objective Vector-valued objective evaluated on a real parameter vector. values Real parameter vector for the central-difference probes. parameters Optional parameter metadata. Non-trainable columns are zeroed. step Positive central-difference displacement.
Returns¶
JacobianResult Objective value, Jacobian matrix, metadata, and diagnostic claim boundary.
Raises¶
ValueError If the objective output is non-vector, non-finite, or shape-unstable, or if parameter and step validation fails.
jacobian(objective, values, *, parameters=None, method='finite_difference', step=1e-06)
¶
Return a vector-objective Jacobian through the canonical transform API.
Parameters¶
objective
Vector-valued objective evaluated on a real parameter vector.
values
Real parameter vector for the diagnostic probes.
parameters
Optional parameter metadata. Non-trainable columns are zeroed.
method
Jacobian backend selector. Only "finite_difference" is currently
accepted.
step
Positive central-difference displacement.
Returns¶
numpy.ndarray
Dense Jacobian with shape (output_size, parameter_count).
Raises¶
ValueError
If method is unsupported or the delegated Jacobian evaluation fails
validation.
value_and_jacobian(objective, values, *, parameters=None, method='finite_difference', step=1e-06)
¶
Evaluate a vector objective and Jacobian through the canonical transform API.
Parameters¶
objective
Vector-valued objective evaluated on a real parameter vector.
values
Real parameter vector for the diagnostic probes.
parameters
Optional parameter metadata. Non-trainable columns are zeroed.
method
Jacobian backend selector. Only "finite_difference" is currently
accepted.
step
Positive central-difference displacement.
Returns¶
JacobianResult Objective value, Jacobian matrix, metadata, and claim boundary.
Raises¶
ValueError
If method is unsupported or the vector objective violates the
finite-difference contract.
jacfwd(objective, values, *, parameters=None, method='finite_difference', step=1e-06)
¶
Return a vector-objective Jacobian using forward-Jacobian semantics.
Parameters¶
objective
Vector-valued objective evaluated on a real parameter vector.
values
Real parameter vector for the diagnostic probes.
parameters
Optional parameter metadata. Non-trainable columns are zeroed.
method
Jacobian backend selector. Only "finite_difference" is currently
accepted.
step
Positive central-difference displacement.
Returns¶
numpy.ndarray
Dense Jacobian with shape (output_size, parameter_count).
Raises¶
ValueError
If method is unsupported or the delegated Jacobian evaluation fails
validation.
value_and_jacfwd(objective, values, *, parameters=None, method='finite_difference', step=1e-06)
¶
Evaluate a vector objective and Jacobian through forward-Jacobian semantics.
Parameters¶
objective
Vector-valued objective evaluated on a real parameter vector.
values
Real parameter vector for the diagnostic probes.
parameters
Optional parameter metadata. Non-trainable columns are zeroed.
method
Jacobian backend selector. Only "finite_difference" is currently
accepted.
step
Positive central-difference displacement.
Returns¶
JacobianResult Objective value, Jacobian matrix, metadata, and claim boundary.
Raises¶
ValueError
If method is unsupported or the delegated Jacobian evaluation fails
validation.
Notes¶
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.
Parameters¶
objective
Vector-valued objective evaluated on a real parameter vector.
values
Real parameter vector for the diagnostic probes.
parameters
Optional parameter metadata. Non-trainable columns are zeroed.
method
Jacobian backend selector. Only "finite_difference" is currently
accepted.
step
Positive central-difference displacement.
Returns¶
numpy.ndarray
Dense Jacobian with shape (output_size, parameter_count).
Raises¶
ValueError
If method is unsupported or the delegated Jacobian evaluation fails
validation.
value_and_jacrev(objective, values, *, parameters=None, method='finite_difference', step=1e-06)
¶
Evaluate a vector objective and Jacobian through reverse-Jacobian semantics.
Parameters¶
objective
Vector-valued objective evaluated on a real parameter vector.
values
Real parameter vector for the diagnostic probes.
parameters
Optional parameter metadata. Non-trainable columns are zeroed.
method
Jacobian backend selector. Only "finite_difference" is currently
accepted.
step
Positive central-difference displacement.
Returns¶
JacobianResult Objective value, Jacobian matrix, metadata, and claim boundary.
Raises¶
ValueError
If method is unsupported or the delegated Jacobian evaluation fails
validation.
Notes¶
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.
Parameters¶
objective Vector-valued objective evaluated on a real parameter vector. values Real parameter vector for the directional probes. tangent Direction vector. Non-trainable entries are masked to zero. parameters Optional parameter metadata applied to the direction mask. step Positive directional finite-difference displacement.
Returns¶
numpy.ndarray Directional output derivative with the same shape as the vector objective value.
Raises¶
ValueError If the tangent, objective output, parameters, or step violate the JVP contract.
value_and_finite_difference_jvp(objective, values, tangent, *, parameters=None, step=1e-06)
¶
Evaluate a vector objective and a directional finite-difference JVP.
Parameters¶
objective Vector-valued objective evaluated on a real parameter vector. values Real parameter vector for the directional probes. tangent Direction vector. Non-trainable entries are masked to zero. parameters Optional parameter metadata applied to the direction mask. step Positive directional finite-difference displacement.
Returns¶
JVPResult Objective value, directional derivative, masked tangent, metadata, and diagnostic claim boundary.
Raises¶
ValueError If tangent length, objective shape stability, parameter validation, or step validation fails.
batch_finite_difference_jvp(objective, values, tangents, *, parameters=None, step=1e-06)
¶
Return stacked finite-difference JVPs for a batch of tangents.
Parameters¶
objective Vector-valued objective evaluated on a real parameter vector. values Real parameter vector for every directional probe. tangents Two-dimensional tangent matrix. Each row defines one direction. parameters Optional parameter metadata applied to each direction mask. step Positive directional finite-difference displacement.
Returns¶
numpy.ndarray Matrix whose rows are directional output derivatives.
Raises¶
ValueError If the tangent batch is malformed or a delegated JVP evaluation fails.
batch_value_and_finite_difference_jvp(objective, values, tangents, *, parameters=None, step=1e-06)
¶
Return one finite-difference JVP result per tangent row.
Parameters¶
objective Vector-valued objective evaluated on a real parameter vector. values Real parameter vector for every directional probe. tangents Two-dimensional tangent matrix. Each row defines one direction. parameters Optional parameter metadata applied to each direction mask. step Positive directional finite-difference displacement.
Returns¶
tuple[JVPResult, ...] One value-and-JVP result per tangent row.
Raises¶
ValueError If the tangent batch is malformed or a delegated JVP evaluation fails.
finite_difference_vjp(objective, values, cotangent, *, parameters=None, step=1e-06)
¶
Return a finite-difference vector-Jacobian product for a vector objective.
Parameters¶
objective Vector-valued objective evaluated on a real parameter vector. values Real parameter vector for the central-difference Jacobian probes. cotangent Vector cotangent contracted with the Jacobian. parameters Optional parameter metadata. Non-trainable columns are zeroed. step Positive central-difference displacement.
Returns¶
VJPResult Objective value, cotangent, contracted VJP, metadata, and claim boundary.
Raises¶
ValueError If Jacobian construction fails validation or the cotangent shape is incompatible.
batch_finite_difference_vjp(objective, values, cotangents, *, parameters=None, step=1e-06)
¶
Return stacked finite-difference VJPs for a batch of cotangents.
Parameters¶
objective Vector-valued objective evaluated on a real parameter vector. values Real parameter vector for the shared Jacobian probes. cotangents Two-dimensional cotangent matrix. Each row defines one VJP. parameters Optional parameter metadata. Non-trainable columns are zeroed. step Positive central-difference displacement.
Returns¶
numpy.ndarray Matrix whose rows are contracted parameter-space VJP vectors.
Raises¶
ValueError If Jacobian construction fails validation or the cotangent batch is malformed.
batch_value_and_finite_difference_vjp(objective, values, cotangents, *, parameters=None, step=1e-06)
¶
Return one finite-difference VJP result per cotangent row.
Parameters¶
objective Vector-valued objective evaluated on a real parameter vector. values Real parameter vector for the shared Jacobian probes. cotangents Two-dimensional cotangent matrix. Each row defines one VJP. parameters Optional parameter metadata. Non-trainable columns are zeroed. step Positive central-difference displacement.
Returns¶
tuple[VJPResult, ...] One contracted VJP result per cotangent row.
Raises¶
ValueError If Jacobian construction fails validation or the cotangent batch is malformed.
vector_jacobian_product(jacobian, cotangent)
¶
Contract a validated cotangent with a vector-objective Jacobian.
Parameters¶
jacobian Previously validated value-and-Jacobian result. cotangent Vector cotangent whose length must match the objective output.
Returns¶
VJPResult Contracted vector-Jacobian product with inherited Jacobian metadata.
Raises¶
ValueError
If jacobian is not a JacobianResult or the cotangent shape does
not match the Jacobian value.
batch_vector_jacobian_product(jacobian, cotangents)
¶
Return one vector-Jacobian product per cotangent row.
Parameters¶
jacobian Previously validated value-and-Jacobian result. cotangents Two-dimensional cotangent matrix. Each row must match the objective output length.
Returns¶
tuple[VJPResult, ...] One contracted VJP result per cotangent row.
Raises¶
ValueError
If jacobian is not a JacobianResult or the cotangent batch is
malformed.
finite_difference_hessian(objective, values, *, parameters=None, step=0.0001)
¶
Return a central finite-difference Hessian for scalar objectives.
Parameters¶
objective Scalar objective evaluated on a real parameter vector. values Real parameter vector for the second-order probes. parameters Optional parameter metadata. Non-trainable rows and columns are zeroed. step Positive central-difference displacement for curvature probes.
Returns¶
numpy.ndarray
Dense Hessian with shape (parameter_count, parameter_count).
Raises¶
ValueError If parameter validation, scalar objective validation, or step validation fails.
value_and_finite_difference_hessian(objective, values, *, parameters=None, step=0.0001)
¶
Evaluate a scalar objective and central finite-difference Hessian.
Parameters¶
objective Scalar objective evaluated on a real parameter vector. values Real parameter vector for the second-order probes. parameters Optional parameter metadata. Non-trainable rows and columns are zeroed. step Positive central-difference displacement for curvature probes.
Returns¶
HessianResult Objective value, Hessian matrix, metadata, and diagnostic claim boundary.
Raises¶
ValueError If parameter validation, scalar objective validation, or step validation fails.
hessian(objective, values, *, parameters=None, method='finite_difference', step=0.0001)
¶
Return a scalar-objective Hessian through the canonical transform API.
Parameters¶
objective
Scalar objective evaluated on a real parameter vector.
values
Real parameter vector for the diagnostic probes.
parameters
Optional parameter metadata. Non-trainable rows and columns are zeroed.
method
Hessian backend selector. Only "finite_difference" is currently
accepted.
step
Positive central-difference displacement.
Returns¶
numpy.ndarray
Dense Hessian with shape (parameter_count, parameter_count).
Raises¶
ValueError
If method is unsupported or the delegated Hessian evaluation fails
validation.
value_and_hessian(objective, values, *, parameters=None, method='finite_difference', step=0.0001)
¶
Evaluate a scalar objective and Hessian through the canonical transform API.
Parameters¶
objective
Scalar objective evaluated on a real parameter vector.
values
Real parameter vector for the diagnostic probes.
parameters
Optional parameter metadata. Non-trainable rows and columns are zeroed.
method
Hessian backend selector. Only "finite_difference" is currently
accepted.
step
Positive central-difference displacement.
Returns¶
HessianResult Objective value, Hessian matrix, metadata, and claim boundary.
Raises¶
ValueError
If method is unsupported or the delegated Hessian evaluation fails
validation.
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.
Parameters¶
objective Scalar objective evaluated on a real parameter vector. values Real parameter vector for the directional curvature probes. tangent Direction vector. Non-trainable entries are masked to zero. parameters Optional parameter metadata applied to the direction mask. step Positive displacement for the nested finite-difference probes.
Returns¶
numpy.ndarray Parameter-space Hessian-vector product.
Raises¶
ValueError If the tangent, parameters, scalar objective result, or step violate the HVP contract.
value_and_finite_difference_hvp(objective, values, tangent, *, parameters=None, step=1e-05)
¶
Evaluate a scalar objective and a directional Hessian-vector product.
Parameters¶
objective Scalar objective evaluated on a real parameter vector. values Real parameter vector for the directional curvature probes. tangent Direction vector. Non-trainable entries are masked to zero. parameters Optional parameter metadata applied to the direction mask. step Positive displacement for the nested finite-difference probes.
Returns¶
HVPResult Objective value, Hessian-vector product, masked tangent, metadata, and diagnostic claim boundary.
Raises¶
ValueError If tangent length, parameter validation, scalar objective validation, or step validation fails.
batch_finite_difference_hvp(objective, values, tangents, *, parameters=None, step=1e-05)
¶
Return stacked finite-difference HVPs for a batch of tangents.
Parameters¶
objective Scalar objective evaluated on a real parameter vector. values Real parameter vector for every directional curvature probe. tangents Two-dimensional tangent matrix. Each row defines one HVP direction. parameters Optional parameter metadata applied to each direction mask. step Positive displacement for nested finite-difference probes.
Returns¶
numpy.ndarray Matrix whose rows are parameter-space Hessian-vector products.
Raises¶
ValueError If the tangent batch is malformed or a delegated HVP evaluation fails.
batch_value_and_finite_difference_hvp(objective, values, tangents, *, parameters=None, step=1e-05)
¶
Return one finite-difference HVP result per tangent row.
Parameters¶
objective Scalar objective evaluated on a real parameter vector. values Real parameter vector for every directional curvature probe. tangents Two-dimensional tangent matrix. Each row defines one HVP direction. parameters Optional parameter metadata applied to each direction mask. step Positive displacement for nested finite-difference probes.
Returns¶
tuple[HVPResult, ...] One value-and-HVP result per tangent row.
Raises¶
ValueError If the tangent batch is malformed or a delegated HVP evaluation fails.
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 admitted value/JVP/VJP callbacks for a fixed matrix power.
Parameters¶
power Static integer exponent; negative powers require a nonsingular matrix.
Returns¶
CustomDerivativeRule Exact callbacks that admit conversions, numeric workspaces and retained derivative powers on each invocation under the current execution owner.
Raises¶
ValueError The exponent is not an integer. Callback input contracts also reject nonreal or non-finite arrays and malformed flattened square matrices. DenseAllocationError Callback storage exceeds native addressability or current capacity.
program_ad_linalg_multi_dot_derivative_rule(operand_shapes)
¶
Build admitted value/JVP/VJP callbacks for fixed multi-dot shapes.
Parameters¶
operand_shapes Positive aligned vector or matrix dimensions. Shape validation does not allocate numeric operands; vectors are allowed only at endpoints.
Returns¶
CustomDerivativeRule Callbacks admitting conversion, chain intermediates and derivatives.
Raises¶
ValueError Static shapes do not meet rank, positive dimension or alignment rules. Callback numeric inputs must be plain real finite arrays. DenseAllocationError Callback storage exceeds native addressability or current capacity.
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, max_execution_gib=None, deadline_monotonic=None, cancelled=None)
¶
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.
max_execution_gib:
Optional declared numeric-buffer cap forwarded to the owned AD scope.
deadline_monotonic:
Absolute monotonic deadline forwarded to the owned AD scope.
cancelled:
Optional cancellation event forwarded to the owned AD scope.
Returns¶
numpy.ndarray
Exact whole-program AD gradient as float64 values.
whole_program_value_and_grad(objective, values, parameters=None, *, trace=True, max_execution_gib=None, deadline_monotonic=None, cancelled=None)
¶
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: One-dimensional real numeric values supplied as a plain NumPy ndarray, list, tuple or range. Opaque array protocols and subclasses refuse before conversion because their allocation behavior is not bounded here. parameters: Optional plain list or tuple of exact Parameter records with plain string names and boolean trainability. Metadata copies and name storage are admitted before copying; opaque sequences and record subclasses refuse without invoking their iteration or attribute protocols. trace: Whether to collect runtime trace events in addition to IR metadata. max_execution_gib: Optional cap for declared input/conversion, parameter, tangent, retained tape, gradient and trace-record buffers. Input storage is admitted before NumPy conversion; capacity is observed before initial tangent allocation; retained tangent and alias growth refuse before their materialisation. Frontend/serialization workspaces, general allocator overhead and undeclared user/third-party allocations are not fully covered by this cap. deadline_monotonic: Absolute monotonic deadline checked before frontend inspection, after source inspection and at retained-node checkpoints. cancelled: Optional cancellation event observed before frontend inspection, after source inspection and at retained-node checkpoints.
Returns¶
WholeProgramADResult Exact executed-program value, gradient, source/bytecode metadata, IR nodes, frontend report, semantics report, and scalar adjoint replay provenance. An in-memory binding checks callable code and captured numeric state, and retains the primal, numeric buffers, typed/raw IR and adjoint content together. Derivative access refuses changed artifacts.
Raises¶
ValueError If the objective is not callable, fails the source/bytecode frontend execution gate, uses unsupported Python semantics, or does not return a traceable scalar; also if captured state has unsupported storage or changes while the objective is evaluated.
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.whole_program_trace_values
¶
Operator-intercepted forward-AD trace value classes and their operations.
This module holds the derivative-carrying value runtime for whole-program AD:
:class:TraceADScalar and :class:TraceADArray and the trace-coupled helpers
that implement their NumPy __array_function__ dispatch, ufunc application,
shape/index/selection/reduction/linalg operations, and coercion. The value
classes and their helpers are mutually recursive (operations build new trace
values), so they form one cohesive runtime unit.
Static operand normalisation comes from
:mod:~scpn_quantum_control.whole_program_trace_metadata, primal predicates from
:mod:~scpn_quantum_control.whole_program_trace_predicates, the trace context and
event recording from :mod:~scpn_quantum_control.whole_program_trace_runtime, and
the per-primitive derivative rules from the program_ad_* primitive modules.
The public reverse/forward-mode entry points
(value_and_grad/grad/whole_program_value_and_grad and friends) are
owned by focused API modules and re-exported by
:mod:~scpn_quantum_control.differentiable for compatibility.
Module size note: this module is intentionally kept whole. Its top-level definitions form a single connected operator-intercepted forward-AD trace-value cluster, so it is sized by responsibility rather than line count. Its classes are mutually recursive, so splitting would introduce import cycles. See docs/architecture.md ("Module size and single-responsibility policy").
TraceADScalar
¶
Operator-intercepted scalar for exact executed-path whole-program AD.
Parameters¶
primal: Finite real value carried by the trace. tangent: One-dimensional derivative vector aligned with the trace parameters. context: Trace context that owns the value and records derived operations. name: Stable SSA-style label used by trace and adjoint metadata.
Notes¶
Arithmetic, comparisons, and supported NumPy ufuncs preserve the owning
context. Conversion to a Python float fails closed because it would
discard derivative information.
__float__()
¶
Reject conversion that would discard derivative information.
__int__()
¶
Reject parameter-dependent integer conversion.
Raises¶
ValueError Integer conversion would discard the active derivative and could turn a traced parameter into an unqualified dynamic shape or index.
__index__()
¶
Reject using a traced parameter as an integer shape or index.
Raises¶
ValueError A derivative-carrying scalar has no static integer indexing contract.
__add__(other)
¶
Return the derivative-preserving scalar sum.
__radd__(other)
¶
Return the derivative-preserving reflected scalar sum.
__sub__(other)
¶
Return the derivative-preserving scalar difference.
__rsub__(other)
¶
Return the derivative-preserving reflected scalar difference.
__mul__(other)
¶
Return the derivative-preserving scalar product.
__rmul__(other)
¶
Return the derivative-preserving reflected scalar product.
__truediv__(other)
¶
Return the derivative-preserving scalar quotient.
__rtruediv__(other)
¶
Return the derivative-preserving reflected scalar quotient.
__pow__(other)
¶
Return the derivative-preserving scalar power.
__rpow__(other)
¶
Return the derivative-preserving reflected scalar power.
__neg__()
¶
Return the derivative-preserving additive inverse.
__abs__()
¶
Return the derivative-preserving absolute value.
__gt__(other)
¶
Return the traced strict-greater-than predicate.
__ge__(other)
¶
Return the traced greater-than-or-equal predicate.
__lt__(other)
¶
Return the traced strict-less-than predicate.
__le__(other)
¶
Return the traced less-than-or-equal predicate.
__eq__(other)
¶
Return the traced equality predicate.
__ne__(other)
¶
Return the traced inequality predicate.
__array_ufunc__(ufunc, method, *inputs, **kwargs)
¶
Dispatch a supported NumPy ufunc through scalar trace semantics.
TraceADArray
¶
Derivative-carrying ranked array for whole-program AD.
Parameters¶
items:
Row-major scalar trace values carried by the array.
shape:
Static NumPy-compatible shape whose element count matches items.
context:
Trace context shared by every scalar item.
source_indices:
Optional original parameter slots retained through alias-preserving
views; None entries identify constants or overwritten elements.
Notes¶
Supported NumPy functions dispatch through __array_function__ and
supported ufuncs through __array_ufunc__. Raw ndarray coercion fails
closed because it would discard derivative and alias metadata.
ndim
property
¶
The rank of the derivative-carrying array.
size
property
¶
The total number of derivative-carrying elements.
T
property
¶
The NumPy-compatible reversed-axis transpose.
__len__()
¶
Return the leading-axis length of a ranked trace array.
__iter__()
¶
Iterate over trace scalars or rank-one row views.
__array__(dtype=None, *, copy=None)
¶
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.
__getitem__(index)
¶
Return a derivative-preserving indexed scalar or array view.
__setitem__(index, value)
¶
Assign traced values while recording deterministic mutation metadata.
__array_ufunc__(ufunc, method, *inputs, **kwargs)
¶
Dispatch direct ufuncs or bounded unbuffered np.add.at mutations.
__array_function__(func, types, args, kwargs)
¶
Dispatch a supported NumPy function through fail-closed trace semantics.
__add__(other)
¶
Return the derivative-preserving elementwise sum.
__radd__(other)
¶
Return the derivative-preserving reflected elementwise sum.
__sub__(other)
¶
Return the derivative-preserving elementwise difference.
__rsub__(other)
¶
Return the derivative-preserving reflected elementwise difference.
__mul__(other)
¶
Return the derivative-preserving elementwise product.
__rmul__(other)
¶
Return the derivative-preserving reflected elementwise product.
__truediv__(other)
¶
Return the derivative-preserving elementwise quotient.
__rtruediv__(other)
¶
Return the derivative-preserving reflected elementwise quotient.
__pow__(other)
¶
Return the derivative-preserving elementwise power.
__rpow__(other)
¶
Return the derivative-preserving reflected elementwise power.
__neg__()
¶
Return the derivative-preserving elementwise additive inverse.
__matmul__(other)
¶
Return the derivative-preserving matrix product.
__rmatmul__(other)
¶
Return the derivative-preserving reflected matrix product.
__gt__(other)
¶
Return the traced elementwise strict-greater-than predicate.
__ge__(other)
¶
Return the traced elementwise greater-than-or-equal predicate.
__lt__(other)
¶
Return the traced elementwise strict-less-than predicate.
__le__(other)
¶
Return the traced elementwise less-than-or-equal predicate.
__eq__(other)
¶
Return the traced elementwise equality predicate.
__ne__(other)
¶
Return the traced elementwise inequality predicate.
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
¶
Sorted categories covered by this audit.
missing_categories
property
¶
Required categories missing from the audit.
passed_cases
property
¶
Cases whose executed residuals are within tolerance.
failed_cases
property
¶
Cases whose executed residuals exceeded tolerance.
blocked_cases
property
¶
Explicit fail-closed transform-algebra boundaries.
support_matrix
property
¶
Support rows generated from executable and blocked cases.
missing_support_rows
property
¶
Required support-matrix rows missing from the generated matrix.
failed_support_rows
property
¶
Generated support rows whose source cases failed.
passed
property
¶
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
¶
Whether TensorFlow is scoped as a compatibility-only surface.
graph_xla_parity_promoted
property
¶
Whether broad TensorFlow Graph/XLA parity is promoted.
maintained_compatibility_routes
property
¶
Bounded TensorFlow routes kept under maintenance.
blocked_routes
property
¶
TensorFlow routes that remain blocked.
ready_for_provider_exceedance
property
¶
Whether TensorFlow can support provider-exceedance claims.
stale_claim_blockers
property
¶
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_optimizer_convergence
¶
Benchmark artefacts for ground-state optimizer convergence rows.
GROUND_STATE_OPTIMIZER_CONVERGENCE_SCHEMA = 'scpn_qc_ground_state_optimizer_convergence_v1'
module-attribute
¶
GroundStateOptimizerConvergenceArtifact
dataclass
¶
Written ground-state optimizer convergence artefact metadata.
to_dict()
¶
Return JSON-ready artifact metadata.
ground_state_optimizer_convergence_payload(suite=None, *, artifact_id='ground-state-optimizer-convergence-local')
¶
Return the ground-state optimizer convergence artifact payload.
render_ground_state_optimizer_convergence_markdown(payload)
¶
Render optimizer convergence payload as bounded Markdown evidence.
write_ground_state_optimizer_convergence_artifact(output_path, *, markdown_path=None, suite=None, artifact_id='ground-state-optimizer-convergence-local')
¶
Write JSON and Markdown ground-state optimizer convergence artefacts.
scpn_quantum_control.benchmarks.open_system_objective_evidence
¶
Benchmark artefacts for bounded Lindblad and MCWF objectives.
OPEN_SYSTEM_OBJECTIVE_EVIDENCE_SCHEMA = 'scpn_qc_open_system_objective_evidence_v1'
module-attribute
¶
OpenSystemObjectiveEvidenceArtifact
dataclass
¶
Written open-system objective artifact metadata.
to_dict()
¶
Return JSON-ready artifact metadata.
open_system_objective_evidence_payload(suite=None, *, artifact_id='open-system-objective-evidence-local')
¶
Return the bounded open-system objective evidence payload.
render_open_system_objective_evidence_markdown(payload)
¶
Render the open-system objective payload as bounded Markdown evidence.
write_open_system_objective_evidence_artifact(output_path, *, markdown_path=None, suite=None, artifact_id='open-system-objective-evidence-local')
¶
Write JSON and Markdown open-system objective artefacts.
scpn_quantum_control.benchmarks.differentiable_catalyst_comparison
¶
Catalyst compiler-workflow evidence boundaries for differentiable comparisons.
CATALYST_UNSUPPORTED_PROVIDER_ROUTES = ('finite_shot_provider_jobs', 'hardware_qpu_execution', 'cloud_provider_submission')
module-attribute
¶
CatalystCompilerWorkflowComparison
dataclass
¶
catalyst_compiler_workflow_comparison(*, runner_status)
¶
Build the standard Catalyst compiler-workflow comparison profile.
scpn_quantum_control.benchmarks.differentiable_external_comparison
¶
External framework comparison harness 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
¶
One external framework/compiler comparison row.
closure_status
property
¶
The row's implementation or permanent-boundary classification.
closure_reason
property
¶
The non-empty implementation or boundary reason for the row.
artifact_fields_ready
property
¶
Whether this row is serializable as an evidence artefact.
__post_init__()
¶
Validate external comparison row evidence invariants.
to_dict()
¶
Return a JSON-ready row.
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
¶
Ticketed PennyLane hardware-plugin execution evidence.
The artefact records a captured live hardware-plugin run without promoting
benchmark or provider-exceedance claims. Calibration freshness is expressed
by UTC capture and expiry timestamps; construction rejects inverted windows,
and run_pennylane_plugin_matrix rejects stale calibration at the review
cutoff before opening the hardware-plugin route.
PennyLaneProviderEvidenceBundle
dataclass
¶
PennyLanePluginMatrixResult
dataclass
¶
Fail-closed PennyLane plugin/provider parity matrix.
local_plugin_parity_ready
property
¶
Whether bounded local/default-qubit PennyLane routes pass.
provider_plugin_execution_ready
property
¶
Whether provider-plugin execution artefacts are attached.
hardware_plugin_execution_ready
property
¶
Whether live hardware-plugin execution artefacts are attached.
provider_plugin_gradient_parity_ready
property
¶
Whether provider-plugin gradient parity artefacts are attached.
ready_for_provider_exceedance
property
¶
Whether the matrix permits PennyLane provider-exceedance claims.
open_gaps
property
¶
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
¶
Validated PennyLane provider-plugin gradient parity evidence.
Parity artefacts must match the referenced provider execution artefact on interface, differentiation method, analytic versus finite-shot policy, device identity, circuit fingerprint, and shots before the provider-gradient route can pass.
PennyLaneProviderPluginExecutionArtifact
dataclass
¶
Validated PennyLane provider-plugin execution evidence.
Provider evidence records the PennyLane interface, differentiation method, and analytic versus finite-shot policy used for the captured provider route. Interface and differentiation method identifiers are constrained to documented PennyLane QNode strings. Those fields are part of the evidence chain, so provider-gradient parity must cite the same values before the route can pass.
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. Ticketed hardware artefacts must
carry fresh calibration metadata for the supplied review cutoff.
scpn_quantum_control.differentiable_claim_ledger
¶
Claim ledger for bounded differentiable Phase-QNode evidence.
ClaimLedger
dataclass
¶
Hold a validated differentiable claim ledger.
Parameters¶
schema Ledger schema identity. artifact_id Stable ledger artefact identity. rows Non-empty ordered claim rows.
ClaimLedgerRow
dataclass
¶
Describe one bounded claim and its evidence surfaces.
Parameters¶
claim_id Stable lowercase snake- or kebab-case identity for the claim. claim_text Human-readable statement governed by the row. implementation_surface Repository-relative production paths supporting the claim. test_surface Repository-relative test paths exercising the production surfaces. docs_surface Repository-relative documentation and evidence paths. evidence_artifact_ids Stable identities for supporting evidence artefacts. benchmark_artifact_ids Stable identities for benchmark evidence. known_gaps Explicit limitations that bound the claim. promotion_status Current promotion state. claim_boundary Exact wording that limits public use of the claim.
ClaimLedgerValidation
dataclass
¶
Report a claim-ledger validation result.
Parameters¶
passed Whether every checked invariant passed. errors Ordered validation errors; empty only for a passing result.
DifferentiableSupportSurfaceAlignment
dataclass
¶
Report docs, API, and generated-manifest claim alignment.
Parameters¶
passed Whether every alignment check passed. errors Ordered alignment errors. checked_claim_ids Claim identities included in the audit. checked_paths Repository surfaces included in the audit. claim_boundary Non-promotional interpretation boundary. schema Alignment schema identity. artifact_id Stable alignment artefact identity.
load_differentiable_claim_ledger(path=DEFAULT_LEDGER_PATH)
¶
Load and validate a differentiable claim ledger.
Parameters¶
path JSON ledger path.
Returns¶
ClaimLedger Validated ledger with ordered rows.
Raises¶
OSError If the ledger cannot be read. json.JSONDecodeError If the ledger is not valid JSON. ValueError If the decoded JSON violates the ledger contract.
load_differentiable_support_surface_alignment(path=DEFAULT_SUPPORT_SURFACE_ALIGNMENT_PATH)
¶
Load and validate support-surface alignment evidence.
Parameters¶
path JSON alignment-evidence path.
Returns¶
DifferentiableSupportSurfaceAlignment Validated alignment evidence.
Raises¶
OSError If the artefact cannot be read. json.JSONDecodeError If the artefact is not valid JSON. ValueError If the decoded JSON violates the alignment contract.
render_claim_ledger_markdown(rows)
¶
render_differentiable_support_surface_alignment_markdown(alignment)
¶
validate_claim_ledger(rows_or_ledger, *, artifact_statuses=None)
¶
Validate claim-ledger promotion invariants.
Parameters¶
rows_or_ledger
Validated ledger or ordered rows to inspect.
artifact_statuses
Optional artefact-ID to status mapping. When supplied, every evidence
and benchmark ID on a promoted row must map to "passed"; an empty
mapping therefore fails closed.
Returns¶
ClaimLedgerValidation Pass flag and deterministic errors.
validate_differentiable_support_surface_alignment(rows=None, *, repo_root=REPO_ROOT, ledger_path=DEFAULT_LEDGER_PATH, manifest_path=DEFAULT_CAPABILITY_MANIFEST_PATH)
¶
Validate claim surfaces against the repository and generated inventory.
Parameters¶
rows
Optional rows to validate instead of loading the committed ledger.
repo_root
Repository root used for path containment and existence checks.
ledger_path
Ledger loaded when rows is omitted.
manifest_path
Generated capability manifest whose path inventory must include source,
test, and documentation surfaces.
Returns¶
DifferentiableSupportSurfaceAlignment Deterministic alignment evidence. Unsafe, missing, or unregistered paths produce a failed result without being dereferenced outside the repository.
validate_public_language_against_ledger(rows_or_ledger, public_texts)
¶
Reject promotional wording unless every ledger row is promoted.
The validator has no category-to-text mapping, so a single promoted row cannot safely authorise promotional wording for a mixed ledger.
Parameters¶
rows_or_ledger Ledger or rows governing the public text. public_texts Public strings to inspect case-insensitively.
Returns¶
ClaimLedgerValidation Pass flag and one error per banned phrase occurrence.
scpn_quantum_control.differentiable_architecture_map
¶
Architecture and Rustification map for differentiable-programming governance.
DifferentiableArchitectureMap
dataclass
¶
Aggregate deterministic differentiable Rustification routing layers.
Parameters¶
schema, artifact_id : str Versioned schema and committed artifact identifiers. layers : tuple[DifferentiableArchitectureMapLayer, ...] Ordered architecture routing layers. rustification_ready : bool Whether every layer and both upstream evidence sources are ready. ready_layer_count, total_layer_count : int Ready and total layer counts. claim_boundary : str Non-promotional interpretation attached to the map.
__post_init__()
¶
Reject structurally empty architecture-map records.
Raises¶
ValueError
If identity text has the wrong type or is blank, layers are not a
non-empty tuple of architecture-layer records, readiness is not a
boolean, or counts are not non-negative integers. Cross-field and
upstream invariants are checked by
:func:validate_differentiable_architecture_map.
DifferentiableArchitectureMapLayer
dataclass
¶
Tie one architecture layer to inventory, scorecard, and evidence paths.
Parameters¶
layer_id : DifferentiableArchitectureLayerId
Stable identifier from :data:REQUIRED_ARCHITECTURE_LAYER_IDS.
title, role : str
Reviewer-facing title and the layer's routing responsibility.
owner_modules, python_surfaces, rust_surfaces, polyglot_surfaces : tuple[str, ...]
Owning modules and implementation paths across language boundaries.
inventory_surface_ids : tuple[str, ...]
Rust/Python inventory rows routed through this layer.
baseline_categories : tuple[DifferentiableBaselineCategory, ...]
External-baseline categories governed by this layer.
test_surfaces, docs_surfaces : tuple[str, ...]
Repository paths that prove and document the routing.
benchmark_surfaces : tuple[str, ...]
Benchmark or evidence artifact identifiers attached to the layer.
blockers, next_hardening_rounds : tuple[str, ...]
Explicit gaps and the rounds that own their remediation.
claim_boundary : str
Non-promotional interpretation attached to the layer.
rustification_ready
property
¶
Whether the layer is free of declared Rustification blockers.
Returns¶
bool
True only when no blocker is attached to the layer.
DifferentiableArchitectureMapValidation
dataclass
¶
Record fail-closed architecture-map validation evidence.
Parameters¶
passed : bool Whether every structural, upstream, routing, and path check passed. errors : tuple[str, ...] Deterministically ordered validation findings. checked_layer_ids, checked_inventory_surface_ids : tuple[str, ...] Layer and inventory identifiers inspected by the validator. checked_baseline_categories : tuple[DifferentiableBaselineCategory, ...] Scorecard categories inspected by the validator. checked_paths : tuple[str, ...] Repository-relative evidence paths inspected by the validator. claim_boundary : str Non-promotional interpretation attached to the evidence.
render_differentiable_architecture_map_markdown(architecture_map)
¶
run_differentiable_architecture_map(*, inventory=None, scorecard=None)
¶
Build the architecture and Rustification map from committed evidence.
Parameters¶
inventory : DifferentiableRustPythonInventory, optional Preloaded Rust/Python inventory. The committed inventory is built when omitted. scorecard : DifferentiableBaselineScorecard, optional Preloaded external-baseline scorecard. The committed scorecard is built when omitted.
Returns¶
DifferentiableArchitectureMap Six ordered routing layers with aggregate readiness.
Raises¶
ValueError If the supplied inventory omits a surface required by the canonical architecture routing specification.
validate_differentiable_architecture_map(architecture_map, *, inventory=None, scorecard=None, repo_root=REPO_ROOT)
¶
Validate architecture layers, references, paths, and readiness invariants.
Parameters¶
architecture_map : DifferentiableArchitectureMap Candidate architecture map to validate. inventory : DifferentiableRustPythonInventory, optional Inventory against which every routed surface is checked. scorecard : DifferentiableBaselineScorecard, optional Scorecard against which every routed category is checked. repo_root : pathlib.Path, optional Repository root used to resolve declared evidence paths.
Returns¶
DifferentiableArchitectureMapValidation Fail-closed upstream, identity, routing, coverage, path, and readiness evidence.
scpn_quantum_control.differentiable_dependency_environment_map
¶
Dependency and environment evidence map for differentiable-programming governance.
DifferentiableDependencyEnvironmentMap
dataclass
¶
Aggregate deterministic dependency profiles and environment evidence.
Parameters¶
schema : str Versioned schema identifier for the emitted map. artifact_id : str Stable identifier for the committed evidence artefact. profiles : tuple[DifferentiableDependencyEnvironmentProfile, ...] Ordered dependency profiles governed by the map. environment_ready : bool Whether every profile and the underlying lock permit promotion. ready_profile_count : int Number of profiles whose locked evidence has no blockers. total_profile_count : int Number of profiles represented in the map. evidence_records : tuple[DifferentiableDependencyEnvironmentEvidence, ...] Ordered version-pin and execution-route evidence inventory. ready_evidence_count : int Number of evidence rows whose cited sources are locked. total_evidence_count : int Number of evidence rows represented in the map. claim_boundary : str Non-promotional interpretation attached to the map.
DifferentiableDependencyEnvironmentProfile
dataclass
¶
Describe one differentiable profile tied to lockfile evidence.
Parameters¶
profile_id : DifferentiableDependencyEnvironmentProfileId or str Stable identifier for the runtime or verification profile. title : str Reviewer-facing profile title. role : str Purpose of the profile within differentiable validation. lockfile_paths : tuple[str, ...] Repository-relative lockfiles that define the environment. evidence_paths : tuple[str, ...] Repository-relative files reviewers must be able to inspect. pinned_package_count : int Total pinned package entries across the profile lockfiles. checksum_count : int Number of profile lockfiles carrying a non-empty checksum. evidence_status : DifferentiableDependencyEnvironmentStatus Whether the profile is locked or remains a hard gap. blockers : tuple[str, ...] Explicit reasons the profile cannot support promotion. claim_boundary : str Non-promotional interpretation attached to the evidence.
environment_ready
property
¶
Whether this dependency profile can support promotion.
Returns¶
bool
True only for a locked profile without blockers.
DifferentiableDependencyEnvironmentMapValidation
dataclass
¶
Record validation evidence for a dependency environment map.
Parameters¶
passed : bool Whether every structural and filesystem invariant passed. errors : tuple[str, ...] Deterministic validation errors in discovery order. checked_profile_ids : tuple[str, ...] Profile identifiers encountered during validation. checked_evidence_ids : tuple[str, ...] Toolchain and execution-route identifiers encountered during validation. checked_paths : tuple[str, ...] Sorted repository-relative evidence paths checked. checked_lockfile_count : int Number of distinct lockfile paths in the environment lock. checked_pinned_package_count : int Aggregate pinned-package count in the environment lock. claim_boundary : str Non-promotional interpretation attached to validation evidence.
render_differentiable_dependency_environment_map_markdown(environment_map)
¶
Render a reviewer-facing Markdown summary of the dependency map.
Parameters¶
environment_map : DifferentiableDependencyEnvironmentMap Dependency map to render without changing its readiness classification.
Returns¶
str SPDX-prefixed Markdown with aggregate readiness, profile rows, and the non-promotional claim boundary.
run_differentiable_dependency_environment_map(*, environment_lock=None)
¶
Build the dependency and environment map from lockfile evidence.
Parameters¶
environment_lock : ExternalValidationEnvironmentLock, optional Prebuilt lock evidence. When omitted, the current repository lockfiles are summarised through the external-validation environment builder.
Returns¶
DifferentiableDependencyEnvironmentMap Ordered profile evidence and aggregate readiness without promotion.
validate_differentiable_dependency_environment_map(environment_map, *, environment_lock=None, repo_root=REPO_ROOT)
¶
Validate profiles, paths, checksums, and readiness invariants.
Parameters¶
environment_map : DifferentiableDependencyEnvironmentMap
Candidate map whose schema, ordering, counts, paths, and blockers are
validated.
environment_lock : ExternalValidationEnvironmentLock, optional
Prebuilt environment lock. When omitted, lock evidence is rebuilt from
repo_root.
repo_root : pathlib.Path, optional
Repository root used to resolve every cited evidence path.
Returns¶
DifferentiableDependencyEnvironmentMapValidation Fail-closed validation evidence containing every discovered error.
scpn_quantum_control.differentiable_dependency_environment_evidence
¶
Version-pin and execution-route evidence for differentiable environments.
DifferentiableDependencyEnvironmentEvidence
dataclass
¶
Describe one version-pin or execution-route evidence row.
Parameters¶
evidence_id : DifferentiableDependencyEnvironmentEvidenceId or str
Stable identifier governed by the required evidence inventory.
title : str
Reviewer-facing row title.
category : DifferentiableDependencyEnvironmentEvidenceCategory
Whether the row describes a toolchain or an execution route.
classification : str
Required toolchain or route classification for the row.
version_pins : tuple[str, ...]
Exact pins or, for a declared-unlocked hard gap, version constraints.
evidence_paths : tuple[str, ...]
Repository-relative source files supporting the row.
evidence_sha256 : tuple[str, ...]
SHA-256 digests aligned one-to-one with evidence_paths.
evidence_status : DifferentiableDependencyEnvironmentEvidenceStatus
Locked evidence or an explicit hard gap.
blockers : tuple[str, ...]
Promotion blockers; empty only for locked evidence.
claim_boundary : str
Canonical non-promotional interpretation.
build_differentiable_dependency_environment_evidence(*, repo_root=REPO_ROOT)
¶
scpn_quantum_control.differentiable_competitive_baselines
¶
Freshness gate for differentiable-computing competitive baselines.
CompetitiveBaselinePromotionGate
dataclass
¶
CompetitiveBaselineRefresh
dataclass
¶
CompetitiveBaselineRow
dataclass
¶
One upstream differentiable-computing baseline source.
classification
property
¶
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
¶
audit_competitive_baseline_promotion_gate(*, refresh=None, refresh_path=DEFAULT_COMPETITIVE_BASELINE_REFRESH_PATH, as_of=None, public_texts=None, public_paths=DEFAULT_PUBLIC_PROMOTION_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, 8, 25))
¶
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
¶
Stable MLIR compiler facade over focused implementation leaves.
MLIRCompileConfig
dataclass
¶
Configuration for Kuramoto-XY MLIR-style export.
__post_init__()
¶
Validate public MLIR compile configuration fields.
DifferentiableMLIRCompileConfig
dataclass
¶
Configuration for differentiable primitive MLIR-style lowering.
__post_init__()
¶
Validate differentiable MLIR compile configuration fields.
CompilerADExecutableConfig
dataclass
¶
Configuration for verified executable primitive AD kernels.
__post_init__()
¶
Validate executable compiler-AD kernel configuration fields.
CompilerADKernelVerification
dataclass
¶
ExecutableCompilerADKernel
dataclass
¶
Executable compiler-backed primitive AD kernel with MLIR provenance.
__post_init__()
¶
Validate executable kernels and their verified provenance.
value(values)
¶
Execute the compiled value kernel.
jvp(values, tangent)
¶
Execute the compiled JVP kernel.
vjp(values, cotangent)
¶
Execute the compiled VJP kernel.
gradient(values)
¶
Execute the compiled scalar-output gradient kernel.
ExecutableWholeProgramADBatchResult
dataclass
¶
Batched replay result from an executable whole-program AD kernel.
__post_init__()
¶
Validate batch shape, provenance, backend, and normalized arrays.
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.
__post_init__()
¶
Validate replay provenance, parameters, signature, and claim boundary.
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.
__post_init__()
¶
Validate the verified native kernel and all executable contracts.
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.
__post_init__()
¶
Validate module text provenance and freeze mapping fields.
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.
CycleSample
dataclass
¶
Sub-microsecond timing record for one outer-loop cycle.
All timestamps are integer nanoseconds on a monotonic clock. A cycle misses
its deadline when end_ns exceeds deadline_ns.
Attributes¶
cycle_id : int Caller-defined cycle identifier. start_ns : int Monotonic cycle start in nanoseconds. end_ns : int Monotonic cycle finish in nanoseconds. deadline_ns : int Absolute monotonic deadline in nanoseconds.
RealtimeSLAConfig
dataclass
¶
Service-level contract for realtime-loop latency and jitter.
Attributes¶
max_latency_s : float
Maximum permitted observed latency in seconds.
max_jitter_s : float
Maximum permitted observed jitter in seconds.
p95_latency_s : float or None
Optional 95th-percentile latency ceiling in seconds.
p99_latency_s : float or None
Optional 99th-percentile latency ceiling in seconds.
max_deadline_miss_rate : float
Maximum permitted fraction of missed ticks in the closed interval
[0, 1].
RealtimeSLAReport
dataclass
¶
Measured SLA verdict for one realtime run.
Attributes¶
compliant : bool Whether every configured SLA bound passed. breach_reasons : tuple[str, ...] Human-readable descriptions of every breached bound. observed_max_latency_s : float Maximum observed latency in seconds. observed_max_jitter_s : float Maximum observed jitter in seconds. observed_p95_latency_s : float Linear-interpolated 95th-percentile latency in seconds. observed_p99_latency_s : float Linear-interpolated 99th-percentile latency in seconds. observed_deadline_miss_rate : float Fraction of ticks recorded as deadline misses. n_ticks : int Number of tick records evaluated.
MonotonicRealtimeClock
¶
Wall-clock implementation backed by :func:time.monotonic.
RealtimeClock
¶
Bases: Protocol
Monotonic clock boundary used by the realtime runtime.
Implementations expose seconds from an arbitrary monotonic epoch. Runtime calculations depend only on differences between readings, never on the epoch itself.
RealtimeRunResult
dataclass
¶
Aggregate result for a realtime control-loop run.
Attributes¶
records : tuple[RealtimeTickRecord, ...] Ordered per-tick telemetry. completed : bool Whether every requested tick completed. missed_deadlines : int Number of ticks whose latency or jitter exceeded its bound. max_latency_s : float Maximum observed execution latency in seconds. max_jitter_s : float Maximum observed budget-filtered jitter in seconds.
RealtimeRuntimeConfig
dataclass
¶
Timing contract for a realtime software control loop.
Attributes¶
sample_period_s : float
Scheduled start-to-start period in seconds.
deadline_s : float
Maximum permitted step execution latency in seconds. It cannot exceed
sample_period_s.
jitter_budget_s : float
Maximum start-to-start scheduling deviation in seconds. Deviations at
or below this value are recorded as zero.
max_missed_deadlines : int
Number of missed ticks tolerated before the runtime fails closed.
align_to_period : bool
Whether each tick waits for its scheduled start. When false, ticks run
immediately while retaining the same schedule for telemetry.
RealtimeTickRecord
dataclass
¶
Auditable timing record for one realtime tick.
Attributes¶
index : int Zero-based tick index. scheduled_start_s : float Intended start time in monotonic seconds. actual_start_s : float Observed start time in monotonic seconds. finish_s : float Observed finish time in monotonic seconds. latency_s : float Step execution duration in seconds. jitter_s : float Budget-filtered start-to-start deviation in seconds. deadline_missed : bool Whether latency or jitter exceeded its configured bound. metrics : Mapping[str, float] Finite numeric metrics returned by the control step. The stored mapping is an immutable copy.
__post_init__()
¶
Copy metrics into an immutable mapping.
SubMicrosecondReport
dataclass
¶
Aggregate inter-cycle jitter and deadline-miss telemetry.
Attributes¶
jitter_p50_ns : float Median retained jitter in nanoseconds. jitter_p95_ns : float Linear-interpolated 95th-percentile jitter in nanoseconds. jitter_p99_ns : float Linear-interpolated 99th-percentile jitter in nanoseconds. jitter_max_ns : float Maximum retained jitter in nanoseconds. deadline_misses : int Total missed cycles, including samples outside the retained window. cycles_observed : int Total cycles recorded or summarised. target_period_ns : float Expected start-to-start interval in nanoseconds. window_size : int Number of jitter samples used for percentile estimation.
SubMicrosecondTracker
¶
Sub-microsecond outer-loop jitter and deadline tracker.
Records integer-nanosecond cycle samples and reports inter-cycle jitter
percentiles against the target period plus a deadline-miss count. The jitter
of a cycle is the absolute deviation of its start-to-start interval from the
target period 1e9 / target_rate_hz nanoseconds; the first observed cycle
has zero jitter. Recent jitter samples are kept in a bounded ring of
ring_buffer_capacity entries for percentile estimation, while total
cycles and total deadline misses are running counters and stay exact across
ring overwrites.
This is software telemetry for the microsecond-scale outer loop, not an intra-shot hardware-latency claim; the downstream sub-50 ns FPGA path is covered by RTL assertions in the consumer.
Parameters¶
target_rate_hz : int Positive target cycle rate in hertz. ring_buffer_capacity : int Positive maximum number of jitter samples retained for percentiles.
Raises¶
TypeError If either parameter is not a plain integer. ValueError If either parameter is less than one.
cycles_observed
property
¶
The total number of recorded cycles.
Returns¶
int Count since construction or the most recent reset.
__init__(target_rate_hz=100000, ring_buffer_capacity=1 << 16)
¶
Initialise an empty tracker for a target rate and window size.
record(sample)
¶
report()
¶
reset()
¶
Clear all retained samples, counters, and interval history.
VirtualRealtimeClock
¶
Deterministic clock for simulation and control-loop verification.
enforce_realtime_sla(result, *, sla)
¶
Require a realtime run to satisfy an SLA contract.
Parameters¶
result : RealtimeRunResult Completed run telemetry to evaluate. sla : RealtimeSLAConfig Maximum, percentile, and miss-rate bounds.
Returns¶
RealtimeSLAReport Compliant report for the run.
Raises¶
ValueError
If result contains no tick records.
RuntimeError
If any configured SLA bound is breached.
evaluate_realtime_sla(result, *, sla)
¶
Evaluate a realtime run against an SLA contract.
Parameters¶
result : RealtimeRunResult Completed run telemetry to evaluate. sla : RealtimeSLAConfig Maximum, percentile, and miss-rate bounds.
Returns¶
RealtimeSLAReport Observed statistics and all breach reasons.
Raises¶
ValueError
If result contains no tick records.
Notes¶
Percentiles use NumPy's linear interpolation method.
run_realtime_control_loop(n_ticks, step, *, config, clock=None)
¶
Run a control step on a fixed-period schedule.
Parameters¶
n_ticks : int Number of ticks to execute. step : RealtimeStep Callable receiving the zero-based tick index and returning finite numeric metrics. config : RealtimeRuntimeConfig Period, deadline, jitter, miss-budget, and alignment contract. clock : RealtimeClock or None Monotonic clock implementation. The wall-clock implementation is used when omitted.
Returns¶
RealtimeRunResult Ordered tick records and aggregate latency, jitter, and miss telemetry.
Raises¶
ValueError
If n_ticks is not a positive integer or a metric is invalid.
RuntimeError
If the number of missed ticks exceeds max_missed_deadlines.
Notes¶
A tick misses when its execution latency exceeds deadline_s or its
unsuppressed start-to-start jitter exceeds jitter_budget_s.
summarise_cycle_samples(start_ns, end_ns, deadline_ns, *, target_rate_hz=100000)
¶
Summarise arrays of cycle timestamps in a single pass.
This is the batch path consumed by the throughput benchmark and by callers
that buffer cycle timestamps and summarise them periodically. It computes the
same jitter percentiles and deadline-miss count as
:class:SubMicrosecondTracker over the full input.
Parameters¶
start_ns : numpy.ndarray or list[int] One-dimensional cycle-start timestamps in monotonic nanoseconds. end_ns : numpy.ndarray or list[int] One-dimensional cycle-finish timestamps in monotonic nanoseconds. deadline_ns : numpy.ndarray or list[int] One-dimensional absolute deadlines in monotonic nanoseconds. target_rate_hz : int Positive target cycle rate in hertz.
Returns¶
SubMicrosecondReport Full-window jitter percentiles and deadline-miss count.
Raises¶
TypeError
If target_rate_hz is not a plain integer.
ValueError
If the rate is non-positive, arrays are not one-dimensional and equal
length, no cycle is supplied, or a finish/deadline precedes its start.
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.
__post_init__()
¶
Validate the Kubernetes resource quantities.
CloudDeploymentSpec
dataclass
¶
Cloud-native deployment request for an offline SCPN workload.
__post_init__()
¶
Validate and freeze the deployment request.
CloudManifestBundle
dataclass
¶
Generated cloud-native manifest files plus provenance digest.
__post_init__()
¶
Validate the manifest digest and freeze the files.
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 provider metadata adapters and compatibility facade.
Provider-neutral capability contracts, route assessment, and OpenPulse
readiness live in :mod:.provider_capability_core. This module re-exports the
exact core and provider-adapter objects for compatibility.
ProviderCapabilitySnapshot
dataclass
¶
Provider target metadata collected without submitting a workload.
__post_init__()
¶
Validate the no-submit target metadata contract.
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, max_calibration_age_seconds=None, as_of=None)
¶
Assess route metadata, optionally requiring a fresh calibration timestamp.
The caller supplies an explicit timezone-aware as_of with a finite,
non-negative maximum age. A readiness result without this gate does not
assert calibration freshness. This function never submits provider work.
probe_aggregator_provider_capability(*, aggregator, provider, metadata_probe, ir_format=None, route_id=None, min_qubits=None, max_calibration_age_seconds=None, as_of=None)
¶
Resolve and assess metadata without submission, with optional freshness gate.
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.
__post_init__()
¶
Validate route identifiers and freeze normalized note metadata.
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
¶
Declared route capabilities used for fail-fast workload admission.
Parameters¶
supports_shots Whether the route admits sampled requests. supports_counts Whether a legacy count summary is available; this does not identify the native photonic, analog or annealing output domain. supports_statevector Whether the route declares statevector output support. supports_mid_circuit_measurement Whether the route declares intermediate measurement support. supports_analog Whether the route declares analog programme support. supports_pulse Whether the route declares pulse programme support. max_qubits Optional positive declared width capacity. supports_cancellation Whether cancellation can be requested from the adapter. supports_cost_estimate Whether the route supplies a cost estimate. max_shots Optional positive integral per-workload sample limit, never a boolean. This keyword-only extension is a declaration, not observed provider capacity; configured live capability gates remain independent.
__post_init__()
¶
Validate declared width and the optional exact integral shot limit.
BackendProfile
dataclass
¶
Static profile for a concrete provider, broker, or simulator route.
QuantumWorkload
dataclass
¶
Provider-neutral workload handed to an injected backend adapter.
Parameters¶
workload_id Stable workload identifier. ir_format Programme representation accepted by the selected route. program Non-empty encoded programme. n_qubits Positive integral logical width, never a boolean or float. For a typed non-gate companion this is the native mode, site or variable count, without inferring an equivalent number of qubits. shots Positive requested sample count as an integer, never a boolean or float. metadata Application-specific JSON-scalar annotations. Adapter-owned submission keys are reserved: approval_id, provider_job_id, execution_mode, backend_name, quantum_computer, ir_format, n_qubits, shots, target, workload_id and broker. Use typed workload fields and adapter arguments for these settings, not annotations. semantics Optional keyword-only versioned native sampling or modality contract. It must bind the exact original programme digest and width. Native source, measurement map, shared parameters and target pins remain separate from the existing semantic-source projection.
Raises¶
ValueError If fields are invalid or metadata shadows a reserved submission key.
__post_init__()
¶
Validate workload identity, program, resources, and metadata.
QuantumJobRef
dataclass
¶
Stable handle retaining the exact admitted native submission.
Parameters¶
job_id Original provider or local durable job identifier. backend_id Exact registered backend identity. workload_id Exact original workload identity. status Observed lifecycle annotation; recovered annotations do not replace adapter-retained submission settings. metadata Detached immutable scalar annotations. submission Optional keyword-only native source and target contract, preserving requested/effective shots and compilation provenance. It does not imply physical execution or replace the existing handle projection.
QuantumJobResult
dataclass
¶
Retain a legacy count summary and optional typed native observation.
Parameters¶
job Retained submission handle whose native request must match the observation. status Observed result lifecycle annotation. counts Detached immutable legacy label-to-integral-count summary. For non-gate outputs this is a compatibility view, without inferring qubit readout from photonic occupations, analog sites or annealing variables. shots Nonnegative integral observed sample total, never a boolean or float. Positive totals equal the count sum. Zero retains the existing legacy unknown-total convention; captured native observations conserve shots. metadata Detached immutable scalar result annotations. provider_observation Optional keyword-only gate, photonic, analog or annealing evidence. Preserves native register bytes, occupations, ordered site samples, spin/binary domains or structured annealing records as applicable. Its request, shots and compatibility counts must match the stored submission and returned result. No hardware attestation is inferred.
Raises¶
ValueError If identity, count conservation or the native observation disagrees.
__post_init__()
¶
Validate result counts and freeze result custody.
QuantumBackend
¶
Bases: Protocol
Runtime protocol for injected provider adapters.
LocalDeterministicSimulator
¶
Offline simulator adapter used to verify the HAL execution contract.
__init__(profile)
¶
Bind a non-cloud profile to an isolated local job store.
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)
¶
Preserve an already completed result when cancellation arrives late.
HardwareAbstractionLayer
¶
Profile registry plus approval-gated execution router.
__init__(profiles, *, operator_policy=None)
¶
Register profiles and immutable policy without creating provider adapters.
Parameters¶
profiles Unique source-owned route declarations. operator_policy Trusted immutable plan ceilings. When configured, every submit requires a bound request and a fresh policy verdict. Unconfigured legacy interactive callers retain their original approval rules.
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.
assess_operator_policy(backend_id, workload, request, *, estimate=None, now=None)
¶
Inspect configured plan admission without invoking an adapter.
Parameters¶
backend_id, workload Exact original route and request to be assessed. request Immutable operational plan bound to the original workload. estimate Dated supplied price for this complete plan, or unknown. now Explicit UTC seconds for offline inspection; submit never accepts this clock.
Returns¶
OperatorPolicyDecision Source-owned verdict with unchanged values and explicit refusals.
Raises¶
PermissionError If no trusted operator policy is configured. ValueError If original HAL workload admission fails.
submit(backend_id, workload, *, approval_id=None, operator_request=None, pricing_estimate=None)
¶
Submit a workload and verify the returned route and workload identity.
Parameters¶
backend_id Registered route selected by the caller. workload Validated programme and requested resources. approval_id Explicit approval required by cloud profiles. operator_request Exact declared plan required by a configured operator policy. Historical verdicts and imported decisions cannot authorise this call. pricing_estimate Dated complete-plan price input. Unknown or stale price refuses configured cost admission before adapter transport.
Returns¶
QuantumJobRef Adapter handle bound to the requested route and workload.
Raises¶
PermissionError If the adapter or required approval is absent. ValueError If workload admission fails or the returned identity differs.
Notes¶
Identity rejection occurs after submission and does not undo it. Do not automatically retry; reconcile the provider operation before resubmitting.
status(job)
¶
Return current status by delegating to the owning adapter.
result(job)
¶
Return unmodified adapter evidence for the requested job identity.
Parameters¶
job Original or recovered handle identifying the job and workload.
Returns¶
QuantumJobResult Adapter result with matching job, backend and workload identifiers. Status and metadata may reflect later lifecycle observations.
Raises¶
ValueError If the adapter returns evidence for a different identity.
cancel(job)
¶
Request cancellation and verify the response job identity.
Parameters¶
job Handle for the job whose cancellation is requested.
Returns¶
QuantumJobRef Adapter response preserving all three identity fields. Its status is not promoted to confirmed cancellation by the router.
Raises¶
ValueError If cancellation is unsupported or the response identity differs.
Notes¶
A rejected response does not undo the provider cancellation request.
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
¶
Execute native Qiskit sampling on the selected Aer-compatible backend.
Parameters¶
profile Built-in local Qiskit Aer route. backend Optional native-compatible backend retained independently of truthiness. Absence selects the default native Aer simulator.
submit(workload, *, approval_id=None)
¶
Bind and compile a copy for the exact native target before execution.
Parameters¶
workload Original QPY or OpenQASM with an optional native sampling companion. approval_id Unused for local simulator execution.
Returns¶
QuantumJobRef Completed stored handle preserving the original payload and captured requested/effective settings, including targeted compilation digest.
Raises¶
ValueError If source, target, static subset, bindings or provider counts disagree.
status(job)
¶
Return the retained terminal state after checking durable identity.
Parameters¶
job Original or recovered handle for the stored backend and workload.
Returns¶
str Completed state of the retained local execution.
Raises¶
KeyError If the job is unknown. ValueError If backend or workload identity differs.
result(job)
¶
Return the same validated result without rewriting prior evidence.
Parameters¶
job Handle matching the exact stored submission identity.
Returns¶
QuantumJobResult Retained immutable counts and optional native measurement observation.
Raises¶
KeyError If the job is unknown. ValueError If backend or workload identity differs.
cancel(job)
¶
Preserve terminal local evidence when cancellation arrives late.
Parameters¶
job Handle matching the original stored submission identity.
Returns¶
QuantumJobRef Retained completed handle without changing source or raw evidence.
Raises¶
KeyError If the job is unknown. ValueError If backend or workload identity differs.
QiskitRuntimeHALAdapter
¶
Submit one native Qiskit circuit through the configured Runtime sampler.
Parameters¶
profile
IBM Quantum route whose resource and IR admission is enforced.
backend
Exact native backend used for target admission and captured compilation.
sampler_factory
Optional native sampler constructor receiving this backend as mode.
An injected callable is retained independently of truthiness.
timeout_s
Provider result-retrieval timeout in seconds, default 600. Native local
PrimitiveJob retrieval uses its supported no-timeout signature.
capability_probe
Optional no-submit probe paired with a calibration age limit.
max_calibration_age_seconds
Finite nonnegative calibration age limit in seconds, paired with the probe.
submit(workload, *, approval_id=None)
¶
Admit source, target and native sample buffers before constructing a sampler.
Parameters¶
workload Original QPY or bound OpenQASM source and optional static sampling contract. Shared free parameters require QPY and original bindings. approval_id Required caller authorization stored with the submitted job.
Returns¶
QuantumJobRef Submitted handle retaining source, target, exact shot settings and targeted compilation digest when capture was requested.
Raises¶
PermissionError If approval is absent. ValueError If source, target, bindings, profile or live metadata disagree. MemoryError If declared native register buffers exceed the active byte budget. This admission is a snapshot, not a memory reservation or whole-process allocation guarantee.
status(job)
¶
Read provider lifecycle after checking the exact retained job identity.
Parameters¶
job Original or recovered handle with unchanged durable identity.
Returns¶
str Canonical provider lifecycle, or completed for a retained result.
Raises¶
KeyError If the job is unknown. ValueError If backend or workload identity differs.
result(job)
¶
Return evidence decoded against the stored submission settings.
Parameters¶
job Original or recovered handle. Its backend and workload identity must match a submission retained by this adapter.
Returns¶
QuantumJobResult
Result using stored shot and provenance metadata, including when
a recovered handle has different lifecycle annotations. Captured
sampling requires exactly one actual native SamplerPubResult;
its ordered uint8 packed register arrays and native joint counts
remain separate from the legacy summary. Packed arrays have shape
(shots, ceil(register_bits / 8)) without parameter broadcasting.
Raises¶
KeyError If this adapter has no retained submission for the job. ValueError If identity, PUB cardinality or counts violate stored settings. TypeError If captured register channels are not actual native BitArrays. MemoryError If native packed buffers exceed the active byte budget before copying.
cancel(job)
¶
Request cancellation without replacing stored submission metadata.
Parameters¶
job Handle with the same durable identity as the stored submission.
Returns¶
QuantumJobRef Updated lifecycle handle retaining original submission metadata.
Raises¶
KeyError If no submission is retained by this adapter. ValueError If the supplied identity differs from the stored identity.
qiskit_circuit_to_workload(circuit, *, workload_id, shots, metadata=None, capture_semantics=False, requested_target=None, parameter_bindings=None)
¶
Encode the unchanged native source with an optional QPY sampling contract.
Parameters¶
circuit
Original Qiskit circuit. QPY retains actual shared Parameter UUIDs.
workload_id
Stable caller identity for this encoded source.
shots
Positive integral number of samples, conserved by result decoding.
metadata
Caller scalar annotations separate from execution settings.
capture_semantics
Capture source digest, final measurement map, register order and native
parameter uses. Default false preserves the legacy workload contract.
requested_target
Optional exact native backend name, admitted before execution. Requires
capture; no implicit replacement device is allowed.
parameter_bindings
Finite real values keyed by actual original native Parameter objects.
Requires capture. Values are applied to a copy at submission; the original
shared parameter identities and source QPY are retained unchanged.
Returns¶
QuantumWorkload Original base64 QPY with an independent versioned sampling companion.
Raises¶
TypeError If the input is not a native Qiskit circuit. ValueError If settings require capture, bindings are invalid, or the circuit is outside the supported static final-measurement subset.
qiskit_circuit_to_qasm3_workload(circuit, *, workload_id, shots, metadata=None, capture_semantics=False, requested_target=None)
¶
Encode OpenQASM 3 and optionally capture fully bound static sampling.
Parameters¶
circuit
Original native circuit. Captured sampling requires no free parameters,
because OpenQASM does not preserve original native Parameter UUIDs.
workload_id
Stable caller identity for the original exported source.
shots
Positive integral number of samples, conserved by result decoding.
metadata
Caller scalar annotations separate from execution settings.
capture_semantics
Capture source digest, static measurement map and register order.
Default false preserves existing OpenQASM payload construction.
requested_target
Optional exact native backend name. Requires capture and is checked
against the selected backend before native transport execution.
Returns¶
QuantumWorkload Original OpenQASM text and optional independent sampling companion.
Raises¶
TypeError If the input is not a native Qiskit circuit. ValueError If a target requires capture, the circuit is outside the static subset, or capture would lose original free-parameter identity. Use QPY and its original native parameter bindings for the latter case.
scpn_quantum_control.hardware.hal_braket
¶
Amazon Braket adapters for :mod:scpn_quantum_control.hardware.hal.
BraketLocalHALAdapter
¶
Execute native Braket workloads on the selected local simulator.
Parameters¶
profile Built-in statevector or density-matrix Braket profile. device Optional native-compatible transport. An injected object is retained regardless of its truth value; absence selects the profile's simulator.
submit(workload, *, approval_id=None)
¶
Validate and execute one native workload without implicit target changes.
Parameters¶
workload Original OpenQASM and optional captured static measurement contract. approval_id Unused for local simulator execution.
Returns¶
QuantumJobRef Completed handle with stored submission settings and raw count observation when capture was requested.
Raises¶
ValueError If source, profile, target, bindings or provider counts are invalid.
status(job)
¶
result(job)
¶
Return immutable captured output or the legacy count result.
Parameters¶
job Handle matching the original stored submission identity.
Returns¶
QuantumJobResult Previously validated result; repeated calls retain the same object.
Raises¶
KeyError If the job is unknown. ValueError If backend or workload identity differs.
cancel(job)
¶
Preserve terminal local evidence when cancellation arrives late.
Parameters¶
job Handle matching the original stored submission identity.
Returns¶
QuantumJobRef Stored completed handle without changing source or raw evidence.
Raises¶
KeyError If the job is unknown. ValueError If backend or workload identity differs.
BraketAwsHALAdapter
¶
Submit native Braket circuits through an explicitly configured AWS device.
Parameters¶
profile AWS Braket gate-model route whose resource and IR limits are enforced. device Optional injected native-compatible device, retained even when falsey. device_arn Explicit ARN required when a device is not injected. device_factory Optional constructor receiving the exact configured ARN. capability_probe Optional no-submit metadata probe paired with a calibration age limit. max_calibration_age_seconds Finite nonnegative age limit in seconds, paired with the probe.
submit(workload, *, approval_id=None)
¶
Submit once after approval and native source/target admission.
Parameters¶
workload Original OpenQASM and optional static gate-model companion. approval_id Required caller authorization recorded with the submitted job.
Returns¶
QuantumJobRef Submitted handle retaining the original payload, requested and effective shots, native target and compiled payload digest.
Raises¶
PermissionError If approval is absent. ValueError If source, target, bindings, resource limits or metadata disagree.
status(job)
¶
Read provider lifecycle after checking stored submission identity.
Parameters¶
job Original or recovered handle with unchanged durable identity.
Returns¶
str Canonical provider state, or completed when a result is retained.
Raises¶
KeyError If the job is unknown. ValueError If backend or workload identity differs.
result(job)
¶
Return evidence decoded against the stored submission settings.
Parameters¶
job Original or recovered handle. Its backend and workload identity must match a submission retained by this adapter.
Returns¶
QuantumJobResult Result using stored shot and provenance metadata, including when a recovered handle has different lifecycle annotations.
Raises¶
KeyError If this adapter has no retained submission for the job. ValueError If identity differs or provider counts violate stored settings.
cancel(job)
¶
Request cancellation without replacing stored submission metadata.
Parameters¶
job Handle with the same durable identity as the stored submission.
Returns¶
QuantumJobRef Updated lifecycle handle retaining original submission metadata.
Raises¶
KeyError If no submission is retained by this adapter. ValueError If the supplied identity differs from the stored identity.
braket_circuit_to_workload(circuit, *, workload_id, shots, metadata=None, capture_semantics=False, requested_target=None, parameter_bindings=None)
¶
Encode the original native circuit and optional static sampling contract.
Parameters¶
circuit
Native Braket Circuit. Shared free symbols retain their original
OpenQASM names; this function does not bind or execute the circuit.
workload_id
Stable caller identity for the unchanged source payload.
shots
Positive integral number of samples, conserved by result decoding.
metadata
Caller annotations separate from source and execution settings.
capture_semantics
Capture static final measurement order, shared symbol uses and the
SHA-256 of the original OpenQASM. Default false preserves legacy output.
requested_target
Optional exact native device name. Requires capture and must equal
the selected device's name before its run method is called.
parameter_bindings
Finite real values keyed by original native free-symbol names.
Requires capture; submission requires every original free symbol.
Returns¶
QuantumWorkload Original OpenQASM with a separate versioned companion when requested. Native measured-qubit order uses the leftmost count bit first; no logical qubit permutation or count reversal is performed here.
Raises¶
TypeError If the source is not a native Braket circuit. ValueError If settings require capture, bindings are invalid, or a gate follows final measurement in the admitted static sampling subset.
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)
¶
Preserve terminal local evidence when cancellation arrives late.
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
¶
Retain synchronous native annealing outputs separately from binary projections.
Parameters¶
profile D-Wave route declaring supported IR and resource limits. sampler Optional explicitly supplied native-compatible sampler. Its truth value does not change admission or select a default route. sampler_factory Optional lazy native-compatible sampler constructor, retained after its first successful construction. Absence uses the optional SDK. bqm_factory Optional constructor receiving each current original admitted plan. Absence uses the optional dimod BQM constructor. solver Declared adapter selector; absent means default, malformed names refuse. The selector itself does not attest a native or physical solver identity.
Raises¶
ValueError If profile or explicit selector is invalid.
submit(workload, *, approval_id=None)
¶
Admit original source, native variable domain and selector before sampling.
Parameters¶
workload Original supported BQM plan and optional source-bound companion. approval_id Required caller authorization for synchronous submission.
Returns¶
QuantumJobRef Completed handle retaining the original model and requested reads. A captured result keeps actual returned columns, SPIN/BINARY values, energies and structured-record bytes separately from legacy counts. Native model construction belongs to the supplied or SDK constructor; no compiled digest or physical execution claim is fabricated.
Raises¶
PermissionError If caller approval is absent. ValueError If profile, source, native domain/order, selector, provider identity, record layout, sample values or exact occurrence totals disagree. TypeError If the selected sampler lacks callable sample retrieval. RuntimeError If the configured native builder requires an unavailable SDK.
status(job)
¶
Read the retained synchronous lifecycle after validating durable identity.
Parameters¶
job Handle matching the original stored backend and workload.
Returns¶
str Stored completed status, or the legacy cancellation annotation.
Raises¶
KeyError If original submission is unavailable. ValueError If durable backend or workload identity differs.
result(job)
¶
Retrieve the original retained result without rerunning an annealing model.
Parameters¶
job Handle matching the original stored backend and workload.
Returns¶
QuantumJobResult Original immutable compatibility histogram and optional typed observation. Returned native variable order and SPIN -1 values survive; missing energies remain unknown. Structured bytes retain the original dtype descriptor, shape and extra native fields.
Raises¶
KeyError If original submission or retained completed result is unavailable. ValueError If durable identity differs.
cancel(job)
¶
Retain a legacy cancellation annotation without erasing completed samples.
Parameters¶
job Handle matching the original stored backend and workload.
Returns¶
QuantumJobRef Original handle with cancelled lifecycle annotation and preserved companion. Synchronous samples remain retrievable; the annotation does not attest a physical provider cancellation.
Raises¶
KeyError If original submission is unavailable. ValueError If durable identity differs.
dwave_bqm_workload(*, linear, quadratic, workload_id, n_variables, reads, offset=0.0, vartype='BINARY', metadata=None, schema=DWAVE_BQM_SCHEMA, capture_semantics=False, requested_target=None)
¶
Encode the original Ising/QUBO plan and optional native annealing companion.
Parameters¶
linear Finite biases keyed by every original variable label. quadratic Finite pair biases whose distinct endpoints belong to the same model. workload_id Stable caller identity for the original model. n_variables Declared native variable count. The legacy HAL width field does not reinterpret annealing variables as gate-model qubits. reads Positive integral requested occurrence total. offset Finite native model energy offset. vartype Original BINARY or SPIN domain, canonicalized to its uppercase name. metadata Caller annotations separate from source and execution settings. schema Supported original BQM plan version. capture_semantics Add a versioned source digest, original encoded variable order and native domain without changing the existing JSON codec. requested_target Optional exact declared adapter selector, requiring native capture. A selector name does not attest a physical solver.
Returns¶
QuantumWorkload Existing canonical BQM JSON plan, whose variables retain the original builder's sorted order, and optional native companion.
Raises¶
ValueError If schema, variables, pair endpoints, finite biases, native domain, resource settings or target admission are invalid.
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 evidence decoded against the stored submission settings.
Parameters¶
job Original or recovered handle. Its backend and workload identity must match a submission retained by this adapter.
Returns¶
QuantumJobResult Result using stored shot and provenance metadata, including when a recovered handle has different lifecycle annotations.
Raises¶
KeyError If this adapter has no retained submission for the job. ValueError If identity differs or provider counts violate stored settings.
cancel(job)
¶
Request cancellation without replacing stored submission metadata.
Parameters¶
job Handle with the same durable identity as the stored submission.
Returns¶
QuantumJobRef Updated lifecycle handle retaining original submission metadata.
Raises¶
KeyError If no submission is retained by this adapter. ValueError If the supplied identity differs from the stored identity.
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
¶
Execute original QPY through an explicitly configured IQM-compatible client.
Parameters¶
profile IQM Cloud route with declared resource and IR admission. backend Optional injected native-compatible backend. Absence uses the explicit server URL; decoded source and bindings qualify before loading a client. server_url Required configured IQM endpoint when no backend is injected. quantum_computer Optional configured native computer selector, recorded separately from the actual backend name used for target admission. import_module Lazy SDK importer; this adapter never installs an optional dependency. timeout_s Positive provider result-retrieval timeout in seconds, default 600. optimisation_level Qiskit target-compilation level, one of 0, 1, 2 or 3. compile_circuit Compile for the selected native target when true. False retains an explicit caller-precompiled boundary without claiming target compilation.
submit(workload, *, approval_id=None)
¶
Admit original source and bindings before client construction or execution.
Parameters¶
workload Original QPY and optional static native request. Metadata cannot replace source, target, shot settings or adapter-owned fields. approval_id Required caller authorization stored with the submitted job.
Returns¶
QuantumJobRef Submitted handle preserving original payload, shared identities, requested/effective shots and actual target. Captured compilation has a digest; caller-precompiled mode is labelled separately.
Raises¶
PermissionError If approval is absent. ValueError If profile, source, IR, bindings or selected target disagree. IQMTargetCompilationError If target compilation fails; the original cause remains available and no target-free retry or provider run follows. ImportError If lazy optional IQM SDK loading fails.
status(job)
¶
Read native provider lifecycle after checking stored submission identity.
Parameters¶
job Original or recovered handle for the same backend and workload.
Returns¶
str Canonical provider lifecycle or unknown when no state is exposed.
Raises¶
KeyError If the submission or retained provider job is unavailable. ValueError If durable identity differs from the stored submission.
result(job)
¶
Retain native count labels against the original stored sampling request.
Parameters¶
job Original or recovered handle with unchanged durable identity.
Returns¶
QuantumJobResult Immutable counts and optional native gate-model observation using stored source, measurement order and exact shot settings. Repeated successful retrieval returns the same retained result.
Raises¶
KeyError If submission or retained transport is unavailable. ValueError If identity, count labels or native shot conservation disagree. TypeError If the provider lacks result retrieval or returns an invalid channel. RuntimeError If a single-circuit result has no usable count map or several maps.
cancel(job)
¶
Request provider cancellation while retaining the original native contract.
Parameters¶
job Handle with the exact backend and workload identity of the stored job.
Returns¶
QuantumJobRef Cancellation-request handle retaining original metadata and optional submission companion. This legacy lifecycle annotation does not attest that the physical provider cancelled the work.
Raises¶
KeyError If the original submission or retained provider job is unavailable. ValueError If identity differs or the provider has no cancellation operation.
iqm_qiskit_workload(circuit, *, workload_id, shots, metadata=None, capture_semantics=False, requested_target=None, parameter_bindings=None)
¶
Encode unchanged native QPY and an optional IQM sampling contract.
Parameters¶
circuit Original Qiskit circuit, retaining native shared parameter UUIDs in QPY. workload_id Stable caller identity for the original encoded source. shots Positive integral requested sample total. metadata Scalar annotations separate from source and execution settings. capture_semantics Capture static measurement map, register order, original parameter uses and source digest. Default false preserves legacy construction. requested_target Optional exact native backend name, requiring capture. parameter_bindings Finite real values keyed by actual original native Parameters, requiring capture. Submission requires every free parameter and binds a copy.
Returns¶
QuantumWorkload Original QPY and optional separate versioned sampling companion.
Raises¶
TypeError If the source is not a native Qiskit circuit. ValueError If capture, static-subset, source or binding admission fails.
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
¶
Submit original native analog plans through an explicitly configured client.
Parameters¶
profile Pasqal route declaring supported IR and resource limits. client Optional injected native-compatible client. Each submission receives its current original decoded sequence and exact requested shots. client_factory Optional lazy construction from the first admitted original sequence. The retained client receives subsequent current sequences directly. target Declared adapter selector. Absence means injected; present malformed selectors refuse. This name does not attest an SDK or physical target.
Raises¶
ValueError If profile or explicit selector is invalid.
submit(workload, *, approval_id=None)
¶
Admit source, native site order and target before client construction.
Parameters¶
workload Original supported Pulser plan and optional source-bound companion. approval_id Required caller authorization for submission.
Returns¶
QuantumJobRef Stored handle preserving original source, exact sampling settings and declared selector provenance. Native compilation remains owned by the configured client, with no fabricated compiled-program digest.
Raises¶
PermissionError If caller approval is absent. ValueError If profile, source, IR, native axes or selected target disagrees. RuntimeError If no calibrated client builder is available.
status(job)
¶
Read native lifecycle after checking original stored submission identity.
Parameters¶
job Original or recovered handle for the same backend and workload.
Returns¶
str Canonical native provider lifecycle, or unknown when absent.
Raises¶
KeyError If original submission or retained provider job is unavailable. ValueError If durable identity differs.
result(job)
¶
Retain native counts against original site order and exact requested shots.
Parameters¶
job Handle matching the original stored backend and workload.
Returns¶
QuantumJobResult Immutable compatibility histogram and optional analog observation retaining original count labels and native register order. Readout polarity and atom-loss interpretation remain unknown. Repeated successful retrieval returns the same result without rereading.
Raises¶
KeyError If original submission or retained provider job is unavailable. ValueError If identity, native labels, values, width or shot conservation fails. TypeError If the retained provider job lacks result retrieval. RuntimeError If the provider has no supported count channel.
cancel(job)
¶
Request cancellation while preserving native source and completed raw data.
Parameters¶
job Handle matching the original stored backend and workload.
Returns¶
QuantumJobRef Legacy cancellation-request annotation with original metadata and companion. It does not attest physical provider cancellation.
Raises¶
KeyError If original submission or retained provider job is unavailable. ValueError If durable identity differs or cancellation is unsupported.
pulser_sequence_workload(payload, *, workload_id, n_qubits, shots, metadata=None, capture_semantics=False, requested_target=None)
¶
Encode original Pulser sites and an optional native analog request companion.
Parameters¶
payload Plan mapping or JSON object containing an ordered site register, finite coordinates and schedules, a positive duration and declared channel. Captured JSON strings retain exact original bytes and site insertion order. workload_id Stable caller identity for the original plan. n_qubits Legacy field containing declared native site count. Native analog sites do not imply gate-model qubits or a particular readout polarity. shots Positive integral requested sample count. metadata Scalar caller annotations separate from execution settings. capture_semantics Retain a separate original source digest and native register order. Default false preserves the existing workload codec. requested_target Optional exact declared client selector, requiring native capture.
Returns¶
QuantumWorkload Original Pulser plan and optional versioned analog companion.
Raises¶
ValueError If plan structure, native values, site count or target admission fails.
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 evidence decoded against the stored submission settings.
Parameters¶
job Original or recovered handle. Its backend and workload identity must match a submission retained by this adapter.
Returns¶
QuantumJobResult Result using stored shot and provenance metadata, including when a recovered handle has different lifecycle annotations.
Raises¶
KeyError If this adapter has no retained submission for the job. ValueError If identity differs or provider counts violate stored settings.
cancel(job)
¶
Request cancellation without replacing stored submission metadata.
Parameters¶
job Handle with the same durable identity as the stored submission.
Returns¶
QuantumJobRef Updated lifecycle handle retaining original submission metadata.
Raises¶
KeyError If no submission is retained by this adapter. ValueError If the supplied identity differs from the stored identity.
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 evidence decoded against the stored submission settings.
Parameters¶
job Original or recovered handle. Its backend and workload identity must match a submission retained by this adapter.
Returns¶
QuantumJobResult Result using stored shot and provenance metadata, including when a recovered handle has different lifecycle annotations.
Raises¶
KeyError If this adapter has no retained submission for the job. ValueError If identity differs or provider counts violate stored settings.
cancel(job)
¶
Request cancellation without replacing stored submission metadata.
Parameters¶
job Handle with the same durable identity as the stored submission.
Returns¶
QuantumJobRef Updated lifecycle handle retaining original submission metadata.
Raises¶
KeyError If no submission is retained by this adapter. ValueError If the supplied identity differs from the stored identity.
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
¶
Sample declared photonic plans through an explicit native-compatible processor.
Parameters¶
profile Quandela route declaring supported IR and resource limits. processor Optional prepared opaque processor. Native capture requires its exact original source digest and records caller-precompiled provenance. processor_factory Optional builder receiving each separately admitted original plan. sampler_factory Optional sampler construction for the selected processor. Its samples operation receives the exact requested count. target Declared adapter selector. Absence means injected; a present malformed name refuses. This selector does not attest an SDK or physical device. prepared_program_sha256 Exact original plan digest for captured execution with a prepared processor.
Raises¶
ValueError If profile or explicit target selector is invalid.
submit(workload, *, approval_id=None)
¶
Admit native source and target before building and sampling the processor.
Parameters¶
workload Original supported photonic plan with optional source-bound companion. approval_id Required caller authorization for sampling.
Returns¶
QuantumJobRef Completed synchronous job preserving exact source, sample settings and selector provenance. Native occupations may exceed one photon; they are retained as typed photonic samples and original labels.
Raises¶
PermissionError If caller approval is absent. ValueError If profile, source, IR, target, prepared digest or sampling data differs. TypeError If selected processor or sampler lacks its sampling operation. RuntimeError If no calibrated builder exists or the provider has no count channel.
status(job)
¶
Read stored synchronous lifecycle after durable identity admission.
Parameters¶
job Original or recovered handle for the same backend and workload.
Returns¶
str Stored completed or cancellation-request lifecycle annotation.
Raises¶
KeyError If original submission is unavailable. ValueError If durable handle identity differs.
result(job)
¶
Return retained native photonic data against the original stored request.
Parameters¶
job Handle matching the original stored backend and workload.
Returns¶
QuantumJobResult Immutable compatibility count view and optional typed photonic occupation samples with exact original state labels. Repeated retrieval returns the same result without sampling again.
Raises¶
KeyError If the original submission or retained result is unavailable. ValueError If durable handle identity differs.
cancel(job)
¶
Retain a legacy cancellation annotation without discarding sampled data.
Parameters¶
job Handle matching the original stored backend and workload.
Returns¶
QuantumJobRef Cancellation annotation retaining original source and companion. Sampling is synchronous; this does not attest physical cancellation.
Raises¶
KeyError If original submission is unavailable. ValueError If durable handle identity differs.
quandela_perceval_workload(payload, *, workload_id, n_modes, shots, metadata=None, capture_semantics=False, requested_target=None)
¶
Encode original photonic mode order and an optional native request companion.
Parameters¶
payload Photonic plan mapping or JSON object with mode count, nonnegative input occupations, supported components and optional postselection. Captured JSON strings retain exact bytes; mappings retain original component order. workload_id Stable caller identity for the original plan. n_modes Positive native mode count stored in the legacy n_qubits field. Modes and photon occupations do not imply a binary gate-model register. shots Positive integral requested number of observations. metadata Scalar caller annotations separate from provider settings. capture_semantics Retain original source digest and ordered native mode identities. Default false preserves legacy plan construction. requested_target Optional exact declared processor selector, requiring native capture.
Returns¶
QuantumWorkload Original photonic plan and optional independent versioned companion.
Raises¶
ValueError If native plan structure, values, mode count or target admission fails.
scpn_quantum_control.hardware.hal_quera_bloqade
¶
QuEra Bloqade adapter for :mod:scpn_quantum_control.hardware.hal.
QuEraBloqadeHALAdapter
¶
Execute declared Bloqade plans through an explicit native-compatible routine.
Parameters¶
profile QuEra route declaring supported IR and resource limits. routine Optional already prepared routine. Captured submission requires its exact original plan digest; opaque routines have caller provenance. routine_name Declared route selector, default injected only when absent. This name is an adapter selector and does not attest an SDK or physical device. routine_factory Optional builder called separately with each admitted original workload. Explicit callable objects are retained irrespective of truth value. prepared_program_sha256 Exact source digest for a captured plan using an injected routine.
Raises¶
ValueError If profile, route configuration or explicit selector is invalid.
submit(workload, *, approval_id=None)
¶
Admit original source, ordered sites and target before building a routine.
Parameters¶
workload Original supported AHS plan with optional native analog companion. approval_id Required caller authorization for submission.
Returns¶
QuantumJobRef Stored job retaining source, exact sampling settings and selector provenance. No gate measurement map or physical calibration is inferred.
Raises¶
PermissionError If caller approval is absent. ValueError If profile, source, IR, native axes, target or prepared digest disagrees. RuntimeError If automatic construction lacks a calibrated provider builder.
status(job)
¶
Retrieve provider lifecycle after checking the original stored identity.
Parameters¶
job Original or recovered handle for the same backend and workload.
Returns¶
str Canonical native lifecycle, optionally obtained after provider fetch.
Raises¶
KeyError If the stored submission or batch is unavailable. ValueError If durable handle identity disagrees.
result(job)
¶
Retain unchanged native readouts and exact sampling conservation.
Parameters¶
job Handle matching the original stored backend and workload.
Returns¶
QuantumJobResult Immutable compatibility histogram and optional analog observation retaining native site order, counts or ordered per-shot samples. Atom-loss interpretation and readout polarity remain unknown. Repeated successful retrieval returns the same stored result.
Raises¶
KeyError If original submission or retained batch is unavailable. ValueError If identity, channel, native values, sample width or shot total fails.
cancel(job)
¶
Request cancellation while retaining source and completed raw evidence.
Parameters¶
job Handle matching the original stored backend and workload.
Returns¶
QuantumJobRef Legacy cancellation annotation preserving the native submission. Missing provider cancel remains supported; this annotation does not attest physical provider cancellation.
Raises¶
KeyError If original submission or batch is unavailable. ValueError If durable handle identity differs.
bloqade_ahs_workload(payload, *, workload_id, n_qubits, shots, metadata=None, capture_semantics=False, requested_target=None)
¶
Encode original ordered sites and an optional analog request companion.
Parameters¶
payload AHS plan mapping or JSON object with ordered atom indices, positions, finite amplitude/phase schedules and positive duration. Captured JSON strings retain their exact original bytes; mappings retain site order. workload_id Stable caller identity for this original plan. n_qubits Legacy field containing the declared native site count. It does not infer gate-model qubits or readout polarity. shots Positive integral number of native samples. metadata Scalar caller annotations separate from execution settings. capture_semantics Retain an independent source digest and original native site order. Default false preserves the legacy workload codec. requested_target Optional exact declared routine selector, requiring native capture.
Returns¶
QuantumWorkload Original Bloqade plan and optional versioned analog companion.
Raises¶
ValueError If plan structure, native values, site count or target admission fails.
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.
Parameters¶
n_qubits : int Number of qubits in the circuit. fidelity_threshold : float Minimum acceptable estimated fidelity, strictly between zero and one. max_depth : int Largest depth considered by the binary search and fidelity sampling. t1_us : float Qubit relaxation time in microseconds, reported with the result. t2_us : float Qubit dephasing time in microseconds. cz_error : float Error probability for each two-qubit gate. readout_error : float Error probability for each measured qubit. two_qubit_fraction : float Fraction of layers containing two-qubit gates.
Returns¶
dict[str, Any] Budget depth, fidelity at that depth, sampled fidelity curve, and hardware parameters.
Raises¶
ValueError
If n_qubits is less than one or fidelity_threshold is outside
the open interval (0, 1).
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¶
depth : int Total number of gate layers. n_qubits : int Number of qubits in the circuit. t1_us : float Qubit relaxation time in microseconds, retained in the public hardware parameter contract. t2_us : float Qubit dephasing time in microseconds. cz_error : float Error probability for each two-qubit gate. readout_error : float Error probability for each measured qubit. two_qubit_fraction : float Fraction of layers containing two-qubit gates.
Returns¶
float
Estimated fidelity in the interval [0, 1].
Raises¶
ValueError
If depth is negative or n_qubits is less than one.
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
¶
Six-layer, 18-oscillator Arcane Sapience identity binding 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': ['working_style_action_verification', 'working_style_delivery_preflight', 'working_style_single_task'], '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 = {'working_style_action_verification': ['ws_action_first', 'ws_verify_before_claim'], 'working_style_delivery_preflight': ['ws_commit_incremental', 'ws_preflight_push'], 'working_style_single_task': ['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 an identity attractor from a binding specification.
Parameters¶
spec : dict[str, Any] or None
Binding specification. None selects ARCANE_SAPIENCE_SPEC.
ansatz_reps : int
Repetition count for the attractor ansatz.
Returns¶
IdentityAttractor Attractor compiled from the specification's coupling and frequency data.
Raises¶
ValueError If the specification uses the stale abbreviated working-style IDs.
solve_identity(spec=None, maxiter=200, seed=None)
¶
quantum_to_orchestrator_phases(quantum_theta, spec=None)
¶
Map reduced quantum phases to orchestrator oscillator phases.
Each quantum oscillator's phase is broadcast to its orchestrator sub-group.
Parameters¶
quantum_theta : NDArray[np.float64]
One phase per reduced oscillator, in specification order.
spec : dict[str, Any] or None
Binding specification. None selects ARCANE_SAPIENCE_SPEC.
Returns¶
dict[str, float] Orchestrator oscillator ID to phase mapping for domainpack injection.
Raises¶
ValueError If the specification uses stale abbreviated working-style IDs or the phase vector length differs from the reduced oscillator count.
orchestrator_to_quantum_phases(orchestrator_phases, spec=None)
¶
Map orchestrator phases back to reduced quantum oscillator phases.
Each quantum oscillator gets the circular mean of its sub-group phases.
Parameters¶
orchestrator_phases : dict[str, float]
Orchestrator oscillator ID to phase mapping.
spec : dict[str, Any] or None
Binding specification. None selects ARCANE_SAPIENCE_SPEC.
Returns¶
NDArray[np.float64] Circular-mean phase for each reduced oscillator in specification order.
Raises¶
ValueError If the specification uses stale abbreviated working-style IDs.
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. SurfaceCodeUPDE supplies a separate X/Z ancilla-interaction and
resource scaffold, not full protection or decoding. This module validates its
repetition-code approach on statevector and is 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, *, max_dense_gib=None)
¶
Execute one QEC-protected Trotter step and extract syndromes.
The protected circuit carries both data and ancilla qubits, so the dense
state is 2**physical_qubit_count(). Admission is checked before the
circuit is built, so an inadmissible code distance refuses without
entering the allocator. Two complex-vector equivalents cover the state
and the real absolute-value/square buffers used to obtain probabilities.
Parameters¶
dt
Trotter step size.
max_dense_gib
Optional dense-allocation budget in GiB. None uses the active
process budget.
Returns¶
dict Per-oscillator syndromes and the detected-error count.
Raises¶
DenseAllocationError If the physical-qubit statevector exceeds the budget.
physical_qubit_count()
¶
Total physical qubits: n_osc * (d + d - 1).
scpn_quantum_control.qec.surface_code_upde
¶
Build a structural surface-code UPDE circuit and resource scaffold.
Each oscillator occupies a distance-d rotated-surface-code-shaped register (Horsman et al., NJP 14, 123011 (2012)). The generated circuit approximates encoding fan-out, distributed physical rotations, inter-patch couplings, and X/Z ancilla interactions for resource and depth analysis. It does not prepare a verified codespace, measure or reset ancillas, allocate classical syndrome bits, invoke a decoder, or demonstrate correction of either X or Z errors.
Physical qubit layout per oscillator: d² data + (d²-1) ancilla = 2d²-1. Total physical qubits: n_osc × (2d² - 1).
Structural operator proxies
- distribute an Rz angle over every data qubit in one patch;
- distribute pairwise RZZ angles across corresponding qubits in two patches;
- append X- and Z-type ancilla-entangling networks without measurements.
These proxies are not validated fault-tolerant logical gates or lattice-surgery
protocols. Decoding remains a separate responsibility; ControlQEC provides
an independent toric-code MWPM analysis surface rather than consuming these
unmeasured ancillas.
SurfaceCodeSpec
dataclass
¶
Record per-patch rotated-surface-code resource counts.
Parameters¶
distance : int
Odd code distance d.
n_data : int
Number of data qubits, d**2.
n_ancilla : int
Number of ancillas, d**2 - 1.
n_physical : int
Total patch register size, 2*d**2 - 1.
Notes¶
Use :meth:from_distance to enforce the odd-distance invariant and derive
consistent counts. Direct dataclass construction does not revalidate fields.
SurfaceCodeUPDE
¶
Model a surface-code-shaped Kuramoto-XY circuit scaffold.
Parameters¶
n_osc : int
Number of oscillator patches; must be at least two.
code_distance : int, default=3
Odd patch distance, at least three.
K : numpy.ndarray or None, optional
Coupling matrix with expected shape (n_osc, n_osc). The Paper 27
deterministic matrix is built when omitted.
omega : numpy.ndarray or None, optional
Natural-frequency vector with expected length n_osc. The canonical
16-entry table, periodically extended for larger systems, is used when
omitted.
Attributes¶
spec : SurfaceCodeSpec
Per-patch resource counts.
total_qubits : int
Full circuit register size, n_osc * (2*d**2 - 1).
Notes¶
Distributed RZ/RZZ operations and ancilla interactions are structural
operator proxies. The circuit contains no measurements or classical bits
and makes no fault-tolerance claim. Custom K and omega shapes are
consumed by :meth:build_step_circuit without constructor validation.
Representative budgets are 68 qubits for n_osc=4, d=3, 196 for
n_osc=4, d=5, 272 for n_osc=16, d=3, and 784 for
n_osc=16, d=5.
__init__(n_osc, code_distance=3, K=None, omega=None)
¶
Configure the structural circuit and its resource register.
Parameters¶
n_osc : int Number of oscillator patches. code_distance : int, default=3 Odd patch distance, at least three. K : numpy.ndarray or None, optional Coupling matrix used by the pair-interaction loop. omega : numpy.ndarray or None, optional Frequency vector used by patch-local distributed rotations.
Raises¶
ValueError If fewer than two oscillators are requested or the distance is below three or even.
encode_logical(osc, qc)
¶
Append the patch's proxy encoding fan-out network.
Parameters¶
osc : int Oscillator patch whose data block receives the operations. qc : qiskit.QuantumCircuit Circuit owning the full patch register.
Notes¶
The method applies Ry(omega[osc] mod 2*pi) to one representative
qubit followed by row and column CNOT fans. This is a structural circuit
proxy, not verified preparation of a logical |+_L> codespace state.
logical_rz(osc, angle, qc)
¶
Append the distributed physical-RZ operator proxy.
Parameters¶
osc : int
Oscillator patch whose data qubits receive the rotations.
angle : float
Aggregate angle divided evenly over the d**2 data qubits.
qc : qiskit.QuantumCircuit
Circuit to mutate.
Notes¶
Applying Rz(angle / d**2) to every data qubit is a resource-model
proxy; this module does not establish it as a fault-tolerant logical RZ.
logical_zz(osc_i, osc_j, angle, qc)
¶
Append the distributed inter-patch RZZ operator proxy.
Parameters¶
osc_i, osc_j : int Distinct oscillator patches coupled pairwise. angle : float Aggregate angle divided over corresponding data-qubit pairs. qc : qiskit.QuantumCircuit Circuit to mutate.
Notes¶
The pairwise physical RZZ layer is not an ancilla-mediated merge-and-split lattice-surgery protocol and is not claimed to implement a fault-tolerant logical ZZ gate.
x_syndrome_extract(osc, qc)
¶
Append the X-labelled ancilla interaction scaffold.
Parameters¶
osc : int Oscillator patch to address. qc : qiskit.QuantumCircuit Circuit to mutate.
Notes¶
Each ancilla receives Hadamard, four ancilla-to-data CNOTs, and a final Hadamard. No measurement, reset, classical bit, or decoded syndrome is produced.
z_syndrome_extract(osc, qc)
¶
build_step_circuit(dt=0.1)
¶
Build one structural Kuramoto-XY circuit step.
Parameters¶
dt : float, default=0.1 Step multiplier applied to frequencies and nonzero couplings.
Returns¶
qiskit.QuantumCircuit
Unmeasured circuit containing proxy encoding, distributed RZ/RZZ,
and X/Z ancilla-interaction layers on total_qubits qubits.
Notes¶
Couplings with magnitude at most 1e-10 are omitted. The returned
circuit has no classical register and performs no correction cycle.
physical_qubit_budget()
¶
Return the patch-based physical-qubit accounting.
Returns¶
dict[str, int]
Oscillator count, distance, per-patch data/ancilla/physical counts,
total physical count, and the theoretical distance-derived value
(d - 1) // 2 under key correctable_errors.
Notes¶
correctable_errors is a code-distance resource label; this structural
scaffold does not execute or verify that correction capability.
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)
¶
Amplify noise by global unitary folding: G -> G (G^dag G)^((scale-1)/2).
The trailing measurement and barrier instructions are detached before folding and re-attached afterwards at their original qubit and clbit positions, so a partial, permuted or multi-register readout keeps the observable it started with. The returned circuit reuses the input's registers, bits, name, metadata and global phase; only the unitary body is repeated.
Parameters¶
circuit
Circuit whose unitary body is folded. Classical operations may appear
only in the trailing measurement/barrier block; a mid-circuit classical
operation is rejected rather than silently dropped.
scale
Odd positive noise-scale factor. scale=1 returns an unchanged copy;
scale=2k+1 appends k inverse-forward pairs.
Returns¶
qiskit.QuantumCircuit
Folded circuit with the same measurement mapping as circuit.
Raises¶
ValueError
If scale is not an odd positive integer, or if the circuit carries a
classical operation outside its trailing measurement block.
References¶
Giurgica-Tiron et al., "Digital zero noise extrapolation for quantum error mitigation", IEEE QCE 2020.
zne_extrapolate(noise_scales, expectation_values, order=1)
¶
Richardson extrapolation to zero noise.
order controls polynomial degree: 1=linear, 2=quadratic.
Scales must be distinct odd positive integers; booleans, floats and strings
are rejected with ValueError without coercion, as in gate_fold_circuit.
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¶
K : ndarray of float Coupling matrix. omega : ndarray of float Natural frequencies. t_total : float Total evolution time. n_steps : int Number of intermediate time steps to return. initial_state : ndarray of complex, optional Initial statevector. Defaults to the all-zero computational basis state. delta : float XXZ anisotropy parameter. Zero selects the XY model.
Returns¶
dict[str, Any] Times, statevectors, qubit count, and final statevector.
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, seed_transpiler=20260718)
¶
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.
calibration_snapshot()
¶
Capture the connected backend's calibration for archival in a result pack.
Returns a JSON-serialisable snapshot (backend name, seed_transpiler,
median T1/T2 and readout error, and the calibration date) so every run's
result pack can carry the device state it was measured against, closing
the "no archived calibration snapshot" reproducibility gap. Returns a
{"available": False} record when the backend exposes no properties
(e.g. a local simulator).
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.
A calibration block records the device state (backend name,
seed_transpiler, median T1/T2 and readout error, calibration
date) the run was measured against, so every pack carries the
calibration snapshot needed to reproduce it.
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.
__post_init__()
¶
Validate the bounded search configuration and freeze its metadata.
WitnessDiscoveryEvaluation
dataclass
¶
WitnessDiscoveryResult
dataclass
¶
WitnessSearchMode
¶
Bases: StrEnum
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¶
x_counts Measurement counts in the X basis. y_counts Measurement counts in the Y basis. n_qubits Number of measured qubits. persistence_threshold Minimum H1 lifetime counted as persistent.
Returns¶
QuantumPHResult Normalized H1 indicator, persistence data, and correlation/distance matrices.
Raises¶
ImportError
If the optional ripser dependency is unavailable.
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.
Parameters¶
x_counts_list X-basis count mappings aligned with the coupling scan. y_counts_list Y-basis count mappings aligned with the coupling scan. n_qubits Number of measured qubits. K_base_values Coupling strengths associated with the count pairs. persistence_threshold Minimum H1 lifetime counted as persistent.
Returns¶
dict[str, Any] Coupling values and aligned p_h1/persistent-H1 series.
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, 5].
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
¶
Exact small-system stabilizer Rényi-2 diagnostics.
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).
The implementation enumerates all 4**n Pauli strings and is therefore a
bounded exact diagnostic. A maximum in a finite coupling scan is not, by
itself, a critical-point estimator, a fault-tolerant resource-cost certificate,
or evidence of classical hardness or quantum advantage.
MagicResult
dataclass
¶
Single-coupling pure-state stabilizer Rényi-2 result.
magic_vs_coupling(omega, K_topology, k_range=None, *, max_dense_gib=None)
¶
Scan exact small-system non-stabilizerness on a finite coupling grid.
peak_K reports only the grid argmax. Interpreting it as a critical point
requires a separate preregistered finite-size and uncertainty study.
scpn_quantum_control.analysis.theory_hook_promotion
¶
Evidence-gated promotion records for experimental theory hooks.
This module is the theory-hook boundary between an importable research routine and a
promoted control or product capability. The registry covers quantum speed
limits, Hamiltonian learning, the finite Koopman closure, the legacy
quantum_phi mutual-information diagnostic, stabilizer Rényi entropy, and
spectral form-factor diagnostics.
The registry is deliberately conservative. A passing local evidence probe shows that a bounded software route works on its stated synthetic fixture; it does not establish hardware validity, differentiability, critical scaling, quantum advantage, consciousness, or operational control authority. All records are immutable and JSON-ready. Evidence execution is local, deterministic, credential-free, and never submits provider work.
TheoryHookTier
¶
Bases: StrEnum
Evidence tier assigned to a theory hook.
BOUNDED identifies a small, testable research diagnostic with an
explicit claim boundary. RESEARCH_ONLY identifies a route that must not
be promoted beyond exploratory analysis under the current semantics.
TheoryHookRole
¶
Bases: StrEnum
Permitted role of a hook in the SCPN Quantum Control stack.
TheoryHookStatus
¶
Bases: StrEnum
Promotion state after applying the theory-hook evidence checklist.
TheoryHookPromotionRecord
dataclass
¶
Immutable promotion decision for one experimental theory hook.
Parameters¶
hook_id
Stable machine identifier used by evidence records.
title
Human-readable name of the hook.
module
Import path containing the bounded implementation.
tier
Evidence tier after theory-hook review.
role
Only role for which the current implementation may be used.
status
Current promotion state. None of the reviewed records is a production
control capability.
differentiable
Whether a documented, tested derivative contract exists. This is
False for every current hook.
evidence_fixture
Exact local fixture exercised by :func:run_theory_hook_evidence.
allowed_claims
Narrow statements supported by the local software evidence.
forbidden_claims
Statements that remain prohibited even when the evidence probe passes.
promotion_requirements
Additional evidence required before a future status change.
references
Primary literature identifiers supporting the mathematical label.
Notes¶
The record is policy metadata, not scientific evidence by itself. Pair it
with a passing :class:TheoryHookEvidenceRecord from the same schema.
admitted_for_control
property
¶
Always false; this registry admits no hook for actuation.
admitted_for_publication_claim
property
¶
Always false; local fixture evidence is not publication proof.
__post_init__()
¶
Reject incomplete or internally inconsistent policy records.
as_dict()
¶
Return a JSON-ready record with explicit negative capabilities.
TheoryHookEvidenceRecord
dataclass
¶
Result of one bounded local theory-hook fixture.
Parameters¶
hook_id
Identifier of the corresponding promotion record.
passed
Whether every invariant in checks passed.
fixture
Human-readable fixture description.
checks
Named boolean invariants evaluated by the probe.
metrics
Small JSON-ready numerical or categorical observations. These values
describe the fixture only and are not extrapolation claims.
TheoryHookPromotionReport
dataclass
¶
Complete theory-hook registry plus its local evidence results.
Parameters¶
schema Versioned serialization schema. claim_boundary Global non-claim that applies to every record. records Promotion decisions in canonical order. evidence One local evidence result for each promotion decision. content_digest SHA-256 digest over the report payload excluding the digest itself.
list_theory_hook_promotions()
¶
Return all theory-hook promotion decisions in stable canonical order.
Returns¶
tuple[TheoryHookPromotionRecord, ...] Immutable registry containing exactly one record per reviewed hook.
get_theory_hook_promotion(hook_id)
¶
run_theory_hook_evidence()
¶
Execute every theory-hook local fixture in canonical registry order.
Returns¶
tuple[TheoryHookEvidenceRecord, ...] One immutable evidence result for each promotion record.
Notes¶
The fixtures use exact local simulators and tiny deterministic arrays. The function does not read credentials, connect to a provider, submit hardware work, or grant control/publication authority.
scpn_quantum_control.analysis.research_lane_registry
¶
Governed catalogue of the package's analysis and gauge research lanes.
The research-lane registry makes the existing deep-analysis stack visible without promoting every importable module into a product or scientific claim. Each immutable row records the module's human-reviewed maturity, relevance to differentiable work, current claim status, optional promotion route, and evidence pointers.
The inventory gate is intentionally strict: every ordinary analysis or
gauge module must have exactly one row. Package __init__ modules and
this registry's own governance implementation are the only exclusions. A new
module therefore fails :func:assert_research_lane_inventory until a reviewer
classifies it explicitly.
Registry membership is catalogue evidence only. It grants no productisation, control, hardware, differentiability, advantage, criticality, topology, consciousness, clinical, or publication claim. Promotions remain governed by their own backlog and evidence packages.
ResearchLaneMaturity
¶
Bases: StrEnum
Human-reviewed implementation maturity.
RESEARCH marks exploratory scientific code. PROTOTYPE marks a
bounded reusable diagnostic whose public contract or evidence is not yet a
product gate. PRODUCT_CANDIDATE marks a stable candidate or a module
already composed by a separately governed product; it is not a promotion
by this registry.
ResearchLaneDiffHook
¶
Bases: StrEnum
Relationship between a lane and differentiable-control work.
ResearchLaneClaimStatus
¶
Bases: StrEnum
Strongest claim class currently carried by a lane's own evidence.
ResearchLaneRecord
dataclass
¶
Immutable human classification for one importable research module.
Parameters¶
module
Fully qualified module path under scpn_quantum_control.analysis or
scpn_quantum_control.gauge.
summary
Narrow description of what the current implementation can provide.
The summary is not a scientific validation claim.
maturity
Human-reviewed implementation maturity.
diff_hook
Relationship to separately governed differentiable-control work.
claim_status
Strongest claim class admitted by the module's current evidence.
promotion_targets
Backlog routes that may consume the lane. A route suffixed planned
or deferred-owner-gate is explicitly not a completed promotion.
evidence_refs
Repository-relative evidence or governance pointers. Empty tuples are
expected for research-only and diagnostic-only lanes.
Notes¶
PRODUCT_CANDIDATE and EVIDENCE_BOUNDED remain non-promotional here.
Callers must consult the referenced product/evidence package before making
any stronger claim.
family
property
¶
Module family, either analysis or gauge.
registry_grants_productisation
property
¶
Always false because catalogue membership is non-promotional.
registry_grants_control
property
¶
Always false; catalogue membership grants no actuation authority.
registry_grants_publication_claim
property
¶
Always false; catalogue membership is not publication evidence.
__post_init__()
¶
Reject blank, out-of-scope, duplicate, or permissive records.
as_dict()
¶
Return a deterministic JSON-ready row with explicit denials.
ResearchLaneInventoryReport
dataclass
¶
Comparison between registered rows and modules found on disk.
missing_modules are importable modules without a human classification.
orphaned_records are registry rows whose implementation no longer
exists. Both conditions fail the gate.
ResearchLaneRegistryReport
dataclass
¶
Complete research-lane catalogue, inventory gate, counts, and digest.
as_dict()
¶
Return the complete deterministic report as JSON-ready data.
list_research_lanes()
¶
Return all human-reviewed lanes in canonical module order.
Returns¶
tuple[ResearchLaneRecord, ...] The immutable registry. The tuple and its records may be safely shared between callers.
get_research_lane(module)
¶
discover_research_lane_modules(package_root=None)
¶
Discover ordinary analysis and gauge modules from source files.
Parameters¶
package_root
Directory containing the analysis and gauge packages. When
omitted, discovery uses the installed scpn_quantum_control package
containing this module.
Returns¶
tuple[str, ...]
Sorted fully qualified module paths. __init__.py and this registry
implementation are excluded by policy.
Raises¶
FileNotFoundError If either required package directory is absent.
validate_research_lane_inventory(discovered_modules=None)
¶
Compare discovered modules with the human-reviewed registry.
Parameters¶
discovered_modules
Optional explicit discovery result for testing or packaged consumers.
When omitted, :func:discover_research_lane_modules scans the current
package. Duplicate values are normalized before comparison.
Returns¶
ResearchLaneInventoryReport
Exact registered/discovered sets plus missing and orphaned entries.
Inspect :attr:ResearchLaneInventoryReport.passed or call
:func:assert_research_lane_inventory for exception semantics.
assert_research_lane_inventory(discovered_modules=None)
¶
Return a passing inventory report or raise a drift error.
Raises¶
RuntimeError If a discovered module lacks a row or a row has no implementation.
build_research_lane_registry_report()
¶
scpn_quantum_control.analysis.rl_research_governance
¶
Fail-closed governance for witness-search and pulse-optimisation research.
RL-governance keeps reinforcement-learning-adjacent routes in a research extra. The existing witness discovery is a seeded static candidate search, not a Gym environment or a trained production policy. Its dense composite witness score is therefore named explicitly and evaluated through deterministic replay over multiple seeds. The pulse optimiser remains unimplemented and blocked behind the separately governed pulse-execution boundary.
Nothing in this module enables provider submission, hardware execution, production control, policy deployment, or a scientific performance claim.
RLResearchLane
¶
Bases: StrEnum
Governed RL-adjacent route.
RLResearchGovernanceError
¶
Bases: RuntimeError
Raised when an RL-adjacent route lacks its research gates.
RLResearchPolicy
dataclass
¶
Explicit research-only enablement and reproducibility budget.
Parameters¶
enabled
Opt-in research flag. The default is False.
preregistration_id
Stable identifier for the protocol fixed before the run. An enabled
route without this value is refused.
seeds
At least three distinct non-negative seeds used for the evaluation
suite.
max_episodes
Maximum witness-search iterations per seed. The legacy API calls these
iterations episodes; no Gym episode contract is implied.
max_evaluations_per_seed
Upper bound on candidate evaluations for each seed.
deterministic_evaluation
Must remain True.
evaluation_exploration_noise
Must remain exactly zero for deterministic evaluation.
allow_hardware
Must remain False.
allow_production_control
Must remain False.
reward_contract
Frozen dense composite score identifier. The score combines final
order, correlations, Fiedler value, witness margin, and novelty; it can
be gamed if reported without its components and is not a sparse task
reward or operational utility.
Notes¶
This policy does not design a Gym environment. Consequently the Gym
step tuple is not applicable; a future environment must separately
implement obs, reward, terminated, truncated, info.
RLResearchDecision
dataclass
¶
RLSeedEvaluation
dataclass
¶
RLSeedSuiteReport
dataclass
¶
estimate_witness_evaluation_budget(spec)
¶
Return a conservative candidate-evaluation upper bound for one seed.
The initial Latin-hypercube candidates consume n_initial evaluations.
Each iteration proposes at most max(batch_size - 1, 1) Bayesian rows
plus one seeded bandit row.
assess_rl_research(policy, lane, *, spec=None)
¶
Return a fail-closed admission decision for an RL-adjacent route.
Parameters¶
policy
Explicit policy. None resolves to the disabled default.
lane
Witness discovery or pulse optimisation.
spec
Search specification used for budget checks. It is ignored for the
pulse route, which is blocked in the current implementation.
assert_rl_research_allowed(policy, lane, *, spec=None)
¶
Return an allowed decision or raise :class:RLResearchGovernanceError.
build_witness_seed_suite(policy, template)
¶
Build one budget-checked witness specification per policy seed.
run_governed_witness_seed_suite(K_nm, omega, *, policy, template, theta0=None, prefer_rust=False)
¶
Run and replay each preregistered seed without hardware or deployment.
Each full seeded search is executed twice. Byte-identical serialized traces are required before a seed result can be constructed. This is reproducible software evidence across multiple seeds, not statistical significance for an operational policy or a claim that the dense score is ungameable.
build_rl_research_evidence_report()
¶
Run the frozen credential-free three-seed governance fixture.
render_rl_research_evidence_markdown(report=None)
¶
Render deterministic human-readable RL governance evidence.
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
An explicit pure-Python reference key pair. This compatibility path cannot
promise memory zeroisation; production code uses :meth:generate.
Raises¶
ValueError
If key_id is empty or whitespace.
key_id
property
¶
The stable identifier recorded in the envelope.
is_destroyed
property
¶
Whether the native secret-key allocation has been destroyed.
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 or key_id is empty.
RuntimeError
If the compiled zeroizing signing-key backend is unavailable.
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.
destroy()
¶
Zeroize and permanently disable the native signing key.
A signer constructed directly with a Python :class:MLDSAKeyPair has
no reliable wipe operation and therefore fails instead of claiming one.
__enter__()
¶
Return this signer for a bounded native-key custody scope.
__exit__(exc_type, exc_value, traceback)
¶
Destroy native secret material when leaving the custody scope.
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)
¶
Execute SCPN-QKD protocol on statevector simulator.
seed is REQUIRED: a key-distribution simulation must never source
its randomness from a hidden default, so the caller states the seed
explicitly (simulation-only — see the module docstring).
Returns dict with raw_key_alice, raw_key_bob, qber, secure_key (the privacy-amplified bit array, empty when the measured QBER is at or above the security threshold), secure_key_length (in bits), and bell_correlator (CHSH value).
derive_layer_key(K, layer_idx, phase_sequence, nonce=b'')
¶
Derive a layer subkey from one coupling row and phase trajectory.
Parameters¶
K Full coupling matrix; the selected row is bound into the digest. layer_idx Zero-indexed layer number. phase_sequence Phase values for the selected layer over the time window. nonce Optional caller-supplied session nonce.
Returns¶
bytes The 32-byte SHA-256 layer-key digest.
derive_master_key(K, R_global, nonce=b'')
¶
Derive a master key from the coupling matrix and order parameter.
Parameters¶
K Full coupling matrix in canonical row-major representation. R_global Global order parameter bound into the digest. nonce Optional caller-supplied session nonce.
Returns¶
bytes
The 32-byte SHA-256 digest of K || R_global || nonce.
evolve_key_phases(K, omega, theta_0, t_window, n_samples=32)
¶
Evolve Kuramoto dynamics and sample the phase trajectory.
Parameters¶
K Coupling matrix for the layer oscillators. omega Intrinsic angular frequency of every layer. theta_0 Initial phase of every layer. t_window Positive integration-window duration. n_samples Number of evenly spaced trajectory samples.
Returns¶
numpy.ndarray
Phase array shaped (n_layers, n_samples).
Raises¶
RuntimeError If the numerical integrator does not complete successfully.
group_key(K, member_layers, phases, nonce=b'')
¶
Derive a shared key for a subset of SCPN layers.
Parameters¶
K Full coupling matrix. member_layers Layer indices included in the key group. phases Current phase value for every layer. nonce Optional session nonce.
Returns¶
bytes The 32-byte SHA-256 digest of the selected submatrix, sorted member indices, selected phases, and nonce.
hmac_sign(key, message)
¶
hmac_verify_key(key, message, expected_mac)
¶
key_hierarchy(K, phases, R_global, nonce=b'')
¶
Derive the master key and every layer subkey.
Parameters¶
K Square coupling matrix. phases Current phase value for every layer. R_global Global order parameter bound into the master key. nonce Optional session nonce bound into every key.
Returns¶
dict[str, Any]
Mapping with the master key under master and indexed layer keys
under layers.
rotating_key_schedule(K, omega, theta_0, n_windows=4, window_duration=1.0)
¶
Generate a sequence of key hierarchies from evolving Kuramoto dynamics.
Parameters¶
K Coupling matrix for the layer oscillators. omega Intrinsic angular frequency of every layer. theta_0 Initial phase of every layer. n_windows Number of consecutive rotation windows. window_duration Integration duration of each window.
Returns¶
list[dict[str, Any]] One hierarchy per window with its index, keys, order parameter, and final phases. Each window starts from the preceding final phases.
verify_key_chain(master, layer_keys, K, phases, R_global, nonce=b'')
¶
Verify the master and layer keys against their derivation inputs.
Parameters¶
master Candidate master-key bytes. layer_keys Candidate keys indexed by layer. K Full coupling matrix used for recomputation. phases Current phase value for every layer. R_global Global order parameter used for recomputation. nonce Session nonce used for recomputation.
Returns¶
bool Whether the master and every supplied layer key match recomputation.
estimate_qber(alice_bits, bob_bits)
¶
extract_raw_key(counts, basis, keep_qubits=None)
¶
Sift measurement results into raw key bits.
Parameters¶
counts
Measurement outcome counts keyed by Qiskit bitstrings.
basis
Declared measurement-basis label. The current majority-vote extraction
is basis independent and assumes counts are already in that basis.
keep_qubits
Qubit indices to extract; None selects every qubit.
Returns¶
numpy.ndarray
One-dimensional uint8 array of majority-vote bits.
prepare_key_state(K, omega, ansatz_reps=2, maxiter=200)
¶
Build the VQE-optimized circuit encoding the K_nm ground state.
Parameters¶
K Coupling matrix encoded by the phase Hamiltonian. omega Intrinsic angular frequency of every qubit/layer. ansatz_reps Number of repetitions in the VQE ansatz. maxiter Maximum optimizer iterations.
Returns¶
dict[str, Any] Bound circuit, ground energy, statevector, and qubit count.
privacy_amplification(raw_key, qber, *, seed)
¶
Toeplitz-hash privacy amplification (Universal₂, leftover-hash lemma).
The extractor is a random binary Toeplitz matrix T of shape
(n_secure_bits, len(raw_key)) whose diagonals are drawn from the
seed-keyed PRNG. Binary Toeplitz matrices form a Universal₂ hash
family, so the leftover-hash lemma bounds the adversary's information
on the output T @ raw_key mod 2. The output length is the
asymptotic BB84 secret fraction 1 - 2*h2(QBER) of the input length
(Shor & Preskill, PRL 85 441); finite-key corrections are out of scope
for this simulation-only module.
Parameters¶
raw_key
Sifted uint8 key bits in {0, 1}.
qber
Estimated quantum bit error rate.
seed
PRNG seed selecting the Toeplitz family member. A real deployment must
use fresh public randomness agreed after the raw key exists; the
parameter is required so no entropy is silently fabricated.
Returns¶
numpy.ndarray
Extracted uint8 bits of length n_secure_bits; empty above the
QBER security threshold or when the secret fraction rounds to zero.
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]].
Parameters¶
rho_2x2 Single-qubit density matrix. gamma Excited-state damping probability.
Returns¶
numpy.ndarray Complex density matrix after applying both Kraus operators.
depolarizing_channel(rho, p)
¶
devetak_winter_rate(qber)
¶
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.
Parameters¶
sv
Full-system statevector before interception.
qubit_i
Alice's reference qubit index.
qubit_j
Bob's intercepted qubit index.
n_total
Total number of qubits represented by sv.
Returns¶
float
Absolute correlation-loss QBER clipped to [0, 0.5].
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.
Parameters¶
sv
Full-system statevector.
qubit_i
First retained qubit index.
qubit_j
Second retained qubit index.
n_total
Total number of qubits represented by sv.
p_depol
Depolarizing probability applied to the reduced pair.
Returns¶
float Wootters concurrence of the noisy reduced state.
security_analysis(sv, alice_qubits, bob_qubits, p_depol_range=None)
¶
Compute key-rate curves versus noise for every Alice/Bob qubit pair.
Parameters¶
sv
Full-system statevector used for all reduced-pair calculations.
alice_qubits
Alice-side qubit indices.
bob_qubits
Bob-side qubit indices.
p_depol_range
Depolarizing probabilities to scan. A 16-point [0, 0.3] grid is
used when omitted.
Returns¶
dict Pairwise rate curves, maximum tolerable noise per pair, and aggregate rate versus noise.
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.
Parameters¶
K Secret coupling matrix used as HMAC key material. challenge Verifier-issued challenge bytes.
Returns¶
bytes SHA-256 HMAC response.
challenge_response_verify(K, challenge, response)
¶
Verify a response against the HMAC for a topology challenge.
Parameters¶
K : NDArray[np.float64] Secret coupling matrix used as the HMAC key material. challenge : bytes Verifier-issued challenge bytes. response : bytes Claimed SHA-256 HMAC response.
Returns¶
bool
True when the response matches the expected HMAC.
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.
Parameters¶
K Reference coupling matrix. n_trials Number of deterministic perturbation trials. sigma Standard deviation of the symmetric Gaussian perturbation.
Returns¶
dict Noise scale and mean, maximum, standard-deviation, and 99th-percentile fingerprint drift statistics.
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.
Parameters¶
K Square coupling matrix.
Returns¶
dict Normalized Fiedler value, spectral entropy, eigenvalues, and radius.
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.
Parameters¶
K Coupling matrix whose rows are committed independently.
Returns¶
list[bytes] SHA-256 digest for each matrix row in input order.
spectral_fingerprint(K)
¶
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.
Parameters¶
K Coupling matrix serialized as commitment material. nonce Optional public commitment nonce.
Returns¶
bytes SHA-256 commitment digest.
topology_distance(fp1, fp2)
¶
verify_commitment(K, nonce, commitment)
¶
verify_fingerprint(K, fingerprint, tol=1e-06)
¶
verify_row_hash(K, row_idx, expected_hash)
¶
__getattr__(name)
¶
Resolve and cache a public export from its original owning module.
Parameters¶
name Public export requested through this package.
Returns¶
Any Original object, including module-valued exports.
Raises¶
AttributeError If the name is undeclared or the original module lacks its attribute. ImportError If the owning module cannot be imported.
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, validate and cache one plugin.
Invalid factories or dataset metadata raise without caching a failed instance. A subsequent call retries construction; unrelated entries remain registered. Discovery does not validate factory results.
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 and privacy boundary for a packaged benchmark artifact.
contains_personal_data describes the packaged file, not every possible
external input accepted by a third-party plugin. The built-in catalogue
is intentionally restricted to curated public constants and small matrices
with no raw participant, clinical, SCADA, or proprietary facility records.
path
property
¶
Absolute path to the packaged artifact.
ApplicationBenchmarkPrivacyAudit
dataclass
¶
One successful packaged-dataset privacy audit row.
Parameters¶
dataset_id
Stable packaged dataset identifier.
source_mode
Validated artifact provenance mode.
privacy_classification
Descriptor classification for the packaged bytes.
contains_personal_data
Whether the packaged artifact contains personal data. Built-in rows
must remain False.
privacy_boundary
Exact licence/provenance note bound to the artifact metadata.
artifact_hashes
Validated SHA-256 custody hashes embedded in the artifact.
passed
Always True for returned rows; mismatches raise instead of
returning an ambiguous partial result.
as_dict()
¶
Return a JSON-ready audit row with defensive hash copying.
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.
ApplicationDataOrigin
¶
Bases: StrEnum
Admitted input provenance for an honesty kit.
ApplicationHonestyAuditReport
dataclass
¶
Deterministic aggregate of honesty kits and dataset privacy checks.
Parameters¶
kits
Validated built-in honesty-kit records.
dataset_privacy
Catalogue privacy audit rows. Each row has already loaded and
validated the corresponding packaged QPUDataArtifact.
passed
property
¶
Whether every built-in kit and dataset privacy row is valid.
__post_init__()
¶
Reject empty, duplicate, or incomplete aggregate reports.
content_digest()
¶
Return a SHA-256 digest of the canonical report payload.
as_dict()
¶
Return the canonical JSON evidence payload including its digest.
ApplicationSupportStatus
¶
Bases: StrEnum
Public support grade for a domain-facing application route.
BOUNDED_RESEARCH means that the named software path is tested for its
documented small benchmark, while SIMULATION_ONLY requires generated
inputs and forbids measured-domain interpretation.
DomainApplicationHonestyKit
dataclass
¶
Immutable claim boundary for one domain-facing application family.
Parameters¶
kit_id
Stable machine identifier for the kit.
domain_tag
Non-promotional domain label used in reports and user interfaces.
title
Human-readable kit name.
support_status
Whether the route is a bounded research benchmark or simulation-only.
data_origin
Provenance class admitted by this kit.
synthetic_only
True when measured or curated domain data must not enter the route.
dataset_ids
Packaged public catalogue identifiers governed by the kit. An empty
tuple means that the route generates its inputs in code.
source_modules
Import paths implementing the bounded route.
allowed_uses
Positive, narrowly worded descriptions of supported software use.
caveats
Scientific and operational limitations that callers must preserve.
claims_forbidden
Explicit claims that this kit never authorises.
forecasting_tags
Simulation-only forecasting tags that may be cross-referenced. These
tags do not convert a synthetic forecast into domain evidence.
Notes¶
Construction validates the internal policy relationships. In particular, a synthetic-only kit cannot declare curated input data or packaged dataset identifiers, and every kit must retain at least one forbidden claim.
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.
JosephsonKnmCandidate
dataclass
¶
JosephsonMagnitudeGate
dataclass
¶
JosephsonMagnitudeStudyDesign
dataclass
¶
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.
ClassicalESNReadoutResult
dataclass
¶
Classical echo-state readout fitted on a fixed reservoir.
QRCBaselineComparison
dataclass
¶
Matched-feature comparison between QRC and a classical ESN readout.
QRCHoldoutComparison
dataclass
¶
Disjoint-train/validation QRC and matched-feature ESN comparison.
QuantumEVSResult
dataclass
¶
Quantum-enhanced EVS feature vector.
Attributes¶
classical_features
Validated input EVS feature vector.
quantum_features
Synchronisation, phase, and sampled correlation features.
r_global
Quantum-state global synchronisation magnitude.
p_h1_proxy
Fraction of output phases whose magnitude exceeds pi / 2.
enhancement_factor
Ratio of quantum-feature norm to classical-feature norm.
QuantumKernelResult
dataclass
¶
Quantum kernel computation result.
ReservoirResult
dataclass
¶
Exact-statevector quantum-reservoir feature result.
ReservoirLinearObjective
dataclass
¶
ReservoirTaskKind
¶
Bases: StrEnum
Synthetic task families admitted by the reservoir certificate suite.
ReservoirTrainingCertificate
dataclass
¶
Digest-bound held-out QRC and matched-feature ESN metrics.
to_dict()
¶
Return a JSON-ready certificate mapping.
SyntheticReservoirDataset
dataclass
¶
Disjoint synthetic train/validation data for one reservoir task.
__post_init__()
¶
Validate shapes, finiteness, domain, and disjoint sample rows.
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.
audit_application_benchmark_privacy()
¶
Audit every packaged application artifact against its privacy descriptor.
Returns¶
tuple[ApplicationBenchmarkPrivacyAudit, ...] One immutable, JSON-ready success row per catalogue descriptor.
Notes¶
This audit reads only files beneath data/public_application_benchmarks.
It never traverses external paths, downloads data, or treats a curated
matrix as raw domain evidence. Any mismatch raises immediately.
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 a packaged artifact and enforce descriptor and privacy custody.
Raises¶
KeyError
If dataset_id is not registered.
ValueError
If identity, domain, provenance mode, privacy boundary, or publication
safety disagrees with the catalogue descriptor.
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).
build_application_honesty_audit_report()
¶
Build deterministic local evidence for every kit and catalogue row.
Returns¶
ApplicationHonestyAuditReport Immutable report with a canonical content digest.
Notes¶
The audit loads only versioned packaged application artifacts. It performs no network access and never opens a user-supplied or private dataset.
get_domain_application_honesty_kit(kit_id)
¶
get_domain_application_honesty_kit_for_dataset(dataset_id)
¶
Return the unique kit governing a packaged dataset identifier.
Synthetic-only kits intentionally have no packaged dataset identifiers and therefore cannot be resolved through this function.
Raises¶
KeyError
If no built-in kit governs dataset_id.
RuntimeError
If registry corruption assigns the same dataset to multiple kits.
list_domain_application_honesty_kits()
¶
Return all built-in domain application honesty kits in stable order.
render_application_honesty_audit_markdown(report)
¶
Render a human-readable Markdown evidence report.
Parameters¶
report
Validated report returned by
:func:build_application_honesty_audit_report.
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.
build_josephson_knm_magnitude_study_design(*, n_junctions=DEFAULT_CANDIDATE_N, topology=DEFAULT_TOPOLOGY, parameters=None, extension_targets=DEFAULT_EXTENSION_TARGETS)
¶
Build the Josephson K_nm magnitude-study preregistration manifest.
Parameters¶
n_junctions:
Number of Josephson-array nodes used for the topology candidate.
topology:
Josephson topology model passed to :func:josephson_benchmark.
parameters:
Parameter set used to evaluate the topology candidate. When omitted,
explicitly labelled nominal transmon literature parameters are used.
extension_targets:
Larger node counts to preregister for the same study after calibrated
Josephson coupling artifacts exist.
Returns¶
JosephsonMagnitudeStudyDesign Design manifest with topology evidence, required calibration fields, and fail-closed promotion gates.
render_josephson_knm_magnitude_study_markdown(design)
¶
Render a human-reviewable Josephson K_nm magnitude-study report.
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.
classical_esn_feature_matrix(X, *, reservoir_size, spectral_radius=0.9, input_scale=0.5, leak_rate=1.0, seed=0)
¶
Return deterministic echo-state features for a sample sequence.
Parameters¶
X:
Input samples with shape (n_samples, n_features).
reservoir_size:
Number of classical reservoir units. Use the QRC feature count for a
matched-feature comparison.
spectral_radius:
Target spectral radius of the recurrent matrix.
input_scale:
Uniform input-weight scale.
leak_rate:
Leaky integration rate in (0, 1].
seed:
Seed for the deterministic reservoir weights.
Returns¶
numpy.ndarray
Feature matrix with shape (n_samples, reservoir_size).
classical_esn_ridge_regression(X_train, y_train, *, reservoir_size, alpha=1.0, spectral_radius=0.9, input_scale=0.5, leak_rate=1.0, seed=0)
¶
Fit a ridge readout on deterministic classical ESN features.
Parameters¶
X_train:
Input samples with shape (n_samples, n_features).
y_train:
Target values with one value per sample.
reservoir_size:
Number of classical reservoir units.
alpha:
Ridge regularisation strength.
spectral_radius:
Target recurrent spectral radius.
input_scale:
Uniform input-weight scale.
leak_rate:
Leaky integration rate in (0, 1].
seed:
Seed for deterministic reservoir weights.
Returns¶
ClassicalESNReadoutResult Features, readout weights, training predictions, and MSE.
compare_quantum_reservoir_to_esn(X_train, y_train, K, *, omega=None, alpha=1.0, max_weight=1, reservoir_size=None, spectral_radius=0.9, input_scale=0.5, leak_rate=1.0, seed=0)
¶
Compare the shipped QRC feature map against a classical ESN baseline.
The default ESN size matches the quantum reservoir feature count. The comparison reports training-set MSE only; it is a bounded capability adjudication surface, not a general performance claim.
Parameters¶
X_train:
Input samples with shape (n_samples, n_features).
y_train:
Target values with one value per sample.
K:
Kuramoto-XY coupling matrix consumed by the existing QRC feature map.
omega:
Optional natural-frequency vector for the QRC feature map.
alpha:
Ridge regularisation strength used by both readouts.
max_weight:
Maximum Pauli-string weight used by the QRC feature map.
reservoir_size:
Classical ESN feature count. When omitted, it matches the QRC count.
spectral_radius:
Target ESN recurrent spectral radius.
input_scale:
Uniform ESN input-weight scale.
leak_rate:
ESN leaky integration rate.
seed:
Seed for deterministic ESN weights.
Returns¶
QRCBaselineComparison Matched-feature predictions and MSE values for the two readouts.
compare_quantum_reservoir_to_esn_holdout(X_train, y_train, X_validation, y_validation, K, *, omega=None, alpha=1.0, max_weight=1, t=1.0, reservoir_size=None, spectral_radius=0.9, input_scale=0.5, leak_rate=1.0, seed=0, max_dense_gib=None)
¶
Compare QRC and ESN readouts on disjoint held-out samples.
The QRC feature map is row-local. The classical ESN state is generated on the concatenated train/validation sequence and split afterwards, so its validation state continues from training rather than silently resetting. The result reports both systems without assuming either must win.
Parameters¶
X_train, X_validation: Disjoint training and validation input matrices with equal width. y_train, y_validation: Scalar targets matching their respective input rows. K: Kuramoto-XY coupling matrix for the exact QRC feature map. omega: Optional natural-frequency vector. alpha: Shared ridge regularisation strength. max_weight: Maximum QRC Pauli-string weight. t: Non-negative QRC evolution time. reservoir_size: ESN feature count; defaults to the QRC feature count. spectral_radius, input_scale, leak_rate, seed: Deterministic ESN configuration. max_dense_gib: Optional per-QRC-statevector allocation ceiling.
Returns¶
QRCHoldoutComparison Train and validation predictions and MSE values for both systems.
quantum_evs_enhance(features, n_osc=8, dt=0.1, trotter_reps=3)
¶
Enhance EVS features through quantum Kuramoto evolution.
Parameters¶
features Finite non-empty one-dimensional classical EVS feature vector. n_osc Quantum oscillator count in the supported Paper-27 frequency range. dt Positive finite evolution time. trotter_reps Positive integer number of Lie-Trotter repetitions.
Returns¶
QuantumEVSResult Preserved classical features, quantum features, synchronisation, phase-topology proxy, and norm enhancement factor.
Raises¶
TypeError
If n_osc or trotter_reps is not an integer.
ValueError
If features, oscillator count, evolution time, or repetitions violate
their public contracts.
canonical_edge_pairs(n_qubits)
¶
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 |
encode_topology_edge_features(x, K, n_qubits, *, t=0.8, reps=2, max_qubits=8)
¶
Encode canonical edge features through a coupling-modulated XY circuit.
Feature x[k] multiplies the coupling for the k-th pair returned by
:func:canonical_edge_pairs. The circuit prepares |+>**n and applies
one Trotter-synthesised evolution of the resulting XY Hamiltonian. No local
feature rotations or provider calls are performed.
Parameters¶
x:
Finite vector of length n_qubits * (n_qubits - 1) // 2.
K:
Finite symmetric (n_qubits, n_qubits) coupling matrix with zero
diagonal. Zero entries are topology masks and ignore their features.
n_qubits:
Qubit count, bounded by max_qubits before dense simulation.
t:
Positive finite evolution time.
reps:
Positive integer Lie-Trotter repetition count, at most 16.
max_qubits:
Positive dense-state allocation budget, at most 20.
Returns¶
qiskit.quantum_info.Statevector
Exact local statevector of dimension 2**n_qubits.
Raises¶
ValueError If shapes, symmetry, diagonal, finiteness, evolution settings, or resource budgets violate the contract.
reservoir_features(x, K, omega=None, t=1.0, max_weight=2, *, max_dense_gib=None)
¶
Compute quantum reservoir features for input x.
Parameters¶
x: Input feature vector with at most one value per qubit. K: Finite square coupling matrix. omega: Optional natural-frequency vector. t: Non-negative reservoir evolution time. max_weight: Maximum Pauli-string weight included in the feature map. max_dense_gib: Optional exact-statevector allocation ceiling.
Returns¶
ReservoirResult Pauli expectation features and their labels.
certify_reservoir_training(dataset, K, *, omega=None, alpha=0.1, max_weight=1, t=1.0, seed=0, max_dense_gib=None)
¶
Fit QRC/ESN readouts and certify their disjoint held-out metrics.
generate_synthetic_reservoir_task(task_kind, *, n_train, n_validation, seed)
¶
Generate a deterministic synthetic forecast or classification task.
The tasks are small functional certificates, not domain benchmarks. They contain no clinical, grid, plasma, private, or operational data.
__getattr__(name)
¶
Resolve and cache a public export from its original owning module.
Parameters¶
name Public export requested through this package.
Returns¶
Any Original object, including module-valued exports.
Raises¶
AttributeError If the name is undeclared or the original module lacks its attribute. ImportError If the owning module cannot be imported.
scpn_quantum_control.applications.dataset_catalog
¶
Packaged application benchmark datasets exposed as QPU data artifacts.
ApplicationBenchmarkDescriptor
dataclass
¶
Metadata and privacy boundary for a packaged benchmark artifact.
contains_personal_data describes the packaged file, not every possible
external input accepted by a third-party plugin. The built-in catalogue
is intentionally restricted to curated public constants and small matrices
with no raw participant, clinical, SCADA, or proprietary facility records.
path
property
¶
Absolute path to the packaged artifact.
ApplicationBenchmarkPrivacyAudit
dataclass
¶
One successful packaged-dataset privacy audit row.
Parameters¶
dataset_id
Stable packaged dataset identifier.
source_mode
Validated artifact provenance mode.
privacy_classification
Descriptor classification for the packaged bytes.
contains_personal_data
Whether the packaged artifact contains personal data. Built-in rows
must remain False.
privacy_boundary
Exact licence/provenance note bound to the artifact metadata.
artifact_hashes
Validated SHA-256 custody hashes embedded in the artifact.
passed
Always True for returned rows; mismatches raise instead of
returning an ambiguous partial result.
as_dict()
¶
Return a JSON-ready audit row with defensive hash copying.
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 a packaged artifact and enforce descriptor and privacy custody.
Raises¶
KeyError
If dataset_id is not registered.
ValueError
If identity, domain, provenance mode, privacy boundary, or publication
safety disagrees with the catalogue descriptor.
audit_application_benchmark_privacy()
¶
Audit every packaged application artifact against its privacy descriptor.
Returns¶
tuple[ApplicationBenchmarkPrivacyAudit, ...] One immutable, JSON-ready success row per catalogue descriptor.
Notes¶
This audit reads only files beneath data/public_application_benchmarks.
It never traverses external paths, downloads data, or treats a curated
matrix as raw domain evidence. Any mismatch raises immediately.
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.honesty_kits
¶
Fail-closed claim and data boundaries for domain-facing applications.
The objects in this module do not certify domain validity. They make the opposite boundary explicit: each kit identifies the small software route that is supported, the data origin admitted by that route, and the claims that remain forbidden. The built-in registry covers the application-honesty power-grid, Josephson, EEG-like, and ITER-inspired application families.
All returned records are immutable and JSON-ready. The audit functions are local and deterministic; they do not read credentials, contact providers, submit hardware work, or inspect private datasets.
ApplicationSupportStatus
¶
Bases: StrEnum
Public support grade for a domain-facing application route.
BOUNDED_RESEARCH means that the named software path is tested for its
documented small benchmark, while SIMULATION_ONLY requires generated
inputs and forbids measured-domain interpretation.
ApplicationDataOrigin
¶
Bases: StrEnum
Admitted input provenance for an honesty kit.
DomainApplicationHonestyKit
dataclass
¶
Immutable claim boundary for one domain-facing application family.
Parameters¶
kit_id
Stable machine identifier for the kit.
domain_tag
Non-promotional domain label used in reports and user interfaces.
title
Human-readable kit name.
support_status
Whether the route is a bounded research benchmark or simulation-only.
data_origin
Provenance class admitted by this kit.
synthetic_only
True when measured or curated domain data must not enter the route.
dataset_ids
Packaged public catalogue identifiers governed by the kit. An empty
tuple means that the route generates its inputs in code.
source_modules
Import paths implementing the bounded route.
allowed_uses
Positive, narrowly worded descriptions of supported software use.
caveats
Scientific and operational limitations that callers must preserve.
claims_forbidden
Explicit claims that this kit never authorises.
forecasting_tags
Simulation-only forecasting tags that may be cross-referenced. These
tags do not convert a synthetic forecast into domain evidence.
Notes¶
Construction validates the internal policy relationships. In particular, a synthetic-only kit cannot declare curated input data or packaged dataset identifiers, and every kit must retain at least one forbidden claim.
ApplicationHonestyAuditReport
dataclass
¶
Deterministic aggregate of honesty kits and dataset privacy checks.
Parameters¶
kits
Validated built-in honesty-kit records.
dataset_privacy
Catalogue privacy audit rows. Each row has already loaded and
validated the corresponding packaged QPUDataArtifact.
passed
property
¶
Whether every built-in kit and dataset privacy row is valid.
__post_init__()
¶
Reject empty, duplicate, or incomplete aggregate reports.
content_digest()
¶
Return a SHA-256 digest of the canonical report payload.
as_dict()
¶
Return the canonical JSON evidence payload including its digest.
list_domain_application_honesty_kits()
¶
Return all built-in domain application honesty kits in stable order.
get_domain_application_honesty_kit(kit_id)
¶
get_domain_application_honesty_kit_for_dataset(dataset_id)
¶
Return the unique kit governing a packaged dataset identifier.
Synthetic-only kits intentionally have no packaged dataset identifiers and therefore cannot be resolved through this function.
Raises¶
KeyError
If no built-in kit governs dataset_id.
RuntimeError
If registry corruption assigns the same dataset to multiple kits.
build_application_honesty_audit_report()
¶
Build deterministic local evidence for every kit and catalogue row.
Returns¶
ApplicationHonestyAuditReport Immutable report with a canonical content digest.
Notes¶
The audit loads only versioned packaged application artifacts. It performs no network access and never opens a user-supplied or private dataset.
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, validate and cache one plugin.
Invalid factories or dataset metadata raise without caching a failed instance. A subsequent call retries construction; unrelated entries remain registered. Discovery does not validate factory results.
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.
GaugeLatticeCrosscheck
dataclass
¶
Side-by-side confinement report from the quantum and lattice routes.
both_tensions_available
property
¶
Whether both routes produced a finite string tension.
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).
crosscheck_confinement_on_lattice(K, omega, *, beta=1.0, n_thermalisation=200, n_leapfrog=10, step_size=0.1, seed=None)
¶
Run both confinement probes on one coupling topology.
Parameters¶
K : NDArray[np.float64]
Symmetric coupling matrix, shape (n, n); non-zero entries define
the gauge-link graph for both routes.
omega : NDArray[np.float64]
Natural frequencies, shape (n,) (quantum route only).
beta : float, optional
Inverse gauge coupling of the classical lattice ensemble; positive.
n_thermalisation : int, optional
HMC updates before measuring; at least 1.
n_leapfrog : int, optional
Leapfrog steps per HMC update; at least 1.
step_size : float, optional
Leapfrog step size; positive.
seed : int or None, optional
Lattice RNG seed for reproducible sampling.
Returns¶
GaugeLatticeCrosscheck The quantum confinement result plus classical lattice observables measured after thermalisation, with the HMC acceptance rate as a sampling-health indicator.
Raises¶
ValueError
If K is not square-symmetric, omega has the wrong shape, or
a sampling parameter is out of range.
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.
__getattr__(name)
¶
Resolve and cache a public export from its original owning module.
Parameters¶
name Public export requested through this package.
Returns¶
Any Original object, including module-valued exports.
Raises¶
AttributeError If the name is undeclared or the original module lacks its attribute. ImportError If the owning module cannot be imported.
TCBO¶
scpn_quantum_control.tcbo
¶
TCBO quantum extensions: topological coherence observer.
TCBOResult
dataclass
¶
Collect small-system TCBO proxy diagnostics.
Attributes¶
p_h1 : float
Gauge vortex density, reused as the Betti-1-labelled proxy.
tee : float
Seven-term entropy inclusion-exclusion proxy in bits.
string_order : float
Real expectation of the endpoint-Z/interior-X Pauli string.
n_qubits : int
Number of oscillators represented by the exact ground state.
betti_0_proxy : float
Fraction of qubits with absolute Z expectation above 0.5.
betti_1_proxy : float
Alias of p_h1; not a computed persistent-homology Betti number.
compute_tcbo_observables(K, omega)
¶
Compute TCBO proxy diagnostics from a small-system exact ground state.
Parameters¶
K : NDArray[np.float64]
Square oscillator-coupling matrix passed to the exact-diagonalisation
and gauge-vortex owners.
omega : NDArray[np.float64]
Oscillator-frequency vector with one entry per row of K.
Returns¶
TCBOResult Vortex-density, entropy inclusion-exclusion, Pauli-string, and polarization-fraction diagnostics.
Notes¶
The state-based fields use classical_exact_diag. The p_h1 field
delegates independently to measure_vortex_density, whose gauge-module
contract owns its own ground-state solve. Consequently this aggregator is a
small-system library utility, not a large-system or hardware pipeline.
__getattr__(name)
¶
Resolve and cache a public export from its original owning module.
Parameters¶
name Public export requested through this package.
Returns¶
Any Original object, including module-valued exports.
Raises¶
AttributeError If the name is undeclared or the original module lacks its attribute. ImportError If the owning module cannot be imported.
PGBO¶
scpn_quantum_control.pgbo
¶
PGBO quantum extensions: phase-geometry bridge.
PGBOResult
dataclass
¶
Quantum PGBO tensor result.
compute_pgbo_tensor(K, omega, epsilon=0.005)
¶
Compute the quantum geometric tensor Q_μν for K_ij parameters.
Parameters are the upper-triangle entries of K.
__getattr__(name)
¶
Resolve and cache a public export from its original owning module.
Parameters¶
name Public export requested through this package.
Returns¶
Any Original object, including module-valued exports.
Raises¶
AttributeError If the name is undeclared or the original module lacks its attribute. ImportError If the owning module cannot be imported.
L16¶
scpn_quantum_control.l16
¶
L16 quantum indicators and bounded heuristic director evidence.
L16DirectorEvidence
dataclass
¶
Complete functional L16 director evidence without stability promotion.
functional_passed
property
¶
Whether every bounded certificate and route gate passed.
action_diversity
property
¶
Whether the frozen real scenarios produced multiple actions.
__post_init__()
¶
Require the complete frozen suite and permanent promotion boundary.
to_payload()
¶
Return the digestable JSON payload without its integrity digest.
L16IndicatorCertificate
dataclass
¶
L16RouteEvidence
dataclass
¶
L16ScenarioSpec
dataclass
¶
L16DirectorPolicyError
¶
Bases: RuntimeError
Raised when the closed-loop execution policy refuses bounded L16 evaluation.
L16Result
dataclass
¶
Legacy L16 indicators and heuristic action label.
validate_l16_evidence(payload)
¶
Return fail-closed findings for one L16 director evidence payload.
write_l16_evidence(json_path, markdown_path, *, payload=None)
¶
Validate and atomically write real or independently supplied L16 evidence.
frozen_l16_scenarios()
¶
Return the three ordered small-system L16 director scenarios.
informative_l16_indicators(result)
¶
Name raw indicators that differ nontrivially from their invariant baseline.
l16_promotion_blockers(certificates)
¶
Return fixed claim boundaries plus findings from the supplied real certificates.
observer_inputs_from_l16(action, *, reason='')
¶
Map a legacy L16 action into the conservative observer interlock contract.
run_l16_director_suite(*, policy=None)
¶
Run complete bounded evidence and retain permanent promotion blockers.
run_l16_indicator_scenario(scenario, *, policy, backend=None)
¶
Execute and replay one frozen scenario under the shared execution policy.
compute_l16_lyapunov(K, omega, t=0.5)
¶
Compute the legacy L16 indicator bundle and weighted heuristic.
The returned stability_score name is retained for compatibility. It is
an uncalibrated weighted composite, not a Lyapunov exponent or stability
guarantee. Use the bounded L16 director product for policy gating and claim boundaries.
__getattr__(name)
¶
Resolve and cache a public export from its original owning module.
Parameters¶
name Public export requested through this package.
Returns¶
Any Original object, including module-valued exports.
Raises¶
AttributeError If the name is undeclared or the original module lacks its attribute. ImportError If the owning module cannot be imported.