Skip to content

Latest commit

 

History

History
2481 lines (1622 loc) · 97.3 KB

File metadata and controls

2481 lines (1622 loc) · 97.3 KB

API Reference

Top-Level Exports

import scpn_control

scpn_control.__version__       # "0.23.0"
scpn_control.FusionKernel      # Grad-Shafranov equilibrium solver
scpn_control.RUST_BACKEND      # True if Rust acceleration available
scpn_control.TokamakConfig     # Preset tokamak geometries
scpn_control.StochasticPetriNet
scpn_control.FusionCompiler
scpn_control.CompiledNet
scpn_control.NeuroSymbolicController
scpn_control.kuramoto_sakaguchi_step
scpn_control.order_parameter
scpn_control.KnmSpec
scpn_control.build_knm_paper27
scpn_control.UPDESystem
scpn_control.LyapunovGuard
scpn_control.RealtimeMonitor
scpn_control.PhysicsDebugAssistant

SCPN — AER Control Observation

scpn_control.scpn.observation adapts asynchronous Address-Event Representation spike streams into bounded controller features while preserving the existing mapping-based observation contract. The Python surface provides SpikeEvent, SpikeBuffer, rate/temporal/ISI decoders, and AERControlObservation.to_features(). NeuroSymbolicController.step() accepts either the existing Mapping[str, float] observation or an AERControlObservation; typed AER input is decoded through AERControlObservation.to_feature_mapping() before the same feature-injection path runs. When JSONL controller logging is enabled, the record includes the decoded obs mapping plus aer_admission metadata from SpikeBuffer.admission_report(). The matching Rust implementation lives in control_core::spike_buffer, with optional PyO3 bindings exposed as scpn_control_rs.PySpikeBuffer and scpn_control_rs.aer_decode_*. monotonic_input and out_of_order_event_count provide bounded ingress evidence. Observations may set require_monotonic=True to fail closed before controller injection if upstream AER timestamps violate the monotonic admission contract.

This is an ingress adapter and feature-decoding contract. It does not claim hardware AER signal integrity, target neuromorphic-device deployment, FPGA timing closure, or PCS admission without separate hardware evidence.

::: scpn_control.scpn.observation.SpikeEvent

::: scpn_control.scpn.observation.SpikeBuffer

::: scpn_control.scpn.observation.AERControlObservation

::: scpn_control.scpn.observation.decode_rate

::: scpn_control.scpn.observation.decode_temporal

::: scpn_control.scpn.observation.decode_isi


SCPN — Geometry-Neutral Replay Schema

scpn_control.scpn.geometry_neutral_replay publishes deterministic geometry-neutral replay reports and schema admission helpers. The v1.1 schema extends the v1 report with optional pulsed-shot context: UUID pulse IDs, capacitor initial energy, trigger timestamp, recovered energy, sorted shot-phase logs, FRC diagnostic scalars, and digest-bound AER admission metadata. Existing v1 reports remain loadable under the v1.1 schema bundle.

Use the dedicated Geometry-Neutral Replay guide for field semantics, example payloads, and claim boundaries.

::: scpn_control.scpn.geometry_neutral_replay.generate_report

::: scpn_control.scpn.geometry_neutral_replay.validate_report

::: scpn_control.scpn.geometry_neutral_replay.load_replay_schema

::: scpn_control.scpn.geometry_neutral_replay.register_v1_1_schema

::: scpn_control.scpn.geometry_neutral_replay.assert_v1_replay_loadable_under_v1_1_schema_bundle

::: scpn_control.scpn.geometry_neutral_replay.build_aer_admission_metadata

::: scpn_control.scpn.geometry_neutral_replay.attach_aer_admission_metadata

::: scpn_control.scpn.geometry_neutral_replay.save_geometry_neutral_replay_report

::: scpn_control.scpn.geometry_neutral_replay.load_geometry_neutral_replay_report


Control — Pulsed Scenario Scheduler v2

scpn_control.control.pulsed_scenario_scheduler_v2 owns the reusable pulsed-fusion lifecycle contract that MIF-CORE incubated as MIF-004. The scheduler models the adjacent state ring:

idle -> ramp_up -> flat_top -> burn -> expansion -> dump -> recharge -> cool_down -> idle

The Python surface provides the control-plane API and audit-log contract. The matching Rust kernel lives in control_control::pulsed_scenario for the compiled hot-path lane. When the optional extension is built, scpn_control_rs.PyPulsedScenarioScheduler exposes that Rust kernel directly to Python without changing the pure-Python API. All surfaces use the same state names, action names, guard thresholds, monotone timestamp checks, and transition reasons.

scpn_control.control.pulsed_scenario_scheduler is retained as the SCPN-MIF-CORE compatibility import and re-exports the v2 implementation. The finite-state topology is also captured in lean/SCPNControl/PulsedFSM.lean, including the liveness theorem pulsed_fsm_eventually_returns_to_idle.

The scheduler is a generic pulsed-reactor controller primitive. It is not a facility-validated PCS implementation by itself. Hardware timing, actuator mapping, capacitor-bank plant dynamics, and measured-shot validation remain separate admission surfaces.

::: scpn_control.control.pulsed_scenario_scheduler

::: scpn_control.control.pulsed_scenario_scheduler_v2.PulsedScenarioState

::: scpn_control.control.pulsed_scenario_scheduler_v2.PulsedScenarioAction

::: scpn_control.control.pulsed_scenario_scheduler_v2.PulsedScenarioSpec

::: scpn_control.control.pulsed_scenario_scheduler_v2.PulsedPlasmaTelemetry

::: scpn_control.control.pulsed_scenario_scheduler_v2.CapacitorBankTelemetry

::: scpn_control.control.pulsed_scenario_scheduler_v2.PulsedScenarioTransition

::: scpn_control.control.pulsed_scenario_scheduler_v2.PulsedScenarioCommand

::: scpn_control.control.pulsed_scenario_scheduler_v2.PulsedScenarioScheduler


Control — Capacitor Bank State Model

scpn_control.control.capacitor_bank_state owns the CONTROL-side bounded series-RLC capacitor-bank contract for pulsed-shot admission. It mirrors the MIF-CORE MIF-005 capacitor-bank mathematics at the control boundary: damping regime classification, closed-form free response, Crank-Nicolson stepping, midpoint-sampled discharge waveforms, conservative feasibility guards, and constant-power recharge projection.

The state equation is:

d/dt [v_C, i]^T = [[0, -1/C], [1/L, -R/L]] [v_C, i]^T + [-i_load/C, 0]^T

where C is capacitance in farads, L is inductance in henries, R is series resistance in ohms, v_C is capacitor voltage in volts, i is series current in amperes, and i_load is the prescribed external load current. The numerical step uses a Crank-Nicolson update so natural-response validation can compare against the analytical underdamped, critical, and overdamped solutions.

CapacitorBank.telemetry() adapts the state model to PulsedScenarioScheduler v2 by emitting scheduler-compatible capacitor-bank telemetry with absolute voltage magnitude, declared voltage limit, and stored energy. The matching Rust kernel lives in control_control::capacitor_bank. When the optional extension is built, scpn_control_rs.PyCapacitorBankModel, scpn_control_rs.PyCapacitorBankSpec, and scpn_control_rs.capacitor_bank_free_response() expose the compiled surface directly to Python.

scpn_control.control.capacitor_bank is retained as the SCPN-MIF-CORE compatibility import and re-exports the state-model implementation without duplicating the RLC mathematics.

CapacitorBank.discharge() now reports an explicit total RLC energy ledger for admission and replay: initial total stored energy, remaining total stored energy, remaining capacitor electric energy, remaining inductor magnetic energy, integrated ohmic loss, integrated prescribed-load extraction, absolute residual, relative residual, and a boolean pass/fail flag. The residual contract is:

energy_initial - energy_remaining
  = resistive_loss + load_energy + energy_balance_residual

The ledger uses midpoint quantities from the same Crank-Nicolson step that advances the state, so the residual is a numerical consistency check on the CONTROL admission model rather than a facility hardware protection claim. CapacitorBankState.energy_J remains scheduler-facing capacitor electric energy only.

This model is a bounded control admission and scheduling primitive. It is not a validated facility capacitor-bank driver, insulation model, switch model, or hardware interlock implementation. Facility deployment still requires target hardware timing, protection relays, isolation evidence, and shot-matched validation artefacts.

::: scpn_control.control.capacitor_bank

::: scpn_control.control.capacitor_bank_state.RLCRegime

::: scpn_control.control.capacitor_bank_state.CapacitorBankSpec

::: scpn_control.control.capacitor_bank_state.CapacitorBankState

::: scpn_control.control.capacitor_bank_state.PulseSpec

::: scpn_control.control.capacitor_bank_state.EnergyReport

::: scpn_control.control.capacitor_bank_state.free_response

::: scpn_control.control.capacitor_bank_state.CapacitorBank


Control — Pulsed-Shot MPC Admission Adapter

scpn_control.control.fusion_neural_mpc.PulsedShotMPCAdapter wraps the CONTROL-owned gradient MPC surface and admits its first action through the pulsed-scenario scheduler and capacitor-bank feasibility guard. It is a control-boundary adapter over existing MPC output, not a new equilibrium solver or a duplicate solver lane.

The adapter applies three deterministic checks:

  • Non-burn scheduler states replace selected burn-action components with the configured safe action.
  • burn state evaluates a PulseSpec against CapacitorBank.feasibility() unless the caller disables that policy.
  • Every step records an explainable decision dictionary with scheduler state, capacitor feasibility text, constraint slack, MPC objective, whether a safe action was applied, and a digest-bound admission evidence payload.

The matching Rust kernel lives in control_control::mpc::MPController as plan_pulsed(). When the optional PyO3 extension is rebuilt, scpn_control_rs.PyMpcController.plan_pulsed() exposes the same admission fields to Python, including evidence_schema_version, action_sha256, safe_action_sha256, burn_action_mask_sha256, peak_current_A, and admission_digest.

Use the dedicated Pulsed MPC Adapter guide for examples, runtime boundaries, and benchmark evidence commands.

::: scpn_control.control.fusion_neural_mpc.PulsedShotMPCDecision

::: scpn_control.control.fusion_neural_mpc.PulsedShotMPCAdapter


Control — Multi-Shot Campaign Orchestrator

scpn_control.control.multi_shot_campaign runs repeated pulsed-shot admission over the scheduler, capacitor-bank telemetry, and replay v1.1 metadata contracts. It accepts explicit shot telemetry, records command and transition logs, requires the canonical pulsed lifecycle by default, and emits a digest-bound campaign report. When supplied, per-shot pulsed_mpc_admission_digest values are validated as lowercase SHA-256 digests and preserved in the campaign report plus replay v1.1 extension fields.

The matching Rust kernel lives in control_control::multi_shot_campaign. When the optional PyO3 extension is rebuilt, scpn_control_rs.PyMultiShotCampaignOrchestrator.run_table() exposes the Rust surface through table-shaped NumPy inputs, including optional per-shot pulsed_mpc_admission_digests.

Use the dedicated Multi-Shot Campaign guide for examples, claim boundaries, and benchmark commands.

Release admission is handled by validation.validate_multi_shot_campaign_evidence. The gate admits the Python/PyO3 benchmark report and the Rust benchmark report only when both carry the pulsed-MPC digest chain, benchmark context, stable SHA-256 payload seals, and a complete Python, PyO3, and Rust surface set. The top-level scpn-control validate command runs this gate by default before a release evidence JSON can be admitted.

::: scpn_control.control.multi_shot_campaign.CampaignShotSample

::: scpn_control.control.multi_shot_campaign.CampaignShotPlan

::: scpn_control.control.multi_shot_campaign.CampaignCommandLog

::: scpn_control.control.multi_shot_campaign.CampaignShotResult

::: scpn_control.control.multi_shot_campaign.MultiShotCampaignOrchestrator


Control — PREEMPT_RT Runtime Admission

scpn_control.core.runtime_admission emits a schema-versioned admission report before native hardware-campaign execution. It binds the observed Linux kernel, PREEMPT_RT evidence, current process affinity, requested execution cores, scheduler policy, CPU governors, heartbeat configuration, and memory-lock limits to the campaign summary. run-hardware-campaign --runtime-admission-policy require fails closed before native execution if the host is not production-admissible.

The optional PyO3 counterpart scpn_control_rs.runtime_admission_snapshot() exposes native-side kernel/core parsing when the Rust extension is installed. validation.validate_runtime_admission_evidence admits persisted runtime-admission benchmark reports into the top-level release gate only when the report carries command, CPU-affinity, host-load, isolation, latency, SHA-256 payload, and production-claim-boundary evidence.

Use the dedicated PREEMPT_RT Runtime Admission guide for policy semantics and operator examples.

::: scpn_control.core.runtime_admission.RuntimeAdmissionRequest

::: scpn_control.core.runtime_admission.RuntimeAdmissionProbe

::: scpn_control.core.runtime_admission.collect_runtime_admission

::: scpn_control.core.runtime_admission.evaluate_runtime_admission


Validation — Benchmark Regression Gates

validation/validate_benchmark_regression_gates.py admits persisted benchmark evidence before the preflight gate accepts a regression baseline. The gate does not run benchmarks and does not create timing evidence. It validates validation/reports/benchmark_regression_gates.json against the referenced latency reports, SHA-256 digests, metric paths, bounded thresholds, sample counts, hardware-context metadata, and explicit non-HIL claim boundaries.

The gate is intended to catch stale, tampered, overclaimed, or regressed local benchmark evidence before release preflight continues. Hardware-in-the-loop, target-device, cloud-GPU, or plant real-time claims remain blocked until those specific benchmark artefacts are generated and admitted separately.


Core — Native C++ Solver Bridge

scpn_control.core.hpc_bridge exposes the optional native Grad-Shafranov solver bridge. Native compilation is disabled unless SCPN_ALLOW_NATIVE_BUILD=1 is set. When enabled, the bridge admits only the package-local solver.cpp whose SHA-256 digest matches solver_manifest.json, resolves the compiler to an absolute regular executable, strips dynamic-loader injection variables from the build environment, rejects symlinked solver inputs and output targets, compiles to a temporary package-local file, and publishes the shared library atomically after the compiler produced a regular file.

The source and checksum manifest are shipped as scpn_control.core package data. Compiled bin/libscpn_solver.so or bin/scpn_solver.dll outputs are operator-local build products and are not committed.

External runtime solver libraries remain blocked unless SCPN_ALLOW_EXTERNAL_SOLVER_LIB=1 is set for a vetted absolute path. The default path searches package-local solver locations only.


Physics Debug Assistance

scpn_control.physics_debug provides a local-first advisory assistant for physics validation gaps. The default provider policy admits loopback endpoints only; facility or external gateways must be explicitly allowlisted. build_local_provider() supplies loopback profiles for common onsite gateway protocols: chat-completions-compatible, Ollama-style chat, direct JSON, and text-generation endpoints. Reports are schema-versioned advisory evidence with secret redaction, falsifiable hypothesis checks, campaign risk controls, and risk-bound prompt-injection neutralization for untrusted evidence text before provider prompting. Prompt-guard findings are recorded in the tamper-evident payload digest. build_guardrail_provider() adds an optional hallucination guardrail gateway with a director-ai default profile and explicit alternate profiles for lab-owned guardrail solutions. Guardrail block decisions fail closed before report persistence; allow findings are bound into the report digest together with the SHA-256 digest of the reviewed provider draft. The guardrail request also binds the provider metadata, safety policy, and guardrail policy digests so reviews cannot be replayed across another provider or relaxed policy. High-severity guardrail findings must use block actions, and risk controls must meet the configured guardrail policy before persistence. They are not validated physics truth, controller-parameter promotion, or facility safety approval. run_provider_quorum() runs multiple providers in local-first order and admits only hypotheses corroborated by the required provider count over the same gap and evidence set. PhysicsDebugSafetyPolicy binds the human-review requirement, caps advisory confidence, and rejects provider text that attempts controller promotion, actuation, review bypass, or approval claims.

::: scpn_control.physics_debug.ProviderPolicy

::: scpn_control.physics_debug.PhysicsDebugGuardrailPolicy

::: scpn_control.physics_debug.PhysicsDebugEvidence

::: scpn_control.physics_debug.PhysicsDebugGap

::: scpn_control.physics_debug.PhysicsDebugSafetyPolicy

::: scpn_control.physics_debug.HTTPChatProvider

::: scpn_control.physics_debug.PhysicsDebugGuardrailProvider

::: scpn_control.physics_debug.PhysicsDebugAssistant

::: scpn_control.physics_debug.build_local_provider

::: scpn_control.physics_debug.build_guardrail_provider

::: scpn_control.physics_debug.build_physics_debug_report

::: scpn_control.physics_debug.run_provider_quorum

::: scpn_control.physics_debug.validate_physics_debug_report

::: scpn_control.physics_debug.validate_physics_debug_quorum_report

::: scpn_control.physics_debug.write_physics_debug_report

::: scpn_control.physics_debug.write_physics_debug_quorum_report


Control — Federated Disruption Prediction

scpn_control.control.federated_disruption supports FedAvg and FedProx training across named tokamak clients without centralising facility arrays. create_facility_clients_from_arrays() is the production ingestion boundary for per-facility X_train, y_train, X_test, and y_test arrays. It enforces the shared 8-feature disruption contract and binary labels before a client joins the federation.

DifferentialPrivacyConfig enables facility-update clipping, Gaussian noise, and a serialisable privacy ledger. The shipped benchmark validation/benchmark_federated_disruption.py publishes deterministic synthetic multi-facility evidence in validation/reports/federated_disruption_benchmark.json and validation/reports/federated_disruption_benchmark.md. Those artefacts test federation, heterogeneity, and differential privacy contracts; they do not claim measured cross-facility validation without external shot databases.

::: scpn_control.control.federated_disruption.DifferentialPrivacyConfig

::: scpn_control.control.federated_disruption.PrivacyLedgerEntry

::: scpn_control.control.federated_disruption.FacilityBenchmarkSummary

::: scpn_control.control.federated_disruption.FederatedConfig

::: scpn_control.control.federated_disruption.MachineClient

::: scpn_control.control.federated_disruption.FederatedServer

::: scpn_control.control.federated_disruption.create_facility_clients_from_arrays

::: scpn_control.control.federated_disruption.run_synthetic_multifacility_benchmark


Control — Quantum Disruption Bridge

scpn_control.control.quantum_disruption_bridge is a fail-closed facade for optional quantum-enhanced disruption prediction. Quantum circuit and provider ownership stays in scpn-quantum-control; SCPN-CONTROL owns the control feature contract, lazy optional import boundary, bounded claim metadata, and tamper-evident advisory reports. The bridge maps the CONTROL 8-feature disruption vector to the ITER 11-feature contract only when missing ITER fields are either supplied explicitly or declared as bounded centre defaults. Reports are not facility validation, controller promotion, or publication-safe evidence without external disruption databases and benchmark artefacts.

quantum_disruption_kernel_matrix() emits a bounded amplitude-encoding kernel report with symmetry, diagonal, and [0, 1] admission checks. The callable quantum owner path uses scpn_quantum_control.control.q_disruption_iter lazily; when that optional dependency is unavailable the report fails closed with status="quantum-unavailable" and no quantum score. Every bridge report also records advisory admission evidence: CONTROL feature digests, ITER mapping digests, default-use reasons, and the external evidence still required before facility or publication claims are admissible. Bridge and kernel reports carry schema-versioned advisory certificates that bind report kind, repository ownership, claim boundary, downstream non-admission policy, and the content digest before the outer payload digest is accepted. The facade also publishes a machine-readable dependency contract that names the scpn-quantum-control backend module, required classifier surface, Qiskit core dependencies, optional provider dependency families, report schemas, feature contract, and non-admission policy for future backend hardening. Generated bridge and kernel reports embed that dependency contract and bind its digest into the advisory certificate so archived reports cannot be replayed against a different quantum backend contract. When the optional backend exposes its own scpn_control_bridge_dependency_contract() callable, CONTROL compares it against the expected contract, records backend-contract attestation evidence, and fails closed before report creation if the backend advertises a conflicting contract. Bridge reports also include schema-versioned advisory decision evidence that records whether the score came from the quantum backend or the classical fallback, applies deterministic low/elevated/high risk-band thresholds, records backend-contract validation state, fixes the control action to blocked, and binds the decision digest into the advisory certificate.

::: scpn_control.control.quantum_disruption_bridge.QuantumDisruptionBridgeConfig

::: scpn_control.control.quantum_disruption_bridge.QuantumFeatureMapping

::: scpn_control.control.quantum_disruption_bridge.map_control_features_to_iter

::: scpn_control.control.quantum_disruption_bridge.quantum_disruption_kernel_matrix

::: scpn_control.control.quantum_disruption_bridge.quantum_disruption_dependency_contract

::: scpn_control.control.quantum_disruption_bridge.run_quantum_disruption_bridge

::: scpn_control.control.quantum_disruption_bridge.validate_quantum_disruption_dependency_contract

::: scpn_control.control.quantum_disruption_bridge.validate_quantum_disruption_bridge_report

::: scpn_control.control.quantum_disruption_bridge.validate_quantum_disruption_kernel_report


Core — Physics Solvers

FusionKernel

FusionKernel validates its JSON configuration before grid construction: the root must be an object, duplicate JSON keys are rejected, dimensions and grid resolution must be physical, physics.plasma_current_target must be positive finite, and physics.vacuum_permeability must be positive finite when supplied.

::: scpn_control.core.fusion_kernel.FusionKernel

Global Design Scanner

GlobalDesignExplorer provides the bounded scalar design metrics consumed by the disruption-contract episode path. It estimates Q, fusion power, neutron wall load, and a relative cost proxy from validated tokamak design inputs.

::: scpn_control.core.global_design_scanner.GlobalDesignExplorer

::: scpn_control.core.global_design_scanner.DesignScannerConfig

TokamakConfig

::: scpn_control.core.tokamak_config.TokamakConfig

TransportSolver

::: scpn_control.core.integrated_transport_solver.TransportSolver

Plasma Power Terms

::: scpn_control.core.plasma_power_terms.bosch_hale_dt_reactivity

::: scpn_control.core.plasma_power_terms.tungsten_radiation_rate

::: scpn_control.core.plasma_power_terms.bremsstrahlung_power_density

Radial Diffusion Numerics

::: scpn_control.core.radial_diffusion.thomas_solve

::: scpn_control.core.radial_diffusion.explicit_diffusion_rhs

::: scpn_control.core.radial_diffusion.build_cn_tridiag

Anomalous Transport Coefficient Models

::: scpn_control.core.anomalous_transport.gyro_bohm_chi_profile

::: scpn_control.core.anomalous_transport.gk_flux_surface_transport

Auxiliary Heating Source Deposition

::: scpn_control.core.aux_heating.aux_heating_source_profiles

Multi-Ion Species Evolution

::: scpn_control.core.species_evolution.evolve_multi_ion_species

::: scpn_control.core.species_evolution.SpeciesEvolutionResult

Runtime State Sanitization

::: scpn_control.core.runtime_sanitization.sanitize_with_fallback

Transport Radial-Grid Geometry

::: scpn_control.core.transport_geometry.rho_volume_element

::: scpn_control.core.transport_geometry.estimate_plasma_surface_area_m2

::: scpn_control.core.transport_geometry.is_canonical_radial_grid

::: scpn_control.core.transport_geometry.canonical_radial_grid

Scaling Laws

::: scpn_control.core.scaling_laws.ipb98y2_tau_e

::: scpn_control.core.scaling_laws.compute_h_factor

GEQDSK I/O

::: scpn_control.core.eqdsk.GEqdsk

::: scpn_control.core.eqdsk.read_geqdsk

::: scpn_control.core.eqdsk.write_geqdsk

Uncertainty Quantification

::: scpn_control.core.uncertainty.quantify_uncertainty

::: scpn_control.core.uncertainty.quantify_full_chain

::: scpn_control.core.uncertainty.UQClaimEvidence

::: scpn_control.core.uncertainty.uq_claim_evidence

::: scpn_control.core.uncertainty.assert_uq_calibrated_claim_admissible

::: scpn_control.core.uncertainty.save_uq_claim_evidence

JAX-Accelerated Transport Primitives

Requires pip install "scpn-control[jax]". GPU execution automatic when jaxlib has CUDA/ROCm.

::: scpn_control.core.jax_solvers.thomas_solve

::: scpn_control.core.jax_solvers.diffusion_rhs

::: scpn_control.core.jax_solvers.crank_nicolson_step

::: scpn_control.core.jax_solvers.batched_crank_nicolson

Differentiable Transport Facade

Requires pip install "scpn-control[jax]" for gradient evaluation. The NumPy path is deterministic for parity checks and non-JAX deployments, but transport_loss_gradient() fails closed without JAX. transport_parameter_gradients() extends the same traced Crank-Nicolson contract to source schedules, returning JAX gradients for both transport coefficients and additive heating, fuelling, or impurity-source inputs. differentiable_transport_rollout() advances a bounded multi-step source schedule with the same four-channel boundary contract. transport_rollout_source_gradients() returns fail-closed JAX gradients for that full source schedule so controller tuning can optimise time-distributed heating, fuelling, and impurity-source inputs without finite differences. The rollout gradient path keeps the loss inside the traced JAX graph and enables JAX x64 before importing jax.numpy, so persisted dtype evidence is not silently downgraded. audit_transport_rollout_source_gradients() and assert_transport_rollout_source_gradients_consistent() compare those rollout gradients against sampled NumPy finite-difference perturbations. audit_transport_parameter_gradients() and assert_transport_parameter_gradients_consistent() compare those JAX gradients against sampled independent finite-difference perturbations before controller-tuning admission. transport_coefficients_from_neural_closure() maps bounded neural transport closure outputs into the four-channel coefficient order used by the facade: electron heat, ion heat, electron particle diffusivity, and a declared impurity diffusivity fraction. gyrokinetic_transport_closure_profiles() wraps the reduced gyrokinetic transport profile evaluator as bounded closure provenance, and transport_coefficients_from_gyrokinetic_closure() maps that closure into the same four-channel coefficient order without promoting the reduced GK model to an externally validated transport claim. transport_campaign_metadata() records backend, dtype, radial grid, timestep, boundary conditions, closure provenance, gradient tolerance, and optional equilibrium-grid shape for reproducible controller-tuning campaigns. save_transport_campaign_metadata() and load_transport_campaign_metadata() persist the same contract as schema-versioned JSON and fail closed on malformed or physically inconsistent replay metadata. assert_transport_campaign_metadata_replay() compares archived campaign metadata with a candidate setup and raises on backend, grid, boundary, closure, gradient-tolerance, or equilibrium-shape drift before controller tuning reruns. transport_differentiability_evidence() and assert_transport_differentiability_claim_admissible() add a tamper-evident admission envelope over campaign metadata and gradient-audit results. That envelope requires JAX backend evidence, passed sampled finite-difference gradient audit, stable SHA-256 digests for the campaign and audit payloads, and an optional link to the safety-critical controller proof artifact digest. Admission revalidates finite non-negative audit losses and errors, tolerance agreement with campaign metadata, unique in-domain sampled audit indices, pass/fail consistency with maximum audit error, and ordered latency percentiles before persisted controller-tuning evidence is accepted. Latency reports also bind runtime provenance for later CPU/GPU comparison: Python version, platform, machine class, JAX and jaxlib versions, default backend, visible JAX devices, and x64 state. transport_full_fidelity_readiness_evidence() and assert_transport_full_fidelity_claim_ready() add the stricter promotion gate for full-fidelity differentiable-transport claims. The gate binds campaign metadata, one-step gradient-latency evidence, rollout source-gradient latency evidence, audit digests, controller formal-proof digests, equilibrium-coupled metadata, and an admitted external reference artifact. The repository benchmark binds the canonical payload SHA-256 from validation/reports/scpn_z3_formal.json when that bounded Z3 formal report is present and passing. Without all of those inputs the claim remains bounded local differentiability evidence. equilibrium_weighted_transport_rollout_tracking_loss() extends the optional Grad-Shafranov flux-map weighting from one transport step to a full source rollout. equilibrium_weighted_transport_rollout_source_gradient() returns fail-closed JAX gradients with respect to both the source schedule and the equilibrium flux map for controller-tuning studies.

::: scpn_control.core.differentiable_transport.differentiable_transport_step

::: scpn_control.core.differentiable_transport.transport_tracking_loss

::: scpn_control.core.differentiable_transport.transport_loss_gradient

::: scpn_control.core.differentiable_transport.transport_parameter_gradients

::: scpn_control.core.differentiable_transport.TransportParameterGradients

::: scpn_control.core.differentiable_transport.differentiable_transport_rollout

::: scpn_control.core.differentiable_transport.transport_rollout_tracking_loss

::: scpn_control.core.differentiable_transport.transport_rollout_source_gradients

::: scpn_control.core.differentiable_transport.TransportRolloutSourceGradients

::: scpn_control.core.differentiable_transport.audit_transport_rollout_source_gradients

::: scpn_control.core.differentiable_transport.assert_transport_rollout_source_gradients_consistent

::: scpn_control.core.differentiable_transport.TransportRolloutGradientAudit

::: scpn_control.core.differentiable_transport.audit_transport_parameter_gradients

::: scpn_control.core.differentiable_transport.assert_transport_parameter_gradients_consistent

::: scpn_control.core.differentiable_transport.TransportGradientAudit

::: scpn_control.core.differentiable_transport.benchmark_transport_parameter_gradient_latency

::: scpn_control.core.differentiable_transport.TransportGradientLatencyReport

::: scpn_control.core.differentiable_transport.save_transport_gradient_latency_report

::: scpn_control.core.differentiable_transport.benchmark_transport_rollout_source_gradient_latency

::: scpn_control.core.differentiable_transport.TransportRolloutGradientLatencyReport

::: scpn_control.core.differentiable_transport.save_transport_rollout_gradient_latency_report

::: scpn_control.core.differentiable_transport.transport_coefficients_from_neural_closure

::: scpn_control.core.differentiable_transport.gyrokinetic_transport_closure_profiles

::: scpn_control.core.differentiable_transport.transport_coefficients_from_gyrokinetic_closure

::: scpn_control.core.differentiable_transport.GyrokineticTransportClosureResult

::: scpn_control.core.differentiable_transport.TransportCampaignMetadata

::: scpn_control.core.differentiable_transport.transport_campaign_metadata

::: scpn_control.core.differentiable_transport.save_transport_campaign_metadata

::: scpn_control.core.differentiable_transport.load_transport_campaign_metadata

::: scpn_control.core.differentiable_transport.assert_transport_campaign_metadata_replay

::: scpn_control.core.differentiable_transport.TransportDifferentiabilityEvidence

::: scpn_control.core.differentiable_transport.transport_differentiability_evidence

::: scpn_control.core.differentiable_transport.assert_transport_differentiability_claim_admissible

::: scpn_control.core.differentiable_transport.TransportFullFidelityReadinessEvidence

::: scpn_control.core.differentiable_transport.transport_full_fidelity_readiness_evidence

::: scpn_control.core.differentiable_transport.assert_transport_full_fidelity_claim_ready

::: scpn_control.core.differentiable_transport.equilibrium_radial_weights

::: scpn_control.core.differentiable_transport.equilibrium_weighted_transport_tracking_loss

::: scpn_control.core.differentiable_transport.equilibrium_weighted_transport_loss_gradient

::: scpn_control.core.differentiable_transport.EquilibriumWeightedTransportGradient

::: scpn_control.core.differentiable_transport.equilibrium_weighted_transport_rollout_tracking_loss

::: scpn_control.core.differentiable_transport.equilibrium_weighted_transport_rollout_source_gradient

::: scpn_control.core.differentiable_transport.EquilibriumWeightedTransportRolloutGradient

End-to-End Differentiable Scenario

differentiable_scenario_gradient() couples a bounded analytic Solov'ev-form equilibrium parametrisation to the differentiable transport rollout, so a controller-tuning loss is differentiable with respect to both the source schedule and the equilibrium shape parameters. The flux parametrisation is a differentiable equilibrium surface, not a Grad-Shafranov PDE solve. Gradient APIs fail closed without JAX, and assert_scenario_claim_admissible() keeps a full-fidelity claim bounded until the gradient audit, latency evidence, and physics-traceability checks pass. Persisted readiness reports are validated with validation.validate_differentiable_scenario.validate_differentiable_scenario_report(); the checked-in report remains blocked on physics traceability rather than promoting the analytic surface to a facility-grade scenario claim.

::: scpn_control.core.differentiable_scenario.scenario_equilibrium_flux

::: scpn_control.core.differentiable_scenario.differentiable_scenario_loss

::: scpn_control.core.differentiable_scenario.differentiable_scenario_gradient

::: scpn_control.core.differentiable_scenario.DifferentiableScenarioGradient

::: scpn_control.core.differentiable_scenario.audit_differentiable_scenario_gradient

::: scpn_control.core.differentiable_scenario.assert_differentiable_scenario_gradient_consistent

::: scpn_control.core.differentiable_scenario.DifferentiableScenarioGradientAudit

::: scpn_control.core.differentiable_scenario.scenario_campaign_metadata

::: scpn_control.core.differentiable_scenario.ScenarioCampaignMetadata

::: scpn_control.core.differentiable_scenario.differentiable_scenario_readiness_evidence

::: scpn_control.core.differentiable_scenario.assert_scenario_claim_admissible

::: scpn_control.core.differentiable_scenario.ScenarioReadinessEvidence

Neural Equilibrium

NeuralEquilibriumAccelerator.pretrain_from_synthetic_equilibria() trains JAX-compatible PCA plus MLP weights on bounded synthetic Solovev-like equilibria for pretraining. The corresponding real EFIT fine-tuning entry point fine_tune_from_efit_reconstructions() fails closed unless the persisted P-EFIT or documented-public-reference artefact validator passes.

::: scpn_control.core.neural_equilibrium.NeuralEquilibriumAccelerator

::: scpn_control.core.neural_equilibrium.NeuralEquilibriumClaimEvidence

::: scpn_control.core.neural_equilibrium.generate_synthetic_equilibrium_dataset

::: scpn_control.core.neural_equilibrium.neural_equilibrium_claim_evidence

::: scpn_control.core.neural_equilibrium.assert_neural_equilibrium_facility_claim_admissible

::: scpn_control.core.neural_equilibrium.save_neural_equilibrium_claim_evidence

::: scpn_control.core.neural_equilibrium.pretrain_neural_equilibrium_synthetic

::: scpn_control.core.neural_equilibrium.PretrainingResult

::: scpn_control.core.neural_equilibrium.SyntheticEquilibriumCampaign

Equilibrium Shape & Profile Metrics

Reusable, reconstruction-agnostic extraction of macroscopic descriptors (R0/minor radius/elongation/triangularity, li(3), poloidal beta, and q95) from a poloidal-flux map and the fitted p'/FF' profiles. Used by the real-time EFIT inverse and shareable by the free-boundary kernel and kinetic EFIT. The poloidal field uses the per-radian convention B_pol = |grad psi| / R (Ampere-consistent); q95 requires contourpy for the flux-surface contour.

::: scpn_control.core.equilibrium_shape.EquilibriumShape

::: scpn_control.core.equilibrium_shape.compute_equilibrium_shape

::: scpn_control.core.equilibrium_shape.boundary_geometry

::: scpn_control.core.equilibrium_shape.poloidal_field

::: scpn_control.core.equilibrium_shape.internal_inductance

::: scpn_control.core.equilibrium_shape.poloidal_beta

::: scpn_control.core.equilibrium_shape.safety_factor_q95

::: scpn_control.core.equilibrium_shape.cylindrical_q95

::: scpn_control.core.equilibrium_shape.pressure_grid

::: scpn_control.core.equilibrium_shape.plasma_boundary

::: scpn_control.core.equilibrium_shape.largest_flux_contour

JAX-Accelerated Neural Equilibrium

Requires pip install "scpn-control[jax]". GPU and autodiff via jax.grad.

::: scpn_control.core.jax_neural_equilibrium.jax_neural_eq_predict

::: scpn_control.core.jax_neural_equilibrium.jax_neural_eq_predict_batched

::: scpn_control.core.jax_neural_equilibrium.load_weights_as_jax

Neural Transport

cross_validate_neural_transport() benchmarks the active surrogate against the analytic critical-gradient reference across fixed regime cases and a canonical profile, so shipped weights can be checked against a deterministic local baseline instead of only reporting synthetic training RMSE.

neural_transport_closure_profiles() packages profile transport coefficients for controller and differentiable-transport coupling. It validates finite strictly ordered profile inputs, fails closed when neural weights are required but unavailable, and records whether coefficients came from loaded weights or the analytic fallback.

::: scpn_control.core.neural_transport.NeuralTransportModel

::: scpn_control.core.neural_transport.NeuralTransportClosureResult

::: scpn_control.core.neural_transport.NeuralTransportClaimEvidence

::: scpn_control.core.neural_transport.neural_transport_closure_profiles

::: scpn_control.core.neural_transport.cross_validate_neural_transport

::: scpn_control.core.neural_transport.neural_transport_claim_evidence

::: scpn_control.core.neural_transport.assert_neural_transport_quantitative_claim_admissible

::: scpn_control.core.neural_transport.save_neural_transport_claim_evidence

MHD Stability

::: scpn_control.core.stability_mhd.run_full_stability_check

IMAS Adapter

::: scpn_control.core.imas_adapter.EquilibriumIDS

::: scpn_control.core.imas_adapter.from_geqdsk

::: scpn_control.core.imas_adapter.from_kernel

HPC Bridge

HPCBridge loads compiled Grad-Shafranov solver libraries only from absolute dynamic-library paths. Package-local solver libraries are trusted by default. External paths provided through SCPN_SOLVER_LIB require the additional operator gate SCPN_ALLOW_EXTERNAL_SOLVER_LIB=1; without that gate the bridge fails closed before calling the dynamic loader.

::: scpn_control.core.hpc_bridge.HPCBridge

Gyrokinetic Transport (v0.16.0)

::: scpn_control.core.gyrokinetic_transport.GyrokineticTransportModel

GK Solver Interface (v0.17.0)

::: scpn_control.core.gk_interface.GKSolverBase

::: scpn_control.core.gk_interface.GKLocalParams

::: scpn_control.core.gk_interface.GKOutput

Native Linear GK Solver (v0.17.0)

::: scpn_control.core.gk_eigenvalue.solve_linear_gk

::: scpn_control.core.gk_quasilinear.quasilinear_fluxes_from_spectrum

GK Hybrid Validation (v0.17.0)

::: scpn_control.core.gk_ood_detector.OODDetector

::: scpn_control.core.gk_scheduler.GKScheduler

::: scpn_control.core.gk_corrector.GKCorrector

Ballooning Solver (v0.16.0)

::: scpn_control.core.ballooning_solver.BallooningEquation

::: scpn_control.core.ballooning_solver.BallooningStabilityAnalysis

::: scpn_control.core.ballooning_solver.find_marginal_stability

Current Diffusion (v0.16.0)

::: scpn_control.core.current_diffusion.CurrentDiffusionSolver

Current Drive (v0.16.0)

::: scpn_control.core.current_drive.ECCDSource

::: scpn_control.core.current_drive.NBISource

::: scpn_control.core.current_drive.CurrentDriveMix

NTM Dynamics (v0.16.0)

::: scpn_control.core.ntm_dynamics.RationalSurface

::: scpn_control.core.ntm_dynamics.NTMIslandDynamics

::: scpn_control.core.ntm_dynamics.NTMController

::: scpn_control.core.ntm_dynamics.eccd_stabilization_factor

::: scpn_control.core.ntm_dynamics.find_rational_surfaces

::: scpn_control.core.ntm_dynamics.bootstrap_from_local

Sawtooth Model (v0.16.0)

::: scpn_control.core.sawtooth.SawtoothCycler

::: scpn_control.core.sawtooth.kadomtsev_crash

SOL Model (v0.16.0)

::: scpn_control.core.sol_model.TwoPointSOL

Integrated Scenario (v0.16.0)

::: scpn_control.core.integrated_scenario.IntegratedScenarioSimulator

::: scpn_control.core.integrated_scenario.audit_scenario_coupling

::: scpn_control.core.integrated_scenario.save_scenario_coupling_report

::: scpn_control.core.integrated_scenario.iter_baseline_scenario

::: scpn_control.control.closed_loop_scenario.run_integrated_scenario_closed_loop

::: scpn_control.control.closed_loop_scenario.closed_loop_scenario_result_to_dict


SCPN — Petri Net Compiler

StochasticPetriNet

verify_liveness() reports random-campaign transition-fire coverage only when the sampled Petri-net walk also preserves finite [0, 1] markings before any controller-style clipping. If a firing step produces an out-of-range or non-finite marking, the report includes marking_bounds_valid=false, records the first violating transition, and returns live=false.

::: scpn_control.scpn.structure.StochasticPetriNet

Formal Verification

FormalPetriNetVerifier uses exact explicit-state reachability over the compiled Petri-net transition relation. backend="auto" records that explicit-state backend and does not relabel the result as z3 just because the optional solver package is importable. backend="z3" is an explicit opt-in and requires the optional z3-solver package; SMT-specific report artefacts remain on the separate z3 model-checking surface below.

::: scpn_control.scpn.formal_verification.FormalPetriNetVerifier

::: scpn_control.scpn.formal_verification.verify_formal_contracts

::: scpn_control.scpn.formal_verification.PlaceInvariant

::: scpn_control.scpn.formal_verification.CTLFormula

::: scpn_control.scpn.formal_verification.LTLFormula

::: scpn_control.scpn.formal_verification.AlwaysBounded

::: scpn_control.scpn.formal_verification.AlwaysEventuallyMarked

::: scpn_control.scpn.formal_verification.EventuallyFires

::: scpn_control.scpn.formal_verification.FireLeadsToMarking

::: scpn_control.scpn.formal_verification.NeverCoMarked

Formal Safety Certificate

The bounded safety certificate captures a formal verification report together with its admission policy and an optional artifact binding; the bundle aggregates independent certificates for a controller release gate. Every payload is schema-versioned, self-digested, and fail-closed.

::: scpn_control.scpn.formal_safety_certificate.SafetyCertificatePolicy

::: scpn_control.scpn.formal_safety_certificate.SafetyCertificateBundlePolicy

::: scpn_control.scpn.formal_safety_certificate.build_safety_certificate_payload

::: scpn_control.scpn.formal_safety_certificate.build_safety_certificate_bundle_payload

::: scpn_control.scpn.formal_safety_certificate.build_safety_certificate_bundle_artifact

::: scpn_control.scpn.formal_safety_certificate.generate_safety_certificate

::: scpn_control.scpn.formal_safety_certificate.validate_safety_certificate_payload

::: scpn_control.scpn.formal_safety_certificate.validate_safety_certificate_bundle_payload

::: scpn_control.scpn.formal_safety_certificate.validate_safety_certificate_bundle_artifact

::: scpn_control.scpn.formal_safety_certificate.admit_safety_certificate_bundle_artifact

::: scpn_control.scpn.formal_safety_certificate.write_safety_certificate

::: scpn_control.scpn.formal_safety_certificate.write_safety_certificate_bundle

Runtime-Bound Safety Certificate

::: scpn_control.scpn.runtime_safety_certificate.RuntimeTarget

::: scpn_control.scpn.runtime_safety_certificate.TimingEnvelope

::: scpn_control.scpn.runtime_safety_certificate.ControllerRuntimeBinding

::: scpn_control.scpn.runtime_safety_certificate.CertificateReplayResult

::: scpn_control.scpn.runtime_safety_certificate.compute_petri_topology_digest

::: scpn_control.scpn.runtime_safety_certificate.issue_runtime_safety_certificate

::: scpn_control.scpn.runtime_safety_certificate.validate_runtime_safety_certificate_payload

::: scpn_control.scpn.runtime_safety_certificate.replay_runtime_safety_certificate

::: scpn_control.scpn.runtime_safety_certificate.assert_runtime_certificate_admissible

::: scpn_control.scpn.z3_model_checking.Z3BoundedModelChecker

Z3 Formal Report I/O

::: scpn_control.scpn.z3_formal_report.verify_z3_formal_contracts

::: scpn_control.scpn.z3_formal_report.build_z3_formal_report_payload

::: scpn_control.scpn.z3_formal_report.build_blocked_z3_formal_report_payload

::: scpn_control.scpn.z3_formal_report.validate_z3_formal_report_payload

::: scpn_control.scpn.z3_formal_report.load_z3_formal_report

::: scpn_control.scpn.z3_formal_report.write_z3_formal_report

FusionCompiler

::: scpn_control.scpn.compiler.FusionCompiler

CompiledNet

::: scpn_control.scpn.compiler.CompiledNet

Inhibitor arcs remain a structure/formal-analysis feature. A caller may compile them only with allow_inhibitor=True, which stores the guard as a negative input-matrix entry for analysis paths that still inspect the original Petri-net structure. Controller artifacts and controller runtime do not encode inhibitor topology yet: CompiledNet.export_artifact(), load_artifact(), and NeuroSymbolicController reject negative dense w_in weights instead of serializing ambiguous inhibitor semantics.

NeuroSymbolicController

NeuroSymbolicController rejects nonzero sc_bitflip_rate unless allow_fault_injection=True is supplied explicitly and the process environment sets SCPN_ALLOW_CONTROLLER_FAULT_INJECTION=1. Bit-flip mutation is a double-gated fault-injection test mode, not a production control default.

Controller JSONL logging requires an explicit log_root whenever log_path is provided. Relative and absolute log paths must resolve under that root and use a .jsonl suffix before any file is opened. Log appends use a constrained append helper that rejects symlink targets where the platform exposes no-follow open semantics.

Runtime-bound safety admission is available through the explicit runtime_safety_certificate, runtime_safety_binding, runtime_safety_target, and runtime_safety_replay constructor arguments. Supplying any one of these requires all four. The controller first checks that the runtime binding's Petri topology digest matches the loaded .scpnctl artifact, then delegates to assert_runtime_certificate_admissible. This keeps ordinary local experiments unchanged while making safety-critical construction fail closed unless artifact, binding, target, and proof replay evidence all match.

::: scpn_control.scpn.controller.NeuroSymbolicController

Contracts

scpn_control.scpn.contracts owns the shared numeric kernels used by both the public contract helpers and the live controller runtime. extract_features() and NeuroSymbolicController.step() use the same signed-error component kernel; decode_actions() and the controller readout use the same slew-rate and absolute-limit action-vector kernel. This keeps standalone contract checks and compiled controller execution aligned.

The scpn_control.scpn package root re-exports FeatureAxisSpec, the shared feature/action kernels, and the runtime-safety certificate dataclasses and helpers so installed-package consumers do not need to reach into private module paths for controller construction and certificate admission.

::: scpn_control.scpn.contracts.ControlObservation

::: scpn_control.scpn.contracts.ControlAction

::: scpn_control.scpn.contracts.ControlTargets

::: scpn_control.scpn.contracts.extract_features

::: scpn_control.scpn.contracts.feature_error_components

::: scpn_control.scpn.contracts.decode_actions

::: scpn_control.scpn.contracts.decode_action_vector

Artifacts

Safety-critical controller admission must call load_artifact(..., require_formal_verification=True) or validate_safety_critical_artifact(). That gate rejects missing, blocked, failed, malformed, or unbounded proof evidence and accepts only hash-addressed bounded proof manifests tied to the compiled controller artifact. The proof manifest must include the canonical artifact payload SHA-256, report SHA-256, bounded proof depth, checked specification names, backend/solver metadata, and a safe relative report URI. Controller artifacts also carry meta.firing_margin, the default fractional firing margin used when a transition omits its own margin. The compiler writes this value, artifact loading validates it as finite and non-negative, and the controller consumes it directly instead of falling back to an implicit runtime constant. Legacy artifacts without the field still load with the historical 0.05 default so archived evidence remains readable. Artifact(...) validates direct construction by default, load_artifact() calls the same public validate_artifact() surface after parsing, and NeuroSymbolicController calls validate_artifact() before runtime arrays, runtime certificates, or controller state are admitted. Validator branch tests can pass validate_on_init=False only to build a deliberately malformed object; that object is still rejected by validate_artifact(), save_artifact(), and controller construction. When callers provide formal_report_root, the loader resolves the report URI under that root and verifies the report bytes against the declared SHA-256. Z3 and Lean report files reached through an artifact manifest are loaded through duplicate-key-safe and schema-strict public report loaders. Z3 reports are additionally schema-versioned as scpn-control.z3-formal-report.v1, carry a canonical payload SHA-256 over the proof payload, reject unknown top-level and proof-section fields, schema-check serialized counterexample records, enforce solver-status/holds/counterexample consistency, reject counterexamples on unknown solver sections, and must match the manifest status, solver, proof depth, and checked specification list before a safety-critical artifact is admitted. Each Z3 proof section must also carry unique non-empty checked_specs; duplicate section obligations are rejected before top-level report/spec matching. Blocked Z3 reports are not proof evidence: they must use the unavailable solver label, zero proof depth, and only the z3_solver_available checked specification. Pass/fail Z3 reports must identify z3-solver and must not use the unavailable-solver label; a missing z3-solver dependency is admitted only as blocked SMT evidence. Lean 4 reports are admitted only through the bounded lean4 manifest path: the manifest must bind a solver string that identifies Lean and includes the declared Lean version, Lake file SHA-256, proof-source SHA-256, theorem names, theorem modules, proved contracts, linked production module references, safety-case identifiers, checked specification list, report SHA-256, and compiled artifact SHA-256. Production module references should use importable module names such as scpn_control.scpn.controller so installed wheels and sdists do not depend on a repository src/ checkout; legacy safe relative source paths remain accepted for existing reports. The Lean report schema is scpn-control.lean4-formal-report.v1; when a report root is supplied, every manifest field above must match the report before admission. The current required Lean proof-contract surface covers PID actuator-saturation preservation and SNN/neuro-symbolic marking-bound preservation, and reports cannot list unsupported proved contracts to imply wider formal coverage. This is an evidence admission contract; it does not claim certification unless the referenced machine-checked proof artefacts are present and verified. The admitted PID/SNN surface is also exact-linked: theorem modules, theorem names, linked production module references, and safety-case identifiers must remain inside the expected PID/SNN namespaces and module references instead of padding a valid report with unrelated evidence. get_artifact_json_schema() returns the current .scpnctl.json Draft-07 schema from the same payload sections and dataclass field sets used by save_artifact() and load_artifact(). The schema declares the serialized meta.firing_margin, closed dense-weight and readout objects, the raw data_u64 packed-weight form, the compact u64-le-zlib-base64 packed-weight form, and the closed formal_verification manifest fields admitted by the runtime validator.

::: scpn_control.scpn.artifact.Artifact

::: scpn_control.scpn.artifact.FormalVerificationEvidence

::: scpn_control.scpn.artifact.compute_artifact_payload_sha256

::: scpn_control.scpn.artifact.validate_artifact

::: scpn_control.scpn.artifact.get_artifact_json_schema

::: scpn_control.scpn.artifact.save_artifact

::: scpn_control.scpn.artifact.load_artifact

::: scpn_control.scpn.artifact.validate_safety_critical_artifact

::: scpn_control.scpn.lean_verification.LeanFormalVerificationReport

::: scpn_control.scpn.lean_verification.build_lean_formal_report_payload

::: scpn_control.scpn.lean_verification.validate_lean_formal_report_payload

::: scpn_control.scpn.lean_verification.write_lean_formal_report

::: scpn_control.scpn.lean_verification.load_lean_formal_report

load_lean_formal_report() and the validation executable validation/validate_scpn_lean_formal.py validate Lean report JSON with duplicate-key rejection and can additionally call load_artifact(..., require_formal_verification=True) against a supplied artifact and report root. This is the release-gate path for admitting Lean proof evidence without running long proof jobs inside the Python test suite. The Lean report and artifact manifest validators also enforce namespace coverage for required controller contracts: PID actuator-saturation evidence must include a ScpnControl.PID theorem module and theorem name, while SNN/neuro-symbolic marking-bound evidence must include a ScpnControl.SNN theorem module and theorem name. Lean evidence must also declare explicit bounded proof_assumptions and a canonical assumption_sha256; report and artifact admission reject unbounded assumptions, certification overclaims, malformed assumption digests, or manifest/report assumption mismatches. Admission also rejects non-Lean solver declarations, Lean solver strings that do not include the reported lean_version, and any proved_contracts outside the currently admitted PID/SNN proof surface. Reports also fail closed when theorem_names, theorem_modules, module_paths, or safety_case_ids include unrelated entries outside the admitted PID/SNN proof boundary. Despite the historical field name, module_paths admits importable module references for installed packages and legacy safe relative source paths for existing reports. The same checks run on the .scpnctl artifact manifest itself, even without a report root, so safety-critical artifact loading cannot admit a stale or padded Lean manifest before report-byte comparison is available. Both Lean report payloads and artifact formal_verification manifests are closed schemas: unknown proof fields are rejected rather than ignored. External Lean reports must also carry the canonical payload_sha256 self-digest; reports that omit it are rejected before safety-critical artifact admission.


Phase — Paper 27 Dynamics

Kuramoto-Sakaguchi Step

::: scpn_control.phase.kuramoto.kuramoto_sakaguchi_step

kuramoto_sakaguchi_step() may dispatch to the optional Rust backend for wrapped phase updates. Treat latency as benchmark-context evidence; source comments and docstrings do not make fixed timing claims.

::: scpn_control.phase.kuramoto.order_parameter

::: scpn_control.phase.kuramoto.lyapunov_v

::: scpn_control.phase.kuramoto.lyapunov_exponent

lyapunov_exponent() validates a positive finite dt and finite, non-negative V(t) samples. Its heuristic floors only the initial and final sample at LYAPUNOV_VALUE_FLOOR before the log ratio, then divides by (n_samples - 1) * dt because the input is a sampled state history.

::: scpn_control.phase.kuramoto.wrap_phase

::: scpn_control.phase.kuramoto.GlobalPsiDriver

::: scpn_control.phase.kuramoto.KuramotoRuntimeEvidence

::: scpn_control.phase.kuramoto.kuramoto_runtime_evidence

::: scpn_control.phase.kuramoto.assert_kuramoto_runtime_claim_admissible

::: scpn_control.phase.kuramoto.save_kuramoto_runtime_evidence

::: scpn_control.phase.kuramoto.load_kuramoto_runtime_evidence

Knm Coupling Matrix

::: scpn_control.phase.knm.KnmSpec

::: scpn_control.phase.knm.build_knm_paper27

UPDE Multi-Layer Solver

::: scpn_control.phase.upde.UPDESystem

UPDESystem.step() returns a single output-state snapshot contract across the NumPy fallback and the optional Rust/PyO3 path. theta1, dtheta, R_layer, Psi_layer, R_global, Psi_global, V_layer, and V_global describe the same completed tick. The input psi_driver still drives the derivative term, but the returned Psi_global is the mean phase of theta1. Stale Rust bindings that cannot provide the full contract fall back to the NumPy implementation instead of returning partial snapshots.

Lyapunov Guard

::: scpn_control.phase.lyapunov_guard.LyapunovGuard

Realtime Monitor

::: scpn_control.phase.realtime_monitor.RealtimeMonitor

::: scpn_control.phase.realtime_monitor.TrajectoryRecorder

Adaptive Knm Engine

::: scpn_control.phase.adaptive_knm.AdaptiveKnmEngine

::: scpn_control.phase.adaptive_knm.AdaptiveKnmConfig

::: scpn_control.phase.adaptive_knm.DiagnosticSnapshot

The adaptive Knm engine uses every required diagnostic field in DiagnosticSnapshot: R_layer and V_layer drive the diagonal coherence channel, while lambda_exp, q95, disruption_risk, and mirnov_rms contribute to a bounded MHD-pair risk drive. The configuration defaults are dimensionless local-control gains except lambda_risk_gain_s, which converts a Lyapunov exponent in 1/s into a dimensionless stress contribution. These settings are bounded heuristics, not facility-calibrated stability claims.

Plasma Knm

::: scpn_control.phase.plasma_knm.build_knm_plasma

WebSocket Stream

PhaseStreamServer binds to loopback by default and requires authenticated clients by default. Operators must supply an API key or explicitly disable client authentication for local development. Non-loopback binds require an API key, command frames are capped by max_payload_bytes, accepted commands are rate-limited with token buckets per connection and per network peer, and production remote exposure should enable TLS with require_tls=True. Authentication, origin, payload, rate-limit, capacity, and command-authority rejections emit structured security audit log events without logging tokens. Query-string token authentication and plaintext non-loopback binds are disabled by default and require explicit operator opt-ins for constrained development or isolated lab environments. Browser clients that send an Origin header are rejected unless the origin is allowlisted, and deployments may restrict command authority with allowed_actions. websocket_runtime_evidence() emits a tamper-evident deployment artifact that binds WebSocket configuration, authenticated sessions, accepted commands, successful broadcasts, audit counters, TLS enforcement, payload caps, and backpressure state without storing API-key material. Qualified facility admission requires client authentication, configured TLS enforcement, observed commands, observed broadcasts, no query-token authentication, no insecure remote binding, and zero backpressure disconnects.

::: scpn_control.phase.ws_phase_stream.PhaseStreamServer

::: scpn_control.phase.ws_phase_stream.WebSocketRuntimeEvidence

::: scpn_control.phase.ws_phase_stream.websocket_runtime_evidence

::: scpn_control.phase.ws_phase_stream.assert_websocket_runtime_claim_admissible

::: scpn_control.phase.ws_phase_stream.save_websocket_runtime_evidence

::: scpn_control.phase.ws_phase_stream.load_websocket_runtime_evidence


Control — Controllers

H-infinity (Riccati DARE)

::: scpn_control.control.h_infinity_controller.HInfinityController

::: scpn_control.control.h_infinity_controller.get_radial_robust_controller

Model Predictive Control

::: scpn_control.control.fusion_neural_mpc.NeuralSurrogate

::: scpn_control.control.fusion_neural_mpc.ModelPredictiveController

Optimal Control

::: scpn_control.control.fusion_optimal_control.OptimalController

Digital Twin

run_digital_twin() now supports persistent sensor calibration bias and drift in addition to dropout and white-noise corruption, and it can now stress the command path with deterministic actuator bias, drift, first-order lag, and rate limiting. The returned summary exposes both commanded and applied actions plus actuator-lag telemetry so replay tests can see what the plant actually received. Density and effective-charge knobs are explicit model-update parameters.

digital_twin_online_update adds fail-closed TRANSP/TSC simulator artifact metadata validation and deterministic Bayesian optimisation over bounded twin parameters. The shipped benchmark is synthetic online-update evidence only; external simulator replay claims require validated artifact metadata and the strict digital-twin reference gate. digital_twin_update_evidence() and assert_digital_twin_update_claim_admissible() bind a bounded Bayesian update to TRANSP and TSC simulator metadata digests, observation and prior digests, result digest, baseline-improvement evidence, and an optional safety-critical controller proof artifact digest. Admission also revalidates source binding, finite non-negative loss history, minimum-loss consistency, best-parameter bounds, strict integer campaign settings, and simulator unit coverage for every observation target.

::: scpn_control.control.tokamak_digital_twin.run_digital_twin

::: scpn_control.control.digital_twin_online_update.validate_external_simulator_artifact

::: scpn_control.control.digital_twin_online_update.bayesian_update_digital_twin

::: scpn_control.control.digital_twin_online_update.DigitalTwinUpdateEvidence

::: scpn_control.control.digital_twin_online_update.digital_twin_update_evidence

::: scpn_control.control.digital_twin_online_update.assert_digital_twin_update_claim_admissible

::: scpn_control.control.digital_twin_online_update.synthetic_online_update_benchmark

Controller Safety-Case Evidence

control.safety_case defines the bounded safety-case workflow contract that links a passing safety-critical controller proof manifest, audited JAX differentiable-transport evidence, and TRANSP/TSC-backed bounded digital-twin online-update evidence. The bundle is tamper-evident and fails closed unless all evidence items bind to the same canonical controller artifact SHA-256. This is a repository safety-package admission boundary, not an external certification claim. save_controller_safety_case_evidence() persists the bundle with a manifest integrity digest, and load_controller_safety_case_evidence() rejects schema drift, malformed fields, or edited evidence payloads before replay admission. evaluate_controller_safety_case_readiness() separates linked bounded evidence from promotion readiness: external physics validation, target-hardware timing evidence, qualified HIL replay evidence, qualified CODAC/EPICS runtime evidence, qualified WebSocket runtime evidence, qualified HDL export evidence, and independent safety-review digests are all required before assert_controller_safety_case_readiness_admissible() accepts the package. ReadinessArtifactEvidence and evaluate_controller_safety_case_readiness_from_artifacts() provide the normal promotion path: each required readiness input must be a typed artifact with a known kind, SHA-256 digest, safe relative artifact URI, producer, and generation timestamp before it can satisfy the promotion gate. The evaluator also requires an explicit artifact_root: each URI must resolve below that root and match the declared bytes. target_hardware_timing artifacts must additionally pass the schema-versioned E2E latency evidence validator with qualified target hardware and the configured p95 limit. hil_replay_evidence artifacts must pass the schema-versioned HIL replay admission loader with qualified target hardware, so local workstation replay cannot satisfy deployment promotion readiness. codac_runtime_evidence artifacts must pass the schema-versioned CODAC runtime admission loader with qualified facility-claim status, deadline-clean cycle evidence, exercised interlock blocking, zero backpressure events, and hash-bound EPICS/OPC-UA exports. websocket_runtime_evidence artifacts must pass the schema-versioned WebSocket runtime admission loader with authenticated command evidence, TLS enforcement, token-bucket and payload-cap configuration, successful broadcast counters, and zero backpressure disconnects. hdl_export_evidence artifacts must pass the schema-versioned FPGA export admission loader with controller-artifact binding, generated project file digests, synthesis-report digest binding, and non-negative timing slack. save_controller_safety_case_readiness() and load_controller_safety_case_readiness() persist that readiness decision with the same schema-versioned integrity-digest semantics as the safety-case bundle.

::: scpn_control.control.safety_case.ControllerSafetyCaseEvidence

::: scpn_control.control.safety_case.SafetyCaseReadinessEvidence

::: scpn_control.control.safety_case.ReadinessArtifactEvidence

::: scpn_control.control.safety_case.controller_safety_case_evidence

::: scpn_control.control.safety_case.assert_controller_safety_case_admissible

::: scpn_control.control.safety_case.save_controller_safety_case_evidence

::: scpn_control.control.safety_case.load_controller_safety_case_evidence

::: scpn_control.control.safety_case.evaluate_controller_safety_case_readiness

::: scpn_control.control.safety_case.evaluate_controller_safety_case_readiness_from_artifacts

::: scpn_control.control.safety_case.assert_controller_safety_case_readiness_admissible

::: scpn_control.control.safety_case.save_controller_safety_case_readiness

::: scpn_control.control.safety_case.load_controller_safety_case_readiness

Flight Simulator

::: scpn_control.control.tokamak_flight_sim.IsoFluxController

::: scpn_control.control.tokamak_flight_sim.run_flight_sim

Free-Boundary Tracking

Experimental closed-loop free-boundary tracking that keeps the full FusionKernel in the loop and re-identifies the local coil-response map from repeated solves. Safe-current fallback targets can be supplied through the free_boundary_tracking.fallback_currents config block when supervisor rejection should ramp the coils toward a predefined safe state. Persistent objective residuals can also be accumulated with the config-driven free_boundary_tracking.observer_gain and observer_max_abs settings. When free-boundary objective tolerances are configured, the controller also uses them directly in its correction and accept/reject logic so tighter X-point or divertor targets take precedence over looser shape goals, and it refuses trial steps that would push an already-satisfied objective back outside tolerance. If the identified coil-response map loses authority entirely, the controller marks that degraded state explicitly and drops into the safe-state recovery path instead of silently accepting a zero-action step. Residuals already inside the configured tolerances are also treated as deadband, so the controller stops chattering the coils once the protected objectives are met. Coil allocation is also headroom-aware, so the regularized solve prefers actuators that still have current authority instead of leaning equally on a nearly saturated coil. Deterministic objective-space sensor bias and per-step drift can be injected through free_boundary_tracking.measurement_bias and measurement_drift_per_step, and known calibration corrections can be applied with measurement_correction_bias and measurement_correction_drift_per_step. The run summary reports both measured and hidden true objective errors so calibration faults cannot masquerade as control success in acceptance tests.

from scpn_control.control.free_boundary_tracking import run_free_boundary_tracking

summary = run_free_boundary_tracking(
    "iter_config.json",
    shot_steps=5,
    gain=0.8,
    verbose=False,
    coil_slew_limits=2.5e5,
    supervisor_limits={"x_point_position": 0.15, "max_abs_actuator_lag": 1.0e5},
    hold_steps_after_reject=2,
)

print(summary["shape_rms"], summary["objective_converged"], summary["supervisor_intervention_count"])

::: scpn_control.control.free_boundary_tracking.FreeBoundaryTrackingController

::: scpn_control.control.free_boundary_tracking.run_free_boundary_tracking

Free-Boundary Tracking Claim Evidence

::: scpn_control.control.free_boundary_tracking_claims.free_boundary_tracking_claim_evidence

::: scpn_control.control.free_boundary_tracking_claims.assert_free_boundary_tracking_facility_claim_admissible

::: scpn_control.control.free_boundary_tracking_claims.save_free_boundary_tracking_claim_evidence

Disruption Predictor

predict_disruption_risk_safe() still returns a bounded scalar risk, but its metadata now includes deterministic sigma-point uncertainty summaries (risk_p05, risk_p50, risk_p95, risk_std, risk_interval) for both fallback and checkpoint inference paths. DisruptionTransformer.predict() returns the same bounded scalar-risk shape expected by evaluate_predictor(), so trained transformer instances can be evaluated directly without wrapper adapters.

::: scpn_control.control.disruption_predictor.DisruptionTransformer

::: scpn_control.control.disruption_predictor.predict_disruption_risk

::: scpn_control.control.disruption_predictor.predict_disruption_risk_safe

Disruption Contracts

::: scpn_control.control.disruption_contracts.run_disruption_episode

::: scpn_control.control.disruption_contracts.predict_disruption_risk

Disruption ROC

scpn_control.control.disruption_roc scores a fixed-weight risk series over a shot, sweeps alarm thresholds, and reports bounded internal ROC/AUC plus warning-time recall. The scoring core is a bounded model (the n=3 toroidal amplitude approximates n=2), so its metrics stay internal and admission-blocked.

::: scpn_control.control.disruption_roc.score_risk_series

::: scpn_control.control.disruption_roc.ShotEvaluation

::: scpn_control.control.disruption_roc.first_alarm_index

::: scpn_control.control.disruption_roc.confusion_at_threshold

::: scpn_control.control.disruption_roc.roc_curve

::: scpn_control.control.disruption_roc.roc_auc_from_curve

::: scpn_control.control.disruption_roc.warning_time_recall

::: scpn_control.control.disruption_roc.disruption_metrics

SPI Mitigation

::: scpn_control.control.spi_mitigation.ShatteredPelletInjection

::: scpn_control.control.spi_mitigation.run_spi_mitigation

Fusion Control Room

::: scpn_control.control.fusion_control_room.run_control_room

::: scpn_control.control.fusion_control_room.TokamakPhysicsEngine

Gymnasium Environment

::: scpn_control.control.gym_tokamak_env.TokamakEnv

Analytic Solver

::: scpn_control.control.analytic_solver.AnalyticEquilibriumSolver

Bio-Holonomic Controller

::: scpn_control.control.bio_holonomic_controller.BioHolonomicController

Digital Twin Ingest

::: scpn_control.control.digital_twin_ingest.RealtimeTwinHook

Director Interface

::: scpn_control.control.director_interface.DirectorInterface

Fueling Mode Controller

::: scpn_control.control.fueling_mode.IcePelletFuelingController

Halo RE Physics

::: scpn_control.control.halo_re_physics.HaloCurrentModel

::: scpn_control.control.halo_re_physics.DisruptionMitigationClaimEvidence

::: scpn_control.control.halo_re_physics.disruption_mitigation_claim_evidence

::: scpn_control.control.halo_re_physics.assert_disruption_mitigation_claim_admissible

::: scpn_control.control.halo_re_physics.save_disruption_mitigation_claim_evidence

HIL Test Harness

::: scpn_control.control.hil_harness.HILControlLoop

::: scpn_control.control.hil_harness.HILBenchmarkResult

::: scpn_control.control.hil_harness.hil_replay_evidence

::: scpn_control.control.hil_harness.assert_hil_replay_evidence_admissible

::: scpn_control.control.hil_harness.save_hil_replay_evidence

::: scpn_control.control.hil_harness.load_hil_replay_evidence

JAX Traceable Runtime

Requires pip install "scpn-control[jax]".

::: scpn_control.control.jax_traceable_runtime.TraceableRuntimeSpec

LIF+NEF SNN Controller

::: scpn_control.control.nengo_snn_wrapper.NengoSNNController

Neuro-Cybernetic Controller

::: scpn_control.control.neuro_cybernetic_controller.NeuroCyberneticController

TORAX Hybrid Loop

::: scpn_control.control.torax_hybrid_loop.run_nstxu_torax_hybrid_campaign

Advanced SOC Learning

::: scpn_control.control.advanced_soc_fusion_learning.run_advanced_learning_sim

NMPC Controller (v0.16.0)

NonlinearMPC validates the NMPC quadratic program contract before optimization: Q, R, and optional terminal P must be finite symmetric positive-definite matrices with tokamak state/input dimensions; state, input, and slew bounds must be finite and ordered; and plant-model evaluations must return finite state vectors. Invalid math contracts fail closed instead of propagating undefined SQP or PGD iterates. The public compute_cost() evaluator includes the finite-horizon terminal penalty, using configured P when supplied and the controller's conservative fallback terminal weight otherwise. Production plant models may provide an analytic linearization_model(x, u) contract returning finite (6, 6) state and (6, 3) input Jacobians. The controller validates those matrices before use and records last_linearization_source == "analytic". If no analytic provider is supplied, the controller can use linearization_backend="jax" for JAX-traceable plant models and records last_linearization_source == "jax"; otherwise it falls back to bounded central finite differences and records last_linearization_source == "finite_difference". Quadratic weights use a strict symmetry gate before positive-definite projection so near-zero off-diagonal asymmetry cannot pass as a valid cost matrix. DARE-derived terminal matrices are accepted only when finite, symmetric, and positive definite; invalid solver output falls back to the conservative terminal weight. Explicit terminal state sets are configured with paired terminal_x_min and terminal_x_max vectors. These bounds must lie inside the configured physics state envelope and currently require qp_backend="scipy", qp_backend="osqp", qp_backend="casadi", or qp_backend="acados" so the coupled terminal-state inequality is enforced inside the constrained QP solve rather than checked after the fact. casadi is a repository-local optional dependency path. The acados backend is a full optional OCP interface: deployments may inject a pre-built acados OCP/solver factory, or provide symbolic_dynamics_model(ca, x, u) so the controller builds a discrete augmented-state acados model. The augmented state stores the previous actuator vector, making |Δu| <= du_max a native acados path constraint instead of a post-solve clamp. The default builder configures SQP, partial-condensing HPIPM, exact Hessian mode, linear least-squares stage/terminal costs, state/input bounds, terminal state bounds, warm starts, fail-closed solver-status handling, and a runtime plant-consistency gate. The returned acados state trajectory must start from the commanded state, remain inside configured state bounds, satisfy any terminal admissible set, and match plant_model transitions within acados_dynamics_residual_tol before the first actuator command is admitted. The previous input supplied to step() must already satisfy actuator bounds so the slew-rate projection cannot propagate an unsafe actuator state. The accepted horizon=1 case is handled as a valid one-step receding-horizon controller and warm-starts from the bounded previous input. Each QP solve records last_qp_iterations and last_qp_converged, making projection-tolerance convergence distinguishable from iteration-budget exhaustion. The projected-gradient QP iteration budget is configured by qp_max_iter instead of being an unobservable hard-coded loop bound. Linearization perturbations are clipped to the configured state/input domain: interior points use central differences, while boundary points use one-sided finite differences.

::: scpn_control.control.nmpc_controller.NonlinearMPC

NMPC Transport-Model Tuning (v0.16.0)

The transport-model tuning entry points live in their own scpn_control.control.nmpc_transport_tuning module: fitting the transport model the controller tracks against is a distinct responsibility from receding-horizon tracking, so it is separated from nmpc_controller. The entry-point signatures and fail-closed semantics are unchanged. tune_transport_coefficients_for_tracking() connects NMPC controller tuning to the differentiable transport facade. It updates four-channel transport coefficients from the JAX gradient of the transport tracking loss, applies non-negative coefficient bounds and fractional update caps, and fails closed when JAX gradients are unavailable. By default, coefficient tuning also runs the differentiable-transport finite-difference gradient audit before admission and stores the audit result beside the validated transport campaign metadata for backend, dtype, radial grid, boundary conditions, closure provenance, and gradient tolerance. tune_neural_transport_closure_for_tracking() initialises the same tuning path from a bounded neural transport closure, preserving the differentiable facade's four-channel coefficient contract, the explicit JAX-gradient requirement, and the default gradient-audit admission gate. tune_transport_sources_for_tracking() applies the audited JAX gradient path to additive heating, fuelling, and impurity-source schedules. Source lower and upper bounds are explicit because replay studies may include physically valid sink terms, and every accepted update carries campaign metadata plus the gradient-audit result. tune_transport_source_rollout_for_tracking() extends that admission boundary from a single transport step to a complete (n_steps, 4, n_rho) source schedule. It uses JAX for the multi-step rollout gradient, requires a sampled NumPy finite-difference audit by default, clips per-entry source updates when configured, and records bounded campaign metadata before the schedule can enter NMPC tuning. The default audit-failure mode is fail-closed. The explicit gradient_audit_failure_mode="warn" mode exists only for advisory, non-control analysis and preserves the failed audit evidence in the returned result.

::: scpn_control.control.nmpc_transport_tuning.TransportCoefficientTuningResult

::: scpn_control.control.nmpc_transport_tuning.TransportSourceScheduleTuningResult

::: scpn_control.control.nmpc_transport_tuning.TransportSourceRolloutGradientAudit

::: scpn_control.control.nmpc_transport_tuning.TransportSourceRolloutTuningResult

::: scpn_control.control.nmpc_transport_tuning.tune_transport_coefficients_for_tracking

::: scpn_control.control.nmpc_transport_tuning.tune_transport_sources_for_tracking

::: scpn_control.control.nmpc_transport_tuning.tune_transport_source_rollout_for_tracking

::: scpn_control.control.nmpc_transport_tuning.tune_neural_transport_closure_for_tracking

Mu-Synthesis (v0.16.0)

::: scpn_control.control.mu_synthesis.MuSynthesisController

::: scpn_control.control.mu_synthesis.compute_mu_upper_bound

::: scpn_control.control.mu_synthesis.MuSynthesisClaimEvidence

::: scpn_control.control.mu_synthesis.mu_synthesis_claim_evidence

::: scpn_control.control.mu_synthesis.assert_mu_synthesis_validated_claim_admissible

::: scpn_control.control.mu_synthesis.save_mu_synthesis_claim_evidence

::: scpn_control.control.mu_synthesis.load_mu_synthesis_claim_evidence

Real-Time EFIT (v0.16.0)

::: scpn_control.control.realtime_efit.RealtimeEFIT

::: scpn_control.control.realtime_efit.EFITLiteClaimEvidence

::: scpn_control.control.realtime_efit.efit_lite_claim_evidence

::: scpn_control.control.realtime_efit.assert_efit_lite_facility_claim_admissible

::: scpn_control.control.realtime_efit.save_efit_lite_claim_evidence

Gain-Scheduled Controller (v0.16.0)

::: scpn_control.control.gain_scheduled_controller.GainScheduledController

Shape Controller (v0.16.0)

::: scpn_control.control.shape_controller.PlasmaShapeController

Safe RL Controller (v0.16.0)

::: scpn_control.control.safe_rl_controller.LagrangianPPO

Sliding-Mode Vertical (v0.16.0)

::: scpn_control.control.sliding_mode_vertical.VerticalStabilizer

Scenario Scheduler (v0.16.0)

::: scpn_control.control.scenario_scheduler.ScenarioOptimizer

Closed-Loop Integrated Scenario Demo (v0.22.1)

scpn_control.control.closed_loop_scenario wires the reusable ScenarioSchedule / FeedforwardController surface into IntegratedScenarioSimulator for the scpn-control demo --scenario combined path. The exported result carries controller commands, bounded auxiliary-power application, and a replay coupling audit. It is a deterministic repository wiring contract; measured-discharge validation remains gated by the physics traceability registry.

::: scpn_control.control.closed_loop_scenario.ClosedLoopScenarioStep

::: scpn_control.control.closed_loop_scenario.ClosedLoopScenarioResult

::: scpn_control.control.closed_loop_scenario.run_integrated_scenario_closed_loop

Fault-Tolerant Control (v0.16.0)

::: scpn_control.control.fault_tolerant_control.ReconfigurableController

RZIp Model (v0.16.0)

::: scpn_control.control.rzip_model.RZIPModel

::: scpn_control.control.rzip_model.RZIPController

::: scpn_control.control.rzip_model.RZIPCalibrationEvidence

::: scpn_control.control.rzip_model.rzip_calibration_evidence

::: scpn_control.control.rzip_model.assert_rzip_facility_claim_admissible

::: scpn_control.control.rzip_model.save_rzip_calibration_evidence

RWM Feedback (v0.16.0)

::: scpn_control.control.rwm_feedback.RWMFeedbackController

::: scpn_control.control.rwm_feedback.RWMClaimEvidence

::: scpn_control.control.rwm_feedback.rwm_claim_evidence

::: scpn_control.control.rwm_feedback.assert_rwm_facility_claim_admissible

::: scpn_control.control.rwm_feedback.save_rwm_claim_evidence


Complete Module Index

This index keeps the published API reference aligned with every tracked Python module under src/scpn_control/. Domain pages above highlight primary entry points; this section exposes the remaining module surfaces through mkdocstrings so public signatures and docstrings stay visible as the codebase grows.

Top-Level CLI

Cli

::: scpn_control.cli

CLI Reference Validators

::: scpn_control.cli_reference_validators

CLI Evidence Validators

::: scpn_control.cli_evidence_validators

Shared Typing Aliases

::: scpn_control._typing

Shared NPZ Writer

::: scpn_control._npz

Control Modules

Burn Controller

::: scpn_control.control.burn_controller

Codac Interface

::: scpn_control.control.codac_interface

::: scpn_control.control.codac_interface.CODACRuntimeEvidence

::: scpn_control.control.codac_interface.codac_runtime_evidence

::: scpn_control.control.codac_interface.assert_codac_runtime_claim_admissible

::: scpn_control.control.codac_interface.save_codac_runtime_evidence

::: scpn_control.control.codac_interface.load_codac_runtime_evidence

Controller Tuning

::: scpn_control.control.controller_tuning

Density Controller

::: scpn_control.control.density_controller

::: scpn_control.control.density_controller.DensityControlClaimEvidence

::: scpn_control.control.density_controller.density_control_claim_evidence

::: scpn_control.control.density_controller.assert_density_control_facility_claim_admissible

::: scpn_control.control.density_controller.save_density_control_claim_evidence

Detachment Controller

::: scpn_control.control.detachment_controller

Federated Disruption

::: scpn_control.control.federated_disruption

State Estimator

::: scpn_control.control.state_estimator

Volt Second Manager

::: scpn_control.control.volt_second_manager

Core Support and Physics Modules

Rust Compatibility

::: scpn_control.core._rust_compat

Statistics Helpers

::: scpn_control.core._statistics

Validators

::: scpn_control.core._validators

Alfven Eigenmodes

::: scpn_control.core.alfven_eigenmodes

Blob Transport

::: scpn_control.core.blob_transport

Checkpoint

::: scpn_control.core.checkpoint

Disruption Sequence

::: scpn_control.core.disruption_sequence

Elm Model

::: scpn_control.core.elm_model

Eped Pedestal

::: scpn_control.core.eped_pedestal

GK CGYRO

::: scpn_control.core.gk_cgyro

GK GENE

::: scpn_control.core.gk_gene

GK Geometry

::: scpn_control.core.gk_geometry

GK GS2

::: scpn_control.core.gk_gs2

GK Nonlinear

::: scpn_control.core.gk_nonlinear

GK Online Learner

OnlineLearner admits finite nonnegative transport targets only when the caller-supplied OOD score is inside the configured threshold. Retraining uses a validation holdout, rolls back on non-improvement, and can persist an auditable JSON report containing every accepted or rejected update decision.

::: scpn_control.core.gk_online_learner

GK QuaLiKiz

::: scpn_control.core.gk_qualikiz

GK Species

::: scpn_control.core.gk_species

GK TGLF

::: scpn_control.core.gk_tglf

GK TGLF Native

::: scpn_control.core.gk_tglf_native

GK Verification Report

::: scpn_control.core.gk_verification_report

Impurity Transport

::: scpn_control.core.impurity_transport

JAX GK Nonlinear

::: scpn_control.core.jax_gk_nonlinear

JAX GK Solver

The linear JAX GK solver includes a schema-versioned parity artifact producer for backend reproducibility. build_jax_gk_parity_artifact() and write_jax_gk_parity_artifact() bind the native local-dispersion comparison, backend metadata, dtype/X64 state, solver kwargs, tolerances, and canonical payload SHA-256 digest while preserving the backend-parity-only claim boundary. Artifacts also bind case-parameter digests, native/JAX mode spectra, dominant mode labels, and case acceptance limits for CBC, kinetic-electron TEM, and low-drive stable-mode parity evidence. validation/validate_jax_gk_parity.py can require named cases and named backends before admitting an evidence directory, so archived single-case artifacts cannot be replayed as full parity coverage.

::: scpn_control.core.jax_gk_solver

::: scpn_control.core.jax_gk_solver.gk_stiffness_chi_i_profile_jax

::: scpn_control.core.jax_gk_solver.build_jax_gk_parity_artifact

::: scpn_control.core.jax_gk_solver.write_jax_gk_parity_artifact

JAX GS Solver

::: scpn_control.core.jax_gs_solver

Kinetic EFIT

::: scpn_control.core.kinetic_efit

::: scpn_control.core.kinetic_efit.KineticEFITClaimEvidence

::: scpn_control.core.kinetic_efit.kinetic_efit_claim_evidence

::: scpn_control.core.kinetic_efit.assert_kinetic_efit_facility_claim_admissible

::: scpn_control.core.kinetic_efit.save_kinetic_efit_claim_evidence

L-H Transition

::: scpn_control.core.lh_transition

Locked Mode

::: scpn_control.core.locked_mode

MARFE

::: scpn_control.core.marfe

MDSplus Acquisition

::: scpn_control.core.mdsplus_acquisition

Momentum Transport

::: scpn_control.core.momentum_transport

Neoclassical

::: scpn_control.core.neoclassical

Neural Turbulence

::: scpn_control.core.neural_turbulence

::: scpn_control.core.neural_turbulence.NeuralTurbulenceClaimEvidence

::: scpn_control.core.neural_turbulence.cross_validate_neural_turbulence

::: scpn_control.core.neural_turbulence.neural_turbulence_claim_evidence

::: scpn_control.core.neural_turbulence.assert_neural_turbulence_quantitative_claim_admissible

::: scpn_control.core.neural_turbulence.save_neural_turbulence_claim_evidence

Orbit Following

::: scpn_control.core.orbit_following

::: scpn_control.core.orbit_following.OrbitFollowingClaimEvidence

::: scpn_control.core.orbit_following.orbit_following_claim_evidence

::: scpn_control.core.orbit_following.assert_orbit_following_external_claim_admissible

::: scpn_control.core.orbit_following.save_orbit_following_claim_evidence

Pedestal

::: scpn_control.core.pedestal

Pellet Injection

::: scpn_control.core.pellet_injection

Plasma Startup

::: scpn_control.core.plasma_startup

Plasma Wall Interaction

::: scpn_control.core.plasma_wall_interaction

Real Data Manifest

::: scpn_control.core.real_data_manifest

Runaway Electrons

::: scpn_control.core.runaway_electrons

Stellarator Geometry

::: scpn_control.core.stellarator_geometry

Tearing Mode Coupling

::: scpn_control.core.tearing_mode_coupling

Vessel Model

::: scpn_control.core.vessel_model

VMEC Lite

::: scpn_control.core.vmec_lite

::: scpn_control.core.vmec_lite.VMECLiteClaimEvidence

::: scpn_control.core.vmec_lite.vmec_lite_claim_evidence

::: scpn_control.core.vmec_lite.assert_vmec_lite_full_vmec_claim_admissible

::: scpn_control.core.vmec_lite.save_vmec_lite_claim_evidence

Phase Modules

GK UPDE Bridge

::: scpn_control.phase.gk_upde_bridge

SCPN Compiler and Replay Modules

FPGA Export

scpn_control.scpn.fpga_export writes bounded HDL project files and tamper-evident export evidence. It does not claim to emit a deployable FPGA bitstream. Facility or hardware claims require qualified synthesis report evidence through assert_hdl_export_claim_admissible.

::: scpn_control.scpn.fpga_export

::: scpn_control.scpn.fpga_export.HDLExportEvidence

::: scpn_control.scpn.fpga_export.hdl_export_evidence

::: scpn_control.scpn.fpga_export.assert_hdl_export_claim_admissible

::: scpn_control.scpn.fpga_export.save_hdl_export_evidence

::: scpn_control.scpn.fpga_export.load_hdl_export_evidence

Geometry Neutral Contracts

::: scpn_control.scpn.geometry_neutral_contracts

Geometry Neutral Replay

::: scpn_control.scpn.geometry_neutral_replay

::: scpn_control.scpn.geometry_neutral_replay.GeometryNeutralReplayEvidence

::: scpn_control.scpn.geometry_neutral_replay.geometry_neutral_replay_evidence

::: scpn_control.scpn.geometry_neutral_replay.assert_geometry_neutral_replay_claim_admissible

::: scpn_control.scpn.geometry_neutral_replay.save_geometry_neutral_replay_evidence

::: scpn_control.scpn.geometry_neutral_replay.load_geometry_neutral_replay_evidence

Studio Vertical

CONTROL's SCPN STUDIO vertical expresses its verbs and evidence on the locked scpn-studio-platform contract (installed via the optional studio extra). It consumes the platform SDK rather than forking it: verbs are declared as platform Verb records, results map to platform EvidenceBundle records, and the capability manifest is the platform CapabilityManifest.

Studio Verbs

::: scpn_control.studio.verbs

Studio Evidence Bundles

::: scpn_control.studio.evidence

Studio Capability Manifest

::: scpn_control.studio.manifest

Studio Live-Emitter Adapters

::: scpn_control.studio.adapters

Studio Panel Feed

The federated panel reads CONTROL's verbs and claims from the wire feed this module emits (studio.control-feed.v1), so the UI never holds a second, drifting copy of the contract. Claim summaries include the platform freshness axis: the safety certificate emits verified-at-source after the mapper re-checks proof coverage, while the other representative claims emit traceable-unchecked and render at their boundary unless fresh source verification is supplied. Regenerate the standalone artefact with python -m scpn_control.studio.feed > studio-web/public/studio-feed.json.

::: scpn_control.studio.feed

Studio Sealed Safety Claim

The Hub's transparency log verifies artefacts with an RFC-8785 JCS canonicaliser that rejects non-integer JSON numbers, so the sealed safety-certificate claim is emitted float-free: integers stay within the exact-interoperability range and exact decimals travel as strings. The module is deliberately SDK-free so the artefact can be produced from a checkout without the optional studio extra.

::: scpn_control.studio.sealed_claim


CLI

scpn-control demo --scenario combined --steps 1000
scpn-control benchmark --n-bench 5000 --json-out
scpn-control validate --json-out
scpn-control validate-release-evidence artifacts/release_evidence_report.json --json-out
scpn-control info --json-out
scpn-control live --port 8765 --zeta 0.5 --layers 16
scpn-control hil-test --shots-dir path/to/shots
Command Description
demo Closed-loop control demonstration (PID, SNN, combined)
benchmark PID vs SNN timing benchmark with JSON output option
validate Import hygiene plus data-manifest, JAX GK parity, and physics-traceability gates
validate-release-evidence Admission check for JSON reports emitted by scpn-control validate --json-out, including data manifests, JAX GK parity, physics traceability, multi-shot campaign evidence, and native formal certificate evidence
info Version, Rust backend status, weight provenance, Python/NumPy versions
live Real-time WebSocket phase sync server
hil-test Hardware-in-the-loop test campaign against shot data

Rust Acceleration

When scpn-control-rs is built via maturin, all core solvers use Rust backends automatically:

from scpn_control import RUST_BACKEND
print(RUST_BACKEND)  # True if Rust available

# Transparent acceleration — same Python API, Rust execution
kernel = FusionKernel(R0=6.2, a=2.0, B0=5.3)

Build Rust bindings:

cd scpn-control-rs/crates/control-python
maturin develop --release

PyO3 Bindings

Python Class Rust Binding Crate
FusionKernel PyFusionKernel control-core
RealtimeMonitor PyRealtimeMonitor control-math
SnnPool PySnnPool control-control
MpcController PyMpcController control-control
Plasma2D PyPlasma2D control-core
TransportSolver PyTransportSolver control-core

Core — Native Rust Engine Wrapper

scpn_control.core.rust_engine is the Python control-plane wrapper for the optional PyO3 native execution bridge. It configures native campaign execution, formal-verification mode, runtime admission, transport backend selection, and emergency telemetry handoff while keeping timing-critical execution inside the compiled Rust data plane when the extension is available.

This wrapper is an execution boundary, not a physics solver. It does not turn a local workstation run into target-hardware PCS evidence unless the matching runtime-admission and benchmark-context reports pass.

::: scpn_control.core.rust_engine

API surface usage model

This page is the binding map for practical integration, not a promise of stable semantics for every release.

  • Use top-level exports for workflow composition.
  • Use submodules for module-specific interfaces and keep import paths explicit.
  • Use documented Rust bindings for hot-path execution only after matching environment checks pass.

When uncertain, start in Python for reproducibility and then switch to native paths only for timing and production-oriented experiments.

API usage expectation for enterprise workflows

This API surface is intentionally split by risk and execution boundary:

  • Safe exploratory usage: top-level Python entry points with explicit argument checks and deterministic defaults.
  • Research extension usage: module-level APIs where validation still controls the admissible claim level.
  • Deployment-oriented usage: PyO3-backed primitives where timing and transport behavior are benchmarked under explicit host context.

When preparing an integration PR, include both:

  • one reproducible usage example against the public API,
  • one admission-visible benchmark or validation record for the same path.

That pairing is the minimum contract for external-facing confidence.

Practical use and scope

Use this page as the public contract boundary for scpn_control exports and import-level behavior.

  • Validate import and symbol usage here before changing interface signatures in src/scpn_control.
  • Use the API map to decide whether integration changes are safe for third-party callers.
  • Pair API updates with corresponding validation and release notes for any public call-flow changes.