SC-NeuroCore API Reference¶
Module _native.array_guards¶
Function require_c_contiguous(arr, name, dtype)¶
Validate array layout before a zero-copy native call.
Module _native.core_engine_bridge¶
Function is_available()¶
Return True if the Rust core engine is loaded.
Function sc_multiply(a, b)¶
SC multiply: AND of two u32 bitstreams.
Function sc_mux(a, b, sel)¶
SC MUX: (sel & a) | (~sel & b).
Function sc_popcount(a)¶
Population count of a u32.
Function sc_popcount64(a)¶
Population count of a u64.
Function sc_popcount_packed(data)¶
Popcount of packed u64 array (from Python list).
Function sc_popcount_packed_np(data)¶
Popcount of packed u64 numpy array (zero-copy).
Function sc_scc_packed(a, b)¶
Stochastic cross-correlation of packed u64 arrays (from Python list).
Function sc_scc_packed_np(a, b)¶
Stochastic cross-correlation of packed u64 numpy arrays (zero-copy).
Function lfsr_encode_packed()¶
Encode an LFSR-16 stochastic bitstream as packed little-endian u64 words.
Function lfsr_encode_bits()¶
Encode an LFSR-16 stochastic bitstream as a uint8 0/1 numpy array.
Module _native.learning_bridge¶
Function is_available()¶
Return whether the required autonomous-learning Rust ABI is loaded.
Function set_deterministic_mode(seed)¶
Set the shared deterministic seed for analogue and WGPU paths.
Function __getattr__(name)¶
Expose read-only historical runtime diagnostics for compatibility.
Module _native.learning_factory¶
Function create_plasticity_layer(count, rule_type, backend, autograd)¶
Construct a Torch, Rust-Rayon, or Rust-WGPU plasticity layer.
Rust backends remain available when PyTorch is not installed. Torch is imported only when explicitly selected so optional dependency failures do not disable native learning.
Module _native.learning_runtime¶
Class OnlineO1SnapshotFFI¶
ctypes representation of the bounded Rust online O(1) snapshot.
Function is_available()¶
Return whether the required autonomous-learning ABI is loaded.
Function has_symbol(name)¶
Return whether the loaded library exposes name.
Function require_symbol(name)¶
Return a typed dynamic symbol or raise for an incompatible library.
Function destroy_noexcept(symbol, pointer)¶
Destroy a native handle without leaking exceptions from finalizers.
Function set_deterministic_mode(seed)¶
Set a shared deterministic seed for CPU analogue and WGPU paths.
Function deterministic_seed()¶
Return the configured shared deterministic seed.
Module _native.learning_rust¶
Class RustOnlineO1Synapse¶
Own one bounded fixed-point online O(1) Rust learner.
- init()
- step()
- Advance one timestep and return the bounded fixed-point state.
- per_synapse_state_bits()
- Return the Rust-reported fixed-point state footprint in bits.
Class RustPlasticityRule¶
Own one scalar Rust STDP, R-STDP, BCM, or ELIGENT rule.
- init(rule_type, weight, param_a, param_b)
- step(pre_spike, post_spike, dt, reward)
- Advance one scalar plasticity timestep through the Rust ABI.
- step_batched(pre_spikes, post_spikes, rewards, dt)
- Advance equally sized vectors in one native boundary crossing.
- weight()
- Return the current Rust-managed rule weight.
- reset()
- Clear rule traces while retaining the learned weight.
Class RustEligentLearner¶
Own one backward-compatible scalar Rust ELIGENT learner.
- init(threshold, target_rate, weight)
- step(fired, pre_spike, global_reward, dt)
- Advance one scalar ELIGENT timestep through the Rust ABI.
- step_batched(fired_slice, pre_spikes, rewards, dt)
- Advance equally sized ELIGENT vectors through one native call.
Module _native.learning_rust_layer¶
Class RustRuleLayer¶
Own a parallel Rust rule layer with length-checked array boundaries.
- init(count, rule_type, weight, param_a, param_b)
- getstate()
- Return validated metadata and Rust-owned serialization bytes.
- get_state_dict()
- Return a Python state dictionary containing Rust serialization.
- setstate(state)
- Atomically replace this layer from a validated serialized state.
- load_state_dict(state_dict)
- Atomically restore this layer from a Python state dictionary.
- step(pre_spikes, post_spikes, rewards, dt)
- Process one exactly sized spatial batch on Rayon threads.
- step_analog(pre_probs, post_probs, rewards, dt, seed)
- Sample probability vectors natively using an explicit safe seed.
- get_weights()
- Return a detached copy of every native rule weight.
- save(path)
- Write the checked in-memory state format to
path. - load(path)
- Read and atomically restore a checked state payload from
path. - reset()
- Clear every rule trace while preserving learned weights.
Module _native.learning_torch¶
Class TorchRuleLayer¶
Execute biological plasticity with optional surrogate autograd.
- init(count, rule_type, weight, param_a, param_b, autograd)
- reset()
- Clear only the mutable traces defined by the selected rule.
- forward(pre_spikes, post_spikes, rewards, dt)
- Advance one vector timestep and return the resulting weights.
- step(pre_spikes, post_spikes, rewards, dt)
- Compatibility wrapper accepting Torch or NumPy vectors.
- get_state_dict()
- Return the standard Torch state as a plain dictionary.
- load_state_dict(state_dict, strict, assign)
- Restore a standard Torch state dictionary.
- get_weights()
- Return a detached CPU copy of every weight.
Module _native.learning_torch_precision¶
Function normalise_bit_spec(spec)¶
Return a per-synapse integer bit vector within the supported domain.
Function normalise_clip(value)¶
Return a finite, positive symmetric quantisation limit.
Function quantise_tensor(values, bits, clip)¶
Symmetrically quantise a tensor, preserving its device and dtype.
Module _native.learning_torch_support¶
Function rule_parameters(rule_type, param_a, param_b, kwargs)¶
Build the five validated scalar parameters shared by every rule.
Function validate_input(values)¶
Move a finite one-dimensional public input onto the layer device.
Module _native.learning_validation¶
Function require_integral()¶
Return an integer after rejecting booleans and non-integral values.
Function require_non_negative_integral()¶
Return a non-negative integer for an unsigned native ABI field.
Function require_integral_range()¶
Return an integer inside the inclusive native ABI domain.
Function require_count(value)¶
Return a positive layer size that can safely cross size_t.
Function require_rule_type(value)¶
Return one of the four native plasticity rule identifiers.
Function require_bool()¶
Return a real Python boolean for the C bool ABI.
Function require_finite_float()¶
Return a finite real scalar after rejecting booleans.
Function require_positive_float()¶
Return a finite strictly positive scalar.
Function require_non_negative_float()¶
Return a finite non-negative scalar.
Function require_unit_interval()¶
Return a finite scalar in the closed unit interval.
Function require_u32_seed()¶
Return a deterministic seed accepted by CPU and WGPU paths.
Function require_u64_seed()¶
Return an explicit seed accepted by the Rayon analogue path.
Function saturate(value, lower, upper)¶
Clamp an already validated integer into inclusive bounds.
Function as_bool_vector(values)¶
Return a contiguous Boolean vector without truthiness coercion.
Function as_float_vector(values)¶
Return a contiguous finite float32 vector.
Function as_probability_vector(values)¶
Return a contiguous finite probability vector in [0, 1].
Module _native.learning_wgpu¶
Class RustWgpuRuleLayer¶
Own one explicit WGPU rule layer with safe host-buffer boundaries.
- init(count, rule_type, weight, param_a, param_b, tau_e, target_sum_weights)
- step(pre_spikes, post_spikes, rewards, dt)
- Advance one exactly sized WGPU probability batch.
- step_analog(pre_probs, post_probs, rewards, dt, seed)
- Advance probability vectors after optionally reseeding WGPU.
- get_weights()
- Return a detached copy of all WGPU-managed weights.
- get_state_dict()
- Return the portable WGPU weight state.
- load_state_dict(state_dict)
- Restore weights through the length-aware WGPU Rust ABI.
- reset()
- Clear WGPU plasticity traces while preserving weights.
Module accel.adaptive_threshold_if¶
Function backend_available(backend)¶
Return whether one maintained execution lane is ready.
Parameters¶
backend : str
One of python, rust, julia, go, or mojo.
Returns¶
bool
True when the named runtime and its Model41 artefact are available.
Function auto_backend()¶
Return the first available runtime in measured ascending-latency order.
Returns¶
str
An available backend name, with python as the total fallback.
Function normalise_result(result)¶
Validate complete state/spike traces and scalar final receipts.
Parameters¶
result : dict[str, object]
Backend mapping with v, theta, spikes, both final states,
and an integral spike_count.
n_steps : int
Required length of every trajectory.
initial : tuple[float, float]
Initial v and theta used to validate an empty batch.
v_reset : float
Membrane potential reset installed at every spike.
theta_rest : float
Baseline threshold of the exact relaxation.
delta_theta : float
Fixed post-spike threshold shift.
tau_theta : float
Threshold relaxation time constant.
dt : float
Sampling interval.
Returns¶
dict[str, numpy.ndarray | float | int] Contiguous finite trajectories and mutually consistent final receipts.
Raises¶
FloatingPointError If any backend field is missing, malformed, non-finite, inconsistent, non-binary, or violates the reset/shift contract.
Function simulate_python(v, theta, v_rest, v_reset, theta_rest, delta_theta, tau_m, tau_theta, dt, current)¶
Run the complete batch through the Python golden model.
Parameters¶
v, theta : float Initial membrane potential and adaptive threshold. v_rest, v_reset, theta_rest, delta_theta, tau_m, tau_theta, dt : float Complete exact-relaxation configuration. current : ArrayLike One finite real piecewise-constant current per maintained step.
Returns¶
dict[str, numpy.ndarray | float | int] Complete post-update traces, final states, and spike count.
Raises¶
ValueError If the configuration or current vector violates the public contract. FloatingPointError If a candidate or returned receipt is non-finite.
Function simulate_adaptive_threshold_if(v, theta, v_rest, v_reset, theta_rest, delta_theta, tau_m, tau_theta, dt, current)¶
Run one complete exact-relaxation batch on a selected execution lane.
Parameters¶
v : float, default: -65.0
Initial membrane potential in millivolts.
theta : float, default: -50.0
Initial adaptive threshold in millivolts.
v_rest : float, default: -65.0
Leak reversal potential in millivolts.
v_reset : float, default: -65.0
Post-spike membrane reset in millivolts.
theta_rest : float, default: -50.0
Baseline threshold in millivolts; must exceed v_rest and v_reset.
delta_theta : float, default: 5.0
Fixed non-negative post-spike threshold shift in millivolts.
tau_m : float, default: 10.0
Positive membrane time constant in milliseconds.
tau_theta : float, default: 50.0
Positive threshold relaxation time constant in milliseconds.
dt : float, default: 0.1
Positive piecewise-constant-input sampling interval in milliseconds.
current : ArrayLike
One finite real current value per maintained step.
backend : str, default: "auto"
auto, python, rust, julia, go, or mojo.
Returns¶
dict[str, numpy.ndarray | float | int] Complete state/spike trajectories and final receipts.
Raises¶
ValueError If the configuration, current, or backend name is invalid. RuntimeError If an explicitly requested maintained backend is unavailable. FloatingPointError If a numerical candidate or backend result violates the contract.
Module accel.aihara_map¶
Function backend_available(backend)¶
Return whether one maintained execution lane is ready.
Function auto_backend()¶
Return the first available lane in measured ascending-latency order.
Function normalise_result(result)¶
Validate complete state, graded-output, event traces, and receipts.
Function simulate_python(y, k, alpha, bias, epsilon, current)¶
Run a complete batch through the Python golden model.
Function simulate_aihara_map(y, k, alpha, bias, epsilon, current)¶
Run one complete source-faithful batch on a selected execution lane.
Module accel.alpha¶
Function backend_available(backend)¶
Return whether one maintained execution lane is ready.
Parameters¶
backend : str
One of python, rust, julia, go, or mojo.
Returns¶
bool
True when the named runtime and its Model42 artefact are available.
Function auto_backend()¶
Return the first available runtime in measured ascending-latency order.
Returns¶
str
An available backend name, with python as the total fallback.
Function normalise_result(result)¶
Validate complete state/spike traces and scalar final receipts.
Parameters¶
result : dict[str, object]
Backend mapping with the five state traces, spikes, the five
final states, and an integral spike_count.
n_steps : int
Required length of every trajectory.
initial : tuple[float, float, float, float, float]
Initial v, a_exc, i_exc, a_inh, i_inh used to validate an empty
batch.
v_rest : float
Membrane-potential reset installed at every spike.
Returns¶
dict[str, numpy.ndarray | float | int] Contiguous finite trajectories and mutually consistent final receipts.
Raises¶
FloatingPointError If any backend field is missing, malformed, non-finite, inconsistent, non-binary, or violates the somatic reset contract.
Function simulate_python(v, a_exc, i_exc, a_inh, i_inh, v_rest, v_threshold, tau_v, tau_exc, tau_inh, dt, exc_current, inh_current)¶
Run the complete batch through the Python golden model.
Function simulate_alpha(v, a_exc, i_exc, a_inh, i_inh, v_rest, v_threshold, tau_v, tau_exc, tau_inh, dt, exc_current, inh_current)¶
Run one complete exact-flow batch on a selected execution lane.
Parameters¶
v, a_exc, i_exc, a_inh, i_inh : float, default: 0.0
Initial membrane potential and synaptic cascade states.
v_rest : float, default: 0.0
Leak reversal potential, also the somatic spike reset.
v_threshold : float, default: 1.0
Spike threshold; must exceed v_rest.
tau_v : float, default: 20.0
Positive membrane time constant.
tau_exc, tau_inh : float, default: 5.0 / 10.0
Positive excitatory and inhibitory alpha time constants.
dt : float, default: 1.0
Positive piecewise-constant-input sampling interval.
exc_current : ArrayLike
One finite real excitatory drive value per maintained step.
inh_current : ArrayLike or float, default: 0.0
Inhibitory drive, scalar or matching the excitatory length.
backend : str, default: "auto"
auto, python, rust, julia, go, or mojo.
Returns¶
dict[str, numpy.ndarray | float | int] Complete state/spike trajectories and final receipts.
Raises¶
ValueError If the configuration, currents, or backend name is invalid. RuntimeError If an explicitly requested maintained backend is unavailable. FloatingPointError If a numerical candidate or backend result violates the contract.
Module accel.amari_field¶
Function backend_available(backend)¶
Return whether one named Amari execution lane is currently usable.
Function auto_backend()¶
Return the first available lane in measured latency order.
Function simulate_amari_field(u_init, tau, a_exc, a_width, b_inh, b_width, dx, dt, currents)¶
Run a complete Amari field batch on an explicit maintained backend.
Module accel.backend¶
Class Backend¶
Acceleration backend handle exposing the stable SC inference contract.
- sc_forward(weights_packed, input_probs)
- Run the stochastic forward pass; see :func:
sc_neurocore.accel.sc_forward.
Class NumpyBackend¶
NumPy fallback backend (always available, the bit-true floor).
- sc_forward(weights_packed, input_probs)
- Run the NumPy bit-true stochastic forward pass.
Class RustBackend¶
Rust-accelerated backend over the compiled engine.
- sc_forward(weights_packed, input_probs)
- Run the compiled Rust stochastic forward pass.
Function available_backends()¶
Report which SC inference backends resolve, in fastest-first order.
Returns¶
dict
Mapping of backend name to availability; numpy is always True.
Function get_backend(name)¶
Return an SC inference backend handle.
Parameters¶
name : str, optional
"auto" (default) returns the fastest available backend in
:data:PRIORITY order; a specific name ("rust", "numpy") forces
that backend.
Returns¶
Backend
A handle whose sc_forward matches the documented contract.
Raises¶
ValueError
If name is not "auto" or a known backend name.
RuntimeError
If an explicitly requested backend is unavailable.
Module accel.backend_order¶
Function with_floor(floor)¶
Return :data:ACCELERATORS with floor appended as the always-available tier.
Module accel.backend_selection¶
Function current_cpu()¶
Return the host CPU model string, matching the benchmark harness convention.
Mirrors benchmarks/bench_*.py::_cpu_model so a live host matches a stored
meta.cpu exactly: the /proc/cpuinfo model name line, else
:func:platform.processor, else "unknown".
Function measured_orders()¶
Build {cpu: {kernel: (backends fastest-measured-first)}} from the JSONs.
Cached: the on-disk benchmarks are immutable for the life of the process.
Malformed or non-comparison files (no backends / kernel / meta.cpu)
are skipped silently — they are simply not a usable measurement.
Function select_backend_order(kernel)¶
Return the dispatch order for kernel, reordered from measured benchmarks.
Compiled backends measured on this host's CPU lead, fastest-first; any backend
in static without a measurement keeps its static position after them; the
floor (static[-1]) is always last. With no matching measurement the static
order is returned verbatim.
Module accel.benda_herz¶
Function backend_available(backend)¶
Function auto_backend()¶
Function simulate_benda_herz(currents)¶
Module accel.brunel_wang¶
Function backend_available(backend)¶
Return whether one named Brunel-Wang runtime is executable.
Function auto_backend()¶
Return the first available measured lane, with Python as floor.
Function simulate_brunel_wang(v, ref_remaining, v_rest, v_reset, v_threshold, tau_m, tau_ref, g_ampa_ext, g_ampa_rec, g_nmda, g_gaba, v_ampa, v_nmda, v_gaba, c_m, mg_conc, dt, i_ampa_ext, s_ampa_rec, s_nmda_rec, s_gaba)¶
Run the complete configured four-gate contract on one real backend.
Module accel.coba_lif¶
Function ensure_julia_loaded()¶
Load the executable COBA LIF Julia module when available.
Function ensure_go_loaded()¶
Load the compiled COBA LIF Go C ABI when available.
Function ensure_mojo_loaded()¶
Load the compiled COBA LIF Mojo C ABI when available.
Function simulate_rust(v, g_e, g_i, refractory_time, c_m, g_l, e_l, e_e, e_i, tau_e, tau_i, v_threshold, v_reset, refractory_period, dt, n_steps, current, delta_ge, delta_gi)¶
Run the complete contract through the production Rust engine.
Function simulate_julia(v, g_e, g_i, refractory_time, c_m, g_l, e_l, e_e, e_i, tau_e, tau_i, v_threshold, v_reset, refractory_period, dt, n_steps, current, delta_ge, delta_gi)¶
Run the Julia recurrence with the complete public contract.
Function simulate_go(v, g_e, g_i, refractory_time, c_m, g_l, e_l, e_e, e_i, tau_e, tau_i, v_threshold, v_reset, refractory_period, dt, n_steps, current, delta_ge, delta_gi)¶
Run the Go recurrence through its C ABI.
Function simulate_mojo(v, g_e, g_i, refractory_time, c_m, g_l, e_l, e_e, e_i, tau_e, tau_i, v_threshold, v_reset, refractory_period, dt, n_steps, current, delta_ge, delta_gi)¶
Run the Mojo recurrence through its C ABI.
Module accel.compte_wm¶
Function backend_available(backend)¶
Return whether one named Compte runtime is executable.
Function auto_backend()¶
Return the first executable measured lane, with Python as floor.
Function simulate_compte_wm(v, s_ampa, s_nmda, x_nmda, s_gaba, ref_remaining, g_l, g_ampa, g_nmda, g_gaba, e_l, e_exc, e_inh, c_m, mg, tau_ampa, tau_nmda, tau_x, tau_gaba, alpha_nmda, v_threshold, v_reset, tau_ref, dt, currents, recurrent_events, external_events, inhibitory_events)¶
Run the complete configured Compte contract on one real backend.
Module accel.dpi_neuron¶
Function ensure_julia_loaded()¶
Load the executable DPI Julia module when available.
Function ensure_go_loaded()¶
Load the compiled DPI Go C ABI when available.
Function ensure_mojo_loaded()¶
Load the compiled DPI Mojo C ABI when available.
Function simulate_rust(n_steps, current)¶
Run the factory-default Rust engine recurrence.
Function simulate_rust_complete(i_mem, i_ahp, refractory_time, i_threshold, i_reset, i_rest, i_tau, i_g, i_tau_ahp, i_ga, i_spike, i_0, kappa, alpha, tau, tau_ahp, refractory_period, dt, n_steps, current)¶
Run the complete configurable production Rust batch.
Function simulate_julia(i_mem, i_ahp, refractory_time, i_threshold, i_reset, i_rest, i_tau, i_g, i_tau_ahp, i_ga, i_spike, i_0, kappa, alpha, tau, tau_ahp, refractory_period, dt, n_steps, current)¶
Run the Julia recurrence with the complete circuit contract.
Function simulate_julia_complete(i_mem, i_ahp, refractory_time, i_threshold, i_reset, i_rest, i_tau, i_g, i_tau_ahp, i_ga, i_spike, i_0, kappa, alpha, tau, tau_ahp, refractory_period, dt, n_steps, current)¶
Run the complete configurable Julia batch.
Function simulate_go(i_mem, i_ahp, refractory_time, i_threshold, i_reset, i_rest, i_tau, i_g, i_tau_ahp, i_ga, i_spike, i_0, kappa, alpha, tau, tau_ahp, refractory_period, dt, n_steps, current)¶
Run the Go recurrence through its C ABI.
Function simulate_mojo(i_mem, i_ahp, refractory_time, i_threshold, i_reset, i_rest, i_tau, i_g, i_tau_ahp, i_ga, i_spike, i_0, kappa, alpha, tau, tau_ahp, refractory_period, dt, n_steps, current)¶
Run the Mojo recurrence through its C ABI.
Function simulate_go_complete(i_mem, i_ahp, refractory_time, i_threshold, i_reset, i_rest, i_tau, i_g, i_tau_ahp, i_ga, i_spike, i_0, kappa, alpha, tau, tau_ahp, refractory_period, dt, n_steps, current)¶
Run the complete configurable Go batch through its C ABI.
Function simulate_mojo_complete(i_mem, i_ahp, refractory_time, i_threshold, i_reset, i_rest, i_tau, i_g, i_tau_ahp, i_ga, i_spike, i_0, kappa, alpha, tau, tau_ahp, refractory_period, dt, n_steps, current)¶
Run the complete configurable Mojo batch through its C ABI.
Module accel.dvs_native¶
Function native_executable(backend)¶
Validate the selected operator command without discovery or runtime installation.
Function read_native_recording(path, maximum, executable)¶
Read an owned native event matrix or refuse the entire command response.
Parameters¶
path : pathlib.Path A local converted NPY camera recording. maximum : int Validated returned float64 matrix byte limit. executable : pathlib.Path Validated operator-owned Linux DVS command. backend : {"go", "rust", "julia", "mojo"} Selected implementation used in refusal diagnostics. Julia takes an installed runtime executable and runs the packaged DVS script without startup files.
Returns¶
numpy.ndarray Writable owned C-contiguous four-column float64 events.
Raises¶
RuntimeError Native refusal, timeout, incomplete frame, invalid shape or oversized result. OSError The declared executable cannot be started.
Notes¶
The child inherits the compute process group, receives this parent's PID and has its own 30-second guard before loading the recording reader. The parent bounds startup and communicate together to 30 seconds, kills and reaps on interruption. Input/native buffers and pipe copies consume additional memory; the result budget is not an aggregate memory limit.
Function go_executable()¶
Validate the explicitly declared Go DVS command for existing callers.
Function read_go_recording(path, maximum, executable)¶
Read the declared Go command through the shared guarded binary protocol.
Module accel.dvs_recordings¶
Function read_dvs_recording(path)¶
Read a converted camera recording as an owned row-major event matrix.
Parameters¶
path : pathlib.Path One NPY array with x, y, polarity and millisecond timestamp columns. Versions 1.0, 2.0 and 3.0, either byte order, and C/Fortran layouts are supported. Real integer, Boolean and floating scalar types are converted to float64; extended precision follows NumPy conversion. maximum_bytes : int Returned matrix byte limit, default 64 MiB. Header parsing uses at most 10,000 bytes. Input bytes and temporary copies are additional memory; this is not an aggregate memory cap.
backend : {"auto", "numpy", "go", "rust", "julia", "mojo"} Auto selects one explicitly declared SC_NEUROCORE_DVS_GO_EXE or SC_NEUROCORE_DVS_RUST_EXE, SC_NEUROCORE_DVS_JULIA_EXE or SC_NEUROCORE_DVS_MOJO_EXE, otherwise NumPy; multiple declarations refuse. Julia uses the declared runtime with the packaged script, one thread and startup files disabled. Explicit native selection requires an existing absolute Linux executable. A selected native refusal never falls back to NumPy.
Returns¶
numpy.ndarray Writable owned float64 array with shape (N, 4), without time rescaling.
Raises¶
ValueError Invalid budget, header, shape, nonreal dtype, truncation, extra content or result exceeding its declared budget. Pickle is never invoked. OSError The local recording or native executable is unreadable. RuntimeError A selected native command is unavailable, refuses or violates its bounded protocol.
Notes¶
Geometry, finite values, time monotonicity and manifest identity are checked by the caller's dataset and encoder contracts. No download or synthetic substitution occurs. NumPy is the reference implementation. Each selected native backend reads the recording directly; no native refusal falls back to NumPy.
Module accel.energy_lif¶
Function backend_available(backend)¶
Function auto_backend()¶
Function simulate_energy_lif(currents)¶
Module accel.ermentrout_kopell_pop¶
Function backend_available(backend)¶
Return whether one named execution lane is ready.
Parameters¶
backend : str
One of python, rust, julia, go, or mojo.
Returns¶
bool
True when the corresponding runtime and artefact are available.
Function auto_backend()¶
Return the first available runtime in measured ascending-latency order.
Returns¶
str
Available backend name, with python as the total fallback.
Function normalise_result(result)¶
Validate traces and final-state receipts from one backend.
Parameters¶
result : dict[str, object]
Backend mapping containing r, v, and both final receipts.
n_steps : int
Required trace length.
initial : tuple[float, float]
Initial r and v used to validate an empty batch.
Returns¶
dict[str, numpy.ndarray | float] Contiguous finite traces and consistent scalar final receipts.
Raises¶
FloatingPointError If a trace or final receipt is absent, malformed, non-finite, physically invalid, or inconsistent with the complete trajectory.
Function simulate_python(r, v, tau, delta, eta_bar, coupling, dt, ext_input)¶
Run the complete batch through the Python golden model.
Parameters¶
r, v : float Initial population firing rate and mean membrane potential. tau, delta, eta_bar, coupling, dt : float Complete MPR configuration and explicit-Euler step. ext_input : ArrayLike One finite external drive per step.
Returns¶
dict[str, numpy.ndarray | float] Complete post-update state traces and final-state receipts.
Raises¶
ValueError If the configuration or input vector violates the public contract. FloatingPointError If a candidate state violates the finite non-negative-rate contract.
Function simulate_ermentrout_kopell_pop(r, v, tau, delta, eta_bar, coupling, dt, ext_input)¶
Run one complete MPR Euler batch on a selected execution lane.
Parameters¶
r, v : float
Initial population firing rate and mean membrane potential.
tau, delta, eta_bar, coupling, dt : float
Complete MPR configuration and explicit-Euler step.
ext_input : ArrayLike
One finite external drive value per step.
backend : str, default="auto"
python, rust, julia, go, mojo, or measured
ascending-latency selection.
Returns¶
dict[str, numpy.ndarray | float]
Complete post-update r and v traces plus final receipts.
Raises¶
ValueError If the configuration, input vector, or backend name is invalid. RuntimeError If an explicitly requested compiled backend is unavailable. FloatingPointError If a backend returns malformed, non-finite, negative-rate, or internally inconsistent results.
Notes¶
All native results pass through :func:normalise_result; no partially
validated backend mapping is returned to the caller.
Module accel.escape_rate¶
Function ensure_julia_loaded()¶
Load the committed Julia module when juliacall is available.
Function ensure_go_loaded()¶
Load the staged Go C-shared EscapeRate library.
Function ensure_mojo_loaded()¶
Load the staged Mojo EscapeRate shared library.
Function simulate_rust(v, v_rest, v_reset, v_threshold, tau_m, rho_0, delta_u, resistance, dt, rng_state, n_steps, current)¶
Run the complete contract through the production Rust engine.
Function simulate_julia(v, v_rest, v_reset, v_threshold, tau_m, rho_0, delta_u, resistance, dt, rng_state, n_steps, current)¶
Run the committed Julia recurrence with the complete contract.
Function simulate_go(v, v_rest, v_reset, v_threshold, tau_m, rho_0, delta_u, resistance, dt, rng_state, n_steps, current)¶
Run the Go recurrence through its generated C ABI.
Function simulate_mojo(v, v_rest, v_reset, v_threshold, tau_m, rho_0, delta_u, resistance, dt, rng_state, n_steps, current)¶
Run the Mojo recurrence through its shared-library ABI.
Module accel.event_recordings¶
Function decode_nmnist_recording(raw)¶
Decode N-MNIST bytes with identical address, polarity and timestamp semantics.
Parameters¶
raw : bytes
Complete 40-bit records from one published-format recording.
backend : {"auto", "numpy", "rust", "mojo", "julia", "go"}
auto chooses available native decoders using the host's recorded
benchmark order, then the NumPy floor. Without measurements Rust
precedes Mojo, Julia and Go. Explicit native selection refuses missing libraries.
Operator settings SC_NEUROCORE_DATASET_RUST_LIBRARY ,
SC_NEUROCORE_DATASET_MOJO_LIBRARY and
SC_NEUROCORE_DATASET_GO_LIBRARY select absolute library paths;
Julia requires an explicit operator opt-in and preconfigured JuliaCall
runtime. Loading never installs dependencies or downloads artifacts.
Returns¶
numpy.ndarray
Float64 columns x, y, polarity, timestamp_ms. Microseconds are
divided by 1000 without encoder-dependent scaling or float32 narrowing.
Raises¶
ValueError Records are incomplete or the backend name is unknown. RuntimeError A requested or configured native decoder is unavailable or refuses the input. Native failure never silently substitutes another backend.
Module accel.gpu_backend¶
Function to_device(arr)¶
Move a NumPy array to the active backend (GPU copy or no-op).
Function to_host(arr)¶
Bring an array back to host RAM as a NumPy array.
Function gpu_pack_bitstream(bits)¶
Pack uint8 {0,1} array into uint64 words.
Works on both CuPy and NumPy arrays.
Args:
bits: Shape (N,) or (B, N) of uint8.
Returns¶
Packed uint64 array, shape ``(ceil(N/64),)`` or ``(B, ceil(N/64))``.
Function gpu_vec_and(a, b)¶
Bitwise AND on packed uint64 arrays (SC multiplication).
Function gpu_popcount(packed)¶
Vectorised SWAR popcount on uint64 arrays — returns per-element counts.
On CuPy this runs as a fused GPU kernel; on NumPy it uses the same
SWAR bit-trick as vector_ops.vec_popcount but returns an array
instead of a scalar.
Function gpu_vec_mac(packed_weights, packed_inputs)¶
GPU-accelerated multiply-accumulate for a dense SC layer.
Args:
packed_weights: (n_neurons, n_inputs, n_words) uint64
packed_inputs: (n_inputs, n_words) uint64
Returns¶
``(n_neurons,)`` total bit counts (= SC dot products).
Module accel.iqif¶
Function ensure_julia_loaded()¶
Load the committed Julia IQIF module when juliacall is available.
Function ensure_go_loaded()¶
Load the staged Go IQIF C-shared library.
Function ensure_mojo_loaded()¶
Load the staged Mojo IQIF shared library.
Function backend_available(backend)¶
Return whether one public execution lane is ready.
Function auto_backend()¶
Choose the first available lane from committed measured evidence.
Function normalise_result(trace, spikes, final_v)¶
Reject malformed or lossy backend output before narrowing to int64.
Function simulate_rust(v, v_rest, v_threshold, v_reset, a, b, v_max, v_min, n_steps, current)¶
Run the complete contract through the production Rust engine.
Function simulate_julia(v, v_rest, v_threshold, v_reset, a, b, v_max, v_min, n_steps, current)¶
Run the complete contract through the committed Julia module.
Function simulate_go(v, v_rest, v_threshold, v_reset, a, b, v_max, v_min, n_steps, current)¶
Run the Go recurrence through its generated C ABI.
Function simulate_mojo(v, v_rest, v_threshold, v_reset, a, b, v_max, v_min, n_steps, current)¶
Run the Mojo recurrence through its shared-library ABI.
Module accel.jansen_rit¶
Function backend_available(backend)¶
Return whether one named execution lane is ready.
Parameters¶
backend : str
One of python, rust, julia, go, or mojo.
Returns¶
bool
True when the corresponding runtime and artefact are available.
Function auto_backend()¶
Return the first available runtime in measured ascending-latency order.
Function normalise_result(result)¶
Validate all traces and final-state receipts from one backend.
Function simulate_python(y0, y3, y1, y4, y2, y5, a_exc, b_exc, a_rate, b_rate, c, e0, v0, r, dt, p_ext)¶
Run the equation-(6) batch through the Python golden model.
Function simulate_jansen_rit(y0, y3, y1, y4, y2, y5, a_exc, b_exc, a_rate, b_rate, c, e0, v0, r, dt, p_ext)¶
Run one complete Jansen–Rit batch on a selected execution lane.
Module accel.jax_backend¶
Function to_jax(arr)¶
Move a NumPy array to the JAX device.
Function to_host(arr)¶
Bring a JAX array back to host RAM as a NumPy array.
Function jax_pack_bitstream(bits)¶
Pack uint8 {0,1} array into uint64 words using JAX.
Module accel.jit_kernels¶
Function jit_pack_bits(bitstream, packed_arr)¶
Pack a uint8 bitstream into a uint64 word array.
Parameters¶
bitstream : numpy.ndarray of shape (N,), uint8
Input bits valued in {0, 1}.
packed_arr : numpy.ndarray of shape (N // 64,), uint64
Output array receiving the packed 64-bit words.
Function jit_vec_mac(packed_weights, packed_inputs, outputs)¶
Accumulate a packed bitwise multiply-accumulate (MAC).
Computes outputs[i] = sum(popcount(packed_weights[i] AND packed_inputs)).
Parameters¶
packed_weights : numpy.ndarray of shape (n_neurons, n_inputs, n_words), uint64 Packed synaptic weight bitstreams. packed_inputs : numpy.ndarray of shape (n_inputs, n_words), uint64 Packed input bitstreams. outputs : numpy.ndarray of shape (n_neurons,) Output array receiving the accumulated MAC results.
Module accel.julia.event_recordings¶
Function julia_recording_enabled()¶
Return the explicit Julia opt-in; refuse malformed operator settings.
Function decode_julia_recording(raw)¶
Decode live immutable input into an exclusive float64 destination.
Parameters¶
raw : bytes Complete N-MNIST records. Runtime paths and opt-in are configured before process startup; importing never resolves or installs Julia dependencies.
Returns¶
numpy.ndarray Row-major x, y, polarity and millisecond timestamp columns.
Raises¶
RuntimeError The explicit opt-in, runtime configuration or native call is refused.
Module accel.julia.neurons._runtime¶
Function is_julia_error(error)¶
Return whether error is the maintained Julia bridge exception.
Module accel.julia.neurons.adaptive_threshold_if¶
Function simulate_adaptive_threshold_if(v_init, theta_init, v_rest, v_reset, theta_rest, delta_theta, tau_m, tau_theta, dt, current)¶
Run the Julia exact-relaxation recurrence with typed failure translation.
Module accel.julia.neurons.aihara_map¶
Function simulate_aihara_map(y, k, alpha, bias, epsilon, current)¶
Run a checked Julia batch and translate typed numerical failures.
Module accel.julia.neurons.alpha¶
Function simulate_alpha(v_init, a_exc_init, i_exc_init, a_inh_init, i_inh_init, v_rest, v_threshold, tau_v, tau_exc, tau_inh, dt, exc_current, inh_current)¶
Run the Julia exact-flow recurrence with typed failure translation.
Module accel.julia.neurons.amari_field¶
Function simulate_amari_field(u_init, tau, a_exc, a_width, b_inh, b_width, dx, dt, currents)¶
Run the complete vector batch through the native Julia module.
Module accel.julia.neurons.benda_herz¶
Function simulate_benda_herz(currents)¶
Run a source Benda-Herz trace in Julia.
Function simulate_sc_stochastic_rate_adaptation(currents, uniforms)¶
Run the retained SC recurrence with controlled uniforms in Julia.
Module accel.julia.neurons.brunel_wang¶
Function simulate_brunel_wang(v, ref_remaining, v_rest, v_reset, v_threshold, tau_m, tau_ref, g_ampa_ext, g_ampa_rec, g_nmda, g_gaba, v_ampa, v_nmda, v_gaba, c_m, mg_conc, dt, ext, ampa, nmda, gaba)¶
Run complete voltage, refractory, and event traces in Julia.
Module accel.julia.neurons.compte_wm¶
Function simulate_compte_wm()¶
Run complete Compte membrane, channel, refractory, and event traces.
Module accel.julia.neurons.energy_lif¶
Function simulate_energy_lif(currents)¶
Run the complete source-faithful eLIF trace in Julia.
Function simulate_sc_normalized_energy_lif(currents)¶
Run the complete retained normalized-energy SC trace in Julia.
Module accel.julia.neurons.mat¶
Function simulate_mat(currents)¶
Run a complete non-resetting MAT* state/event trace in Julia.
Function simulate_sc_resetting_mat(currents)¶
Run a complete candidate-first RK4/reset trace in Julia.
Module accel.julia.neurons.mckean¶
Function simulate_mckean(currents)¶
Run a complete source McKean state/event trace in Julia.
Module accel.julia.neurons.nagumo_sato_map¶
Function simulate_nagumo_sato_map(y, k, alpha, bias, current)¶
Run a checked Julia batch and translate typed numerical failures.
Module accel.julia.neurons.non_resetting_lif¶
Function simulate_non_resetting_lif(currents)¶
Run a complete source MAT(1) state/event trace in Julia.
Function simulate_sc_non_resetting_adaptive_lif(currents)¶
Run a complete retained-project state/event trace in Julia.
Module accel.julia.neurons.sc_adaptive_threshold_map¶
Function simulate_sc_adaptive_threshold_map(x, theta, k, beta, gamma, theta_spike, x_threshold, current)¶
Run a checked Julia batch and translate typed numerical failures.
Module accel.julia.neurons.sc_chaotic_map¶
Function simulate_sc_chaotic_map(x, y, k_f, k_s, alpha, delta, x_threshold, current)¶
Module accel.julia.neurons.sigma_delta¶
Function simulate_sigma_delta(currents)¶
Run the complete sampled APSDM trace in Julia.
Function simulate_sc_sigma_delta_accumulator(currents)¶
Run the complete retained bipolar accumulator trace in Julia.
Module accel.lapicque¶
Function ensure_julia_loaded()¶
Load the executable Lapicque Julia module when available.
Function ensure_go_loaded()¶
Load the compiled Lapicque Go C-ABI bridge when available.
Function ensure_mojo_loaded()¶
Load the compiled Lapicque Mojo C ABI when available.
Function simulate_rust(n_steps, current)¶
Run the factory-default Rust engine recurrence.
Function simulate_rust_complete(v, v_rest, v_reset, v_threshold, tau, resistance, dt, capacitance, series_resistance, polarization_resistance, excited, source_profile, n_steps, drive)¶
Run the complete profile-explicit Rust production batch.
Function simulate_julia(v, v_rest, v_reset, v_threshold, tau, resistance, dt, n_steps, current)¶
Run the Julia recurrence with the complete numeric contract.
Function simulate_julia_complete(v, v_rest, v_reset, v_threshold, tau, resistance, dt, capacitance, series_resistance, polarization_resistance, excited, source_profile, n_steps, drive)¶
Run the complete profile-explicit Julia batch.
Function simulate_go(v, v_rest, v_reset, v_threshold, tau, resistance, dt, n_steps, current)¶
Run the Go service recurrence through its C ABI.
Function simulate_go_complete(v, v_rest, v_reset, v_threshold, tau, resistance, dt, capacitance, series_resistance, polarization_resistance, excited, source_profile, n_steps, drive)¶
Run the complete Go batch through its mutation-free C ABI.
Function simulate_mojo(v, v_rest, v_reset, v_threshold, tau, resistance, dt, n_steps, current)¶
Run the Mojo recurrence through its C ABI.
Function simulate_mojo_complete(v, v_rest, v_reset, v_threshold, tau, resistance, dt, capacitance, series_resistance, polarization_resistance, excited, source_profile, n_steps, drive)¶
Run the complete Mojo batch through its mutation-free C ABI.
Module accel.mat¶
Function backend_available(backend)¶
Return whether one named MAT* runtime is executable now.
Function auto_backend()¶
Return the first available measured lane, with Python as floor.
Function simulate_mat(currents)¶
Run the complete configured MAT* contract on one real backend.
Module accel.mcculloch_pitts¶
Function ensure_julia_loaded()¶
Load the committed Julia module when juliacall is available.
Function ensure_go_loaded()¶
Load the staged Go C-shared McCulloch--Pitts library.
Function ensure_mojo_loaded()¶
Load the staged Mojo McCulloch--Pitts shared library.
Function backend_available(backend)¶
Return whether one public execution lane is ready.
Function auto_backend()¶
Choose the first available lane from committed measured evidence.
Function normalise_result(result)¶
Reject malformed native output before returning the public binary trace.
Function math_is_finite_integer(value)¶
Return whether a converted backend scalar is finite and integral.
Function evaluate_rust(theta, counts, flags)¶
Evaluate the complete batch through the production Rust engine.
Function evaluate_julia(theta, counts, flags)¶
Evaluate the complete batch through the committed Julia module.
Function evaluate_go(theta, counts, flags)¶
Evaluate the Go recurrence through its generated C ABI.
Function evaluate_mojo(theta, counts, flags)¶
Evaluate the Mojo recurrence through its shared-library ABI.
Module accel.mckean¶
Function backend_available(backend)¶
Return whether an executable implementation of backend is available.
Function auto_backend()¶
Select the first available backend under the configured policy.
Function simulate_mckean(currents)¶
Execute the complete source state/event trace on one selected runtime.
Module accel.mojo.isa_baseline¶
Function pin_isa(argv)¶
Return argv with --target-cpu x86-64-v3 after its mojo subcommand.
Finds the mojo executable followed by build or run and inserts
the baseline flag immediately after the subcommand. The executable is matched
by basename, so a resolved absolute path (e.g. shutil.which("mojo") →
/home/user/.local/bin/mojo) is pinned exactly like the bare mojo
token — otherwise an absolute-path call site would build an unpinned kernel
that SIGILLs on a non-AVX-512 runner. A *.mojo source file is not matched
(its basename ends in .mojo, not mojo). Idempotent: an argv that
already carries --target-cpu is returned unchanged. A copy is returned;
the input list is not mutated.
Module accel.mojo.runner¶
Class MojoKernelRunner¶
Run the maintained monolithic Mojo kernel suite from Python.
The runner is a subprocess façade over kernels.mojo. It discovers the
kernel bundle at construction time, invokes the pixi-managed Mojo toolchain
for builds and benchmark runs, and keeps Python fallbacks for scalar helper
methods. Those scalar helpers do not attempt hidden Mojo IPC; benchmark
execution remains the explicit Mojo subprocess surface.
Parameters¶
_mojo_dir:
Directory expected to contain kernels.mojo. The default is the
installed package directory.
_pixi_bin:
Absolute pixi executable used to launch the Mojo toolchain.
- post_init()
- Validate the configured Mojo kernel directory.
- build()
- Build
kernels.mojothrough pixi. - run_benchmark(timeout_sec)
- Run the kernel benchmark suite and parse millisecond timings.
- popcount(data)
- Return the Python Hamming weight of packed stochastic words.
- lfsr_encode(seed, threshold, bits)
- Encode a threshold stream with the maintained LFSR-16 fallback.
Module accel.mpi_driver¶
Class MPIDriver¶
Distributed sc-neurocore driver built on MPI.
Handles partitioning and synchronisation of bitstreams across cluster nodes.
- init()
- scatter_workload(global_inputs)
- Distribute a large input array across nodes along axis 0.
- gather_results(local_results)
- Collect per-node result arrays back to the root rank.
- barrier()
- Synchronize all nodes.
Module accel.nagumo_sato_map¶
Function backend_available(backend)¶
Return whether one maintained execution lane is ready.
Function auto_backend()¶
Return the first available lane in measured ascending-latency order.
Function normalise_result(result)¶
Validate complete state/output traces and scalar receipts.
Function math_isfinite(value)¶
Avoid importing a scalar math helper into the public surface.
Function simulate_python(y, k, alpha, bias, current)¶
Run a complete batch through the Python golden model.
Function simulate_nagumo_sato_map(y, k, alpha, bias, current)¶
Run one complete source-faithful batch on a selected lane.
Module accel.non_resetting_lif¶
Function backend_available(backend)¶
Return whether one named MAT(1) runtime is executable now.
Function auto_backend()¶
Return the first available measured lane, with Python as floor.
Function simulate_non_resetting_lif(currents)¶
Run the complete configured source MAT(1) contract on one backend.
Module accel.perfect_integrator¶
Function ensure_julia_loaded()¶
Load the executable perfect-integrator Julia module when available.
Function ensure_go_loaded()¶
Load the compiled perfect-integrator Go C ABI when available.
Function ensure_mojo_loaded()¶
Load the compiled perfect-integrator Mojo C ABI when available.
Function simulate_rust_complete(v, c_m, v_threshold, v_reset, dt, source_profile, n_steps, current)¶
Run the complete profile-explicit Rust production batch.
Function simulate_julia_complete(v, c_m, v_threshold, v_reset, dt, source_profile, n_steps, current)¶
Run the complete profile-explicit Julia batch.
Function simulate_go_complete(v, c_m, v_threshold, v_reset, dt, source_profile, n_steps, current)¶
Run the complete Go batch through its mutation-free C ABI.
Function simulate_mojo_complete(v, c_m, v_threshold, v_reset, dt, source_profile, n_steps, current)¶
Run the complete Mojo batch through its mutation-free C ABI.
Module accel.poisson¶
Function ensure_julia_loaded()¶
Load the committed Julia module when juliacall is available.
Returns¶
bool
True when the Julia recurrence is ready for execution, otherwise
False. Import, source, or runtime failures remain non-fatal probes.
Function ensure_go_loaded()¶
Load the staged Go C-shared Poisson library.
Returns¶
bool
True when the library exports the configured Poisson ABI, otherwise
False.
Function ensure_mojo_loaded()¶
Load the staged Mojo Poisson shared library.
Returns¶
bool
True when the library exports the configured Poisson ABI, otherwise
False.
Function simulate_rust(rate_hz, dt_ms, rng_state, n_steps, rate_override)¶
Run the complete contract through the production Rust engine.
Parameters¶
rate_hz : float
Configured homogeneous rate in hertz.
dt_ms : float
Bin width in milliseconds.
rng_state : int
Non-zero 16-bit LFSR state at batch entry.
n_steps : int
Number of binary time bins to generate.
rate_override : float
Batch rate in hertz, or a negative value to select rate_hz.
Returns¶
events : numpy.ndarray
Validated contiguous uint8 event trace.
final_rng : int
Non-zero 16-bit LFSR state at batch exit.
Raises¶
RuntimeError If the Rust engine boundary is unavailable. FloatingPointError If the engine returns malformed event or RNG data.
Function simulate_julia(rate_hz, dt_ms, rng_state, n_steps, rate_override)¶
Run the committed Julia recurrence with the complete contract.
Parameters¶
rate_hz : float
Configured homogeneous rate in hertz.
dt_ms : float
Bin width in milliseconds.
rng_state : int
Non-zero 16-bit LFSR state at batch entry.
n_steps : int
Number of binary time bins to generate.
rate_override : float
Batch rate in hertz, or a negative value to select rate_hz.
Returns¶
events : numpy.ndarray
Validated contiguous uint8 event trace.
final_rng : int
Non-zero 16-bit LFSR state at batch exit.
Raises¶
RuntimeError If the Julia module is unavailable. FloatingPointError If the module returns malformed event or RNG data.
Function simulate_go(rate_hz, dt_ms, rng_state, n_steps, rate_override)¶
Run the Go recurrence through its generated C ABI.
Parameters¶
rate_hz : float
Configured homogeneous rate in hertz.
dt_ms : float
Bin width in milliseconds.
rng_state : int
Non-zero 16-bit LFSR state at batch entry.
n_steps : int
Number of binary time bins to generate.
rate_override : float
Batch rate in hertz, or a negative value to select rate_hz.
Returns¶
events : numpy.ndarray
Validated contiguous uint8 event trace.
final_rng : int
Non-zero 16-bit LFSR state at batch exit.
Raises¶
RuntimeError If the Go shared library is unavailable. FloatingPointError If the C ABI rejects the contract or returns inconsistent data.
Function simulate_mojo(rate_hz, dt_ms, rng_state, n_steps, rate_override)¶
Run the Mojo recurrence through its shared-library ABI.
Parameters¶
rate_hz : float
Configured homogeneous rate in hertz.
dt_ms : float
Bin width in milliseconds.
rng_state : int
Non-zero 16-bit LFSR state at batch entry.
n_steps : int
Number of binary time bins to generate.
rate_override : float
Batch rate in hertz, or a negative value to select rate_hz.
Returns¶
events : numpy.ndarray
Validated contiguous uint8 event trace.
final_rng : int
Non-zero 16-bit LFSR state at batch exit.
Raises¶
RuntimeError If the Mojo shared library is unavailable. FloatingPointError If the C ABI rejects the contract or returns inconsistent data.
Module accel.quadratic_if¶
Function ensure_julia_loaded()¶
Load the executable Quadratic IF Julia module when available.
Function ensure_go_loaded()¶
Load the compiled Quadratic IF Go C ABI when available.
Function ensure_mojo_loaded()¶
Load the compiled Quadratic IF Mojo C ABI when available.
Function simulate_rust(n_steps, current)¶
Run the factory-default Rust engine exact-flow recurrence.
Function simulate_julia(v, v_reset, v_peak, dt, n_steps, current)¶
Run the Julia recurrence with the complete numeric contract.
Function simulate_go(v, v_reset, v_peak, dt, n_steps, current)¶
Run the Go recurrence through its C ABI.
Function simulate_mojo(v, v_reset, v_peak, dt, n_steps, current)¶
Run the Mojo recurrence through its C ABI.
Function simulate_rust_complete(v, v_reset, v_peak, dt, source_profile, n_steps, current)¶
Run the checked profile-explicit production Rust batch.
Function simulate_julia_complete(v, v_reset, v_peak, dt, source_profile, n_steps, current)¶
Run the checked profile-explicit Julia batch.
Function simulate_go_complete(v, v_reset, v_peak, dt, source_profile, n_steps, current)¶
Run the failure-atomic Go complete C-ABI packet.
Function simulate_mojo_complete(v, v_reset, v_peak, dt, source_profile, n_steps, current)¶
Run the failure-atomic Mojo complete C-ABI packet.
Module accel.resonate_and_fire¶
Function backend_available(backend)¶
Return whether one maintained execution lane is ready.
Parameters¶
backend : str
One of python, rust, julia, go, or mojo.
Returns¶
bool
True when the named runtime and its Model40 artefact are available.
Function auto_backend()¶
Return the first available runtime in measured ascending-latency order.
Returns¶
str
An available backend name, with python as the total fallback.
Function normalise_result(result)¶
Validate complete state/spike traces and scalar final receipts.
Parameters¶
result : dict[str, object]
Backend mapping with x, y, spikes, both final states, and
an integral spike_count.
n_steps : int
Required length of every trajectory.
initial : tuple[float, float]
Initial x and y used to validate an empty batch.
threshold : float
Source voltage-coordinate threshold used to validate spike resets.
Returns¶
dict[str, numpy.ndarray | float | int] Contiguous finite trajectories and mutually consistent final receipts.
Raises¶
FloatingPointError If any backend field is missing, malformed, non-finite, inconsistent, non-binary, or violates the source reset contract.
Function simulate_python(x, y, b, omega, threshold, dt, current)¶
Run the complete batch through the Python golden model.
Parameters¶
x, y : float Initial current-like and voltage-like state coordinates. b, omega, threshold, dt : float Complete exact-flow configuration. current : ArrayLike One finite real piecewise-constant current per maintained step.
Returns¶
dict[str, numpy.ndarray | float | int] Complete post-update traces, final states, and sampled crossing count.
Raises¶
ValueError If the configuration or current vector violates the public contract. FloatingPointError If an exact-flow candidate or returned receipt is non-finite.
Function simulate_resonate_and_fire(x, y, b, omega, threshold, dt, current)¶
Run one complete exact-flow batch on a selected execution lane.
Parameters¶
x, y : float, default: 0.0
Initial current-like and voltage-like state coordinates.
b : float, default: -1.0
Radial damping or growth coefficient.
omega : float, default: 10.0
Positive angular resonance frequency.
threshold : float, default: 1.0
Positive spike threshold on the voltage-like y coordinate.
dt : float, default: 0.01
Positive piecewise-constant-input sampling interval.
current : ArrayLike
One finite real current value per maintained step.
backend : str, default: "auto"
auto, python, rust, julia, go, or mojo.
Returns¶
dict[str, numpy.ndarray | float | int] Complete state/spike trajectories and final receipts.
Raises¶
ValueError If the configuration, current, or backend name is invalid. RuntimeError If an explicitly requested maintained backend is unavailable. FloatingPointError If a numerical candidate or backend result violates the contract.
Module accel.sc_adaptive_threshold_map¶
Function backend_available(backend)¶
Return whether one executable SC adaptive-map lane is ready.
Function auto_backend()¶
Return the first available lane in measured ascending-latency order.
Function normalise_result(result)¶
Validate state traces, upward events, and scalar receipts.
Function simulate_python(x, theta, k, beta, gamma, theta_spike, x_threshold, current)¶
Run a complete batch through the Python project specification.
Function simulate_sc_adaptive_threshold_map(x, theta, k, beta, gamma, theta_spike, x_threshold, current)¶
Run one complete retained-project-model batch on a selected lane.
Module accel.sc_chaotic_map¶
Function backend_available(backend)¶
Return whether one executable SC-map lane is available.
Function auto_backend()¶
Function normalise_result(result)¶
Validate complete traces, edge events, and final receipts.
Function simulate_python(x, y, k_f, k_s, alpha, delta, x_threshold, current)¶
Function simulate_sc_chaotic_map(x, y, k_f, k_s, alpha, delta, x_threshold, current)¶
Module accel.sc_inference¶
Function sc_forward_numpy(weights_packed, input_probs, length, seed)¶
NumPy reference for :func:sc_forward — the bit-true floor.
Parameters¶
weights_packed : array_like
Pre-packed unipolar weight bitstreams, shape (n_out, n_in, n_words)
uint64 with n_words = ceil(length / 64).
input_probs : array_like
Input probabilities, shape (n_in,) float64 in [0, 1].
length : int
Bitstream length.
seed : int, optional
Base LFSR seed for the input encoder.
Returns¶
numpy.ndarray
(n_out,) float64 AND-then-popcount estimate of
weights @ input_probs divided by length.
Raises¶
ValueError
If shapes are inconsistent or probabilities lie outside [0, 1].
Function sc_forward(weights_packed, input_probs)¶
Stochastic forward pass over caller-owned packed weight bitstreams.
Encodes input_probs into LFSR bitstreams, ANDs them against the pre-packed
weights and returns the popcount estimate of weights @ input_probs. The
accelerated and NumPy backends are bit-identical for a fixed seed.
Parameters¶
weights_packed : array_like
(n_out, n_in, n_words) uint64 packed unipolar weight bitstreams.
input_probs : array_like
(n_in,) float64 input probabilities in [0, 1].
length : int
Bitstream length (keyword-only).
backend : str or Backend, optional
"auto" selects the fastest available backend; a name or a
:class:~sc_neurocore.accel.backend.Backend forces one.
seed : int, optional
Base LFSR seed for the input encoder.
Returns¶
numpy.ndarray
(n_out,) float64 estimate of weights @ input_probs.
Module accel.sc_non_resetting_adaptive_lif¶
Function backend_available(backend)¶
Return whether one named retained-project runtime is executable now.
Function auto_backend()¶
Return the first available measured lane, with Python as floor.
Function simulate_sc_non_resetting_adaptive_lif(currents)¶
Run the complete retained-project contract on one real backend.
Module accel.sc_normalized_energy_lif¶
Function backend_available(backend)¶
Function auto_backend()¶
Function simulate_sc_normalized_energy_lif(currents)¶
Module accel.sc_resetting_mat¶
Function backend_available(backend)¶
Return whether one named SC resetting-MAT runtime is executable.
Function auto_backend()¶
Return the first available measured lane, with Python as floor.
Function simulate_sc_resetting_mat(currents)¶
Run the complete configured SC recurrence on one real backend.
Module accel.sc_sigma_delta_accumulator¶
Function backend_available(backend)¶
Function auto_backend()¶
Function simulate_sc_sigma_delta_accumulator(currents)¶
Run the complete retained project contract on one real backend.
Module accel.sc_stochastic_rate_adaptation¶
Function backend_available(backend)¶
Function auto_backend()¶
Function simulate_sc_stochastic_rate_adaptation(currents, uniforms)¶
Module accel.sc_triangular_mckean¶
Function backend_available(backend)¶
Return whether the retained recurrence can execute on backend.
Function auto_backend()¶
Select the first available backend under the configured policy.
Function simulate_sc_triangular_mckean(currents)¶
Execute the complete retained state/event trace on one runtime.
Module accel.shd_recordings¶
Function read_shd_recording(path, index)¶
Read one auditory recording and its label through a selected real reader.
Parameters¶
path : pathlib.Path
Local HDF5 file; the caller verifies dataset-manifest identity.
index : int
Non-negative recording index, identical in all three datasets.
maximum_bytes : int
Event-result byte budget, default 64 MiB. Zero admits empty rows.
HDF5 input vectors, IPC bytes and temporary copies are additional memory.
backend : {"auto", "numpy", "rust", "go", "julia", "mojo"}
Auto uses measured shd-recording order, otherwise Rust, Go, Julia, Mojo then NumPy.
Rust uses SC_NEUROCORE_SHD_RUST_LIBRARY or installed
rust/safety/libshd.so; Go requires an existing
SC_NEUROCORE_SHD_GO_LIBRARY absolute path
or installed go/services/loaders/libshd.so. Its read runs in a
fresh process to separate Julia and system HDF5 shared libraries.
Julia requires an existing absolute SC_NEUROCORE_SHD_JULIA_EXE
executable and system HDF5; its CLI uses only the installed standard
library. Linux parent-death signals bound its lifetime when the caller
disappears. Mojo requires an existing compiled Linux
SC_NEUROCORE_SHD_MOJO_EXE and can select system HDF5 via
SC_NEUROCORE_SHD_MOJO_HDF5_LIBRARY. An attempted native read never silently falls back or downloads a file.
Returns¶
tuple
Writable float64 (events, 4) x/y/polarity/millisecond array and label.
Raises¶
ValueError Index, budget, backend or NumPy recording format is invalid. OSError A NumPy recording is unreadable or native process creation fails. RuntimeError A selected native library is absent, fails, times out or returns invalid data.
Notes¶
The operator owns native library code. Each native read lifetime is 30 seconds; every worker is reaped. Reads do not certify event geometry or finite values.
Module accel.sigma_delta¶
Function backend_available(backend)¶
Function auto_backend()¶
Function simulate_sigma_delta(currents)¶
Run the complete sampled source contract on one real backend.
Module accel.sigmoid_rate¶
Function ensure_julia_loaded()¶
Load the committed Julia module when juliacall is available.
Function ensure_go_loaded()¶
Load the staged Go sigmoid-rate C-shared library.
Function ensure_mojo_loaded()¶
Load the staged Mojo sigmoid-rate shared library.
Function backend_available(backend)¶
Return whether one public execution lane is ready.
Function auto_backend()¶
Choose the first available lane from committed measured evidence.
Function normalise_result(trace, final_rate)¶
Reject malformed or non-atomic backend output before public commit.
Function simulate_rust(r, tau, beta, theta, dt, n_steps, current)¶
Run the complete contract through the production Rust engine.
Function simulate_julia(r, tau, beta, theta, dt, n_steps, current)¶
Run the complete contract through the committed Julia module.
Function simulate_go(r, tau, beta, theta, dt, n_steps, current)¶
Run the Go recurrence through its generated C ABI.
Function simulate_mojo(r, tau, beta, theta, dt, n_steps, current)¶
Run the Mojo recurrence through its exported C ABI.
Module accel.theta¶
Function ensure_julia_loaded()¶
Load the executable Theta Julia module when available.
Function ensure_go_loaded()¶
Load the compiled Theta Go C ABI when available.
Function ensure_mojo_loaded()¶
Load the compiled Theta Mojo C ABI when available.
Function simulate_rust(n_steps, current)¶
Run the factory-default Rust engine exact-flow recurrence.
Function simulate_julia(theta, dt, n_steps, current)¶
Run the Julia recurrence with the complete numeric contract.
Function simulate_go(theta, dt, n_steps, current)¶
Run the Go recurrence through its C ABI.
Function simulate_mojo(theta, dt, n_steps, current)¶
Run the Mojo recurrence through its C ABI.
Function simulate_rust_complete(theta, dt, n_steps, current)¶
Run the checked phase-explicit production Rust batch.
Function simulate_julia_complete(theta, dt, n_steps, current)¶
Run the checked phase-explicit Julia batch.
Function simulate_go_complete(theta, dt, n_steps, current)¶
Run the failure-atomic Go complete C-ABI packet.
Function simulate_mojo_complete(theta, dt, n_steps, current)¶
Run the failure-atomic Mojo complete C-ABI packet.
Module accel.threshold_linear_rate¶
Function ensure_julia_loaded()¶
Load the committed Julia module when juliacall is available.
Function ensure_go_loaded()¶
Load the staged Go threshold-linear C-shared library.
Function ensure_mojo_loaded()¶
Load the staged Mojo threshold-linear shared library.
Function backend_available(backend)¶
Return whether one public execution lane is ready.
Function auto_backend()¶
Choose the first available lane from committed measured evidence.
Function normalise_result(trace, final_rate)¶
Reject malformed or non-atomic backend output before public commit.
Function simulate_rust(r, theta, gain, n_steps, current)¶
Run the complete contract through the production Rust engine.
Function simulate_julia(r, theta, gain, n_steps, current)¶
Run the complete contract through the committed Julia module.
Function simulate_go(r, theta, gain, n_steps, current)¶
Run the Go transfer through its generated C ABI.
Function simulate_mojo(r, theta, gain, n_steps, current)¶
Run the Mojo transfer through its exported C ABI.
Module accel.vector_ops¶
Function pack_bitstream(bitstream)¶
Pack a uint8 bitstream into uint64 words for 64-way parallel processing.
Parameters¶
bitstream : numpy.ndarray of shape (N,) or (Batch, N), uint8, or list[int]
Input bits valued in {0, 1}. Python lists are accepted for the
one-dimensional compatibility path and are converted to uint8.
Returns¶
numpy.ndarray of shape (ceil(N / 64),) or (Batch, ceil(N / 64)), uint64 The packed 64-bit words.
Function unpack_bitstream(packed, original_length, original_shape)¶
Unpacks uint64 array back to uint8 bitstream.
Args: packed: Packed uint64 array (1D or 2D) original_length: Total number of bits to extract original_shape: Optional tuple for reshaping output (batch, length)
Returns¶
Unpacked bitstream of shape (original_length,) or original_shape
Function vec_and(a_packed, b_packed)¶
Bitwise-AND two packed arrays, realising stochastic multiplication.
Function vec_xnor(a_packed, b_packed)¶
Bitwise XNOR on packed arrays. SC bipolar multiplication: P(A XNOR B) = P(A)P(B) + (1-P(A))(1-P(B)).
Function vec_not(packed)¶
Bitwise NOT on packed arrays. SC complement: P(NOT A) = 1 - P(A).
Function vec_mux(select_packed, a_packed, b_packed)¶
Bitwise MUX on packed arrays. SC scaled addition: P(out) = P(sel)P(A) + (1-P(sel))P(B).
When sel is a Bernoulli(0.5) stream, this computes the average (A+B)/2.
Function vec_popcount(packed)¶
Count the total set bits in a packed array, for integration/accumulation.
Module accel.wilson_cowan¶
Function backend_available(backend)¶
Return whether one public execution lane is ready.
Function auto_backend()¶
Choose the first available lane from committed measured evidence.
Function normalise_result(e_trace, i_trace, e_final, i_final)¶
Reject malformed or non-atomic backend output before public commit.
Function simulate_rust(e, i, w_ee, w_ei, w_ie, w_ii, tau_e, tau_i, a, theta, dt, n_steps, current)¶
Run the complete contract through the production Rust engine.
Function simulate_julia(e, i, w_ee, w_ei, w_ie, w_ii, tau_e, tau_i, a, theta, dt, n_steps, current)¶
Run the Julia recurrence through its JuliaCall facade.
Function simulate_go(e, i, w_ee, w_ei, w_ie, w_ii, tau_e, tau_i, a, theta, dt, n_steps, current)¶
Run the Go recurrence through its generated C ABI.
Function simulate_mojo(e, i, w_ee, w_ei, w_ie, w_ii, tau_e, tau_i, a, theta, dt, n_steps, current)¶
Run the Mojo recurrence through its exported C ABI.
Module accel.wong_wang¶
Function backend_available(backend)¶
Return whether one named execution lane is ready.
Parameters¶
backend : str
One of python, rust, julia, go, or mojo.
Returns¶
bool
True when the corresponding runtime and compiled artefact exist.
Function auto_backend()¶
Return the first available backend in ascending measured-latency order.
Returns¶
str
Available runtime name, with python as the fail-safe floor.
Function normalise_result(result)¶
Validate a complete backend result before exposing it publicly.
Parameters¶
result : dict[str, object] Mapping produced by one runtime facade. n_steps : int Required trace length. initial : tuple[float, float, float, float] Initial dynamic states used for empty-batch final validation.
Returns¶
dict[str, numpy.ndarray | float] Contiguous, finite traces and mutually consistent final states.
Raises¶
FloatingPointError If any trace, range, or final-state invariant is violated.
Function simulate_python(s1, s2, noise1, noise2, tau_s, tau_ampa, gamma, j_n, j_cross, i_0, sigma, dt, stim1, stim2, xi)¶
Run the deterministic-sample batch through the Python golden model.
Parameters¶
s1, s2 : float
Initial NMDA gating fractions.
noise1, noise2 : float
Initial Ornstein-Uhlenbeck input-current states.
tau_s, tau_ampa, gamma, j_n, j_cross, i_0, sigma, dt : float
Published reduced-model parameters.
stim1, stim2 : ArrayLike
Per-step external currents.
xi : ArrayLike
Interleaved standard-normal samples of length 2 * n_steps.
Returns¶
dict[str, numpy.ndarray | float] Validated state/rate traces and final dynamic states.
Raises¶
ValueError If a state, parameter, or input violates the numerical contract. FloatingPointError If a complete candidate result violates a state invariant.
Function simulate_wong_wang(s1, s2, noise1, noise2, tau_s, tau_ampa, gamma, j_n, j_cross, i_0, sigma, dt, stim1, stim2, xi)¶
Run one complete Wong-Wang batch on a selected execution lane.
Parameters¶
s1, s2, noise1, noise2 : float Initial dynamic states. tau_s, tau_ampa, gamma, j_n, j_cross, i_0, sigma, dt : float Published reduced-model parameters. stim1, stim2 : ArrayLike Per-step external currents. xi : ArrayLike Interleaved standard-normal samples. backend : str, default="auto" Explicit runtime name or ascending measured-latency selection.
Returns¶
dict[str, numpy.ndarray | float] Validated state/rate traces and final dynamic states.
Raises¶
ValueError If inputs or the backend name violate the public contract. RuntimeError If an explicitly selected runtime is unavailable. FloatingPointError If a runtime returns malformed or physically invalid output.
Module adapters.base¶
Class BaseStochasticAdapter¶
Abstract base class for all domain-specific adapters.
- encode(state)
- Map domain state to stochastic bitstreams.
- step_jax(dt, inputs)
- The JAX-accelerated mathematical kernel for the domain dynamics.
- decode(bitstreams)
- Map stochastic bitstreams back to domain-specific observables.
- get_metrics()
- Return domain-specific metrics (e.g. Coherence, Concentration).
Module adapters.holonomic._jax_compat¶
Function make_rng(seed)¶
Create a PRNG key (JAX) or seed array (NumPy fallback).
Function split_rng(key)¶
Split a PRNG key into two children.
Function uniform(key, shape, minval, maxval)¶
Uniform samples in [minval, maxval).
Function normal(key, shape)¶
Standard normal samples.
Function maybe_jit(fn)¶
JIT-compile if JAX available, otherwise identity.
Module adapters.holonomic.dna_storage¶
Class DNAEncoder¶
Interface for DNA Data Storage. Maps Bitstreams to Nucleotides (A, C, T, G).
- encode(bitstream)
- Converts uint8 {0,1} bitstream to DNA string.
- decode(dna_str)
- Converts DNA string back to bitstream.
Module adapters.holonomic.grn¶
Class GeneticRegulatoryLayer¶
Bio-Hybrid Layer. Neural Activity -> Gene Expression (Protein) -> Neural Param Modulation.
- post_init()
- step(spikes)
- Update protein levels based on spike activity.
- get_threshold_modulators()
- Protein acts as inhibitor: Higher protein -> Higher threshold.
Module adapters.holonomic.l10_fire¶
Class L10_HolonomicParameters¶
Parameters derived from Paper 10 and Topological Insulation specs.
Class L10_FirewallAdapter¶
JAX-traceable adapter for the SCPN Topological Firewall layer.
- init(params, seed)
- encode(domain_state)
- Maps firewall strength to stochastic bitstreams.
- step_jax(dt, inputs)
- Advances the L10 holonomic dynamics using JAX.
- decode(bitstreams)
- Maps bitstreams back to Firewall Integrity index.
- get_metrics()
- Returns L10-specific metrics.
Module adapters.holonomic.l11_noos¶
Class L11_HolonomicParameters¶
Parameters derived from Paper 11 and NTHS specifications.
Class L11_NoosphericAdapter¶
JAX-traceable adapter for the SCPN Noospheric layer.
- init(params, seed)
- encode(domain_state)
- Maps cultural spins to stochastic bitstreams.
- step_jax(dt, inputs)
- Advances the L11 holonomic dynamics using JAX.
- decode(bitstreams)
- Maps bitstreams back to Noospheric Polarization index.
- get_metrics()
- Returns L11-specific metrics like Polarization and Info Density.
Module adapters.holonomic.l12_gaian¶
Class L12_HolonomicParameters¶
Parameters derived from Paper 12 and MQN specifications.
Class L12_GaianAdapter¶
JAX-traceable adapter for the SCPN Ecological-Gaian layer.
- init(params, seed)
- encode(domain_state)
- Maps ecological coherence to stochastic bitstreams.
- step_jax(dt, inputs)
- Advances the L12 holonomic dynamics using JAX.
- decode(bitstreams)
- Maps bitstreams back to Gaian Synchrony Index.
- get_metrics()
- Returns L12-specific metrics like Coherence and Flow.
Module adapters.holonomic.l13_source¶
Class L13_HolonomicParameters¶
Configuration for the Layer 13 source-field adapter.
Parameters¶
n_vacuum_nodes: Number of nodes in the one-dimensional vacuum lattice. bitstream_length: Number of stochastic bits emitted per vacuum node. j_primordial_coupling: Finite nearest-neighbour primordial lattice coupling. h_potential_bias: Finite scalar source-field bias applied to each node. lambda_scission: Finite non-negative symmetry-breaking drive.
Class L13_SourceAdapter¶
JAX-traceable adapter for the SCPN source-field layer.
- init(params, seed)
- Initialise the Layer 13 source-field adapter.
- encode(domain_state)
- Map vacuum potential to stochastic source-field bitstreams.
- step_jax(dt, inputs)
- Advance the L13 holonomic dynamics using JAX-compatible arrays.
- decode(bitstreams)
- Map bitstreams back to primordial source coherence.
- get_metrics()
- Return L13-specific vacuum and Fisher-metric telemetry.
Module adapters.holonomic.l14_trans¶
Class L14_HolonomicParameters¶
Parameters derived from Paper 14 and Keystone Tuning specs.
Class L14_TransdimensionalAdapter¶
JAX-traceable adapter for the SCPN Transdimensional layer.
- init(params, seed)
- encode(domain_state)
- Maps resonance alignment to stochastic bitstreams.
- step_jax(dt, inputs)
- Advances the L14 holonomic dynamics using JAX.
- decode(bitstreams)
- Maps bitstreams back to Brane Alignment index.
- get_metrics()
- Returns L14-specific metrics.
Module adapters.holonomic.l15_cons¶
Class L15_HolonomicParameters¶
Parameters derived from Paper 15 and executive optimization specs.
Class L15_ConsiliumAdapter¶
JAX-traceable adapter for the SCPN Consilium layer.
- init(params, seed)
- encode(domain_state)
- Maps executive optimization state to stochastic bitstreams.
- step_jax(dt, inputs)
- Advances the L15 holonomic dynamics using JAX.
- decode(bitstreams)
- Maps bitstreams back to Global Coherence Index.
- get_metrics()
- Returns L15-specific metrics.
Module adapters.holonomic.l16_meta¶
Class L16_HolonomicParameters¶
Parameters derived from Paper 16 and Meta-Layer specifications.
Class L16_MetaAdapter¶
JAX-traceable adapter for the SCPN Cybernetic Closure layer (The Director).
- init(params, seed)
- encode(domain_state)
- Maps director's will to stochastic bitstreams.
- step_jax(dt, inputs)
- Advances the L16 holonomic dynamics using JAX.
- decode(bitstreams)
- Maps bitstreams back to Cybernetic Will index.
- get_metrics()
- Returns L16-specific metrics.
Module adapters.holonomic.l1_quantum¶
Class L1_HolonomicParameters¶
Parameters derived from Paper 1 and Monograph 28.
Class L1_QuantumAdapter¶
JAX-traceable adapter for the SCPN Quantum Biological layer.
- init(params, seed)
- encode(domain_state)
- Maps coherence probabilities to stochastic bitstreams.
- step_jax(dt, inputs)
- Advances the L1 holonomic dynamics using JAX.
- decode(bitstreams)
- Maps bitstreams back to global coherence metric.
- get_metrics()
- Returns L1-specific metrics like Coherence and Pumping levels.
Module adapters.holonomic.l2_chem¶
Class L2_HolonomicParameters¶
Parameters derived from Paper 2 and Monograph 28.
Class L2_NeurochemicalAdapter¶
JAX-traceable adapter for the SCPN Neurochemical layer.
- init(params, seed)
- encode(domain_state)
- Maps neurochemical concentrations to stochastic bitstreams.
- step_jax(dt, inputs)
- Advances the L2 holonomic dynamics using JAX.
- decode(bitstreams)
- Maps bitstreams back to neurochemical concentrations.
- get_metrics()
- Returns L2-specific metrics like Field Potential and Tonus.
Module adapters.holonomic.l3_gen¶
Class L3_HolonomicParameters¶
Parameters derived from Paper 3 and the CBC Bridge specification.
Class L3_GenomicAdapter¶
JAX-traceable adapter for the SCPN Genomic/Epigenomic layer.
- init(params, seed)
- encode(domain_state)
- Maps accessibility states to stochastic bitstreams.
- step_jax(dt, inputs)
- Advances the L3 CBC bridge dynamics using JAX.
- decode(bitstreams)
- Maps bitstreams back to average genomic accessibility.
- get_metrics()
- Returns L3-specific metrics like Spin Polarization and Bio-Potential.
Module adapters.holonomic.l4_cell¶
Class L4_HolonomicParameters¶
Parameters derived from Paper 4 and T7 Validation protocols.
Class L4_CellularAdapter¶
JAX-traceable adapter for the SCPN Cellular-Tissue layer.
- init(params, seed)
- encode(domain_state)
- Maps synchronization activity to stochastic bitstreams.
- step_jax(dt, inputs)
- Advances the L4 holonomic dynamics using JAX.
- decode(bitstreams)
- Maps bitstreams back to Kuramoto order parameter.
- get_metrics()
- Returns L4-specific metrics.
Module adapters.holonomic.l5_org¶
Class L5_HolonomicParameters¶
Parameters derived from Paper 5 and FEP (Free Energy Principle).
Class L5_OrganismalAdapter¶
JAX-traceable adapter for the SCPN Organismal-Psychoemotional layer.
- init(params, seed)
- encode(domain_state)
- Maps organismal state to stochastic bitstreams.
- step_jax(dt, inputs)
- Advances the L5 holonomic dynamics using JAX.
- decode(bitstreams)
- Maps bitstreams back to average valence and HRV coherence.
- get_metrics()
- Returns L5-specific metrics.
Module adapters.holonomic.l6_plan¶
Class L6_HolonomicParameters¶
Configuration for the Layer 6 Gaia-field adapter.
Parameters¶
n_regions:
Number of regional planetary field nodes.
bitstream_length:
Number of stochastic bits emitted per region.
f_schumann:
Positive finite Schumann resonance frequency in hertz.
q_factor:
Positive finite cavity quality factor.
alpha_gaia:
Positive finite regional-to-planetary coupling strength.
p_percolation:
Critical percolation threshold in the open interval (0, 1).
Class L6_PlanetaryAdapter¶
JAX-traceable adapter for the SCPN planetary-biospheric layer.
- init(params, seed)
- Initialise the Layer 6 planetary adapter.
- encode(domain_state)
- Map planetary coherence to stochastic regional bitstreams.
- step_jax(dt, inputs)
- Advance the L6 holonomic dynamics using JAX-compatible arrays.
- decode(bitstreams)
- Map bitstreams back to the global coherence index.
- get_metrics()
- Return L6-specific Gaia and Schumann telemetry.
Module adapters.holonomic.l7_sym¶
Class L7_HolonomicParameters¶
Parameters derived from Paper 7 and Metatron's Cube geometry.
Class L7_SymbolicAdapter¶
JAX-traceable adapter for the SCPN geometrical-symbolic layer.
- init(params, seed)
- encode(domain_state)
- Map symbolic phases to stochastic bitstreams.
- step_jax(dt, inputs)
- Advances the L7 holonomic dynamics using JAX.
- decode(bitstreams)
- Map bitstreams back to symbolic coherence telemetry.
- get_metrics()
- Return L7-specific routing and phase-stability metrics.
Module adapters.holonomic.l8_cosm¶
Class L8_HolonomicParameters¶
Parameters derived from Paper 8 and PTA specifications.
Class L8_CosmicAdapter¶
JAX-traceable adapter for the SCPN Cosmic Phase-Locking layer.
- init(params, seed)
- encode(domain_state)
- Maps cosmic phases to stochastic bitstreams.
- step_jax(dt, inputs)
- Advances the L8 holonomic dynamics using JAX.
- decode(bitstreams)
- Maps bitstreams back to Cosmic Alignment.
- get_metrics()
- Returns L8-specific metrics.
Module adapters.holonomic.l9_mem¶
Class L9_HolonomicParameters¶
Configuration for the Layer 9 TSVF memory adapter.
Parameters¶
n_memory_slots: Number of holographic memory rows retained by the adapter. bitstream_length: Number of stochastic bits carried by each memory row. retrieval_gain: Non-negative multiplier applied to the total TSVF overlap. weak_measurement_strength: Bounded measurement coupling reserved for the TSVF update kernel. temporal_window: Positive temporal-memory window used by downstream Layer 9 consumers.
Class L9_MemoryAdapter¶
JAX-traceable adapter for the SCPN existential-memory layer.
- init(params, seed)
- Initialise the Layer 9 memory adapter.
- encode(domain_state)
- Map memory imprints to stochastic bitstreams via TSVF overlap.
- step_jax(dt, inputs)
- Advance the L9 holonomic dynamics using JAX-compatible arrays.
- decode(bitstreams)
- Map bitstreams back to memory-retrieval quality.
- get_metrics()
- Return L9-specific overlap and imprint-density metrics.
Module adapters.holonomic.neuromodulation¶
Class NeuromodulatorSystem¶
Global Emotional/Chemical System. Modulates neuron parameters based on Dopamine (DA), Serotonin (5HT), Norepinephrine (NE).
- update_levels(reward, stress)
- Adjust chemicals based on environmental feedback.
- modulate_neuron(neuron_params)
- Returns modified parameters for a StochasticLIFNeuron.
Module adapters.importers¶
Class NeuroMLImporter¶
Class-oriented registry surface for NeuroML 2 cell imports.
- import_cells(path)
- Parse a NeuroML 2 XML file into imported cell definitions.
- create_neuron(cell)
- Instantiate a neuron from a parsed NeuroML cell definition.
Class SONATAImporter¶
Class-oriented registry surface for SONATA network imports.
- import_network(nodes_path, edges_path)
- Import a SONATA network from nodes and optional edges files.
Class SpikeInterfaceImporter¶
Class-oriented registry surface for spike-train conversion imports.
- to_bitstreams(spike_times, duration_ms, dt)
- Convert spike times to a binary bitstream matrix.
- to_population_input(spike_times, duration_ms, dt)
- Convert spike times to
Population.step_allinput. - to_probabilities(spike_times, duration_ms, max_rate_hz)
- Convert spike trains into bounded stochastic-computing probabilities.
Module adapters.neuroml¶
Class ImportedCell¶
Result of importing a NeuroML cell definition.
Attributes¶
notes : tuple of str What the mapping to the SC-NeuroCore model assumed, approximated or could not carry, in words a user can check against the document.
Function import_neuroml(path)¶
Parse a NeuroML 2 document and return its point-cell definitions.
Parameters¶
path : str or Path Path to .nml or .xml file.
Returns¶
list of ImportedCell
One per cell definition, each with its mapping notes.
Raises¶
ValueError
The root is not a <neuroml> element, the document holds an element
this importer does not model, or a cell attribute is missing, lacks
its unit, has a unit of the wrong dimension or is out of range.
Function create_neuron(cell)¶
Instantiate an SC-NeuroCore neuron from an ImportedCell.
Returns a neuron object ready for .step() calls.
Module adapters.sonata¶
Class SONATANode¶
A single node (neuron) from a SONATA population.
node_id is the node's id within population; model_type and
model_template are None when the file does not state them.
Class SONATAEdge¶
A single edge (synapse) from a SONATA population.
source_id and target_id are ids within source_population and
target_population; weight and delay are None when the file
does not state them.
Class SONATANetwork¶
Parsed SONATA network with nodes and edges.
node_populations maps each node population name to its node ids, and
edge_populations each edge population name to indices into edges.
metadata records the file's SONATA version and how many edges state no
weight or no delay.
- n_nodes()
- n_edges()
- connectivity_matrix()
- Build the dense connectivity matrix (n_nodes x n_nodes), rows = targets.
Function import_sonata_nodes(path)¶
Parse a SONATA nodes HDF5 file through libsonata.
Returns¶
list of SONATANode Every node of every population, populations in name order.
Raises¶
ValueError
The file is not a SONATA file, has no node population, or a population
lacks node_type_id.
Function import_sonata_edges(path)¶
Parse a SONATA edges HDF5 file through libsonata.
Returns¶
list of SONATAEdge Every edge of every population, populations in name order.
Raises¶
ValueError
The file is not a SONATA file or a population lacks edge_type_id.
Function import_sonata(nodes_path, edges_path)¶
Import a complete SONATA network from nodes + edges files.
Parameters¶
nodes_path : path to nodes.h5 edges_path : path to edges.h5 (optional)
Returns¶
SONATANetwork Parsed nodes, edges, populations and version metadata.
Raises¶
ValueError A file is not SONATA or is incomplete, or an edge names a node the nodes file does not contain.
Module adapters.spikeinterface¶
Function spike_trains_to_bitstreams(spike_times, duration_ms, dt)¶
Convert spike times to binary bitstream matrix.
Parameters¶
spike_times : dict mapping unit_id → array of spike times (ms) duration_ms : float Total recording duration in ms. dt : float Time bin width in ms.
Returns¶
np.ndarray Shape (n_units, n_bins), dtype uint8, binary {0, 1}.
Function spike_trains_to_population_input(spike_times, duration_ms, dt)¶
Convert spike times to current input array for Population.step_all().
Each spike becomes a current pulse of amplitude 1.0 at the spike time bin.
Parameters¶
spike_times : dict mapping unit_id → array of spike times (ms) duration_ms : float dt : float
Returns¶
np.ndarray Shape (n_timesteps, n_units), suitable for time-stepped simulation.
Function firing_rates_to_sc_probs(spike_times, duration_ms, max_rate_hz)¶
Convert firing rates to SC probabilities in [0, 1].
Parameters¶
spike_times : dict mapping unit_id → array of spike times (ms) duration_ms : float max_rate_hz : float Rate corresponding to probability 1.0.
Returns¶
np.ndarray Shape (n_units,), probabilities in [0, 1].
Function from_sorting(sorting, dt)¶
Convert a SpikeInterface SortingExtractor to bitstream matrix.
Parameters¶
sorting : spikeinterface.core.BaseSorting SpikeInterface sorting result. dt : float Time bin width in ms.
Returns¶
np.ndarray Shape (n_units, n_bins), dtype uint8.
Module analog_bridge.analog_bridge¶
Class AnalogSubstrateProfile¶
Parameter set for analog/mixed-signal neuromorphic chips.
- brainscales3(cls)
- Return the bundled BrainScaleS-3 substrate profile.
- dynapse2(cls)
- Return the bundled DynapSE-2 substrate profile.
Class AEREvent¶
Address-Event Representation spike event.
Class AnalogBridge¶
Quantize stochastic weights and thresholds for analog substrates.
- init(g_range, v_range, dac_res, profile)
- emit_analog_config(nodes)
- Emit DAC configuration dictionaries for SC weights and LIF nodes.
Class EventDrivenInterface¶
Converts between SC bitstreams and AER event streams.
- init(clock_period_us)
- bitstream_to_events(neuron_id, bitstream)
- Convert a boolean bitstream to a sequence of AER spike events.
- events_to_current(events, duration_us, tau_syn, weight)
- Convert AER events to time-discretized synaptic current trace.
- rate_code(events, window_us)
- Compute firing rate (Hz) from an event list.
Class CalibrationRoutine¶
On-chip characterization loop for analog substrate alignment.
- init(bridge, num_steps)
- sweep_conductance()
- Sweep DAC range and report (dac_value, target_g, actual_g) tuples.
- max_quantization_error()
- Return worst-case quantization error across the conductance range.
- effective_resolution_bits()
- Compute effective number of bits (ENOB) given quantization errors.
Module analysis.explainability¶
Class SpikeToConceptMapper¶
Map spike-vector activity to human-readable semantic concepts.
- init(concept_map)
- explain(spikes)
- Describe the concepts implied by an active spike vector.
Module analysis.phi_estimation¶
Function phi_star(data, tau, backend)¶
Geometric integrated information Phi* (Barrett & Seth 2011).
Phi* = MI(past; future) - min_partition Σ_k MI(past_k; future_k) under the
Gaussian assumption, with each mutual information a difference of covariance
log-determinants (Cholesky form).
Parameters¶
data : numpy.ndarray
Shape (n_channels, n_timesteps) — spike counts or continuous signals.
tau : int, optional
Time lag for the past→future mapping.
backend : str, optional
"auto" selects the fastest available backend (Rust engine when present,
otherwise the NumPy reference); "python", "rust", "julia",
"go" and "mojo" force a specific path.
Returns¶
float
Phi* estimate in nats. Non-negative; 0 means fully reducible.
Function phi_from_spike_trains(spikes, bin_size, tau, backend)¶
Compute Phi* from binary spike trains by binning into spike counts.
Parameters¶
spikes : numpy.ndarray
Shape (n_neurons, n_timesteps), binary {0, 1}.
bin_size : int, optional
Number of timesteps per bin.
tau : int, optional
Time lag in bins.
backend : str, optional
Forwarded to :func:phi_star.
Returns¶
float Phi* in nats.
Module analysis.spike_stats.basic¶
Function spike_times(binary_train, dt)¶
Extract spike times (seconds) from a binary 0/1 array.
Function isi(binary_train, dt)¶
Inter-spike intervals (seconds) from a binary train.
Function firing_rate(binary_train, dt)¶
Mean firing rate (Hz).
Function spike_count(binary_train)¶
Return the total number of spikes in a binary spike train.
Function bin_spike_train(binary_train, bin_size)¶
Bin a binary spike train into spike counts per bin.
Module analysis.spike_stats.causality¶
Function pairwise_granger_causality(source, target, bin_size, order)¶
Return pairwise Granger causality from source to target.
Parameters¶
source: One-dimensional binary or count-valued source spike train. target: One-dimensional binary or count-valued target spike train. bin_size: Positive number of samples per spike-count bin. order: Positive autoregressive model order.
Returns¶
float Log-likelihood ratio. Positive values indicate that past source counts reduce target prediction error under the regularised Granger model.
Raises¶
ValueError
If bin_size or order is not positive, or if either train is not
one-dimensional and finite.
Function conditional_granger_causality(source, target, condition, bin_size, order)¶
Return conditional Granger causality from source to target.
The reduced model predicts target from its own history and the
condition history. The full model adds source history, following the
Geweke conditional Granger construction.
Parameters¶
source: One-dimensional binary or count-valued source spike train. target: One-dimensional binary or count-valued target spike train. condition: One-dimensional binary or count-valued conditioning spike train. bin_size: Positive number of samples per spike-count bin. order: Positive autoregressive model order.
Returns¶
float
Log-likelihood ratio after controlling for condition. Positive
values indicate source-specific predictive information.
Raises¶
ValueError
If bin_size or order is not positive, or if any train is not
one-dimensional and finite.
Function spectral_granger_causality(trains, bin_size, order, n_freqs)¶
Return frequency-domain Granger causality for a spike-train population.
Parameters¶
trains:
Non-empty list of one-dimensional spike trains. All trains must produce
the same number of bins.
bin_size:
Positive number of samples per spike-count bin.
order:
Positive autoregressive model order.
n_freqs:
Positive number of frequencies in the closed interval [0, 0.5].
Returns¶
np.ndarray
Array with shape (n_neurons, n_neurons, n_freqs). Singular transfer
matrices are skipped and leave the corresponding frequency slice at
zero rather than raising during the inverse.
Raises¶
ValueError If any domain parameter is not positive, if the population is empty, if any train is not one-dimensional and finite, or if binned lengths differ.
Function partial_directed_coherence(trains, bin_size, order, n_freqs)¶
Return partial directed coherence for a spike-train population.
Parameters¶
trains:
Non-empty list of one-dimensional spike trains. All trains must produce
the same number of bins.
bin_size:
Positive number of samples per spike-count bin.
order:
Positive autoregressive model order.
n_freqs:
Positive number of frequencies in the closed interval [0, 0.5].
Returns¶
np.ndarray
Normalised PDC tensor with shape (n_neurons, n_neurons, n_freqs).
Raises¶
ValueError If any domain parameter is not positive, if the population is empty, if any train is not one-dimensional and finite, or if binned lengths differ.
Function directed_transfer_function(trains, bin_size, order, n_freqs)¶
Return the directed transfer function for a spike-train population.
Parameters¶
trains:
Non-empty list of one-dimensional spike trains. All trains must produce
the same number of bins.
bin_size:
Positive number of samples per spike-count bin.
order:
Positive autoregressive model order.
n_freqs:
Positive number of frequencies in the closed interval [0, 0.5].
Returns¶
np.ndarray
Normalised DTF tensor with shape (n_neurons, n_neurons, n_freqs).
Singular transfer matrices are skipped and leave the corresponding
frequency slice at zero.
Raises¶
ValueError If any domain parameter is not positive, if the population is empty, if any train is not one-dimensional and finite, or if binned lengths differ.
Module analysis.spike_stats.correlation¶
Function cross_correlation(train_a, train_b, max_lag_ms, dt)¶
Cross-correlogram between two binary spike trains.
Returns (correlation, lags_ms).
Function pairwise_correlation(trains, dt)¶
Pairwise Pearson correlation matrix across neurons.
Function event_synchronization(train_a, train_b, dt, tau_ms)¶
Quian Quiroga et al. 2002 -- event synchronization.
Function spike_train_coherence(train_a, train_b, dt)¶
Magnitude-squared coherence between two binary spike trains.
Returns (coherence, freqs_hz).
Function spike_time_tiling_coefficient(train_a, train_b, dt_param, delta_ms)¶
Spike Time Tiling Coefficient (STTC). Cutts & Eglen 2014.
Corrects for firing rate bias unlike simple coincidence measures.
Function covariance_matrix(trains, bin_size)¶
Spike count covariance matrix across neurons. de la Rocha et al. 2007.
Function autocorrelation_time(binary_train, dt, max_lag_ms)¶
Autocorrelation time (seconds). Integral of normalized autocorrelation until first zero crossing.
Function noise_correlation(trains, bin_size)¶
Noise correlation (trial-to-trial variability correlation). Averbeck & Lee 2006.
Uses residuals after subtracting mean across neurons.
Function signal_correlation(trains, bin_size)¶
Signal correlation (tuning similarity). Pearson correlation of mean responses.
Function spike_count_covariance(trains, window)¶
Windowed spike count covariance. Kohn & Smith 2005.
Function joint_psth(train_a, train_b, bin_size)¶
Joint PSTH (JPSTH) matrix. Aertsen et al. 1989.
Returns 2D histogram of binned spike counts (neuron_a x neuron_b).
Function coincidence_index(train_a, train_b, dt, delta_ms)¶
Coincidence index (kappa). Joris et al. 2006.
Corrects raw coincidence count for expected coincidences from rate.
Module analysis.spike_stats.decoding¶
Function population_vector_decode(trains, preferred_directions, window)¶
Georgopoulos population vector decoding.
Each neuron i has a preferred direction (angle in radians). Decoded direction per time bin = weighted sum of preferred directions. Returns decoded angles per time bin.
Function bayesian_decode(spike_counts, tuning_rates, prior)¶
Bayesian MAP decoder. Dayan & Abbott 2001.
spike_counts: (n_neurons,) observed counts. tuning_rates: (n_stimuli, n_neurons) mean rates per stimulus. prior: (n_stimuli,) prior probabilities. Uniform if None. Returns: MAP stimulus index.
Function maximum_likelihood_decode(spike_counts, tuning_rates)¶
Maximum likelihood stimulus decoder. Dayan & Abbott 2001.
Poisson likelihood: argmax_s prod_j (lambda_j^{n_j} * exp(-lambda_j) / n_j!).
Function linear_discriminant_decode(train_data, labels, test_point)¶
Fisher linear discriminant decoder. Fisher 1936.
train_data: (n_samples, n_features). labels: (n_samples,). test_point: (n_features,). Returns predicted class label.
Function naive_bayes_decode(train_data, labels, test_point)¶
Gaussian naive Bayes decoder. Mitchell 1997.
Assumes feature independence. Returns predicted class label.
Module analysis.spike_stats.dimensionality¶
Function spike_train_pca(trains, n_components, bin_size, backend)¶
PCA on a binned spike-count matrix (neurons × time bins).
Parameters¶
trains : list of numpy.ndarray
Binary spike trains, one per neuron.
n_components : int, optional
Number of principal components to keep.
bin_size : int, optional
Number of timesteps per bin.
backend : str, optional
"auto" selects the fastest measured path — the NumPy/LAPACK reference,
which outperforms the compiled dense-eigendecomposition backends;
"python", "rust", "julia", "go" and "mojo" force a
specific path (the compiled backends are kept for cross-language parity
and portability).
Returns¶
tuple of numpy.ndarray
(projected, explained_variance_ratio); projected is
(n_components, n_bins). Empty arrays when no trains are supplied.
Function demixed_pca(trains_by_condition, n_components, bin_size, backend)¶
Demixed PCA (Kobak et al. 2016) on condition-mean activity.
Separates condition-dependent variance by projecting the grand-mean-centred condition means onto the leading eigenvectors of their covariance.
Parameters¶
trains_by_condition : dict
{condition_id: [binary trains per neuron]}.
n_components : int, optional
Number of components to keep.
bin_size : int, optional
Number of timesteps per bin.
backend : str, optional
See :func:spike_train_pca.
Returns¶
tuple of numpy.ndarray
(projected, explained_variance_ratio); empty arrays when fewer than
two conditions carry data.
Function factor_analysis(trains, n_factors, bin_size, n_iter, backend)¶
Factor analysis via EM (Rubin & Thayer 1982) on binned activity.
The loadings start from a deterministic PCA initialisation (so the result is reproducible and seed-independent) and each EM step solves its symmetric positive-definite systems by Cholesky factorisation.
Parameters¶
trains : list of numpy.ndarray
Binary spike trains, one per neuron.
n_factors : int, optional
Number of latent factors.
bin_size : int, optional
Number of timesteps per bin.
n_iter : int, optional
Number of EM iterations.
backend : str, optional
See :func:spike_train_pca.
Returns¶
tuple of numpy.ndarray
(loadings, uniquenesses) of shapes (n_neurons, n_factors) and
(n_neurons,).
Module analysis.spike_stats.distance¶
Function van_rossum_distance(train_a, train_b, dt, tau_ms)¶
Van Rossum 2001 -- exponential-kernel spike train distance.
Function victor_purpura_distance(times_a, times_b, cost_per_s)¶
Victor-Purpura 1996 -- edit distance between spike time arrays.
Function isi_distance(train_a, train_b, dt)¶
ISI-distance (Kreuz et al. 2007) -- ratio-based ISI comparison.
Function spike_distance(times_a, times_b, t_start, t_end)¶
SPIKE-distance. Kreuz et al. 2013.
Function spike_sync(times_a, times_b, t_start, t_end)¶
SPIKE-synchronization. Kreuz et al. 2015.
Function spike_sync_profile(times_a, times_b, n_bins, t_start, t_end)¶
Binned SPIKE-synchronization profile. Kreuz et al. 2015.
Function spike_profile(times_a, times_b, n_bins, t_start, t_end)¶
Binned SPIKE-distance profile. Kreuz et al. 2013.
Function isi_profile(binary_train_a, binary_train_b, dt, n_bins)¶
Binned ISI-distance profile. Kreuz et al. 2007.
Function adaptive_spike_distance(times_a, times_b, t_start, t_end, cost)¶
Adaptive SPIKE-distance with cost parameter interpolating ISI and SPIKE. Kreuz et al. 2013.
cost=0: pure SPIKE-distance. cost=1: ISI-like weighting.
Function schreiber_similarity(train_a, train_b, dt, sigma_ms)¶
Schreiber et al. 2003 -- spike train similarity via smoothed correlation.
Convolves each train with Gaussian kernel, returns Pearson correlation.
Function hunter_milton_similarity(times_a, times_b, dt_max)¶
Hunter-Milton 2003 similarity.
Function earth_movers_distance(times_a, times_b, t_start, t_end, n_bins)¶
Earth mover's distance between spike time distributions. Rubner et al. 1998.
Function multi_neuron_victor_purpura(spike_times_list, cost_per_s)¶
All-pairs Victor-Purpura distance matrix.
Function generalized_victor_purpura(times_a, times_b, cost_func)¶
Generalized Victor-Purpura with arbitrary cost function. Victor & Purpura 1997.
cost_func(dt) returns the cost of shifting a spike by dt seconds. Default: linear cost q*|dt| with q=1000.
Function spike_distance_matrix(spike_times_list, metric, t_start, t_end)¶
All-pairs spike train distance matrix.
metric: 'spike_distance', 'spike_sync', 'victor_purpura'.
Module analysis.spike_stats.gpfa¶
Function gpfa_pca_init(Y, n_latents, bin_ms)¶
Deterministic PCA initialisation of the GPFA parameters.
The loading matrix C is the top n_latents left singular vectors of the
centred data, scaled by their singular values; a fixed sign convention (each
column's largest-magnitude entry made positive) makes the result reproducible
across runs and BLAS/LAPACK implementations. This replaces the former random
initialisation, so every backend can start the EM from an identical C.
Parameters¶
Y : numpy.ndarray
Binned spike counts, shape (n_neurons, n_bins).
n_latents : int
Number of latent dimensions.
bin_ms : float
Bin width in milliseconds, used to set the GP timescales tau.
Returns¶
tuple
(C, d, R, tau) — loading matrix (n_neurons, n_latents), offset
(n_neurons,), observation-noise covariance (n_neurons, n_neurons)
and GP timescales (n_latents,).
Function gpfa_em(Y, C0, d0, R0, tau, max_iter, tol)¶
Run the GPFA EM loop from a fixed initialisation (NumPy reference floor).
The GP timescales tau are held fixed, so the kernel matrices are constant
across iterations. Returns the filtered trajectories together with the final
parameters and the per-iteration marginal log-likelihoods.
Parameters¶
Y : numpy.ndarray
Binned spike counts, shape (n_neurons, n_bins).
C0, d0, R0 : numpy.ndarray
Initial loading matrix, offset and observation-noise covariance.
tau : numpy.ndarray
GP timescales, shape (n_latents,).
max_iter : int
Maximum EM iterations.
tol : float
Convergence tolerance on the log-likelihood increment.
Returns¶
tuple
(trajectories, C, d, R, log_likelihoods).
Function gpfa(trains, n_latents, bin_ms, dt, max_iter, tol, seed, backend)¶
Extract smooth latent trajectories from parallel spike trains via EM.
The initialisation is deterministic (PCA, see :func:gpfa_pca_init), so the
result is reproducible and identical across acceleration backends up to
floating-point round-off. seed is retained for API compatibility but no
longer affects the result.
Parameters¶
trains : list of numpy.ndarray
Parallel binary/integer spike trains.
n_latents : int, optional
Number of latent dimensions (clamped to min(n_neurons, n_bins)).
bin_ms, dt : float, optional
Bin width (ms) and simulation timestep (s).
max_iter, tol : int, float, optional
EM iteration cap and log-likelihood convergence tolerance.
seed : int, optional
Retained for API compatibility; initialisation is deterministic.
backend : str, optional
"auto" selects the fastest measured backend — the nalgebra-backed
Rust path when the engine is present, otherwise the NumPy reference
("python"); "rust", "julia", "go" and "mojo" run the
parity-verified compiled paths on request.
Returns¶
dict
Keys trajectories, C, d, R, log_likelihoods, tau.
Function gpfa_transform(new_trains, params, bin_ms, dt)¶
Project new spike trains using learned GPFA parameters.
Module analysis.spike_stats.information¶
Function mutual_information(train_a, train_b, bin_size)¶
Mutual information between two binned spike trains (bits).
MI = H(A) + H(B) - H(A,B) using binned spike counts.
Function transfer_entropy(source, target, bin_size, lag)¶
Transfer entropy from source to target spike train (bits).
TE = H(target_future | target_past) - H(target_future | target_past, source_past)
Function spike_train_entropy(binary_train, bin_size, word_length)¶
Spike train entropy via binary word analysis. Strong et al. 1998.
Function noise_entropy(binary_train, n_trials, bin_size, word_length)¶
Noise entropy estimate via splitting train into pseudo-trials. de Ruyter van Steveninck et al. 1997.
Splits the train into n_trials segments, computes entropy per segment, averages.
Function stimulus_specific_information(spike_counts, stimulus_ids)¶
Stimulus-specific information (SSI). Butts 2003.
spike_counts: array of spike counts per trial. stimulus_ids: corresponding stimulus labels. Returns SSI in bits.
Function kozachenko_leonenko_mi(x, y, k)¶
Kozachenko-Leonenko k-NN mutual information estimator. Kraskov et al. 2004.
Function time_rescaling_ks_test(times, rate_func, t_start, t_end)¶
Time-rescaling KS test for point process goodness-of-fit. Brown et al. 2002.
rate_func(t) -> float: conditional intensity function. Returns (ks_statistic, passes_at_95pct).
Module analysis.spike_stats.lfp¶
Function phase_locking_value(binary_train, lfp_signal)¶
Phase locking value (PLV) between spikes and LFP phase.
Extracts instantaneous phase of LFP via Hilbert transform, then computes PLV = |mean(exp(j*phase_at_spikes))|.
Function spike_field_coherence(binary_train, lfp_signal, dt)¶
Spike-field coherence (SFC) between binary train and LFP.
Returns (coherence, freqs_hz). SFC = |S_xy|^2 / (S_xx * S_yy).
Function spike_phase_histogram(binary_train, lfp_signal, n_bins)¶
Histogram of LFP phase at spike times.
Returns (counts, bin_centers_rad) with bins spanning [-pi, pi].
Module analysis.spike_stats.network¶
Function functional_connectivity(trains, max_lag_ms, dt)¶
Infer functional connectivity matrix from peak cross-correlation.
Returns NxN matrix where entry (i,j) is max |cross-correlation| between neuron i and neuron j within +/-max_lag.
Function unitary_events(trains, bin_size, alpha)¶
Unitary event analysis. Gruen et al. 2002.
Detects bins where coincident spikes exceed chance (Poisson assumption). Returns list of significant bin indices.
Function cell_assembly_detection(trains, bin_size, threshold)¶
Cell assembly detection via PCA on binned spike matrix. Lopes-dos-Santos et al. 2013.
Returns list of assemblies (each a list of neuron indices above threshold).
Function synfire_chain_detection(trains, dt, max_delay_ms, min_chain_length)¶
Synfire chain detection via cross-correlation peak ordering. Abeles 1991.
Returns list of chains (ordered neuron indices with sequential activation).
Module analysis.spike_stats.neural_decoders¶
Class POYODecoder¶
Population decoder via spike tokenisation and cross-attention.
Azabou et al. "A Unified, Scalable Framework for Neural Population Decoding." NeurIPS 2023. arXiv:2310.16046.
Architecture: individual spikes are tokenised with learned unit embeddings + sinusoidal temporal encoding. Learnable latent queries attend to the spike tokens via cross-attention (PerceiverIO backbone). Output queries decode from the latent representation.
- post_init()
- Initialise the POYO decoder weights from the seed.
- encode(spike_trains, dt)
- Encode population activity to latent representation.
- decode(latents, output_queries)
- Cross-attention decode from latents.
- reset()
- Clear cached unit embeddings.
Class POSSMDecoder¶
Population decoder via spike tokenisation and diagonal state-space model.
Ryoo et al. "Generalizable, Real-Time Neural Decoding with Hybrid State-Space Models." ICLR 2025. arXiv:2506.05320.
Uses POYO spike tokenisation with a recurrent SSM backbone instead of full attention, enabling causal online prediction at millisecond resolution with up to 9x lower inference cost.
Diagonal SSM recurrence (S4D, Gu et al. 2022): h_t = A_bar h_{t-1} + B_bar x_t y_t = Re(C h_t) + D x_t
Discretisation (zero-order hold): A_bar = exp(dt * A) B_bar = (A_bar - I) * diag(A)^{-1} * B
- post_init()
- Initialise the POSSM decoder state-space parameters from the seed.
- discretise(step_dt)
- Zero-order hold discretisation.
- step(x)
- Single causal SSM step.
- encode_causal(spike_trains, dt)
- Causal online encoding of spike trains.
- reset()
- Reset hidden state to zero.
Class NDT3Decoder¶
Autoregressive neural data transformer for motor decoding.
Ye & Pandarinath. "A Generalist Intracortical Motor Decoder." bioRxiv 2025.02.02.634313.
Bins population spike counts, projects to d_model embeddings, adds positional encoding, and predicts next-bin output via causal (masked) self-attention.
- post_init()
- Initialise the NDT-3 decoder weights from the seed.
- bin_and_embed(spike_trains, dt)
- Bin spike trains and project to embeddings.
- predict_next(embedded)
- Causal autoregressive prediction of next time bin.
- decode(spike_trains, dt)
- Full decode pipeline: bin → embed → causal attention → output.
Class CEBRAEncoder¶
Contrastive embedding encoder for neural data.
Schneider, Lee & Mathis. "Learnable latent embeddings for joint behavioural and neural analysis." Nature 604 (2023). arXiv:2204.00673.
Uses InfoNCE contrastive loss with time-based or behaviour-based positive pair sampling to learn low-dimensional embeddings of neural population activity.
InfoNCE loss (van den Oord et al. 2018): L = -log( exp(sim(z_i, z_j^+) / τ) / Σ_k exp(sim(z_i, z_k) / τ) ) where sim(a, b) = a · b / (||a|| ||b||) (cosine similarity)
- post_init()
- Initialise the CEBRA encoder weights from the seed.
- encode(x)
- Encode neural data through 2-layer MLP.
- cosine_similarity(a, b)
- Pairwise cosine similarity matrix.
- infonce_loss(anchors, positives)
- InfoNCE contrastive loss. van den Oord et al. (2018).
- fit(data, n_steps, time_offset)
- Train encoder with time-contrastive learning.
- transform(data)
- Embed neural data into learned latent space.
Function tokenise_spikes(spike_trains, dt)¶
Convert binary spike trains to sorted (unit_id, timestamp) tokens.
Used by POYO+ and POSSM (Azabou et al. 2023; Ryoo et al. 2025).
Parameters¶
spike_trains : list of 1-D binary arrays (one per neuron). dt : timestep in ms.
Returns¶
unit_ids : int64 array [n_tokens]. timestamps : float64 array [n_tokens] in ms.
Function sinusoidal_position_encode(timestamps, d_model)¶
Sinusoidal position encoding. Vaswani et al. (2017).
PE(t, 2i) = sin(t / 10000^{2i/d}) PE(t, 2i+1) = cos(t / 10000^{2i/d})
Function scaled_dot_product_attention(queries, keys, values)¶
Scaled dot-product attention.
Attention(Q, K, V) = softmax(Q K^T / sqrt(d_k)) V
Module analysis.spike_stats.patterns¶
Function spike_directionality(times_a, times_b, t_start, t_end)¶
Spike directionality. Kreuz et al. 2015.
Returns asymmetry measure in [-1, 1]. Positive: A leads B.
Function spike_train_order(times_list, t_start, t_end)¶
Spike train order matrix. Kreuz et al. 2017.
Returns (n x n) matrix of pairwise directionality values.
Function cubic_higher_order(binary_train, dt, max_lag)¶
Third-order cumulant (bispectrum domain). Nikias & Petropulu 1993.
Returns 2D array C3(tau1, tau2) for lag pairs up to max_lag.
Module analysis.spike_stats.point_process¶
Function conditional_intensity(binary_train, dt, window_ms)¶
Conditional intensity function estimate (Hz). Brown et al. 2004.
Moving-window MLE of the Poisson rate at each time step.
Function isi_hazard_function(binary_train, dt, bins)¶
ISI hazard function h(t) = f(t) / S(t). Tuckwell 1988.
Returns (hazard, bin_centers) where hazard is the failure rate at each ISI duration.
Function isi_survivor_function(binary_train, dt, bins)¶
ISI survivor function S(t) = P(ISI > t). Tuckwell 1988.
Returns (survivor, bin_centers).
Function renewal_density(binary_train, dt, bins)¶
Renewal density h(t) from ISI distribution. Cox 1962.
Returns (density, bin_centers). Density normalized by mean rate.
Module analysis.spike_stats.rate¶
Function instantaneous_rate(binary_train, dt, kernel, sigma_ms)¶
Instantaneous firing rate via kernel convolution (Hz).
Kernels: 'gaussian', 'exponential', 'rectangular'.
Function population_rate(trains, dt, sigma_ms)¶
Population-level instantaneous firing rate (Hz).
Sums all trains then applies Gaussian kernel smoothing.
Function psth(trials, bin_ms, dt)¶
Peri-stimulus time histogram across trials.
Returns (rates_hz, bin_centers_ms).
Module analysis.spike_stats.sorting_quality¶
Function isolation_distance(cluster, noise, backend)¶
Isolation distance (Harris et al. 2001).
The Mahalanobis distance at which the number of noise points reaching the
cluster equals the cluster size — the squared Mahalanobis radius of the
n_cluster-th nearest noise point.
Parameters¶
cluster : numpy.ndarray
Shape (n_cluster, n_features) — the cluster's feature vectors.
noise : numpy.ndarray
Shape (n_noise, n_features) — competing (noise) feature vectors.
backend : str, optional
"auto" selects the fastest available backend (Rust engine when
present, otherwise the NumPy reference); "python", "rust",
"julia", "go" and "mojo" force a specific path.
Returns¶
float
Isolation distance; nan when n_cluster < 2 or fewer noise points
than cluster points are supplied.
Function l_ratio(cluster, noise, backend)¶
L-ratio cluster quality (Schmitzer-Torbert et al. 2005).
The mean over noise points of the chi-squared survival weight
exp(-½ (d²_Mahalanobis - n_features)) (clamped to [0, 1]), normalised
by the cluster size — small for well-isolated clusters.
Parameters¶
cluster : numpy.ndarray
Shape (n_cluster, n_features) — the cluster's feature vectors.
noise : numpy.ndarray
Shape (n_noise, n_features) — competing (noise) feature vectors.
backend : str, optional
Forwarded to the polyglot dispatch (see :func:isolation_distance).
Returns¶
float
L-ratio; nan when n_cluster < 2 or no noise points are supplied.
Function silhouette_score(features, labels)¶
Mean silhouette score. Rousseeuw 1987.
Measures cluster separation: s_i = (b_i - a_i) / max(a_i, b_i).
Function d_prime(cluster_a, cluster_b)¶
d-prime (sensitivity index) between two clusters. Green & Swets 1966.
Uses first principal axis for projection.
Function isi_violation_rate(binary_train, dt, refractory_ms)¶
ISI violation rate: fraction of ISIs below refractory period. Hill et al. 2011.
Function presence_ratio(binary_train, n_bins)¶
Presence ratio: fraction of time bins containing at least one spike. IBL 2019.
Function amplitude_cutoff(amplitudes, bins)¶
Amplitude cutoff estimate. Hill et al. 2011.
Fraction of spikes estimated to be missing below the amplitude histogram peak.
Function snr(waveforms)¶
Signal-to-noise ratio of spike waveforms. Suner et al. 2005.
waveforms: (n_spikes, n_samples). SNR = peak_amplitude / noise_std.
Function nn_hit_rate(cluster, noise, k)¶
Nearest-neighbor hit rate. Chung et al. 2017.
Fraction of cluster points whose k nearest neighbors are also in the cluster.
Function drift_metric(waveforms, timestamps, n_bins)¶
Waveform drift metric. IBL 2019.
Measures change in mean waveform amplitude over time.
Module analysis.spike_stats.spade¶
Function spade_detect(trains, bin_ms, dt, min_support, max_pattern_size, n_surrogates, alpha, seed)¶
Detect repeated spatiotemporal spike patterns with significance testing.
Module analysis.spike_stats.spectral¶
Function power_spectrum(binary_train, dt)¶
Power spectral density of a binary spike train.
Returns (psd, freqs_hz).
Module analysis.spike_stats.statistics¶
Function significance_bootstrap(statistic_func, train_a, train_b, n_surrogates, seed)¶
Bootstrap significance test for a pairwise statistic.
Returns (observed_value, p_value). statistic_func(a, b) -> float.
Module analysis.spike_stats.stimulus¶
Function spike_triggered_average(stimulus, binary_train, window_steps)¶
Spike-triggered average (STA) of a stimulus signal.
Returns the average stimulus snippet preceding each spike.
Function spike_triggered_covariance(stimulus, binary_train, window_steps)¶
Spike-triggered covariance (STC). Schwartz et al. 2006.
Returns covariance matrix of stimulus snippets preceding spikes.
Function spatial_information(binary_train, positions, n_bins, dt)¶
Spatial information (bits/spike). Skaggs et al. 1993.
positions: 1D array of position values (same length as binary_train). SI = sum(p_i * r_i/r_mean * log2(r_i/r_mean)).
Function place_field_detection(binary_train, positions, n_bins, threshold_std, dt)¶
Detect place fields as contiguous bins with rate > mean + threshold_std * std. O'Keefe & Dostrovsky 1971.
Returns list of (field_start, field_end) position values.
Function tuning_curve(binary_train, stimulus_values, n_bins, dt)¶
Compute tuning curve: mean firing rate vs stimulus value. Dayan & Abbott 2001.
Returns (mean_rates, bin_centers).
Module analysis.spike_stats.surrogates¶
Function surrogate_isi_shuffle(binary_train, seed)¶
Generate surrogate by shuffling ISIs. Preserves rate + ISI distribution.
Function surrogate_dither(binary_train, dither_ms, dt, seed)¶
Generate surrogate by jittering each spike time +/-dither_ms.
Function surrogate_trial_shuffle(trains, seed)¶
Shuffle trial order. Destroys trial-to-trial correlation.
Function homogeneous_poisson(rate_hz, duration_s, dt, seed)¶
Generate homogeneous Poisson spike train. Heeger 2000.
Function inhomogeneous_poisson(rate_func, duration_s, dt, seed)¶
Generate inhomogeneous Poisson spike train via thinning. Lewis & Shedler 1979.
rate_func(t) -> float: time-varying rate in Hz.
Function gamma_process(rate_hz, shape, duration_s, dt, seed)¶
Generate gamma-renewal spike train. Kuffler et al. 1957.
shape=1: Poisson. shape>1: more regular. shape<1: more bursty.
Function compound_poisson_process(rate_hz, burst_mean, duration_s, dt, seed)¶
Compound Poisson process: Poisson events each producing a burst. Snyder & Miller 1991.
burst_mean: mean number of spikes per event (Poisson distributed).
Function surrogate_joint_isi(binary_train, seed)¶
Joint-ISI surrogate: preserves ISI distribution and serial ISI correlations. Louis et al. 2010.
Shuffles pairs of consecutive ISIs while preserving their joint statistics.
Function surrogate_bin_shuffling(binary_train, bin_size, seed)¶
Bin-shuffling surrogate: shuffles spikes within bins. Hatsopoulos et al. 2003.
Function surrogate_spike_train_shifting(binary_train, max_shift, seed)¶
Circular shifting surrogate: shifts entire train by random offset. Hatsopoulos et al. 2003.
Module analysis.spike_stats.temporal¶
Function burst_detection(binary_train, dt, max_isi_ms, min_spikes)¶
Detect bursts: consecutive spikes with ISI < max_isi_ms.
Returns list of (start_time_s, end_time_s, spike_count).
Function first_spike_latency(binary_train, dt)¶
Time to first spike (seconds). Returns nan if no spike.
Function response_onset(binary_train, baseline_steps, dt, threshold_sigma)¶
Detect response onset as first bin exceeding baseline + threshold_sigma * std.
Returns onset time (seconds), or nan if no response detected.
Function change_point_detection(binary_train, bin_size, threshold)¶
CUSUM-based change point detection in firing rate. Page 1954.
Returns list of bin indices where significant rate changes occur.
Module analysis.spike_stats.variability¶
Function cv_isi(binary_train, dt)¶
Coefficient of variation of ISI. CV=1 for Poisson, <1 for regular.
Function cv2(binary_train, dt)¶
Local coefficient of variation CV2. Holt et al. 1996.
CV2 = mean(2|ISI_{i+1} - ISI_i| / (ISI_{i+1} + ISI_i)). Less sensitive to firing rate changes than global CV.
Function local_variation(binary_train, dt)¶
Local variation LV. Shinomoto et al. 2003.
LV = (3/(N-1)) * sum((ISI_i - ISI_{i+1})^2 / (ISI_i + ISI_{i+1})^2). LV=1 for Poisson, <1 for regular, >1 for bursty.
Function lvr(binary_train, dt, refractoriness_ms)¶
Revised local variation LvR. Shinomoto et al. 2009.
Corrects LV for refractoriness: LvR = mean(3(1 - 4ISI_iISI_{i+1}/(ISI_i+ISI_{i+1})^2)(1 + 4*R/(ISI_i+ISI_{i+1}))).
Function fano_factor(binary_train, window_ms, dt)¶
Fano factor: variance/mean of spike counts in sliding windows.
Function isi_entropy(binary_train, dt, bins)¶
Shannon entropy of the ISI distribution (bits).
Higher entropy = more irregular. Poisson has maximum entropy for a given rate.
Function lempel_ziv_complexity(binary_train)¶
Lempel-Ziv 1976 complexity. Normalized by N/log2(N).
Function approximate_entropy(binary_train, m, r_factor)¶
Approximate entropy (ApEn). Pincus 1991.
Function sample_entropy(binary_train, m, r_factor)¶
Sample entropy (SampEn). Richman & Moorman 2000.
Function permutation_entropy(binary_train, order, delay)¶
Bandt-Pompe permutation entropy. Bandt & Pompe 2002.
Function hurst_exponent(binary_train, min_window)¶
Hurst exponent via detrended fluctuation analysis (DFA). Peng et al. 1994.
H > 0.5: long-range positive correlation. H < 0.5: anti-correlated.
Function allan_factor(binary_train, dt, n_scales)¶
Allan factor for spike trains. Allan 1966, adapted for point processes.
Returns (af_values, window_sizes_s). AF > 1 indicates fractal clustering.
Function rescaled_range(binary_train, min_window)¶
Hurst exponent via rescaled range (R/S) analysis. Hurst 1951.
Classic alternative to DFA. Returns H from log-log fit of R/S vs scale.
Function complexity_pdf(binary_train, dt, bins)¶
ISI probability density function via histogram. Abeles 1982.
Function optimal_bin_width(binary_train, dt)¶
Shimazaki-Shinomoto 2007 optimal histogram bin width for firing rate.
Minimizes MISE cost C(delta) = (2*mean - var) / (N * delta)^2 over candidate deltas. Returns optimal bin width in seconds.
Function optimal_kernel_bandwidth(binary_train, dt)¶
Silverman's rule-of-thumb bandwidth for ISI kernel density. Silverman 1986.
h = 0.9 * min(std, IQR/1.34) * N^{-1/5}.
Module analysis.spike_stats.waveform¶
Function waveform_width(waveform, dt)¶
Trough-to-peak width (seconds). Bartho et al. 2004.
Measures time from waveform minimum to subsequent maximum.
Function waveform_amplitude(waveform)¶
Peak-to-trough amplitude. Bartho et al. 2004.
Function waveform_repolarization_slope(waveform, dt)¶
Repolarization slope: max dV/dt after trough. Bean 2007.
Function waveform_recovery_slope(waveform, dt)¶
Recovery slope: dV/dt during return to baseline after peak. Bean 2007.
Function waveform_halfwidth(waveform, dt)¶
Half-width: duration at half-minimum amplitude. Bartho et al. 2004.
Function waveform_pt_ratio(waveform)¶
Peak-to-trough ratio. Bartho et al. 2004.
Ratio of post-trough peak amplitude to trough amplitude.
Module arcane_zenith¶
Class ArcaneZenithCognitiveCore¶
A self-improving cognitive primitive combining ArcaneNeuron and Zenith plasticity.
Rather than maintaining static deep-context parameters, the ArcaneZenith module deploys 4 synchronized Zenith meta-plasticity connections controlling physical limits. Zenith plasticity weights ∈ [0, 1] are smoothly mapped to safe biological ranges for each parameter using a sigmoid interpolator.
Example: >>> core = create_arcane_neuron_with_zenith_plasticity(backend="torch") >>> for i in range(10): ... spike = core.step(current=i % 50) >>> print(f"drift={core.neuron.identity_drift:.4f}")
- init(backend)
- step(current)
- Step the unified physical simulation one tick forward.
- step_from_bio_rates(rates)
- Modulate phenomenological bounds leveraging a multi-channel biological firing rate map.
- evaluate_bio_pathway_resilience(rates)
- Run deterministic fault-injection resilience over biological pathways.
- run_meta_learning_episode(currents)
- Run a full outer-loop adaptation episode over a current sequence.
- export_reasoning_trace()
- Export a compact symbolic trace for outer-loop introspection.
- export_symbolic_reasoning_log()
- Export a short symbolic self-verification log for downstream audit.
- step_from_genome(genome)
- Modulate phenomenological bounds leveraging a generated Evo Substrate Genome.
- reset()
- get_state()
- Output serialized limits combining Arcane and Zenith structures natively.
- get_state_dict()
- load_state_dict(state_dict)
Function create_arcane_neuron_with_zenith_plasticity(backend)¶
Seamless factory configuring a unified ArcaneZenith primitive running entirely connected.
Module asic_flow.constraints¶
Class CDCCheckGenerator¶
Generates clock-domain crossing lint scripts.
- generate(design, clock_domains)
- Render CDC checks for explicit domains or the design clock.
Class IRDropGenerator¶
Generates IR drop analysis scripts for OpenROAD.
- generate(pdk, design, toggle_rate)
- Render OpenROAD power-grid analysis at an input toggle fraction.
Class IOPin¶
Specification for one IO pad.
Class IOConstraintGenerator¶
Generates IO placement constraint files.
- generate(pins, design)
- Render one OpenROAD
place_pincommand per supplied IO pin. - auto_assign(signal_names, sides)
- Auto-assign pins to die edges round-robin.
Class LECGenerator¶
Generates Logic Equivalence Checking scripts.
- generate(design)
- Render a Yosys equivalence proof between synthesis and routed RTL.
Module asic_flow.decks¶
Class SynthesisGenerator¶
Generates Yosys synthesis TCL scripts.
- generate(pdk, design)
- Render the Yosys synthesis script for
designandpdk.
Class FloorplanGenerator¶
Generates OpenROAD floorplan TCL scripts.
- generate(pdk, design)
- Render the OpenROAD floorplan and optional two-net power grid.
Class PlaceRouteGenerator¶
Generates OpenROAD place-and-route TCL scripts.
- generate(pdk, design)
- Render the OpenROAD placement, clock-tree, and routing script.
Class SDCGenerator¶
Generates Synopsys Design Constraints (SDC) for STA.
- generate(pdk, design)
- Render clock, IO-delay, reset, fanout, and load constraints.
Class GDSIIExporter¶
Generates GDSII stream-out scripts.
- generate(pdk, design)
- Render open-PDK stream-out commands or a vendor-tool boundary.
Module asic_flow.design¶
Class SCASICOptimisationConfig¶
SC-specific synthesis settings for stochastic neuromorphic datapaths.
- yosys_passes()
- Return the ordered Yosys passes selected for the SC datapath.
Class DesignParams¶
ASIC design parameters.
- clock_period_ns()
- Return the target clock period in nanoseconds.
- die_width_um()
- Return the die width in micrometres.
- die_height_um()
- Return the die height in micrometres.
- core_area_mm2()
- Return the rectangular core area in square millimetres.
Module asic_flow.estimation¶
Class DesignEstimate¶
Uncalibrated pre-synthesis screening estimate for an SC module.
Class PreSynthEstimator¶
Compute deterministic screening values before synthesis.
The legacy coefficients are architectural scaling assumptions, not foundry-characterised PPA models:
- Bitstream ops: ~10 gates/bit
- LIF neuron: ~500 gates
- STDP synapse: ~200 gates
- AER router: ~100 gates/port
Outputs support relative design screening only. They are not physical evidence and must not be presented as post-synthesis or signoff results.
- estimate(cls, n_neurons, n_synapses, bitstream_width, n_aer_ports, pdk)
- Estimate design metrics from architectural parameters.
Module asic_flow.flow¶
Class ASICFlowOutput¶
Complete output of the ASIC tape-out flow.
- to_dict()
- Map canonical bundle filenames to their generated contents.
Class ASICFlowGenerator¶
Top-level generator for the complete ASIC tape-out pipeline.
- generate(pdk, design)
- Generate all deterministic decks for one PDK/design pair.
Class ASICFlowBundle¶
Generated ASIC flow files plus the evidence manifest path.
- to_dict()
- Serialise bundle paths, PDK resolution, and screening estimate.
Function generate_asic_flow_bundle(output_dir)¶
Write a complete ASIC flow deck and evidence manifest in one call.
The helper deliberately does not run Yosys/OpenROAD. It materialises the scripts, resolves the requested PDK paths, records missing artefacts, and adds a pre-synthesis estimate so Python API users can inspect the bundle before launching external EDA tools.
Module asic_flow.hierarchy¶
Class BlockConfig¶
One block in a hierarchical ASIC flow.
Class HierarchicalFlow¶
Multi-block ASIC flow with per-block synthesis + top integration.
- add_block(block)
- Append one logical or hard-macro block to the flow.
- block_names()
- Return block names in deterministic insertion order.
- generate_block_scripts(pdk)
- Generate one Yosys synthesis script per configured block.
- generate_top_integration(pdk)
- Render top-level netlist linkage and hard-macro LEF reads.
Module asic_flow.pdk¶
Class PDKType¶
Process-design-kit families supported by the deck templates.
Class PDKConfig¶
Process Design Kit configuration.
- from_pdk_type(cls, pdk)
- Construct the maintained preset for a process family.
- is_open_source()
- Return whether the process has a maintained open-source file map.
- with_pdk_root(pdk_root)
- Return a copy with
$PDK_ROOTvariables bound topdk_root.
Class ResolvedPDKFiles¶
Resolved file paths required by the open-source ASIC flow.
- required_paths()
- Return the Liberty, cell-LEF, and technology-LEF paths.
- optional_paths()
- Return optional setup, DRC-deck, and LVS-setup paths.
Class PDKResolution¶
Outcome of resolving a PDK against the local filesystem.
- usable_for_synthesis()
- Return whether every synthesis-required PDK file was found.
- usable_for_signoff()
- Return whether required and optional signoff files were found.
Class OpenSourcePDKResolver¶
Resolve Sky130/GF180 file locations without requiring OpenLane at import time.
- resolve(pdk, pdk_root, require_existing)
- Bind
$PDK_ROOTand report missing PDK artefacts.
Class PDKValidationResult¶
Result of PDK sanity check.
Function validate_pdk(pdk)¶
Check PDK configuration for obvious errors.
Function validate_pdk_installation(pdk, pdk_root, require_signoff)¶
Check whether the resolved open-source PDK files are present locally.
Module asic_flow.readiness¶
Class TapeOutChecklist¶
Go/no-go checklist for ASIC tape-out.
- readiness_score()
- Return the fraction of the ten required checks that passed.
- is_tape_out_ready()
- Return whether all ten readiness checks passed.
- failing_checks()
- Return stable field names for every incomplete readiness check.
- from_signoff(summary)
- Populate from a signoff summary.
Module asic_flow.signoff¶
Class SignoffCheckResult¶
Result of one signoff check.
Class SignoffGenerator¶
Generates signoff scripts and evaluates results.
- generate_sta_script(pdk, design)
- Generate OpenSTA timing analysis script.
- generate_drc_script(pdk, design)
- Generate DRC check script (KLayout-based for open PDKs).
- generate_lvs_script(pdk, design)
- Generate LVS check script.
- evaluate_timing(wns, tns, clock_period_ns)
- Evaluate timing signoff from worst/total negative slack.
- evaluate_power(dynamic_mw, leakage_mw, budget_mw)
- Compare dynamic plus leakage power against a milliwatt budget.
- evaluate_area(cell_count, used_area_um2, die_area_um2)
- Compare placed-cell area with the 85 percent utilisation limit.
Class CornerType¶
Process-corner combinations used by multi-corner timing analysis.
Class PVTCorner¶
Process-Voltage-Temperature corner definition.
- label()
- Return a stable corner-temperature-voltage label.
Class MultiCornerAnalysis¶
Generates multi-corner STA scripts for all PVT corners.
- generate(pdk, design, corners)
- Render one OpenSTA analysis section per selected PVT corner.
- worst_slack(per_corner_wns)
- Return the corner with the smallest worst negative slack.
Class OCVConfig¶
On-Chip Variation derating factors.
- generate_sdc_fragment()
- Render early and late cell/net derates as an SDC fragment.
- conservative(cls)
- Return wider early/late derates for screening runs.
Class DRCViolation¶
One DRC rule violation.
Class SignoffSummary¶
Structured signoff summary with pass/fail per check.
- drc_clean()
- Return whether no counted error-severity DRC violation exists.
- all_pass()
- Return whether timing, power, area, DRC, and LVS all pass.
- to_dict()
- Serialise the signoff decision and counted DRC violations.
Module audio.adaptive_engine¶
Class SessionPhase¶
Adaptive audio control phase for a closed-loop session.
Class AdaptiveSessionReport¶
Summary of a completed adaptive audio session.
- to_dict()
- Return a JSON-compatible summary of the adaptive session.
Class AdaptiveAudioEngine¶
Closed-loop adaptive audio controller coupling SSGF with EVS.
Parameters¶
ssgf : SSGFEngine The geometry solver producing audio mappings. evs : EVSEngine The entrainment verification scorer. profile : UserProfile, optional User preferences for chronotype-aware adaptation.
- init(ssgf, evs, profile)
- on_evs_update(snapshot)
- Process one EVS update and return adapted audio parameters.
- get_session_report()
- Generate summary report of the current session.
- current_phase()
- Return the active adaptive-control phase.
- tick()
- Return the number of processed EVS updates.
- reset()
- Reset session state (does not reset SSGF or EVS).
Module audio.evs_engine¶
Class EVSConfig¶
Configuration for FFT-based entrainment scoring.
Attributes¶
sample_rate: EEG sample rate in hertz. fft_window: Number of samples retained in the ring buffer for FFT scoring. baseline_duration_s: Baseline collection duration in seconds. update_interval_samples: Nominal sample interval between external EVS updates.
Class EVSSnapshot¶
Single-tick entrainment verification observation.
Attributes¶
evs_score:
Composite entrainment score in the inclusive range 0 to 100.
relative_increase:
Target-band power increase relative to baseline.
peak_alignment:
Alignment between the spectral peak and target frequency.
band_dominance:
Fraction of total spectral power in the target band.
temporal_consistency:
Stability score computed from recent EVS values.
is_verified:
Whether score and confidence clear the verification threshold.
confidence:
Confidence score derived from the number of scoring updates.
target_hz:
Target entrainment frequency in hertz.
peak_hz:
Dominant measured frequency in hertz.
band_powers:
Per-band FFT power estimates.
timestamp:
Snapshot creation time from time.time().
- to_dict()
- Serialise the snapshot into JSON-compatible telemetry.
Class EVSEngine¶
FFT-based Entrainment Verification Score engine.
Workflow¶
start_baseline()-- begin collecting baseline EEGadd_sample(voltage)-- feed raw EEG samples one at a time- After baseline_duration_s, baseline finalises automatically
set_target(hz)-- set the entrainment target frequency-
compute()returnsEVSSnapshotevery update_interval_samples -
init(cfg)
- Initialise the EVS ring buffer and scoring state.
- start_baseline()
- Begin baseline EEG collection.
- add_sample(voltage)
- Feed one raw EEG voltage sample.
- set_target(hz)
- Set the entrainment target frequency.
- compute()
- Compute current EVS snapshot.
- baseline_done()
- Whether baseline EEG collection has been finalised.
- score_history()
- Return a copy of accumulated EVS scores.
- reset()
- Clear buffers, baseline state, and score history.
Module audio.ssgf_engine¶
Class SSGFConfig¶
Configuration for the SSGF geometry-coupled oscillator engine.
Attributes¶
N: Number of oscillators in the Kuramoto field. z_dim: Length of the latent geometry vector decoded into the symmetric coupling matrix. lr_z: Gradient-descent step size for the latent geometry vector. sigma_g: Scale applied to geometry-derived phase coupling. micro_steps: Number of Kuramoto integration steps per outer geometry update. dt: Integration timestep in seconds. noise: Standard deviation of phase noise injected during each micro-step. K_base: Baseline Kuramoto coupling retained for compatibility with profile tuning surfaces. K_alpha: Adaptive coupling multiplier retained for compatibility with profile tuning surfaces. field_pressure: Cosine field pressure applied as a global steering term. seed: Deterministic NumPy random seed for reproducible initial conditions.
Class SSGFEngine¶
Lightweight SSGF geometry-coupled Kuramoto solver.
Maintains a latent vector z whose decoded geometry matrix W(t) feeds back into the micro-cycle, steering oscillators toward higher global coherence R. Audio-mapping observables are derived from the resulting phase dynamics and spectral properties of W.
- init(cfg)
- Initialise the SSGF state from a deterministic configuration.
- outer_step()
- Advance one SSGF outer cycle.
- get_audio_mapping()
- Derive CCW audio parameters from current SSGF state.
- get_state()
- Return a JSON-compatible snapshot of the current SSGF state.
Module audio.user_profile¶
Class Chronotype¶
Sleep chronotype model (after Dr. Michael Breus).
Each chronotype has a preferred entrainment frequency range and optimal session timing.
Class UserProfile¶
Per-user preference and adaptation model.
Parameters¶
user_id : str Unique user identifier. chronotype : Chronotype Sleep chronotype. baseline_band_powers : dict Resting-state EEG band powers (populated after first baseline). preferred_cost_weights : dict SSGF cost weights tuned to this user. sensitivity_map : dict Per-band sensitivity multipliers (e.g. {"alpha": 1.2}). session_count : int Total completed sessions. preferred_target_hz : float, optional Explicitly set target frequency (overrides chronotype default).
- post_init()
- Populate chronotype-derived defaults for omitted profile maps.
- get_best_target_hz()
- Return the best entrainment target for this user.
- update_from_session(avg_evs, peak_evs, best_target_hz, band_powers)
- Update profile after a completed session.
- to_dict()
- Serialise the profile into JSON-compatible primitive values.
- from_dict(cls, data)
- Build a profile from a dictionary produced by :meth:
to_dict.
Module augmentation.curriculum¶
Class SpikeCurriculum¶
Schedule training difficulty across epochs.
Parameters¶
total_epochs : int Total training epochs. start_timesteps : int Initial sequence length. end_timesteps : int Final sequence length. start_rate_scale : float Initial firing rate multiplier (>1 = amplified = easier). end_rate_scale : float Final firing rate multiplier (1.0 = natural). start_noise : float Initial background noise rate. end_noise : float Final background noise rate. warmup_fraction : float Fraction of epochs for linear warmup (0.0-1.0).
- timesteps(epoch)
- Sequence length for this epoch.
- rate_scale(epoch)
- Return the firing-rate multiplier for the given epoch.
- noise_rate(epoch)
- Background noise rate for this epoch.
- apply_to_spikes(spikes, epoch, seed)
- Apply curriculum-scheduled transforms to a spike tensor.
- schedule_summary()
- Print the curriculum schedule.
Module augmentation.spike_augment¶
Class SpikeAugment¶
Composable spike-domain augmentation.
Parameters¶
jitter_steps : int Max temporal jitter in timesteps (spikes shift +/- jitter). dropout_rate : float Probability of dropping each spike (0.0 = none, 1.0 = all). rate_scale : tuple of float (min_scale, max_scale) for random firing rate scaling. polarity_flip_prob : float Probability of flipping spike polarity (for DVS ON/OFF channels). bg_noise_rate : float Background noise spike probability per neuron per step. hot_pixel_prob : float Probability of a neuron becoming a hot pixel (fires every step). seed : int Random seed for reproducibility.
- call(spikes)
- Apply all augmentations to a spike tensor.
Module autofit.features¶
Function extract_spike_times(voltage, threshold, dt)¶
Find spike times from a voltage trace via threshold crossing.
Function extract_features(voltage, dt, threshold)¶
Extract standard electrophysiology features from a voltage trace.
Returns dict with: spike_times, spike_count, mean_isi, cv_isi, firing_rate, v_rest, v_max, v_min, ap_height, ap_width
Module autofit.fitter¶
Class FittedModel¶
Result of fitting one model to experimental data.
Function fit(voltage, current, dt, threshold, candidates, top_k)¶
Fit neuron models to an experimental voltage recording.
Parameters¶
voltage : ndarray Target voltage trace. current : ndarray Injected current trace (same length as voltage). dt : float Timestep in ms. threshold : float Spike detection threshold. candidates : list of str, optional Model names to try. Default: all fittable models. top_k : int Return top K best-fitting models.
Returns¶
list of FittedModel Sorted by combined_score (lower is better).
Module bci_studio.bci_primitives¶
Class BCIPrimitiveConfig¶
Configuration for the deterministic closed-loop primitive.
- post_init()
Class BCIFrame¶
One raw neural signal frame.
Class BCIFeedbackCommand¶
Feedback command emitted by the primitive.
Packet layout is 24 bytes: [schema:u16, command:u8, flags:u8,
channel:u16, reserved:u16, amplitude:f32, timestamp_us:u64, score:f32].
- to_packet()
- from_packet(cls, packet)
Class BCIClosedLoopTrace¶
Audit trace for one processed frame.
- as_dict()
Class BCIPrimitiveResult¶
Result from one closed-loop primitive step.
- as_legacy_dict()
Class BCIClosedLoopPrimitive¶
Deterministic raw-signal to feedback primitive with audit trace.
- init(config)
- process_frame(frame)
Class BCIClosedLoopEngine¶
Backward-compatible wrapper around :class:BCIClosedLoopPrimitive.
- init(channels)
- weights()
- process_bci_frame(raw_ephys, reward)
Module bci_studio.bci_studio¶
Class SessionMetrics¶
- mean_latency_ms()
- p95_latency_ms()
- spike_rate()
- summary()
Class SpikeCodec¶
SC-domain lossy compression for neural data streams.
Uses run-length encoding on spike trains with delta-time encoding.
- encode(spikes)
- Compress boolean spike array to RLE byte stream.
- decode(data)
- Decompress RLE byte stream back to spike array.
- compression_ratio(original)
- Return compression ratio (original_bytes / compressed_bytes).
Class OnlineLearner¶
Local STDP-inspired weight update rule (pure Python fallback).
- init(num_weights, lr, decay)
- step(spikes, reward)
- Apply reward-modulated STDP update.
Class FPGAFeedbackController¶
Serializes BCI commands for DMA push to FPGA feedback register.
- serialize(command, channel, amplitude, timestamp_us)
- Pack a feedback command into a 16-byte DMA-aligned struct.
- deserialize(data)
- Unpack a feedback command.
Class LatencyProfiler¶
Rolling window latency tracker with percentile reporting.
- init(window_size)
- record(latency_ms)
- mean()
- p50()
- p95()
- p99()
- budget_met()
- True if p95 latency is under 10 ms BCI hard real-time target.
Class BCIStudio¶
End-to-end BCI closed-loop orchestrator.
- init(channels, lr)
- start_session()
- stop_session()
- process_frame(raw_ephys, reward)
- Process a single BCI frame through the full pipeline.
Module benchmarks.metrics¶
Class BenchmarkResult¶
NeuroBench-compatible benchmark result.
- to_neurobench_json()
- Export as NeuroBench-compatible JSON.
- summary()
Function compute_metrics(predictions, targets, spike_counts, weights, timesteps, latency_ms, task, model)¶
Compute NeuroBench-compatible metrics from model outputs.
Parameters¶
predictions : ndarray Model predictions (class indices for classification). targets : ndarray Ground truth labels. spike_counts : ndarray, optional Per-sample total spike counts. weights : list of ndarray, optional Weight matrices for parameter counting. timesteps : int Number of simulation timesteps. latency_ms : float Inference latency in milliseconds. task : str Task name for the report. model : str Model name for the report.
Returns¶
BenchmarkResult
Module benchmarks.mlperf_sc_report¶
Function aggregate_mlperf_sc_results(result_paths)¶
Aggregate validated MLPerf-SC result files into a deterministic report.
Module benchmarks.mlperf_sc_runner¶
Function run_mlperf_sc_fixture()¶
Run the deterministic synthetic MLPerf-SC fixture and return result path.
Module benchmarks.mlperf_sc_schema¶
Class MLPerfSCValidationError¶
Raised when an MLPerf-SC result violates the fail-closed schema.
Class MLPerfSCRun¶
Benchmark run identity and dataset contract.
Class MLPerfSCExecution¶
Execution target and stochastic-computing mode metadata.
Class MLPerfSCArea¶
Hardware utilisation metrics when a synthesis or board path exists.
Class MLPerfSCMetrics¶
Accuracy, latency, energy, power, and area metrics.
Class MLPerfSCArtifact¶
One evidence artifact referenced by the result.
Class MLPerfSCEvidence¶
Evidence class, environment manifest, and raw artifact references.
Class MLPerfSCResult¶
Typed MLPerf-SC benchmark result.
Function validate_mlperf_sc_result(payload)¶
Validate a decoded MLPerf-SC result and return a typed result.
Function mlperf_sc_result_to_dict(result)¶
Serialise a typed MLPerf-SC result to the canonical dictionary shape.
Module benchmarks.online_o1_adaptation¶
Function build_online_o1_adaptation_benchmark()¶
Return a deterministic Python/Rust adaptation benchmark report.
Function write_online_o1_adaptation_benchmark(path)¶
Write a canonical benchmark report and return the output path.
Module benchmarks.stochastic_backprop¶
Function build_stochastic_backprop_benchmark()¶
Return deterministic evidence for SC-aware backpropagation loss reduction.
Function write_stochastic_backprop_benchmark(path)¶
Write a canonical stochastic backpropagation benchmark report.
Function build_stochastic_backprop_estimator_regression_manifest()¶
Return seeded estimator-family variance evidence across bitstream lengths.
Function write_stochastic_backprop_estimator_regression_manifest(path)¶
Write seeded estimator-family regression evidence to canonical JSON.
Module benchmarks.tasks¶
Class BenchmarkTask¶
Definition of a benchmark task.
Module bio.dna_storage¶
Class DNAEncoder¶
Interface for DNA Data Storage. Maps Bitstreams to Nucleotides (A, C, T, G).
- encode(bitstream)
- Converts uint8 {0,1} bitstream to DNA string.
- decode(dna_str)
- Converts DNA string back to bitstream.
Module bio.grn¶
Class GeneticRegulatoryLayer¶
Bio-Hybrid Layer. Neural Activity -> Gene Expression (Protein) -> Neural Param Modulation.
- post_init()
- step(spikes)
- Update protein levels based on spike activity.
- get_threshold_modulators()
- Protein acts as inhibitor: Higher protein -> Higher threshold.
Module bio.neuromodulation¶
Class NeuromodulatorSystem¶
Global Emotional/Chemical System. Modulates neuron parameters based on Dopamine (DA), Serotonin (5HT), Norepinephrine (NE).
- update_levels(reward, stress)
- Adjust chemicals based on environmental feedback.
- modulate_neuron(neuron_params)
- Returns modified parameters for a StochasticLIFNeuron.
Module bio.transcriptomic¶
Class ScKGBERTInterface¶
Knowledge-enhanced foundation model for single-cell transcriptomics.
Li Y, Qiao G, Du H, Gao X, Wang G. "scKGBERT: a knowledge-enhanced foundation model for single-cell transcriptomics." Genome Biology 26:402 (2025).
Dual-encoder architecture: S-Encoder (sequence) + K-Encoder (knowledge graph from STRING PPI database). Uses Gaussian attention for biomarker identification.
Gaussian attention (Li et al. 2025): α_ij = exp(-||q_i - k_j||² / (2σ²)) / Σ_m exp(-||q_i - k_m||² / (2σ²))
This emphasises genes whose query-key distance is small, concentrating attention on biologically relevant gene–gene interactions.
- post_init()
- Initialise the scKG-BERT interface weights from the seed.
- gaussian_attention(queries, keys, values)
- Gaussian attention mechanism. Li et al. (2025).
- encode_expression(expression)
- Encode a single-cell expression profile via S-Encoder.
- encode_with_knowledge(expression)
- Encode via dual S-Encoder + K-Encoder pathway.
- predict_cell_type(expression, prototypes, labels)
- Predict cell type via nearest prototype.
- gene_importance(expression)
- Compute gene importance scores via Gaussian attention weights.
Class GeneformerInterface¶
Rank-value tokenisation and masked gene prediction.
Theodoris CV et al. "Transfer learning enables predictions in network biology." Nature 619 (2023).
Core innovation: each cell's transcriptome is represented as a sequence of gene tokens, ranked by expression scaled by inverse corpus frequency. The model is pretrained with masked gene prediction (analogous to BERT MLM) to learn network dynamics.
- post_init()
- Initialise the Geneformer interface weights from the seed.
- tokenise(expression, global_medians)
- Rank-value tokenisation. Theodoris et al. (2023).
- mask_tokens(token_ids, rng_seed)
- Randomly mask tokens for MLM pretraining.
- multi_head_attention(x)
- Multi-head self-attention. Vaswani et al. (2017).
- encode_cell(expression, global_medians)
- Extract cell-level embedding from expression profile.
- predict_masked_genes(expression, global_medians, rng_seed)
- Masked gene prediction (MLM objective).
- gene_network_attention(expression, global_medians)
- Extract attention-derived gene–gene interaction matrix.
Function rank_value_encode(expression, global_medians)¶
Rank-value encoding for single-cell gene expression.
Theodoris et al. (2023): genes are ranked by their expression in the cell, scaled by inverse frequency across the corpus (approximated by 1 / global_median).
Parameters¶
expression : 1-D array [n_genes], raw counts or normalised expression. global_medians : 1-D array [n_genes], median expression per gene across the corpus. If None, uniform weighting is used.
Returns¶
ranked_indices : int64 array — gene indices sorted by weighted expression (highest first), with zero-expression genes excluded.
Module bioware.bioware_acquisition¶
Class SpikeDetector¶
Threshold-based spike detector for MEA voltage traces.
Uses adaptive threshold: threshold = mean ± sigma * noise_estimate where noise_estimate = median(|x|) / 0.6745 (robust RMS). Supports configurable refractory period to prevent double-counting.
- post_init()
- Validate detector configuration and refractory interval.
- estimate_noise(voltage_data)
- Estimate per-channel noise from voltage data.
- detect(voltage_data, snippet_ms)
- Detect spikes in multi-channel voltage data.
Class SpikeSorter¶
Research spike sorter using PCA feature extraction and K-Means clustering.
Projects uniform waveforms onto their dominant principal components before
clustering them into units. Fitting requires the optional scikit-learn
dependency; incomplete waveform sets remain explicitly unassigned.
- post_init()
- Validate cluster count, projection width, and deterministic seed.
- fit(spikes)
- Fit PCA and KMeans models sequentially on available waveforms.
- assign(spikes)
- Assign cluster IDs based on PCA feature projections.
Class ArtifactRejector¶
Blanks stimulation artifacts from voltage data.
Zeros the voltage trace in a window around each stimulation onset.
- post_init()
- Validate non-negative artifact-blanking intervals.
- blank(voltage_data, stim_times_s, sample_rate_hz)
- Return voltage data with stimulus artifacts blanked.
Module bioware.bioware_analysis¶
Class CultureHealth¶
Monitor organoid/culture viability from MEA activity.
- post_init()
- Validate rate thresholds used by the aggregate health heuristic.
- assess(spike_counts, duration_s)
- Assess culture health from spike activity.
Class LFPBand¶
Frequency band definition for LFP extraction.
- post_init()
- Validate a named half-open frequency interval.
Class LatencyBudget¶
Tracks and enforces closed-loop latency requirements.
- post_init()
- Validate budget, history, and violation accounting.
- record(latency_us)
- Record a latency measurement. Returns True if within budget.
- mean_latency_us()
- Return the arithmetic mean of recorded loop latencies.
- p99_latency_us()
- Return the 99th percentile closed-loop latency.
- compliance_ratio()
- Return the fraction of samples inside the latency budget.
Class NetworkBurst¶
Detected network-wide synchronised burst event.
- post_init()
- Validate a detected network-burst summary.
Function extract_lfp_power(voltage_data, sample_rate_hz, bands)¶
Extract per-channel power in each LFP band.
Uses FFT-based power spectral density estimation. Returns dict of band_name → per-channel power array.
Function detect_network_bursts(spikes, bin_width_s, threshold_sigma, min_channels)¶
Detect network-wide synchronised bursts.
Bins spikes in time, detects bins with activity > threshold_sigma above the mean, and requires participation from ≥ min_channels.
Module bioware.bioware_audit¶
Class BioAuditEntry¶
One audit entry for a bio-hybrid session.
- post_init()
- Validate one timestamped session-audit record.
Class BioAuditLog¶
Tamper-evident in-memory audit log for bio-hybrid experiments.
- post_init()
- Validate experiment identity and strictly ordered audit entries.
- log(entry)
- Append one audit entry to the session log.
- total_rounds()
- Return the number of recorded audit entries.
- to_list()
- Serialise audit entries to deterministic dictionaries.
- checksum()
- Return a cross-environment SHA-256 over identity and log contents.
Module bioware.bioware_contracts¶
Class MEALayout¶
Standard MEA electrode layouts.
Class MEAConfig¶
Multi-electrode array configuration.
- post_init()
- Validate physical and acquisition configuration boundaries.
- from_layout(cls, layout)
- Create a configuration preset for a standard MEA layout.
Class DetectedSpike¶
One detected spike event from MEA data.
- post_init()
- Validate spike identity, timing, amplitude, and optional waveform.
Class AEREvent¶
Address-Event Representation packet.
Compatible with sc_aer_encoder.v format:
- post_init()
- Validate the maintained unsigned 16-bit AER packet fields.
Class StimProtocol¶
Optogenetic stimulation protocols.
Class OptogeneticPulse¶
One optical stimulation pulse.
- post_init()
- Validate timing, irradiance, wavelength, and illuminated area.
- power_mw()
- Return optical power as irradiance multiplied by illuminated area.
Class BioHybridFrameResult¶
Strictly typed output packet detailing a full closed-loop step.
Behaves both as a dataclass (result.round) and, for backward
compatibility with pre-dataclass callers, as a mapping view of its
fields (result["round"], "latency_us" in result,
dict(result)). The mapping surface is read-only.
- post_init()
- Validate counts and payload cardinalities for one closed-loop frame.
- getitem(key)
- Return a dataclass field through the legacy mapping interface.
- contains(key)
- Return whether
keynames a public result field. - keys()
- Return the mapping-view field names in dataclass declaration order.
Module bioware.bioware_encoding¶
Class MEAToAERTranscoder¶
Converts MEA spike events to AER events for hardware.
Maps biological electrode channels to AER neuron IDs, converting real-time timestamps to hardware clock ticks.
- post_init()
- Validate the hardware clock and optional channel mapping.
- transcode(spikes, t_start_s)
- Convert spikes in one 16-bit hardware-clock epoch to AER events.
Class AERToSCConverter¶
Converts AER event streams to SC bitstreams.
Uses a time-windowed rate code: count events per neuron per window, then LFSR-encode the resulting firing probabilities.
- post_init()
- Validate window, bitstream, neuron, and LFSR boundaries.
- convert(events)
- Convert AER events to per-neuron SC bitstreams.
Class SCToOptoEncoder¶
Encodes SC bitstream output as optogenetic pulse sequences.
Maps SC bitstream density to optical stimulation intensity, enabling closed-loop feedback from in-silico → biological. Enforces total power budget for tissue safety.
- post_init()
- Validate optical timing, irradiance, area, and power limits.
- encode(bitstreams, t_start_ms)
- Convert SC bitstreams to optogenetic pulses.
Function decode_bitstream_rate(bitstreams, sc_clock_hz)¶
Decode SC bitstreams back to biological firing rates (Hz).
Interprets popcount/length as probability, scales by SC clock to get equivalent biological firing rate.
Module bioware.bioware_experiment¶
Class PharmModel¶
Simulates effect of pharmacological agents on spike rate.
Models excitatory (e.g., bicuculline) or inhibitory (e.g., TTX) agents as gain factors on firing rate.
- post_init()
- Validate the pharmacological gain and experiment-time constants.
- apply(t_current_s)
- Mark the pharmacological agent as applied at the current time.
- effective_gain(t_current_s)
- Return the active firing-rate gain at an experiment timestamp.
- modulate_spikes(spike_counts, t_current_s)
- Modulate spike counts by pharmacological gain.
- modulate_spike_events(spikes, t_current_s)
- Apply pharmacological rate gain to spike events.
Class WellConfig¶
One well in a multi-well MEA plate.
- post_init()
- Validate well identity, culture label, passage, and MEA config.
- label()
- Return the stable plate label for this well.
Class MultiWellPlate¶
Multi-well plate (e.g., 6/24/48/96-well MEA plate).
- post_init()
- Validate well types and unique well identifiers.
- add_well(well)
- Append a well configuration to the plate.
- standard_6_well(cls, layout)
- Construct a six-well plate with uniform MEA layout presets.
- num_wells()
- Return the number of configured wells.
- get_well(well_id)
- Return a well by identifier.
Module bioware.bioware_fitness¶
Function mea_fitness_hook(detected_spikes, target_rate)¶
Organism fitness metrics derived from MEA response dynamics.
Designed to plug into the evo_substrate
ReplicationEngine(metrics_fn=mea_fitness_hook) — returns the
{"accuracy", "energy_mw", "latency_ms"} triple the engine scores.
Accuracy is a bounded distance to the target mean per-channel firing
rate when duration_s is supplied, or to the legacy per-channel
spike count when it is omitted. The legacy energy_mw key is a
dimensionless optimisation proxy equal to 0.5 * spike_count; it is
not a measured power or energy quantity. latency_ms is either a
caller-supplied closed-loop measurement, the first response latency after
stimulus_time_s, or the first spike timestamp relative to frame start.
Module bioware.bioware_plasticity¶
Class BiologicalSTDP¶
Spike-Timing-Dependent Plasticity adapter for bio-hybrid loops.
Bridges biological STDP time constants (∼20 ms) to SC clock rates (MHz) via a time-scaling factor. Computes ΔW from pre/post spike timing in biological time, then converts to Q8.8 weight updates for the SC domain.
- post_init()
- Validate time constants, amplitudes, and Q8.8 bounds.
- compute_dw(dt_ms)
- Compute weight change from spike timing difference.
- update_weight(current_q88, dt_ms)
- Update Q8.8 weight from spike timing.
Class BCMPlasticity¶
Bienenstock-Cooper-Munro plasticity adapter.
Implements sliding-threshold BCM rule where the modification threshold θ tracks the postsynaptic firing rate. Converts biological firing rates to Q8.8 weight deltas.
- post_init()
- Validate BCM dynamics and Q8.8 weight bounds.
- update_theta(post_rate_hz, dt_ms)
- Update the sliding threshold from postsynaptic activity.
- compute_dw(pre_rate_hz, post_rate_hz)
- BCM weight change: ΔW = η * x * y * (y - θ).
- update_weight(current_q88, pre_rate, post_rate)
- Apply the BCM update to a saturated Q8.8 synaptic weight.
Class HomeostaticPlasticity¶
Intrinsic excitability scaling to maintain target firing rate.
Implements homeostatic plasticity: if a neuron fires too fast, reduce its excitability (threshold up); too slow, increase it. Operates on Q8.8 threshold values.
- post_init()
- Validate target dynamics and Q8.8 threshold bounds.
- update_threshold(current_q88, observed_rate_hz, dt_ms)
- Adjust threshold to drive firing rate toward target.
Module bioware.bioware_session¶
Class BioHybridSession¶
Manages a complete bio-hybrid experiment session.
Orchestrates MEA recording, spike detection, AER transcoding, stochastic
conversion, optogenetic feedback, and culture-health assessment. The
stdp and homeostatic policies are retained for caller-managed
updates; process_frame does not mutate plasticity state implicitly.
- post_init()
- Validate component compatibility before processing live data.
- process_frame(voltage_data, t_start_s, stim_times_s)
- Process one frame whose timestamps fit one AER counter epoch.
Module bioware.bioware_validation¶
Function require_finite(value, name)¶
Require a finite scalar value.
Parameters¶
value: Scalar to validate. name: Field name used in the error message.
Raises¶
TypeError
If value is a boolean or not a real scalar.
ValueError
If value is NaN or infinite.
Function require_nonnegative(value, name)¶
Require a finite scalar greater than or equal to zero.
Function require_positive(value, name)¶
Require a finite scalar strictly greater than zero.
Function require_nonnegative_int(value, name)¶
Require a non-boolean integer greater than or equal to zero.
Function require_positive_int(value, name)¶
Require a non-boolean integer strictly greater than zero.
Function validate_voltage_matrix(voltage_data)¶
Validate a non-empty, finite two-dimensional MEA voltage matrix.
Parameters¶
voltage_data:
Matrix with shape (samples, channels).
expected_channels:
Optional exact channel count.
Raises¶
TypeError If the input is not a NumPy array with a numeric dtype. ValueError If dimensionality, shape, channel count, or finiteness is invalid.
Function validate_binary_bitstream(bitstream)¶
Validate a one-dimensional NumPy bitstream containing only 0 and 1.
Module bridges.aer_router¶
Class SpikePacket¶
Wire format for an AER spike event (28 bytes big-endian).
- encode()
- Serialize to 28-byte big-endian frame.
- decode(cls, data)
- Deserialize from 28-byte big-endian frame.
Class RouteStats¶
Per-route delivery statistics.
Class AERRouter¶
Manages route registration, spike dispatch, and ACK tracking.
This is a pure-Python simulation/client. For high-performance UDP routing, use the Go server (hil_debugger/interconnect).
- init()
- register_route(neuron_id, addr)
- Map a neuron ID to a destination address (host:port).
- unregister_route(neuron_id)
- Remove a route for the given neuron ID.
- route_count()
- Return the number of currently registered neuron routes.
- dispatch_spike(packet)
- Dispatch a spike packet to the registered target.
- ack_received(seq)
- Process an ACK for the given sequence number.
- pending_count()
- Return the number of dispatched packets awaiting ACKs.
- total_sent()
- Return the total number of packets accepted for dispatch.
- total_acked()
- Return the total number of ACKs processed by the router.
- get_stats(neuron_id)
- Return a defensive copy of per-route statistics when present.
Module bridges.annealing_analysis¶
Class EnergyLandscape¶
Compute energy statistics and spectral gaps for an Ising model.
- init()
- Configure deterministic large-model sampling and backend choice.
- analyze(model, samples)
- Analyze exhaustive, supplied, or deterministic random samples.
Class EmbeddingAnalyzer¶
Estimate logical-to-physical embedding requirements.
- analyze(model)
- Return graph density, degree, and Pegasus chain estimates.
Class SampleAggregator¶
Deduplicate samples and compute energy-distribution statistics.
- aggregate(samples, energies, temperature)
- Aggregate an aligned sample and energy sequence.
Class TTSAnalyzer¶
Compute time-to-solution from single-run success probability.
- compute(p_success, t_anneal_us, p_target)
- Compute the standard cumulative-success TTS metric.
- from_samples(energies, ground_state_energy, t_anneal_us, tolerance, p_target)
- Estimate single-run success from observed energies.
- compare_solvers(results, ground_state_energy, tolerance)
- Compute comparable TTS rows for named solver outputs.
Module bridges.annealing_backends¶
Function require_rust_energy()¶
Return the native energy kernel or raise a stable availability error.
Function require_rust_batch_energy()¶
Return the native batch kernel or raise a stable availability error.
Function require_rust_annealer()¶
Return the native annealer or raise a stable availability error.
Function build_spin_bqm(h, couplings, offset)¶
Build a dimod spin BQM, returning None when dimod is absent.
Function require_dwave_components()¶
Return dimod and D-Wave constructors or raise an availability error.
Module bridges.annealing_compilers¶
Class SCToIsing¶
Compile an SC adjacency matrix into an Ising model.
- init(coupling_scale, field_scale)
- Configure finite coupling and local-field scales.
- compile(adjacency, node_labels, biases, name)
- Compile a finite square weight matrix.
Class SCToQUBO¶
Compile an SC adjacency matrix into a QUBO model.
- init(penalty)
- Configure a positive constraint penalty.
- compile(adjacency, node_labels, name)
- Compile a finite square weight matrix into canonical QUBO terms.
Class SCBitstreamQUBO¶
Build QUBOs for SC weight selection and connection pruning.
- init(penalty)
- Configure a positive constraint penalty.
- weight_optimization(target_output, candidate_weights, n_bits)
- Encode
||target - candidate_weights @ x||²for binaryx. - pruning(adjacency, importance_scores, max_connections)
- Select exactly
max_connectionsundirected candidate edges.
Module bridges.annealing_decomposition¶
Class ProblemDecomposer¶
Partition large Ising graphs into bounded overlapping subproblems.
- init(max_subproblem_size, overlap, n_iterations)
- Configure maximum size, real overlap, and merge iterations.
- decompose(model)
- Return bounded submodels; small inputs retain object identity.
- solve_decomposed(model, solver)
- Solve submodels iteratively and reconstruct by exact global index.
Module bridges.annealing_hardware¶
Class HardwareGraph¶
Capacity model for Chimera, Pegasus, and Zephyr topologies.
- init(topology, size)
- Select a topology and a valid positive size parameter.
- n_physical_qubits()
- Return the idealized physical-qubit capacity.
- connectivity()
- Return the idealized per-qubit connectivity.
- can_embed(model)
- Return a conservative degree-based capacity estimate.
Class ChainBreakResolver¶
Resolve embedded-chain disagreement by vote or local energy search.
- init(method)
- Select a supported deterministic resolution method.
- resolve(physical_samples, chains, model)
- Map physical samples to logical samples and optionally refine them.
- analyze_breaks(physical_samples, chains)
- Measure per-chain and aggregate break rates.
Module bridges.annealing_io¶
Function export_ising_json(model, path)¶
Write a canonical JSON representation of an Ising model.
Function export_qubo_json(model, path)¶
Write a canonical JSON representation of a QUBO model.
Function export_bqm(model)¶
Return a dimod spin BQM, or None when dimod is unavailable.
Function visualize_ising(model)¶
Return a stable Unicode text rendering of fields and couplings.
Module bridges.annealing_models¶
Class ProblemType¶
Quantum optimization problem type.
Class QubitSpec¶
Specification for one logical qubit.
- post_init()
- Validate the qubit index, label, and bias.
Class CouplerSpec¶
Specification for one logical Ising/QUBO coupling.
- post_init()
- Validate distinct endpoints and a finite strength.
Class IsingModel¶
Ising spin-glass model H = Σhᵢsᵢ + ΣJᵢⱼsᵢsⱼ.
- post_init()
- Normalize canonical couplings and validate model bounds.
- energy(spins)
- Compute energy for a partial spin assignment.
Class QUBOModel¶
Quadratic unconstrained binary optimization model xᵀQx.
- post_init()
- Normalize matrix keys and validate model bounds.
- energy(bits)
- Compute QUBO energy for a partial binary assignment.
- to_ising()
- Convert QUBO to an exactly energy-equivalent Ising model.
Function validate_backend_choice(backend)¶
Validate and narrow an execution-backend selector.
Module bridges.annealing_solvers¶
Class SimulatedAnnealer¶
Metropolis simulated annealer with explicit backend selection.
- init(n_sweeps, beta_start, beta_end, seed)
- Configure a deterministic annealer.
- solve_ising(model, num_reads)
- Solve an Ising model and preserve a stable sample contract.
- solve_qubo(model, num_reads)
- Convert a QUBO to Ising, solve it, and map samples back to bits.
Class DWaveInterface¶
Submit validated Ising models to D-Wave or use a local fallback.
- init(chain_strength, num_reads, annealing_time_us)
- Configure QPU sampling parameters.
- available()
- Return whether both Ocean SDK components are importable.
- solve_ising(model)
- Submit to a QPU, or run a bounded local fallback when unavailable.
Module bridges.annealing_transforms¶
Class AnnealingSchedule¶
Build validated linear, pause, and reverse annealing schedules.
- init()
- Create an empty schedule.
- linear(duration_us)
- Configure a standard linear anneal from zero to one.
- pause_and_quench(ramp_time_us, pause_at_s, pause_duration_us, quench_time_us)
- Ramp, hold at an intermediate fraction, then quench.
- reverse(initial_s, reverse_to_s, ramp_time_us, hold_time_us, forward_time_us)
- Configure a reverse anneal followed by a forward return.
- points()
- Return a defensive copy of the schedule points.
- total_time_us()
- Return zero for an empty schedule or its final timestamp.
- to_dict()
- Return a D-Wave-compatible schedule payload.
Class GaugeTransform¶
Generate deterministic random spin-reversal transformations.
- init(n_gauges, seed)
- Configure a positive transform count and deterministic seed.
- transform(model)
- Return energy-equivalent gauge-transformed model copies.
- untransform_sample(sample, gauge)
- Return a transformed sample to the original spin frame.
Class SCPrecisionEncoder¶
Encode unit-interval SC values as binary, unary, or one-hot qubits.
- init(encoding, n_bits)
- Select a supported encoding and positive qubit count.
- n_levels()
- Return the number of representable precision levels.
- encode(sc_value)
- Encode one finite SC value after clipping it to
[0, 1]. - decode(qubits)
- Decode a validated partial binary qubit mapping.
- qubits_needed(n_sc_values)
- Return the total qubits required for a non-negative value count.
- encode_array(values)
- Encode a non-empty one-dimensional array into global qubit indices.
Module bridges.dna_analysis¶
Class CrossHybridizationChecker¶
Detect unwanted cross-hybridization between circuit strands.
Computes a pairwise alignment score matrix for all strands in a design and flags pairs with dangerous complementarity.
Parameters¶
max_complementary_run : int Maximum allowed consecutive complementary bases between two non-interacting strands (default 8).
- init(max_complementary_run)
- check(design)
- Check all strand pairs for cross-hybridization.
Class TopologicalAnalyzer¶
Analyze circuit topology: depth, fan-out, feedback detection.
Builds a directed graph from gate connectivity, then computes: - Topological sort order (or detects cycles) - Circuit depth (critical path length) - Fan-out per signal (number of consumers) - Feedback loops (cycles in the gate graph)
- analyze(design)
- Run full topological analysis.
Class HairpinChecker¶
Detect potential hairpin (stem-loop) secondary structures.
Scans each strand for self-complementary regions that could form intramolecular hairpins, reducing effective concentration and interfering with gate operation.
Parameters¶
min_stem_length : int Minimum stem length to flag (default 4 bp). min_loop_length : int Minimum loop length for a valid hairpin (default 3 nt).
- init(min_stem_length, min_loop_length)
- check_strand(sequence)
- Find potential hairpins in a single sequence.
- check_design(design)
- Check all strands in a circuit for hairpins.
Class GateOptimizer¶
Circuit-level gate optimization.
Performs: - Dead gate elimination (outputs not consumed by any downstream gate) - Constant propagation (gates with all-zero or all-max inputs) - Identity elimination (BUFFER gates with direct pass-through) - Duplicate detection (identical gate specs)
- optimize(gates, output_names)
- Optimize a gate list before compilation.
Module bridges.dna_bridge¶
Class BitstreamToDNA¶
High-level API for mapping SC bitstreams to DNA circuits.
This is the primary entry point for the DNA computing bridge. Accepts a description of an SC Boolean network and compiles it into a complete DNA circuit design.
Parameters¶
method : str
Compilation method: "displacement" (default),
"enzymatic", or "hybrid".
seed : int
Sequence generation seed for reproducibility.
temperature_c : float
Design temperature in Celsius.
Examples¶
compiler = BitstreamToDNA(method="displacement", seed=42) design = compiler.compile_network( ... gates=[ ... {"type": "AND", "inputs": ["A", "B"], "output": "C"}, ... {"type": "NOT", "inputs": ["C"], "output": "D"}, ... ], ... input_names=["A", "B"], ... output_names=["D"], ... ) print(design.total_gates) 2 print(design.total_strands) ... export_genbank(design, "nand_circuit.gb")
- init(method, seed, temperature_c)
- compile_network(gates, input_names, output_names, name)
- Compile an SC Boolean network into a DNA circuit.
- simulate(design, input_concentrations, duration_s, dt)
- Simulate the compiled circuit.
- validate(design)
- Validate design using NUPACK (or fallback).
Class SCNetworkBridge¶
Bridge between SC-NeuroCore network objects and DNA compilation.
Converts Population/Projection-based SC networks into the gate-spec format consumed by BitstreamToDNA. Supports automatic gate-type inference from connection weights.
Parameters¶
method : str
Compilation method ("displacement" or "enzymatic").
seed : int
Random seed.
- init(method, seed)
- from_adjacency(adjacency, input_indices, output_indices, name)
- Compile from an adjacency matrix.
Module bridges.dna_compilers¶
Class StrandDisplacementCompiler¶
Compile SC Boolean gates into toehold-mediated displacement circuits.
Implements the seesaw gate architecture from Qian & Winfree (2011) adapted for SC-NeuroCore's bitstream operations.
Parameters¶
designer : SequenceDesigner | None Sequence generator. If None, a default is created. temperature_c : float Target operating temperature in Celsius.
- init(designer, temperature_c)
- compile_and(input_a, input_b, output)
- Compile a 2-input AND gate.
- compile_or(input_a, input_b, output)
- Compile a 2-input OR gate via catalytic hairpin assembly.
- compile_not(input_name, output)
- Compile a NOT gate via strand sequestration.
- compile_threshold(input_name, output, threshold)
- Compile a threshold gate for concentration-dependent activation.
- compile_mux(select, input_a, input_b, output)
- Compile a 2:1 multiplexer (MUX) gate.
- compile_amplifier(input_name, output)
- Compile a catalytic signal amplifier.
- compile_buffer(input_name, output)
- Compile a signal restoration buffer.
Class EnzymaticGateCompiler¶
Compile SC gates into enzyme-mediated DNA logic circuits.
Uses restriction enzymes and ligases to implement Boolean operations on DNA substrates. Operates on double-stranded DNA with specific recognition sites.
Parameters¶
designer : SequenceDesigner | None Sequence generator.
- init(designer)
- compile_nand(input_a, input_b, output)
- NAND gate via dual restriction enzyme cascade.
- compile_xor(input_a, input_b, output)
- XOR gate via nick-sealing ligase logic.
Module bridges.dna_encoding¶
Class GF4ErrorCorrection¶
Reed–Solomon-like error correction over GF(4) for DNA sequences.
Maps nucleotides to GF(4) elements: A=0, C=1, G=2, T=3. Adds parity symbols for error detection and correction of synthesis/sequencing errors.
Parameters¶
n_parity : int Number of parity nucleotides per block (default 4). block_size : int Data nucleotides per block (default 12).
- init(n_parity, block_size)
- encode(sequence)
- Add error-correction parity nucleotides to a sequence.
- decode(encoded_sequence)
- Decode and correct errors. Returns (corrected_data, n_corrections).
Class DualRailEncoder¶
Dual-rail encoding for fault-tolerant DNA circuits.
Each logical signal is encoded as two physical strands: the "true" rail and the "complement" rail. Valid states: - (high, low) = logical 1 - (low, high) = logical 0 - (high, high) = fault detected - (low, low) = fault detected
This provides single-fault detection for each signal.
- encode(design, compiler)
- Convert a single-rail circuit to dual-rail.
- check_faults(result, threshold_nM)
- Detect faults in dual-rail simulation results.
Module bridges.dna_io¶
Class PlateLayout¶
Organize oligos into 96-well synthesis plate format.
Maps each unique oligo to a well position (A01–H12), generates ordering manifests for IDT/Sigma/Eurofins, and computes plate utilization.
Parameters¶
n_wells : int Wells per plate (default 96).
- init(n_wells)
- layout(design)
- Generate plate layout for a circuit design.
Function export_genbank(design, path)¶
Export circuit design to GenBank format.
Creates a multi-record GenBank file with one record per strand, including annotations for functional domains (toehold, recognition, clamp).
Parameters¶
design : DNACircuitDesign
Compiled circuit.
path : str
Output file path (e.g. "circuit.gb").
Function export_fasta(design, path)¶
Export all strands to FASTA format.
Parameters¶
design : DNACircuitDesign
Compiled circuit.
path : str
Output file path (e.g. "circuit.fasta").
Function export_nupack_input(design, path)¶
Export circuit in NUPACK multi-strand input format.
Parameters¶
design : DNACircuitDesign
Compiled circuit.
path : str
Output file path (e.g. "circuit.nupack").
Function export_json(design, path)¶
Export circuit design as JSON for visualization/interchange.
Parameters¶
design : DNACircuitDesign
Compiled circuit.
path : str
Output file path (e.g. "circuit.json").
Function estimate_cost(design, price_per_base_usd, fixed_per_oligo_usd, purification)¶
Estimate oligo synthesis cost for a circuit design.
Parameters¶
design : DNACircuitDesign
Compiled circuit.
price_per_base_usd : float
Cost per nucleotide (default $0.10 for standard desalt).
fixed_per_oligo_usd : float
Fixed setup cost per oligonucleotide.
purification : str
"standard" (1×), "hplc" (2.5×), "page" (3×).
Returns¶
dict Cost breakdown: per-strand costs, total, summary.
Function generate_protocol(design, volume_uL, buffer_name)¶
Generate a wet-lab protocol for assembling a DNA circuit.
Parameters¶
design : DNACircuitDesign Compiled circuit. volume_uL : float Total reaction volume in µL. buffer_name : str Buffer system name.
Returns¶
str Markdown-formatted protocol.
Function visualize_circuit(design)¶
Generate a text-based circuit diagram.
Returns an ASCII diagram showing gate connectivity, signal flow, and strand counts per gate.
Parameters¶
design : DNACircuitDesign Compiled circuit.
Returns¶
str Multi-line ASCII circuit diagram.
Function visualize_kinetics(result)¶
Generate a text-based time-course chart.
Produces a simple ASCII sparkline for each output trace.
Parameters¶
result : dict
Simulation result from KineticSimulator.simulate().
Returns¶
str Multi-line ASCII sparkline chart.
Module bridges.dna_sequences¶
Class SequenceDesigner¶
Deterministic DNA sequence generator with constraint satisfaction.
Generates sequences that satisfy GC content, homopolymer, and orthogonality constraints using a seed-based deterministic algorithm. This ensures reproducible designs without requiring NUPACK.
Parameters¶
seed : int Random seed for reproducible sequence generation. gc_target : tuple[float, float] Acceptable GC content range (default 0.40–0.60). max_homopolymer : int Maximum consecutive identical nucleotides (default 3).
- init(seed, gc_target, max_homopolymer)
- generate(length, name)
- Generate a sequence satisfying all constraints.
- generate_complement(sequence)
- Return the Watson-Crick complement (3' → 5').
- generate_toehold(name)
- Generate a toehold domain (6 nt).
- generate_recognition(name)
- Generate a recognition domain (15 nt).
Module bridges.dna_simulation¶
Class KineticSimulator¶
Mass-action kinetics simulator for DNA strand displacement.
Simulates the time evolution of strand concentrations using selectable integration (Euler or RK4) with Arrhenius temperature scaling of rate constants.
Parameters¶
rate_hybridization : float
Second-order rate constant for toehold binding (M⁻¹ s⁻¹).
rate_displacement : float
First-order rate constant for branch migration (s⁻¹).
temperature_c : float
Temperature in Celsius.
integrator : str
Integration method: "euler" or "rk4".
- init(rate_hybridization, rate_displacement, temperature_c, integrator)
- simulate(design, input_concentrations, duration_s, dt)
- Simulate circuit kinetics.
Class NoiseModel¶
Monte Carlo noise injection for robustness analysis.
Perturbs strand concentrations, hybridization rates, and temperature to assess circuit robustness under realistic experimental conditions.
Parameters¶
concentration_cv : float Coefficient of variation for pipetting noise (default 0.05 = 5%). temperature_std_c : float Temperature uncertainty in °C (default 0.5). n_trials : int Number of Monte Carlo trials (default 50). seed : int Random seed.
- init(concentration_cv, temperature_std_c, n_trials, seed)
- sensitivity_analysis(design, input_concentrations, duration_s)
- Run Monte Carlo sensitivity analysis.
Class ConcentrationOptimizer¶
Gradient-free optimization of strand concentrations.
Uses Nelder–Mead simplex to minimize output error across all truth-table entries, finding optimal working concentrations for translator, threshold, and fuel strands.
Parameters¶
n_evaluations : int Maximum function evaluations (default 200). seed : int Random seed for initial simplex.
- init(n_evaluations, seed)
- optimize(design, truth_table, duration_s)
- Optimize concentrations against a truth table.
Class SCPrecisionAnalyzer¶
Stochastic computing precision analysis for DNA circuits.
Evaluates the effective bit-width, signal-to-noise ratio, and output precision achievable by a DNA-encoded SC circuit at given strand concentrations.
In standard SC, a bitstream of length L encodes precision log2(L+1) bits. In DNA circuits, the analog concentration range [0, max_nM] plays the role of L.
- analyze(design, input_concentrations, max_conc_nM, duration_s)
- Analyze SC precision of a compiled circuit.
Class DegradationModel¶
Time-dependent DNA strand degradation model.
Models first-order exponential decay of strand concentrations based on nuclease activity, temperature, and strand length.
Parameters¶
half_life_hr : float Base half-life in hours at 37°C (default 24 for ssDNA). temperature_c : float Operating temperature in Celsius.
- init(half_life_hr, temperature_c)
- predict_concentration(initial_nM, strand_length, time_hr)
- Predict remaining concentration after time_hr hours.
- analyze_design(design, time_hr)
- Predict degradation across all circuit strands.
Module bridges.dna_thermodynamics¶
Class NUPACKInterface¶
Interface to NUPACK for thermodynamic validation.
Provides minimum free energy (MFE) structure prediction, base-pair probability computation, and design validation. Falls back to internal nearest-neighbour estimates, Watson-Crick secondary-structure dynamic programming, and Boltzmann-style pair probabilities when NUPACK is not installed.
Parameters¶
temperature_c : float Temperature in Celsius. na_concentration_M : float Sodium concentration in molar.
- init(temperature_c, na_concentration_M)
- has_nupack()
- Return whether optional NUPACK thermodynamic analysis is installed.
- compute_mfe(sequence)
- Compute minimum free energy and structure.
- compute_pair_probabilities(sequence)
- Compute base-pair probability matrix.
- validate_design(design)
- Validate a full circuit design.
Module bridges.dna_types¶
Class GateType¶
Supported DNA logic gate types.
Class CompilationMethod¶
Compilation target for the DNA circuit.
Class DNAStrand¶
A single-stranded DNA molecule used in a circuit.
Attributes¶
name : str
Unique identifier (e.g. "gate_0_input_a").
sequence : str
5' → 3' nucleotide sequence (A, C, G, T).
role : str
Functional role: "signal", "fuel", "output",
"waste", "toehold", "translator".
concentration_nM : float
Initial concentration in nanomolar.
- length()
- Return the nucleotide length of this strand.
- gc_content()
- Return the fraction of nucleotides that are G or C bases.
- complement()
- Return the reverse-complement strand sequence.
- max_homopolymer_run()
- Return the longest repeated-base run in the strand.
- delta_g_37()
- Nearest-neighbour ΔG° at 37 °C (kcal/mol).
- melting_temperature(na_conc_M, strand_conc_M)
- Return nearest-neighbour DNA duplex melting temperature in °C.
Class DNAGate¶
A logic gate implemented via DNA strand displacement.
Attributes¶
gate_id : int Unique gate index in the circuit. gate_type : GateType Logic operation (AND, OR, NOT, etc.). input_names : list[str] Names of input signal strands. output_name : str Name of the output signal strand. strands : list[DNAStrand] All DNA strands participating in this gate (inputs, fuel, translator complexes, output, waste). threshold : float For threshold gates, the activation threshold concentration. leak_rate : float Estimated spurious activation rate (per second).
- strand_count()
- Return the number of strands implementing this gate.
Class DNACircuitDesign¶
Complete compiled DNA circuit.
Holds the full strand-level design for a compiled SC network, including all gates, signal routing, and thermodynamic validation.
Attributes¶
name : str Circuit identifier. gates : list[DNAGate] Ordered list of compiled gates. input_strands : list[DNAStrand] Primary input signal strands. output_strands : list[DNAStrand] Primary output signal strands. fuel_strands : list[DNAStrand] Fuel/helper strands consumed during computation. method : CompilationMethod Compilation target used. temperature_c : float Design temperature in Celsius. na_concentration_M : float Sodium concentration for thermodynamic calculations.
- total_strands()
- Return the total strand count across circuit inputs, outputs, fuel, and gates.
- total_gates()
- Return the number of DNA logic gates in the circuit.
- total_nucleotides()
- Return the total nucleotide count across all circuit strands.
- validate()
- Run design rule checks. Returns list of warnings.
Module bridges.local_llm¶
Class LocalLLMError¶
Raised when the local LLM endpoint is unavailable or malformed.
Class LocalLLMProvider¶
Local LLM endpoint protocol.
Class LocalLLMConfig¶
Connection and generation settings for a local LLM endpoint.
- resolved_provider()
- Resolve AUTO to a concrete provider using the configured URL.
Class LocalLLMResponse¶
Structured response from a local LLM endpoint.
Class SpikePromptAdapter¶
Convert spike activity into compact text suitable for local LLM prompts.
- summarise_rates(rates_hz)
- Summarise per-neuron firing rates as compact ranked text.
- raster_summary(raster)
- Summarise a boolean spike raster into rates and density statistics.
Class LocalLLMBridge¶
Thin client for local LLM chat endpoints.
- init(config)
- chat(user_prompt)
- Send a prompt to the configured local LLM chat endpoint.
- analyse_spike_raster(raster)
- Summarise a spike raster through the local LLM.
Module bridges.photonic_codesign¶
Class PhotonicCoDesignConfig¶
Configuration for a reproducible stochastic photonic design pass.
- post_init()
Class BitstreamEvidence¶
One encoded SC channel and its statistical evidence.
- to_json()
- Return a compact JSON-ready evidence record.
Class PhotonicCoDesignReport¶
Complete output of a stochastic photonic co-design pass.
- to_json()
- Return a deterministic JSON-ready report.
- export_json(path)
- Write the report to a JSON file.
Class StochasticPhotonicCoDesignLoop¶
End-to-end stochastic bitstream, photonic NoC, and FDTD loop.
- init(config)
- compile(adjacency)
- Run the full co-design loop for one SC connectivity matrix.
Function derive_probabilities_from_adjacency(adjacency, floor, ceiling)¶
Derive per-node SC probabilities from inbound absolute weight mass.
Function encode_bitstream_bank(probabilities)¶
Encode probabilities into deterministic LFSR-backed SC bitstreams.
Module bridges.photonic_noc¶
Class WaveguideType¶
Photonic waveguide type.
Class WaveguideSegment¶
A single waveguide path segment.
Attributes¶
source : int Source node index. target : int Target node index. length_um : float Physical length in micrometers. wavelength_nm : float Operating wavelength (default 1550 nm). loss_db : float Total insertion loss for this segment. n_crossings : int Number of waveguide crossings. wg_type : WaveguideType Waveguide geometry type.
Class MZIGate¶
Mach-Zehnder interferometer gate specification.
Models a single MZI stage implementing an SC computing operation via thermo-optic or electro-optic phase shifting.
Attributes¶
gate_id : str Unique gate identifier. operation : str Gate operation type (AND, OR, NOT, MUL, ADD). input_ports : list[int] Input waveguide port indices. output_port : int Output waveguide port index. phase_shift_rad : float Applied phase shift in radians. arm_length_um : float MZI arm length in micrometers. insertion_loss_db : float Total insertion loss. extinction_ratio_db : float On/off extinction ratio.
Class WDMChannel¶
Wavelength-division multiplexing channel.
Attributes¶
channel_id : int Channel index. wavelength_nm : float Center wavelength. bandwidth_nm : float Channel bandwidth (default 0.8 nm for DWDM). signal_name : str Associated SC signal name. power_dbm : float Launch power.
Class PhotonicCircuitDesign¶
Complete photonic NoC design.
Attributes¶
name : str Design name. waveguides : list[WaveguideSegment] All waveguide segments. mzi_gates : list[MZIGate] All MZI computing stages. wdm_channels : list[WDMChannel] WDM channel assignments. n_nodes : int Number of processing element nodes. routing_table : dict[tuple[int, int], list[int]] Hop-by-hop routing table. total_area_um2 : float Estimated chip area.
Class WaveguideRouter¶
Route waveguides between SC network nodes.
Uses a mesh topology with shortest-path (Manhattan) routing.
Parameters¶
pitch_um : float Node-to-node pitch in micrometers (default 250). loss_db_per_cm : float Waveguide propagation loss (default 2.0 dB/cm).
- init(pitch_um, loss_db_per_cm)
- route(adjacency, node_labels)
- Route waveguides for an SC network adjacency matrix.
Class MZICompiler¶
Compile SC operations into MZI gate cascades.
Maps SC gates to photonic MZI operations: - AND/MUL → MZI with π/2 phase shift (coherent multiplication) - OR/ADD → Y-junction combiner - NOT → MZI with π phase shift (bar state)
Parameters¶
arm_length_um : float Default MZI arm length (default 200 μm).
- init(arm_length_um)
- compile_gate(gate_type, input_ports, output_port, gate_id)
- Compile a single SC gate to an MZI specification.
- compile_network(gates)
- Compile a list of SC gate specs into MZI cascade.
Class WDMAssigner¶
Assign WDM channels to SC signal paths.
Parameters¶
base_wavelength_nm : float
Starting wavelength (default 1550.0 nm).
channel_spacing_nm : float
Channel spacing (default 0.8 nm for 100 GHz DWDM).
max_channels : int
Hard cap on the number of channels the assigner will emit.
Default 96 follows the ITU-T G.694.1 DWDM C-band grid at
50 GHz spacing (~0.4 nm). At the default 0.8 nm spacing the
physical C-band (~1530-1565 nm, ~35 nm) only fits ~44
channels — the cap protects callers from silently spilling
into invalid wavelengths. Pass a larger value (or
max_channels=0 to disable) for multi-band (C+L+S)
designs.
Raises¶
ValueError
From :meth:assign when len(signal_names) exceeds
max_channels and max_channels > 0.
- init(base_wavelength_nm, channel_spacing_nm, max_channels)
- assign(signal_names, power_dbm)
- Assign a WDM channel to each signal.
Class PowerBudgetAnalyzer¶
Optical power budget and OSNR analysis.
Computes end-to-end power budget for each path in the photonic circuit, flagging paths that exceed the detector sensitivity.
- analyze(design, laser_power_dbm, detector_sensitivity_dbm)
- Run power budget analysis.
Class SCToPhotonic¶
Top-level compiler: SC network → photonic NoC design.
Parameters¶
pitch_um : float Mesh pitch (default 250 μm). arm_length_um : float MZI arm length (default 200 μm).
- init(pitch_um, arm_length_um)
- compile(adjacency, node_labels, gate_specs, name)
- Compile SC network into a photonic design.
Class ThermalPhaseShifter¶
Thermo-optic phase shifter model for MZI tuning.
Parameters¶
heater_length_um : float Heater length (default 100 μm). dn_dt : float Thermo-optic coefficient (default 1.86e-4 K⁻¹ for Si). thermal_resistance_kw : float Heater thermal resistance (default 10 K/mW).
- init(heater_length_um, dn_dt, thermal_resistance_kw)
- power_for_phase(phase_rad, wavelength_nm)
- Compute electrical power needed for a given phase shift.
- analyze_design(design)
- Compute total power budget for all MZI phase shifters.
Class CrosstalkAnalyzer¶
Analyze inter-channel crosstalk in WDM systems.
Parameters¶
adjacent_xt_db : float Adjacent-channel crosstalk (default -25 dB).
- init(adjacent_xt_db)
- analyze(channels)
- Analyze crosstalk between WDM channels.
Function export_photonic_json(design, path)¶
Export photonic design to JSON.
Parameters¶
design : PhotonicCircuitDesign The design to export. path : str Output file path.
Function visualize_photonic(design)¶
Generate ASCII visualization of a photonic design.
Returns¶
str Multi-line ASCII representation.
Module chaos.rng¶
Class ChaoticRNG¶
Logistic-map chaotic RNG for SC bitstream generation.
x_{n+1} = r * x_n * (1 - x_n)
At r=4.0 the logistic map is fully chaotic with Lyapunov exponent ln(2) ~ 0.693 and an invariant density Beta(0.5, 0.5) on (0, 1). The 100-step burn-in discards transients from the initial condition.
Parameters¶
r : float Bifurcation parameter. Must be in (3.57, 4.0] for chaos. Default 4.0 gives maximal chaos. x : float Initial condition in (0, 1). Avoid 0.0, 0.5, 1.0 exactly (these are fixed/periodic points at r=4). burn_in : int Steps to discard before first output.
Example¶
rng = ChaoticRNG(r=4.0, x=0.37) bits = rng.generate_bitstream(p=0.5, length=1000) 0.4 < bits.mean() < 0.6 True
- post_init()
- random(size)
- Generate size chaotic floats in (0, 1).
- random_vectorized(size, n_maps)
- Generate samples from n_maps independent logistic maps in parallel.
- generate_bitstream(p, length)
- Generate SC bitstream where P(bit=1) ~ p.
- lyapunov_exponent(n_steps)
- Estimate the maximal Lyapunov exponent via derivative averaging.
- shannon_entropy(n_samples, n_bins)
- Estimate Shannon entropy of the chaotic sequence in bits.
- autocorrelation(n_samples, max_lag)
- Compute autocorrelation of the chaotic sequence up to max_lag.
- reset(x)
- Reset to initial condition (with fresh burn-in).
- state()
- Current internal state.
Class TentMapRNG¶
Tent map chaotic RNG — piecewise linear alternative to logistic map.
x_{n+1} = mu * min(x_n, 1 - x_n)
At mu=2.0 the tent map is topologically conjugate to the logistic map at r=4.0 but has uniform invariant density on (0, 1) — better for SC bitstream generation where uniform marginals are desired.
Parameters¶
mu : float Slope parameter. Must be in (1, 2] for chaos. Default 2.0. x : float Initial condition in (0, 1).
- post_init()
- random(size)
- Generate size chaotic floats in (0, 1).
- generate_bitstream(p, length)
- Generate SC bitstream where P(bit=1) ~ p.
- reset(x)
- Reset to initial condition (with fresh burn-in).
- state()
Module chip_compiler.chip_spec¶
Class CoreSpec¶
Specification for one neuromorphic core.
Class ChipSpec¶
Full neuromorphic chip specification.
Parameters¶
name : str Chip identifier (e.g., 'loihi2', 'xylo', 'akida'). vendor : str total_cores : int core : CoreSpec Per-core specification (assumes homogeneous cores). clock_mhz : float power_mw_per_core : float Estimated dynamic power per active core. routing_topology : str 'mesh', 'crossbar', 'tree', 'ring' max_fan_out : int Maximum outgoing connections per neuron. analog_noise_cv : float Coefficient of variation for analog process variation. 0.0 for fully digital chips.
- total_neurons()
- total_power_mw()
- fits(n_neurons, max_fan_out)
- Check if a network fits on this chip.
- cores_needed(n_neurons)
- Minimum cores needed for N neurons.
Function load_chip_spec(path)¶
Load and validate a chip spec from a JSON file.
Module chip_compiler.compiler¶
Class CoreMapping¶
Mapping of neurons to one chip core.
Class CompilationResult¶
Result of compiling an SNN to a chip target.
- summary()
Function compile_for_chip(layer_sizes, weights, neuron_types, target)¶
Compile an SNN to a target neuromorphic chip.
Parameters¶
layer_sizes : list of (n_inputs, n_neurons) weights : list of ndarray, optional Weight matrices per layer. If provided, will be quantized. neuron_types : list of str, optional Neuron type per layer (e.g., 'LIF', 'Izhikevich'). target : str or ChipSpec Target chip name or spec.
Returns¶
CompilationResult
Module chiplet.hierarchical_backends¶
Class RefinementOwner¶
Structural interface required by backend dispatch.
Function encode_csr(partitions, adjacency, graph)¶
Encode adjacency and ordered partitions into the shared flat ABI.
Function decode_part_map(part_map, partition_count)¶
Decode a flat vertex-to-partition mapping.
Function refine_rust(owner, partitions, adjacency, graph)¶
Run the PyO3 Rust kernel and decode its partition map.
Function refine_julia(owner, partitions, adjacency, graph)¶
Run the Julia kernel and decode its partition map.
Function refine_go(owner, partitions, adjacency, graph)¶
Run the typed Go C-shared kernel and decode its partition map.
Function refine_mojo(owner, partitions, adjacency, graph)¶
Run the Mojo raw-address kernel and decode its partition map.
Function dispatch_refine(owner, partitions, adjacency, graph)¶
Dispatch to the requested kernel or the Python reference.
Module chiplet.hierarchical_balancing¶
Class LoadMetrics¶
Load and boundary metrics for one partition.
Class MigrationRecommendation¶
A scored proposal to move one vertex between partitions.
Class CorrelationLoadBalancer¶
Recommend balancing moves while accounting for boundary correlation.
- init(imbalance_threshold, scc_weight)
- Configure the imbalance trigger and SCC penalty.
- compute_load_metrics(graph, partitions)
- Compute vertex, weight, boundary-SCC, and ghost counts.
- recommend_migrations(graph, partitions, max_recommendations)
- Return highest-gain moves from overloaded to underloaded partitions.
Class RankMapper¶
Map partitions to ranks and count inter-rank boundary edges.
- init(num_ranks, hierarchy)
- Configure rank count and physical hierarchy.
- assign(partitions, graph)
- Assign every partition to an MPI rank.
- cross_rank_edges(graph, partitions)
- Count partition-boundary edges that also cross rank boundaries.
Module chiplet.hierarchical_bisection¶
Class BisectionMixin¶
Private multilevel-bisection behaviour for the public partitioner.
Module chiplet.hierarchical_boundary¶
Class GhostCellManager¶
Compute read-only halo vertices required by each partition.
- compute_halos(graph, partitions)
- Return the external neighbour vertices required by each partition.
- halo_sizes(graph, partitions)
- Return each partition's ghost-cell count.
Class BoundarySyncConfig¶
Configuration for decorrelated boundary synchronisation.
Class BoundarySyncProtocol¶
Manage decorrelation seeds and SCC-budget violations at boundaries.
- init(config)
- Initialise empty buffers and violation state.
- init_buffers(graph, partitions, seeds)
- Initialise a non-zero XOR-derived seed for every boundary edge.
- check_scc_budget(graph, partitions)
- Return boundary edges whose absolute SCC exceeds the budget.
- num_buffers()
- Return the number of initialised decorrelation buffers.
Module chiplet.hierarchical_core¶
Class HierarchicalPartitioner¶
Multi-level graph partitioner with selectable KL-refinement backend.
- init(num_partitions, coarsen_threshold, kl_iterations, correlation_penalty, seed, refine_backend)
- Configure deterministic bisection and refinement.
- partition(graph)
- Partition the graph and return partitions with independent seeds.
Module chiplet.hierarchical_graph¶
Class HierarchyLevel¶
Physical hierarchy levels available to the MPI rank mapper.
Class CorrelationEdge¶
An undirected edge with connection and SC-correlation weights.
Class CSRGraph¶
Compressed sparse-row graph with constant-time adjacency slices.
- from_edge_list(cls, num_vertices, edges, vertex_weights)
- Build a symmetric CSR graph from an undirected edge list.
- neighbors(vertex)
- Return the adjacent-vertex slice for the vertex.
- degree(vertex)
- Return the number of neighbours of the vertex.
- edge_conn(vertex)
- Return connection weights aligned with the neighbour slice.
- edge_scc(vertex)
- Return SCC weights aligned with the neighbour slice.
- num_edges()
- Return the undirected edge count.
Class CorrelationAwareGraph¶
Adjacency graph with cached constant-time correlation-edge lookups.
- adjacency()
- Return a symmetric adjacency mapping.
- edge_weight(u, v)
- Return the connection weight for an edge, or zero if absent.
- edge_scc(u, v)
- Return the SCC weight for an edge, or zero if absent.
- num_edges()
- Return the undirected edge count.
- to_csr()
- Convert this graph to its symmetric CSR representation.
Class LFSRSeedAllocator¶
Allocate deterministic, separated non-zero 16-bit LFSR seeds.
- init(base_seed)
- Initialise the allocator with a 16-bit base seed.
- allocate(num_partitions)
- Return one deterministic seed for every requested partition.
- verify_uniqueness(seeds)
- Return whether all supplied seeds are unique.
Module chiplet.hierarchical_metrics¶
Function calculate_edge_cut(graph, partitions)¶
Count edges whose endpoints belong to different partitions.
Function calculate_boundary_scc(graph, partitions)¶
Return the maximum absolute SCC across boundary edges.
Function calculate_mean_boundary_scc(graph, partitions)¶
Return the mean absolute SCC across boundary edges.
Function calculate_total_boundary_scc(graph, partitions)¶
Return the total absolute SCC across boundary edges.
Function calculate_imbalance_ratio(partitions)¶
Return maximum size divided by ideal size, minus one.
Function calculate_comm_volume(graph, partitions, bytes_per_spike, bitstream_length)¶
Estimate messages and bytes transferred across partition boundaries.
Module chiplet.hierarchical_partitioner¶
Function __getattr__(name)¶
Expose historical read-only backend diagnostics.
Module chiplet.hierarchical_refinement¶
Class RefinementMixin¶
Private reference-refinement behaviour for the public partitioner.
- repartition_incremental(graph, partitions, max_moves)
- Move the best boundary vertex repeatedly until no gain remains.
Module chiplet.hierarchical_reporting¶
Class PartitionReport¶
Metrics and deterministic seeds from one partitioning run.
- summary()
- Return a concise human-readable report.
Function build_partition_report(graph, partitions, seeds, scc_budget)¶
Compose all partition metrics and SCC-budget violations.
Module chiplet.link_protocols¶
Class CDCConfig¶
Describe asynchronous crossing parameters for one directed link.
- post_init()
- Validate clock, FIFO-depth, and synchronizer-stage boundaries.
- ratio()
- Return source-to-destination clock ratio, or one for a zero destination clock.
- is_mesochronous()
- Return whether source and destination clocks differ by less than one percent.
Class LinkProtection¶
Describe frame-integrity overhead for one die-to-die link.
- post_init()
- Validate the protection mode and derive its frame overhead.
- effective_bandwidth_ratio()
- Return payload bits divided by payload plus protection bits.
Class CreditConfig¶
Configure receiver-buffer credits for a package link.
- post_init()
- Validate positive credit-count and credit-granularity boundaries.
- buffer_flits()
- Return total receiver capacity represented by the credit counter.
- credit_width()
- Return counter width sufficient to represent the full buffer.
Function compute_cdc_configs(topology)¶
Derive per-link CDC settings from topology die clocks.
Function emit_crc32_sv(data_width)¶
Emit an IEEE 802.3 CRC-32 frame checker for data_width bits.
Function emit_credit_controller_sv(config, link_name)¶
Emit a saturating credit controller for link_name.
Module chiplet.partition¶
Class PartitionAssignment¶
Store neuron identifiers grouped by their assigned die.
- assign(neuron_id, die_id)
- Assign
neuron_idtodie_id. - neurons_on_die(die_id)
- Return neurons assigned to
die_id. - to_routing_tables(connectivity)
- Convert cross-die connectivity into per-source-die routing tables.
Module chiplet.power¶
Class PowerDomain¶
Describe a voltage island spanning one or more package dies.
- post_init()
- Validate domain identity, die ownership, and voltage boundaries.
- is_gated()
- Return whether the domain is currently marked inactive.
- die_mask()
- Return the 64-bit ownership mask used by generated RTL.
Class PowerDomainMap¶
Maintain non-overlapping voltage-domain ownership for package dies.
- add_domain(domain)
- Add a domain after rejecting duplicate die ownership.
- domain_for_die(die_id)
- Return the domain owning
die_id, orNonewhen unassigned. - active_dies()
- Return sorted dies belonging to active domains.
- gated_dies()
- Return sorted dies belonging to inactive domains.
Function emit_power_gating_sv(domain)¶
Emit a sequenced isolation and switch controller for domain.
Module chiplet.routing¶
Class RoutingEntry¶
Map one source neuron to a remote die, neuron, and Q8.8 weight.
Class RoutingTable¶
Store AER routes originating on one die.
- add_route(src, dst_die, dst_neuron, weight)
- Append one source-to-destination route.
- routes_to_die(target_die)
- Return entries whose destination is
target_die. - num_entries()
- Return the number of routes in the table.
- target_dies()
- Return sorted unique destination die identifiers.
Class PackageEnergyReport¶
Record per-link and aggregate communication energy.
- total_nj()
- Return aggregate energy in nanojoules.
Class CongestionReport¶
Record per-link utilisation and the highest-utilisation link.
Class TimingSimResult¶
Summarise accumulated timing and reliability along one path.
Function compute_decorrelation_seeds(topology)¶
Assign deterministic non-zero LFSR seeds to directed links.
The golden-ratio sequence spreads adjacent link indices over the 16-bit state space while preserving reproducibility.
Function link_energy_pj(link, bits)¶
Return energy in picojoules for bits transmitted over link.
Function estimate_package_energy(topology, bits_per_link)¶
Estimate communication energy for uniform traffic on every link.
Function estimate_congestion(topology, routing_tables, events_per_cycle)¶
Estimate directed-link utilisation from AER routing tables.
Function find_disjoint_paths(topology, src_die, dst_die, max_paths)¶
Find up to max_paths directed link-disjoint paths.
Function simulate_timing(topology, src_die, dst_die)¶
Return the lowest-latency reachable path between two dies.
Function adaptive_route(topology, src_die, dst_die, congestion, congestion_threshold)¶
Find a path avoiding links above congestion_threshold when possible.
Function bandwidth_aware_route(topology, src_die, dst_die, required_gbps)¶
Find a path whose every link meets required_gbps.
Module chiplet.rtl¶
Class ChipletOutput¶
Contain generated source and constraint artefacts for one topology.
- to_dict()
- Return generated artefacts keyed by their output filename.
Class ChipletGenerator¶
Generate connected multi-die routing RTL from a chiplet topology.
- generate(topology, routing)
- Generate package RTL and timing constraints.
Module chiplet.thermal¶
Class DieThermal¶
Hold thermal properties and runtime state for one die.
Parameters¶
die_id Non-negative package die identifier. temperature_c Current junction temperature in degrees Celsius. power_mw Dissipated power in milliwatts. heat_capacity_j_per_k Positive die heat capacity in joules per kelvin. r_to_ambient_k_per_w Positive junction-to-ambient resistance in kelvin per watt. r_spread_k_per_w Non-negative within-die spreading resistance in kelvin per watt. max_temperature_c Junction-temperature throttle threshold in degrees Celsius.
- post_init()
- Validate the die identity and finite physical thermal properties.
- is_throttled()
- Return whether the current temperature meets the throttle threshold.
Class PackageThermalReport¶
Contain steady-state, transient, and conductance evidence for a package.
Function simulate_thermal(topology, power_per_die_mw, ambient_c)¶
Solve the package thermal network.
Parameters¶
topology Dies and interposer links forming the thermal network. power_per_die_mw Optional per-die dissipation overrides in milliwatts. ambient_c Ambient temperature in degrees Celsius. die_state Optional per-die material and runtime-state overrides. transient_steps Number of implicit-Euler transient samples after cold start. transient_dt_s Positive transient integration step in seconds.
Returns¶
PackageThermalReport Steady-state temperatures and optional transient trajectory.
Raises¶
ValueError If the topology is empty or any numerical contract is invalid.
Module chiplet.topology¶
Class InterposerTech¶
Supported die-to-die interconnect technology presets.
Class InterposerLink¶
Describe one directed die-to-die link.
Parameters¶
src_die, dst_die
Non-negative source and destination die identifiers.
technology
Interconnect technology used by the link.
latency_ns, jitter_ns
Nominal latency and non-negative timing jitter in nanoseconds.
bandwidth_gbps
Positive link bandwidth in gigabits per second.
bit_error_rate
Per-bit error probability in the closed interval [0, 1].
data_width
Positive payload width in bits.
is_bidirectional
Whether package metadata treats the physical link as bidirectional.
thermal_resistance_k_per_w
Optional measured bond resistance in kelvin per watt.
- post_init()
- Validate endpoint identities and finite physical link properties.
- from_tech(cls, src, dst, tech)
- Construct a link from a technology preset.
- latency_cycles()
- Return rounded link latency at the historical 200 MHz reference clock.
- fifo_depth_log2()
- Return the minimum asynchronous FIFO depth exponent for link jitter.
Class ChipletDie¶
Describe one die and its local AER configuration.
- post_init()
- Validate die identity, clock, seed, and local interface widths.
- clock_period_ns()
- Return the die clock period in nanoseconds.
Class ChipletTopology¶
Store the directed die and interposer graph for one package.
- add_die(die)
- Append a die to the topology.
- add_link(link)
- Append a directed interposer link to the topology.
- mesh_2d(cls, rows, cols, tech)
- Construct a rectangular mesh without wrap-around links.
- ring(cls, n_dies, tech)
- Construct a directed ring with one outgoing edge per die.
- star(cls, n_dies, tech)
- Construct a bidirectional star with die zero as the hub.
- get_links_from(die_id)
- Return all directed links originating at
die_id. - get_links_to(die_id)
- Return all directed links terminating at
die_id. - get_die(die_id)
- Return the die with
die_id, orNonewhen it is absent. - num_dies()
- Return the number of dies registered in the topology.
Class StackingType¶
Supported die-stacking geometries.
Class TSVLink¶
Describe the physical geometry of a through-silicon-via link.
- latency_ns()
- Return TSV latency in nanoseconds.
- bandwidth_gbps()
- Return aggregate bandwidth at one bit per TSV and 200 MHz.
Function make_torus(rows, cols, tech)¶
Construct a rectangular torus with right and downward wrap-around links.
Function add_3d_stack(topology, bottom_die, top_die, stacking)¶
Add reciprocal links between vertically associated dies.
Returns¶
InterposerLink
The bottom-to-top link. The reciprocal link is also added to topology.
Module cli.commands.compile¶
Function add_compile_commands(subparsers)¶
Register equation and NIR compilation commands.
Parameters¶
subparsers : argparse._SubParsersAction[argparse.ArgumentParser] Top-level command registry.
Function run_compile_nir(args)¶
Compile a NIR file to Verilog RTL artefacts.
Parameters¶
args : argparse.Namespace
Parsed compile-nir arguments.
Returns¶
int Zero on success, otherwise one for invalid command input.
Function compile_loaded_nir_network(network, args)¶
Lower an imported NIR network to RTL artefacts, as compile-nir does.
Parameters¶
network : SCNetwork
The network from_nir imported; a graph the Python API accepts but
no .nir file can express (a multi-port subgraph joined without port
addressing) reaches the same pipeline this way.
args : argparse.Namespace
Parsed compile-nir arguments, already validated.
Returns¶
int Zero once every artefact has been written.
Function run_compile(args)¶
Compile an ODE equation to Verilog RTL and optional synthesis.
Parameters¶
args : argparse.Namespace
Parsed compile arguments.
Returns¶
int Zero after artefact emission; invalid equations propagate their typed error.
Notes¶
The command supports three compilation modes via CLI flags:
- Standard (default): combinational datapath at the configured
precision (
--data-width/--fraction). - Pipelined (
--pipeline auto|N): insert register stages at multiply outputs for high-frequency targets.autousescritical_path_depth()+pipeline_stages_needed()fromstatic_analysis.py.--pipeline-pointsselects individual signals to register. - Adaptive precision (
--adaptive-precision): generate a dual-datapath module with LP and HP sub-modules, hysteresis-based precision switching, and clock gating. Configure LP/HP widths via--lp-width/--lp-fracand--hp-width/--hp-fracor precision strings via--lp-precision/--hp-precision.
Module cli.commands.dataset¶
Function add_dataset_command(subparsers)¶
Register dataset manifest, dataset verify and dataset split.
Parameters¶
subparsers : argparse._SubParsersAction[argparse.ArgumentParser] Top-level command registry.
Function run_dataset_manifest(args)¶
Write the manifest of a dataset directory.
Parameters¶
args : argparse.Namespace
Parsed dataset manifest arguments.
Returns¶
int Zero on success, two when the directory or the version is refused.
Function run_dataset_verify(args)¶
Compare a directory with a manifest.
Parameters¶
args : argparse.Namespace
Parsed dataset verify arguments.
Returns¶
int Zero when the directory holds exactly the manifest's bytes, one when it differs, two when the manifest cannot be read.
Function run_dataset_split(args)¶
Divide a published split by whole groups and write the plan.
Parameters¶
args : argparse.Namespace
Parsed dataset split arguments.
Returns¶
int Zero on success, two when the manifest or the request is refused.
Module cli.commands.deploy¶
Function add_deploy_command(subparsers)¶
Register the model deployment command.
Parameters¶
subparsers : argparse._SubParsersAction[argparse.ArgumentParser] Top-level command registry.
Function run_deploy(args)¶
Deploy one model through the selected target workflow.
Parameters¶
args : argparse.Namespace Parsed deployment arguments.
Returns¶
int Zero on success, otherwise one for an invalid or failed deployment.
Function run_auto_synthesis(output_dir, target, top_module, cfg)¶
Run the open-source synthesis flow when its tools are installed.
Parameters¶
output_dir : str Deployment directory containing the HDL tree. target : str Target identifier used in status output. top_module : str SystemVerilog top-module name. cfg : dict[str, str] Device family, part, package, and tool configuration.
Returns¶
bool
True when Yosys succeeds, otherwise False.
Module cli.commands.formal¶
Function add_formal_command(subparsers)¶
Register network formal verification.
Parameters¶
subparsers : argparse._SubParsersAction[argparse.ArgumentParser] Top-level command registry.
Function run_formal(args)¶
Compile and replay network-level formal verification artefacts.
Parameters¶
args : argparse.Namespace
Parsed formal arguments.
Returns¶
int Zero when emitted contracts and requested verification pass, otherwise one.
Module cli.commands.hub¶
Function add_hub_command(subparsers)¶
Register the self-hosted hub bundle command.
Parameters¶
subparsers : argparse._SubParsersAction[argparse.ArgumentParser] Top-level command registry.
Function run_hub_init(args)¶
Write the requested self-hosted hub bundle.
Parameters¶
args : argparse.Namespace
Parsed hub-init arguments.
Returns¶
int Zero on success, otherwise one for invalid configuration or I/O failure.
Module cli.commands.info¶
Function add_info_command(subparsers)¶
Register the runtime information command.
Parameters¶
subparsers : argparse._SubParsersAction[argparse.ArgumentParser] Top-level command registry.
Function run_info(args)¶
Print runtime information without importing optional dependencies.
The execution-lane report reads this installation's packages and files; it does not start Julia or load a native library.
Parameters¶
args : argparse.Namespace
Parsed info arguments.
Returns¶
int Always zero after the status report is emitted.
Module cli.commands.maintenance¶
Function add_maintenance_commands(subparsers)¶
Register benchmark and preflight delegates.
Parameters¶
subparsers : argparse._SubParsersAction[argparse.ArgumentParser] Top-level command registry.
Function run_benchmark(args)¶
Run the repository benchmark suite in a child interpreter.
Parameters¶
args : argparse.Namespace
Parsed benchmark arguments.
Returns¶
int Child process exit status.
Function run_preflight(args)¶
Run the repository preflight script in a child interpreter.
Parameters¶
args : argparse.Namespace
Parsed preflight arguments.
Returns¶
int Child process exit status.
Module cli.commands.mapping¶
Function add_mapping_command(subparsers)¶
Register the NIR silicon-mapping command.
Parameters¶
subparsers : argparse._SubParsersAction[argparse.ArgumentParser] Top-level command registry.
Function run_mapping(args)¶
Write a NIR silicon-mapping report.
Parameters¶
args : argparse.Namespace
Parsed map-nir arguments.
Returns¶
int Zero on success, otherwise one for invalid input or conversion failure.
Module cli.commands.scnir¶
Function add_scnir_command(subparsers)¶
Register SC-NIR document operations.
Parameters¶
subparsers : argparse._SubParsersAction[argparse.ArgumentParser] Top-level command registry.
Function run_scnir(args)¶
Execute an SC-NIR document operation.
Parameters¶
args : argparse.Namespace
Parsed scnir arguments.
Returns¶
int Zero on success, otherwise one for invalid input or evidence.
Module cli.commands.serve¶
Function add_serve_command(subparsers)¶
Register the streaming inference command.
Parameters¶
subparsers : argparse._SubParsersAction[argparse.ArgumentParser] Top-level command registry.
Function run_serve(args)¶
Load a NIR graph and start its blocking spike server.
Parameters¶
args : argparse.Namespace
Parsed serve arguments.
Returns¶
int Zero after a clean server shutdown, otherwise one for invalid input.
Module cli.commands.studio¶
Function add_studio_commands(subparsers)¶
Register Studio launch and operator commands.
Parameters¶
subparsers : argparse._SubParsersAction[argparse.ArgumentParser] Top-level command registry.
Function run_studio(args)¶
Launch the local Studio application.
Parameters¶
args : argparse.Namespace
Parsed studio arguments.
Returns¶
int Zero after a clean server shutdown, otherwise one when Studio extras are absent.
Function run_studio_backup_plan(args)¶
Emit the Studio durable-state backup and restore plan.
Parameters¶
args : argparse.Namespace
Parsed studio-backup-plan arguments.
Returns¶
int Zero when required durable targets exist, otherwise one.
Function run_studio_bootstrap_admin(args)¶
Create the first local Studio service-account identity file.
Parameters¶
args : argparse.Namespace
Parsed studio-bootstrap-admin arguments.
Returns¶
int Zero on success, otherwise one for invalid input or I/O failure.
Function run_studio_deployment_profile(args)¶
Emit a Studio deployment profile package.
Parameters¶
args : argparse.Namespace
Parsed studio-deployment-profile arguments.
Returns¶
int Zero on success, otherwise one for an invalid profile.
Function run_studio_preflight(args)¶
Run the Studio release-readiness preflight.
Parameters¶
args : argparse.Namespace
Parsed studio-preflight arguments.
Returns¶
int Zero when the report passes, otherwise one.
Function run_studio_add_browser_user(args)¶
Add a persistent browser-login user to a Studio identity file.
Parameters¶
args : argparse.Namespace
Parsed studio-add-browser-user arguments.
Returns¶
int Zero on success, otherwise one for invalid input or I/O failure.
Module cli.commands.synthesis¶
Function add_synthesis_command(subparsers)¶
Register synthesis evidence collection.
Parameters¶
subparsers : argparse._SubParsersAction[argparse.ArgumentParser] Top-level command registry.
Function run_collect_synthesis(args)¶
Collect synthesis reports into optimiser evidence JSON.
Parameters¶
args : argparse.Namespace
Parsed collect-synthesis arguments.
Returns¶
int Zero on success, otherwise one for missing or invalid evidence.
Module cli.commands.train¶
Function add_train_command(subparsers)¶
Register train.
Parameters¶
subparsers : argparse._SubParsersAction[argparse.ArgumentParser] Top-level command registry.
Function run_train(args)¶
Run one training request to a terminal state and print its outcome.
Parameters¶
args : argparse.Namespace
Parsed config, job_root and timeout.
Returns¶
int 0 completed with its criterion met or none declared, 1 failed or stopped, 2 request refused, 3 criterion missed.
Module cli.parser¶
Function build_parser()¶
Build the top-level parser and all command-specific parsers.
Returns¶
argparse.ArgumentParser
Parser for the installed sc-neurocore console script.
Function main(argv)¶
Run the command-line interface and return a process exit status.
Parameters¶
argv : Sequence[str] | None
Argument vector without the executable name. None reads
sys.argv through :mod:argparse.
Returns¶
int Zero on success, otherwise the command-specific failure status.
Module comm.aer_udp¶
Class AEREvent¶
Single AER spike event.
Class AERSender¶
Send AER spike events over UDP.
Parameters¶
host : str Destination IP address. port : int Destination UDP port.
- init(host, port)
- send(events)
- Send a batch of AER events. Returns number of packets sent.
- send_spikes(spike_vector, timestamp)
- Convert a binary spike vector to AER events and send.
- close()
Class AERReceiver¶
Receive AER spike events over UDP.
Parameters¶
host : str Bind address. port : int Listen port. timeout : float Socket timeout in seconds.
- init(host, port, timeout)
- receive()
- Receive one packet of AER events. Returns empty list on timeout.
- receive_as_vector(n_neurons)
- Receive and convert to binary spike vector.
- close()
Module compiler._sby_runner¶
Class SbyRun¶
The raw outcome of one :func:run_sby_task invocation.
Attributes¶
verdict : str
The parsed SymbiYosys verdict ("PASS", "FAIL", "ERROR", ...).
rc : int
The return code reported inside the DONE (..., rc=N) summary line.
returncode : int
The sby process exit code (distinct from rc: the process may exit
non-zero on a FAIL while rc classifies the proof outcome).
counterexample : str or None
The failing-assertion description when the output carries one, else
None.
trace_path : str or None
Absolute path to the counterexample trace (resolved against the work
directory) when the output names one, else None.
summary : list[str]
The sby summary: lines, retained for diagnostics.
stdout : str
The full captured standard output, retained for error reporting.
Function formal_tools_available(engine)¶
Return True when the full proof toolchain is on PATH.
Checks sby and yosys plus the SMT solver binary for engine — for
the smtbmc backend the engine name is also the solver executable name
(z3, boolector, yices …). A runner may have sby and yosys
installed yet lack the solver (as on a CI image that ships only the HDL
toolchain), in which case a proof would error out at the engine stage; this
guard reports that case as unavailable so callers and tests can skip cleanly.
Parameters¶
engine : str
The smtbmc SMT engine whose solver binary must also be present.
Returns¶
bool
True only when sby, yosys, and the engine solver all
resolve on PATH.
Function parse_verdict(stdout)¶
Extract the (verdict, rc) from the sby summary.
SymbiYosys prints one DONE (<verdict>, rc=<n>) line per finished task; the
last such line is the authoritative outcome (an earlier DONE (ERROR, ...)
can precede a retried task). Returns ("UNKNOWN", -1) when no DONE line
is present at all — a truncated or crashed run.
Parameters¶
stdout : str
The captured sby standard output.
Returns¶
tuple[str, int]
The verdict token and the sby return code it reported.
Function run_sby_task(workdir, sby_name)¶
Run one already-written .sby task in workdir and read its verdict.
The .sby script and every source file it reads must already exist in
workdir; this call only invokes sby -f <sby_name> there, captures the
output, and parses it into an :class:SbyRun. Counterexample text and trace
path are extracted opportunistically — they are populated regardless of
verdict when present, and the caller decides which fields matter for its
result type.
Parameters¶
workdir : Path
Directory holding the .sby script and its sources; also the sby
run tree and the base for resolving a relative counterexample trace path.
sby_name : str
File name of the .sby script within workdir.
timeout_s : float
Wall-clock limit for the sby process.
Returns¶
SbyRun The parsed run outcome.
Raises¶
RuntimeError
If the sby process exceeds timeout_s.
Function is_inconclusive(run)¶
Return True for an inconclusive result — proved nothing, disproved nothing.
A k-induction (mode prove) run whose base case holds but whose induction
step does not converge reports UNKNOWN with :data:_INCONCLUSIVE_RC: the
property may well be true, but was not proved and no counterexample was found
(the induction step reached the goal from an unreachable predecessor). This
is a real, honest outcome distinct from both a disproof and a tool failure.
Parameters¶
run : SbyRun The raw run to inspect.
Returns¶
bool
True only for the UNKNOWN / inconclusive-return-code signature.
Function raise_for_incomplete(run)¶
Raise when the run is a tool or setup failure, not a verdict about the design.
A PASS (proved) or FAIL (disproved with a counterexample) is a
conclusive outcome, and an inconclusive k-induction result
(:func:is_inconclusive) is a real — if unhelpful — outcome; none of these
raise. Any other verdict — ERROR, a crash with no DONE line, a
timeout — is a tool or setup failure that must not be read as a claim about
the design, so callers invoke this before interpreting a result.
Parameters¶
run : SbyRun
The raw run to inspect.
what : str
Short label for the check ("equivalence proof", "property proof")
used in the raised message.
Raises¶
RuntimeError When the run neither proved, disproved, nor came back inconclusive.
Module compiler._verilog_folded_datapath¶
Function compile_to_datapath(neuron, module_name, data_width, fraction)¶
Compile an EquationNeuron to a combinational processing element.
State is carried on ports — <var>_reg inputs and <var>_next_out
outputs — instead of internal registers, so one PE can be time-multiplexed
across many neurons (the folded interconnect stores per-neuron state in BRAM
and streams it through this PE one neuron per cycle). spike_out and each
<var>_next_out are the post-threshold, post-reset next values, computed by
the same fragments as :func:compile_to_verilog — so the folded datapath is
bit-for-bit identical to the per-instance module.
param_ports names the parameters to carry on input ports instead of
baking them as module parameter defaults. A folded population whose neurons
have heterogeneous parameters drives these ports from a per-neuron parameter ROM
(one value per neuron, streamed by the sequencer), the parameter-space analogue of
the state BRAM. Because the arithmetic body references each parameter by the same
P_<NAME> identifier whether it is a parameter or an input wire, moving a
parameter to a port changes only its declaration — the datapath stays bit-for-bit
identical. Every name must be a real neuron parameter/constant; the rest stay baked.
Escape-rate models additionally expose the already-advanced 16-bit rng_sample
input: the folded population owns one LFSR state per neuron in BRAM and supplies
that sample on the same cycle as the corresponding membrane state.
Pipelining is not supported here (a combinational PE has no register stages); the folded sequencer provides the one-cycle-per-neuron timing instead.
Unsigned emission is rejected because the expression and derivative
datapaths use signed fixed-point arithmetic. Product rounding accepts
"truncate", "nearest", or "bankers"; "stochastic" is
rejected because the PE has no caller-owned product-rounding LFSR.
Module compiler._verilog_registered_module¶
Function compile_to_verilog(neuron, module_name, data_width, fraction)¶
Compile an EquationNeuron to synthesizable Verilog RTL.
Parameters¶
neuron : EquationNeuron
The neuron defined by arbitrary ODE strings.
module_name : str
Name of the generated Verilog module.
data_width : int
Bit width for fixed-point arithmetic (default 16 = Q8.8).
fraction : int
Number of fractional bits (default 8).
signed : bool
Must be True. Unsigned emission is rejected because the expression
and derivative datapaths use signed fixed-point arithmetic.
overflow : str
Overflow mode: "saturate" (default), "wrap", or "trap".
rounding : str
Rounding mode: "truncate" (default), "nearest",
or "bankers". "stochastic" is rejected because the generated
datapath has no caller-owned product-rounding LFSR.
pipeline_stages : int
0 disables global pipelining; any positive value registers multiply
outputs. Must be non-negative and cannot be combined with
pipeline_points.
pipeline_points : list[str], optional
Unique intermediate multiply names to register instead of enabling the
global pipeline.
Module compiler.auto_tune¶
Function precision_plan_manifest(assignments)¶
Build a deterministic manifest for a per-synapse precision plan.
Function auto_tune_synapse_precisions(layer_weights)¶
Auto-tune per-synapse precision for an explicit percent error target.
Module compiler.block_floating¶
Class BlockFloatingMode¶
Shared-exponent block floating-point specification.
- label()
- Human-readable label.
- exponent_bias()
- Bias applied to shared exponents.
- min_exponent()
- Minimum unbiased exponent.
- max_exponent()
- Maximum unbiased exponent.
- mantissa_range()
- Largest signed mantissa magnitude.
- emit_fraction()
- Conservative fixed-point fallback fraction for RTL emission.
- metadata()
- Deterministic metadata payload for cross-target telemetry.
- block_exponent_count(parameter_count)
- Return the exact number of shared exponents for a flat parameter payload.
- block_exponent_layout(parameter_count)
- Return the explicit exponent-vector layout for downstream emitters.
- validate_exponents(exponents)
- Validate exponent vector length and code range for a parameter payload.
- from_string(cls, fmt)
- Parse strict canonical format like 'BFP16E3'.
- from_aliases(cls, fmt)
- Parse tolerant aliases such as BFP16_E3, BFP16.3, BFP16-3, and BFP16E3X32.
Class BlockExponentLayout¶
Concrete shared-exponent layout for flattened block-floating parameters.
- post_init()
- last_block_size()
- Number of parameters carried by the final exponent block.
- manifest()
- Deterministic block-exponent layout manifest.
- validate_exponents(exponents)
- Validate exponent vector length and encoded range.
Module compiler.block_floating_quantization¶
Class CompiledBlockFloatingDense¶
Dense operator compiled with shared-exponent block-floating weights.
- post_init()
- output_size()
- Number of dense output channels.
- input_size()
- Number of dense input channels.
- reconstructed_weights()
- Float reconstruction of the compiled block-floating weight matrix.
- manifest()
- Deterministic deployment metadata for block-floating dense weights.
- forward_float(inputs)
- Return dense outputs from BFP weights and quantised fixed-point inputs.
- forward_with_overflow(inputs)
- Return saturated fixed-point output codes and per-output overflow flags.
- forward_accumulator_codes(inputs)
- Return saturated output codes in the configured fixed-point input format.
- precision_trap_report(inputs)
- Return saturation telemetry suitable for a hardware trap register.
- precision_envelope_report(inputs)
- Return a conservative absolute-output envelope for this workload.
Function compile_dense_block_floating(weights, fmt)¶
Compile a dense matrix into block-floating weights with Q-format inputs.
Function quantize_block_floating(weights, fmt)¶
Quantize float weights into shared-exponent block-floating blocks.
Function dequantize_block_floating(quantized, exponents, fmt)¶
Reconstruct floats from block-floating mantissas and exponents.
Module compiler.c_expr_emitter¶
Class CExprEmitter¶
Lower a Python expression AST to a C++ (ap_fixed) expression string.
Parameters¶
state_vars : set of str
ODE state-variable names; emitted verbatim (they are struct members /
locals in the generated function).
param_map : dict, optional
Mapping from parameter names to their C++ identifiers.
math_ns : str
Namespace prefix for transcendental calls ("hls" for Vitis HLS math,
"std" for a portable <cmath> build).
fp_type : str
Fixed-point type name used to cast numeric literals.
Attributes¶
free_vars : list of str Identifiers referenced by the expression that are not state variables, parameters, or the input current — collected in first-seen order for the exporter to declare as inputs.
- init(state_vars, param_map)
- visit_BinOp(node)
- Emit C++ for a binary operation (add, sub, mul, div, pow).
- visit_UnaryOp(node)
- Emit C++ for a unary operation (negate, positive).
- visit_Name(node)
- Resolve a Python name to its C++ identifier, recording free variables.
- visit_Constant(node)
- Emit a numeric constant cast to the fixed-point type.
- visit_Compare(node)
- Emit C++ for comparison operators (>, >=, <, <=).
- visit_Call(node)
- Emit C++ for a supported function call.
- generic_visit(node)
- Raise for any unsupported AST node type.
Function emit_c_expr(expr_str, state_vars, param_map)¶
Parse an ODE expression and return its C++ form plus its free variables.
Parameters¶
expr_str : str Python-syntax ODE expression. state_vars : set of str ODE state-variable names. param_map : dict, optional Parameter-name to C++-identifier mapping. math_ns : str Namespace prefix for transcendental calls. fp_type : str Fixed-point type used to cast numeric literals.
Returns¶
tuple of (str, list of str) The C++ expression string and the free identifiers it references (in first-seen order).
Module compiler.c_fixed_emitter¶
Function signed_q(q, value)¶
Encode value as the signed integer its Verilog 'sd literal denotes.
This is the two's-complement bit pattern of round(value * 2**fraction)
truncated to data_width bits, reinterpreted as a signed integer — exactly
what :meth:Q88.encode_signed_literal writes into the RTL, but as a Python
int suitable for a C/Rust literal.
Function emit_c_fixed_expr(expr_str, state_map, param_map, q)¶
Lower an ODE expression to a bit-exact integer C/Rust expression.
Parameters¶
expr_str : str
Python-syntax ODE right-hand-side expression.
state_map : dict
ODE variable name to its register-read source lvalue.
param_map : dict
Parameter name to its signed Q-format integer value.
q : Q88
Fixed-point configuration.
lang : str
"c" or "rust".
input_ref : str
Source expression reading the input current I.
lut_start : int
Starting index for LUT table naming, so several expressions of one kernel
get unique table names.
Returns¶
tuple
(expr, statements, tables, free_vars, lut_count, input_used) — the
64-bit-integer expression string, the helper statements it depends on, the
LUT tables it references, the free identifiers it introduced (first-seen
order), the next free LUT index, and whether the input current was read.
Module compiler.certification_gen¶
Class CertificationItem¶
A single certification evidence item.
Attributes¶
req_id : str
Requirement identifier (e.g. "REQ-001").
description : str
Requirement description.
design_ref : str
Design artifact (e.g. Verilog module name).
verification_ref : str
Verification artifact (e.g. SVA property, Cocotb test).
status : str
"PASS", "FAIL", or "UNTESTED".
Function generate_certification_evidence(module_name, items)¶
Generate XML traceability matrix for safety certification.
Produces a certification evidence document linking requirements to design and verification artifacts in the format required by DO-254 (avionics), IEC 61508 (industrial), or ISO 26262 (automotive).
Parameters¶
module_name : str
Design module under certification.
items : list[CertificationItem]
Requirement-to-evidence mapping.
standard : str
"do254", "iec61508", or "iso26262".
dal_level : str
Design Assurance Level or SIL/ASIL level.
Returns¶
str XML certification evidence document.
Module compiler.cocotb_gen¶
Function generate_cocotb_testbench(module_name)¶
Generate a Cocotb (Python) testbench for a compiled neuron.
Parameters¶
module_name : str Verilog module name. data_width : int Fixed-point data width. fraction : int Fractional bits. n_steps : int Number of simulation clock cycles. input_current : float Input current value.
Returns¶
str Complete Cocotb Python testbench.
Module compiler.compiler_impl¶
Function compile_adaptive_precision(neuron, module_name, lp_width, lp_frac, hp_width, hp_frac)¶
Compile an EquationNeuron to dual-datapath adaptive-precision Verilog.
Module compiler.constraint_gen¶
Function generate_constraints(module_name)¶
Generate timing constraint file for FPGA synthesis.
Parameters¶
module_name : str
Top-level module name.
target_freq_mhz : float
Target clock frequency in MHz.
format : str
"xdc" for Xilinx Vivado, "sdc" for Intel Quartus / generic.
clock_port : str
Name of the clock input port.
reset_port : str
Name of the reset input port.
data_width : int
Data width for I/O delay estimation.
Returns¶
str Complete constraint file content.
Module compiler.equivalence_check¶
Class EquivalenceResult¶
Outcome of a machine-checked equivalence proof.
Attributes¶
proven : bool
True when the checker proved output equivalence to depth cycles.
verdict : str
The raw SymbiYosys verdict ("PASS", "FAIL", "ERROR", ...).
mode : str
"bmc" (bounded) or "prove" (k-induction).
depth : int
Checked depth in clock cycles.
engine : str
SMT engine used (e.g. "z3").
returncode : int
sby process exit code.
counterexample : str or None
Failing-assertion description on a FAIL verdict, else None.
trace_path : str or None
Path to the counterexample VCD trace on FAIL, else None.
summary : list[str]
The sby summary lines, retained for diagnostics.
Function prove_equivalence(dut_verilog, ref_verilog, io_ports)¶
Prove dut_verilog equivalent to ref_verilog via SymbiYosys.
Parameters¶
dut_verilog, ref_verilog : str
Verilog sources defining dut_top and ref_top respectively.
io_ports : list[MiterPort]
Shared interface passed to :func:build_equivalence_miter.
dut_top, ref_top : str
Module names under verification (must differ).
dut_params, ref_params : dict[str, int], optional
Per-instance parameter overrides.
depth : int
BMC / induction depth in clock cycles.
engine : str
SMT engine ("z3" by default; the smtbmc backend).
mode : {"bmc", "prove"}
Bounded model checking or k-induction.
reset_cycles : int
Leading clocks to hold reset before comparing.
clock, reset_n : str
Clock and active-low reset port names.
timeout_s : float
Wall-clock limit for the sby process.
workdir : str or Path, optional
Directory for the generated sources and sby run tree. A temporary
directory is created and left in place if omitted (caller cleans up).
Returns¶
EquivalenceResult The parsed verdict.
Raises¶
RuntimeError
If the formal tools are absent, the sby run errors out (a tool or
setup failure, distinct from a FAIL disproof), or times out.
Module compiler.equivalence_miter¶
Class MiterPort¶
One port of the module interface shared by the DUT and the reference.
Attributes¶
name : str
Port identifier.
width : int
Bit width (1 for a scalar port).
signed : bool
Whether the port is declared signed.
direction : str
"input" or "output".
- declaration(suffix)
- Return a Verilog
wiredeclaration for this port.
Function parse_module_interface(verilog, top)¶
Parse the ANSI port interface of a Verilog module.
Parameters¶
verilog : str
Verilog source containing the module.
top : str
Module name whose interface to parse.
params : dict[str, int], optional
Values for any parameters used in port width expressions (e.g.
{"DATA_WIDTH": 16}). Widths that reference an unlisted parameter
raise :class:ValueError.
Returns¶
list[MiterPort] The ports in declaration order.
Function build_equivalence_miter(dut_top, ref_top, io_ports)¶
Build a sequential-equivalence miter for two interface-compatible modules.
Both dut_top and ref_top are instantiated with the same io_ports;
the miter exposes the clock and every non-reset input as free top-level
inputs (the model checker explores all their values), derives an active-low
reset held for reset_cycles clocks from a counter, and asserts that every
output agrees between the two instances once reset is released.
Parameters¶
dut_top, ref_top : str
Module names of the device-under-test and the reference. Must differ so
both sources can be read into one design.
io_ports : list[MiterPort]
The shared interface. Must contain clock and reset_n inputs and
at least one output.
miter_name : str
Name of the generated miter module.
dut_params, ref_params : dict[str, int], optional
Parameter overrides applied to the respective instance (the two modules
may take different parameter sets).
reset_cycles : int
Number of leading clocks to hold reset asserted before comparing.
clock, reset_n : str
Port names of the clock and active-low reset.
Returns¶
str The complete miter Verilog module.
Module compiler.expr_lut_tables¶
Function const_float(node)¶
Constant-fold a literal or simple literal-arithmetic node to a float.
Recognises fractional exponents such as 1.0 / 3.0 in x ** p by
folding compile-time-constant expressions built from literals and +,
-, *, / (and unary minus).
Parameters¶
node : ast.AST Expression node to fold.
Returns¶
float or None
The folded value, or None if the node is not a compile-time
constant.
Function symmetric_sample_points()¶
Return the 256 sample points over [-16, 16) at 0.125 spacing.
The symmetric transcendental LUTs (exp, tanh, sigmoid, sin, cos, cosh,
exprel, cbrt) are tabulated on this grid; the value x == 0 falls at
index 128. Must match the LUT-call defaults (lut_min=-16, step=0.125)
in the emitting backends.
Returns¶
list of float The 256 tabulation points.
Function log_sample_points()¶
Return the 256 positive log points over [1/256, 8+1/256).
The 1/32 spacing and 1/256 offset are both exactly representable in
Q8.8 and Q16.16, so every lowering backend derives the same integer index.
Returns¶
list of float The 256 strictly positive tabulation points.
Function sqrt_sample_points()¶
Return the 16 non-negative sqrt points from zero through 7.5.
Returns¶
list of float The 16 half-unit tabulation points.
Function exp_lut_entries(data_width, fraction)¶
Quantised exp LUT over the symmetric grid, saturated to the word max.
Parameters¶
data_width : int
Fixed-point word width; sets the signed saturation cap.
fraction : int
Number of fractional bits (the Q-format scale 1 << fraction).
Returns¶
list of int 256 integer Q-format entries.
Function log_lut_entries(fraction)¶
Quantised log LUT on the canonical positive 256-point grid.
Parameters¶
fraction : int Number of fractional bits.
Returns¶
list of int 256 integer Q-format entries.
Function sqrt_lut_entries(fraction)¶
Quantised sqrt LUT (16 entries over [0, 7.5] at 0.5 spacing).
Parameters¶
fraction : int Number of fractional bits.
Returns¶
list of int 16 integer Q-format entries.
Function tanh_lut_entries(fraction)¶
Quantised tanh LUT over the symmetric grid.
Parameters¶
fraction : int Number of fractional bits.
Returns¶
list of int 256 integer Q-format entries.
Function cosh_lut_entries(data_width, fraction)¶
Quantised cosh LUT over the symmetric grid, saturated to the word max.
Parameters¶
data_width : int Fixed-point word width; sets the signed saturation cap (cosh grows fast). fraction : int Number of fractional bits.
Returns¶
list of int 256 integer Q-format entries.
Function cbrt_lut_entries(fraction)¶
Quantised cube-root LUT over the symmetric grid (odd, sign-preserving).
Parameters¶
fraction : int Number of fractional bits.
Returns¶
list of int 256 integer Q-format entries.
Function exprel_lut_entries(data_width, fraction)¶
Quantised exprel(z) = (exp(z)-1)/z LUT, with the removable limit 1 at 0.
Grows like exp(z)/z for large z, so entries saturate to the word max.
Parameters¶
data_width : int Fixed-point word width; sets the signed saturation cap. fraction : int Number of fractional bits.
Returns¶
list of int 256 integer Q-format entries.
Function sigmoid_lut_entries(fraction)¶
Quantised logistic-sigmoid LUT over the symmetric grid.
Parameters¶
fraction : int Number of fractional bits.
Returns¶
list of int 256 integer Q-format entries.
Function sin_lut_entries(fraction)¶
Quantised sin LUT over the symmetric grid.
Parameters¶
fraction : int Number of fractional bits.
Returns¶
list of int 256 integer Q-format entries.
Function cos_lut_entries(fraction)¶
Quantised cos LUT over the symmetric grid.
Parameters¶
fraction : int Number of fractional bits.
Returns¶
list of int 256 integer Q-format entries.
Module compiler.fixed_point_quantization¶
Function quantize_weights(weights, fmt, rounding, clip)¶
Quantize float weights to fixed-point integers.
Parameters¶
weights : np.ndarray
Float weight matrix (any shape).
fmt : str | QFormat | QFormatMixed
Q-format string/object, e.g. "Q8.8" or QFormatMixed().
rounding : str
nearest (round half to even), stochastic, or floor.
clip : bool
If True, clip values to the representable range before quantization.
Function dequantize_weights(quantized, fmt, scale)¶
Convert quantized fixed-point weights back to float.
Function dequantize(quantized, fmt, scale)¶
Alias matching the mixed-precision public API.
Function q_weights_to_sc_probabilities(quantized, fmt)¶
Convert fixed-point quantized weights to SC probabilities in [0, 1].
Function quantization_error(weights, fmt, rounding)¶
Compute quantization error statistics.
Module compiler.formal_evidence¶
Function write_precision_formal_evidence_bundle(output_dir, assignments)¶
Write a SymbiYosys evidence bundle for adaptive-precision claims.
Renders the bounded-error monitor RTL, the bound assertion checker, a runnable
.sby script, and a manifest describing the claim. The bundle is
deterministic: identical arguments produce byte-identical artefacts.
Parameters¶
output_dir : str or Path
Directory to write the bundle into (created if absent).
assignments : list[SynapsePrecision]
The precision plan. Must be non-empty.
module_name : str
Top-level module name for the generated RTL and SVA.
execute : bool
When False (default) the bundle is only written and the manifest
records symbiyosys_executed = False — no external tools are invoked,
keeping the call deterministic and CI-safe. When True and the formal
toolchain (sby / yosys / z3) is on PATH, the proof is run
and the real verdict recorded; when the toolchain is absent, a skip reason
is recorded instead of a fabricated pass.
unbounded : bool
Selects the proof method for both the emitted .sby and the executed
proof. False (default) uses bounded model checking to length + 2
cycles — complete because the accumulator saturates. True uses
k-induction (mode prove), an unbounded proof whose depth does not
scale with the bitstream length (the monitor carries the 1-inductive
strengthening lemma the induction needs). k-induction can come back
inconclusive, which is recorded honestly rather than as a pass.
Returns¶
dict[str, Any] The manifest that was written.
Raises¶
ValueError
If assignments is empty.
Module compiler.formal_property_check¶
Class PropertyProofResult¶
Outcome of a machine-checked RTL property proof.
Attributes¶
proven : bool
True when the checker proved every bound assertion holds to depth
cycles under the SVA environment assumptions.
verdict : str
The raw SymbiYosys verdict ("PASS", "FAIL", "ERROR", ...).
mode : str
"bmc" (bounded) or "prove" (k-induction).
depth : int
Checked depth in clock cycles.
engine : str
SMT engine used (e.g. "z3").
returncode : int
sby process exit code.
counterexample : str or None
Failing-assertion description on a FAIL verdict, else None.
trace_path : str or None
Path to the counterexample VCD trace on FAIL, else None.
summary : list[str]
The sby summary lines, retained for diagnostics.
Function prove_property(rtl_verilog, sva_verilog)¶
Prove rtl_verilog satisfies the assertions in sva_verilog via SymbiYosys.
Parameters¶
rtl_verilog : str
Synthesisable Verilog source defining top.
sva_verilog : str
SystemVerilog source carrying the environment assume constraints and
the assert obligations, bound onto top with a bind statement.
top : str
The RTL module name under verification.
mode : {"bmc", "prove"}
Bounded model checking (default, complete for state-stationary designs) or
k-induction.
depth : int
BMC / induction depth in clock cycles.
engine : str
SMT engine ("z3" by default; the smtbmc backend).
timeout_s : float
Wall-clock limit for the sby process.
workdir : str or Path, optional
Directory for the generated sources and sby run tree. A temporary
directory is created and left in place if omitted (caller cleans up).
Returns¶
PropertyProofResult The parsed verdict.
Raises¶
RuntimeError
If the formal tools are absent, the sby run errors out (a tool or
setup failure, distinct from a FAIL disproof), or times out.
Module compiler.fpga_wrapper¶
Function equation_to_fpga()¶
One-liner: ODE string → (Python neuron, Verilog RTL).
Module compiler.guard_bits¶
Function compute_guard_bits(expr_str)¶
Compute the number of guard bits needed for safe accumulation.
When summing N values, the accumulator needs ceil(log2(N+1))
extra MSBs to guarantee no intermediate overflow. For a single
addition (a + b), 1 guard bit suffices. For a + b + c + d,
2 guard bits are needed.
Parameters¶
expr_str : str A Python-syntax ODE right-hand-side expression.
Returns¶
int Minimum number of guard bits needed (0 if no additions).
Examples¶
compute_guard_bits("a + b") 1 compute_guard_bits("a + b + c + d") 2 compute_guard_bits("a * b") 0
Function compute_guard_bits_multi(equations)¶
Compute guard bits for every state variable in a multi-ODE system.
Parameters¶
equations : dict Mapping from variable name to RHS expression string.
Returns¶
dict Mapping from variable name to required guard bits.
Module compiler.hardware_numeric_contract¶
Class EncodedQuantity¶
One value the RTL encodes, and the value it holds there.
Parameters¶
kind:
Where the value comes from. literal_divisor is the reciprocal the
compiler multiplies by when an expression divides by a literal.
name:
The parameter, constant or state name, or where a literal appears.
value:
The value the neuron declares.
rtl_value:
The value the encoded word represents in the RTL.
status:
exact, rounded, underflows_to_zero or out_of_range.
blocking:
True when the status makes the format unrepresentable.
- relative_error()
- Return
|rtl_value - value| / |value|, orNonefor a zero value. - describe()
- Return a one-line statement of what the RTL holds.
- to_public_dict()
- Return the JSON projection.
Class LookupTable¶
One transcendental look-up table the datapath uses.
Arguments outside [domain_min, domain_max) are clamped to the first or
last entry.
- to_public_dict()
- Return the JSON projection.
Class HardwareNumericContract¶
What one neuron's generated RTL holds at one fixed-point format.
Parameters¶
q_format:
Studio label, Q<integer bits>.<fraction bits>.
data_width, fraction:
Word width and fraction bits.
method:
The integration method the RTL realises.
overflow, rounding:
Accumulate commit policy and multiply product policy.
arithmetic:
The bit-true arithmetic statement when the generated C kernel mirrors
this neuron, else None.
mirror_refusal:
Why no bit-true C kernel mirrors this neuron, or "".
quantities:
Every encoded value, in declaration order, literals once each.
lookup_tables:
The look-up tables the datapath uses.
- resolution()
- Return the value of one least-significant bit.
- min_value()
- Return the most negative representable value.
- max_value()
- Return the most positive representable value.
- blocking()
- Return the quantities that make the format unrepresentable.
- representable()
- Return whether every blocking check passes.
- refusal()
- Return why the format is unrepresentable, or
"". - to_public_dict()
- Return the path-free JSON projection.
Function hardware_numeric_contract(neuron, q_format)¶
Return what neuron's generated RTL holds at q_format.
Parameters¶
neuron: The neuron the equation compiler lowers. q_format: The signed fixed-point format. overflow, rounding: The accumulate and multiply policies the RTL is compiled with.
Returns¶
HardwareNumericContract The encoded quantities, look-up tables and bit-true mirror status.
Module compiler.host_driver_gen¶
Function generate_host_driver(module_name, params)¶
Generate host-side driver code for a bus-wrapped neuron.
Parameters¶
module_name : str
Neuron module name.
params : dict[str, int]
Parameter names and bit widths.
language : str
"python" or "c".
bus : str
Bus protocol.
base_address : int
Memory-mapped base address.
data_width : int
Fixed-point data width.
fraction : int
Fractional bits.
live_update_spec : MMIOUpdateSpec, optional
Live-control bank contract. When provided, generated drivers include
CRC-guarded live-parameter update, trap check, and committed readback
helpers for each named bank entry.
Returns¶
str Complete driver source code.
Module compiler.intelligence.adiabatic_clocks¶
Class AdiabaticPhase¶
Adiabatic clock phase timing (ps).
Attributes¶
name : str rise_ps : float hold_ps : float fall_ps : float sleep_ps : float
Function generate_adiabatic_clocks(phases, freq_mhz)¶
Generate multi-phase clocking for adiabatic computing.
Module compiler.intelligence.aging_reliability¶
Class ReliabilityEstimate¶
Mean time to failure estimate.
Attributes¶
mttf_hours : float Estimated MTTF in hours. mttf_years : float Estimated MTTF in years. failure_mode : str Dominant failure mechanism. voltage_stress : float Normalised voltage stress factor. temp_accel : float Arrhenius temperature acceleration factor. mechanism_mttf_hours : dict[str, float] Per-mechanism MTTF estimates for NBTI, HCI, and TDDB.
Class AgingPrediction¶
Transistor aging prediction.
Attributes¶
initial_fmax_mhz : float degraded_fmax_mhz : float degradation_pct : float recommended_derating : float dominant_mechanism : str nbti_degradation_pct : float hci_degradation_pct : float
Function predict_reliability()¶
Predict MTTF from voltage, temperature, and technology node.
Function predict_aging(initial_fmax_mhz)¶
Predict end-of-life Fmax after transistor aging.
Module compiler.intelligence.approximate_computing¶
Class ApproximationConfig¶
Approximate computing configuration.
Attributes¶
populations : dict[str, dict] total_energy_savings_pct : float max_output_error_pct : float
Function configure_approximation(equations)¶
Configure precision-energy tradeoff knobs per state variable.
Module compiler.intelligence.auto_quantization¶
Class QuantSweepResult¶
Result of a quantisation sweep for one (width, fraction) pair.
Attributes¶
data_width : int Total bit width tested. fraction : int Fractional bits tested. guard_bits : int Guard bits required. estimated_luts : int Estimated LUT usage. estimated_dsps : int Estimated DSP usage. estimated_ffs : int Estimated flip-flop usage. max_representable : float Maximum representable value. min_step : float Minimum step size (LSB resolution).
Function auto_quantisation_sweep(equations, target)¶
Sweep data widths to find accuracy-vs-resource trade-offs.
Compiles the same ODE equations at multiple quantisation levels (Q4.2 through Q32.16) and reports the resource cost and numerical precision for each. Enables rapid design-space exploration.
Parameters¶
equations : dict[str, str]
ODE equations mapping state variable names to expressions.
target : str
Target platform name for resource estimation.
widths : list[int], optional
Data widths to sweep. Defaults to [4, 8, 12, 16, 20, 24, 32].
fraction_ratio : float
Fraction of data_width used for fractional bits (default 0.5).
Returns¶
list[QuantSweepResult] Sweep results sorted by data_width (ascending).
Function format_quantisation_report(results)¶
Format a quantisation sweep into a readable markdown table.
Parameters¶
results : list[QuantSweepResult]
Results from auto_quantisation_sweep().
Returns¶
str Markdown table comparing all quantisation levels.
Module compiler.intelligence.bit_true_kernel¶
Function c_word_type(data_width)¶
Return the C integer type the kernel uses for a data_width-bit word.
Harnesses that drive a generated kernel (per-step input words, decoded
state reads) must pass and read exactly this type; it is the type of the
I_t step argument and of every <state>_out field.
Function kernel_arithmetic_contract()¶
State the fixed-point arithmetic a generated neuron kernel performs.
The description is derived from the same configuration checks the
generator applies, so it cannot drift from what
:func:generate_bittrue_kernel_from_neuron emits: value encoding,
multiply width collapse and product rounding, accumulate overflow
handling, division and modulo lowering, look-up-table geometry for the
transcendental vocabulary, and the threshold / reset / output sequencing
of the RTL always block the kernel mirrors.
Parameters¶
data_width, fraction : int
Fixed-point word geometry (Q<data_width - fraction>.<fraction>
in the Studio label convention, Q8.8 = 16 bits).
overflow : str
"saturate" or "wrap" (the accumulate commit policy).
rounding : str
"truncate" or "nearest" (the multiply product policy).
method : str
"euler" (next = commit(reg + fxmul(f, dt_q))) or "map"
(next = commit(f)).
Returns¶
dict Path-free, JSON-portable statement of the arithmetic.
Raises¶
ValueError For a geometry, mode or method the kernel does not mirror, with the same message the generator would raise.
Function generate_bittrue_kernel(module_name, equations)¶
Generate a bit-true fixed-point kernel from a {var: derivative} mapping.
Each state variable advances by one unit-dt explicit-Euler step using the
same wrap-truncate multiply and saturating accumulate as the RTL datapath.
Identifiers in the derivatives that are not state variables become step
arguments (the input current I maps to I_t when referenced), so the
kernel exercises the bit-true primitives without a per-instance I/O contract.
For a whole-neuron kernel that mirrors the generated Verilog, use
:func:generate_bittrue_kernel_from_neuron.
Parameters¶
module_name : str
Base name for the generated struct / functions.
equations : dict
Mapping from state-variable name to its derivative expression string.
data_width : int
Fixed-point total width (default 16 → Q8.8).
fraction : int
Fractional bits (default 8).
language : str
"c" (default) or "rust".
Returns¶
str Bit-true kernel source code.
Function generate_bittrue_kernel_from_neuron(neuron, module_name)¶
Generate a whole-neuron kernel bit-identical to the compiled Verilog.
Mirrors :func:sc_neurocore.compiler.verilog_compiler.compile_to_verilog
exactly for explicit-Euler and discrete-map neurons — parameter/constant
Q-encoding, wrap-truncate arithmetic, the same overflow handling, and the
threshold / reset / spike sequencing of the RTL always block. Threshold
and reset expressions may read <state>_prev aliases for the pre-step
register while ordinary state names resolve to the integrated candidate.
Both state and output fields take the same post-reset value on a spike. The
resulting <module>_step therefore produces the identical per-cycle state
trace as the RTL, which the iverilog co-simulation checks on the stimuli it runs.
Parameters¶
neuron : EquationNeuron
The neuron whose ODEs, parameters, threshold and reset rules are lowered.
module_name : str
Base name for the generated struct / functions.
data_width, fraction : int
Fixed-point format (default Q8.8).
signed : bool
Signed two's complement (only True is supported; unsigned neuron state
is not part of the RTL contract).
overflow : str
"saturate" (default) or "wrap".
rounding : str
"truncate" (default) or "nearest".
language : str
"c" (default) or "rust".
Returns¶
str Bit-true whole-neuron kernel source code.
Module compiler.intelligence.bitstream_encryption¶
Function generate_bitstream_encryption(module_name)¶
Generate bitstream encryption TCL/constraints for secure boot.
Module compiler.intelligence.bitstream_flow¶
Function generate_oss_makefile(module_name)¶
Generate a Makefile for open-source FPGA synthesis (Yosys + nextpnr).
Parameters¶
module_name : str
Top-level module name.
target : str
"ice40" or "ecp5".
device : str
Device string (e.g. "hx8k", "um5g-85k").
package : str
Package (e.g. "ct256", "CABGA381").
freq_mhz : float
Target frequency.
verilog_files : list, optional
Verilog source files.
pcf_file : str, optional
Pin constraint file.
Returns¶
str Complete Makefile content.
Module compiler.intelligence.bram_array¶
Function generate_bram_array(module_name)¶
Generate a time-multiplexed BRAM-backed neuron array in Verilog.
A single compute pipeline is shared across N neurons with BRAM-backed state. The array processes one neuron per clock cycle.
Parameters¶
module_name : str Module name. neuron_count : int Number of neurons. data_width : int Fixed-point data width. state_vars : int State variables per neuron.
Returns¶
str Verilog module source code.
Module compiler.intelligence.carbon_footprint¶
Class CarbonEstimate¶
Carbon footprint estimate per compilation target.
Attributes¶
profile_name : str Target profile. manufacturing_kg_co2 : float Estimated manufacturing CO₂ (kg). operation_kg_co2_per_year : float Estimated annual operation CO₂ (kg). total_5yr_kg_co2 : float Total 5-year lifecycle CO₂ (kg). energy_mix : str Assumed energy source.
Function estimate_carbon_footprint(profile_name)¶
Estimate carbon footprint for a compilation target.
Module compiler.intelligence.cdc_analyzer¶
Class CDCReport¶
Clock domain crossing analysis result.
Attributes¶
crossings : list[dict] Each crossing: signal, src_domain, dst_domain, sync_type. violations : list[str] Unsynchronized crossings. total_crossings : int safe : bool
Function analyze_cdc(equations)¶
Analyze clock domain crossings in a neuron array.
Module compiler.intelligence.cdc_synchroniser¶
Function generate_cdc_synchroniser(signal_name)¶
Generate a CDC (Clock Domain Crossing) synchroniser in Verilog.
Uses a multi-stage register chain to safely transfer signals between clock domains.
Parameters¶
signal_name : str Name of the signal being synchronised. width : int Bit width (1 for single-bit CDC). stages : int Number of synchroniser stages (2 minimum, 3 for MTBF). src_clock : str Source clock name. dst_clock : str Destination clock name.
Returns¶
str Verilog CDC synchroniser module.
Module compiler.intelligence.checksum¶
Function embed_model_checksum(verilog)¶
Embed a SHA-256 checksum of the compiled model in the Verilog source.
Module compiler.intelligence.cognitive_bounds¶
Class CognitiveBounds¶
Clamping results for cognitive stability.
Attributes¶
safe_equations : dict[str, str] lyapunov_divergence_proxy : float switches_inserted : int
Function enforce_cognitive_bounds(equations, state_bounds)¶
Enforce safe operating ranges on cognitive models via RTL clamping.
Module compiler.intelligence.compilation_cache¶
Class CompilationCache¶
Memoized compilation result cache.
Keyed by (equations_hash, target, data_width, fraction).
Avoids redundant recompilation when re-targeting.
- init()
- get(equations, target, data_width, fraction)
- Look up a cached compilation result.
- put(equations, target, data_width, fraction, result)
- Store a compilation result in cache.
- size()
- Number of cached entries.
Module compiler.intelligence.compilation_report¶
Function generate_compilation_report(module_name, equations, profile_name)¶
Generate comprehensive compilation report.
Consolidates Verilog, timing, power, carbon, risk, and reliability into a single markdown document.
Parameters¶
module_name : str Module name. equations : dict[str, str] ODE equations. profile_name : str Target profile. include_carbon : bool Include carbon footprint section. include_reliability : bool Include reliability prediction.
Returns¶
str Markdown report.
Module compiler.intelligence.compilation_summary¶
Function generate_compilation_summary(module_name, equations, target)¶
Generate a comprehensive human-readable compilation summary.
Produces a markdown document summarising all aspects of a compilation.
Parameters¶
module_name : str Compiled module name. equations : dict[str, str] ODE equations compiled. target : str Target platform. data_width : int Total bit width. fraction : int Fractional bits. verilog_lines : int Lines of generated Verilog.
Returns¶
str Markdown compilation summary.
Module compiler.intelligence.compliance_matrix¶
Class ComplianceEntry¶
Single compliance requirement mapping.
Attributes¶
req_id : str
Requirement identifier.
standard : str
Safety standard name.
description : str
Requirement description.
verification : str
How it is verified.
status : str
"covered", "partial", or "gap".
artefact : str
File or test that provides evidence.
Function generate_compliance_matrix(module_name)¶
Generate safety compliance matrix for certification.
Maps DO-254 / IEC 61508 / ISO 26262 requirements to SC-NeuroCore verification artefacts.
Parameters¶
module_name : str Module under certification. standards : list[str], optional Standards to cover. Default: all three. has_tmr : bool TMR wrapper is present. has_checksum : bool Model checksum is embedded. has_sva : bool SVA assertions are generated. has_provenance : bool Provenance chain exists.
Returns¶
list[ComplianceEntry] Compliance matrix entries.
Function format_compliance_report(entries)¶
Format compliance matrix as markdown.
Module compiler.intelligence.cxl_coherence¶
Class CXLMapping¶
CXL.mem Type-3 mapping for neuron state.
Attributes¶
device_count : int
Number of CXL memory devices.
state_device_ids : list[int]
Devices hosting neuron state.
weight_device_ids : list[int]
Devices hosting synaptic weights.
total_capacity_gb : float
Total CXL memory capacity.
host_bandwidth_gbps : float
Required host→CXL bandwidth.
coherence_protocol : str
CXL protocol used ("CXL.mem" or "CXL.cache").
Function advise_cxl_mapping(neuron_count, synapse_count)¶
Advise on CXL.mem Type-3 device mapping for neuron state.
Plans the distribution of neuron state and synaptic weights across CXL 3.0 Type-3 memory expander devices.
Parameters¶
neuron_count : int
Total neurons.
synapse_count : int
Total synaptic connections.
data_width : int
Bits per value.
device_capacity_gb : float
Capacity per CXL device (GB).
max_devices : int
Maximum CXL devices available.
access_pattern : str
"streaming" (sequential) or "random" (scattered).
Returns¶
CXLMapping
Module compiler.intelligence.debug_probes¶
Class DebugProbeSpec¶
Auto-generated debug probe specification.
Attributes¶
probe_type : str
"ila" (Xilinx) or "signaltap" (Intel).
signals : list[str]
Probed signal names.
depth : int
Capture depth.
tcl_commands : str
Vendor-specific TCL to insert probes.
Function insert_debug_probes(module_name, equations)¶
Auto-insert ILA/SignalTap debug probes.
Parameters¶
module_name : str
Module name.
equations : dict[str, str]
ODE equations (state variables become probed signals).
vendor : str
"xilinx" or "intel".
depth : int
Capture depth in samples.
Returns¶
DebugProbeSpec Probe specification with TCL commands.
Module compiler.intelligence.dispatch_planner¶
Class DispatchPlan¶
Multi-backend SNN dispatch plan.
Attributes¶
backends : dict[str, list[str]] Backend name → list of assigned state variables. sync_barriers : list[str] Synchronisation point descriptions. total_neurons_per_backend : dict[str, int] Neuron count per backend. estimated_speedup : float Estimated speedup vs single-backend.
Function plan_heterogeneous_dispatch(equations, backends)¶
Plan multi-backend dispatch for an SNN model.
Splits ODE variables across heterogeneous backends based on compute characteristics (fast dynamics → FPGA, slow → MCU, learning → GPU).
Parameters¶
equations : dict[str, str] ODE equations. backends : list[str] Available backend targets. neuron_count : int Total neurons. time_constants : dict[str, float], optional Time constants per variable.
Returns¶
DispatchPlan Multi-backend assignment.
Module compiler.intelligence.drift_compensation¶
Class DriftCompensator¶
Analog drift compensation parameters.
Attributes¶
refresh_interval_ms : float
How often to re-calibrate (ms).
drift_rate_per_day : float
Expected weight drift per day.
compensation_method : str
"periodic_refresh", "adaptive", or "ecc".
verilog_controller : str
Generated Verilog refresh controller.
Function generate_drift_compensator(module_name)¶
Generate analog drift compensation controller.
Module compiler.intelligence.dvfs_controller¶
Function generate_dvfs_controller(module_name)¶
Generate a Verilog DVFS controller FSM.
Module compiler.intelligence.dvs_bridge¶
Function generate_dvs_aer_bridge(module_name)¶
Generate a DVS (Dynamic Vision Sensor) to AER bridge in Verilog.
Converts Prophesee / Metavision / Sony IMX636 event packets into the SC-NeuroCore AER address-event protocol for zero-copy sensor- to-spike-network interfacing on FPGA.
Parameters¶
module_name : str Output module name. addr_width : int Pixel address width (covers X*Y event space). polarity_bit : bool Include ON/OFF polarity in the event word. timestamp_width : int Timestamp field width in bits. fifo_depth : int Input event FIFO depth (power of 2).
Returns¶
str Synthesisable Verilog module.
Module compiler.intelligence.energy_harvesting¶
Class EnergySchedule¶
Energy-aware neuron update schedule.
Attributes¶
total_neurons : int Total neurons. energy_budget_uj : float Energy budget per epoch (µJ). neurons_per_epoch : int Neurons updatable within budget. update_order : list[int] Priority-ordered neuron indices. epoch_duration_ms : float Epoch duration. duty_cycle : float Fraction of neurons updated per epoch.
Class EnergyHarvestBudget¶
Energy harvesting feasibility analysis.
Attributes¶
harvester_power_uw : float design_power_uw : float energy_positive : bool recommended_duty_cycle : float margin_pct : float
Function generate_energy_schedule(neuron_count)¶
Generate energy-budget-aware neuron update schedule.
Function model_energy_harvest(design_power_uw)¶
Model whether an energy harvester can sustain the neural workload.
Module compiler.intelligence.equivalence_sketch¶
Class EquivalenceSketch¶
Formal equivalence proof skeleton between ODE and RTL.
Attributes¶
module_name : str Module under verification. equations : dict[str, str] Source ODE equations. assertions : list[str] SVA assertion strings for equivalence checking. proof_steps : list[str] Human-readable proof argument steps. quantisation_bound : float Maximum quantisation error bound.
Function generate_equivalence_sketch(module_name, equations)¶
Generate a formal equivalence proof sketch for ODE→RTL translation.
Produces a structured argument that the compiled Verilog computes the same function as the source ODE within quantisation error.
Parameters¶
module_name : str Module name. equations : dict[str, str] ODE equations. data_width : int Fixed-point total width. fraction : int Fractional bits.
Returns¶
EquivalenceSketch Proof skeleton with SVA assertions.
Module compiler.intelligence.fault_injection¶
Class FaultCampaignResult¶
Fault injection campaign result.
Attributes¶
total_injections : int sdc_count : int sdc_rate : float critical_bits : list[int] recommended_tmr_bits : list[int]
Function run_fault_campaign(equations, data_width)¶
Run a fault injection campaign on the state register.
Module compiler.intelligence.fault_tree¶
Class FaultTree¶
Fault Tree Analysis for safety certification.
Attributes¶
top_event : str Top-level failure event. gates : list[dict] Logic gates (AND/OR). basic_events : list[dict] Leaf failure events with rates. mcs : list[list[str]] Minimal cut sets.
Function generate_fault_tree(module_name, equations)¶
Generate FTA/FMEA for DO-254 Level A certification.
Module compiler.intelligence.hil_calibration¶
Class HILCalibration¶
Hardware-in-the-loop calibration protocol.
Attributes¶
protocol_steps : list[str] num_parameters : int sweep_ranges : dict[str, tuple[float, float]]
Function generate_hil_calibration(module_name, equations)¶
Generate hardware-in-the-loop calibration protocol.
Module compiler.intelligence.hls_export¶
Function generate_hls_cpp(module_name, equations)¶
Translate compiled neuron equations to Vitis/Catapult HLS C++.
Generates a synthesisable ap_fixed C++ function with #pragma HLS
directives for Xilinx Vitis HLS or Siemens Catapult. Each equation is a
derivative that is Euler-integrated (<var>_next = <var> + dt * d<var>);
the first state variable is treated as the membrane potential and reset by
subtracting the threshold when it spikes. Free identifiers in the equations
become function inputs so the generated unit is self-contained.
Parameters¶
module_name : str
Function/module name.
equations : dict
Mapping state_var -> derivative expression (Python syntax).
data_width : int
Fixed-point total width.
fraction : int
Fractional bits.
hls_tool : str
"vitis" or "catapult".
dt : float
Euler integration timestep.
threshold : float
Membrane spike threshold.
Returns¶
str Complete HLS C++ source file.
Module compiler.intelligence.holographic_interconnect¶
Class HolographicRouter¶
Holographic interconnect router specification.
Attributes¶
slm_grid_size : tuple[int, int] diffraction_limit_nm : float optical_fanout_per_beam : int phase_array_complexity : float
Function route_holographic_interconnects(num_neurons, connections)¶
Route 3D optical holographic interconnects using SLM phase arrays.
Module compiler.intelligence.ip_obfuscation¶
Class ObfuscationResult¶
IP obfuscation report.
Attributes¶
techniques_applied : list[str] key_bits : int original_signals : int obfuscated_signals : int
Function obfuscate_ip(module_name, equations)¶
Apply logic locking and structural obfuscation for IP protection.
Module compiler.intelligence.learning_export¶
Class OnChipLearningParams¶
Parameters for on-chip STDP / reward-modulated plasticity.
Attributes¶
learning_rule : str
"stdp", "rstdp" (reward-modulated), or "triplet".
tau_plus_ms : float
Pre→post time constant (ms).
tau_minus_ms : float
Post→pre time constant (ms).
a_plus : float
Potentiation amplitude.
a_minus : float
Depression amplitude.
w_max : float
Maximum synaptic weight.
w_min : float
Minimum synaptic weight.
reward_tau_ms : float
Reward signal time constant (ms), for RSTDP.
target_platform : str
Target neuromorphic platform.
Function generate_learning_params()¶
Generate on-chip learning parameters for neuromorphic targets.
Creates calibration parameters for platforms with in-situ plasticity (BrainChip Akida 2, BrainScaleS-2, SpiNNaker 2).
Parameters¶
learning_rule : str
"stdp" (spike-timing), "rstdp" (reward-modulated),
or "triplet" (triplet-based STDP).
tau_plus_ms : float
LTP time constant.
tau_minus_ms : float
LTD time constant.
a_plus : float
Potentiation amplitude.
a_minus : float
Depression amplitude.
w_max : float
Weight ceiling.
w_min : float
Weight floor.
reward_tau_ms : float
Reward eligibility trace time constant.
target : str
Target platform name.
Returns¶
OnChipLearningParams Complete learning parameter set.
Function export_learning_config(params)¶
Export on-chip learning parameters as a configuration file.
Parameters¶
params : OnChipLearningParams
Learning parameters from generate_learning_params().
output_format : str
"json" or "yaml".
Returns¶
str Configuration file content.
Module compiler.intelligence.license_compliance¶
Class LicenseCheck¶
IP core license compatibility result.
Attributes¶
compatible : bool conflicts : list[str] licenses_found : list[str]
Function check_license_compliance(project_license, dependencies)¶
Verify IP core licensing compatibility.
Module compiler.intelligence.memory_map¶
Class MemoryMap¶
Address decoder specification for neuron arrays.
Attributes¶
base_address : int Base address of neuron array. entries : list[dict[str, int | str]] Address map entries. total_bytes : int Total address space consumed. decoder_verilog : str Generated address decoder Verilog.
Function generate_memory_map(module_name, equations)¶
Generate address decoder for multi-neuron SoC arrays.
Parameters¶
module_name : str Module name. equations : dict[str, str] ODE equations. num_neurons : int Number of neuron instances. data_width : int Register width in bits. base_address : int Base address.
Returns¶
MemoryMap
Module compiler.intelligence.model_complexity¶
Class ModelComplexity¶
Model compute-profile classification.
Attributes¶
classification : str
"compute_bound", "memory_bound", or "comm_bound".
compute_ops : int
Total arithmetic operations.
memory_vars : int
State variables.
comm_ratio : float
Inter-variable coupling ratio.
recommended_paradigm : str
Best platform class.
Function classify_model_complexity(equations)¶
Classify a model's compute profile.
Module compiler.intelligence.morphology_synth¶
Class Morphology¶
Interconnect topology morphology.
Attributes¶
topology : str
"Hypercube", "3D Torus", or "2D Mesh".
bisection_bandwidth_gbps : float
routing_latency_ns : float
dimensions : int
Function synthesize_morphology(equations, max_generations)¶
Auto-synthesizer for optimal interconnect topologies.
Module compiler.intelligence.multi_die_floorplan¶
Class FloorplanResult¶
Multi-die/chiplet floorplan assignment.
Attributes¶
die_assignment : dict[str, int] Block name → die index. die_utilization : dict[int, float] Die index → utilization (0-1). total_dies : int
Function plan_multi_die_floorplan(blocks)¶
Assign neuron blocks to chiplet/die positions.
Uses first-fit-decreasing bin packing.
Parameters¶
blocks : dict[str, int] Block name → neuron count. die_capacity : int Max neurons per die. num_dies : int Available dies.
Returns¶
FloorplanResult
Module compiler.intelligence.mxfp_encoding¶
Class MXFPConfig¶
Microsoft Microscaling (MX) floating-point format.
Based on OCP Microscaling Formats Specification v1.0 (2024).
Attributes¶
element_bits : int Bits per element (4, 6, or 8). exp_bits : int Exponent bits per element. mantissa_bits : int Mantissa bits per element (including implicit 1). block_size : int Elements per shared-exponent block. shared_exp_bits : int Shared exponent width (typically 8).
- label()
- Human-readable format label.
- bits_per_block()
- Total bits for one block including shared exponent.
Function mxfp_encode_block(values, config)¶
Encode a block of floats to MXFP format.
Parameters¶
values : list[float] Block of float values (len must equal config.block_size). config : MXFPConfig MXFP format configuration.
Returns¶
tuple[int, list[int]] (shared_exponent, list_of_encoded_elements).
Function mxfp_decode_block(shared_exp, elements, config)¶
Decode a block of MXFP elements to floats.
Parameters¶
shared_exp : int Shared exponent. elements : list[int] Encoded element integers. config : MXFPConfig MXFP format configuration.
Returns¶
list[float] Decoded float values.
Module compiler.intelligence.network_optimizer¶
Class TopologyPlan¶
Multi-chip network topology optimisation result.
Attributes¶
chip_assignment : dict[int, int] Neuron index → chip index. inter_chip_spikes : int Estimated inter-chip spikes per timestep. intra_chip_spikes : int Estimated intra-chip spikes per timestep. bandwidth_reduction : float Reduction vs naive assignment. num_chips : int Total chips used.
Function optimize_network_topology(adjacency)¶
Optimize SNN partitioning across multiple chips.
Minimises inter-chip spike communication by grouping heavily-connected neurons onto the same chip.
Parameters¶
adjacency : dict[int, list[int]] Neuron connectivity: source → list of targets. num_chips : int Number of available chips. neurons_per_chip : int, optional Max neurons per chip. Default: ceil(N / num_chips).
Returns¶
TopologyPlan Optimised chip assignment.
Module compiler.intelligence.nir_import¶
Class NIRGraph¶
Imported dict-form NIR graph representation.
Attributes¶
nodes : dict[str, dict]
Node name → its raw input parameters.
edges : list[tuple[str, str]]
Directed edges (source, target).
equations : dict[str, str]
Node name → the membrane (dv/dt) right-hand side, with parameters
substituted to concrete values. Kept as a flat str per node for
back-compatibility and stability analysis.
framework : str
Source framework label.
node_types : dict[str, str]
Node name → the canonical template type it resolved to.
state_equations : dict[str, dict[str, str]]
Node name → {state_variable: right-hand side} for the full (possibly
multi-compartment) model, so nothing is lost for multi-state neurons.
thresholds : dict[str, str | None]
Node name → its spike threshold expression (None if the type has no
threshold, e.g. leaky/plain integrators).
resets : dict[str, str | None]
Node name → its reset rule expression (None if the type has none).
parameters : dict[str, dict[str, float]]
Node name → the resolved numeric parameters (template defaults overlaid
with the node's own values).
defaulted_parameters : dict[str, tuple[str, ...]]
Node name → template parameters the node did not give, which took the
template's default value.
unused_parameters : dict[str, tuple[str, ...]]
Node name → parameters the node gave that its template does not use and
that were therefore not applied.
Function import_nir_graph(nir_data)¶
Import a dict-form Neuromorphic Intermediate Representation graph.
Each node's type selects a canonical ODE template (shared with the FPGA
back-end); the node's parameters overlay the template defaults and are
substituted into concrete equations, thresholds and reset rules. Defaulted
and unused parameters are reported on the result.
Parameters¶
nir_data : dict
Graph as {"nodes": {name: {"type": ..., <params>}}, "edges": [...]}.
Every node needs a type.
framework : str
Source framework label recorded on the result.
Returns¶
NIRGraph
Imported graph with per-node equations, state equations, thresholds,
reset rules, resolved parameters, and the defaulted and unused
parameters of each node. For the authoritative typed import use
:func:sc_neurocore.nir_bridge.from_nir.
Raises¶
ValueError A node has no type or an unsupported one, or an edge is not a pair of node names of this graph.
Module compiler.intelligence.ode_stability¶
Class StabilityResult¶
ODE discretization stability analysis.
Attributes¶
stable : bool True if discretization is stable. max_eigenvalue : float Largest eigenvalue magnitude. critical_dt : float Maximum stable timestep. method : str Analysis method used.
Function verify_ode_stability(equations)¶
Verify numerical stability of discretized ODE system.
Uses eigenvalue analysis of the linearized system.
Parameters¶
equations : dict[str, str] ODE equations. dt : float Timestep. time_constants : dict[str, float], optional Time constants per variable.
Returns¶
StabilityResult
Module compiler.intelligence.omni_paradigm¶
Class OmniDispatchMap¶
Mapping of variables to heterogeneous computing backends.
Attributes¶
cmos_variables : list[str] Standard digital/SRAM variables. thermodynamic_variables : list[str] Stochastic/noise-driven variables (RRAM, PCM). optical_variables : list[str] High-bandwidth weight/sum variables (Photonic). quantum_variables : list[str] Entangled/superposition variables (Superconducting).
Function dispatch_omni_paradigm(equations)¶
Dispatch ODE variables across heterogeneous computing paradigms.
Module compiler.intelligence.optical_encoding¶
Class MZIWeightEncoding¶
Encoded weights for a Mach-Zehnder interferometer photonic array.
Attributes¶
phases_theta : list[list[float]] Phase-shift θ values (radians). phases_phi : list[list[float]] Phase-shift φ values (radians). transmission : list[list[float]] Effective transmission coefficients. mesh_size : int Number of MZI columns.
Function encode_mzi_weights(weights)¶
Encode a weight matrix as MZI phase-shift parameters.
Function generate_mzi_config(encoding)¶
Generate a photonic chip configuration file from MZI weights.
Module compiler.intelligence.pareto_explorer¶
Class ParetoPoint¶
A single Pareto-optimal design point.
Attributes¶
config : dict power_mw : float area_luts : int latency_ns : float
Function explore_pareto(equations)¶
Explore power/area/latency Pareto frontier.
Module compiler.intelligence.pim_layout¶
Class PIMLayout¶
Memory layout plan for Processing-in-Memory targets.
Attributes¶
bank_count : int Number of memory banks used. neurons_per_bank : int Neurons assigned per bank. weights_per_bank : int Weight entries per bank. bank_utilisation : float Fraction of bank capacity used (0.0–1.0). parallel_factor : int Number of banks that can compute in parallel. layout_map : dict[str, list[int]] Mapping of data regions to bank IDs.
Function plan_pim_layout(neuron_count, synapse_count)¶
Plan data placement across PIM memory banks.
Distributes neuron state and synaptic weights across memory banks.
Parameters¶
neuron_count : int Total neurons in the network. synapse_count : int Total synaptic connections. data_width : int Bits per value. bank_size_kb : int Capacity of each memory bank in KB. num_banks : int Number of available memory banks. target : str Target platform name.
Returns¶
PIMLayout
Module compiler.intelligence.pipeline_wrapper¶
Function generate_pipeline_wrapper(module_name, equations)¶
Generate a pipelined wrapper that inserts register stages.
Auto-computes the critical path depth and required pipeline stages.
Parameters¶
module_name : str Inner neuron module name. equations : dict[str, str] ODE equations. data_width : int Data width. target : str Target platform name. stages : int, optional Override pipeline stages.
Returns¶
str Synthesisable Verilog pipeline wrapper.
Module compiler.intelligence.portability_scorer¶
Class PortabilityScore¶
Cross-platform portability assessment.
Attributes¶
score : float Portability score 0-100. compatible_profiles : int Number of compatible profiles. total_profiles : int Total profiles checked. blockers : list[str] Portability blockers.
Function score_portability(equations)¶
Score how portable a model is across all profiles.
Module compiler.intelligence.posit_arithmetic¶
Class PositConfig¶
Posit number format configuration.
Attributes¶
nbits : int Total bit width (8 or 16). es : int Exponent field size (0, 1, or 2).
- useed()
- The useed value: 2^(2^es).
- max_value()
- Maximum finite value.
- min_positive()
- Smallest positive value.
Function posit_encode(value, config)¶
Encode a float to posit integer representation.
Parameters¶
value : float Value to encode. config : PositConfig Posit format.
Returns¶
int Posit-encoded integer (nbits wide).
Function posit_decode(bits, config)¶
Decode a posit integer to float.
Parameters¶
bits : int Posit-encoded integer. config : PositConfig Posit format.
Returns¶
float Decoded value.
Module compiler.intelligence.power_domain_wrapper¶
Function generate_power_domain_wrapper(module_name)¶
Generate a clock/power gating wrapper for always-on edge deployment.
Creates a wrapper module with ICG and power-down state retention.
Parameters¶
module_name : str
Inner neuron module name.
data_width : int
Data width.
state_vars : list[str], optional
State variables to retain. Defaults to ["v"].
always_on_signals : list[str], optional
Signals kept in the always-on domain. Defaults to ["spike_out"].
wakeup_cycles : int
Clock cycles required to exit power-down.
Returns¶
str Synthesisable Verilog power domain wrapper.
Module compiler.intelligence.power_intent¶
Function generate_power_intent(module_name)¶
Generate IEEE 1801 UPF power intent for neuron arrays.
Module compiler.intelligence.power_state_machine¶
Function generate_power_state_machine(module_name)¶
Generate sleep/wake/hibernate FSM for ultra-low-power.
Module compiler.intelligence.pqc_protection¶
Class PQCProtection¶
Post-quantum cryptographic IP protection result.
Attributes¶
algorithm : str signature_hex : str key_size_bits : int quantum_safe : bool
Function protect_ip_pqc(module_name, equations)¶
Apply post-quantum cryptographic protection to IP core.
Module compiler.intelligence.provenance_chain¶
Class ProvenanceRecord¶
Cryptographic audit trail entry.
Attributes¶
stage : str Pipeline stage name. input_hash : str SHA-256 of input artefact. output_hash : str SHA-256 of output artefact. timestamp : str ISO 8601 timestamp. parameters : dict Compilation parameters used.
Function generate_provenance_chain(module_name, equations, verilog_source)¶
Generate a cryptographic provenance chain for compilation.
Function format_provenance_json(chain)¶
Format provenance chain as JSON manifest.
Module compiler.intelligence.reconfig_planner¶
Class ReconfigPartition¶
Partial reconfiguration partition plan.
Attributes¶
partitions : list[dict[str, list[str]]] Each partition maps region name → assigned variables. schedule : list[str] Time-ordered bitstream swap schedule. total_regions : int Number of reconfigurable regions. bitstream_count : int Total partial bitstreams needed.
Function plan_partial_reconfiguration(equations)¶
Plan FPGA partial reconfiguration for SNN time-multiplexing.
Splits neuron equations across reconfigurable regions and generates a swap schedule.
Parameters¶
equations : dict[str, str] ODE equations. max_regions : int Maximum reconfigurable regions. time_slots : int Number of time-multiplexed slots.
Returns¶
ReconfigPartition Partition plan with schedule.
Module compiler.intelligence.regression_watchdog¶
Class RegressionCheck¶
Compilation regression check result.
Attributes¶
metric : str baseline : float current : float delta_pct : float regression : bool
Function check_regression(baseline, current)¶
Detect performance regressions between compilations.
Module compiler.intelligence.reversible_logic¶
Class ReversibleNetlist¶
Reversible logic netlist metrics.
Attributes¶
toffoli_gates : int fredkin_gates : int ancilla_bits : int landauer_dissipation_kt : float
Function synthesize_reversible_logic(equations, bits)¶
Synthesize reversible (lossless) logic for zero-energy computation.
Module compiler.intelligence.sbom_gen¶
Class SBOM¶
Software/Hardware Bill of Materials.
Attributes¶
format : str components : list[dict] total_components : int
Function generate_sbom(module_name, profile_name)¶
Generate SBOM/HBOM for IP core compliance.
Module compiler.intelligence.seu_scrub_scheduler¶
Class ScrubSchedule¶
Configuration memory scrubbing schedule.
Attributes¶
interval_ms : float strategy : str frames_per_cycle : int expected_seu_rate : float
Function schedule_seu_scrubbing(config_bits)¶
Generate scrubbing schedule for space-grade configuration memory.
Module compiler.intelligence.shadow_twin¶
Function generate_digital_twin(module_name, equations, profile_name)¶
Generate a Python digital twin that mirrors deployed hardware.
Module compiler.intelligence.side_channel_lint¶
Class SideChannelFinding¶
Side-channel leakage finding.
Attributes¶
signal : str
Signal name.
risk_level : str
"high", "medium", or "low".
category : str
"timing" or "power".
description : str
Explanation.
recommendation : str
Mitigation suggestion.
Function lint_side_channels(equations)¶
Analyse equations for power/timing side-channel vulnerabilities.
Module compiler.intelligence.storage_recommendation¶
Class StorageRecommendation¶
Storage recommendation for neuron array state.
Attributes¶
strategy : str
"registers", "bram", or "uram".
neuron_count : int
Number of neurons in the array.
total_bits : int
Total state bits.
bram_18k_used : int
Estimated 18Kb BRAM tiles consumed.
bram_36k_used : int
Estimated 36Kb BRAM tiles consumed.
uram_used : int
Estimated URAM tiles consumed (UltraScale+ only).
reason : str
Human-readable explanation.
Function storage_recommendation(neuron_count, state_bits_per_neuron)¶
Determine optimal storage strategy for a neuron array.
Decides between registers (small), BRAM (medium), and URAM (large) based on total state bits and target capabilities.
Parameters¶
neuron_count : int Number of neurons in the array. state_bits_per_neuron : int State bits per neuron. has_uram : bool True if the target has UltraRAM. register_threshold : int Max neurons for register-based storage. uram_threshold : int Min neurons for URAM migration.
Returns¶
StorageRecommendation Optimal storage strategy with resource estimates.
Module compiler.intelligence.supply_chain_risk¶
Class SupplyChainRisk¶
Supply chain risk assessment for a hardware profile.
Attributes¶
profile_name : str Assessed profile. risk_score : float Risk score 0-100 (higher = riskier). risk_factors : list[str] Individual risk factor descriptions. alternatives : list[str] Suggested alternative profiles. export_control : str Export control classification.
Function score_supply_chain_risk(profile_name)¶
Assess supply chain risk for a hardware profile.
Module compiler.intelligence.target_comparison¶
Class TargetComparison¶
Compilation comparison for one target.
Attributes¶
target : str Platform name. data_width : int Selected data width. fraction : int Fractional bits. overflow : str Overflow mode. dsp_block : str DSP block type. max_freq_mhz : int | None Maximum frequency. estimated_luts : int Estimated LUT usage. estimated_dsps : int Estimated DSP usage. pipeline_stages : int Required pipeline stages. critical_path_depth : int DSP chain depth.
Function compare_targets(equations, targets)¶
Compare compilation results across multiple hardware targets.
Function format_comparison_report(results)¶
Format a multi-target comparison as a markdown table.
Module compiler.intelligence.target_recommender¶
Class TargetRecommendation¶
Ranked hardware target recommendation.
Attributes¶
profile_name : str Recommended profile. score : float Fitness score (0-100). rationale : str Why this target is recommended.
Function recommend_target(equations)¶
Recommend optimal hardware targets for a neuron model.
Given ODE equations and constraints, ranks all registered profiles and returns the top N recommendations.
Parameters¶
equations : dict[str, str] ODE equations. max_power_mw : float, optional Maximum power budget. min_freq_mhz : float, optional Minimum clock frequency. max_data_width : int, optional Maximum data width. require_class : str, optional Required platform class. top_n : int Number of recommendations.
Returns¶
list[TargetRecommendation] Ranked recommendations.
Module compiler.intelligence.tcl_gen¶
Function generate_tcl_project(module_name)¶
Generate FPGA project TCL script.
Parameters¶
module_name : str
Top-level module name.
tool : str
"vivado" or "quartus".
part : str
Target FPGA part number.
verilog_files : list, optional
Verilog source files.
constraint_file : str, optional
Constraint file (XDC/SDC).
Returns¶
str Complete TCL script.
Module compiler.intelligence.telemetry_ingestion¶
Class TelemetryResult¶
Hardware telemetry comparison result.
Attributes¶
samples : int max_drift : float mean_drift : float alerts : list[str] healthy : bool
Function ingest_telemetry(telemetry_data, twin_states)¶
Ingest hardware telemetry and compare against digital twin.
Module compiler.intelligence.testbench_gen¶
Function generate_testbench(module_name, equations)¶
Generate verification testbench for compiled neuron.
Module compiler.intelligence.thermal_analysis¶
Class ThermalEstimate¶
Thermal analysis result for a compiled neuron.
Attributes¶
power_mw : float
Estimated total power in milliwatts.
delta_t_c : float
Estimated temperature rise in °C.
junction_temp_c : float
Estimated junction temperature.
hotspot_delta_t_c : float
Local temperature rise from concentrated DSP power.
derated_freq_mhz : float
Frequency after thermal derating.
thermal_safe : bool
True if junction temp is within limits.
hotspot_risk : str
"none", "low", "medium", "high".
Class ThermalEnvelopeEstimate¶
Junction temperature estimate.
Attributes¶
power_mw : float
Estimated power dissipation (mW).
theta_ja : float
Junction-to-ambient thermal resistance (°C/W).
t_ambient : float
Ambient temperature (°C).
t_junction : float
Estimated junction temperature (°C).
thermal_margin : float
Margin to max T_j (°C).
pass_fail : str
"PASS" or "FAIL".
Function thermal_analysis(estimated_power_mw, target_freq_mhz)¶
Estimate thermal impact and frequency derating.
Function estimate_thermal_envelope()¶
Predict junction temperature from power dissipation.
Function generate_thermal_constraints(module_name, analysis)¶
Generate XDC constraints for thermal-aware DSP placement.
Module compiler.intelligence.timescale_partitioner¶
Class TimescalePartition¶
Partitioned ODE system by timescale.
Attributes¶
fast_equations : dict[str, str] Fast dynamics (membrane, spikes). slow_equations : dict[str, str] Slow dynamics (adaptation, homeostasis). fast_clock_div : int Clock divider for fast domain (1 = full speed). slow_clock_div : int Clock divider for slow domain. cdc_signals : list[str] Signals requiring clock domain crossing.
Function partition_timescales(equations, time_constants)¶
Partition ODE equations by timescale for multi-clock execution.
Identifies fast vs slow dynamics and assigns them to different clock domains, inserting CDC synchronisers at domain boundaries.
Parameters¶
equations : dict[str, str] ODE equations. time_constants : dict[str, float], optional Known time constants per variable (ms). If None, estimated from equation structure. threshold_ratio : float Ratio above which a variable is considered "slow".
Returns¶
TimescalePartition Partitioned system with clock assignments.
Module compiler.intelligence.timing_closure¶
Class TimingReport¶
Static timing analysis report.
Attributes¶
critical_path : list[str] critical_delay_ns : float target_period_ns : float slack_ns : float timing_met : bool recommendations : list[str]
Function verify_timing_closure(equations)¶
Perform static timing analysis on the dataflow graph.
Module compiler.intelligence.tmr_wrapper¶
Function generate_tmr_wrapper(module_name)¶
Generate a Triple Modular Redundancy wrapper for any neuron module.
Instantiates three copies of the target module and a majority voter to mask Single Event Upsets (SEUs).
Parameters¶
module_name : str
Name of the inner neuron module to wrap.
data_width : int
Data width of the inner module.
state_vars : list[str], optional
State variable names for output voting. Defaults to ["v"].
voter : str
Voter type: "majority" (2-of-3) or "median" (middle value).
Returns¶
str Synthesisable Verilog TMR wrapper module.
Module compiler.intelligence.trojan_lint¶
Class TrojanLintResult¶
Hardware trojan lint analysis result.
Attributes¶
suspicious_paths : list[str] risk_level : str total_checks : int
Function lint_hardware_trojans(equations)¶
Detect suspicious combinational paths that could hide trojans.
Module compiler.intelligence.ucie_partitioning¶
Class UCIePartition¶
Partitioning plan for a neuron array across chiplet tiles.
Attributes¶
tile_count : int Number of chiplet tiles used. neurons_per_tile : int Neurons assigned per tile. inter_tile_spikes : int Estimated spikes crossing tile boundaries per timestep. die_to_die_bandwidth_gbps : float Required UCIe bandwidth (Gbps). latency_penalty_ns : float Additional latency from die-to-die communication. partition_map : dict[int, list[int]] Tile ID → list of neuron indices.
Function advise_ucie_partition(neuron_count, connectivity)¶
Advise on neuron array partitioning across chiplet tiles.
Analyses a neuron array's connectivity to estimate inter-tile spike traffic and UCIe bandwidth requirements.
Parameters¶
neuron_count : int Total neurons in the network. connectivity : float Connection probability between any two neurons (0.0–1.0). tile_count : int Number of chiplet tiles. spike_rate_hz : float Average firing rate per neuron (Hz). timestep_us : float Simulation timestep (µs). ucie_lane_gbps : float UCIe lane bandwidth (Gbps per lane). ucie_latency_ns : float UCIe die-to-die latency (ns).
Returns¶
UCIePartition
Module compiler.intelligence.ucie_protocol_mapper¶
Class UCIeMapping¶
UCIe die-to-die protocol mapping result.
Attributes¶
lanes : dict[str, int] protocol_version : str total_bandwidth_gbps : float
Function map_ucie_protocol(blocks)¶
Map neuron array blocks to UCIe die-to-die protocol lanes.
Parameters¶
blocks : dict[str, int] Block name → data width in bits per cycle. lane_bandwidth_gbps : float Bandwidth per UCIe lane. protocol_version : str UCIe protocol version.
Returns¶
UCIeMapping
Module compiler.intelligence.vhdl_emitter¶
Function verilog_to_vhdl_wrapper(module_name)¶
Generate a VHDL-2008 entity/architecture wrapper for a Verilog module.
This produces a VHDL entity that matches the Verilog module's port list, enabling mixed-language simulation and synthesis (Vivado, Questa, GHDL). The VHDL wrapper instantiates the Verilog module as a component.
Parameters¶
module_name : str Verilog module name. data_width : int Fixed-point data width. signed : bool Whether ports use signed types.
Returns¶
str VHDL-2008 source code.
Module compiler.intelligence.watermark¶
Class WatermarkResult¶
Netlist watermark embedding result.
Attributes¶
watermark_hash : str embedding_method : str overhead_percent : float verifiable : bool
Function embed_watermark(module_name, equations)¶
Embed a verifiable watermark into the compiled netlist.
Module compiler.intelligence.weight_noise¶
Class WeightNoiseProfile¶
Device-variation noise model for analog/memristive targets.
Attributes¶
noise_model : str
"gaussian", "uniform", or "lognormal".
sigma : float
Standard deviation of noise (fraction of weight range).
cycle_drift : float
Weight drift per program/erase cycle (fraction).
retention_loss_per_day : float
Daily retention loss (fraction).
target_platform : str
Target platform.
Function inject_weight_noise(weights)¶
Inject device-variation noise into a weight matrix.
Simulates manufacturing variations and read noise in analog compute-in-memory (Mythic, IBM PCM) and memristive crossbar (Rain AI) targets. Enables robustness validation before tapeout.
Parameters¶
weights : list[list[float | int]]
Original weight matrix.
noise_model : str
"gaussian", "uniform", or "lognormal".
sigma : float
Noise magnitude (fraction of weight range).
seed : int, optional
Random seed for reproducibility.
Returns¶
list[list[float]] Weight matrix with injected noise.
Function create_noise_profile()¶
Create a device-variation noise profile for analog targets.
Parameters¶
noise_model : str Noise distribution type. sigma : float Read noise standard deviation. cycle_drift : float Weight drift per program/erase cycle. retention_loss_per_day : float Daily state retention loss. target : str Target platform.
Returns¶
WeightNoiseProfile Complete noise characterisation.
Module compiler.intelligence.weight_rom¶
Function generate_weight_rom(weights, module_name)¶
Generate a weight ROM for synaptic connections.
Produces either a Verilog ROM module or a Xilinx .coe / Intel
.mif memory initialisation file for BRAM-based weight storage.
Parameters¶
weights : list[list[int]]
2D weight matrix [src_neuron][dst_neuron] in Q-format integers.
module_name : str
ROM module name.
data_width : int
Weight bit width.
output_format : str
"verilog" (synthesisable ROM), "coe" (Xilinx), "mif" (Intel).
Returns¶
str Weight ROM in the specified format.
Module compiler.intelligence.wetware_mea¶
Class MEAMapping¶
Mapping of neuron populations to MEA electrodes.
Attributes¶
electrode_count : int stimulation_freq_hz : float voltage_amplitude_mv : float spatial_density : str
Function map_wetware_mea(populations, connectivity)¶
Map neuron populations to wetware Multi-Electrode Array (MEA) sites.
Module compiler.ir_type_checker¶
Class SignalType¶
Signal domains accepted by the stochastic IR compatibility checker.
Class IRNode¶
A typed node in the Stochastic IR graph.
Class IREdge¶
Connection record from one typed IR node port to another.
Class IRTypeError¶
A type mismatch found during checking.
Function types_compatible(src, dst)¶
Check if src can connect to dst without explicit conversion.
Function check_ir_types(nodes, edges)¶
Type-check an IR graph and return all type errors.
Parameters¶
nodes : dict mapping node name → IRNode edges : list of IREdge connections
Returns¶
list of IRTypeError (empty if all types check out)
Module compiler.layer_precision¶
Class LayerPrecision¶
Bitstream length assignment for one layer.
Parameters¶
layer_index: Zero-based layer index in the adaptive-precision plan. name: Non-empty layer name used in reports and manifests. bitstream_length: Positive stochastic-computing bitstream length. Layer-level planners round this value to a power of two. error_bound: Finite non-negative per-layer stochastic error bound. sensitivity: Finite non-negative sensitivity score used for budget allocation.
- post_init()
- Validate adaptive-precision row invariants.
- to_dict()
- Return a JSON-serializable adaptive-precision manifest row.
Module compiler.length_planner¶
Function assign_lengths(layer_weights, layer_names, total_budget, min_length, max_length, target_error, method)¶
Assign per-layer bitstream lengths under a target error budget.
Parameters¶
layer_weights:
One- or two-dimensional finite weight tensors, one tensor per layer.
One-dimensional tensors are treated as single-output layers.
layer_names:
Optional non-empty layer names. When provided, the list length must match
layer_weights exactly.
total_budget:
Optional aggregate bitstream-length budget for sensitivity planning.
When omitted, sensitivity planning uses max_length * n_layers.
min_length:
Minimum bitstream length assigned to any layer.
max_length:
Maximum bitstream length assigned to any layer.
target_error:
Positive per-layer target error used by the Hoeffding planner.
method:
Planning method. hoeffding uses analytic Hoeffding lengths;
sensitivity and proportional allocate from sensitivity scores.
Returns¶
list[LayerPrecision] Validated layer precision rows in input-layer order.
Raises¶
ValueError If planner bounds, method, names, or weight tensors are invalid.
Module compiler.live_control_ops¶
Class MMIOWrite¶
One deterministic memory-mapped write in a live-update transaction.
- post_init()
Class MMIORead¶
One deterministic memory-mapped read in a live-control transaction.
- post_init()
Module compiler.live_control_specs¶
Class TrapSpec¶
Contract for overflow and saturation trap signalling.
- post_init()
Class ParameterBankSpec¶
Immutable contract describing one writable bank mapped to MMIO.
- post_init()
- entry_width_bits()
- Return storage width in bits for one bank entry.
- entry_width_bytes()
- Return storage width in bytes for one bank entry.
- span_bytes()
- Return total byte span from start to end for the bank.
- end_address_bytes()
- Return first invalid byte address beyond the parameter bank.
- encoded_word_max()
- Largest unsigned storage word accepted for one entry.
- signed_code_min()
- Smallest signed two's-complement code accepted for convenience.
- signed_code_max()
- Largest signed two's-complement code accepted for convenience.
- normalise_encoded_word(value)
- Return an unsigned storage word after validating encoded range.
- entry_index(parameter)
- Resolve a parameter name or numeric entry into a bank index.
- entry_address(parameter)
- Return byte address for one parameter entry in this bank.
- to_dict()
- Serialise to JSON-compatible mapping.
- from_dict(cls, payload)
- Rehydrate immutable bank spec from serialized mapping.
Class MMIOUpdateSpec¶
Contract for dynamic updates through bus-mapped control registers.
- post_init()
- has_traps()
- Whether the contract requires overflow/saturation signalling.
- total_address_space_bytes()
- Total MMIO span from min bank start to max bank end.
- control_register_addresses()
- Return absolute addresses for the fixed live-control register map.
- status_bits()
- Return host-visible status-bit assignments.
- control_bits()
- Return host-writeable control-bit assignments.
- trap_bits()
- Return deterministic trap-bit assignments for generated parameter banks.
- effective_trap_width()
- Return trap-vector width needed by host-visible generated traps.
- trap_clear_mask()
- Return the mask that clears all host-visible generated trap bits.
- update_checksum(bank_name, parameter, encoded_value)
- Return deterministic IEEE CRC32 guard for one staged update.
- bank_index(bank_name)
- Return deterministic bank-select index for one bank name.
- bank_by_name(bank_name)
- Return a bank by name or fail closed.
- build_update_sequence(bank_name, parameter, encoded_value)
- Build an atomic staged MMIO update sequence.
- build_apply_sequence()
- Build the host-side write sequence that applies a loaded shadow word.
- build_rollback_sequence()
- Build the host-side write sequence that restores shadow from active state.
- build_selective_trap_clear_sequence(trap_mask)
- Build the host-side sequence for clearing selected sticky traps.
- build_trap_clear_sequence()
- Build the host-side sequence for clearing all generated sticky traps.
- build_readback_sequence(bank_name, parameter)
- Build the host-side select/readback sequence for one active entry.
- to_dict()
- Serialise contract for manifest persistence.
- from_dict(cls, payload)
- Rehydrate contract from serialized mapping.
Module compiler.mixed_dense_kernel¶
Class MixedDenseBatchResult¶
Per-element results of a batched mixed-precision dense contraction.
Each array has shape (n_batch, n_outputs).
Attributes¶
outputs_q1616 : numpy.ndarray
Saturated Q16.16 accumulator codes, int32.
overflow : numpy.ndarray
True where the accumulator left the Q16.16 range, bool_.
underflow : numpy.ndarray
True where a non-zero contraction rounded to zero without
overflowing, bool_.
Function mixed_dense_forward_batch_q88_q1616(weights_q88, inputs_q1616, n_outputs, n_inputs)¶
Pure-Python batched mixed-precision dense MAC — the bit-true floor reference.
Parameters¶
weights_q88 : array_like
Row-major n_outputs * n_inputs Q8.8 weights (int16 range).
inputs_q1616 : array_like
Row-major n_batch * n_inputs Q16.16 input codes (int32 range).
n_outputs : int
Number of dense output channels.
n_inputs : int
Number of dense input channels.
Returns¶
MixedDenseBatchResult Per-batch, per-output saturated Q16.16 codes with overflow/underflow flags.
Raises¶
ValueError
If shapes are inconsistent or the accumulation can exceed int64.
Function available_backends()¶
Probe which acceleration backends can run the mixed-dense kernel.
Returns¶
dict
Mapping of backend name to availability, in fastest-first order. The
python floor is always True.
Function mixed_dense_forward_batch(weights_q88, inputs_q1616, n_outputs, n_inputs)¶
Run the batched mixed-precision dense MAC through the fastest available backend.
Parameters¶
weights_q88, inputs_q1616, n_outputs, n_inputs
See :func:mixed_dense_forward_batch_q88_q1616.
backend : str, optional
"auto" (default) selects the fastest available backend in
:data:FASTEST_FIRST_BACKENDS order. A specific name forces that backend.
Returns¶
MixedDenseBatchResult Bit-identical to the Python floor for every backend.
Raises¶
ValueError
If backend is not a known name.
ImportError
If an explicitly requested accelerator backend is unavailable.
Module compiler.mixed_dense_quantization¶
Class CompiledMixedDense¶
Bit-true mixed fixed-point dense operator compiled from float weights.
- post_init()
- output_size()
- Number of dense output channels.
- input_size()
- Number of dense input channels.
- accumulator_divisor()
- Raw-product divisor that converts Qw*Qa products into Qa codes.
- manifest()
- Deterministic deployment metadata for host, Rust, and HDL emitters.
- forward_with_overflow(inputs)
- Return saturated Q-accumulator codes and per-output overflow flags.
- forward_accumulator_codes(inputs)
- Return saturated accumulator-format integer codes for dense outputs.
- precision_trap_report(inputs)
- Return saturation telemetry suitable for a hardware trap register.
- precision_envelope_report(inputs)
- Return a conservative absolute-output envelope for this workload.
- forward_float(inputs)
- Return dense outputs reconstructed from saturated accumulator codes.
Function compile_dense_mixed_precision(weights, fmt)¶
Compile a dense weight matrix into the mixed Q8.8/Q16.16 MAC contract.
Module compiler.mixed_precision_spec¶
Class MixedPrecisionSpec¶
Specification for mixed-precision compilation.
Maps each state variable to its own PrecisionConfig, enabling heterogeneous datapaths in a single Verilog module.
Parameters¶
var_configs : dict[str, PrecisionConfig] Per-variable precision configuration.
- total_bits()
- Total bit count across all variables.
- variables()
- List of variable names.
- get(var)
- Get the precision config for a variable.
- require_scalar_encoding()
- Reject variables whose precision needs detached block exponents.
- summary()
- Return a human-readable summary of the precision allocation.
- manifest()
- Return deterministic per-variable precision metadata.
Module compiler.mlir_emitter¶
Class MLIRNode¶
Operation record emitted into the dependency-free MLIR text builder.
Class MLIRBundle¶
Generated MLIR file, optional lowered Verilog, and evidence manifest.
- to_dict()
- Return a JSON-serialisable manifest representation.
Class MLIREmitter¶
Translate sc-neurocore objects into MLIR text formatted for CIRCT.
- init(module_name)
- get_wire()
- Allocate the next SSA wire name for emitted MLIR operations.
- emit_and(lhs, rhs)
- Emit a comb.and operation for stochastic multiplication.
- emit_lfsr(width, seed)
- Emit a clocked, parametric
sc_lfsrinstance for CIRCT lowering. - emit_xor(lhs, rhs)
- Emit a comb.xor operation.
- emit_mux(cond, true_val, false_val)
- Emit a comb.mux operation for SC scaled addition.
- generate()
- Generate CIRCT-consumable
hw/combdialect MLIR for the module. - write_bundle(output_dir)
- Write MLIR plus a manifest describing CIRCT lowering readiness.
Function generate_mlir_bundle(emitter, output_dir)¶
Write a CIRCT-ready MLIR file, a manifest, and optionally lowered Verilog.
With run_circt=False (default) the bundle is evidence-first: it records
whether circt-opt is available but does not execute it. With
run_circt=True it verifies the module and lowers it to Verilog through
circt-opt, writing <module>.v and recording genuine execution
evidence in the manifest; it raises :class:SCCompilerError if circt-opt
is missing or rejects the MLIR, rather than claiming an un-run lowering.
Module compiler.multi_target¶
Class CompilationResult¶
Per-target compilation result for comparison.
Attributes¶
target : str Profile name. verilog_lines : int Lines of generated Verilog. data_width : int Total bit width. fraction : int Fractional bits. overflow : str Overflow mode. rounding : str Rounding mode. estimated_luts : int LUT estimate. estimated_dsps : int DSP block estimate. estimated_ffs : int Flip-flop estimate. guard_bits : int Required guard bits. max_freq_mhz : int | None Target max frequency, or None when unknown.
Function compile_multi_target(equations, targets, module_name)¶
Compile a neuron to multiple targets and collect metrics.
Parameters¶
equations : dict Variable name → ODE RHS expression. targets : list[str] Profile names to compile against. module_name : str Base module name.
Returns¶
list[CompilationResult] Per-target compilation results.
Function format_comparison_table(results)¶
Format multi-target results as a markdown comparison table.
Parameters¶
results : list[CompilationResult] Per-target compilation results.
Returns¶
str Markdown table string.
Module compiler.operator_abstraction¶
Class LiftedSignal¶
One internal result abstracted to a free input port.
Attributes¶
internal : str
Name of the internal signal to abstract (e.g. a multiplier product wire).
port : str
Name of the free input port to expose it as. It may differ from
internal so two modules that name the product differently can present
the same abstracted interface for the miter to share.
msb : str or None
Most-significant bit-index expression of the port width, preserving a
parameter-dependent width ("2*DATA_WIDTH-1"). None declares a
scalar (1-bit) port.
signed : bool
Whether the port is declared signed.
- declaration()
- Return the
input wireport declaration for the module header.
Function abstract_to_free_inputs(verilog)¶
Abstract each signal's driver away and expose it as a free input port.
For every :class:LiftedSignal the internal name is renamed to the target
port name, its declaration and continuous-assign driver are removed, and the
port is added to top's ANSI interface. The result over-approximates the
original: the abstracted result is unconstrained, so a miter proof that
survives it is sound for the concrete design (see the module docstring).
Parameters¶
verilog : str
Single-module Verilog source containing top.
top : str
Module to transform.
signals : list[LiftedSignal]
The internal results to abstract. Must be non-empty with unique port
names that do not collide with an existing port.
Returns¶
str The transformed Verilog source.
Raises¶
ValueError
If signals is empty, a port name is duplicated or already declared, or
a signal's declaration / driver cannot be located.
Module compiler.overflow_proof¶
Class Interval¶
A closed interval [lo, hi] for interval arithmetic.
- add(other)
- Add two intervals: [a,b] + [c,d] = [a+c, b+d].
- sub(other)
- Subtract intervals: [a,b] - [c,d] = [a-d, b-c].
- mul(other)
- Multiply intervals: all four products, take min/max.
- truediv(other)
- Divide intervals. Raises if divisor contains zero.
- neg()
- Negate: -[a,b] = [-b, -a].
- contains(lo, hi)
- Check if this interval is contained within [lo, hi].
Class OverflowProofResult¶
Result of a formal overflow proof.
Attributes¶
proven_safe : bool True if the expression provably cannot overflow at the given precision. expr_interval : Interval The computed output interval of the expression. q_min : float Minimum representable value in the Q-format. q_max : float Maximum representable value in the Q-format. margin_lo : float How far the expression minimum is from the Q-format minimum (positive = safe). margin_hi : float How far the expression maximum is from the Q-format maximum (positive = safe).
Class FixedPointEnvelopeProof¶
Static fixed-point width proof over conservative Q-code bounds.
The proof is intended for deployment artefacts that already compute conservative absolute output bounds, such as mixed Q8.8/Q16.16 and block-floating dense paths. It does not use realised output cancellation: a small output value remains unsafe when the absolute product envelope exceeds the signed Q-format capacity.
- manifest()
- Return a stable JSON-serialisable proof manifest.
Function prove_fixed_point_envelope(bound_codes)¶
Prove whether conservative Q-code bounds fit a fixed-point format.
Parameters¶
bound_codes : Sequence[int] Conservative absolute output bounds in integer Q-code units. For signed formats the function accepts signed codes and proves against their absolute magnitudes. Unsigned formats reject negative codes. total_bits : int Total output width, including the sign bit for signed formats. fractional_bits : int Fractional precision bits in the Q-format. signed : bool Whether the target fixed-point format is signed.
Returns¶
FixedPointEnvelopeProof Fail-closed width proof and saturation requirement.
Function prove_no_overflow(expr_str, bounds, data_width, fraction, signed)¶
Statically prove that an expression cannot overflow at a given precision.
Uses interval arithmetic to compute the range of possible output values, then checks whether the output interval fits within the Q-format range.
Parameters¶
expr_str : str Python-syntax arithmetic expression. bounds : dict Mapping from variable name to (min, max) bounds. data_width : int Total bit width. fraction : int Fractional bits. signed : bool Whether the format is signed.
Returns¶
OverflowProofResult
Contains proven_safe=True if the proof succeeds.
Module compiler.pipeline¶
Class CompilerPipeline¶
Coordinate MLIR lowering, synthesis, and place-and-route tool steps.
The pipeline writes generated artifacts under work_dir and validates
artifact paths before invoking the external EDA toolchain.
- init(work_dir)
- compile_mlir_to_verilog(mlir_content, output_name)
- Lower
hw/combdialect MLIR to Verilog withcirct-opt. - run_synthesis(v_path, target_fpga)
- Run Yosys synthesis and return the expected JSON netlist path.
- run_pnr(json_path, target_device)
- Run nextpnr place-and-route and return the expected ASC path.
Module compiler.pipeline_analysis¶
Function critical_path_depth(expr_str)¶
Count the longest chain of Mult/Div nodes in an expression.
This determines how many DSP blocks are chained in series in the resulting Verilog datapath. At high frequencies, each DSP in series adds ~2.5 ns of combinational delay.
Parameters¶
expr_str : str Python-syntax arithmetic expression.
Returns¶
int Maximum multiply/divide chain length (0 = no multiplies).
Examples¶
critical_path_depth("a * b + c") 1 critical_path_depth("a * b * c * d") 3 critical_path_depth("a + b") 0
Function pipeline_stages_needed(depth, target_freq_mhz, dsp_delay_ns, routing_overhead_ns)¶
Compute how many pipeline registers are needed between DSP blocks.
Parameters¶
depth : int
Critical path depth (from critical_path_depth()).
target_freq_mhz : int
Target clock frequency in MHz.
dsp_delay_ns : float
Propagation delay per DSP multiply (default 2.5 ns for Artix-7).
routing_overhead_ns : float
Routing overhead per stage.
Returns¶
int Number of pipeline registers to insert (0 = no pipelining needed).
Function pipeline_analysis(equations, target_freq_mhz, dsp_delay_ns)¶
Analyse pipeline requirements for a multi-ODE system.
Parameters¶
equations : dict Variable name → RHS expression. target_freq_mhz : int Target clock frequency. dsp_delay_ns : float DSP propagation delay.
Returns¶
dict
Per-variable analysis: {var: {"depth": int, "stages": int,
"achievable_mhz": int}}.
Module compiler.platforms.registry¶
Class HardwareProfile¶
Complete hardware configuration for a target platform.
Attributes¶
name : str
Short machine-readable identifier (e.g. "loihi2").
vendor : str
Chip vendor (e.g. "Intel", "Xilinx").
family : str
Product family (e.g. "Arria 10", "ECP5").
platform_class : str
One of "fpga", "neuromorphic", "asic", "simulation".
data_width : int
Total bit width for fixed-point arithmetic.
fraction : int
Number of fractional bits.
signed : bool
True for signed (two's complement), False for unsigned Q-format.
overflow : OverflowMode
How to handle arithmetic overflow in next-state logic.
rounding : RoundingMode
How to round after fixed-point multiplication truncation.
dsp_block : str
Name of the DSP hard macro (e.g. "DSP48E2").
dsp_mult_a : int
Width of the DSP A-port (multiplier input A).
dsp_mult_b : int
Width of the DSP B-port (multiplier input B).
max_freq_mhz : int | None
Typical maximum clock frequency (0 = unknown).
notes : str
Human-readable rationale for the configuration.
- int_bits()
- Number of integer bits (excluding sign bit if signed).
- q_format_label()
- Human-readable Q-format string (e.g.
'Q9.9'or'UQ8.8'). - max_value()
- Maximum representable positive value.
- min_value()
- Minimum representable value (most negative or zero).
- resolution()
- Smallest representable step.
- from_constraints(cls, name)
- Auto-construct an optimal profile from spec-sheet constraints.
Function get_profile(name)¶
Look up a hardware profile by name.
Parameters¶
name : str
Case-insensitive profile name (e.g. "loihi2", "artix7").
Returns¶
HardwareProfile The matching profile.
Raises¶
KeyError If no profile matches.
Function list_profiles()¶
List all registered hardware profiles, optionally filtered.
Parameters¶
platform_class : str, optional
Filter by class: "fpga", "neuromorphic", "asic", "simulation"
"accelerator", "dsp", "photonic", "in_memory", "emerging".
vendor : str, optional
Filter by vendor name (case-insensitive substring match).
Returns¶
list[HardwareProfile] Matching profiles, sorted by (platform_class, vendor, name).
Function list_profile_names()¶
Return all registered profile names, sorted.
Function load_toml_profile(path)¶
Load a user-defined hardware profile from a TOML file.
Enables users to register custom hardware targets without modifying the SC-NeuroCore source. TOML format::
[profile]
name = "my_chip"
vendor = "My Corp"
family = "ChipNet-1"
platform_class = "accelerator"
data_width = 16
fraction = 8
overflow = "saturate"
rounding = "nearest"
max_freq_mhz = 500
dsp_block = "MAC"
dsp_mult_a = 16
dsp_mult_b = 16
notes = "Custom chip description."
Parameters¶
path : str Path to the TOML file.
Returns¶
HardwareProfile The loaded and registered profile.
Raises¶
FileNotFoundError If the TOML file does not exist. ValueError If required fields are missing.
Function load_toml_profiles_dir(directory)¶
Load all TOML profiles from a directory.
Scans the directory for *.toml files and loads each as a hardware
profile. Useful for bulk-registering custom targets.
Parameters¶
directory : str Path to the directory containing TOML profile files.
Returns¶
list[HardwareProfile] All loaded profiles.
Function load_profiles_from_toml(path)¶
Load custom hardware profiles from a TOML file.
Allows users and vendors to define profiles without modifying SC-NeuroCore source code. This is the profile-extension path.
TOML format::
[[profile]]
name = "my_custom_chip"
vendor = "MyVendor"
family = "CustomFamily"
platform_class = "custom"
data_width = 16
fraction = 8
overflow = "saturate"
rounding = "nearest"
Parameters¶
path : str Path to TOML file.
Returns¶
list[str] Names of loaded profiles.
Function register_platform_hook(hook_fn)¶
Register a third-party platform discovery function.
The hook function should return a list of HardwareProfile instances when called with no arguments. Profiles are registered at runtime.
Parameters¶
hook_fn : callable Function returning list[HardwareProfile].
Function discover_platforms()¶
Execute all registered discovery hooks.
Returns¶
list[str] Names of newly discovered profiles.
Module compiler.power_estimator¶
Class PowerEstimate¶
Estimated power consumption for a compiled neuron.
Attributes¶
dynamic_mw : float Dynamic (switching) power in milliwatts. static_mw : float Leakage power in milliwatts. total_mw : float Total power (dynamic + static). energy_per_spike_nj : float Energy per spike event in nanojoules. toggle_rate : float Average toggle rate (transitions per clock per bit).
Function estimate_power(verilog)¶
Estimate power consumption from generated Verilog.
When a VCD trace is provided, dynamic power uses measured bit-level switching activity. Otherwise the function falls back to structural activity factors derived from registers, adders, multipliers, and technology parameters.
Parameters¶
verilog : str Generated Verilog source. data_width : int Fixed-point data width. freq_mhz : float Clock frequency in MHz. vdd : float Supply voltage (V). process_nm : int Process node in nm (7, 16, 28, 45, ...). spike_rate_hz : float Expected average spike rate. activity_vcd : str or Path, optional VCD trace text or a path to a VCD file. When provided, bit-level transitions in the trace drive dynamic power. vcd_time_units_per_cycle : float Number of VCD timestamp units per target clock cycle.
Returns¶
PowerEstimate Estimated power breakdown.
Module compiler.precision_config¶
Class BlockFloatingScalarEncodingError¶
Raised when block-floating precision is used by a scalar-only encoder.
Class BlockFloatingPrecisionConfig¶
Block-floating specification for a single variable.
Attributes¶
mantissa_bits: Number of signed mantissa bits emitted on the fixed datapath. exponent_bits: Number of bits stored for each shared block exponent code. block_size: Number of flattened parameters that share one exponent code. signed: Whether the mantissa stream uses signed two's-complement values.
- post_init()
- Validate block-floating width and layout invariants.
- data_width()
- Mantissa datapath width emitted for hardware and manifest payloads.
- fraction()
- Conservative fractional width used by fixed-datapath fallbacks.
- emit_fraction()
- Fractional width advertised to downstream fixed-datapath emitters.
- kind()
- Stable manifest kind for block-floating precision contracts.
- int_bits()
- Signed mantissa magnitude bits excluding shared exponent metadata.
- exponent_bias()
- Bias that maps stored exponent codes to unbiased exponents.
- exponent_code_min()
- Smallest encoded shared-exponent code.
- exponent_code_max()
- Largest encoded shared-exponent code.
- mantissa_abs_max()
- Largest signed mantissa magnitude before applying the block exponent.
- max_exponent()
- Largest unbiased exponent represented by the exponent stream.
- min_exponent()
- Smallest unbiased exponent represented by the exponent stream.
- max_value()
- Largest positive value representable by mantissa and exponent fields.
- min_value()
- Smallest signed value representable by mantissa and exponent fields.
- resolution()
- Smallest positive exponent quantum available to the block stream.
- q_label()
- Canonical block-floating label including mantissa, exponent, and block size.
- is_block_floating()
- Whether this precision contract requires shared exponent metadata.
- supports_scalar_encoding()
- Whether
encodecan produce a complete scalar storage word. - require_scalar_encoding()
- Reject scalar consumers before block exponent metadata is lost.
- can_represent(value)
- Return whether
valuelies inside the coarse block-floating range. - encode(value)
- Reject scalar encoding when block exponent metadata is unavailable.
- manifest()
- Return the parameter-count-independent block-floating manifest.
- block_exponent_count(parameter_count)
- Return the number of shared exponents needed for
parameter_count. - block_exponent_layout(parameter_count)
- Return the flattened exponent-vector layout for
parameter_count. - validate_exponents(exponents)
- Validate and normalise encoded block exponents for a parameter payload.
- manifest_for_parameter_count(parameter_count)
- Return a deterministic manifest with optional concrete layout metadata.
Class PrecisionConfig¶
Fixed-point configuration for a single variable.
Attributes¶
data_width: Total fixed-point storage width in bits. fraction: Number of fractional bits below the binary point. signed: Whether encoded values use signed two's-complement storage.
- int_bits()
- Integer magnitude bits available above the configured fraction.
- max_value()
- Largest fixed-point value representable by this configuration.
- min_value()
- Smallest fixed-point value representable by this configuration.
- resolution()
- Quantisation step represented by one least-significant bit.
- q_label()
- Standard sign-inclusive Q-format label.
- emit_fraction()
- Fractional width advertised to downstream fixed-point emitters.
- kind()
- Stable manifest kind for fixed-point precision contracts.
- is_block_floating()
- Whether this precision contract requires shared exponent metadata.
- supports_scalar_encoding()
- Whether
encodecan produce a complete scalar storage word. - require_scalar_encoding()
- Validate that this fixed-point config is scalar-encodable.
- manifest()
- Return a deterministic fixed-point manifest for compilers and telemetry.
- can_represent(value)
- Return whether
valuelies inside the fixed-point dynamic range. - encode(value)
- Quantise
valueto the nearest clamped fixed-point integer code.
Function encode_scalar_value(config, value)¶
Encode one scalar value or reject precision modes requiring exponent metadata.
Module compiler.precision_presets¶
Function from_preset(var_presets)¶
Create a MixedPrecisionSpec from named presets.
Set scalar_only when the downstream consumer cannot carry detached
block-exponent metadata. Block-floating selections then fail during preset
resolution instead of later scalar encoding.
Module compiler.precision_solver¶
Function solve_precision(bounds)¶
Solve a deterministic per-variable fixed-point precision assignment.
The solver derives integer bits from each value range and fractional bits from the requested resolution. Optional total-bit budgets reduce the largest fractional fields first until the budget is met or every reduced variable is already at one fractional bit.
Parameters¶
bounds : dict Mapping from variable name to (min, max) value bounds. min_resolution : dict, optional Mapping from variable name to minimum required resolution. Defaults to 0.01 for all variables. max_total_bits : int, optional If set, the solver will reduce fractional bits to fit. signed : bool Whether to use signed formats. align_to : int Align each variable's data_width to this multiple.
Returns¶
MixedPrecisionSpec Per-variable precision configuration derived from range, resolution, alignment, signedness, and optional total-bit budget constraints.
Module compiler.proof_transforms¶
Class ProofTransform¶
Metadata for one selectable formal-proof RTL transform.
Attributes¶
kind : ProofTransformKind
Stable dispatch key accepted by :func:apply_proof_transform.
module : str
Import path that owns the concrete transform implementation.
entrypoint : str
Public callable name inside module.
purpose : str
Human-readable reason the proof pipeline may select the transform.
default_enabled : bool
Whether ordinary compiler emission enables the transform by default.
Proof transforms remain opt-in, so current registry entries are false.
Function list_proof_transforms()¶
Return the formal-proof transforms available to opt-in proof pipelines.
Returns¶
tuple[ProofTransform, ...] Immutable registry entries. Every entry is disabled by default for ordinary compilation and must be selected explicitly by proof tooling.
Function get_proof_transform(kind)¶
Return the registry entry for kind.
Parameters¶
kind : str
Stable transform key, such as "whitebox_taps" or
"operator_abstraction".
Returns¶
ProofTransform Registry metadata for the requested transform.
Raises¶
KeyError
If kind is not registered.
Function apply_proof_transform(kind, verilog)¶
Apply one registered proof-only RTL transform.
Parameters¶
kind : ProofTransformKind
Transform dispatch key.
verilog : str
Verilog source containing top.
top : str
Module name passed to the selected transform.
taps : sequence of StateTap, optional
State taps required when kind is "whitebox_taps".
signals : sequence of LiftedSignal, optional
Lifted signals required when kind is "operator_abstraction".
Returns¶
str Transformed Verilog source.
Raises¶
KeyError
If kind is not registered.
ValueError
If the selected transform's required payload is missing.
Module compiler.q_format¶
Class QFormat¶
Signed fixed-point Q-format specification.
Attributes¶
integer_bits: Number of signed integer bits, including the sign bit. fraction_bits: Number of fractional bits below the binary point.
- post_init()
- Validate the fixed-point width fields after construction.
- total_bits()
- Total signed fixed-point storage width in bits.
- scale()
- Integer scale factor used to encode real values.
- min_val()
- Smallest representable signed fixed-point value.
- max_val()
- Largest representable signed fixed-point value.
- min_value()
- Minimum representable fixed-point value.
- max_value()
- Maximum representable fixed-point value.
- q_label()
- Canonical Q-format label.
- from_string(cls, fmt)
- Parse 'Q8.8', 'Q4.12', etc.
Class QFormatMixed¶
Mixed fixed-point contract for Q-format weights and wider accumulators.
Attributes¶
weight_fmt: Stored weight format. accum_fmt: Wider accumulator format used by mixed-precision dense kernels. scale_per_tensor: Whether one scale is shared by the tensor instead of per-channel scale. rounding: Rounding policy applied by the quantizer.
- post_init()
- Validate mixed-format compatibility after construction.
- accumulator_guard_bits()
- Extra accumulator bits available above the stored weight width.
- metadata()
- Deterministic metadata for manifests and hardware telemetry.
Module compiler.quantization_reports¶
Class PrecisionTrapReport¶
Per-output fixed-point saturation report for deployment trap wiring.
- post_init()
- output_count()
- Number of output channels covered by this report.
- overflow_count()
- Number of outputs that saturated during the producing operation.
- has_overflow()
- Whether any output channel saturated.
- underflow_count()
- Number of nonzero outputs that collapsed below one output LSB.
- has_underflow()
- Whether any nonzero output collapsed to the zero code.
- saturated_min_count()
- Number of outputs clamped to the minimum representable code.
- saturated_max_count()
- Number of outputs clamped to the maximum representable code.
- manifest()
- Deterministic trap metadata for host and hardware telemetry.
Class PrecisionEnvelopeReport¶
Conservative fixed-point output-envelope report for deployment checks.
- post_init()
- output_count()
- Number of output channels covered by this report.
- overflow_count()
- Number of outputs that saturated during the producing operation.
- observed_overflow_free()
- Whether the realised workload avoided fixed-point saturation.
- underflow_count()
- Number of nonzero outputs that collapsed below one output LSB.
- observed_underflow_free()
- Whether the realised workload avoided sub-LSB output collapse.
- conservative_safe_bound_code()
- Largest symmetric absolute code accepted as overflow-free.
- max_abs_output_code()
- Maximum absolute saturated output code observed in the workload.
- max_abs_bound_code()
- Maximum conservative absolute output bound for the workload.
- min_headroom_code()
- Smallest conservative headroom, in fixed-point integer codes.
- conservative_overflow_free()
- Whether the absolute envelope proves the workload is in range.
- fixed_point_envelope_proof()
- Static Q-format width proof for the conservative envelope.
- required_total_bits()
- Signed fixed-point width required by the conservative envelope.
- required_integer_bits()
- Q-format integer bits, including sign, required by the envelope.
- width_headroom_bits()
- Remaining signed fixed-point width after the conservative proof.
- saturation_required()
- Whether the conservative proof requires a saturating output clamp.
- static_overflow_proven_safe()
- Whether static width proof guarantees no Q-format overflow.
- manifest()
- Deterministic envelope metadata for predeployment gates.
Module compiler.quantizer¶
Function parse_precision_format(fmt)¶
Parse fixed-point and block-floating precision labels.
Module compiler.resource_estimator¶
Class ResourceEstimate¶
Estimated FPGA resource usage.
Attributes¶
luts : int Estimated look-up tables. ffs : int Estimated flip-flops (registers). dsps : int Estimated DSP blocks. brams : int Estimated block RAMs. mul_count : int Number of multiplications in the design. add_count : int Number of additions/subtractions. reg_bits : int Total register bits.
Function estimate_resources(verilog)¶
Estimate FPGA resources from generated Verilog without synthesis.
Uses pattern matching on the Verilog source to count multipliers, adders, registers, and LUTs. This is a heuristic — actual usage depends on the synthesis tool, but estimates are within ~20% for typical designs.
Parameters¶
verilog : str Generated Verilog source code. data_width : int Neuron data width (for LUT estimation). has_dsp : bool True if target has DSP blocks (multiplies go to DSP, not LUTs).
Returns¶
ResourceEstimate Estimated resource usage.
Module compiler.riscv_driver¶
Function generate_riscv_driver(module_name, params)¶
Generate a RISC-V C driver for neuron control via MMIO.
Supports bare-metal, FreeRTOS, and Zephyr templates with timer-driven neuron tick tasks for real-time operating system integration.
Parameters¶
module_name : str
Neuron module name.
params : dict[str, int]
Parameter names and bit widths.
base_address : int
MMIO base address.
data_width : int
Fixed-point data width.
fraction : int
Fractional bits.
rtos : str
"baremetal", "freertos", or "zephyr".
Returns¶
str Complete RISC-V C driver with optional RTOS integration.
Module compiler.sby_formal¶
Function generate_sby_script(module_name)¶
Generate a SymbiYosys .sby formal verification script.
Enables one-command bounded model checking of compiled neurons using open-source formal tools (SymbiYosys + Yosys + solver).
Parameters¶
module_name : str
Top-level Verilog module name.
sva_file : str, optional
SystemVerilog assertions file. Defaults to {module}_sva.sv.
depth : int
BMC / induction depth in clock cycles.
mode : str
"bmc" (bounded), "prove" (induction), "cover".
solver : str
Solver backend ("smtbmc", "aiger").
engine : str
SMT engine ("boolector", "z3", "yices").
Returns¶
str
Complete .sby configuration file.
Module compiler.sensitivity_analysis¶
Function analyze_sensitivity(layer_weights, lengths, n_trials, seed)¶
Measure per-layer sensitivity to bitstream length reduction.
Parameters¶
layer_weights: One-dimensional or two-dimensional layer weight arrays. Vector weights are treated as a single-output dense layer. lengths: Candidate stochastic bitstream lengths to sample. When omitted, the estimator uses the default production planning ladder. n_trials: Number of independent input-vector samples per layer. seed: Deterministic NumPy random seed used for reproducible planning.
Returns¶
list[float] One non-negative sensitivity score for each supplied layer.
Raises¶
ValueError If trial count, candidate lengths, or layer weight arrays are invalid.
Module compiler.slr_placement¶
Class SLRPlacement¶
SLR (Super Logic Region) placement for multi-die FPGAs.
Attributes¶
module_name : str Module or instance name. slr : int Target SLR index (0-based). pblock_name : str Vivado PBLOCK name (auto-generated if empty).
- post_init()
- Auto-generate pblock name if not set.
Function generate_slr_constraints(placements)¶
Generate Vivado XDC for multi-die SLR placement.
Emits PBLOCK constraints that pin modules to specific SLRs and optionally adds inter-SLR pipeline register directives.
Parameters¶
placements : list[SLRPlacement] Module-to-SLR assignments. insert_pipeline_regs : bool Add register duplication directives for SLR crossings. target_freq_mhz : float Target frequency for SLR crossing timing.
Returns¶
str Complete XDC constraint block.
Module compiler.sva_gen¶
Function generate_sva(state_vars)¶
Generate SystemVerilog Assertions for a compiled neuron module.
Produces three categories of formal properties:
- Overflow assertions — check that no state variable exceeds the representable range after the next-state update.
- Reachability covers — prove that spike output is reachable.
- Input assumptions — constrain external inputs to valid bounds.
Parameters¶
state_vars : list[str]
Names of state variables (e.g. ["v"]).
data_width : int
Bit width of the fixed-point format.
fraction : int
Fractional bits.
signed : bool
True for signed format.
input_bounds : dict, optional
Mapping from input names to (min_q, max_q) bounds in Q-format integers.
module_name : str
Name of the target module.
Returns¶
str SystemVerilog bind module with assertions.
Module compiler.synapse_planner¶
Function assign_synapse_precisions(layer_weights, layer_names, sensitivity_maps, target_error, min_bits, max_bits, min_length, max_length, confidence)¶
Assign per-synapse bit widths and SC lengths with error bounds.
Parameters¶
layer_weights:
One- or two-dimensional finite weight tensors, one tensor per layer.
One-dimensional tensors are treated as single-output layers.
layer_names:
Optional non-empty layer names. When provided, the list length must match
layer_weights exactly.
sensitivity_maps:
Optional finite non-negative sensitivity maps with shapes matching each
corresponding weight tensor.
target_error:
Positive aggregate target error fraction.
min_bits:
Minimum fixed-point bit width assigned to any synapse.
max_bits:
Maximum fixed-point bit width assigned to any synapse.
min_length:
Minimum stochastic bitstream length assigned to any synapse.
max_length:
Maximum stochastic bitstream length assigned to any synapse.
confidence:
Hoeffding confidence in the open interval (0, 1).
Returns¶
list[SynapsePrecision] Validated per-synapse precision rows in layer/output/input order.
Raises¶
ValueError If planner bounds, names, sensitivity maps, or weight tensors are invalid.
Module compiler.synapse_precision¶
Class SynapsePrecision¶
Precision assignment and conservative error bound for one synapse.
Parameters¶
layer_index: Zero-based layer index in the adaptive-precision plan. layer_name: Non-empty layer name used in reports and manifests. output_index: Zero-based output row index for the weight matrix. input_index: Zero-based input column index for the weight matrix. bit_width: Positive fixed-point bit width assigned to the synapse. bitstream_length: Positive stochastic-computing bitstream length assigned to the synapse. sensitivity: Finite non-negative synapse sensitivity score. quantization_error_bound: Finite non-negative error bound from fixed-point quantization. stochastic_error_bound: Finite non-negative Hoeffding-style stochastic error bound. total_error_bound: Finite non-negative aggregate bound that must cover both components.
- post_init()
- Validate per-synapse precision-row invariants.
- to_dict()
- Return a JSON-serialisable precision-plan row.
Module compiler.testbench_gen¶
Function generate_testbench(neuron, module_name, n_steps, input_current, data_width, fraction, cycles_per_step)¶
Generate a Verilog testbench for a compiled equation neuron.
Drives the module with constant current for n_steps logical steps and
monitors spike_out and state outputs, producing a VCD waveform.
Parameters¶
neuron : EquationNeuron
The neuron (same one passed to compile_to_verilog).
module_name : str
Must match the module name used in compile_to_verilog.
n_steps : int
Number of logical integration steps to drive.
input_current : float
Constant input current (Q-encoded internally).
data_width : int
Bit width matching the compiled module.
fraction : int
Fractional bits matching the compiled module.
cycles_per_step : int
Clock cycles per logical step. Combinational modules advance one logical
step per clock (1, the default). A pipelined module advances one
logical step every latency + 1 clocks and gates spike_out to pulse
only on that valid cycle, so pass latency + 1 here to drive n_steps
logical steps; the spike count over the run is unchanged by the padding.
Returns¶
str Verilog testbench source code.
Module compiler.verilog_compiler_config¶
Class Q88¶
Describe a fixed-point word used by compiler diagnostics and emitters.
The historical class name is retained for API compatibility, but
data_width and fraction are configurable. Unsigned instances are
valid for range analysis and raw-word encoding. The equation-to-Verilog
emitters currently reject unsigned instances because their state and
expression datapaths are signed.
============ ========== =============== ================= =============== Mode data_width fraction Integer range Resolution ============ ========== =============== ================= =============== Q8.8 16 8 [-128, +127.996] 1/256 ≈ 0.004 Q4.12 16 12 [-8, +7.9998] 1/4096 ≈ 0.0002 Q16.16 32 16 [-32768, +32767] 1/65536 ≈ 1.5e-5 UQ8.8 16 8 (unsigned) [0, +255.996] 1/256 ≈ 0.004 ============ ========== =============== ================= ===============
Overflow Modes
- ``"saturate"`` — clamp to the representable interval (default)
- ``"wrap"`` — two's complement wrap-around (Loihi 2 hardware behaviour)
- ``"trap"`` — emit a simulation-only ``$fatal`` assertion
Rounding Modes
"truncate" — arithmetic shift towards negative infinity (default)
- "nearest" — round to nearest, ties away from zero
- "bankers" — round to nearest, ties to even (IEEE 754 default)
- "stochastic" — reserved label; equation-to-Verilog emission rejects it
Parameters¶
data_width : int
Total number of bits in the encoded word.
fraction : int
Number of fractional bits.
signed : bool
Whether range diagnostics interpret the word as two's-complement.
overflow : str
Overflow policy consumed by the Verilog emitters.
rounding : str
Product-rounding policy consumed by the expression emitter. The public
equation-to-Verilog paths reject "stochastic" because they do not
own a rounding LFSR.
- post_init()
- Validate the fixed-point geometry and declared arithmetic modes.
- integer_bits()
- Return the number of magnitude bits above the binary point.
- max_value()
- Return the largest representable value.
- min_value()
- Return the smallest representable value.
- resolution()
- Return the spacing between adjacent encoded values.
- encode(value)
- Encode a value as its fixed-width raw bit pattern.
- encode_signed_literal(value)
- Encode a float as a Verilog signed decimal literal.
- check_range(value, label)
- Return diagnostic messages when a value is outside the format.
- precision_report(dt, params)
- Build a fixed-point quantisation diagnostics report.
Module compiler.whitebox_taps¶
Class StateTap¶
One observation tap exposing an internal signal as an output port.
Attributes¶
port : str
Name of the new output wire port.
source : str
Verilog expression assigned to the port — typically an internal register
name ("v_reg") or a constant ("32'd0") that pins a tap a peer
module lacks.
msb : str or None
The most-significant bit-index expression of the port width, so a
parameter-dependent width is preserved ("DATA_WIDTH-1" renders
[DATA_WIDTH-1:0]). None declares a scalar (1-bit) port.
signed : bool
Whether the port is declared signed.
- declaration()
- Return the
output wireport declaration for the module header. - assignment()
- Return the continuous
assignthat drives the tap from its source.
Function expose_state_taps(verilog)¶
Instrument top to expose internal signals as observation output ports.
Adds each tap's output wire port to the module's ANSI port list and a
continuous assign before endmodule. The result is behaviourally
identical to the original on its original ports; the new ports let a miter
assert the state-matching invariant an unbounded k-induction proof needs (see
the module docstring for why hierarchical references and bind do not work
with yosys 0.33).
Parameters¶
verilog : str
Verilog source containing top.
top : str
Module to instrument.
taps : list[StateTap]
The taps to add. Must be non-empty; port names must be unique and must
not collide with an existing port.
Returns¶
str The instrumented Verilog source.
Raises¶
ValueError
If taps is empty, a tap port is duplicated or already declared, or the
module / its endmodule cannot be located.
Module compiler_service¶
Class LiveUpdateKind¶
Kinds of update package a compiler service may emit.
Class DigitalTwinSyncContract¶
Digital-twin sync requirements for a compiler-service request.
- post_init()
- to_dict()
- Return a JSON-compatible sync contract.
Class LiveUpdatePolicy¶
Policy deciding whether a compiler update needs re-synthesis.
- classify(changed_fields)
- Classify changed fields into the minimum required update kind.
- to_dict()
- Return a JSON-compatible policy manifest.
Class CompilerServiceRequest¶
One request accepted by the compiler-service contract boundary.
- post_init()
- to_dict()
- Return a deterministic request manifest.
Class LiveUpdatePackage¶
Update package planned for a live FPGA/digital-twin loop.
- to_dict()
- Return a JSON-compatible package summary.
Class CompilerServiceResponse¶
Deterministic response from the contract boundary.
- to_dict()
- Return a JSON-compatible compiler-service response.
Function build_compiler_service_contract()¶
Build a deterministic compiler-service boundary manifest.
Function plan_live_update(request, policy)¶
Classify a request into a live-update package.
Function build_compiler_service_response(request)¶
Build a response without invoking a network service or toolchain.
Module compression.pruning¶
Class PruningReport¶
Results of a pruning operation.
Function prune_weights(weights, threshold, method)¶
Prune small weights from layer weight matrices.
Parameters¶
weights : list of ndarray Weight matrices for each layer. threshold : float Pruning threshold. Weights with |w| <= threshold are zeroed. method : str 'magnitude' (default): prune by absolute value. 'percentile': treat threshold as percentile (0-100) of weight magnitudes to prune.
Returns¶
(pruned_weights, PruningReport)
Function prune_neurons(weights, firing_rates, activity_threshold)¶
Structural pruning: remove neurons with low firing rates.
Removes entire rows from weight matrices (output neurons) and corresponding columns from the next layer's weight matrix (input connections). Reduces layer width, not just sparsity.
Parameters¶
weights : list of ndarray Weight matrices [W1, W2, ...] where W_i has shape (n_out, n_in). firing_rates : list of ndarray, optional Per-neuron firing rates for each layer. If None, uses output weight magnitude as a proxy for importance. activity_threshold : float Neurons with firing rate (or weight norm) below this are pruned.
Returns¶
(pruned_weights, PruningReport)
Function prune_stochastic(weights, bitstream_length, min_popcount_bits)¶
Stochastic-aware pruning: score weights by bitstream contribution.
In SC networks, weight w encodes probability p = clip(|w|, 0, 1). The expected popcount contribution per inference is: contribution = min(p, 1-p) * bitstream_length
Weights that produce nearly-deterministic bitstreams (p near 0 or 1) contribute almost nothing to computation — they can be replaced with constant 0/1 gates, saving AND+popcount hardware.
Parameters¶
weights : list of ndarray Weight matrices (values in [0, 1] for unipolar SC). bitstream_length : int Bitstream length (L). Longer streams = more bits per weight. min_popcount_bits : float Minimum expected popcount contribution to keep a weight. Weights contributing fewer bits than this are zeroed.
Returns¶
(pruned_weights, PruningReport)
Module compression.quantization¶
Function quantize_weights(weights, bits, symmetric)¶
Quantize weight matrices to fixed-point with given bit width.
Parameters¶
weights : list of ndarray Float weight matrices. bits : int Target bit width (default 8). Range: [2, 16]. symmetric : bool Symmetric quantization around zero (default True).
Returns¶
list of ndarray Quantized weights (still float dtype but with discrete values).
Function quantize_delays(delays, resolution, max_delay)¶
Quantize continuous delays to integer grid.
Parameters¶
delays : ndarray Continuous delay values. resolution : int Delay step size (default 1). Resolution=2 means delays are rounded to {0, 2, 4, 6, ...}, halving the buffer depth. max_delay : int, optional Clamp delays to this maximum.
Returns¶
ndarray of int Quantized integer delays.
Module continual.engine¶
Class PlasticityConfig¶
Per-layer on-chip plasticity configuration.
Extracted from training for hardware deployment.
Parameters¶
layer_name : str rule : str Plasticity rule: 'stdp', 'r_stdp', 'homeostatic', 'none'. tau_pre : float Pre-synaptic trace time constant (ms). tau_post : float Post-synaptic trace time constant (ms). lr_potentiation : float Potentiation learning rate (A+). lr_depression : float Depression learning rate (A-). w_min : float Minimum weight. w_max : float Maximum weight. homeostatic_target : float Target firing rate for homeostatic regulation.
Class ContinualReport¶
Report from a continual learning session.
- summary()
- Render a multi-line human-readable continual-learning report.
Class ContinualLearner¶
Continual learning engine with EWC and on-chip plasticity extraction.
Parameters¶
weights : list of ndarray Initial trained weight matrices per layer. layer_names : list of str Names for each layer. ewc_lambda : float Regularization strength for EWC (0 = no protection). plasticity_rule : str Default on-chip plasticity rule for all layers.
- init(weights, layer_names, ewc_lambda, plasticity_rule)
- compute_fisher(gradients_per_sample)
- Compute Fisher Information diagonal from per-sample gradients.
- ewc_penalty()
- Compute EWC regularization penalty.
- register_task(accuracy)
- Register completion of a task.
- update_weights(new_weights)
- Update weights (e.g., after training on a new task).
- extract_plasticity_configs()
- Extract per-layer plasticity parameters for on-chip deployment.
- report()
- Generate a continual learning report.
Module contrastive.ssl¶
Class SpikeContrastiveLoss¶
InfoNCE contrastive loss adapted for spike representations.
Computes similarity between spike-rate vectors from two augmented views of the same input. Positive pairs = same input, different augmentation. Negative pairs = different inputs.
Parameters¶
temperature : float Contrastive temperature scaling.
- init(temperature)
- compute(view_a, view_b)
- Compute contrastive loss for a batch of spike-rate pairs.
Class CSDPRule¶
Contrastive Signal-Dependent Plasticity.
Local learning rule: weight update depends on (pre, post, contrastive_signal). Positive phase: present real data → Hebbian update. Negative phase: present corrupted data → anti-Hebbian update.
Generalizes Forward-Forward to spiking circuits.
Reference: Ororbia 2024, Science Advances
Parameters¶
lr : float Learning rate. decay : float Weight decay for regularization.
- post_init()
- Validate the scalar learning-rule parameters.
- positive_update(weights, pre_spikes, post_spikes)
- Hebbian update from positive (real) data.
- negative_update(weights, pre_spikes, post_spikes)
- Anti-Hebbian update from negative (corrupted) data.
- contrastive_step(weights, pos_pre, pos_post, neg_pre, neg_post)
- Apply one positive phase followed by one negative phase.
- goodness(activations)
- Compute 'goodness' score (sum of squared activations).
Module control.adaptive_loop¶
Class AdaptationEvent¶
Record of a single adaptation cycle.
Class AdaptiveLoopConfig¶
Configuration for the adaptive controller.
Class AdaptiveController¶
Closed-loop: Runtime drift → Optimizer SA → New config.
Usage::
ctrl = AdaptiveController(budget, layers)
for bitstream_pair in stream:
event = ctrl.step(bitstream_pair)
if event and event.config_changed:
apply_new_config(ctrl.current_config)
- init(budget, layers, config)
- step(bitstream_a, bitstream_b)
- Feed a bitstream pair; returns AdaptationEvent if re-optimisation triggered.
- adaptation_rate()
- Fraction of steps that triggered re-optimisation.
- summary()
Module control.controllers¶
Class SpikingPID¶
Population-coded PID controller.
Error → rate-coded spike populations → P/I/D populations → output current. Gains are synaptic weights.
Parameters¶
Kp, Ki, Kd : float PID gains (encoded as synaptic weights). n_neurons : int Population size per channel. dt : float Timestep.
- init(Kp, Ki, Kd, n_neurons, dt)
- step(error)
- Compute PID output for one timestep.
- step_spike(error, rng)
- Compute PID output as spike population.
- reset()
Class SpikingKalmanFilter¶
Spike-domain Kalman filter for state estimation.
State prediction and correction using LIF-based integration. Kalman gain encoded as synaptic weight matrix.
Parameters¶
n_states : int State dimension. n_measurements : int Measurement dimension. A : ndarray State transition matrix. H : ndarray Observation matrix. Q : ndarray Process noise covariance. R : ndarray Measurement noise covariance.
- init(n_states, n_measurements, A, H, Q, R)
- predict()
- Predict step: x = A @ x, P = A @ P @ A^T + Q.
- update(z)
- Update step with measurement z.
- step(z)
- Predict + update in one call.
- reset()
Class SpikingLQR¶
Spike-domain Linear Quadratic Regulator.
Computes optimal gain K from system matrices (A, B, Q, R). Control law: u = -K @ x. Weights derived analytically.
Parameters¶
A : ndarray (n, n) — state transition B : ndarray (n, m) — control input Q : ndarray (n, n) — state cost R : ndarray (m, m) — control cost
- init(A, B, Q, R)
- control(x)
- Compute optimal control: u = -K @ x.
- gain_matrix()
Module control.sc_runtime¶
Class DecorrelatorType¶
Class ECCMode¶
Class ActivityZone¶
Class RuntimeConfig¶
Current runtime configuration for a bitstream engine.
- effective_length()
- copy()
Class AdaptationEvent¶
Log entry for a runtime adaptation.
Class ActivityMonitor¶
Rolling-window bitstream activity tracker.
Maintains running statistics of popcount density and SCC for drift detection.
- init(window_size, drift_threshold)
- observe(bitstream, reference)
- Record one observation.
- mean_density()
- mean_scc()
- drift_active()
- current_zone()
Class HammingECC¶
Hamming(7,4) encoder/decoder (Python mirror of Rust ScDoctor ECC).
- encode(data_4bit)
- Encode 4-bit data to 7-bit Hamming codeword.
- decode(encoded_7bit)
- Decode 7-bit Hamming codeword to 4-bit data, correcting 1-bit errors.
- encode_bitstream(bitstream)
- Apply Hamming(7,4) ECC to an entire bitstream (groups of 4 bits).
- decode_bitstream(encoded)
- Decode Hamming(7,4) encoded bitstream.
Class SECDEC_ECC¶
SECDED (Single Error Correct, Double Error Detect) Hamming(8,4).
Extends Hamming(7,4) with an overall parity bit for 2-bit error detection. Corrects all 1-bit errors, detects all 2-bit errors.
- init()
- encode(data_4bit)
- Encode 4-bit data to 8-bit SECDED codeword.
- decode(encoded_8bit)
- Decode 8-bit SECDED codeword.
- encode_bitstream(bitstream)
- Apply SECDED(8,4) to an entire bitstream.
- decode_bitstream(encoded)
- Decode SECDED(8,4) encoded bitstream.
Class AdaptationPolicy¶
Rules for runtime bitstream adaptation.
- init(scc_high, scc_low, min_length, max_length, ecc_trigger_length, enable_decorrelator_cascade)
- decide(config, metrics)
- Evaluate metrics and return (new_config, trigger_reason_or_None).
Class RuntimeReport¶
Summary report from a runtime session.
- num_adaptations()
- adaptation_rate(last_n)
- Adaptations per observation (optionally over last_n events).
- summary()
Class SCRuntimeEngine¶
Main runtime adapter: monitors + adapts + applies ECC.
- init(initial_config, policy, monitor_window)
- observe(bitstream, reference)
- Feed one bitstream observation through the runtime.
- protect(bitstream)
- Apply ECC protection if enabled in current config.
- recover(encoded)
- Decode ECC-protected bitstream if enabled.
- protect_batch(bitstreams)
- Apply ECC to a batch of bitstreams.
- recover_batch(encoded_list)
- Decode a batch of ECC-protected bitstreams.
Function classify_activity(density)¶
Map popcount density to activity zone.
Module conversion.ann_to_snn¶
Function replace_relu_with_qcfs(model, T, theta, learn_theta)¶
Swap every ReLU/ReLU6 in a model for a QCFS activation, in place.
This prepares a trained or fresh ANN for conversion-aware fine-tuning: after substitution the network is retrained for a few epochs so the QCFS thresholds settle. Conversion loss is then measured against the source ANN; QCFS does not guarantee lossless conversion for arbitrary spike timing.
Parameters¶
model : nn.Module Model whose registered ReLU/ReLU6 children are replaced in place. All aliases of one original activation retain one shared QCFS module and learned threshold. The container and activation training modes are preserved; the root module itself is returned unchanged. T : int Quantisation step budget for each inserted QCFS layer. theta : float Initial firing threshold for each inserted QCFS layer. learn_theta : bool Whether each inserted threshold is a trainable parameter (the QCFS fine-tuning default).
Returns¶
nn.Module
The same model instance, returned for chaining.
Function convert(model, calibration_data, T, percentile)¶
Convert a trained PyTorch ANN to a rate-coded SNN.
Activations are associated with their actual preceding source operations. ReLU and QCFS stages retain separate calibration scales and preloads in mixed networks. Unsupported dense-target operators fail compatibility admission.
Parameters¶
model : nn.Module Trained PyTorch model representable by a single-input dense forward path with Linear, ReLU/ReLU6 and QCFS operations. Actual invocations, including shared modules and functional ReLUs, determine the exported topology. calibration_data : Tensor, optional Sample source-format input for every ReLU invocation, including functional activations in mixed ReLU/QCFS networks. None uses unit ReLU scales; QCFS invocations always retain their learned thresholds. T : int, optional Number of simulation timesteps (higher = more accurate, slower). If None, the QCFS route adopts the layers' trained step budget and the ReLU route defaults to 16. percentile : float Activation percentile for threshold normalization on the ReLU route.
max_working_bytes : int Numeric storage budget for source copying and exported snapshots.
Returns¶
ConvertedSNN Converted spiking network ready to run.
Module conversion.calibration¶
Function calibrate_activation_thresholds(model, calibration_data, percentile)¶
Measure each ReLU's inference activation percentile in forward order.
Parameters¶
model : nn.Module
Source ANN. Its original per-module training modes and user hooks are
retained on success and failure.
calibration_data : torch.Tensor
Nonempty finite input tensor passed through the actual source network.
percentile : float
Activation percentile in the closed interval [0, 100].
Returns¶
list of float
Per-invocation activation scales, floored at 1e-6 for silent ReLUs.
Raises¶
ValueError If the input, percentile or measured activations are invalid.
Module conversion.checkpoint_network¶
Class CheckpointNetwork¶
A converted network and how it was obtained from its checkpoint.
Attributes¶
snn : ConvertedSNN
The converted network.
source : {'state_dict', 'studio_qcfs_conversion'}
Which checkpoint form was read.
layer_sizes : list of tuple of int
(inputs, outputs) of every dense layer, in forward order.
calibration : str
What set the ReLU thresholds: samples, unit scales or
learned QCFS thresholds.
Function build_qcfs_classifier(n_inputs, hidden, n_outputs, steps)¶
Build the dense classifier with QCFS activations the Studio conversion route trains.
Parameters¶
n_inputs, n_outputs : int Flattened input width and class count. hidden : tuple of int Hidden widths in order; empty for a direct input-to-output layer. steps : int QCFS step budget of every activation.
Returns¶
torch.nn.Sequential
Flatten then alternating Linear and QCFS layers, ending in Linear.
Function network_from_checkpoint(payload)¶
Convert the network a trusted, already loaded checkpoint holds.
Parameters¶
payload : object
What torch.load(..., weights_only=True) returned.
steps : int
Timestep budget for a plain state dict; a Studio checkpoint uses its own.
calibration : ndarray, optional
(samples, inputs) source-format samples for ReLU threshold calibration
of a plain state dict.
max_dense_params : int
Largest accepted number of dense weights.
Returns¶
CheckpointNetwork The converted network and its provenance.
Raises¶
ValueError The payload is not a dense checkpoint this function can rebuild exactly.
Module conversion.converted_io¶
Function save_converted_network(snn, path)¶
Write snn to path and return its digest.
Parameters¶
snn : ConvertedSNN
The network to write.
path : str or Path
Destination .npz file; an existing file is replaced.
Returns¶
str
The network's converted_sha256, also stored in the file.
Function load_converted_network(path)¶
Read a network written by :func:save_converted_network.
Parameters¶
path : str or Path
The .npz file.
Returns¶
ConvertedSNN The network, whose digest equals the one recorded in the file.
Raises¶
ValueError Another schema, missing or extra arrays, or a digest mismatch.
Module conversion.converted_snn¶
Class ConvertedSNN¶
A dense IF stack with deterministic input encoding and replayable state.
Parameters¶
weights : sequence of array_like
Output-by-input matrices. Constructor inputs are copied to float64.
biases : sequence of array_like or None
Constant per-step currents in each layer's normalized threshold units.
thresholds : sequence of float
Positive finite thresholds, one per layer.
T : int
Positive timestep budget, at most 2**53 for exact count arithmetic.
initial_membrane_fraction : float
Default IF membrane preload in threshold units; QCFS uses 0.5.
output_scale : float
Positive finite source activation units per unit of decoded rate.
output_mode : {'spikes', 'linear'}
IF spike-count output or integrated signed linear readout. A linear
final layer has no threshold/reset events and starts at zero.
max_working_bytes : int
Numeric buffer budget for constructor coefficient snapshots. Runtime
calls accept their own budget; each defaults to 256 MiB.
layer_membrane_fractions : sequence of float, optional Per-layer preloads for mixed activation routes. None uses the global fraction; the final linear integrator always starts at zero.
Notes¶
Public coefficient arrays are owned by this object. Replays snapshot and
validate them again, so caller edits cannot bypass shape/domain admission.
The dense-if-f64-sequential-v1 profile orders input-column reductions
and separates multiplication/addition instead of using BLAS reductions.
- init(weights, biases, thresholds, T, initial_membrane_fraction, output_scale, output_mode)
- Copy and validate all coupled parameters before exposing the network.
- n_layers()
- Return the current number of connected weighted layers.
- replay(inputs)
- Replay explicit frames, optionally continuing independently owned states.
- run(x)
- Encode and simulate one input vector or a batch for the stored budget.
- rates(x)
- Decode accumulated responses into the source activation's units.
- classify(x)
- Return the first maximal response index for a vector or each batch row.
Module conversion.if_benchmark_cli¶
Function main(argv)¶
Run the actual bundled comparison with the current interpreter and explicit owner settings.
Parameters¶
argv : sequence of str or None Comparison arguments; None reads the actual command line.
Returns¶
int Actual comparison process exit status; no dependency/build side effects.
Raises¶
FileNotFoundError Installed resources and the source checkout's owning script are absent.
Module conversion.if_benchmark_identity¶
Function source_digests(resources)¶
Bind the benchmark and all maintained runtime counterparts to current source bytes.
The public and native owners are always read from the imported sc_neurocore
package, so a report binds the code that actually ran, whether that package is a
source checkout or an installed wheel.
Parameters¶
resources : Path or None
Directory holding the executing comparison scripts. None resolves the
installed package's conversion/benchmark_resources, or the owning
checkout's benchmarks when the package is a source tree.
Returns¶
dict of str to str Repository-relative owning source paths and their SHA-256 digests.
Raises¶
OSError The build declaration beside the comparison scripts cannot be read.
Function configured_artifacts(backends)¶
Require explicit installed native inputs and bind their actual bytes without building.
Parameters¶
backends : tuple of str Configured providers whose actual artifact bytes must be bound.
Returns¶
dict of str to str Declared native artifact names, Julia executable and locked-project digests.
Raises¶
KeyError, OSError Required owner configuration or its actual installed file is absent.
Module conversion.if_benchmark_order¶
Function measured_order()¶
Resolve host-matched measured native ordering without importing any native runtime.
Returns¶
tuple of str Native providers ordered by full-response warm latency; NumPy stays the floor.
Raises¶
RuntimeError Explicit comparison is malformed, stale, instrumented or mismatched with current runtime/source/configured artifacts. A different CPU uses static order.
Module conversion.if_benchmark_record¶
Function positive_integer(value)¶
Check an actual positive integer, excluding JSON booleans.
Parameters¶
value : object Untrusted numeric record field.
Returns¶
bool True only for a positive integral timing or repetition count.
Function validated_timing_order(record)¶
Require all five bit-matched corpora and derive ordering from actual raw warm samples.
Parameters¶
record : dict Parsed comparison after schema, runtime, source and artifact admission.
Returns¶
tuple of str Native runtimes sorted by equal-weight geometric mean warm call latency.
Raises¶
ValueError, KeyError, TypeError Incomplete corpus, invalid samples or inconsistent recorded aggregates.
Module conversion.if_dispatch¶
Function replay_backend(parameters, inputs, initial_state, trace, binary_inputs, max_working_bytes, backend)¶
Select an explicitly configured native replay or the always-available floor.
Parameters¶
parameters : IFParameters Owned finite coefficients and response semantics. inputs : array_like Explicit replay frames. initial_state : sequence of array_like or None Optional continuation states copied before execution. trace : bool Retain complete post-step state/event trajectories. binary_inputs : bool Require exact zero/one events when True. max_working_bytes : int Positive numeric replay buffer limit. backend : {'auto', 'numpy', 'rust', 'go', 'mojo', 'julia'} Auto uses a validated configured comparison, or the static native order, before NumPy.
Returns¶
IFReplayResult Owned responses and complete requested trajectories.
Raises¶
ValueError Unknown backend or invalid replay domains. RuntimeError Requested native library absent or incompatible.
Function resolve_replay_backend(backend)¶
Name the runtime a replay request executes on, without loading it.
Parameters¶
backend : {'auto', 'numpy', 'rust', 'go', 'mojo', 'julia'} Auto orders configured native providers by a validated optional comparison; without one, Rust then Go then Mojo then Julia. NumPy always uses the floor.
Returns¶
{'numpy', 'rust', 'go', 'mojo', 'julia'} The explicit name, or the provider auto resolves to under the current configuration. Requesting that name explicitly selects the same runtime.
Raises¶
ValueError Backend name is unsupported. RuntimeError The Julia opt-in is malformed, or the measured comparison is invalid.
Function select_native(backend)¶
Resolve the requested native runtime, including for empty input batches.
Parameters¶
backend : {'auto', 'numpy', 'rust', 'go', 'mojo', 'julia'} Auto orders configured native providers by a validated optional comparison; without one, Rust then Go then Mojo then Julia. NumPy always uses the floor.
Returns¶
NativeAPI or None Loaded native ownership API or the selected NumPy floor.
Raises¶
ValueError Backend name is unsupported. RuntimeError Explicit native configuration is absent or its library cannot load.
Module conversion.if_encoding¶
Function simulate_encoded(parameters, x, steps, input_mode, seed, max_working_bytes, backend)¶
Run row-major MT19937 events or constant current with bounded storage.
Parameters¶
parameters : IFParameters Owned and validated dense coefficients. x : array_like Finite input vector or batch in the unit interval. steps : int Positive timestep budget, at most 2**53. input_mode : {'poisson', 'constant'} Bernoulli events or direct bounded currents. seed : int Unsigned 32-bit MT19937 seed. max_working_bytes : int Positive numeric buffer budget, checked before encoding allocation.
backend : {"auto", "numpy", "rust", "go", "mojo", "julia"} Replay runtime selected once for the complete encoded call, including empty batches.
Returns¶
ndarray Accumulated output with the original vector/batch shape.
Raises¶
ValueError If encoding, shape, domains, seed or timestep budget are invalid. MemoryError If a block's numeric buffers exceed the declared byte budget.
Module conversion.if_inputs¶
Function prepare_replay(parameters, inputs, initial_state, trace, binary_inputs, max_working_bytes)¶
Admit and own complete frames and initial states before native execution.
Parameters¶
parameters : IFParameters Checked owned finite dense coefficients and final response mode. inputs : array_like Explicit time/batch/input bounded currents or binary events. initial_state : sequence of array_like or None Finite batch/output state per layer; None selects admitted preloads. trace : bool Include complete trace storage in the numeric reservation. binary_inputs : bool Require exact zero/one events when True. max_working_bytes : int Positive addressable numeric-buffer limit excluding caller/runtime storage.
Returns¶
tuple Owned contiguous float64 frames and independently owned initial states.
Raises¶
ValueError Invalid frame/state dimensions, storage domains or input values. MemoryError Numeric reservation exceeds the working byte budget. FloatingPointError Finite preload multiplication overflows.
Module conversion.if_julia¶
Class JuliaInterface¶
Keep the configured Julia module rooted while managing pointer calls and shutdown.
- init(runtime, module)
- Retain the supplying managed runtime and forbid calls once its exit hook is pending.
- replay(request, result)
- Call the complete native request through JuliaCall's registered-thread entry.
- buffer(handle, kind, index, view)
- Borrow a rooted numeric vector while keeping managed runtime entry safe.
- free(handle)
- Release an expired view owner's rooted storage through the managed runtime.
Function admitted_julia_runtime(executable, project, label)¶
Return the running JuliaCall runtime only if it is the exact configured one.
Parameters¶
executable, project : str
Resolved configured Julia executable and locked project.
label : str
Runtime user named in refusals, such as "Julia IF".
Returns¶
JuliaRuntime The imported JuliaCall module with one thread and Julia signal handling.
Raises¶
RuntimeError JuliaCall started with another executable, project, thread count or signal setting. ImportError JuliaCall is not installed.
Function load_julia()¶
Require explicit offline Julia configuration and obtain its owned replay interface.
Returns¶
NativeAPI Managed Julia calls sharing the complete ABI-one request/view contract.
Raises¶
RuntimeError Runtime/project/versions/configuration unavailable or incompatible.
Module conversion.if_julia_configuration¶
Function julia_configuration(user)¶
Admit explicit matching Julia runtime options before importing JuliaCall.
Parameters¶
user : str
Runtime user named in every refusal, such as "Julia QCFS".
Returns¶
tuple of str Resolved installed executable and locked project paths.
Raises¶
RuntimeError Options conflict, dependencies differ or required offline settings are absent.
Notes¶
A successful admission is reused while every setting, option and file identity it read is unchanged, so each managed call does not reparse the locked project; any change repeats the complete admission.
Module conversion.if_julia_types¶
Class JuliaNativeModule¶
Julia function values accepting scalar C addresses and ABI metadata.
Class QCFSJuliaModule¶
Julia QCFS function values accepting integer addresses and element counts.
Class JuliaNamespace¶
A Julia namespace containing a maintained rooted module.
Class JuliaThreads¶
Active Julia default-pool worker count, fixed during runtime initialization.
Class JuliaOptions¶
Active Julia signal handling selected when the runtime initialized.
Class JuliaBase¶
The Julia include function value for loading source into a rooted namespace.
Class JuliaMain¶
The managed main namespace used solely for source loading.
Class JuliaRuntime¶
Configured runtime fields; import must not resolve or install dependencies.
Module conversion.if_native¶
Function load_native(path)¶
Load a configured C library and require the exact replay ownership ABI.
Parameters¶
path : str Explicit owner-configured native library; no build or download occurs.
Returns¶
NativeAPI Loaded ABI-one replay, buffer and release functions.
Raises¶
RuntimeError Library unavailable, entry points absent or ABI version incompatible.
Function replay_native(api, parameters, inputs, initial_state, trace, binary_inputs, max_working_bytes)¶
Replay through the checked native C boundary with automatically owned views.
Parameters¶
api : NativeAPI Configured ABI-one native library. parameters : IFParameters Owned validated coefficients; borrowed throughout the native call. inputs : array_like Explicit time/batch/input unit currents or binary events. initial_state : sequence of array_like or None Optional independently copied batch/output states. trace : bool Retain complete state/event trajectories. binary_inputs : bool Require exact zero/one events when True. max_working_bytes : int Positive numeric reservation excluding caller/runtime overhead.
Returns¶
IFReplayResult Native-owned arrays whose views retain their supplying library/owner.
Raises¶
ValueError Invalid input, geometry, coefficients or native domain refusal. MemoryError Native or shared numeric buffer reservation refused. FloatingPointError Finite arithmetic overflow refused by the native kernel. RuntimeError Malformed native ownership or internal native failure.
Module conversion.if_native_types¶
Class LayerSpec¶
Native ABI-one borrowed dense layer and optional initial-state descriptor.
Class ReplayRequest¶
ABI-one request with retained caller-owned descriptors and arrays.
Class BufferView¶
Borrowed row-major result storage, live until its opaque owner is freed.
Class NativeAPI¶
Loaded library or managed-runtime root and typed ownership/buffer entry points.
Class NativeOwner¶
Release native storage only after all arrays retaining this owner have expired.
- init(api, handle)
- Bind one successful native allocation to automatic final-owner cleanup.
Module conversion.if_parameters¶
Class IFParameters¶
Owned row-major coefficients and the declared final-layer response.
Function real_array(values, name)¶
Copy real numeric data to owned contiguous float64 storage.
Parameters¶
values : array_like Boolean, integer or floating input data. name : str Parameter name included in refusal messages.
Returns¶
ndarray Finite, owned float64 values in C order.
Raises¶
ValueError If the data is nonreal, nonfinite or cannot be represented in float64.
Function parameter_snapshot(weights, biases, thresholds, initial_membrane_fraction, output_mode)¶
Validate coupled layer dimensions and freeze independent parameter copies.
Parameters¶
weights : sequence of array_like Output-by-input weight matrices, connected in sequence. biases : sequence of array_like or None Per-step output currents, one per layer; None denotes absent bias. thresholds : sequence of float Positive finite IF thresholds, one per layer. initial_membrane_fraction : float Finite default membrane offset in threshold units. output_mode : {'spikes', 'linear'} Final IF spike count or integrated linear readout.
max_working_bytes : int Numeric buffer budget checked before owned coefficient copies.
layer_membrane_fractions : sequence of float, optional Per-layer preloads; None repeats the global membrane fraction.
Returns¶
IFParameters Validated owned coefficients for a complete replay.
Raises¶
ValueError If lengths, dimensions, parameter domains or output mode are invalid.
Module conversion.if_replay¶
Class IFReplayResult¶
Owned output responses, final states and optional complete traces.
A spiking final layer produces spike counts; a linear final layer produces its integrated current. Final states include the linear readout integrator. Trace tuples contain every layer's post-reset state and only IF spike events.
Function replay_dense_if(parameters, inputs)¶
Replay real input frames with inclusive thresholds and subtractive reset.
Parameters¶
parameters : IFParameters
Owned checked coefficients and final response mode.
inputs : array_like
Explicit (steps, batch, input_neurons) frames in [0, 1].
initial_state : sequence of array_like, optional
Finite (batch, output_neurons) states, one per layer. Caller-owned
buffers are copied. Default IF states use the configured membrane shift;
a linear readout starts from zero.
trace : bool
Retain each post-step state and every IF event when True.
binary_inputs : bool
Require exact zero/one input events. False admits bounded current drive.
max_working_bytes : int Numeric buffer reservation checked before copying frames or states.
Returns¶
IFReplayResult Incremental spike counts or cumulative linear readout and owned states.
Raises¶
ValueError If input shape, values or initial-state dimensions are invalid. FloatingPointError If a finite-input replay overflows its numerical state. MemoryError If owned buffers exceed the declared working byte budget.
Notes¶
Input columns are accumulated in ascending order with separate float64 multiply and add operations. Bias follows the complete dot product. Layers consume the preceding layer's events within the same timestep. Each IF emits at most one spike, including when the membrane equals its threshold. Empty time or batch axes preserve initial states and emit no events. A linear readout retains its supplied cumulative integral.
Module conversion.if_resources¶
Function admit_parameter_storage(weights, biases, max_working_bytes)¶
Admit coefficient snapshots and return their float64 element count.
Parameters¶
weights, biases : sequence of array_like Coefficients whose metadata is inspected before owned float64 copies. max_working_bytes : int Positive addressable byte budget. Caller-owned storage and interpreter overhead are excluded; two complete coefficient copies are reserved.
Returns¶
int Total number of weight and bias elements.
Raises¶
ValueError If the budget is not a positive addressable integer. MemoryError If coefficient snapshots exceed the declared budget.
Function admit_replay_buffers(weights, biases, shape)¶
Admit a conservative portable bound on one replay's numeric buffers.
Parameters¶
weights, biases : sequence of ndarray Checked connected dense coefficients. shape : tuple of int Time, batch and input-neuron dimensions. trace, linear : bool Trace retention and final linear-integrator mode. max_working_bytes : int Operator-selected positive addressable byte budget.
Returns¶
int Reserved numeric bytes, excluding caller buffers and runtime overhead.
Raises¶
MemoryError If the complete reservation exceeds the supplied budget.
Notes¶
Reserve eight bytes per element of 2P + 2F + 2S + 2O + H + 5M + I:
coefficients P, full frames F, all states S, output O, requested state/event
traces H, largest layer M and one input frame I. Doubled buffers and five
largest-layer buffers cover validation, snapshots and arithmetic temporaries.
Python integer arithmetic cannot wrap the reservation.
Module conversion.loss_report¶
Class ConversionLossReport¶
Measured agreement between a source ANN and its converted SNN.
Attributes¶
schema_version : str
sc-neurocore.conversion-loss-report.v1.
samples : int
Number of labelled samples both networks classified.
classes : int
Width of the output both networks produce.
timesteps : int
The converted network's timestep budget.
input_mode : {'constant', 'poisson'}
Declared input encoding of the converted network.
seed : int
Poisson seed of the first batch; batch k uses (seed + k) mod 2**32.
batch_size : int
Samples per converted-network call.
backend : {'numpy', 'rust', 'go', 'mojo', 'julia'}
Replay runtime every converted batch executed on.
source_accuracy : float
Fraction of samples the source ANN labels correctly.
converted_accuracy : float
Fraction of samples the converted SNN labels correctly.
accuracy_drop : float
source_accuracy - converted_accuracy; positive is a loss.
agreement : float
Fraction of samples on which both networks predict the same class.
rate_mean_abs_error : float
Mean absolute difference between decoded SNN rates and source outputs.
rate_max_abs_error : float
Largest such difference.
source_sha256 : str
Digest of every source parameter and buffer, by name, dtype and shape.
converted_sha256 : str
Digest of the converted coefficients and replay semantics.
data_sha256 : str
Digest of the evaluated inputs, their shape and their labels.
numerical_profile : str
Arithmetic profile of the converted replay.
- to_public_dict()
- Return the report as JSON-ready fields.
Function converted_sha256(snn)¶
Digest a converted network's coefficients and replay semantics.
Parameters¶
snn : ConvertedSNN Network whose current public coefficients are digested.
Returns¶
str Hex SHA-256 over weights, biases, thresholds, budget, preloads, output scale and output mode.
Function source_sha256(model)¶
Digest every parameter and buffer of a PyTorch module.
Parameters¶
model : torch.nn.Module Module whose state is digested in name order.
Returns¶
str Hex SHA-256 over each state entry's name, dtype, shape and C-ordered storage bytes. PyTorch runs only on little-endian hosts, so the bytes are little-endian for every dtype, including those NumPy lacks.
Function data_sha256(inputs, labels)¶
Digest evaluated inputs and labels.
Parameters¶
inputs : ndarray Float64 samples in their source shape. labels : ndarray Int64 class labels, one per sample.
Returns¶
str Hex SHA-256 over the input shape and values followed by the labels.
Function measure_conversion_loss(model, snn, inputs, labels)¶
Classify labelled samples with a source ANN and its converted SNN and compare.
Parameters¶
model : torch.nn.Module
Source network. It runs under no_grad in inference mode on the
device and dtype of its first parameter; every module's training flag
is restored afterwards.
snn : ConvertedSNN
The network converted from model.
inputs : array_like
(samples, *source_shape) values in [0, 1]. The converted
network receives each sample flattened in C order.
labels : array_like
(samples,) integer classes in [0, classes).
input_mode : {'constant', 'poisson'}
Declared encoding for the converted network.
seed : int
Unsigned 32-bit Poisson seed of the first batch.
batch_size : int
Positive number of samples per call of either network.
max_working_bytes : int
Numeric buffer budget of each converted-network call.
backend : {'auto', 'numpy', 'rust', 'go', 'mojo', 'julia'}
Replay runtime. Auto is resolved once, and every batch runs on the
runtime the report names.
Returns¶
ConversionLossReport Accuracies, agreement, rate error, executed runtime and digests.
Raises¶
ValueError Empty, non-finite or malformed inputs, invalid labels, an invalid batch size or seed, or outputs of different widths.
Module conversion.model_trace¶
Class ConversionTracer¶
Retain QCFS as an atomic source activation alongside Torch leaf modules.
- is_leaf_module(m, module_qualified_name)
- Keep actual QCFS invocations instead of tracing threshold validation.
Function capture_inference_graph(model, max_working_bytes)¶
Trace an independent inference copy and restore every global random generator.
Parameters¶
model : nn.Module Source network; its tensors, module modes and hook registries are retained. max_working_bytes : int Positive numeric budget checked before copying source tensor storage.
Returns¶
GraphModule Runnable inference graph retaining every actual forward invocation.
Raises¶
MemoryError If independent source tensor storage exceeds the declared byte budget. ValueError If the source forward requires untraceable data-dependent control flow.
Notes¶
User forward code executes during symbolic tracing. Model state is isolated by deepcopy; Python, NumPy, Torch CPU and accelerator generator states are restored on both paths, serialised against other conversions in the process. This does not undo external effects performed by custom user forward code.
Module conversion.qcfs¶
Class QCFSActivation¶
QCFS activation: quantized clip-floor-shift ReLU replacement.
For T timesteps and threshold theta: QCFS(x) = clip(floor(x * T / theta + 0.5), 0, T) * theta / T
This quantizes activations to T+1 levels in [0, theta], matching the achievable spike rates of an IF neuron over T timesteps.
Parameters¶
T : int
Number of simulation timesteps, 1 <= T <= 2**32 - 1: the step
domain every native counterpart shares.
theta : float
Firing threshold (default 1.0).
learn_theta : bool
Make threshold trainable (default False).
- init(T, theta, learn_theta)
- Create a positive finite threshold and positive integer rate grid.
- forward(x)
- Quantise activations to the spike-rate grid with a straight-through gradient.
- extra_repr()
- Return the compact PyTorch module representation.
Module conversion.qcfs_dispatch¶
Function select_qcfs_native(backend)¶
Resolve the requested QCFS runtime; None selects NumPy.
Parameters¶
backend : {'auto', 'numpy', 'rust', 'go', 'mojo', 'julia'}
Auto takes the first configured provider of QCFS_AUTO_ORDER (Mojo,
Rust, Go, Julia) and otherwise NumPy. An explicit native backend
requires its configuration; explicit NumPy never reads any.
Returns¶
QCFSNativeAPI or None Loaded provider, or None for NumPy.
Raises¶
ValueError Backend name is unsupported. RuntimeError Explicit configuration is absent, or a configured provider cannot load.
Function qcfs_forward(x, steps, theta)¶
Quantise activations onto the QCFS rate lattice without PyTorch.
Parameters¶
x : array_like
Real activations of any shape.
steps : int
Simulation steps, 1 <= steps <= 2**32 - 1.
theta : float
Finite positive firing threshold.
backend : {'auto', 'numpy', 'rust', 'go', 'mojo', 'julia'}
Runtime selection; see select_qcfs_native.
Returns¶
numpy.ndarray
float64 floor(clip(x * T / theta + 0.5, 0, T)) * theta / T with the
shape of x; infinities saturate and NaN stays NaN.
Raises¶
ValueError Step count, threshold or backend name invalid. TypeError Non-real activations. RuntimeError Selected runtime unavailable or a provider refused admitted input.
Function qcfs_backward(x, upstream, steps, theta)¶
Evaluate QCFS straight-through derivatives without PyTorch.
Parameters¶
x, upstream : array_like
Real activations and upstream gradients of one shape.
steps : int
Simulation steps, 1 <= steps <= 2**32 - 1.
theta : float
Finite positive firing threshold.
backend : {'auto', 'numpy', 'rust', 'go', 'mojo', 'julia'}
Runtime selection; see select_qcfs_native.
Returns¶
tuple of numpy.ndarray
Input derivative and each element's threshold derivative, as
QCFSActivation autograd yields for a one-element batch; summing the
second array gives a shared threshold's gradient up to summation order.
Raises¶
ValueError Step count, threshold, backend name or shape mismatch. TypeError Non-real activations or gradients. RuntimeError Selected runtime unavailable or a provider refused admitted input.
Module conversion.qcfs_kernel¶
Function checked_qcfs_parameters(steps, theta)¶
Admit the shared QCFS step domain and a finite positive threshold.
Parameters¶
steps : int
Simulation steps and quantisation intervals, 1 <= steps <= 2**32 - 1.
theta : float
Firing threshold and upper activation bound.
Returns¶
tuple of (int, float) The admitted step count and threshold.
Raises¶
ValueError Step count outside the shared domain or threshold not finite and positive.
Function qcfs_values(values, name)¶
Copy real activations into one contiguous float64 array.
Parameters¶
values : array_like Real integer or floating activations of any shape. name : str Argument name used in the refusal message.
Returns¶
numpy.ndarray C-contiguous float64 copy with the input shape.
Raises¶
TypeError Boolean, complex, object or other non-real input.
Function reference_forward(x, steps, theta)¶
Quantise admitted activations onto the shifted clipped rate lattice.
Parameters¶
x : numpy.ndarray Contiguous float64 activations. steps, theta : int, float Admitted step count and threshold.
Returns¶
numpy.ndarray
floor(clip(x * T / theta + 0.5, 0, T)) * theta / T; NaN stays NaN.
Function reference_backward(x, upstream, steps, theta)¶
Return per-element input and threshold derivatives of the surrogate.
Parameters¶
x, upstream : numpy.ndarray Contiguous float64 activations and equally shaped upstream gradients. steps, theta : int, float Admitted step count and threshold.
Returns¶
tuple of numpy.ndarray
Input derivative (upstream on the open interior 0 < s < T, zero
elsewhere) and each element's threshold contribution
upstream * floor(c) / T plus, on the interior, -upstream * x / theta
in autograd's operation order: exactly the threshold gradient a
one-element batch receives. Summing the second array reduces a shared
threshold's gradient up to summation order.
Module conversion.qcfs_native¶
Class QCFSNativeAPI¶
A loaded provider root and its forward and backward array entry points.
Parameters¶
library : object
Loaded library or managed Julia interface kept alive by this record.
forward : callable
(steps, theta, x, count, output) -> status over integer addresses.
backward : callable
(steps, theta, x, upstream, count, input_gradient, threshold_gradient)
-> status over integer addresses.
Class QCFSJulia¶
Keep the Julia QCFS module rooted and refuse calls once shutdown begins.
- init(module)
- Retain the module and its bound functions; stop calls once exit is pending.
- forward(steps, theta, x, count, output)
- Quantise through the managed runtime; see
sc_qcfs_forward. - backward(steps, theta, x, upstream, count, inputs, thresholds)
- Differentiate through the managed runtime; see
sc_qcfs_backward.
Function load_qcfs_library(path)¶
Load a configured C library and require QCFS array ABI version one.
Parameters¶
path : str Explicit owner-configured shared library; nothing is built or downloaded.
Returns¶
QCFSNativeAPI Typed forward and backward entry points of the loaded library.
Raises¶
RuntimeError Library unavailable, entry points absent or ABI version incompatible.
Function load_qcfs_julia()¶
Require explicit offline Julia configuration and return the QCFS interface.
Returns¶
QCFSNativeAPI Managed Julia calls sharing the QCFS array contract.
Raises¶
RuntimeError Runtime, project, versions or configuration unavailable or incompatible, or the runtime is closing.
Module conversion.random_custody¶
Function preserved_random_state()¶
Restore every global generator the body may advance, even when it raises.
Covers Python random, NumPy's legacy global generator, the PyTorch CPU
generator and the generator of every device of the current accelerator type
(torch.accelerator), through torch.random.fork_rng. Sections are
serialised across threads; other code that draws concurrently outside a
section is not isolated.
Yields¶
None Control while the caller's states are held.
Module conversion.source_calibration¶
Class ActivationMeasurement¶
Retain independent observed tensors for the requested source invocations.
- init(graph, names)
- Initialize actual graph execution and an empty observation map.
- run_node(n)
- Snapshot each selected actual tensor before subsequent in-place operators.
Function calibrate_source_nodes(plan, data, percentile)¶
Measure source ReLU invocation thresholds with inference graph execution.
Parameters¶
plan : SourcePlan Independent source graph and actual activation metadata. data : Tensor Nonempty finite source-format calibration input. percentile : float Finite percentile in the closed interval zero to one hundred.
Returns¶
dict of str to float Positive scales indexed by actual activation node name.
Raises¶
MemoryError If source input validation and activation buffers exceed the plan budget. ValueError If inputs, percentile or observed tensors are invalid.
Module conversion.source_graph¶
Class SourceActivation¶
Source activation kind, exact invocation and learned quantization metadata.
Class SourceLayer¶
One owned affine coefficient set followed by its actual source activation.
Class SourcePlan¶
Runnable source inference graph and the supported target's lowered layers.
Function compile_source_graph(model, max_working_bytes)¶
Lower a supported straight-line source graph using actual execution order.
Parameters¶
model : nn.Module Source network. Repeated/shared calls remain distinct invocations. max_working_bytes : int Budget for independent source storage and inserted identity coefficients.
Returns¶
SourcePlan Owned dense coefficients with per-invocation activation metadata.
Raises¶
ValueError If inputs, outputs or operators cannot be represented by the dense target. MemoryError If source copying or inserted identity storage exceeds the budget.
Notes¶
Consecutive affine maps are composed without inserting an IF nonlinearity. Composition uses float64 arithmetic; source/target loss still needs measured acceptance, including differences from the source dtype's rounding order.
Module conversion.target_report¶
Class LayerCalibration¶
How one layer was fitted into the target format, and what that cost.
Attributes¶
index : int
Zero-based layer position.
drive : {'analog', 'spikes'}
What the layer integrates; only a spike-driven layer's replay is exact.
readout : {'spiking', 'linear'}
Whether the layer fires or integrates its current as the readout.
scale_exponent : int
e of the scale 2**e applied to the layer's normalised values.
threshold_code : int
The threshold as a stored integer; zero for a linear readout.
measured_peak : float
Largest pre-reset membrane magnitude on the calibration samples, in
normalised threshold units.
headroom_bits : float or None
log2 of the representable maximum over the scaled peak; None
when the membrane never moved.
weights : int
Number of weights.
zeroed_weights : int
Non-zero weights that round to zero.
weight_max_abs_error, weight_rms_error : float
Rounding error of the weights in normalised units.
bias_max_abs_error : float
Rounding error of the bias; zero without a bias.
preload_exact : bool
Whether the initial membrane preload lies on the grid.
overflow_steps : int
Sample-steps at which the rounded network's membrane left the range.
Class TargetReport¶
A converted network fitted into one target format and measured there.
Attributes¶
schema_version : str
sc-neurocore.conversion-target-report.v1.
profile : dict
The target profile's identity and numeric format.
compatible : bool
Every layer fits with a threshold of at least one grid step and no
measured overflow.
refusals : list of str
Why the network is not compatible; empty when it is.
layers : list of LayerCalibration
One entry per layer.
samples, timesteps : int
Calibration samples and the network's timestep budget.
input_mode : str
constant: every sample drives the first layer as a current.
backend : str
Replay runtime both networks ran on.
agreement : float
Fraction of samples on which both networks predict the same class.
output_max_abs_difference : float
Largest decoded-output difference between the two networks.
float_accuracy, quantized_accuracy, accuracy_drop : float or None
Present when labels were given.
exact_accumulation : bool
Whether spike-driven layers' replay equals integer accumulation: the
format is at most 53 bits wide and their preloads lie on the grid.
converted_sha256, data_sha256 : str
Digests of the unrounded network and of the calibration samples.
arithmetic : str
What the measurement emulates and what it does not.
- to_public_dict()
- Return the report as JSON-ready fields.
Function calibrate_for_target(snn, profile, inputs, labels)¶
Fit snn into profile's fixed-point format and measure the rounded network.
Parameters¶
snn : ConvertedSNN
Converted network in normalised threshold units.
profile : HardwareProfile
Target format from :mod:sc_neurocore.compiler.platforms.
inputs : array_like
(samples, input_neurons) calibration values in [0, 1], driven as
constant currents for the network's timestep budget.
labels : array_like, optional
(samples,) integer classes; accuracies are reported when given.
batch_size : int
Positive samples per replay.
max_working_bytes : int
Numeric buffer budget of each replay chunk.
backend : {'auto', 'numpy', 'rust', 'go', 'mojo', 'julia'}
Replay runtime, resolved once and named in the report.
Returns¶
TargetReport Per-layer scales and rounding costs, measured ranges, both networks' agreement and, with labels, accuracies.
Raises¶
ValueError Empty or out-of-range inputs, invalid labels or batch size.
Module core.bipolar¶
Function bipolar_encode(value, L, rng)¶
Encode a bipolar value in [-1, 1] as a Bernoulli bitstream.
p = (value + 1) / 2. Bitstream has P(bit=1) = p.
Function bipolar_decode(bits)¶
Decode a bitstream back to bipolar value in [-1, 1].
value = 2 * mean(bits) - 1.
Function bipolar_multiply(a, b)¶
XNOR gate: bipolar multiplication.
XNOR(a, b) = NOT(XOR(a, b)) = 1 when a == b, 0 when a != b. E[XNOR] decodes to v_a * v_b in bipolar domain.
Function bipolar_mac(inputs, weights, L, seed)¶
Bipolar multiply-accumulate: weighted sum via XNOR + popcount.
Parameters¶
inputs : (N,) float array, values in [-1, 1] weights : (M, N) float array, values in [-1, 1] L : int, bitstream length seed : int
Returns¶
(M,) float array, dot product results (sum of N bipolar products)
Function bipolar_sc_layer(inputs, weights, bias, L, seed, activation)¶
Single SC layer: bipolar MAC + optional bias + activation.
Parameters¶
inputs : (N,) float, normalised to [-1, 1] weights : (M, N) float, normalised to [-1, 1] bias : (M,) float or None L : bitstream length activation : "relu", "none", or "tanh"
Returns¶
(M,) float, layer output in [-1, 1]
Function float_to_bipolar_weights(weight_tensor)¶
Normalise float weights to [-1, 1] for bipolar SC.
Preserves sign information (unlike unipolar to_sc_weights).
Module core.mdl_parser¶
Class MDLSpecification¶
Serializable MDL payload containing architecture and state sections.
Class MindDescriptionLanguage¶
Parser for the Mind Description Language (MDL).
A universal, substrate-independent format for archiving an agent's architecture and state.
- encode(orchestrator, agent_name)
- Export the orchestrator state to a YAML MDL string.
- decode(mdl_string)
- Parse an MDL string back into a dictionary for reconstruction.
Module core.orchestrator¶
Class CognitiveOrchestrator¶
Central orchestrator that sequences registered modules into a pipeline.
Connects disparate processing modules and routes a :class:TensorStream
through them in execution order.
- register_module(name, module_obj)
- Register a named module object for later pipeline execution.
- set_attention(module_name)
- Focus orchestrator resources on a specific module.
- execute_pipeline(pipeline, initial_input)
- Execute a sequence of modules, handling TensorStream conversions.
Module core.sc_correlation¶
Class CorrelationDiagnostic¶
Result of a two-stream SC correlation check.
Attributes¶
value_a, value_b : float
Decoded one-probabilities of the two streams.
scc : float
Estimated stochastic cross-correlation in [-1, 1].
predicted_and_bias : float
AND bias the SCC implies via multiply_correlation_bias.
observed_and_bias : float
AND bias measured directly from the streams.
flagged : bool
Whether abs(predicted_and_bias) exceeds the configured threshold.
Function estimate_scc(bits_a, bits_b)¶
Estimate the stochastic cross-correlation of two equal-length bitstreams.
Parameters¶
bits_a, bits_b : array-like of {0, 1} Equal-length observed SC bitstreams.
Returns¶
float
SCC in :math:[-1, 1]. Returns 0.0 for a degenerate stream (all-zero
or all-one), where correlation is not identifiable.
Raises¶
ValueError If the streams are empty, non-binary, or of unequal length.
Function observed_and_bias(bits_a, bits_b)¶
Return the measured AND bias :math:a/N - p_a p_b of two streams.
Parameters¶
bits_a, bits_b : array-like of {0, 1} Equal-length observed SC bitstreams.
Returns¶
float
The signed deviation of the observed one-probability of AND from the
independent product :math:p_a p_b.
Function correlation_diagnostic(bits_a, bits_b)¶
Diagnose AND-composition correlation bias between two SC bitstreams.
Estimates the SCC, converts it to the predicted AND bias through
:func:sc_neurocore.core.sc_error_bounds.multiply_correlation_bias, compares
it with the directly-measured bias, and flags streams whose predicted bias
exceeds bias_threshold.
Parameters¶
bits_a, bits_b : array-like of {0, 1}
Equal-length observed SC bitstreams.
bias_threshold : float, optional
Absolute predicted-bias magnitude above which the pair is flagged
(default 0.01). Must be non-negative.
Returns¶
CorrelationDiagnostic Decoded values, SCC, predicted and observed AND bias, and the flag.
Module core.sc_error_bounds¶
Class SCErrorBound¶
Summary of the accuracy of one encoded SC value.
Attributes¶
value : float
The encoded value.
length : int
Bitstream length :math:N.
bipolar : bool
Whether the value is in the bipolar domain.
variance : float
Estimator variance.
std_error : float
Estimator standard error :math:\sqrt{\text{variance}}.
ci95_halfwidth : float
Half-width of the 95% normal-approximation confidence interval
(:math:1.959964 \times \text{std\_error}).
Function bernoulli_variance(value, length)¶
Variance of the decoded unipolar SC estimate :math:\hat p = k/N.
Parameters¶
value : float
The encoded probability :math:p \in [0, 1].
length : int
Bitstream length :math:N (positive).
Returns¶
float
:math:p (1 - p) / N.
Function bernoulli_std_error(value, length)¶
Return the standard error :math:\sqrt{p(1-p)/N} of a unipolar SC estimate.
Function bipolar_variance(value, length)¶
Variance of the decoded bipolar SC estimate for :math:v \in [-1, 1].
With :math:p = (v + 1)/2 and :math:\hat v = 2 \hat p - 1,
:math:\operatorname{Var}(\hat v) = 4 \operatorname{Var}(\hat p)
= (1 - v^2)/N.
Parameters¶
value : float
Bipolar value :math:v \in [-1, 1].
length : int
Bitstream length :math:N (positive).
Returns¶
float
:math:(1 - v^2)/N.
Function bipolar_std_error(value, length)¶
Return the standard error :math:\sqrt{(1 - v^2)/N} of a bipolar SC estimate.
Function multiply_variance(value_a, value_b, length)¶
Variance of a unipolar AND product of two independent streams.
The output stream is Bernoulli with value :math:p_a p_b, so its decoded
estimate has variance :math:p_a p_b (1 - p_a p_b) / N.
Parameters¶
value_a, value_b : float
Encoded probabilities in :math:[0, 1].
length : int
Bitstream length :math:N (positive).
Returns¶
float
:math:p_a p_b (1 - p_a p_b) / N.
Function multiply_correlation_bias(value_a, value_b, scc)¶
Signed bias of a unipolar AND from stochastic cross-correlation.
For independent streams :math:E[\text{AND}] = p_a p_b. With stochastic
cross-correlation :math:\rho \in [-1, 1] (Alaghi & Hayes), the joint
one-probability moves linearly toward its comonotone bound
:math:\min(p_a, p_b) for :math:\rho > 0 and its countermonotone bound
:math:\max(0, p_a + p_b - 1) for :math:\rho < 0:
.. math:: E[\text{AND}] = p_a p_b + \begin{cases} \rho\,(\min(p_a, p_b) - p_a p_b) & \rho \ge 0 \ \rho\,(p_a p_b - \max(0, p_a + p_b - 1)) & \rho < 0. \end{cases}
Parameters¶
value_a, value_b : float
Encoded probabilities in :math:[0, 1].
scc : float
Stochastic cross-correlation :math:\rho \in [-1, 1].
Returns¶
float
The signed bias :math:E[\text{AND}] - p_a p_b.
Function mux_add_variance(value_a, value_b, length)¶
Variance of a fair-select MUX scaled adder of two streams.
A 2:1 multiplexer with select :math:s \sim \mathrm{Bernoulli}(1/2) emits a
stream of value :math:q = (p_a + p_b)/2, whose estimate has variance
:math:q (1 - q) / N.
Parameters¶
value_a, value_b : float
Encoded probabilities in :math:[0, 1].
length : int
Bitstream length :math:N (positive).
Returns¶
float
:math:q (1 - q) / N with :math:q = (p_a + p_b)/2.
Function dot_product_variance(values_a, values_b, length)¶
Variance of a MUX-tree unipolar dot product of two independent vectors.
The scaled dot product :math:\frac{1}{K}\sum_k \text{AND}(a_k, b_k) of
length :math:K has variance
:math:\frac{1}{K^2 N}\sum_k a_k b_k (1 - a_k b_k), whose standard error
grows as :math:O(1/\sqrt{K N}) — the SC analogue of the
:math:\sqrt{K}\,u inner-product growth of Connolly & Higham (2025).
Parameters¶
values_a, values_b : list of float
Equal-length vectors of probabilities in :math:[0, 1].
length : int
Bitstream length :math:N (positive).
Returns¶
float Variance of the scaled dot-product estimate.
Function low_discrepancy_error_bound(length)¶
Deterministic error bound :math:1/N for a low-discrepancy SC source.
Sobol/Halton bitstreams are deterministic: a value representable at
resolution :math:1/N is encoded exactly, and any value is within
:math:1/N. This replaces the pseudo-random :math:O(1/\sqrt N) standard
error with a hard :math:O(1/N) bound (Najafi, Lilja & Riedel 2018).
Parameters¶
length : int
Bitstream length :math:N (positive).
Returns¶
float
:math:1 / N.
Function hoeffding_confidence(length, epsilon)¶
Distribution-free confidence that :math:|\hat p - p| < \epsilon.
Hoeffding's inequality gives
:math:P(|\hat p - p| \ge \epsilon) \le 2 e^{-2 N \epsilon^2}, so the
confidence is :math:\max(0, 1 - 2 e^{-2 N \epsilon^2}).
Parameters¶
length : int
Bitstream length :math:N (positive).
epsilon : float
Absolute error tolerance in :math:(0, 1].
Returns¶
float
The confidence lower bound in :math:[0, 1].
Function hoeffding_min_length(epsilon, confidence)¶
Smallest :math:N guaranteeing confidence at tolerance epsilon.
Inverting Hoeffding's bound,
:math:N \ge \lceil \ln(2 / (1 - c)) / (2 \epsilon^2) \rceil.
Parameters¶
epsilon : float
Absolute error tolerance in :math:(0, 1].
confidence : float
Target confidence :math:c \in [0, 1).
Returns¶
int The minimum distribution-free bitstream length.
Function min_length_for_std_error(value, target_std)¶
Smallest :math:N whose SC standard error is at most target_std.
Unipolar: :math:N \ge \lceil p(1-p) / \sigma^2 \rceil; bipolar:
:math:N \ge \lceil (1 - v^2) / \sigma^2 \rceil.
Parameters¶
value : float
Encoded value: :math:p \in [0, 1] (unipolar) or :math:v \in [-1, 1]
(bipolar).
target_std : float
Target standard error :math:\sigma > 0.
bipolar : bool, optional
Interpret value in the bipolar domain (default False).
Returns¶
int The minimum bitstream length (at least 1).
Function sc_error_bound(value, length)¶
Summarise the SC accuracy of one encoded value as an :class:SCErrorBound.
Parameters¶
value : float
Encoded value: :math:p \in [0, 1] (unipolar) or :math:v \in [-1, 1]
(bipolar).
length : int
Bitstream length :math:N (positive).
bipolar : bool, optional
Interpret value in the bipolar domain (default False).
Returns¶
SCErrorBound Variance, standard error, and 95% confidence half-width.
Module core.tensor_stream¶
Class TensorStream¶
Unified tensor container for sc-neurocore.
Handles automatic conversion between the probability, bitstream, and quantum domains.
- from_prob(cls, probs)
- Create a tensor stream whose data is already in probability form.
- to_bitstream(length)
- Convert probability-domain data into Bernoulli bitstreams.
- to_prob()
- Convert supported domains into probability-domain tensors.
- to_quantum()
- Convert probability-domain data into two-amplitude quantum encoding.
Module core.types¶
Class DecorrelationStrategy¶
Decorrelation strategies for stochastic bitstreams.
Class ComputeMode¶
Compute mode for a layer.
Class NeuronType¶
Supported neuron models.
Class HardwareBudget¶
Unified FPGA resource budget (shared by Optimizer, NAS, Runtime).
- utilisation(luts, ffs, bram, dsp)
- Return resource utilisation fractions against this budget.
Class ResourceReport¶
Unified resource consumption report.
- meets_budget(budget)
- Return True when all tracked resources fit within a budget.
- summary()
- Render the resource report as a compact human-readable string.
Class LayerSpec¶
Layer specification usable by Optimizer, NAS, and Runtime.
This is the shared representation — each subsystem can extend it but all core resource estimation uses this base.
- estimate_luts()
- Unified LUT estimation shared across all subsystems.
- estimate_power_mw()
- Estimate layer power in milliwatts from mode and workload size.
- estimate_accuracy()
- Estimate stochastic-computing accuracy from mode and bitstream length.
Function estimate_network(layers)¶
Estimate total resources for a network of layers.
Module dashboard.text_dashboard¶
Class SCDashboard¶
Simple CLI dashboard for monitoring SC simulation rates.
- init(n_neurons)
- Create a dashboard with one rolling history per neuron.
- update(firing_rates, step)
- Append one frame of firing rates and render the dashboard.
Module datasets.encoders¶
Class EventBinning¶
Bin camera events into a binary spike tensor.
An event at t ms lands in step floor(t / dt_ms); events at or after
n_steps * dt_ms are dropped, never merged into the last step. With
polarity="separate" ON and OFF events have their own channels (OFF
first), with "merge" they share one. An event outside the sensor or
before time zero is refused rather than clipped.
Attributes¶
dt_ms:
Step length in milliseconds.
n_steps:
Number of steps in the window.
width, height:
Sensor geometry in pixels.
polarity:
"separate" or "merge".
- post_init()
- Refuse a setting the declaration could not state faithfully.
- channels()
- Channels per step: pixels, twice over when polarities are separate.
- declaration()
- Return the full description, enough to rebuild this encoder.
- digest()
sha256:over the declaration.- encode(events)
- Bin
(N, 4)events with columnsx, y, polarity, t_ms.
Class PoissonRates¶
Encode per-step firing probabilities as seeded Bernoulli spike trains.
Attributes¶
n_steps:
Number of steps.
dt_ms:
Step length; the probability per step is rate * dt_ms, clipped
to [0, 1].
seed:
Generator seed; the same seed and input give the same spikes.
- post_init()
- Refuse a setting the declaration could not state faithfully.
- declaration()
- Return the full description, enough to rebuild this encoder.
- digest()
sha256:over the declaration.- encode(rates)
- Return the spike trains for a vector of rates.
Class FirstSpikeLatency¶
Encode values in [0, 1] as one spike each, larger values earlier.
Attributes¶
n_steps:
Number of steps.
tau:
The spike of value v falls in step int(tau * (1 - v)),
limited to the window.
- post_init()
- Refuse a setting the declaration could not state faithfully.
- declaration()
- Return the full description, enough to rebuild this encoder.
- digest()
sha256:over the declaration.- encode(values)
- Return one spike per value; a value outside
[0, 1]is refused.
Function encoder_from_declaration(declaration)¶
Rebuild the encoder a declaration describes.
Parameters¶
declaration:
A declaration as :meth:EventBinning.declaration and its siblings
return it.
Returns¶
EventBinning or PoissonRates or FirstSpikeLatency The encoder; its own declaration equals the one given.
Raises¶
ValueError On another schema, an unknown encoder, or a declaration that is not exactly what the rebuilt encoder declares.
Module datasets.encoding¶
Function poisson_encode(rates, T, dt_ms, seed)¶
Convert firing-rate array to Poisson spike trains.
Parameters¶
rates : array_like, shape (N,) Firing probabilities per timestep, clipped to [0, 1]. T : int Number of timesteps. dt_ms : float Timestep duration in ms (scales rates linearly). seed : int or None RNG seed for reproducibility.
Returns¶
spikes : ndarray, shape (T, N), dtype bool
Function latency_encode(values, T, tau, strict)¶
Convert normalised values in [0, 1] to first-spike-time trains.
Higher values spike earlier. Each neuron fires exactly once.
Parameters¶
values : array_like, shape (N,)
Input values, expected in [0, 1].
T : int
Number of timesteps.
tau : float
Time constant controlling the spike-time spread.
strict : bool
If True (default), raise ValueError when any value lies
outside [0, 1]. If False, silently clip the resulting
spike times to [0, T-1] (the legacy behaviour). The
clip happens regardless of strict; this flag controls
only whether the function raises before clipping.
Returns¶
spikes : ndarray, shape (T, N), dtype bool
Raises¶
ValueError
If strict=True (default) and any element of values
is outside [0, 1].
Module datasets.event_samples¶
Function read_event_sample(root, dataset, sample)¶
Read a manifest sample as spatial events with millisecond timestamps.
Parameters¶
root:
Operator dataset root whose manifest has already been verified.
dataset:
nmnist, shd or dvs_cifar10.
sample:
Sample location in that verified manifest. SHD selects a recording
inside its HDF5 file; camera datasets use one file per recording.
Returns¶
numpy.ndarray
Events with columns x, y, polarity, t_ms. Auditory channels use
x=channel, y=0, polarity=0; seconds are converted to milliseconds.
Raises¶
ValueError For an unsupported dataset, a path outside the root, malformed binary records, or incompatible sample indices and event columns. OSError If a verified recording is no longer readable.
Notes¶
No download or synthetic substitution occurs. The caller must bind the sample metadata to an actual file manifest before invoking this reader.
Module datasets.loaders¶
Function load_nmnist(root, train, dt_ms, T, synthetic, n_samples, seed)¶
Load N-MNIST spiking vision dataset.
Neuromorphic-MNIST: 34x34 DVS recordings of MNIST digits moved on an ATIS sensor via saccadic eye movements. 10 classes.
Orchard et al., "Converting Static Image Datasets to Spiking Neuromorphic Datasets Using Saccades", Front. Neurosci. 2015.
Parameters¶
root : path Directory containing the extracted dataset. train : bool Load training split if True, test split otherwise. dt_ms : float Temporal resolution for synthetic fallback. T : int Number of timesteps for synthetic fallback. synthetic : bool Force synthetic data generation. n_samples : int Number of synthetic samples to generate. seed : int RNG seed for reproducible synthetic data.
Returns¶
samples : list of ndarray, each shape (N_events, 4) Real recordings use float64 columns [x, y, polarity, timestamp_ms] to avoid float32 timestamp rounding before temporal binning. labels : ndarray of int
Function load_shd(root, train, dt_ms, T, synthetic, n_samples, seed)¶
Load Spiking Heidelberg Digits (SHD) dataset.
Audio digits 0-9 in English and German, spike-encoded through an artificial cochlea model. 700 input channels, 20 classes.
Cramer et al., "The Heidelberg Spiking Data Sets for the Systematic Evaluation of Spiking Neural Networks", IEEE TNNLS 2022.
Parameters¶
root : path Directory containing shd_train.h5 / shd_test.h5. train : bool Load training split if True, test split otherwise. dt_ms : float Temporal resolution for binning spikes. T : int Number of timesteps for synthetic fallback. synthetic : bool Force synthetic data generation. n_samples : int Number of synthetic samples to generate. seed : int RNG seed for reproducible synthetic data.
Returns¶
samples : list of ndarray, each shape (T, 700) dtype bool Binned spike trains. labels : ndarray of int
Function load_dvs_cifar10(root, train, dt_ms, T, synthetic, n_samples, seed)¶
Load DVS-CIFAR10 event-camera dataset.
CIFAR-10 images displayed on a monitor and recorded by a DVS camera at 128x128 resolution. 10 classes.
Li et al., "CIFAR10-DVS: An Event-Stream Dataset for Object Classification", Front. Neurosci. 2017.
Parameters¶
root : path Directory containing the extracted dataset. train : bool Load training split if True, test split otherwise. dt_ms : float Temporal resolution for synthetic fallback. T : int Number of timesteps for synthetic fallback. synthetic : bool Force synthetic data generation. n_samples : int Number of synthetic samples to generate. seed : int RNG seed for reproducible synthetic data.
Returns¶
samples : list of ndarray, each shape (N_events, 4) Real recordings use float64 columns [x, y, polarity, timestamp_ms] to avoid float32 timestamp rounding before temporal binning. labels : ndarray of int
Module datasets.manifest¶
Class DatasetDescription¶
What one supported event dataset is, as its publisher states it.
Attributes¶
name:
Identifier used by the loaders and the manifest, e.g. "shd".
title:
Published name.
citation:
The paper to cite.
doi:
DOI of that paper.
url:
Where the publisher distributes the files.
licence:
SPDX identifier of the data licence.
licence_url:
Text of that licence.
sensor:
"dvs" for an event camera, "cochlea" for an auditory model.
geometry:
(width, height) of a camera, or (channels,) of a cochlea.
polarities:
Number of event polarities; 0 when events carry none.
classes:
Number of labels.
file_format:
The file format the loader reads, including the unit of its times.
group_key:
What a group is, and why it is the leakage unit.
- to_dict()
- Return the JSON form.
Class FileRecord¶
One file of the dataset: path relative to the root, size and digest.
Class SampleRecord¶
One sample: where it is, which published split it is in, its label and group.
Class EventDatasetManifest¶
Every file and sample of one event dataset as it lies on disk.
Attributes¶
dataset: The dataset description. version: The release of the data the user holds, as its publisher names it. files: Every file read, sorted by path. samples: Every sample, in loader order.
- to_dict()
- Return the JSON form, with the schema identifier.
- digest()
sha256:over the canonical JSON form; identifies this exact manifest.- splits()
- Return the published split names, in first-seen order.
Class ManifestVerification¶
How the files on disk differ from a manifest.
Attributes¶
missing: Files the manifest lists that are not on disk. changed: Files whose size or SHA-256 differs. unexpected: Files in the dataset layout that the manifest does not list.
- ok()
Truewhen the disk holds exactly the manifest's bytes.
Function build_manifest(name, root)¶
Scan a dataset directory and record its files and samples.
Parameters¶
name:
"nmnist", "shd" or "dvs_cifar10".
root:
Directory in the layout the matching loader reads.
version:
The release the files come from, as the publisher names it; it is
recorded, not inferred, because the files do not carry it.
Returns¶
EventDatasetManifest The manifest.
Raises¶
ValueError On an unknown dataset, an empty version, a directory holding none of the dataset's files, or a label outside the dataset's classes.
Function verify_manifest(manifest, root)¶
Compare the files under root with a manifest, byte for byte.
Parameters¶
manifest: The manifest an experiment recorded. root: Directory holding the dataset now.
Returns¶
ManifestVerification
Missing, changed and unexpected files; ok when there are none.
Function manifest_from_dict(data)¶
Read a manifest's JSON form, refusing anything it does not define.
Parameters¶
data: The parsed JSON.
Returns¶
EventDatasetManifest The manifest.
Raises¶
ValueError On another schema, a missing or unknown field, or a dataset description that differs from the one this version supports.
Module datasets.splits¶
Class SplitPlan¶
Which samples of a manifest go to which split, by whole groups.
Attributes¶
manifest_digest:
Digest of the manifest the positions refer to.
source_split:
The published split that was divided.
seed:
Seed of the group order.
fractions:
Requested share of samples per split, in declaration order.
assignment:
Split name to the positions of its samples in manifest.samples.
groups:
Split name to the groups it holds.
- to_dict()
- Return the JSON form, with the schema identifier.
- digest()
sha256:over the canonical JSON form.
Function group_split(manifest)¶
Divide one published split into new splits made of whole groups.
Groups are taken in an order fixed by seed; each goes to the split
whose sample count is furthest below its requested share. The shares are
therefore met as closely as whole groups allow, never by cutting a group.
Parameters¶
manifest: The dataset manifest. fractions: Share of the source split's samples per new split; positive, summing to one. source_split: The published split to divide; other published splits are untouched. seed: Seed of the group order.
Returns¶
SplitPlan The plan, tied to the manifest's digest.
Raises¶
ValueError On shares that are not positive or do not sum to one, an unknown source split, or fewer groups than requested splits.
Function leaked_groups(manifest, plan)¶
Return the groups that have samples in more than one split of a plan.
Parameters¶
manifest: The manifest the plan was drawn from. plan: The plan to check.
Returns¶
tuple of str Leaked groups, sorted; empty for a sound plan.
Raises¶
ValueError When the plan was drawn from another manifest.
Function group_overlap(manifest)¶
Report groups that the publisher's own splits share.
Parameters¶
manifest: The dataset manifest.
Returns¶
dict Each shared group to the published splits it appears in; empty when the published splits keep every group apart.
Function split_plan_from_dict(data)¶
Read a plan's JSON form, refusing anything it does not define.
A plan read back is not trusted to be sound: check it against its
manifest with :func:validate_split_plan before training on it.
Parameters¶
data: The parsed JSON.
Returns¶
SplitPlan The plan.
Raises¶
ValueError On another schema, missing or unknown fields, invalid types, duplicate positions, or inconsistent split names. Values are never coerced.
Function validate_split_plan(manifest, plan)¶
Check a complete split's sample and group custody before training.
Parameters¶
manifest: Manifest whose source split is being divided. plan: Imported or generated plan. Every source sample must occur once, every part must be non-empty, and declared groups must match samples.
Raises¶
ValueError If the schema, manifest digest, source split, sample membership, coverage, group declarations or separation is invalid.
Notes¶
Requested fractions are allocation goals, not an exact sample-count constraint: indivisible groups can prevent exact fraction matching.
Module debug.analyzer¶
Class DivergencePoint¶
First point where two traces diverge.
Class CausalEvent¶
One event in a causal spike chain.
Function find_divergence(trace_a, trace_b)¶
Find the first timestep where two traces produce different spikes.
Useful for comparing ANN-converted SNN vs directly-trained SNN, or Python simulation vs hardware output.
Returns None if traces are identical.
Function spike_diff(trace_a, trace_b)¶
Summary of spike differences between two traces.
Returns¶
dict with keys: total_mismatches: int mismatch_rate: float (fraction of timestep*neuron pairs) first_divergence: DivergencePoint or None per_neuron_mismatches: ndarray
Function causal_chain(trace, neuron_id, timestep, max_depth)¶
Trace backward from a spike to find causal input events.
Starting from neuron_id at timestep, finds the chain of spikes that contributed current to this neuron in preceding timesteps.
Parameters¶
trace : ExecutionTrace neuron_id : int Target neuron. timestep : int Timestep of the spike to explain. max_depth : int Maximum backward steps to trace.
Returns¶
list of CausalEvent Causal chain from target backward to inputs.
Module debug.hil_client¶
Class SpikeEvent¶
Single telemetry sample from an FPGA or simulator.
Class SpikeRingBuffer¶
Fixed-capacity circular buffer for SpikeEvent telemetry.
Lock-protected overwrite-on-full. Mirrors Go RingBuffer.
- init(capacity)
- push(evt)
- snapshot(n)
- head()
- capacity()
Class LayerAggregator¶
Per-layer running statistics collector.
- init()
- record(evt)
- get(layer_id)
- all()
- mean_correlation(ls)
- mean_precision(ls)
Class ErrorBudget¶
Threshold-based alerting for precision/correlation bounds.
- check(evt)
Class CorrelationWindow¶
Sliding window for correlation values.
- init(size)
- add(v)
- count()
- mean()
- max()
Class PrecisionTracker¶
Exponential moving average of precision.
- update(precision)
Class EventFilter¶
Selects events matching criteria.
- match(evt)
Class TriggerCondition¶
Conditional breakpoint for debugger.
- evaluate(evt)
Class TriggerLog¶
Records fired trigger events for post-mortem analysis.
- init()
- fire(evt)
- count()
Class RateLimiter¶
Token-bucket rate limiter for high-speed streams.
- init(capacity)
- allow()
- refill(n)
- available()
Class HealthStatus¶
Debugger health snapshot.
Function filter_events(events, f)¶
Apply a filter to a list of events.
Function check_health(events_received, uptime_seconds, buffer_head, buffer_capacity, clients_active)¶
Compute health status from telemetry metrics.
Function export_csv(events)¶
Export events to CSV string.
Function export_json(events)¶
Export events to JSON array string.
Module debug.hil_debugger¶
Class HILDebugger¶
High-level wrapper for the HIL telemetry server.
- init(port)
- start()
- Starts the HIL debugger server.
- stop()
- Stops the HIL debugger server.
- is_running()
- Returns True if the server is active.
- url()
- Returns the base URL for the active telemetry server.
Module debug.hil_server¶
Class HILServerDaemon¶
Manages the background execution of the Go HIL Debugger service.
- post_init()
- start(build)
- Compile and start the standalone HIL Debugger service.
- stop()
- Gracefully terminate the background HIL debugger process.
- is_running()
- Returns True if the daemon process is running.
Module debug.sc_doctor¶
Class ScDoctor¶
Adaptive bitstream length controller with optional ECC.
Correlation-driven feedback loop: - High correlation (>0.15): double bitstream length - Low correlation (<0.05): halve bitstream length (floor 256) - ECC auto-enabled when length exceeds 2048
- init(initial_length, target_precision)
- adapt(current_correlation, popcount)
- Analyze correlation and adjust bitstream length.
- encode_ecc(data)
- Hamming(7,4) encode a 4-bit chunk → 7-bit codeword.
- decode_ecc(encoded)
- Hamming(7,4) decode with single-bit error correction.
Module debug.sc_scope¶
Class TransportType¶
Class TransportConfig¶
Configuration for a transport backend.
Class TransportBackend¶
Pluggable transport adapter for bitstream acquisition.
Production backends (JTAG, UART, PYNQ DMA) require hardware;
the SIMULATED backend generates synthetic data for testing
and development.
- connect()
- Establish connection to the target.
- disconnect()
- read_bitstream(num_words, layer_id)
- Read packed bitstream words from the target.
Class BitstreamSample¶
One timestamped bitstream capture.
- bit_length()
- popcount()
- density()
- effective_bits()
- Shannon entropy-based effective precision.
Class AnalysisWindow¶
Windowed statistics from recent samples.
- post_init()
- push(sample)
- count()
- mean_density()
- std_density()
- mean_effective_bits()
- total_popcount()
- sample_rate_hz()
- Estimated sample rate from timestamps.
Class LiveAnalyzer¶
Real-time SC bitstream analyzer with per-layer windows.
- init(num_layers, window_size)
- ingest(sample)
- Process one incoming sample.
- layer_stats(layer_id)
- Get summary stats for one layer.
- all_stats()
Class LayerErrorBudget¶
Per-layer precision tracking against golden model expectations.
- check(measured_density)
- Check if measured density is within tolerance.
- current_error()
- mean_error()
- max_error()
- violations()
- pass_rate()
Class TriggerType¶
Class TriggerCondition¶
Conditional capture trigger.
Class TriggerEvent¶
A triggered capture event.
Class TriggerEngine¶
Evaluates capture triggers against incoming samples.
- init()
- add_trigger(condition)
- evaluate(sample)
- Check all triggers against a sample. Returns fired events.
- event_count()
- clear()
Class ScopeSession¶
Manages a live debugging session.
- start()
- Start the scope session.
- stop()
- add_error_budget(layer_id, expected_density, tol)
- capture_one(layer_id, neuron_id, num_words)
- Capture one bitstream sample from the target.
- capture_sweep(num_layers, num_words)
- Capture one sample from each layer.
- status()
Class ScopeRenderer¶
Text-mode rendering of live scope data for CLI output.
- render_density_bar(cls, density, width)
- Render a density as a text bar.
- render_layer_summary(cls, layer_id, stats)
- render_session(cls, session)
- Render full session status as text.
Function compute_scc(a, b)¶
Stochastic Computing Correlation between two u32-packed bitstreams.
Dispatches to the Rust stochastic_doctor_core.py_scc_packed when the
compiled extension is importable (the default when the repo is built with
maturin develop --release). Falls back to :func:_compute_scc_python
when the extension is missing — the fallback is numerically identical
(both implement the case-split Alaghi & Hayes 2013 form).
Module debug.tracer¶
Class ExecutionTrace¶
Complete execution trace of an SNN run.
Attributes¶
n_neurons : int Total neurons across all populations. n_steps : int Number of simulation timesteps. spikes : ndarray of shape (n_steps, n_neurons) Binary spike matrix. voltages : ndarray of shape (n_steps, n_neurons) Membrane voltages. currents : ndarray of shape (n_steps, n_neurons) Input currents. population_labels : list of str Population names. population_ranges : list of (start, end) Neuron index ranges per population.
- spike_count()
- Total spikes in the trace.
- firing_rates()
- Per-neuron firing rate (spikes per step).
- neuron_trace(neuron_id)
- Extract full trace for one neuron.
- spike_times(neuron_id)
- Timesteps when a neuron spiked.
- population_spikes(pop_label)
- Spike matrix for one population.
Class SpikeTracer¶
Records execution trace during SNN simulation.
Wraps a Network and intercepts step_all to record spikes, voltages, and currents at every timestep.
Usage¶
tracer = SpikeTracer(network) trace = tracer.run(duration=0.1, dt=0.001) divergence = find_divergence(trace, expected_spikes)
- init(network)
- run(duration, dt, seed)
- Run the network and record full execution trace.
Module digital_twin.mismatch¶
Class FPGAMismatchModel¶
Wraps weight matrices and neuron parameters with FPGA imperfections.
Parameters¶
quantization_bits : int Fixed-point bit width (default 16 for Q8.8). weight_cv : float Coefficient of variation for weight perturbation (default 0.02 = 2%). threshold_cv : float Per-neuron threshold variation (default 0.05 = 5%). clock_jitter_pct : float Clock period variation (default 0.01 = 1%). seed : int Random seed for reproducibility.
- post_init()
- quantize(values)
- Apply Q-format quantization noise.
- perturb_weights(weights)
- Add process variation noise to weights.
- perturb_thresholds(thresholds)
- Add per-neuron threshold mismatch.
- jitter_timing(n_steps)
- Generate clock jitter: per-step timing variation.
- apply_to_network_weights(weights)
- Apply all hardware imperfections to a list of weight matrices.
- mismatch_report(weights)
- Report expected mismatch statistics for given weights.
Module digital_twin.twinsync¶
Class LamportClock¶
Lamport logical clock for causal ordering.
- init()
- tick()
- Local event: increment.
- send()
- Prepare timestamp for sending.
- receive(remote_time)
- Update on message receipt.
Class VectorClock¶
Vector clock for full causal dependency tracking.
- init(node_id, num_nodes)
- tick()
- send()
- receive(remote_clock)
- happened_before(other)
- Check if self happened-before other (self < other).
- concurrent_with(other)
- Check if self is concurrent with other.
Class EventType¶
Class TwinEvent¶
One event in the time-warp simulation.
Class Checkpoint¶
Deterministic state snapshot for rollback.
- compute_checksum()
Class CheckpointManager¶
Manages state snapshots for time-warp rollback.
Preserves the identity substrate (ArcaneNeuron.v_deep) across rollback: deep compartment is NEVER rolled back.
- init(max_checkpoints)
- save(node_id, virtual_time_ns, neuron_state, synapse_state, lfsr_state, identity_deep, lamport_time, vector_clock)
- find_rollback_target(node_id, target_time_ns)
- Find the latest checkpoint at or before target_time.
- discard_after(node_id, time_ns)
- Discard checkpoints after a given time (post-rollback cleanup).
- total_checkpoints()
Class NodeState¶
Per-node state in the time-warp simulation.
Class TimeWarpEngine¶
Optimistic parallel simulation with anti-message rollback.
Implements the Jefferson Time Warp protocol adapted for SC neuromorphic simulation:
- Each node advances optimistically at its own rate
- Straggler events trigger rollback + anti-messages
- Global Virtual Time (GVT) advances monotonically
- Fossil collection prunes checkpoints below GVT
-
Identity (v_deep) is NEVER rolled back — it is the self
-
init(num_nodes, checkpoint_interval_ns)
- inject_event(event)
- Inject an event into the simulation.
- process_next()
- Process the next event from the queue.
- compute_gvt()
- Compute Global Virtual Time (minimum of all LVTs + in-transit).
- fossil_collect()
- Remove checkpoints below GVT.
- status()
- inject_sync_barrier(virtual_time_ns)
- Inject a sync barrier event to all nodes at given time.
- verify_causal_order()
- Verify causal ordering of processed events.
- detect_starvation(threshold_ns)
- Detect nodes lagging behind GVT by more than threshold.
- node_throughput()
- Events processed per node.
Class SyncMode¶
Class DivergenceMetric¶
Measures divergence between physical and digital twin.
- total_divergence()
- within_tolerance()
Class TwinSession¶
Orchestrates physical ↔ digital twin synchronization.
Manages bidirectional data flow: - Physical → Digital: sensor events (MEA spikes, EEG) - Digital → Physical: stimulation commands (opto, TMS)
- init(num_nodes, mode, max_divergence)
- start()
- stop()
- inject_physical_event(spike_time_ns, neuron_id, target_node)
- Inject a physical sensor event into the digital twin.
- advance(steps)
- Advance the simulation by N steps.
- update_divergence(physical_rate_hz, digital_rate_hz, physical_identity)
- Update divergence metrics.
- status()
Class LookaheadConfig¶
Null-message lookahead for conservative synchronization.
Each node declares a minimum time advance (lookahead) it guarantees before generating output events. Peers can safely advance by at least this amount without rollback risk.
- can_advance_to(target_ns)
- send_null_message(current_ns)
Class NullMessageOptimizer¶
Reduces rollbacks in mixed conservative/optimistic mode.
- init(num_nodes, default_lookahead_ns)
- safe_advance_time(node_id)
- Maximum time this node can safely advance to.
- broadcast_null(node_id, current_ns)
Class DeltaCheckpoint¶
Stores only the diff from a base checkpoint.
- compute_delta(base_state, new_state, base_id, new_id, virtual_time_ns, node_id)
- compression_ratio()
- num_changes()
Class ReplayVerifier¶
Verifies bitstream-exact replay across runs.
Compares checkpoint hashes from two runs to prove determinism.
- init()
- record_run_a(checkpoint)
- record_run_b(checkpoint)
- is_deterministic()
- first_divergence_index()
- compared_count()
Class DriftCorrection¶
One drift correction action.
Class DriftAutoCorrector¶
Closed-loop drift correction between physical and digital twin.
- init(max_drift_ns, correction_gain)
- check_and_correct(physical_time_ns, digital_time_ns, node_id)
- total_corrections()
Class MPIRankMapping¶
Maps MPI ranks to physical node topology.
- neuron_count()
Class MPITopology¶
Physical→logical node layout for distributed twin.
- init()
- add_rank(mapping)
- total_neurons()
- num_ranks()
- rank_for_neuron(neuron_id)
- co_located_ranks(rank)
- Ranks on the same host (cheap communication).
Class BackpressureController¶
Prevents event overload by throttling injection rate.
- init(max_queue_depth, cooldown_ns)
- should_accept(current_queue_depth)
- rejection_rate()
- is_backpressured()
Class CheckpointAuditChain¶
Tamper-evident chain of checkpoint hashes.
- init()
- append(checkpoint)
- verify()
- length()
Class SessionSnapshot¶
Serializable session state for persistence.
- from_session(session)
- to_dict()
Class TwinEndpoint¶
One twin in a federation.
Class TwinFederation¶
Federates multiple digital twins for multi-subject studies.
- init()
- register(twin_id, session, priority)
- twin_count()
- global_gvt()
- advance_all(steps)
- total_divergence()
Class AdaptiveCheckpointInterval¶
Dynamically adjusts checkpoint frequency based on rollback rate.
- init(base_interval, min_interval, max_interval)
- update(total_rollbacks, total_events)
- Adjust interval: more rollbacks → more frequent checkpoints.
- is_aggressive()
Module distillation.distill¶
Class TemporalDistillationLoss¶
Temporal-aware distillation loss for SNN→SNN or ANN→SNN transfer.
Matches per-timestep output distributions from teacher to student, with entropy regularization to prevent learning erroneous knowledge.
Parameters¶
temperature : float Softmax temperature for logit matching. alpha : float Weight of distillation loss vs task loss (0=task only, 1=distill only). entropy_weight : float Entropy regularization strength.
- init(temperature, alpha, entropy_weight)
- compute(student_logits, teacher_logits, targets)
- Compute distillation loss.
Class SelfDistiller¶
Self-distillation: use extended-T model as implicit teacher.
Run the same model at T_teacher timesteps (more accurate) to generate soft targets for training at T_student timesteps (faster).
Parameters¶
T_teacher : int Timesteps for teacher forward pass. T_student : int Timesteps for student forward pass. temperature : float
- generate_targets(run_fn, inputs)
- Run model at T_teacher steps to generate soft targets.
Module doctor.diagnose¶
Class Severity¶
Class Diagnosis¶
Single diagnostic finding.
Class DiagnosticReport¶
Full diagnostic report for an SNN architecture.
- summary()
- has_critical()
- score()
- Health score 0-100. 100 = no issues.
Function diagnose(layer_sizes, weights, spike_rates, target, bitstream_length)¶
Run architecture diagnostics.
Parameters¶
layer_sizes : list of (n_inputs, n_neurons) weights : list of ndarray, optional Weight matrices per layer. spike_rates : list of ndarray, optional Per-neuron firing rates per layer (from profiling). target : str FPGA target for hardware checks. bitstream_length : int SC bitstream length.
Returns¶
DiagnosticReport
Module drivers.physical_twin¶
Class PhysicalTwinBridge¶
Synchronise software neuron state with an explicit twin backend.
mode="EMULATION" is a deterministic local noise model for development
and CI. mode="TCP" opens a JSON-line request/response connection for a
real hardware-twin service. The class never marks itself connected to
physical hardware unless a TCP exchange actually succeeds.
- init(ip, port)
- sync_step(sw_v_mem, sw_spike)
- Send software state and return the twin membrane voltage.
Module drivers.sc_neurocore_driver¶
Class RealityHardwareError¶
Raised when physical hardware is required but missing.
Class SC_NeuroCore_Driver¶
Primary driver for the sc-neurocore FPGA overlay on PYNQ-Z2.
This driver enforces 'Reality Checks'. It will NOT run on standard x86 CPUs unless explicitly in 'EMULATION' mode.
- init(bitstream_path, mode, seed)
- Construct a driver in HARDWARE or EMULATION mode.
- write_layer_params(layer_id, params)
- Writes parameters to a specific layer's AXI-Lite registers.
- run_step(input_vector)
- Executes one integration step on the FPGA.
Module drivers.verify_hardware_link¶
Function verify_link(extras)¶
Run the hardware-link diagnostic CLI.
Parameters¶
extras : bool Run the optional Evo 2 + Opentrons probes when True (default). Set to False to only check the FPGA subsystem; skips the imports of sibling-repo modules.
Module edge.aer_router¶
Class AERRoutingDaemon¶
Orchestrates the Go-based AER UDP mesh multi-FPGA router pipeline dynamically.
- init(port)
- start(build)
- stop()
- Tears down the active background UDP topology safely.
Module edge.bitstream¶
Function popcount32(word)¶
Count set bits in a u32 word (Wilkes-Wheeler-Gill).
Function popcount_slice(words)¶
Popcount over a packed u32 word slice.
Function sc_and(a, b)¶
SC multiply (bitwise AND).
Function sc_or(a, b)¶
SC saturating addition (bitwise OR).
Function sc_xor(a, b)¶
SC absolute difference / HDC bind (bitwise XOR).
Function sc_sub(a, b)¶
SC saturating subtraction: a AND NOT b.
Function sc_mux(a, b, sel)¶
SC scaled addition (2:1 MUX): (a AND sel) OR (b AND NOT sel).
Function and_packed(a, b)¶
SC AND over two packed word slices.
Function mux_packed(a, b, sel)¶
SC MUX over two packed word slices with a select bitstream.
Function probability(words, bit_length)¶
Estimated probability from a packed bitstream.
Function scc(a, b, bit_length)¶
SCC between two packed u32 bitstreams (Alaghi & Hayes, 2013).
Returns a correlation coefficient in [-1, 1].
Module edge.deploy¶
Function generate_cargo_config(board)¶
Generate .cargo/config.toml content for a target board.
Function generate_memory_x(board)¶
Generate memory.x linker script content for a target board.
Module edge.lfsr¶
Class Lfsr16¶
16-bit Galois LFSR bitstream encoder.
Bit-compatible with the Rust core_engine::bitstream::Lfsr16. Uses u32-packed output for MCU word alignment.
- init(seed)
- step()
- Advance LFSR by one clock, return new state.
- encode(threshold, bit_length)
- Encode probability (threshold/65535) into packed u32 words.
- encode_float(p, bit_length)
- Encode a probability [0.0, 1.0] into a packed bitstream.
Module edge.neuron¶
Class LifNeuron¶
Leaky Integrate-and-Fire neuron (SC domain, integer arithmetic).
Membrane potential = running popcount of input bitstream. Leak = right-shift per tick (exponential decay). Fires when potential exceeds threshold.
- tick(input_words)
- Process one timestep, return True if spike fired.
- reset()
Class IzhikevichNeuron¶
Izhikevich neuron with integer SC-domain dynamics.
Uses fixed-point arithmetic (Q16.16) to avoid floating-point. Supports regular spiking, fast spiking, chattering, and intrinsic burst.
- tick(input_current_q16)
- Process one timestep. Returns True on spike.
- reset()
- regular_spiking(cls)
- fast_spiking(cls)
- chattering(cls)
- intrinsic_burst(cls)
Module edge.power_estimator¶
Class Board¶
Supported RISC-V MCU targets.
- init(label, ram_kb, flash_kb, active_uw, sleep_uw)
Class PowerProfile¶
Estimated power profile for a target board at a given clock.
- for_board(cls, board, clock_mhz)
- duty_cycled_uw(duty)
- Estimate µW for a given duty cycle (0.0=sleep, 1.0=active).
Class MemoryFootprint¶
Memory footprint estimate for a tinySC network.
- estimate(cls, num_layers, neurons_per_layer, bs_words, board)
- Estimate memory for a network configuration.
- max_neurons(board)
- Maximum neurons that fit in a board's RAM (single layer).
Module edge.power_thermal¶
Class PowerThermalConfig¶
Inputs for an FPGA power and thermal deployment estimate.
- post_init()
Class VivadoPowerReport¶
Power and thermal values parsed from a routed Vivado power report.
Class VivadoUtilizationReport¶
Resource counts parsed from a Vivado utilisation report.
Function build_power_thermal_model(config)¶
Build a deterministic JSON-compatible FPGA power/thermal model.
Function build_power_thermal_model_from_vivado_reports(report_dir, config)¶
Build a power/thermal model seeded from Vivado implementation reports.
The returned model keeps the estimator resource breakdown for workload context, but replaces headline power and thermal values with the routed report values from Vivado.
Function parse_vivado_power_report(path)¶
Parse headline power and thermal fields from a Vivado report_power file.
Function parse_vivado_utilization_report(path)¶
Parse FPGA resource counts from a Vivado report_utilization file.
Function write_power_thermal_model(output_dir, config)¶
Write power_thermal_model.json beside generated FPGA artefacts.
Function write_power_thermal_model_from_vivado_reports(report_dir, output_dir, config)¶
Write report-derived FPGA power/thermal JSON beside deployable artefacts.
Module edge.sc_network¶
Class SCLayer¶
Single dense SC layer: weights × inputs via AND + popcount threshold.
- post_init()
- Validate and normalise layer configuration after dataclass construction.
- words_per_input()
- Return packed weight words required to cover all layer inputs.
- forward(input_words, bit_length)
- Run SC inference: AND each weight row with input, threshold popcount.
Class SCNetwork¶
Multi-layer feed-forward SC network runner.
Usage::
net = SCNetwork(bit_length=1024)
net.add_layer(SCLayer(n_inputs=32, n_outputs=16))
net.add_layer(SCLayer(n_inputs=16, n_outputs=8))
output = net.run([0.5] * 32)
- post_init()
- Validate network-level stochastic-computing execution parameters.
- add_layer(layer)
- Append a layer after validating stochastic-mode compatibility.
- encode_inputs(probabilities)
- Encode float probabilities into per-input packed bitstreams.
- run(input_probabilities)
- Full inference: encode → cascaded layer inference → spike output.
- export_weights()
- Export all layer weights in serialization-ready format.
- from_weights(cls, layers_data, bit_length, lfsr_seed)
- Construct network from deserialized weight data.
- layer_count()
- Return the number of layers currently registered in the network.
- total_neurons()
- Return the total output-neuron count across all registered layers.
Module edge.sobol¶
Class SobolGenerator¶
1D Sobol sequence generator with 16-bit resolution.
Uses Joe-Kuo direction numbers (dimension 1) and Gray-code indexing so only one XOR per step.
- init(seed)
- step()
- Advance by one step, return the next Sobol value in [0, 65535].
- encode(threshold, length)
- Encode a probability into packed u64 words using Sobol sequence.
- reset(seed)
- Reset to initial state.
Module edge.telemetry¶
Class TelemetryRing¶
Fixed-size ring buffer for telemetry samples (u32 values).
- init(capacity)
- push(value)
- mean()
- last()
- count()
- capacity()
Class LayerTelemetry¶
Telemetry counters for a single SC layer.
- record_tick(n_spikes, n_neurons)
- Record one tick's worth of activity.
- mean_spike_rate()
- mean_utilization()
- lifetime_spike_rate()
Class DeviceTelemetry¶
Aggregate telemetry for the full device/network.
- get_layer(layer_id)
- record(layer_id, n_spikes, n_neurons)
- summary()
Module edge.web_deploy¶
Class WebDeploymentConfig¶
Configuration for generating browser deployment artefacts.
- post_init()
Class WebDeploymentManifest¶
Manifest consumed by the generated browser runtime.
- to_dict()
- Return a JSON-serialisable manifest dictionary.
Function build_web_deployment(model_path, output_dir, config)¶
Generate a static browser deployment scaffold for a model artefact.
Module edge.weights¶
Class WeightHeader¶
Weight blob header (16 bytes).
- to_bytes()
- from_bytes(cls, data)
- validate()
Class LayerHeader¶
Per-layer header (16 bytes).
- to_bytes()
- from_bytes(cls, data)
- words_per_row()
Function serialize_weights(layers)¶
Serialize network weights to binary blob.
Parameters¶
layers : list Each entry is (n_inputs, n_outputs, threshold, weight_rows). weight_rows is list[list[int]] (n_outputs × words_per_row u32 values).
Returns¶
bytes Complete weight blob with headers.
Function deserialize_weights(data)¶
Deserialize a weight blob into layer headers + weight matrices.
Returns¶
list[tuple[LayerHeader, list[list[int]]]] Each entry is (header, weight_rows).
Module encoding.encoders¶
Function rate_encode(values, T, seed)¶
Rate coding: spike probability proportional to value.
Parameters¶
values : ndarray of shape (N,) Input values in [0, 1]. T : int Number of timesteps. seed : int
Returns¶
ndarray of shape (T, N), binary
Function latency_encode(values, T)¶
Latency (Time-to-First-Spike) coding: higher value = earlier spike.
Parameters¶
values : ndarray of shape (N,) Input values in [0, 1]. T : int
Returns¶
ndarray of shape (T, N), binary
Function delta_encode(values, threshold)¶
Delta coding: spike when change exceeds threshold.
Parameters¶
values : ndarray of shape (T,) or (T, N) Time-varying input signal. threshold : float
Returns¶
ndarray of same shape, binary
Function phase_encode(values, T, n_phases)¶
Phase coding: value encoded as spike phase within oscillation cycle.
Parameters¶
values : ndarray of shape (N,) Input values in [0, 1]. T : int n_phases : int Number of phase bins per cycle.
Returns¶
ndarray of shape (T, N), binary
Function burst_encode(values, T, max_burst)¶
Burst coding: value encoded as burst length (consecutive spikes).
Parameters¶
values : ndarray of shape (N,) Input values in [0, 1]. T : int max_burst : int Maximum burst length for value=1.
Returns¶
ndarray of shape (T, N), binary
Function rank_order_encode(values, T)¶
Rank-order coding: neurons fire in order of decreasing value.
Parameters¶
values : ndarray of shape (N,) T : int
Returns¶
ndarray of shape (T, N), binary
Function sigma_delta_encode(values, threshold)¶
Sigma-delta coding: integrate error, spike when threshold exceeded.
Parameters¶
values : ndarray of shape (T,) or (T, N) Time-varying signal. threshold : float
Returns¶
ndarray of same shape, binary
Module encoding.optimizer¶
Class EncodingRecommendation¶
Recommendation for one encoding scheme.
Class EncodingOptimizer¶
Profile data and recommend optimal spike encoding.
Parameters¶
T : int Number of simulation timesteps.
- init(T)
- profile(data)
- Compute data statistics relevant to encoding selection.
- recommend(data)
- Recommend encoding schemes ranked by suitability.
Module energy.estimator¶
Class LayerEstimate¶
Resource estimate for one layer.
Class EnergyReport¶
Complete pre-silicon energy estimate for an SNN on an FPGA target.
- post_init()
- summary()
- Human-readable summary.
Function estimate(layer_sizes, target, bitstream_length, neuron_type, event_driven, clock_mhz, include_infra)¶
Estimate FPGA resources and power for an SNN.
Parameters¶
layer_sizes : list of (n_inputs, n_neurons) Architecture as list of layer dimensions. target : str FPGA target: 'ice40', 'ecp5', 'artix7', 'zynq'. bitstream_length : int SC bitstream length L (affects latency and precision). neuron_type : str 'lif' (clock-driven) or 'event' (event-driven). event_driven : bool Use event-driven architecture (AER). clock_mhz : float Target clock frequency. include_infra : bool Include AXI/DMA infrastructure cost.
Returns¶
EnergyReport Complete resource and power estimate.
Module energy.folded_estimator¶
Class FoldedAreaEstimate¶
Area, latency, and power estimate for a folded-interconnect network.
All counts are pre-synthesis estimates derived from Yosys-calibrated per-block costs; treat them as ~20%-accurate architectural guidance, not synthesis truth.
- post_init()
- as_dict()
- Return a plain mapping of the estimate (for JSON artefacts).
- summary()
- Human-readable one-block summary.
Function estimate_folded_area(metrics)¶
Estimate folded-interconnect FPGA resources, latency, and power.
Parameters¶
metrics : FoldedResourceMetrics
The architectural summary attached to a folded compile
(NetworkCompilationResult.folded_metrics).
target : str
FPGA target key in :data:sc_neurocore.energy.fpga_models.TARGETS
('ice40', 'ecp5', 'artix7', 'zynq').
data_width : int
Fixed-point data width (the multiply and ROM-mux widths).
clock_mhz : float
Target clock frequency, used to turn cycles into time and energy.
event_driven : bool
Charge the event-driven neuron cost and AER infrastructure instead of the
clock-driven LIF cost.
include_infra : bool
Add the AXI-Lite register-file (and AER, when event_driven) infrastructure
LUTs.
Returns¶
FoldedAreaEstimate The folded area, latency, and power estimate.
Raises¶
ValueError
If target is not a known FPGA target.
Module energy.fpga_models¶
Class FPGATarget¶
FPGA target specification.
Class ModuleCost¶
Resource cost for one SC module instance.
Module energy_accounting.accountant¶
Class HardwareCostModel¶
Energy costs for a specific hardware target.
All values in picojoules (pJ).
Class LayerEnergy¶
Energy breakdown for one layer.
Class EnergyReport¶
Complete energy accounting report.
- summary()
- dominant_layer()
- energy_per_spike_pj()
Class EnergyAccountant¶
Per-spike energy accounting system.
Parameters¶
hardware : str or HardwareCostModel Target hardware for cost mapping.
- init(hardware)
- account(layer_names, layer_sizes, spike_counts, n_timesteps)
- Compute energy breakdown from spike activity.
Module energy_accounting.sustainability_profiler¶
Class FPGAResourceReport¶
Vivado-style utilisation report.
- dynamic_power_mw()
- Estimate dynamic power: P = C_eff * V² * f * activity.
- total_power_mw()
- power_breakdown()
- Per-component dynamic power breakdown in mW.
- scale_dvfs(clock_mhz, voltage_v)
- Return a new report with scaled clock and voltage (DVFS).
- from_vivado_dict(cls, d)
- Parse from a Vivado utilisation report dictionary.
Class GridRegion¶
Class CarbonModel¶
CO₂ emissions model for a given power profile.
- co2_g_per_kwh()
- compute(power_mw, duration_hours)
- Return grams of CO₂ emitted.
- annual_footprint_kg(power_mw)
- Annual CO₂ in kilograms (24/7 operation).
Class EmbodiedCarbon¶
Manufacturing + end-of-life carbon footprint.
- total_embodied_kg()
- amortised_annual_kg()
- Annual embodied carbon amortised over device lifetime.
Class EnergyHarvester¶
Class HarvestProfile¶
Energy-harvesting power curve.
- post_init()
- average_power_mw()
- energy_over(hours)
- Total energy harvested in mWh.
- power_at(hour_of_day)
- Instantaneous power at a given hour (0–24).
Class MultiHarvestStack¶
Combines multiple energy-harvesting sources.
- init(profiles)
- add(profile)
- average_power_mw()
- power_at(hour_of_day)
- energy_over(hours)
- num_sources()
Class EnergyStorageSim¶
Battery/supercap state-of-charge simulation.
- post_init()
- step(net_power_mw, dt_hours)
- Advance one time step. Returns clamped SoC.
- energy_stored_mwh()
- is_depleted()
Class ThermalModel¶
Simple junction-temperature model.
T_j = T_ambient + P_total * R_theta_ja
- junction_temp(power_mw)
- is_safe(power_mw)
- max_power_mw()
- Maximum power before thermal limit.
Class DutyCycleConfig¶
Optimised duty-cycle configuration for a deployment.
Class NetZeroReport¶
Results of a net-zero feasibility analysis.
Class SustainabilityOptimizer¶
Optimises SC deployment for net-zero energy operation.
- init(fpga, carbon, embodied, thermal)
- analyze(harvest, target_hours)
- Run full sustainability analysis.
- hourly_profile(harvest, hours)
- Generate an hourly power-balance profile.
- simulate_storage(harvest, storage, hours)
- Simulate battery SoC over time with harvest and load.
- energy_efficiency(ops_per_second)
- Compute energy efficiency metrics.
- deployment_lifetime(harvest, battery_mwh)
- Estimate deployment lifetime and maintenance intervals.
- adaptive_duty_cycle_sim(harvest, hours, min_active)
- Simulate time-varying adaptive duty cycling.
Function analyze_multi_harvest(fpga, stack, carbon)¶
Run sustainability analysis with a stacked harvest profile.
Module energy_accounting.unified_reporter¶
Class UnifiedEnergyReport¶
Combined report from runtime profiling + sustainability analysis.
- summary()
Class UnifiedEnergyReporter¶
Orchestrates power estimation → carbon accounting → thermal analysis.
Usage::
reporter = UnifiedEnergyReporter(region=GridRegion.EU)
report = reporter.analyze(total_power_mw=150.0, duration_h=1.0)
- init(region, ambient_temp_c, asic_power_mw)
- analyze(layer_configs, total_power_mw, inference_time_s)
- Full analysis: power → carbon → thermal.
Module ensembles.orchestrator¶
Class EnsembleOrchestrator¶
Manages a collective of SC-NeuroCore Agents. Implements ensemble consensus and coordinated action.
- add_agent(name, agent)
- run_consensus(pipeline, initial_input)
- Runs the same pipeline on all agents and averages results.
- coordinated_mission(goal)
- Assigns sub-tasks to agents based on their capabilities.
Module event_driven.simulator¶
Class SpikeEvent¶
One spike event in the priority queue.
Class EventStats¶
Statistics from an event-driven simulation run.
- summary()
Class EventDrivenSimulator¶
Event-driven asynchronous SNN simulator.
Parameters¶
n_neurons : int Total neurons. connectivity : list of (source, target, weight, delay) Synaptic connections. threshold : float Spike threshold for LIF neurons. tau_mem : float Membrane time constant (ms). v_rest : float Resting potential. v_reset : float Reset potential after spike. refractory : float Refractory period (ms).
- init(n_neurons, connectivity, threshold, tau_mem, v_rest, v_reset, refractory)
- inject_spikes(events)
- Inject external spike events.
- inject_current(events)
- Inject current pulses.
- run(duration)
- Run event-driven simulation.
- reset()
- Reset all state.
Module evo_substrate.deployment¶
Class TileAllocation¶
Maps an organism to a physical FPGA tile.
Class TileDeploymentTracker¶
Tracks which organisms are deployed on which FPGA tiles.
- init(num_tiles)
- deploy(organism, tile_id)
- Assign an organism to a tile and return the recorded allocation.
- evict(tile_id)
- Mark a tile as free without mutating the former organism.
- free_tiles()
- Return tile identifiers with no active allocation.
- utilisation()
- Return the fraction of tiles carrying an allocation.
Module evo_substrate.development¶
Class ActivationFunc¶
Select the nonlinear response used by a CPPN node.
Class CPPNNode¶
One node in a CPPN network.
Class CPPNEdge¶
One edge in a CPPN network.
Class CPPNGenome¶
Compositional Pattern Producing Network for developmental encoding.
- init()
- query(x, y)
- Query the CPPN at coordinates (x, y).
- generate_weight_matrix(rows, cols)
- Generate a weight matrix by querying CPPN at grid positions.
- num_nodes()
- Return the number of nodes in the CPPN graph.
- num_edges()
- Return the number of edges in the CPPN graph.
Module evo_substrate.ecology¶
Class Island¶
One sub-population (deme) in an island model.
Class IslandModel¶
Multi-deme evolution with periodic migration.
- init(num_islands, migration_rate)
- add_organism(island_id, organism)
- Append an organism to the selected island population.
- migrate(rng)
- Migrate best organisms between random island pairs.
- total_population()
- Return the number of organisms across every island.
Class NoveltyArchive¶
Behavioural novelty archive for novelty search.
- init(k_nearest, threshold)
- novelty_score(behaviour)
- Return mean distance to the nearest archived behaviours.
- maybe_add(behaviour)
- Archive a copied behaviour when its novelty exceeds the threshold.
- size()
- Return the number of archived behaviour vectors.
Class ExtinctionDetector¶
Detects population stagnation and triggers extinction events.
- init(stagnation_gens, kill_fraction)
- check(best_fitness)
- Record fitness and report whether recent progress stagnated.
- apply(population, rng)
- Kill kill_fraction of population randomly.
Class CoevoRole¶
Identify an organism's role in a co-evolutionary interaction.
Class CoevoOrganism¶
Organism with a co-evolutionary role.
Class CoevolutionArena¶
Runs predator-prey or symbiotic co-evolution.
- init()
- add_predator(organism)
- Add an organism to the predator population.
- add_prey(organism)
- Add an organism to the prey population.
- evaluate_interactions()
- Evaluate predator-prey fitness from pairwise interactions.
- total_organisms()
- Return the combined predator and prey population.
Module evo_substrate.emission¶
Class OrganismEmitter¶
Emits evolved organisms as NIR graph or Verilog.
- to_nir(genome)
- Emit a simplified NIR-compatible graph dict.
- to_verilog(genome, module_name)
- Emit Verilog wrapper for the organism.
- to_photonic_netlist(genome, pml_layers)
- Emit a photonic netlist compatible with the optics PhotonicCompiler.
Module evo_substrate.fitness¶
Class FitnessType¶
Identify the objective exposed by a fitness evaluation.
Class FitnessResult¶
Fitness evaluation result.
- compute_composite(w_acc, w_energy, w_latency)
- Update and return the weighted three-objective fitness.
Class FitnessEvaluator¶
Evaluates organism fitness from simulation metrics.
- init(fitness_type)
- evaluate(genome, metrics)
- Evaluate one genome from simulation metrics and hardware proxies.
Class HWFitnessReport¶
Fitness feedback from actual FPGA execution.
- hw_composite()
- Return the weighted accuracy, clock, and timing-closure score.
Class HWFitnessCollector¶
Collects HW fitness from deployed organisms.
- init()
- submit(report)
- Store the latest FPGA fitness report for one genome.
- get(genome_id)
- Return the latest report for the genome, if submitted.
- total_reports()
- Return the number of genomes with submitted FPGA reports.
Module evo_substrate.genome¶
Class TopologyGene¶
Encodes the network topology.
- to_vector()
- Serialise topology fields in their canonical five-value order.
- from_vector(cls, v)
- Construct a topology gene while enforcing physical parameter bounds.
Class NeuronGene¶
Encodes neuron-level parameters (ArcaneNeuron-compatible).
- to_vector()
- Serialise neuron kinetics in their canonical eight-value order.
- from_vector(cls, v)
- Construct neuron kinetics while enforcing finite lower bounds.
Class PlasticityGene¶
Encodes plasticity rule parameters.
- to_vector()
- Serialise plasticity fields in their canonical six-value order.
- from_vector(cls, v)
- Construct plasticity parameters while enforcing valid rates.
Class Genome¶
Complete genome for an evolving SC organism.
- to_vector()
- Return the canonical 19-value topology-neuron-plasticity vector.
- from_vector(cls, v, gen)
- Construct a genome from its canonical parameter vector.
- vector_dim()
- Return the number of values in the canonical genome vector.
- compute_id()
- Set and return the 12-hex SHA-256 prefix of the genome vector.
Class GenomeSerializer¶
Serializes/deserializes genomes for persistence.
- to_dict(genome)
- Return a JSON-ready mapping that preserves genome identity fields.
- from_dict(d)
- Reconstruct a genome from :meth:
to_dictoutput.
Module evo_substrate.lineage¶
Class LineageRecord¶
One entry in the ancestry log.
Class LineageTracker¶
Tracks ancestry graph for all organisms.
- init()
- record(organism, mutation_type)
- Append one ancestry record and index it by genome identifier.
- get_ancestors(genome_id)
- Walk the ancestry chain to the root.
- num_records()
- Return the number of recorded organisms.
Module evo_substrate.organism¶
Class Organism¶
One evolving SC organism.
Module evo_substrate.replication¶
Class ReplicationEngine¶
Manages organism reproduction, mutation, and deployment.
Selection → Replication → Mutation → Safety Check → Deploy
- init(mutation_engine, crossover_engine, fitness_evaluator, max_population, elitism, industrial_mode, runtime_fault_config, degradation_policy)
- seed(genome)
- Seed the population with an initial organism.
- replicate(parent)
- Create a mutated child from a parent.
- replicate_crossover(parent_a, parent_b)
- Create a child via crossover of two parents.
- evaluate_all(metrics_fn)
- Evaluate fitness for all living organisms.
- verify_runtime_faults(organism, config)
- Run seeded runtime fault diagnosis and apply bounded degradation.
- select_and_cull(survival_fraction)
- Select fittest organisms, cull the rest. Elitism preserved.
- evolve_generation(metrics_fn)
- Run one full evolutionary generation.
- best_organism()
- Return the highest-fitness living organism, if one is evaluated.
- best_fitness()
- Return the best living composite fitness, or zero when unavailable.
- mean_fitness()
- Return mean composite fitness across evaluated organisms.
Module evo_substrate.safety¶
Class RuntimeFaultConfig¶
Runtime fault-check settings for evolved SC organisms.
Class RuntimeFaultCheck¶
Recorded runtime fault/degradation decision for one organism.
- from_plan(cls, organism, plan)
- Capture a degradation plan against the organism's current identity.
- to_dict()
- Return a JSON-ready fault-check summary.
Class SafetyBounds¶
Constrains the mutation space to prevent runaway replication.
Enforces hard limits on genome parameters that could cause resource exhaustion or unsafe behaviour on FPGA tiles.
- clamp(genome)
- Clamp mutable genome fields to configured deployment bounds.
- is_within_bounds(genome)
- Return whether topology dimensions fit the configured bounds.
Class ResourceBudget¶
Per-organism resource constraints.
- check(genome)
- Return budget compliance and human-readable resource violations.
Class SafetyCheckResult¶
Result of a formal safety check on emitted Verilog/NIR.
Class FormalSafetyGuard¶
Validates emitted organisms against safety constraints before deployment.
Links to the safety_cert module for IEC 61508 compliance.
- init(bounds)
- check(genome)
- Evaluate topology limits and update cumulative rejection counters.
- rejection_rate()
- Return rejected checks divided by all completed checks.
Module evo_substrate.selection¶
Class HallOfFame¶
Maintains the top-N organisms across all generations.
- init(max_size)
- update(organism)
- Insert a fitted organism and retain the highest-ranked entries.
- best_fitness()
- Return the highest retained composite fitness, or zero when empty.
- size()
- Return the number of retained hall-of-fame entries.
Class TournamentSelector¶
Tournament selection with configurable pressure.
- init(tournament_size)
- select(population, rng)
- Return the highest-fitness member of one random tournament.
- select_n(population, n, rng)
- Run independent tournaments and return the requested selections.
Class ParetoFront¶
Maintains a non-dominated Pareto front.
- init()
- update(organism)
- Insert an organism when no retained member dominates its fitness.
- size()
- Return the number of non-dominated organisms.
Class AgeRegulator¶
Culls organisms that exceed a maximum lifespan.
- init(max_age)
- apply(population, current_generation)
- Mark over-age organisms dead and return the number culled.
Class BloatMetrics¶
Measures genome complexity for bloat detection.
- is_bloated()
- Return whether complexity exceeds the baseline bloat score.
Class BloatPenalizer¶
Penalizes fitness for bloated genomes.
- init(penalty_weight, threshold)
- penalize(fitness, genome)
- Apply a bounded multiplicative penalty above the bloat threshold.
Function dominates(a, b)¶
Return whether the first result Pareto-dominates the second.
Function compute_bloat(genome, baseline_neurons)¶
Compute bloat relative to a baseline.
Module evo_substrate.speciation¶
Function genomic_distance(a, b)¶
Normalised L1 distance between genome vectors.
Dispatches to the Rust evo_substrate_core.py_genomic_distance when
the compiled extension is importable. The NumPy fallback is kept as
the reference implementation and produces bit-exact identical values.
Function assign_species(population, threshold)¶
Assign organisms to species by genomic distance.
First organism of each species is the representative.
Function population_diversity(population)¶
Mean pairwise genomic distance (0 = clones, 1 = max diversity).
Function shared_fitness(organism, population, sigma)¶
Shared fitness: divide by niche count to prevent species domination.
Module evo_substrate.statistics¶
Class GenerationStats¶
Statistics for one generation.
Class EvoStatisticsTracker¶
Records per-generation statistics for analytics.
- init()
- record(stats)
- Append statistics for one completed generation.
- generations_tracked()
- Return the number of recorded generations.
- fitness_trajectory()
- Return best fitness in generation order.
- diversity_trajectory()
- Return population diversity in generation order.
- improvement_rate()
- Return best-fitness change from the first to latest generation.
Class GenomeDiff¶
Structural diff between two genomes.
- is_identical()
- Return whether the canonical vectors contain no changed values.
Class ComplexityTracker¶
Tracks population complexity over generations.
- init()
- record(generation, population)
- Append mean and maximum complexity for a non-empty population.
- mean_trajectory()
- Return mean genome complexity in generation order.
- is_complexifying()
- Return whether mean complexity increased over three or more samples.
Function genome_diff(a, b)¶
Compute structural diff between two genomes.
Function genome_complexity(genome)¶
Measure evolved complexity (information-theoretic).
Module evo_substrate.variation¶
Class MutationType¶
Identify the mutation operator applied to a child genome.
Class MutationConfig¶
Controls mutation rates and magnitudes.
Class MutationEngine¶
Applies mutations to genomes.
- init(config, rng_seed)
- mutate(genome)
- Apply a random mutation and return the mutated child.
Class CrossoverEngine¶
Uniform crossover between two parent genomes.
- init(rng_seed)
- crossover(parent_a, parent_b)
- Uniform crossover: each gene drawn from either parent.
Module exceptions¶
Class SCNeuroError¶
Base exception for all SC-NeuroCore errors.
Class SCEncodingError¶
Probability or bitstream value outside valid range.
Class SCConfigError¶
Invalid configuration parameter (layer size, threshold, etc.).
Reserved for future use — v3.14.0 callers raise plain
ValueError for configuration errors. Migration tracked
under task #36.
Class SCWeightError¶
Weight value or shape mismatch.
Reserved for future use — v3.14.0 weight loaders raise plain
ValueError or KeyError for shape/value errors.
Migration tracked under task #36.
Class SCCompilerError¶
Compiler pipeline configuration or target error.
Raised by sc_neurocore.compiler.pipeline for unknown FPGA
target, invalid output names, and path-escape detection.
Class SCDependencyError¶
Optional dependency (JAX, Torch, PennyLane, Qiskit) not installed.
Raised by JAX backend, quantum hardware bridge, learning callbacks (W&B, TensorBoard) and similar feature-gated paths.
Class SCHardwareError¶
FPGA/hardware driver or bitstream error.
Raised by the PYNQ driver (missing IP block) and by Verilog export when the model is not in the LIF whitelist.
Class BitstreamOverflowError¶
Bitstream length exceeds the maximum supported width.
Reserved for future use — v3.14.0 bitstream encoders saturate
silently or raise plain ValueError for related issues
(e.g. the recent Q8.8 dt-underflow guard). Migration tracked
under task #36.
Class SeedCollisionError¶
Two encoders received the same LFSR seed, breaking decorrelation.
Reserved for future use — v3.14.0 the encoder API does not detect seed collisions. Implementing this would require a global seed registry across all encoders. Tracked under task #36.
Class BitwidthMismatchError¶
Operands have incompatible fixed-point widths.
Reserved for future use — v3.14.0 the compiler hard-codes Q8.8 throughout, so multi-width layouts are not supported. This exception will fire once the compiler accepts mixed widths. Tracked under task #36.
Class CoverageGateError¶
Test coverage fell below the required threshold.
Reserved for future use — v3.14.0 coverage gating lives in CI workflow YAML, not in Python code. The exception is here so coverage-aware tooling has a stable raise target. Tracked under task #36.
Class HardwareSimMismatchError¶
Python golden model and Verilog RTL produced different results.
Reserved for future use — v3.14.0 the cosim suite raises
plain AssertionError from pytest assertions instead of
this typed exception. Migration tracked under task #36.
Class IRCompilationError¶
IR graph failed verification or code generation.
Reserved for future use — v3.14.0 the compiler raises the
parent SCCompilerError (line 90 of pipeline.py)
rather than this leaf type. Migration tracked under task #36.
Module experimental.alternative_path¶
Class AlternativePathMode¶
Execution mode for an alternative path.
Class AlternativePathConfig¶
Explicit policy for alternative-path execution.
The default is intentionally conservative: baseline only.
Class ComparisonStats¶
Comparison summary between baseline and candidate outputs.
Class AlternativePathResult¶
Structured result of a safe alternative-path execution.
- to_report()
- Return a JSON-serialisable summary for logging or benchmarking.
Class AlternativePathCase¶
Named input case for repeated comparison and benchmarking.
Class AlternativePathBatchSummary¶
Aggregate report for a route evaluated over multiple named cases.
- to_report()
- Return a JSON-serialisable summary of the batch run.
Class AlternativePathRoute¶
Named pair of stable baseline and experimental candidate implementations.
- describe()
- Return route metadata for discovery and documentation.
- run(config)
- Execute the route according to the provided policy.
- evaluate_cases(cases, config)
- Run the route across named cases and aggregate compare/benchmark results.
Class AlternativePathRegistry¶
Registry for named alternative execution paths.
- init()
- register(route)
- get(name)
- names()
- describe()
- run(name, config)
- evaluate(name, cases, config)
Function compare_outputs(baseline, candidate, config, context)¶
Compare outputs from baseline and candidate implementations.
Module experimental.builtins¶
Function build_builtin_registry()¶
Register all built-in experimental routes.
Function builtin_cases_for_route(route_name)¶
Return the default case set for a built-in route.
Module experimental.examples¶
Function make_demo_sigmoid_route()¶
Create a self-contained demo route for benchmarking and comparison.
Function build_demo_registry()¶
Create a registry with the built-in demo route.
Module experimental.memory_routes¶
Function make_delayed_recall_shared_state_route()¶
Route a bounded delayed-recall task against a shared-memory candidate.
The candidate is quantum-inspired only in the broad architectural sense: it adds a non-local shared latent state to a real spiking baseline. It does not claim to model ATP, Posner molecules, or validated in-vivo quantum memory.
Module experimental.physics_routes¶
Function make_heat_cosine_mode_route()¶
Route Monte Carlo heat evolution against an exact Neumann cosine mode.
Function make_harmonic_symplectic_route()¶
Route harmonic-oscillator integration against the symplectic solver.
Function make_kuramoto_noiseless_symplectic_lift_route()¶
Route a bounded noiseless Kuramoto regime against a symplectic XY lift.
Module experimental.reporting¶
Function default_report_path(route_name)¶
Return the default JSON report path for a route.
Function write_batch_report(summary, path)¶
Write a batch summary to a JSON report file.
Module experimental.solver_routes¶
Function make_lif_subthreshold_exact_route()¶
Route subthreshold LIF integration against the analytical solution.
Module experiments.advanced_demo¶
Function run_advanced_demo()¶
Module experiments.agent_synergy_demo¶
Function run_agent_demo()¶
Module experiments.bitstream_drive¶
Function run_bitstream_driven_lif(x_input, x_min, x_max, length, neuron_params)¶
Drive a StochasticLIFNeuron with a bitstream-encoded input current.
Steps:
1. Encode scalar input current x_input in [x_min, x_max] as a unipolar
bitstream of length length.
2. At each time step t, set:
I_t = I_high if bitstream[t] == 1 else I_low
or more simply, treat the bit directly as a scaled current.
3. Run neuron for length steps, collect spike bitstream.
4. Estimate:
- input probability p_in from the input bitstream
- firing probability p_fire from the spike bitstream
Returns¶
input_bits : np.ndarray Input bitstream (0/1). spike_bits : np.ndarray Output spike bitstream (0/1). p_in : float Estimated input probability. p_fire : float Estimated firing probability.
Function demo()¶
Module experiments.deep_research_demo¶
Function run_deep_research_demo()¶
Module experiments.demo_adaptive_audio¶
Function run_demo()¶
Module experiments.demo_param_sweep¶
Function run_pattern_trials(label, x_inputs, weight_values, n_neurons, T, noise_std, n_trials, base_seed)¶
Run multiple trials of SCDenseLayer for a given pattern (x_inputs). Return matrix of shape (n_trials, n_neurons) with firing rates.
Function nearest_centroid_multi(sample, centroids)¶
Nearest-centroid classifier over K classes. centroids[k]: firing-rate centroid for class k.
Function demo()¶
Module experiments.demo_pattern_classification¶
Function run_pattern_trials(label, x_inputs, weight_values, n_neurons, T, n_trials, base_seed)¶
Run multiple trials of SCDenseLayer for a given pattern (x_inputs). Return matrix of shape (n_trials, n_neurons) with firing rates.
Function nearest_centroid_classify(sample, centroid_A, centroid_B)¶
Simple nearest-centroid classifier in firing-rate space. Returns label 0 or 1.
Function demo()¶
Module experiments.demo_pattern_classification_3class¶
Function run_pattern_trials(label, x_inputs, weight_values, n_neurons, T, n_trials, base_seed)¶
Run multiple trials of SCDenseLayer for a given pattern (x_inputs). Return matrix of shape (n_trials, n_neurons) with firing rates.
Function nearest_centroid_multi(sample, centroids)¶
Nearest-centroid classifier over K classes. centroids[k]: firing-rate centroid for class k.
Function demo()¶
Module experiments.demo_pattern_pca¶
Function compute_pca_2d(X)¶
Simple 2D PCA using SVD.
Parameters¶
X : np.ndarray Data matrix of shape (n_samples, n_features)
Returns¶
X_2d : np.ndarray Projection of X into 2D principal component space, shape (n_samples, 2) mean : np.ndarray Mean vector of original data (n_features,) components : np.ndarray PCA components (2, n_features)
Function demo_pca_plot()¶
Module experiments.demo_poisson_spikes¶
Function run_demo()¶
Module experiments.demo_sc_dense_layer¶
Function demo()¶
Module experiments.demo_sc_pipeline¶
Function demo()¶
Module experiments.demo_sleep_optimization¶
Function generate_eeg_epoch(stage, n_samples, sample_rate, rng)¶
Return n_samples of simulated EEG voltage for stage.
Function run_demo()¶
Module experiments.demo_swarm_control¶
Function run_demo()¶
Module experiments.demo_tcbo_consciousness¶
Function run_demo()¶
Module experiments.demonstration_convergence¶
Function run_demonstration()¶
Module experiments.exascale_demo¶
Function run_exascale_demo()¶
Module experiments.experimental_horizons_demo¶
Function run_horizons_demo()¶
Module experiments.l7_symbolic_coupling¶
Function gather_symbolic_features()¶
Function run()¶
Module experiments.learning_demo¶
Function run_learning_experiment()¶
Module experiments.mega_advancements_demo¶
Function run_demo()¶
Module experiments.quantum_neuromorphic_demo¶
Function run_demo()¶
Module experiments.spatial_generative_demo¶
Function run_spatial_gen_demo()¶
Module experiments.system_level_demo¶
Function run_system_demo()¶
Module experiments.tcbo_demo_engine¶
Class ScenarioName¶
Class ScenarioConfig¶
Class SyntheticEEGGenerator¶
Configurable Kuramoto oscillator network for synthetic EEG.
- init(N, dt, seed)
- set_coupling_scale(scale)
- apply_anesthesia(strength)
- apply_alpha_boost(factor)
- apply_coupling_decay(rate)
- step(perturbation)
- One Kuramoto timestep. Returns phases in [0, 2pi).
- run(n_steps)
- Run n_steps, return (n_steps, N) history.
- get_order_parameter()
- reset(seed)
Class TCBOController¶
PI controller for gap-junction coupling kappa.
- init(tau_h1, Kp, Ki, kappa_min, kappa_max)
- step(p_h1, kappa, dt)
- Compute new kappa from consciousness deficit.
- reset()
Class TCBODemoSnapshot¶
Per-step snapshot of the TCBO demo state.
- to_dict()
Class TCBODemoEngine¶
Orchestrates TCBO consciousness detection scenarios.
- init(N, dt, seed)
- get_scenarios()
- start_scenario(name)
- Initialize and start a named scenario.
- step()
- Advance one timestep.
- run_scenario(name, duration_s, subsample)
- Run a full scenario, returning subsampled snapshots.
- get_state()
- get_history(last_n)
- reset()
Function get_tcbo_demo_engine()¶
Function reset_tcbo_demo_engine()¶
Module experiments.whitepaper_benchmark¶
Function run_whitepaper_benchmark()¶
Module explain.spike_explain¶
Class ExplanationResult¶
Result of an explanation method.
- top_k(k)
- Return top-k most important (timestep, neuron_id, score) tuples.
- summary()
- Render a human-readable report of the top attributed inputs.
Class SpikeAttributor¶
Backward spike attribution via eligibility-trace chain.
Traces the contribution of each input spike to the output through intermediate layers using eligibility trace products. Approximation of temporal backpropagation attribution.
Parameters¶
decay : float Temporal decay factor for backward attribution (0-1).
- init(decay)
- attribute(spikes, weights, output_neuron)
- Compute per-input-spike attribution scores.
Class TemporalSaliency¶
Perturbation-based temporal saliency.
For each input spike, measure the change in output when that spike is removed. Spikes whose removal causes large output change are salient (important).
Parameters¶
run_fn : callable Function that takes input spikes (T, N) and returns output spike counts or rates (N_output,).
- init(run_fn)
- explain(spikes, output_neuron)
- Compute perturbation-based saliency for each input spike.
Class CausalImportance¶
Causal importance via forward intervention.
Silence each neuron (clamp to zero) across all timesteps and measure the impact on classification output. Builds a per-neuron causal importance score.
Parameters¶
run_fn : callable Function that takes input spikes (T, N) and returns output (N_output,).
- init(run_fn)
- explain(spikes, output_neuron)
- Compute causal importance by silencing each neuron.
Module explainability.explainability¶
Class LFSRReplay¶
Deterministic LFSR-16 replay engine.
Mirrors core_engine::Lfsr16 polynomial: x^16 + x^14 + x^13 + x^11 + 1.
Given the same seed, reproduces the exact same bitstream for formal
verification and replay-based auditing.
- init(seed)
- step()
- Advance one step, return new register value.
- encode(threshold, length)
- Generate a bitstream by comparing LFSR output against threshold.
- reset()
- Reset to initial seed for replay.
Class SpikeDecision¶
Class DecisionMargin¶
How close a decision was to flipping.
Class DecisionNode¶
One node in a spike decision tree.
- is_leaf()
- margin()
Class SpikeDecisionTree¶
Captures "why this spike fired" as a verifiable decision tree.
- init()
- add_decision(neuron_id, bitstream, threshold, scc, parent, timestep, layer_id, contributing_neurons, threshold_q16)
- Record a spike decision from bitstream observation.
- depth()
- num_spikes()
- num_nodes()
- nodes_at_layer(layer_id)
- Return all nodes at a given layer.
- nodes_at_timestep(timestep)
- Return all nodes at a given timestep.
- get_node(neuron_id)
- Look up a node by neuron ID.
- spike_path()
- Return the chain of spiking nodes from root down.
- to_dict()
Class ProvenanceStep¶
One step in a full provenance chain.
Class ProvenanceTrace¶
Full chain from input → encoding → computation → spike decision.
- init()
- add_step(stage, description, data, metadata)
- Record one provenance step.
- finalize()
- is_complete()
- num_steps()
- chain_hash()
- Hash of the entire provenance chain for tamper detection.
- to_list()
Class RegulatoryMetadata¶
IEC 62304 / FDA SaMD traceability fields.
Class FormalPropertyLink¶
Cross-reference to SymbiYosys formal verification.
Class VerifiabilityReport¶
Formal audit report with hash verification.
Class SensitivityResult¶
Result of a 'what-if' threshold perturbation.
Class SensitivityAnalyzer¶
Counterfactual analysis: 'would the decision flip if threshold ±N?'
- analyze(node, perturbations)
- critical_delta(node)
- Smallest threshold change that flips the decision.
Class CausalAttribution¶
Attribution of a spike to upstream neurons.
- top_contributors()
- Sorted (descending) list of contributing neurons.
Class CausalAttributor¶
Computes causal attribution from input neurons to output spike.
- attribute(target, input_bitstreams, weights)
- Compute per-input-neuron contribution to the target popcount.
Class DiffEntry¶
One field that differs between two explanations.
Class ExplanationDiff¶
Compares two decision nodes to find divergence points.
- diff(a, b)
Class TemporalWindow¶
Records decisions across timesteps for temporal attribution.
- init()
- add(node)
- spike_rate_at(timestep)
- active_timesteps()
- peak_timestep()
- Timestep with the highest spike rate.
- num_timesteps()
Class NaturalLanguageExplainer¶
Generates human-readable explanation strings.
- explain_node(node)
- explain_attribution(attr)
- explain_sensitivity(results)
- enhance_with_local_llm(text)
- Enhance a deterministic explanation through the local LLM bridge.
- explain_node_with_local_llm(node)
- Generate a local-LLM-enhanced explanation for one decision node.
Class MultiLayerTrace¶
Traces decisions across network layers.
- init()
- add(node)
- layer_ids()
- spikes_at_layer(layer_id)
- spike_rate_at_layer(layer_id)
- propagation_path()
- Per-layer spike rate for visualising propagation.
Class SymbolicPathStep¶
One step in a symbolic decision path.
Class SymbolicPath¶
Human-readable symbolic path: input → encoding → decision.
- init()
- add(neuron_id, decision, reason)
- length()
- to_list()
Class ExplainabilityEngine¶
End-to-end explainability: replay + decision tree + provenance.
- init(seed)
- explain_spike(neuron_id, threshold_q16, bitstream_length, spike_threshold_count, scc, timestep, layer_id, contributing_neurons)
- Explain one spike decision via deterministic replay.
- verify(regulatory, formal_properties)
- Generate a verifiability report with full replay check.
- replay_bitstream(threshold_q16, length)
- Replay a bitstream from the engine's seed (for external comparison).
- sensitivity(node, perturbations)
- Run sensitivity analysis on a decision node.
- attribute(target, input_bitstreams, weights)
- Compute causal attribution for a decision.
- explain_spike_with_local_llm(neuron_id, threshold_q16, bitstream_length, spike_threshold_count)
- Run the deterministic explainability path, then enhance it locally.
Module export.compiler_export¶
Class SSAEnvironment¶
Manages Static Single Assignment (SSA) registers for MLIR/Relay.
- init()
- allocate(edge_name)
- Allocate and bind the next SSA register for an SC-IR edge.
- get(edge_name)
- Return an allocated register or validate an external input register.
Class ShapeInference¶
Infers tensor shapes dynamically across the SNN graph.
- init(input_shapes)
- infer(node)
- Infer and store the output shape for one supported SC-IR node.
Class CompilerExporter¶
Export SC-IR graph-like objects to strict SSA MLIR text.
- init(target)
- Create an exporter for a supported compiler backend target.
- export_to_mlir(ir_graph, input_shapes)
- Emit strict SSA MLIR text via topological traversal.
Module export.onnx_export¶
Class ONNXTensorType¶
Tensor element type and static shape for the JSON ONNX model.
Parameters¶
elem_type: ONNX tensor element type id. shape: Static tensor dimensions.
- to_dict()
- Return the ONNX tensor-type dictionary representation.
Class ONNXNode¶
Custom-domain ONNX node for a lowered stochastic-computing operation.
Parameters¶
op_type: ONNX operator type. domain: Operator domain. inputs: Input tensor names. outputs: Output tensor names. name: Stable node name. attributes: Optional scalar operator attributes.
- to_dict()
- Return the ONNX node dictionary representation.
Class ONNXGraph¶
JSON-serializable ONNX model envelope.
Parameters¶
name: ONNX graph name. nodes: Lowered ONNX nodes. inputs: Named graph inputs and tensor types. outputs: Named graph outputs and tensor types. metadata: String metadata entries attached to the model.
- to_dict()
- Return the complete ONNX model dictionary representation.
- to_json(indent)
- Return the complete ONNX model as formatted JSON.
Class ONNXExporter¶
Export SC-NeuroCore IR graphs to ONNX-compatible dictionaries.
Parameters¶
graph_name: Name assigned to the emitted ONNX graph.
- init(graph_name)
- export(ir_graph, input_shapes, metadata)
- Convert an SC-IR graph to an ONNX graph representation.
Module export.onnx_exporter¶
Class SCOnnxExporter¶
Export SC networks to ONNX protobuf or legacy JSON.
- export(layers, filename)
- Export layers to filename.
Module export.pipeline¶
Class PipelineStageResult¶
Result from a single pipeline stage.
output accepts strings (verilog / relay / mlir text) and the
richer ONNXGraph object so each stage can store its native
representation without stringifying.
Class PipelineResult¶
Full pipeline result.
- success()
- summary()
Class ExportPipeline¶
End-to-end: NeuronPlugin → ONNX → TVM → MLIR → Verilog.
Usage::
pipeline = ExportPipeline()
result = pipeline.run("LIF", n_neurons=64, bitstream_length=256)
print(result.verilog)
- init(registry, target)
- run(neuron_name, n_neurons, bitstream_length, module_name)
- Execute the full export pipeline for a neuron model.
Module export.tvm_lowering¶
Class TargetDevice¶
Class TargetSchedule¶
- for_fpga(cls, vendor)
- for_gpu(cls)
- for_cpu(cls)
Class RelayFunction¶
- to_relay_text()
Class TVMLowering¶
Lowers SC-NeuroCore IR to TVM Relay IR text representation.
- init(schedule)
- lower(ir_graph, input_shapes, func_name)
- Lower SC-IR graph to Relay IR text.
- emit_build_script(relay_text)
- Generate a self-contained TVM build script for the lowered IR.
Module fault_injection.fault_injection¶
Class FaultModel¶
Class RadiationProfile¶
Preset radiation environments with typical BER (bit error rate).
- post_init()
- leo(cls)
- geo(cls)
- deep_space(cls)
- terrestrial(cls)
Class FaultInjectionResult¶
- post_init()
- probability_original()
- probability_corrupted()
- absolute_error()
Class ResilienceReport¶
- post_init()
- summary()
Class FaultInjector¶
Applies configurable faults to SC bitstreams.
- init(seed)
- inject(bitstream, model, ber)
- Inject faults into a boolean bitstream.
- inject_at_positions(bitstream, positions)
- Flip specific bit positions (deterministic injection).
Class ResilienceBenchmark¶
Monte-Carlo resilience benchmarking harness.
- init(seed)
- run()
- Run Monte-Carlo fault injection trials.
- sweep_ber()
- Sweep across multiple BER values to produce a degradation curve.
Module fault_injection.resilience_mode¶
Class ResilienceModeConfig¶
Configuration for a resilience-mode run over one bitstream layer.
- post_init()
Class ResilienceModeTrialReport¶
Aggregate measurements for one fault model.
- post_init()
- to_dict()
- Return a JSON-ready report.
Class ResilienceModeReport¶
Full resilience-mode output for one layer and radiation profile.
- post_init()
- requires_replay()
- Whether any fault model requires deterministic replay.
- to_dict()
- Return a JSON-ready report.
Class FaultInjectionResilienceMode¶
Run seeded fault-injection trials and degradation policy together.
- init(config)
- run(bitstreams)
- Evaluate resilience for a binary
(neurons, bits)layer.
Module fault_injection.resilience_policy¶
Class DegradationAction¶
Runtime action recommended after seeded fault diagnosis.
Class SeededFaultObservation¶
Fault-injection observation linked to deterministic replay seed.
- post_init()
Class DegradationPlan¶
Graceful-degradation decision derived from seeded diagnostics.
- post_init()
- to_dict()
- Return a JSON-ready summary without expanding full bitstreams.
Class GracefulDegradationPolicy¶
Combine seeded fault injection with stochastic-doctor diagnosis.
- post_init()
- evaluate(bitstreams)
- Inject seeded faults, audit the layer, and recommend degradation.
Module federated.federated_sc¶
Class DPMechanism¶
Bitstream-level differential privacy via calibrated bit-flipping.
Instead of adding Gaussian/Laplace noise to real-valued gradients, we flip bits in the SC bitstream with probability p. This achieves (ε,0)-differential privacy where ε = ln((1-p)/p) per bit.
For a bitstream of length L, the total privacy cost is ε_total via Rényi-DP composition (tighter than naive composition).
- flip_probability()
- Calibrated bit-flip probability for the target ε.
- privatise(bitstream, rng)
- Apply DP noise by flipping bits with calibrated probability.
- per_bit_epsilon()
- Privacy cost per individual bit.
- total_epsilon(bitstream_length)
- Total ε under advanced composition (Rényi-based bound).
Class PrivacyAccountant¶
Rényi Differential Privacy (RDP) composition tracker.
Tracks cumulative privacy budget across federated rounds. Uses the moments accountant for tight composition.
- consume_round(mechanism, bitstream_length)
- Account for one round. Returns True if budget remains.
- current_epsilon()
- Convert accumulated RDP to (ε,δ)-DP.
- remaining_epsilon()
- How much budget is left.
- is_exhausted()
- Return whether the privacy budget is exhausted.
Class SecretShare¶
Additive secret sharing over GF(2) for bitstream aggregation.
Splits a bitstream into N shares such that XOR of all shares recovers the original. Individual shares reveal nothing.
- split(bitstream, rng)
- Split bitstream into additive GF(2) shares.
- reconstruct(shares)
- Reconstruct bitstream from all shares (XOR).
- verify_reconstruction(original, shares)
- Verify that shares reconstruct correctly.
Class CommitmentScheme¶
SHA-256 commitment for verifiable aggregation.
Compatible with the ZKPVerifier in security/zkp.py.
- commit(data, nonce)
- Create a binding commitment to data.
- verify(data, commitment, nonce)
- Verify a commitment.
- generate_nonce(rng)
- Generate a random 32-byte nonce.
Class SCGradientEncoder¶
Encodes real-valued gradients as SC bitstreams with DP noise.
- encode(gradients, seeds, rng)
- Encode gradient vector as privatised SC bitstreams.
- decode(bitstreams, g_min, g_max)
- Decode SC bitstreams back to gradient values.
Class FederatedClient¶
One participant in federated SC learning.
- post_init()
- Seed the client RNG deterministically from the client id.
- local_train(data, labels, lr)
- Simulate one local training step (gradient computation).
- encode_gradients(gradients)
- Encode gradients as privatised SC bitstreams + commitment.
Class FederatedAggregator¶
Secure aggregation server for federated SC bitstreams.
- aggregate_bitstreams(client_bitstreams, weights)
- Weighted majority-vote aggregation of SC bitstreams.
- detect_outliers(client_bitstreams, threshold)
- Detect malicious/outlier clients via cosine similarity.
- verify_commitments(client_bitstreams, commitments, nonces)
- Verify that submitted bitstreams match commitments.
Class ConvergenceTracker¶
Tracks loss/gradient-norm across federated rounds.
- record(aggregated_gradient)
- Record one round's gradient norm.
- record_loss(loss)
- Append a per-round loss value to the client history.
- converged()
- Simple heuristic: converged if last 5 grad norms < 0.01.
- trend()
- Return trend direction.
Class FederatedRound¶
Orchestrates one complete round of federated SC learning.
- run(data_per_client, labels_per_client, client_weights)
- Execute one federated round.
- status()
- Return current federated learning status.
Class DPCertificate¶
Exportable privacy proof document for regulatory compliance.
- from_accountant(cls, accountant, mechanism, bitstream_length)
- Build a differential-privacy certificate from an accountant.
- to_dict()
- Return the certificate as a serialisable dictionary.
- is_compliant()
- Return whether the spent epsilon is within the target budget.
Class AdaptiveEpsilonScheduler¶
Dynamically adjust ε per round based on convergence state.
- post_init()
- Initialise the current epsilon to the base privacy budget.
- step(converging)
- Compute ε for the next round.
Class ErrorFeedback¶
Error feedback for gradient sparsification.
Accumulates the residual from sparsification to avoid information loss over rounds.
- accumulate(gradients)
- Add residual from previous round.
- update(original, sparse)
- Store the residual (what was lost to sparsification).
Class AuditEntry¶
Single audit log entry for one federated round.
- post_init()
- Stamp the audit entry with the current wall-clock time.
Class AuditLog¶
Per-round provenance record for regulatory compliance.
- log_round(round_number, num_active, epsilon_consumed, grad_norm)
- Record one federated round in the audit log.
- to_list()
- Return the audit log as a list of serialisable dictionaries.
- total_rounds()
- Return the number of logged federated rounds.
- max_epsilon()
- Return the maximum epsilon recorded across all rounds.
Function lfsr_encode(value, seed, length)¶
Encode a probability [0,1] into a packed bitstream using LFSR-16.
Function bitstream_probability(bits)¶
Estimate probability from a bitstream.
Function clip_gradients(gradients, max_norm)¶
L2 gradient clipping for formal DP sensitivity bounds.
Clips the gradient vector so its L2 norm ≤ max_norm. This is required for provable (ε,δ)-DP guarantees.
Function sparsify_topk(gradients, k)¶
Top-k gradient sparsification.
Returns (sparse_gradients, mask) where only k largest-magnitude entries are non-zero. Reduces communication cost proportionally.
Function poisson_subsample(clients, sampling_rate, rng)¶
Poisson subsampling of clients for privacy amplification.
Each client is independently included with probability sampling_rate.
This provides privacy amplification by a factor of O(sampling_rate).
Function stochastic_quantize(gradients, levels, rng)¶
Stochastic quantization to reduce communication bits.
Quantizes each gradient to one of levels levels with
unbiased randomized rounding. E[Q(g)] = g.
Function krum_select(client_vectors, num_byzantine)¶
Multi-Krum selection: find the vector closest to most others.
Returns the index of the most "central" client update.
Tolerates up to num_byzantine malicious clients.
Function trimmed_mean(client_vectors, trim_fraction)¶
Coordinate-wise trimmed mean aggregation.
Removes the top and bottom trim_fraction of values per
coordinate before averaging. Robust to Byzantine clients.
Function fedprox_gradient(gradients, local_weights, global_weights, mu)¶
Add FedProx proximal term for non-IID robustness.
grad_proximal = grad + μ * (w_local - w_global)
Function amplified_epsilon(base_epsilon, sampling_rate)¶
Compute privacy amplification from Poisson subsampling.
Uses the Balle et al. (2018) bound: ε' ≈ log(1 + q(e^ε - 1)) where q is the sampling rate.
Module federation.attestation¶
Class FpgaArtifact¶
A content-addressed FPGA evidence artifact backing a hardware claim.
Parameters¶
role
What the artifact is — e.g. "synthesis-timing", "synthesis-utilisation",
"cosim-transcript" (the bit-exactness proof), or "bitstream".
digest
SHA-256 of the artifact ("sha256:<hex>"); the identity that binds the claim
to the real file.
media_type
The artifact's media type (e.g. "text/vivado-timing").
Raises¶
ValueError If any field is blank.
- post_init()
- Reject blank fields — every artifact must be addressable.
- to_dict()
- Return the JSON-serialisable mapping of the artifact.
Function regrade_sc_inference(unit)¶
Recompute the sc-inference grade from the signed unit.
reference-validated only when the accelerated backend is bit-identical to the
NumPy floor (max_abs_error == 0); otherwise bounded-model. Derived from the
evidence, never read from a (forgeable) claim_status field.
Function seal_sc_inference(result)¶
Seal an sc-inference result in recompute mode (no attestation).
Parameters¶
result
The path-free stochastic-computing inference result.
signer
The studio's :class:~scpn_studio_platform.seal.keys.Signer.
Returns¶
HonestyEnvelope A recompute-verifiable envelope: the WASM/NumPy kernel re-derives the result and its digest must match.
Function regrade_fpga(unit)¶
Recompute the FPGA grade from the signed unit.
reference-validated only when the co-simulation is bit-exact and a
cosim-transcript artifact backs that claim; otherwise validation-gap. A
bit-exact flag with no transcript to prove it does not earn the validated grade.
Function attest_fpga_deployment(result, artifacts)¶
Seal an FPGA deployment in attestation mode with a signed result-pack.
The FPGA run cannot be recomputed client-side, so the claim is verified by signature
plus artifact-digest binding, not recompute. The result-pack reference content-
addresses the real Vivado/cosim/bitstream artifacts and is studio-self-attested (the
provider_sig is the studio's detached signature over the pack digest).
Parameters¶
result
The path-free synthesis/deployment result.
artifacts
The content-addressed artifacts the claim rests on; at least one is required, and
a cosim-transcript must be present for the claim to grade as validated.
signer
The studio's :class:~scpn_studio_platform.seal.keys.Signer.
Returns¶
HonestyEnvelope
An attestation-verifiable envelope on the fpga substrate.
Raises¶
ValueError If no artifacts are supplied.
Function verify_envelope(envelope, rendered_grade)¶
Verify a SC-NeuroCore honesty envelope, dispatching the regrade by schema.
Parameters¶
envelope
The :meth:HonestyEnvelope.to_dict wire form on the page, or None when the
page carries no seal.
rendered_grade
The grade the page displays for the claim, or None.
keyring
The trust anchor mapping key_id → public verifier.
Returns¶
Verdict
:data:~scpn_studio_platform.seal.verdict.Verdict.VERIFIED only when the
signature is valid and the rendered grade equals the grade recomputed from the
signed unit; otherwise STRIPPED / FORGED / UNGRADED.
Module federation.evidence¶
Class ScInferenceResult¶
A path-free stochastic-computing inference result.
Parameters¶
active_backend
The accelerated backend that produced the result (e.g. "rust").
reference_backend
The bit-true reference backend (the NumPy floor).
max_abs_error
Maximum absolute difference between the active and reference outputs for
the fixed seed; 0.0 means bit-identical.
bitstream_length
The stochastic bitstream length used.
input_digest
SHA-256 of the weights/inputs/seed.
result_digest
SHA-256 of the output firing rates.
Raises¶
ValueError If a count is non-positive, an error is negative, or a digest is empty.
- post_init()
- Validate counts, error sign, and digests.
Class FpgaDeploymentResult¶
A path-free FPGA synthesis/deployment result.
Parameters¶
device
The target device (e.g. "xc7z020-1clg400").
cosim_bit_exact
Whether the synthesised RTL co-simulation matched the Q8.8 fixed-point
reference bit-for-bit.
lut_used, ff_used
Look-up tables and flip-flops consumed by the synthesised design.
worst_negative_slack_ns
Worst negative slack at the target clock; >= 0 means timing closed.
clock_mhz
The synthesis target clock frequency, in MHz.
result_digest
SHA-256 of the bitstream / synthesis report.
Raises¶
ValueError If a resource count is negative, the clock is non-positive, or the digest is empty.
- post_init()
- Validate resource counts, clock, and digest.
Function sc_inference_evidence(result)¶
Build the studio.sc-inference.v1 bundle (measured software result).
Parameters¶
result The path-free inference result. operator Opaque identity of the operator/tenant. studio_version Version of the SC-NeuroCore studio that produced the result. started, ended ISO-8601 start/end timestamps (passed in; no hidden clock). host Optional host descriptor the run executed on.
Returns¶
EvidenceBundle
A measured bundle that renders as validated only when the accelerated
backend is bit-identical to the NumPy floor.
Function fpga_deployment_evidence(result)¶
Build the studio.fpga-deployment.v1 bundle (hardware-validated silicon).
The synthesised RTL is co-simulated against the Q8.8 fixed-point reference on
the fpga substrate. The claim is reference-validated only when that
co-simulation is bit-exact; a mismatch degrades to validation-gap.
Parameters¶
result The path-free synthesis/deployment result. operator Opaque identity of the operator/tenant. studio_version Version of the SC-NeuroCore studio that produced the result. started, ended ISO-8601 start/end timestamps (passed in; no hidden clock). host Optional host descriptor the synthesis ran on.
Returns¶
EvidenceBundle
A hardware-validated bundle on the fpga substrate.
Module federation.manifest¶
Function declared_surface()¶
Return the content-addressable declared surface of the SC-NeuroCore studio.
The surface is the canonical JSON of each advertised verb plus the evidence schema list, keyed by a stable logical path. Hashing surface content (not git state) is what makes the digest reproducible across checkouts.
Returns¶
dict[str, bytes]
Mapping of logical path to canonical-JSON bytes, suitable for
:func:scpn_studio_platform.manifest.content_digest.
Function build_manifest()¶
Build the SC-NeuroCore studio's capability manifest.
Parameters¶
studio_version
The studio version to stamp; defaults to :data:STUDIO_VERSION (the
source sc-neurocore version).
Returns¶
CapabilityManifest
The schema-A manifest, with a content digest over :func:declared_surface.
Module federation.verbs¶
Function core_verbs()¶
Return the SC-NeuroCore verbs drawn from the shared core spine.
Returns¶
tuple[Verb, ...]
The subset of :data:NEUROCORE_VERBS whose names are in the platform
:data:scpn_studio_platform.verbs.CORE_VERBS.
Function domain_verbs()¶
Return the SC-NeuroCore verbs distinctive to a neuromorphic studio.
Returns¶
tuple[Verb, ...]
The subset of :data:NEUROCORE_VERBS not present in the platform core
spine (encode, deploy).
Function evidence_schemas()¶
Return the distinct evidence schemas every SC-NeuroCore verb emits.
Returns¶
tuple[str, ...]
The sorted, de-duplicated union of each verb's produces schemas.
Module few_shot.haam¶
Class HebbianFewShot¶
Class-indexed Hebbian memory for few-shot spike episodes.
Parameters¶
n_features : int Number of spike-rate features per pattern after temporal averaging. n_classes : int Number of class slots stored by the associative memory. lr_hebbian : float, default=0.1 Non-negative multiplier applied when support patterns are accumulated into their class memory rows.
- init(n_features, n_classes, lr_hebbian)
- store(spike_pattern, label)
- Store one support pattern in the class memory.
- query_scores(spike_pattern)
- Return cosine scores for a query against every stored class.
- query(spike_pattern)
- Classify one query pattern by nearest stored memory.
- few_shot_episode(support_x, support_y, query_x)
- Run one reset-store-query few-shot episode.
- export_weights()
- Return a defensive copy of the class memory matrix.
- reset()
- Clear the memory matrix and support counts.
Class SpikePrototypeNet¶
Nearest-prototype classifier for spike-rate few-shot episodes.
Parameters¶
n_features : int
Number of features per vector after temporal averaging.
metric : {"cosine", "euclidean", "hamming"}, default="cosine"
Distance or similarity metric used to score queries against support-set
prototypes. hamming thresholds vectors at zero and scores by negative
normalised bit disagreement.
- post_init()
- Validate the prototype classifier configuration after dataclass init.
- classify(support_x, support_y, query_x)
- Classify query patterns from support-set prototypes.
- export_prototypes()
- Return defensive copies of the most recently computed prototypes.
Module fitting.cohort¶
Class CohortSample¶
An independently split recording with explicit additive input noise.
group identifies the acquisition, subject or simulation replicate;
related recordings must stay in one split. observations names physical
state variables; spikes contains one binary event per simulation step.
Noise is sampled before submission and replayed exactly for every model.
- post_init()
- Refuse ambiguous splits, missing names and nonfinite samples.
- effective_current()
- Return the identical additive input supplied to every trial.
- to_public_dict()
- Export all samples and their split custody.
Class SweepDomain¶
Explicit finite parameter values, typed as integer or real.
- post_init()
- Refuse nonfinite, duplicate or incorrectly typed values.
- to_public_dict()
- Export every trial value without resampling a range.
Class CohortMetric¶
A model-specific observable and a declared lower-is-better metric.
Trace RMSE requires the observed state and its physical unit. Binary event disagreement and absolute spike-count error operate on the recorded events.
- post_init()
- Require metric-specific units instead of mixing unlike errors.
- to_public_dict()
- Export the precise metric contract.
Class CohortModel¶
One complete DSL model, its parameter sweep and its chosen metric.
- post_init()
- Validate model references and unique parameter/constraint names.
- trial_count()
- Return the Cartesian sweep size without materialising trials.
- parameter_sets()
- Iterate the complete declared grid, including infeasible trials.
- to_public_dict()
- Export the schema, sweep, metric and constraints together.
Class ExperimentCohort¶
Versioned experiment with one time/input contract and leakage-safe splits.
- post_init()
- Check sample custody, common timebase and complete pre-run admission.
- trial_count()
- Return the complete grid size across all models.
- estimated_steps()
- Return the complete simulation-step budget before execution.
- to_public_dict()
- Export the full effective cohort, sufficient for replay.
Function cohort_sha256(payload)¶
Hash JSON with integral float values normalised for browser round trips.
JSON readers may emit 1 where Python emitted 1.0. Those are the
same numerical cohort sample and must retain their digest after transport.
Function cohort_from_dict(document)¶
Read a full cohort with strict version, field and numeric custody.
Module fitting.cohort_run¶
Function run_cohort(cohort)¶
Run every declared trial, retaining rejected and divergent members.
Parameters¶
cohort: Admitted complete models, samples, sweep domains and split custody. progress: Optional trial-event sink; raising cancels execution.
Returns¶
dict Full cohort, all trial outcomes, training-only selection, provenance and deterministic result digest. Hardware measurements are not inferred.
Function replay_cohort(result)¶
Recompute the whole sweep and compare complete result digests.
Module fitting.constraints¶
Class ParameterConstraint¶
Require low <= sum(coefficients[name] * value[name]) <= high.
Coefficients and bounds are in the model's value space, including when a parameter is searched logarithmically. Bounds must define a nonempty interval; equality constraints are refused.
- post_init()
- Refuse empty, nonfinite or reversed constraint definitions.
- value(parameters)
- Evaluate this combination without changing parameter units.
- accepts(parameters)
- Return whether the value obeys both bounds without clamping.
- to_public_dict()
- Export the whole named constraint for deterministic replay.
Function constraints_from_dict(entries)¶
Read exported constraints, preserving all coefficients and bounds.
Module fitting.fit¶
Function fit_parameters(problem)¶
Fit problem and return the complete, replayable result.
Parameters¶
problem:
The model, domains and split cohort.
progress:
Optional generation-event sink; it may raise to cancel a background job.
generations, population:
Differential-evolution size: at most generations generations of
population members per fitted parameter.
Returns¶
dict The problem as given, the fitted values, training and hold-out error per recording, the optimiser history and trial counts, the identifiability diagnosis, the uncertainty, provenance, and the digest binding them.
Function replay_fit(result)¶
Run an exported fit again and say whether it reproduced.
Returns¶
dict
reproduced is true when the new result's digest equals the exported
one; both digests and the new result are included.
Module fitting.pareto¶
Function measured_pareto(result, receipts)¶
Return nondominated holdout-error/latency/resource/energy rows or refuse.
Parameters¶
result: Complete cohort result whose scientific digest and trials are verified. receipts: Operator-supplied physical measurement documents, each bound to one trial and the cohort. All acquisition contracts must match exactly.
Returns¶
dict Custody-labelled comparison; all four axes are minimised. Missing or incomparable evidence yields no frontier and an explicit reason. The reason is always one of this module's fixed refusal sentences, never exception text, because the Studio returns it to remote callers.
Module fitting.problem¶
Class ParameterDomain¶
The range one parameter is searched over.
Attributes¶
name:
A parameter of the model's schema.
low, high:
Finite bounds, low < high.
scale:
log searches the logarithm (bounds must be positive), for a
parameter whose plausible values span decades.
- post_init()
- internal_bounds()
- Return the bounds in the space the optimiser searches.
- to_value(internal)
- Map a searched coordinate back to the parameter's own value.
- to_public_dict()
- Return the domain as it is exported.
Class Recording¶
One stimulus and the observed variable's response, sample by sample.
- post_init()
- Validate sample lengths, finiteness and optional acquisition custody.
- data_sha256()
- Digest of the samples, independent of the recording's name.
- to_public_dict()
- Return the recording as it is exported.
Class FitProblem¶
A model, what to fit in it, and a cohort split into training and hold-out.
- post_init()
- Admit the model, parameter references, seed and leakage-safe split.
- to_public_dict()
- Return the whole problem as it is exported and replayed.
Function canonical_sha256(payload)¶
Return the digest of a JSON value in canonical form.
Function problem_from_dict(document)¶
Rebuild a problem from its exported form.
Raises¶
ValueError When the document is another version or its fields do not form a valid problem.
Function simulate(schema, observable, parameters, current)¶
Run the model with parameters under current and return the observable.
Returns¶
numpy.ndarray or None
The observable after each step, or None when the state stopped
being finite: a failed trial.
Module fitting.refusals¶
Class LaboratoryRefusal¶
A deliberate laboratory validation message safe for the caller to read.
Generated conversion, schema and structural exceptions remain unmarked; the HTTP boundary replaces them with its fixed malformed-document message.
Module formal.counterexample_replay¶
Class RateBoundReplayResult¶
Replay result for an aligned-window network rate-bound property.
Class RefractoryReplayResult¶
Replay result for a monitored-output refractory invariant.
Class AntagonisticReplayResult¶
Replay result for a mutually-exclusive output-pair invariant.
Class TemporalSeparationReplayResult¶
Replay result for a bidirectional temporal-separation invariant.
Class PopulationCoactivationReplayResult¶
Replay result for a population-level output coactivation cap.
Class PopulationSilenceReplayResult¶
Replay result for post-coactivation global output silence.
Class PopulationInactivityReplayResult¶
Replay result for bounded consecutive population inactivity.
Function replay_rate_bound_counterexample(spike_trace, rate_bound)¶
Replay a spike trace against the same aligned-window rate bound used by SVA.
Function replay_refractory_counterexample(spike_trace, refractory)¶
Replay a spike trace against a monitored-output refractory invariant.
Function replay_antagonistic_counterexample(spike_trace, exclusion)¶
Replay a spike trace against a mutually-exclusive output-pair invariant.
Function replay_temporal_separation_counterexample(spike_trace, separation)¶
Replay a spike trace against a bidirectional output temporal separation.
Function replay_population_coactivation_counterexample(spike_trace, population)¶
Replay a spike trace against a population coactivation cap.
Function replay_population_silence_counterexample(spike_trace, silence)¶
Replay a spike trace against a post-coactivation global silence contract.
Function replay_population_inactivity_counterexample(spike_trace, inactivity)¶
Replay a spike trace against a bounded consecutive-inactivity contract.
Module formal.lean_bridge¶
Class FormalProofEngine¶
Invokes Lean 4 safety_bounds.lean to formally verify mathematical parameters dynamically.
- init()
- is_available()
- list_axioms()
- Return explicit Lean axiom names declared in the bundled proof file.
- list_theorems()
- Return explicit top-level Lean theorem names declared in the proof file.
- axiom_inventory_matches()
- Return True only when the proof file contains the reviewed axiom set.
- theorem_inventory_matches()
- Return True only when the proof file contains the reviewed theorem set.
- proof_inventory_matches()
- Return True only when reviewed theorem and axiom inventories match.
- check_proofs()
- Invoke native Lean elaboration for the bundled proof boundary.
Module formal.network_properties¶
Class DenseLIFNetworkSpec¶
Formal boundary contract for a dense LIF network HDL module.
- post_init()
Class NetworkRateBound¶
Bound a selected output neuron's spike count inside a fixed time window.
- post_init()
Class NetworkRefractoryInvariant¶
Forbid a selected output from spiking during its refractory window.
- post_init()
Class NetworkAntagonisticOutputExclusion¶
Forbid two antagonistic network outputs from spiking in the same cycle.
- post_init()
Class NetworkOutputTemporalSeparation¶
Forbid two outputs from spiking within a bounded cycle window.
- post_init()
Class NetworkPopulationCoactivationCap¶
Bound the number of simultaneously active outputs in a sample cycle.
- post_init()
Class NetworkPopulationSilenceAfterCoactivation¶
Require global output silence after a population coactivation event.
- post_init()
Class NetworkPopulationInactivityBound¶
Bound consecutive valid cycles with no active network outputs.
- post_init()
Function validate_systemverilog_identifier(value)¶
Return value after checking it is a plain SystemVerilog identifier.
Module formal.property_compiler¶
Function compile_dense_lif_fixture_rtl(network)¶
Compile a deterministic dense LIF fixture RTL module for formal runs.
Function compile_network_rate_bound_sva(network, rate_bound)¶
Compile a network output spike-rate contract into deterministic SVA.
Function compile_network_refractory_sva(network, refractory)¶
Compile a network output refractory contract into deterministic SVA.
Function compile_network_antagonistic_exclusion_sva(network, exclusion)¶
Compile a mutually-exclusive output-pair contract into deterministic SVA.
Function compile_network_temporal_separation_sva(network, separation)¶
Compile a bidirectional output temporal-separation contract into SVA.
Function compile_network_population_coactivation_sva(network, population)¶
Compile a population-level output coactivation cap into deterministic SVA.
Function compile_network_population_silence_sva(network, silence)¶
Compile a post-coactivation global silence contract into deterministic SVA.
Function compile_network_population_inactivity_sva(network, inactivity)¶
Compile a bounded global-output inactivity contract into deterministic SVA.
Module formal.report_schema¶
Class FormalReportValidationError¶
Raised when a formal network verification report violates its schema.
Function validate_formal_network_report(payload)¶
Validate a formal network verification report without external dependencies.
Module fusion.multimodal¶
Class ModalityConfig¶
Configuration for one sensor modality.
Class MultiModalFusion¶
Fuse spike trains from multiple sensor modalities.
Parameters¶
modalities : list of ModalityConfig Sensor modality definitions. output_dt_us : float Output time bin width in microseconds (common timebase). mode : str Fusion mode: 'concatenate', 'sum', or 'attention'.
- init(modalities, output_dt_us, mode)
- fuse(spike_trains, duration_us)
- Fuse spike trains from all modalities into a unified output.
Module fusion.sensor_fusion¶
Class SensorModality¶
Enumeration of the supported sensor modalities.
Class EventStream¶
Timestamped event stream from a single sensor modality.
- num_events()
- Return the number of events in the stream.
- duration_us()
- Return the stream duration in microseconds.
- event_rate()
- Return the mean event rate in events per microsecond.
- to_bitstream(length, num_channels)
- Convert event stream to SC bitstream matrix (channels × length).
Class BitstreamDecorrelator¶
On-the-fly decorrelation for heterogeneous bitstreams.
Uses per-stream LFSR-based scrambling to break inter-stream correlations introduced by shared clock domains or spatial proximity.
- init(seed)
- decorrelate(streams, method)
- Decorrelate a list of bitstream matrices.
- measure_scc(a, b)
- Compute stochastic cross-correlation between two bitstreams.
Class CrossModalAttention¶
SC-domain cross-modal attention kernel.
Implements query-key-value attention using stochastic arithmetic: - Q·K similarity: SC-AND (bitwise AND = multiplication) - Weighted V: SC-MUX (bitwise multiplexer = scaled addition)
- init(num_channels, seed)
- attend(query_stream, key_stream, value_stream)
- Compute cross-modal attention in SC domain.
Class FusionMetrics¶
Metrics from a sensor fusion pass.
Class SensorFusionLayer¶
Multi-stream sensor fusion with per-modality weighting.
- init(num_channels, bitstream_length, seed)
- set_weight(modality, weight)
- Set the fusion weight for a modality, clipped to
[0, 1]. - fuse(streams, use_attention)
- Fuse multiple event streams into a single SC bitstream.
Class HDCBinding¶
Hyperdimensional computing for cross-modal representation binding.
Uses binary hypervectors for modality-independent representation. Binding: XOR (permutation-invariant association). Bundling: majority vote (superposition).
- init(dim, seed)
- get_hypervector(key)
- Get or create a random hypervector for a key.
- bind(a, b)
- XOR binding: associate two representations.
- bundle(vectors)
- Majority-vote bundling: superpose multiple vectors.
- similarity(a, b)
- Cosine-like similarity via Hamming distance.
- encode_stream(stream, num_channels)
- Encode an event stream as a single hypervector.
Class DVSAdapter¶
Adapter for Dynamic Vision Sensor (event camera).
- encode_events(timestamps, x, y, polarities, resolution)
- Encode DVS camera events into an EventStream of AER addresses.
Class CochleaAdapter¶
Adapter for silicon cochlea (frequency-to-channel mapping).
- init(num_channels, freq_min_hz, freq_max_hz)
- freq_to_channel(freq_hz)
- Log-scale frequency to channel mapping (tonotopic).
- encode_spikes(timestamps, frequencies)
- Encode cochlear spike timestamps and frequencies into an EventStream.
Class TactileAdapter¶
Adapter for e-skin / tactile sensor arrays.
- encode_pressure(timestamps, taxel_ids, pressures, threshold)
- Convert pressure readings to ON/OFF events.
Class IMUAdapter¶
Adapter for IMU / proprioceptive streams.
- encode_angular_rate(timestamps, axis_id, rates_dps, deadzone_dps)
- Convert angular rate to events (above deadzone).
Class TemporalAligner¶
Aligns heterogeneous event streams to a common time window.
- init(window_us)
- align(streams)
- Slice all streams to their overlapping time window.
- slice_windows(stream)
- Slice a stream into fixed-width time windows.
Class FusionVerilogEmitter¶
Generates SystemVerilog for configurable multi-modal fusion.
- emit(module_name, num_streams, bitstream_width, use_attention)
- Emit configurable multi-modal fusion SystemVerilog as a string.
Class FusionEnergyEstimate¶
Sub-mW energy estimate for fusion pipeline.
- total_mw()
- Return the total estimated power in milliwatts.
Class FusionEnergyEstimator¶
Estimates per-inference energy for SC fusion on FPGA.
- init(tech_node_nm, vdd_v)
- estimate(num_streams, num_channels, bitstream_length, use_attention, clock_mhz)
- Estimate fusion energy from stream, channel, and timing parameters.
Module generative.audio_synthesis¶
Class SCAudioSynthesizer¶
SC Audio Synthesis engine. Converts bitstreams/probabilities to waveform buffers.
- synthesize_tone(frequency, duration_ms, probability)
- Synthesize a simple sine tone modulated by probability (amplitude).
- bitstream_to_audio(bitstream)
- Roughly convert a bitstream to an audio signal (Filtering).
Module generative.text_gen¶
Class SCTextGenerator¶
A minimal token-level text generator for SC. Maps probability distributions over vocabulary to tokens.
- generate_token(prob_dist)
- Input: prob_dist (len(vocab),)
- generate_sequence(length)
- Generate a random sequence of tokens.
Module generative.three_d_gen¶
Class SC3DGenerator¶
Generator for 3D mesh and point cloud outputs from stochastic voxel data.
Implements Marching Cubes algorithm for isosurface extraction.
- export_point_cloud_json(points, intensities, filename)
- Export a point cloud to JSON format.
- generate_surface_mesh(voxel_grid, iso_level)
- Generate a surface mesh from a voxel grid using Marching Cubes.
- export_mesh_obj(mesh, filename)
- Export mesh to OBJ format.
- export_mesh_json(mesh, filename)
- Export mesh to JSON format.
- bitstream_to_voxels(bitstreams, grid_size)
- Convert bitstream outputs to a voxel grid.
- generate_from_scpn(scpn_outputs, grid_size)
- Generate 3D mesh directly from SCPN layer outputs.
Module graphs.gnn¶
Class StochasticGraphLayer¶
Event-Based Graph Convolution Layer. Message Passing happens via Bitstreams.
- init(adj_matrix, n_features)
- forward(node_features)
- node_features: (N, Features)
Module hardware.constraints¶
Class Violation¶
A single hardware constraint violation.
Attributes: neuron_id: Index of the offending neuron. constraint: Name of the violated constraint. value: Actual value that violates the constraint. limit: Maximum allowed value. message: Human-readable description.
Class HardwareConstraints¶
Constraint set for a target device.
Derived from a DeviceSpec, or specified manually.
- from_device(cls, device)
- Derive constraints from a device specification.
Class ConstraintChecker¶
Check and optionally fix hardware constraint violations.
- check(adjacency, constraints, weights, delays)
- Check all constraints. Returns list of violations (empty if clean).
- auto_fix(adjacency, constraints)
- Attempt automatic fixes: prune weakest connections to satisfy fan-in/out.
Module hardware.deployment¶
Class DeploymentPackage¶
Self-contained deployment artifact for neuromorphic hardware.
Attributes: device: Target device specification. placements: Neuron-to-core mapping. config_blob: Binary configuration data for the target. metadata: Additional deployment metadata.
Class Deployer¶
Create and validate deployment packages.
- package(adjacency, device, placements, weights)
- Create a deployment package.
- validate(package)
- Validate a deployment package for consistency.
- summary(package)
- Human-readable deployment summary.
Module hardware.device¶
Class DeviceFamily¶
Supported neuromorphic hardware families.
Class DeviceSpec¶
Physical specification of a neuromorphic device.
Attributes: family: Hardware family identifier. cores: Number of neuro-cores on the chip. neurons_per_core: Maximum neurons per core. synapses_per_core: Maximum synaptic connections per core. axons_per_core: Maximum input axons per core. tick_ns: Duration of one simulation tick in nanoseconds. precision_bits: Weight precision in bits. supports_learning: Whether on-chip learning is supported. power_per_core_mw: Estimated power per active core (mW). max_fan_in: Maximum fan-in per neuron. max_fan_out: Maximum fan-out per neuron. weight_bits: Synaptic weight bit-width. delay_bits: Synaptic delay bit-width. max_delay_ticks: Maximum synaptic delay in ticks.
Function get_device(family)¶
Look up a device specification by family name or enum.
Module hardware.experiment¶
Class HardwareExperimentError¶
Raised when a protocol or its observations cannot be admitted as evidence.
Attributes¶
field : str The protocol or observation field that was refused. reason : str What is wrong, in words an operator can act on.
- init(field, reason)
Class Protocol¶
A hardware experiment as declared before it runs.
Attributes¶
declared_at : str
ISO 8601 timestamp with zone at which the protocol was fixed.
operator : dict
name and optional contact of whoever authorised and runs it.
device : dict
vendor, model, serial and optional firmware.
image : dict
kind (one of :data:IMAGE_KINDS) and sha256 of what executes.
network_sha256, data_sha256 : str
Digests of the converted network and of the evaluation data.
samples : int
Evaluation samples per measured run.
latency : dict
start_event, end_event, clock, warmup_runs and
measured_runs; includes_transport is always true.
power : dict or None
instrument (vendor, model, serial), calibration (certificate,
calibrated_on, valid_until), measurement_point and
sample_rate_hz; None when energy is not measured.
criteria : list of dict
Preregistered metric and threshold pairs.
- to_public_dict()
- Return the protocol as stored, including its opt-in and digest.
- sha256()
- Return the digest that a receipt binds to.
Function resolve_protocol(value)¶
Resolve a declared protocol, refusing anything that could not be evidence.
Parameters¶
value : mapping
The protocol document. opt_in must be true; a stored protocol
resubmitted with its sha256 must match it.
Returns¶
Protocol The protocol exactly as a receipt will bind it.
Raises¶
HardwareExperimentError A missing opt-in or identity, an unknown field, a latency definition without transport, a power declaration without a valid calibration, or a criterion that cannot be judged.
Function seal_receipt(protocol, observations)¶
Seal a hardware run's raw observations against its declared protocol.
Parameters¶
protocol : Protocol
The protocol declared before the run.
observations : mapping
started_at, finished_at, device_serial, image_sha256,
warmup_latency_ms and latency_ms lists, correct and, when
power was declared, energy (source: instrument,
instrument_serial, joules_per_inference per measured run);
optional notes.
Returns¶
dict
The receipt: the full protocol, the admitted observations, derived
accuracy, nearest-rank latency percentiles and energy, the verdict of
every preregistered criterion, and sha256 over all of it.
Raises¶
HardwareExperimentError An observation that does not belong to this protocol, or energy that was not measured by its declared, calibrated instrument.
Function verify_receipt(receipt)¶
Recompute a sealed receipt from its protocol and raw observations.
Parameters¶
receipt : mapping
A document :func:seal_receipt produced.
Returns¶
dict The receipt, when every digest, derived figure and verdict recomputes to exactly what it states.
Raises¶
HardwareExperimentError Another schema, a changed protocol or observation, or a derived figure or verdict that does not follow from the observations.
Module hardware.mapping¶
Class NeuronPlacement¶
Placement of a single neuron on hardware.
Class Mapper¶
Map neurons to cores using different strategies.
- map_greedy(adjacency, device)
- Greedy sequential mapping: fill cores one by one.
- map_balanced(adjacency, device)
- Balanced mapping: distribute neurons evenly across cores.
- map_locality(adjacency, device)
- Locality-aware mapping: cluster connected neurons on same core.
Module hardware.resource_estimator¶
Class ResourceEstimate¶
Hardware resource estimation result.
Attributes: cores_needed: Minimum cores to host the network. neurons_mapped: Total neurons to place. synapses_mapped: Total synapses to route. utilization_pct: Average core utilization (%). power_mw: Estimated total power (mW). latency_us: Estimated single-tick latency (µs). fits: Whether the network fits on the target device.
Class ResourceEstimator¶
Estimate hardware cost for deploying an SC-NeuroCore network.
- estimate(adjacency, device)
- Estimate resources from an adjacency matrix.
- fits(adjacency, device)
- Quick check: does the network fit on the device?
- compare(adjacency, devices)
- Compare resource requirements across multiple devices.
Module hdc.base¶
Class HDCEncoder¶
Hyperdimensional computing encoder.
Dimension D is usually >= 10,000. seed makes every draw
deterministic (given the same call order); tie_policy states
what an even-count bundle does on exactly tied bit positions:
"zeros" clears them (historical strict-majority behaviour),
"ones" sets them, and "random" decides each tied position
from a fresh seeded tie-break hypervector (the unbiased Kanerva
convention).
- post_init()
- Validate configuration and initialise the seeded generator.
- generate_random_vector()
- Generate a random D-dimensional binary vector in {0, 1}.
- item(name)
- Return the named item hypervector, drawing it on first use.
- bind(v1, v2)
- Bind two hypervectors via XOR.
- bundle(vectors)
- Bundle hypervectors by majority superposition.
- majority(sum_vec, count)
- Return the majority vector of
countbundled binary vectors. - permute(v, shifts)
- Permute a hypervector by a cyclic shift.
- level_vectors(low, high, levels)
- Return the
levelslinear level hypervectors for [low, high]. - encode_level(value, low, high, levels)
- Encode a scalar as its nearest linear level hypervector.
Class AssociativeMemory¶
Simple HDC associative clean-up memory.
Stores (key, value) pairs or bare prototypes for nearest-match retrieval.
- store(label, vector)
- Store a labelled hypervector in the clean-up memory.
- query(query_vec)
- Return the label of the closest stored vector by Hamming distance.
Module hdc.classifier¶
Class CentroidHDClassifier¶
Nearest-centroid classifier over binary hypervectors.
Deterministic for a seeded encoder: fitting, prediction, and
retraining consume randomness only through the encoder (and only
when its tie policy is "random").
- fit(vectors, labels)
- Accumulate the labelled hypervectors into their class centroids.
- predict(vector)
- Return the label of the nearest centroid by Hamming distance.
- retrain(vectors, labels, epochs)
- Run mistake-driven retraining; return misclassifications per epoch.
- centroid(label)
- Return a copy of one fitted class centroid.
- classes()
- Return the fitted class labels in sorted order.
Module hdl.aer_priority_queue_reference¶
Class AERPriorityEvent¶
Address-event payload emitted by the hardware priority queue.
Class AERPriorityStep¶
One cycle of queue input/output activity.
Class AERPriorityQueueReference¶
Finite AER strict-priority queue with hardware-equivalent traps.
- init()
- occupancy()
- ready()
- empty()
- full()
- enqueue(event)
- Accept an event if capacity is available, otherwise latch a drop.
- peek()
- Return the next event without consuming it.
- dequeue()
- Consume and return the highest-priority event.
- step(event)
- Advance one hardware cycle with optional input and output ready.
- drain()
- Drain the queue according to the strict-priority contract.
- extend(events)
- Enqueue all events that fit and return the accepted count.
Module hdl.resources¶
Function list_baseline_primitive_rtl()¶
Return the static baseline Verilog primitives bundled with the wheel.
Function baseline_primitive_path(name)¶
Return an importlib resource handle for a known baseline primitive.
Function baseline_primitive_text(name)¶
Read a known baseline primitive as UTF-8 text.
Module hdl_gen._bus_wrappers¶
Function render_axi_lite_wrapper(inner_module, params, data_width, addr_width, bus_data_width)¶
Render an AXI4-Lite slave wrapper around a neuron module.
Parameters¶
inner_module : str Name of the generated neuron module to instantiate. params : dict[str, int] Parameter-port names mapped to their bit widths. data_width : int Neuron datapath width. addr_width : int AXI address width. bus_data_width : int AXI register data width.
Returns¶
str Complete SystemVerilog wrapper source.
Function render_wishbone_wrapper(inner_module, params, data_width, addr_width, bus_data_width)¶
Render a Wishbone B4 slave wrapper around a neuron module.
Parameters¶
inner_module : str Name of the generated neuron module to instantiate. params : dict[str, int] Parameter-port names mapped to their bit widths. data_width : int Neuron datapath width. addr_width : int Wishbone address width. bus_data_width : int Wishbone register data width.
Returns¶
str Complete SystemVerilog wrapper source.
Module hdl_gen._ident¶
Function sanitize_ident(name, context)¶
Validate an HDL-facing identifier before interpolating it into source.
Module hdl_gen._live_parameter_bank¶
Function render_axi_live_parameter_bank(spec)¶
Render the AXI4-Lite live-parameter bank core.
Parameters¶
spec : MMIOUpdateSpec Validated live-control register and parameter-bank contract. module_name : str SystemVerilog module identifier for the generated core. addr_width : int or None Optional AXI address width override. bus_data_width : int AXI data width. The maintained core requires 32 bits. block_ram_threshold_bits : int Minimum bank capacity that receives a block-RAM style hint.
Returns¶
str Complete SystemVerilog source for the AXI4-Lite parameter bank.
Module hdl_gen._pcie_live_parameter_bank¶
Function render_pcie_live_parameter_bank(spec)¶
Render a PCIe-MMIO adapter around the AXI4-Lite parameter-bank core.
Parameters¶
spec : MMIOUpdateSpec Validated PCIe live-control contract. module_name : str SystemVerilog module identifier for the generated adapter. addr_width : int or None Optional MMIO address width override. bus_data_width : int MMIO data width. The maintained adapter requires 32 bits. block_ram_threshold_bits : int Minimum parameter-bank capacity that receives a block-RAM hint.
Returns¶
str PCIe adapter source followed by its generated AXI4-Lite core.
Module hdl_gen.aer_emitter¶
Class AEREmitter¶
Emit a research-stage AER wrapper around the existing sync HDL path.
This is intentionally conservative: the compute pipeline remains clocked and the output is wrapped in a 4-phase AER-style request/acknowledge interface. It is not a QDI async network replacement.
- init(module_name, bus_width)
- add_layer(layer_type, name, params)
- generate()
Module hdl_gen.bus_interface¶
Function generate_bus_wrapper(inner_module, params)¶
Generate a bus-attached wrapper around a compiled neuron module.
Parameters¶
inner_module : str
Name of the inner Verilog neuron module (for example, "sc_lif").
params : dict[str, int]
Mapping from Verilog parameter name to bit width.
bus : BusProtocol
Bus protocol: "axi_lite" or "wishbone".
data_width : int
Neuron fixed-point data width.
addr_width : int
Address bus width.
bus_data_width : int
Bus register data width.
base_address : int
Reserved documentation address retained for API compatibility.
Returns¶
str Complete SystemVerilog source for the bus wrapper module.
Function generate_register_map(params)¶
Return the register map for a neuron's parameters.
Parameters¶
params : dict[str, int] Parameter names and their bit widths. base_address : int Starting byte address.
Returns¶
dict[str, int] Mapping from register name to byte address.
Function generate_live_parameter_bank(spec)¶
Generate a live-parameter bank from an MMIO update spec.
The emitted RTL stores each parameter bank in distributed RAM or BRAM and exposes the fixed live-control register map through either AXI4-Lite or a PCIe MMIO register-window adapter. The PCIe path models the endpoint adapter contract: upstream PCIe hard IP decodes posted writes and reads into the single-clock MMIO strobes exposed here.
Parameters¶
spec : MMIOUpdateSpec Validated live-control register and parameter-bank contract. module_name : str SystemVerilog module identifier. addr_width : int or None Optional address-width override. bus_data_width : int Bus data width. Maintained live-control paths require 32 bits. block_ram_threshold_bits : int Minimum bank capacity that receives a block-RAM style hint.
Returns¶
str Complete SystemVerilog source for the selected live-control protocol.
Module hdl_gen.ip_xact¶
Function generate_ip_xact(module_name)¶
Generate IP-XACT component XML.
Parameters¶
module_name : str Top-level Verilog module name. vendor : str IP vendor identifier. library : str IP library name. version : str IP version string. data_width : int Neuron data width. params : dict, optional Verilog parameters. bus : str Bus interface type.
Returns¶
str IP-XACT XML string.
Module hdl_gen.kuramoto_emitter¶
Class KuramotoEmitter¶
Emit a bounded fixed-point Kuramoto phase core for HDL experiments.
The generated RTL is intentionally narrow in scope:
- noiseless only
- all-to-all scalar coupling only
- fixed-point phase state
- LUT-based sine approximation
This is a synthesis exploration scaffold, not a drop-in replacement for the production Kuramoto solvers.
- init(module_name)
- Initialize a bounded research Kuramoto HDL emitter configuration.
- initial_phase_state_fixed()
- Return the emitted fixed-point reset state for each oscillator.
- fixed_point_step(phase_state)
- Mirror one generated RTL phase step in integer fixed-point arithmetic.
- fixed_point_error_summary()
- Characterise fixed-point drift against the float Kuramoto Euler step.
- fixed_state_to_float(phase_state)
- Convert integer fixed-point phase state to radians.
- generate()
- Emit deterministic Verilog for the configured research Kuramoto core.
Module hdl_gen.lfsr16_emitter¶
Class Lfsr16Emitter¶
Emit a synthesisable standalone LFSR-16 Verilog module.
- init(module_name, seed)
- generate()
- Return the standalone LFSR-16 Verilog module.
Module hdl_gen.online_learning_emitter¶
Class OnlineO1ResourceEstimate¶
Deterministic pre-synthesis resource estimate for one online-learning block.
- as_dict()
- Return a deterministic JSON-ready estimate payload.
Class OnlineO1LearningEmitter¶
Emit a synthesisable reward-modulated STDP state machine.
- init()
- generate()
- Return Verilog for one bounded online-learning synapse lane.
- estimate_resources()
- Return a conservative pre-synthesis resource estimate.
- manifest()
- Return deterministic metadata for the generated learning lane.
Module hdl_gen.quasirandom_emitter¶
Class Halton16Emitter¶
Emit a synthesisable standalone Halton-16 (Van der Corput base-2) module.
Architecture: pure counter + bit-reversal wiring. Zero multipliers, zero LUTs for core logic.
- init(module_name)
- generate()
- Return the standalone Halton-16 Verilog module.
Class QuasiRandomEmitter¶
Unified factory for quasi-random SNG emitters.
Parameters¶
method : str
"sobol" or "halton".
module_name : str, optional
Override the default module name.
seed : int, optional
Seed for Sobol (ignored for Halton).
- init(method, module_name, seed)
- generate()
- Generate the Verilog source for the selected method.
- module_name()
- Return the sanitised module name.
Module hdl_gen.side_channel_encoding_emitter¶
Class SideChannelEncodingEmitter¶
Emit a synthesisable ROM-style wrapper for one protected encoding record.
- init()
- generate()
- Return a Verilog module exposing payload and dummy stream bits.
- manifest()
- Return transport metadata linking the HDL hook to analytic evidence.
Module hdl_gen.sobol16_emitter¶
Class Sobol16Emitter¶
Emit a synthesisable standalone Sobol-16 Verilog module.
- init(module_name, seed)
- generate()
- Return the standalone Sobol-16 Verilog module.
Module hdl_gen.spice_generator¶
Class SpiceGenerator¶
Generates SPICE netlists for Memristive Crossbars.
- generate_crossbar(weights, filename)
- weights: (Rows, Cols) - Conductance values [0, 1] mapped to [G_off, G_on].
Module hdl_gen.tmr_wrapper¶
Function generate_tmr_wrapper(module_name, inputs, outputs)¶
Generate a TMR wrapper for a given Verilog module.
Parameters¶
module_name : str
Name of the target module to triplicate.
inputs : list of (name, width) tuples
Input ports of the target module.
outputs : list of (name, width) tuples
Output ports to protect with majority voting.
voter_module : str
Name of the voter module (default: sc_tmr_voter).
Returns¶
str Generated Verilog source for the TMR wrapper.
Module hdl_gen.verilog_generator¶
Class VerilogGenerator¶
Generates Top-Level Verilog for a defined SC Network.
- init(module_name, bus_width)
- Initialise with a top-level module name.
- add_layer(layer_type, name, params)
- Add a layer definition to the network.
- generate(mode)
- Emits Verilog code.
- emit_lfsr16_source(module_name, seed)
- Emit a standalone LFSR-16 stochastic source module.
- emit_sobol16_source(module_name, seed)
- Emit a standalone Sobol-16 stochastic source module.
- emit_sources_from_ir(ir)
- Emit standalone stochastic source modules declared in an IR payload.
- emit_async_aer(module_name)
- Emit the research-stage async AER wrapper.
- emit_kuramoto_phase(module_name)
- Emit the bounded research Kuramoto phase core.
- emit_halton16_source(module_name)
- Emit a standalone Halton-16 stochastic source module.
- emit_quasirandom_source(method, module_name, seed)
- Emit a quasi-random source via the unified factory.
- emit_decorrelator()
- Return the path to the sc_decorrelator HDL module.
- emit_edt_controller()
- Return an instantiation template for the EDT controller.
- emit_tmr_wrapper(module_name, inputs, outputs)
- Generate a TMR wrapper for the given module.
- save_to_file(path)
- Write generated Verilog to a file.
Function emit_sources_from_ir(ir)¶
Emit LFSR-16 and Sobol-16 source modules from a lightweight IR payload.
The helper accepts the mapping shapes already used by documentation,
tests, and compiler-service payloads: {"nodes": [...]},
{"nodes": {"node_id": {...}}}, or a direct iterable of node mappings.
Non-source nodes are ignored. Source nodes must identify their generator
through source_type, decorrelator, generator, strategy, or
the node type/node_type itself.
Module homeostasis.regulator¶
Class StabilityMetrics¶
Network stability measurements.
- summary()
- Render a multi-line human-readable network-stability report.
Class NetworkRegulator¶
Network-wide homeostatic regulator.
Monitors population firing rates and adjusts thresholds, learning rates, and weights to maintain target activity levels.
Parameters¶
target_rate : float Target mean firing rate (spikes per step). rate_tolerance : float Acceptable deviation from target (fraction). threshold_step : float Per-step threshold adjustment magnitude. lr_scale_factor : float Multiplicative LR adjustment factor.
- init(target_rate, rate_tolerance, threshold_step, lr_scale_factor)
- regulate(firing_rates, thresholds, learning_rate, weights)
- Apply homeostatic regulation.
Class SleepConsolidation¶
Sleep-phase synaptic renormalization for memory consolidation.
During sleep: suppress external input, apply power-law weight decay, allow spontaneous replay through recurrent dynamics.
Reference: Sleep-Based Homeostatic Regularization (arXiv Jan 2026)
Parameters¶
decay_exponent : float Power-law exponent for weight decay (higher = more aggressive). noise_amplitude : float Spontaneous activity noise during sleep. duration_fraction : float Sleep duration as fraction of epoch (0.1 = 10% of time sleeping).
- init(decay_exponent, noise_amplitude, duration_fraction)
- apply(weights, seed)
- Apply sleep consolidation to weights.
- should_sleep(epoch, total_epochs)
- Determine if this epoch should include a sleep phase.
Module hub.bundle¶
Class HubBundleConfig¶
Configuration for a local self-hosted hub bundle.
- post_init()
Function build_model_zoo_index()¶
Build a deterministic model-zoo index for hub manifests.
Function build_benchmark_plan(config)¶
Build the benchmark-runner plan included in the hub bundle.
Function build_hub_manifest(config)¶
Build a deterministic manifest for a self-hosted hub bundle.
Function write_hub_bundle(output_dir, config)¶
Write a local Docker Compose hub bundle and return generated paths.
Module hypervisor.accounting¶
Class UsageRecord¶
One billing record.
Class ResourceAccounting¶
Tracks per-tenant resource usage for metered billing.
- init()
- record(tenant_id, cycles, spikes)
- total_cycles(tenant_id)
- total_spikes(tenant_id)
- invoice(tenant_id, cost_per_cycle)
- Compute billing amount.
Module hypervisor.audit¶
Class AuditEventType¶
Class AuditEntry¶
- post_init()
Class SecurityAuditLog¶
Structured, append-only audit trail for compliance.
- init(max_entries)
- log(event)
- query(event_type, tenant_id)
- count()
- checksum()
Module hypervisor.hypervisor¶
Class HypervisorConfig¶
Hypervisor configuration.
Class Hypervisor¶
Multi-tenant neuromorphic hypervisor.
Manages tenant lifecycle, hardware allocation, scheduling, firewall enforcement, and live migration.
- init(config)
- add_region(region)
- Register a hardware region.
- register_tenant(tenant)
- Register a new tenant.
- allocate(tenant_id)
- Allocate a free region to a tenant.
- deallocate(tenant_id)
- Release a tenant's hardware region.
- remove_tenant(tenant_id)
- Remove a tenant entirely.
- schedule(num_cycles)
- Generate a schedule for active tenants.
- migrate(tenant_id, target_region_id)
- Migrate a tenant to a different region.
- check_access(tenant_id, addr, is_write)
- Check if a tenant can access an address (firewall).
- status()
- Get hypervisor status.
- tenant_report(tenant_id)
- Get a report for one tenant.
- compute_utilisation()
- Compute utilisation fraction per region.
- check_overcommit()
- Check if total tenant QoS exceeds fabric capacity.
- get_faulted_regions()
- List regions in FAULTED state.
- mark_region_faulted(region_id)
- Mark a region as faulted and evict its tenant.
Class MigrationThrottle¶
Rate-limits migration requests to prevent storms.
- allow()
- Check if a migration is allowed under the rate limit.
- record()
- recent_count()
Function admission_check(tenant, regions, existing_tenants)¶
Check if a new tenant can be admitted without overcommitting.
Module hypervisor.isolation¶
Class FirewallRule¶
One address-range access rule.
- end_addr()
Class BitstreamFirewall¶
AXI address-range isolation preventing cross-tenant access.
Each tenant can only access its own region's AXI address space. Any cross-region access is blocked and logged as a violation.
- init()
- add_rule(rule)
- remove_tenant_rules(tenant_id)
- check_access(tenant_id, addr, is_write)
- Check if a tenant can access an address.
- violation_count()
- clear_violations()
Function verify_isolation(firewall, regions)¶
Verify that no two tenants share address ranges.
Returns list of violation descriptions (empty = sound).
Module hypervisor.migration¶
Class MigrationRequest¶
Request to migrate a tenant between regions.
Class MigrationResult¶
Result of a migration attempt.
Class MigrationEngine¶
Live migration of tenants between hardware regions.
Migration steps: 1. Pause tenant on source region 2. Checkpoint state (voltages, weights, LFSR, spike queues) 3. Verify checkpoint integrity (SHA-256) 4. Restore state on target region 5. Update firewall rules 6. Resume tenant
- init()
- checkpoint(tenant)
- Checkpoint tenant state for migration.
- restore(tenant, state)
- Restore a sealed checkpointed state to a tenant.
- migrate(tenant, source, target, firewall)
- Execute live migration.
Module hypervisor.preemption¶
Class PreemptionEvent¶
Record of a preemption event.
Class PreemptionManager¶
Handles preemption with state checkpoint/restore.
- init()
- preempt(victim, preemptor, region, cycle)
- Preempt victim and give region to preemptor.
- restore_preempted(tenant)
- Restore a previously preempted tenant's state.
Module hypervisor.qos_monitor¶
Class BandwidthMeter¶
Per-tenant throughput metering (spikes/cycles per window).
- record(tenant_id, spike_count, cycle)
- throughput(tenant_id)
- Spikes per cycle (averaged over window).
- exceeds_quota(tenant_id, max_mbps)
Class SLAViolation¶
One SLA violation.
Class SLAMonitor¶
Monitors per-tenant QoS compliance and detects violations.
- init()
- check_latency(tenant, measured_us, cycle)
- check_bandwidth(tenant, measured_mbps, cycle)
- total_violations()
- violations_for(tenant_id)
Module hypervisor.region¶
Class RegionState¶
Class HWRegion¶
One isolated hardware region on the fabric.
- axi_end_addr()
- is_free()
- contains_addr(addr)
Class RegionHealth¶
Health score with degradation model.
- health_score()
- 0.0 = dead, 1.0 = perfect.
- is_degraded()
- record_error()
Function select_region_multi_die(regions, min_neurons, preferred_die)¶
Select best free region, preferring a specific die.
Module hypervisor.scheduler¶
Class SchedulingPolicy¶
Class ScheduleSlot¶
One time slot in the schedule.
- end_cycle()
Class Scheduler¶
Multi-tenant temporal scheduler with preemption.
Supports priority-based, round-robin, fair-share, and EDF scheduling.
- init(policy)
- generate_schedule(tenants, num_cycles)
- Generate a schedule for the given tenants.
Module hypervisor.tenant¶
Class TenantPriority¶
Class QoSPolicy¶
Quality-of-Service policy for a tenant.
Class TenantState¶
Checkpointable state for live migration.
- compute_checksum()
Class Tenant¶
One SC network tenant on the hypervisor.
Module identity.checkpoint¶
Class Checkpoint¶
Save and restore complete IdentitySubstrate state.
- save(substrate, path)
- Save complete state to .npz file.
- load(path)
- Restore substrate from checkpoint.
- merge(paths)
- Merge multiple checkpoints by averaging weights and concatenating history.
Module identity.decoder¶
Class StateDecoder¶
Extract cognitive state from spiking network for session priming.
- init(substrate)
- extract_dominant_patterns(n_components)
- PCA on recent spike trains -> dominant activity patterns.
- extract_attractor_states(threshold)
- Find stable attractor states via correlation clustering.
- extract_connectivity_signature()
- Functional connectivity matrix summarizing learned structure.
- generate_priming_context()
- Generate a text summary of current network state.
Module identity.director¶
Class DirectorController¶
L16 self-monitoring and self-regulation for the identity substrate.
- init(substrate)
- monitor()
- Measure current dynamics from recent spike history.
- diagnose()
- Identify problems in network dynamics.
- correct()
- Apply corrective actions based on diagnosis.
- report()
- Generate human-readable health report.
Module identity.encoder¶
Class TraceEncoder¶
Encode reasoning traces as temporal spike patterns.
LSH maps text chunks to neuron groups. Poisson spike trains weighted by chunk salience deliver the encoded signal.
- init(n_neurons, hash_dims, seed)
- encode(text, duration_ms, dt)
- Convert text to spike pattern array (n_neurons, n_steps).
- encode_key_value(key, value)
- Encode a key-value pair as a combined spike pattern.
Module identity.substrate¶
Class IdentitySubstrate¶
Persistent spiking neural network for identity continuity.
Three populations: - cortical: HodgkinHuxley excitatory (main processing) - inhibitory: WangBuzsaki fast-spiking (balance/stability) - memory: HindmarshRose bursting (pattern storage via attractors)
Connectivity: small-world E->E with STDP, random E->I, I->E, E->M, M->E.
- init(n_cortical, n_inhibitory, n_memory, seed)
- step(stimuli, dt)
- Advance one timestep. Inject external current into cortical neurons.
- run(duration, dt, stimuli_sequence)
- Run for duration seconds. Optional time-varying stimuli array.
- inject_experience(reasoning_trace)
- Encode a reasoning trace as spike patterns and inject via run().
- extract_state()
- Extract current network state for session priming.
- health_check()
- L16 Director: check network dynamics are healthy.
- spike_history()
- ee_weights()
Module industrial_applications¶
Class IndustrialDomain¶
Supported industrial application domains.
Class EvidenceCategory¶
Evidence categories expected in an industrial readiness pack.
Class EvidenceRequirement¶
One evidence requirement for an application profile.
- to_dict()
- Return a JSON-ready requirement.
Class IndustrialApplicationProfile¶
Readiness profile for one SC-NeuroCore industrial use case.
- to_dict()
- Return a JSON-ready profile.
Class IndustrialReadinessAssessment¶
Evidence coverage assessment for one industrial application profile.
- ready()
- Whether all mandatory evidence categories are present.
- mandatory_coverage()
- Mandatory evidence coverage ratio.
- to_dict()
- Return a JSON-ready assessment.
Class IndustrialApplicationRegistry¶
Registry of application profiles and evidence-readiness checks.
- init(profiles)
- get(domain)
- Return the profile for a domain.
- list_profiles()
- Return all registered profiles in deterministic order.
- assess(domain, evidence_bag)
- Assess whether the evidence bag covers a domain profile.
Function default_industrial_profiles()¶
Return conservative built-in industrial application profiles.
Function assess_industrial_readiness(domain, evidence_bag)¶
Assess readiness for a built-in industrial application domain.
Module integrations.lava_bridge¶
Class LoihiNetworkConfig¶
Configuration for a deployed Loihi network.
Class SCtoLavaConverter¶
Convert SC-NeuroCore layer stack to Lava Process network.
- init(weight_bits)
- convert_dense_layer(sc_layer)
- Convert an SCDenseLayer or VectorizedSCLayer to Loihi config.
- convert_training_model(spiking_net)
- Convert a trained SpikingNet to a list of LoihiNetworkConfigs.
Function export_weights_loihi(weights, weight_bits, weight_exp)¶
Convert SC probability weights [0,1] to Loihi fixed-point format.
Loihi uses signed integer weights with configurable precision. Maps [0,1] → [-128, 127] for 8-bit weights.
Function loihi_threshold_from_sc(sc_threshold, weight_bits)¶
Convert SC normalised threshold to Loihi integer threshold.
Module interfaces.bci¶
Class BCIEncoder¶
Encode continuous neural signals into spike trains.
Replaces the old BCIDecoder (misleading name — it encodes, not decodes). Uses seeded RNG for deterministic, reproducible encoding.
Parameters¶
n_channels : int Number of recording channels. sampling_rate : int Input signal sampling rate (Hz). window_ms : float Encoding window duration in milliseconds. seed : int RNG seed for reproducibility.
- encode(signal, T)
- Encode a signal block into spike trains via rate coding.
- encode_stream(signal)
- Encode a multi-window signal stream.
- normalize_signal(signal)
- Normalize signal to [0, 1]. Legacy API — use _normalize().
- encode_to_bitstream(signal, length)
- Legacy API. Encodes (channels, time) → (channels, length).
Class BCIDecoder¶
Legacy alias. Use BCIEncoder instead.
- init(channels, sampling_rate)
Module interfaces.bci_closed_loop¶
Class ClosedLoopBCIConfig¶
Configuration for one raw-waveform to feedback HIL loop.
Class FeedbackFrame¶
Feedback vector emitted to an implant emulator or hardware adapter.
Class ClosedLoopBCIResult¶
One processed BCI/HIL loop window.
Class SpikeDecoder¶
Decoder interface for closed-loop spike windows.
- decode(spike_raster)
- Decode a binary spike raster into feedback control values.
Class FeedbackSink¶
Feedback interface for an implant emulator or hardware adapter.
- apply_feedback(values, timestamp_us)
- Apply decoded feedback values and return the emitted frame.
Class RateSpikeDecoder¶
Decode spike rasters as per-channel firing rates.
- decode(spike_raster)
Class ImplantEmulator¶
Deterministic feedback sink used by the closed-loop template.
- apply_feedback(values, timestamp_us)
Class ClosedLoopBCITemplate¶
WaveformCodec + AER + telemetry closed-loop BCI scaffold.
- post_init()
- process_window(waveform)
- Process one raw electrode window through the closed-loop template.
Module interfaces.bci_hil_manifest¶
Class BCIHILBoardProfile¶
Board/input profile for a closed-loop BCI reference pipeline.
- to_dict()
- Return a deterministic manifest dictionary.
Function available_bci_hil_profiles()¶
Return all reference profiles in deterministic order.
Function get_bci_hil_profile(profile_id)¶
Return one reference profile by identifier.
Function build_bci_hil_reference_manifest(profile_id)¶
Build a deterministic closed-loop BCI/HIL reference manifest.
Function create_bci_hil_template(profile_id)¶
Create a ClosedLoopBCITemplate from a reference profile.
Module interfaces.ccw_bridge¶
Class CCWMode¶
CCW modulation modes aligned with VIBRANA.
Class CCWParameters¶
Parameters for CCW audio generation.
Class VIBRANAState¶
State for VIBRANA visualization sync.
Class CCWBridge¶
Bridge between SC-NeuroCore and CCW/VIBRANA systems.
Converts bitstream outputs from SCPN layers into audio parameters and visualization states for the CCW application.
- init(params)
- bitstream_to_frequency(bitstream, freq_min, freq_max)
- Convert a bitstream to a frequency value.
- scpn_metrics_to_ccw(metrics)
- Convert SCPN global metrics to CCW audio parameters.
- glyph_vector_to_vibrana(glyph_vector)
- Convert L7 glyph vector to VIBRANA visualization parameters.
- generate_binaural_sample(ccw_params, duration_samples)
- Generate binaural audio samples from CCW parameters.
- generate_ccw_metadata(scpn_outputs, glyph_vector)
- Generate complete CCW metadata package for audio/visual sync.
- export_glyph_stream(glyph_vector, cosmic_vector, filepath)
- Export glyph stream data for VIBRANA/CCW hardware playback.
- create_session_config(mode, duration_minutes)
- Create a complete CCW session configuration.
Function create_bridge(ccw_params)¶
Factory function to create a CCW bridge instance.
Module interfaces.dvs_input¶
Class DVSInputLayer¶
Convert Dynamic Vision Sensor AER events into stochastic bitstreams.
Parameters¶
height: Positive number of pixel rows in the event-camera frame. width: Positive number of pixel columns in the event-camera frame. decay_tau: Positive finite exponential-decay time constant in milliseconds.
- post_init()
- Validate sensor geometry and allocate the internal event surface.
- process_events(events)
- Integrate a timestamp-ordered batch of DVS events.
- generate_bitstream_frame(length)
- Generate a stochastic bitstream cube from the current DVS surface.
Module interfaces.real_world¶
Class LSLBridge¶
Lab Streaming Layer (LSL) Bridge. Connects EEG/Physiological streams to sc-neurocore. (Mock implementation for standalone use).
- init(stream_name)
- receive_chunk(max_samples)
- Simulates receiving a chunk of samples.
Class ROS2Node¶
ROS 2 Interface Node. Publishes motor commands from sc-neurocore to robots.
- init(node_name)
- publish_cmd_vel(linear_x, angular_z)
- Simulate publishing a velocity command to /cmd_vel; returns success.
Module interfaces.zenith_bci_loop¶
Class ZenithBCILoopConfig¶
Configuration for deterministic closed-loop stream processing.
Attributes¶
n_channels: Number of neural acquisition channels in each waveform window. sampling_rate_hz: Sample rate used to convert window length into ingest latency. gpu_lanes: Parallel codec/decode lanes available for latency estimation. latency_budget_ms: Maximum allowed end-to-end closed-loop latency in milliseconds. threshold_sigma: Spike-detection threshold multiplier passed to the BCI template. snippet_samples: Number of waveform samples captured around each detected event. waveform_mode: Closed-loop waveform codec mode forwarded to the BCI template. quantize_bits: Bit width used by the waveform quantizer. timestamp_bits: Bit width reserved for encoded event timestamps.
- post_init()
- Validate strictly positive loop sizing and latency parameters.
Class ZenithBCILoopResult¶
Single-step closed-loop output with latency budget evidence.
Attributes¶
command:
Integer control action emitted for the processed waveform window.
feedback_active_channels:
Number of channels that received active feedback.
spike_count:
Total detected spikes in the processed window.
decoded_rates:
Per-channel decoded spike-rate estimates.
latency_breakdown_ms:
Stage-level latency ledger keyed by processing stage name.
total_latency_ms:
Sum of all estimated stage latencies in milliseconds.
latency_budget_ms:
Budget the closed-loop step was checked against.
latency_budget_met:
Whether total_latency_ms stayed within latency_budget_ms.
pathway_name:
Human-readable identifier for the acquisition/control pathway.
schema_version:
Stable serializer schema emitted by :meth:to_dict.
- to_dict()
- Return the stable JSON-compatible result payload.
Class ZenithBCILoop¶
Closed-loop primitive for continuous BCI streams with latency guarantees.
- init(config)
- process_stream(waveform)
- Process one continuous stream window into a closed-loop control action.
Module ir.scnir_compatibility¶
Class SCNIRCompatibilityRow¶
One compatibility row for a NIR primitive.
- as_dict()
- Return a deterministic JSON-ready row.
Function scnir_compatibility_matrix()¶
Return the deterministic SC-NIR compatibility matrix.
Function scnir_compatibility_matrix_dicts()¶
Return the matrix as deterministic JSON-ready dictionaries.
Function build_scnir_compatibility_audit(evidence_root)¶
Build a versioned closure-audit report for the SC-NIR compatibility matrix.
The report is intentionally derived from the executable matrix after validation, so release automation consumes the same data that enforces parser coverage and evidence-path freshness.
Function validate_scnir_compatibility_matrix(evidence_root)¶
Fail if the matrix drifts from parser-declared support or stale evidence paths.
Parameters¶
evidence_root:
Optional repository root used to verify that every audit_evidence
path in the matrix resolves to an existing file.
Module ir.scnir_convert¶
Class SCNIRConversionConfig¶
Configuration for deterministic SC-NIR metadata export.
- post_init()
- resolved_accumulator_bits()
- Accumulator width used by exported precision metadata.
Function build_scnir_from_neuron_graph(neuron_graph)¶
Build an SC-NIR document from an existing NIR-derived NeuronGraph.
Function export_scnir_from_nir(model_path)¶
Read a NIR model, export SC-NIR metadata, and write it to JSON.
Module ir.scnir_handoff_audit¶
Class SCNIRHDLHandoffAuditError¶
Raised when a compile-nir HDL handoff directory is incomplete or inconsistent.
Class SCNIRHDLHandoffAuditReport¶
Deterministic summary of a validated SC-NIR HDL handoff directory.
- as_dict()
- Return a stable JSON-ready report.
Function audit_scnir_hdl_handoff(directory)¶
Validate a compile-nir HDL output directory and return an audit report.
The audit is intentionally structural and fail-closed: every SC-NIR stream must have exactly one matching source-manifest row and emitted source module, aggregate counts must match the typed document, and top-level SC-NIR localparams must agree with the JSON handoff metadata.
Function write_scnir_hdl_handoff_audit(directory, output_path)¶
Validate a handoff directory and write the JSON audit report.
Module ir.scnir_hdl¶
Class SCNIRHDLSourceManifestEntry¶
Serialisable manifest row for one emitted stochastic source module.
- as_dict()
- Return a deterministic JSON-ready representation.
Class SCNIRHDLSourceBundle¶
Concrete HDL source modules plus the manifest that explains them.
- manifest_dicts()
- Return deterministic JSON-ready manifest rows.
Function build_scnir_source_bundle(document)¶
Emit deterministic HDL source modules for every SC-NIR stream.
Only source kinds with the standard threshold-bit output contract are materialised here. Unsupported SC-NIR source kinds fail closed instead of being lowered to semantically incompatible RTL.
Module ir.scnir_schema¶
Class SCNIRValidationError¶
Raised when an SC-NIR payload violates the fail-closed contract.
Class SCNIRPrecision¶
Fixed-point interpretation attached to one stochastic stream.
Class SCNIRSource¶
Random or deterministic source metadata for a stochastic stream.
Class SCNIRCorrelationConstraint¶
Correlation rule between two stochastic streams.
Class SCNIRStreamTransform¶
Deterministic transform applied before a logical stochastic stream.
Class SCNIRStream¶
SC metadata for one logical stochastic bitstream.
Class SCNIRHierarchyPort¶
One typed port on a hierarchical SC-NIR hardware instance.
Class SCNIRHierarchyInstance¶
One hierarchy instance boundary for future nested hardware handoff.
Class SCNIRDocument¶
Top-level SC-NIR metadata document.
Function validate_scnir_dict(payload)¶
Validate a decoded SC-NIR payload or raise SCNIRValidationError.
Function scnir_from_dict(payload)¶
Build a typed SC-NIR document from a decoded mapping.
Function scnir_to_dict(document)¶
Convert a typed SC-NIR document to deterministic JSON-ready data.
Function load_scnir(path)¶
Load and validate an SC-NIR JSON document.
Function write_scnir(path, document)¶
Write an SC-NIR JSON document after validating it.
Function upgrade_scnir_dict(payload)¶
Upgrade supported SC-NIR payloads to the current canonical schema.
Version v0.1 did not encode recurrent connection delay, and versions
before v0.3 did not distinguish spiking, analogue-state, and weight
streams. Version v0.4 added explicit stream transform metadata for
threshold comparators. Version v0.5 permits delay_steps to be
either a scalar integer or a per-source-column integer vector. Version
v0.6 adds top-level hierarchy instance and port metadata. Version
v0.7 adds optional validated per-weight-stream online-learning
annotations. Legacy upgrades insert the missing fields before validating
through the typed schema. Current documents are canonicalised through the
same deterministic writer.
Module layers.attention¶
Class StochasticAttention¶
Stochastic Computing Attention Block.
Two modes:
forward()— row-sum normalised (SC-native, no exp). Matches Rust engineforward().forward_softmax()— proper softmax with temperature scaling.
Example¶
Q = np.random.default_rng(0).uniform(0, 1, (4, 8)) K = np.random.default_rng(1).uniform(0, 1, (6, 8)) V = np.random.default_rng(2).uniform(0, 1, (6, 5)) attn = StochasticAttention(dim_k=8) attn.forward(Q, K, V).shape (4, 5) attn.forward_softmax(Q, K, V).shape (4, 5)
- post_init()
- forward(Q, K, V)
- Row-sum normalised attention (SC-native, no exp).
- forward_softmax(Q, K, V)
- Proper softmax attention with temperature scaling.
- forward_bitstream(Q, K, V, length, use_sobol)
- SC-native attention via bitstream AND gates.
Module layers.circuit_primitives¶
Class LateralInhibition¶
Lateral inhibition: each neuron inhibits its neighbors.
Models the surround suppression found in retinal ganglion cells, cortical simple cells, and throughout sensory processing.
The inhibition kernel is a Gaussian centered on each neuron with
width radius, producing a Mexican-hat (center-surround) response
when combined with the neuron's own excitation.
- post_init()
- Build the lateral-inhibition kernel matrix.
- apply(rates)
- Apply lateral inhibition to firing rates.
Class WinnerTakeAll¶
k-Winner-Take-All circuit.
Only the top-k neurons remain active; all others are suppressed to zero. Models competitive dynamics in cortical columns and basal ganglia action selection.
With k=1, this is a hard argmax over the population.
- apply(rates)
- Apply k-WTA to firing rates.
- winners(rates)
- Return indices of the k winning neurons.
Module layers.fusion¶
Class SCFusionLayer¶
Fuse multiple data modalities using stochastic multiplexing.
Parameters¶
input_dims : Mapping[str, int] Declared feature count for each accepted modality. fusion_weights : Mapping[str, float] Raw modality weights. Positive totals are normalised to one; non-positive totals fall back to equal weights across the weighted modalities, matching the Rust fusion layer contract. length : int, default=LAYER_DEFAULT_LENGTH Stochastic bitstream length carried for layer-level configuration.
Example¶
import numpy as np layer = SCFusionLayer( ... input_dims={"audio": 4, "visual": 4}, ... fusion_weights={"audio": 0.7, "visual": 0.3}, ... ) out = layer.forward({"audio": np.ones(4), "visual": np.zeros(4)}) out.shape (4,)
- post_init()
- Validate modality metadata and normalise fusion weights.
- forward(inputs)
- Return the weighted stochastic-fusion expectation.
Module layers.hardware_aware¶
Class HardwareAwareSCLayer¶
SC layer with memristive hardware defect injection.
Parameters¶
n_inputs : int Number of input channels. n_neurons : int Number of output neurons. length : int Bitstream length. stuck_rate : float Fraction of synapses with stuck-at faults (0 or 1). Default 0.05. variability : float Additive weight noise std. Default 0.02. seed : int Random seed for defect generation.
- post_init()
- Build the backing layer and inject stuck-at and variability defects.
- forward(input_values)
- Run a forward pass through the defect-injected stochastic layer.
- update_weights(gradient, lr)
- Update weights with gradient, respecting stuck-at mask.
- weights()
- Return the current defect-affected weight matrix.
- n_stuck()
- Return the number of stuck-at synapses.
- stuck_fraction()
- Return the fraction of synapses that are stuck-at.
Module layers.jax_dense_layer¶
Class JaxSCDenseLayer¶
JAX-accelerated stochastic dense layer of LIF neurons.
Example¶
layer = JaxSCDenseLayer(n_neurons=10, n_inputs=5, seed=0) # doctest: +SKIP import jax.numpy as jnp # doctest: +SKIP spikes = layer.step(jnp.ones(10) * 0.5) # doctest: +SKIP spikes.shape # doctest: +SKIP (10,)
- post_init()
- step(I_t)
- Advance the entire layer by one time step.
- run(currents)
- Run for multiple steps.
- reset()
Module layers.memristive¶
Class MemristiveDenseLayer¶
Dense layer mapped to a memristor crossbar with hardware non-idealities.
Defect parameters from Prezioso et al., Nature 521:61-64, 2015.
- post_init()
- apply_hardware_defects()
- Corrupt weights based on physical properties.
Module layers.predictive_coding¶
Class PredictiveCodingSCLayer¶
Zero-multiplication predictive coding in SC.
Parameters¶
n_inputs : int Number of input channels. n_neurons : int Number of predictive neurons. length : int Bitstream length. lr : float STDP-like learning rate for prediction weights. seed : int or None Random seed.
- post_init()
- Initialise the prediction weights and recurrent state.
- forward(inputs)
- Process one timestep.
- reset()
- Re-initialise the prediction weights and clear the previous input.
Module layers.rall_dendrite¶
Class RallDendrite¶
Dendritic tree with Rall branching and compartmental dynamics.
Parameters¶
n_branches : int Number of dendritic branches. branch_length : int Number of compartments per branch. tau : float Membrane time constant (ms). coupling : float Inter-compartment coupling strength (0 to 1). dt : float Timestep (ms).
- post_init()
- Validate the dendrite geometry and initialise compartment state.
- step(branch_inputs)
- Advance one timestep.
- branch_voltages()
- Current compartment voltages, shape (n_branches, branch_length).
- reset()
- Reset all compartment and soma voltages to zero.
Module layers.recurrent¶
Class SCRecurrentLayer¶
SC recurrent / reservoir layer (echo state network).
Spectral radius bound follows Jaeger, GMD Report 148, 2001.
Example¶
import numpy as np res = SCRecurrentLayer(n_inputs=3, n_neurons=10, seed=0) state = res.step(np.array([0.5, 0.3, 0.8])) state.shape (10,)
- post_init()
- step(input_vector)
- Process one time step (e.g., one frame of audio).
- reset()
Module layers.sc_conv_layer¶
Class SCConv2DLayer¶
SC 2D convolutional layer using stochastic probability encodings.
sc_mode="unipolar" accepts probabilities in [0, 1] and uses
probability-product accumulation. sc_mode="bipolar" accepts signed
values in [-1, 1] and uses signed XNOR-equivalent products.
Example¶
import numpy as np conv = SCConv2DLayer(in_channels=1, out_channels=2, kernel_size=3, padding=1) img = np.random.rand(1, 8, 8) out = conv.forward(img) out.shape (2, 8, 8)
- post_init()
- Validate the layer configuration and initialise stochastic kernels.
- forward(input_image)
- Apply the stochastic convolution to a channel-first image tensor.
Module layers.sc_dense_layer¶
Class SCDenseLayer¶
Stochastic-computing dense layer of LIF neurons.
Each neuron receives SC dot-product input current and produces independent
spike trains. weight_values may be either a single shared vector of
length n_inputs or a dense matrix shaped (n_neurons, n_inputs).
Software-only but fully SC-driven at the input/synapse level.
Example¶
layer = SCDenseLayer( ... n_neurons=4, x_inputs=[0.5, 0.3], weight_values=[0.8, 0.6], ... x_min=0.0, x_max=1.0, w_min=0.0, w_max=1.0, length=256, ... ) layer.run(T=100) trains = layer.get_spike_trains() trains.shape (4, 100)
- post_init()
- reset()
- run(T)
- Run the layer for T time steps, updating all neurons.
- get_spike_trains()
- Return spike matrix of shape (n_neurons, T).
- summary()
- Return firing statistics for each neuron.
Module layers.sc_learning_layer¶
Class SCLearningLayer¶
SC dense layer with integrated STDP learning.
Each neuron has per-input STDP synapses. Plasticity follows Bi & Poo 1998 asymmetry convention.
- post_init()
- Build the LIF neurons and their per-input STDP synapses.
- run_epoch(input_values)
- Run one bitstream epoch of duration
lengthand return the spikes. - get_weights()
- Return the dense weight matrix gathered from all synapses.
Module layers.vectorized_layer¶
Class VectorizedSCLayer¶
High-performance SC layer using packed bitwise operations.
Uses GPU (CuPy) when available, otherwise pure NumPy.
Optional sparse connectivity via scipy.sparse.
Example¶
import numpy as np layer = VectorizedSCLayer(n_inputs=8, n_neurons=4, length=512) out = layer.forward(np.random.rand(8)) out.shape (4,) (out >= 0).all() and (out <= 1).all() True
- post_init()
- from_exported_weights(cls, exported_layer)
- Build a packed SC inference layer from
to_sc_weights()output. - forward(input_values)
- Compute output firing rates for the layer.
Module learning.advanced¶
Class BPTTLearner¶
Backpropagation Through Time for spiking networks.
Uses fast-sigmoid surrogate gradient (Neftci et al. 2019) to handle the spike non-differentiability.
- init(network, loss_fn, lr)
- train_step(inputs, targets)
- One BPTT step: forward pass, loss, backward with surrogate gradients.
Class TBPTTLearner¶
Truncated Backpropagation Through Time for long sequences.
Splits input into chunks of k timesteps, backpropagating gradients
only within each chunk while carrying forward state (membrane voltage)
across boundaries. Reduces memory from O(T) to O(k).
Williams & Peng 1990.
- init(network, loss_fn, lr, k)
- train_step(inputs, targets)
- One TBPTT step over the full sequence, chunked into windows of k.
Class EligibilityTrace¶
E-prop eligibility trace: three-factor learning (pre x post x error).
Bellec et al. 2020.
- init(tau_e, dt)
- update(pre_spike, post_spike, error_signal)
- Compute weight delta from three-factor rule.
Class RewardModulatedLearner¶
Reward-modulated STDP (R-STDP).
Maintains per-synapse eligibility traces and applies weight updates scaled by a global reward signal.
- init(network, tau_reward)
- step(reward)
- Apply reward-modulated weight update.
Class MetaLearner¶
MAML-style meta-learning for spiking networks.
Finn et al. 2017. Inner loop: fast adaptation on a task. Outer loop: meta-gradient across tasks.
- init(network, inner_lr, outer_lr)
- inner_loop(task_data, n_steps)
- Fast adaptation: n_steps of gradient descent on task_data.
- outer_step(tasks)
- Meta-gradient update across multiple tasks.
Class HomeostaticPlasticity¶
Homeostatic synaptic scaling to maintain target firing rate.
Turrigiano 2008. Multiplicatively scales all incoming weights to keep the population mean rate near target_rate.
- init(target_rate, tau)
- update(population)
- Scale weights of all incoming projections to population.
Class ShortTermPlasticity¶
Tsodyks-Markram short-term plasticity (STP).
Tsodyks & Markram 1997. Models depression (tau_d) and facilitation (tau_f) with use parameter u_se.
- init(tau_d, tau_f, u_se)
- update(pre_spikes)
- Compute effective weight scaling given pre-synaptic spikes.
Class StructuralPlasticity¶
Activity-dependent synapse creation and elimination.
Grows new synapses between correlated neurons and prunes weak ones.
- init(growth_rate, prune_threshold)
- update(projection)
- Grow or prune synapses in a Projection based on activity.
Module learning.callbacks¶
Class TrainingCallback¶
Base class for training callbacks.
- log(metrics, step)
- Record a mapping of metric names to values at the given step.
- close()
- Flush and release any resources held by the callback.
Class TensorBoardCallback¶
Log scalars to TensorBoard via torch.utils.tensorboard.
- init(log_dir)
- log(metrics, step)
- Write each metric as a TensorBoard scalar at the given step.
- close()
- Close the underlying TensorBoard summary writer.
Class WandBCallback¶
Log metrics to Weights & Biases.
- init(project)
- log(metrics, step)
- Forward the metrics to the active Weights & Biases run.
- close()
- Finish the active Weights & Biases run.
Class CSVCallback¶
Log metrics to a CSV file (no dependencies).
- init(path)
- log(metrics, step)
- Buffer one row of metrics for the given step in memory.
- close()
- Write all buffered metric rows to the CSV file.
Module learning.federated¶
Class FederatedAggregator¶
Privacy-preserving federated learning using SC bitstreams.
- aggregate_gradients(client_gradients)
- Aggregate gradient bitstreams from multiple clients by majority vote.
- secure_sum_protocol(client_gradients)
- Sum client bitstreams as a secure-aggregation surrogate.
Module learning.lifelong¶
Class EWC_SCLayer¶
Lifelong Learning Layer using Elastic Weight Consolidation (Approx).
- post_init()
- consolidate_task()
- Call after finishing a task.
- apply_ewc_penalty(step_size)
- Push weights back toward consolidated values, weighted by Fisher info.
Module learning.neuroevolution¶
Class SNNGeneticEvolver¶
Genetic algorithm for evolving SNN weights and parameters.
- init(layer_factory, fitness_func)
- evolve(generations)
- Run the GA for the given number of generations and return the best individual.
Module learning.online_o1¶
Class OnlineO1Config¶
Hardware-bounded configuration for local reward-modulated STDP.
- post_init()
- Validate and normalize fixed-point fields after dataclass initialization.
- max_weight()
- Maximum unsigned fixed-point weight.
- max_trace()
- Maximum unsigned trace value.
- min_eligibility()
- Minimum signed eligibility value.
- max_eligibility()
- Maximum signed eligibility value.
- min_reward()
- Minimum signed reward input.
- max_reward()
- Maximum signed reward input.
- per_synapse_state_bits()
- Stored bits per synapse: weight plus three bounded traces.
- to_scnir_annotation()
- Return deterministic SC-NIR metadata for online-learning synapses.
Class OnlineO1Snapshot¶
Immutable synapse state snapshot after one online update.
Class OnlineO1Synapse¶
One fixed-point reward-modulated STDP synapse with O(1) state.
- post_init()
- Initialize bounded mutable synapse state from a validated configuration.
- state_fields()
- Names of state fields retained between timesteps.
- state_bit_count()
- Stored state bits for one synapse.
- snapshot()
- Return the current bounded state.
- step()
- Advance one streamed timestep and return the bounded state.
Function build_online_o1_memory_proof()¶
Return a sequence-length independent memory proof for the rule.
Module learning.schedulers¶
Class StepScheduler¶
Drop learning rate by gamma every step_size steps.
- init(lr_init, step_size, gamma)
- step()
- Advance one scheduler step and return the current learning rate.
- reset()
- Reset the internal step counter without changing the current rate.
Class ExponentialScheduler¶
Multiply learning rate by gamma each step.
- init(lr_init, gamma)
- step()
- Apply one exponential decay update and return the new rate.
- reset()
- Leave the stateless exponential schedule unchanged.
Class CosineScheduler¶
Cosine annealing from lr_init to lr_min over total_steps.
- init(lr_init, lr_min, total_steps)
- step()
- Advance one cosine-annealing step and return the new rate.
- reset()
- Restore the initial learning rate and restart the cosine schedule.
Class WarmupCosineScheduler¶
Linear warmup followed by cosine decay.
- init(lr_init, lr_min, warmup_steps, total_steps)
- step()
- Advance through warmup or cosine decay and return the current rate.
- reset()
- Return to the pre-warmup state with zero current learning rate.
Module license¶
Class CommercialLicenseStatus¶
Current AGPL/commercial licence state.
The raw licence key is intentionally never stored in this object.
Function get_license_status()¶
Return the current local licence state without contacting a network.
Function reset_license_status()¶
Reset process-local licence state to the default AGPL mode.
Function set_license_key(key)¶
Validate and install an explicit commercial licence key for this process.
Function load_license_from_env()¶
Validate SC_NEUROCORE_LICENSE_KEY when it is explicitly configured.
Function validate_license_key(key)¶
Validate a Polar customer-portal licence key.
Validation is opt-in. AGPL users who never call this function, never call
set_license_key(), and do not set SC_NEUROCORE_LICENSE_KEY are not
blocked and do not need the HTTP dependency.
Module math.category_theory¶
Class CategoryObject¶
Domain-tagged value transported between computational categories.
Class Morphism¶
Named structure-preserving map between two :class:CategoryObject domains.
- init(func, name)
- call(obj)
- Apply the morphism, tagging the result with the morphism name.
Class CategoryTheoryBridge¶
Functors mapping between the stochastic, quantum, and bio domains.
- stochastic_to_quantum(bitstream)
- Map a bitstream probability
pto the quantum amplitude pair. - quantum_to_bio(state_vector)
- Map quantum probability
|beta|^2to a concentration in[0, 10]uM. - bio_to_stochastic(concentration, length)
- Map a concentration to a Bernoulli bitstream of the given length.
- get_functor(source, target)
- Return the morphism mapping the
sourcedomain totarget.
Module math.topology¶
Function winding_number(phases)¶
Compute the winding number of a phase trajectory around S^1.
The winding number counts how many times the phase wraps around the circle [0, 2*pi). It is a topological invariant — continuous deformations of the trajectory cannot change it.
Parameters¶
phases : np.ndarray, shape (T,) Time series of phase values (radians).
Returns¶
int Number of complete windings (positive = counterclockwise).
Function ollivier_ricci_curvature(knm, i, j, backend)¶
Compute Ollivier-Ricci curvature between nodes i and j on the coupling graph.
Ollivier (2009), "Ricci curvature of Markov chains on metric spaces." The curvature kappa(i,j) measures how much the neighborhoods of i and j overlap. Positive curvature = neighborhoods converge (community structure). Negative curvature = neighborhoods diverge (bottleneck).
kappa(i,j) = 1 - W1(mu_i, mu_j) / d(i,j) where mu_i is the lazy random walk distribution from node i, and W1 is the Wasserstein-1 distance on the unweighted support graph (an exact successive-shortest-path min-cost flow).
Parameters¶
knm : np.ndarray, shape (N, N)
Coupling matrix (non-negative, not necessarily symmetric).
i, j : int
Node indices.
backend : {"auto", "rust", "julia", "go", "mojo", "python"}
Acceleration backend selector. auto prefers Rust when the
sc_neurocore_engine wheel is built, else the pure-NumPy path.
The named backends force a specific path and raise RuntimeError
when that backend is unavailable. Every backend reproduces the
NumPy reference to float64 round-off.
Returns¶
float Ollivier-Ricci curvature. Returns 0.0 for self or disconnected pairs.
Function sheaf_consistency_defect(phases, knm)¶
Compute the sheaf consistency defect for the SCPN phase state.
In sheaf theory, a global section exists iff the gluing conditions are satisfied on all overlaps. For the SCPN, the coupling matrix defines the overlaps, and the phase differences weighted by coupling measure the failure to glue.
defect = (1/N^2) * sum_{i,j} |K_ij| * |1 - cos(theta_i - theta_j)|
When phases are synchronized (all equal), defect = 0. When phases are maximally incoherent, defect approaches max(|K|).
This is equivalent to (1 - Kuramoto_R) weighted by coupling.
Parameters¶
phases : np.ndarray, shape (N,) Phase values (radians) for each layer/oscillator. knm : np.ndarray, shape (N, N) Coupling matrix.
Returns¶
float Sheaf consistency defect >= 0. Zero means globally coherent.
Function connection_curvature(phases, knm)¶
Compute the connection curvature from PGBO phase dynamics.
The PGBO covariant derivative u_mu = dphi_mu - alpha * A_mu defines a U(1) connection. The curvature F_{ij} = K_{ij} * cos(theta_i - theta_j) measures the obstruction to parallel transport between layers i and j.
Parameters¶
phases : np.ndarray, shape (N,) Phase values. knm : np.ndarray, shape (N, N) Coupling matrix.
Returns¶
np.ndarray, shape (N, N) Connection curvature matrix. Diagonal is zero.
Module memristor.memristor_mapper¶
Class MemristorTechnology¶
Supported memristor fabrication technologies.
Class ConductanceModel¶
Per-device conductance variability model.
Models both device-to-device (D2D) fabrication variability and cycle-to-cycle (C2C) read/write noise as Gaussian distributions.
- post_init()
- Fill any unset conductance parameters from the technology presets.
- dynamic_range()
- ON/OFF conductance ratio.
- level_step()
- Conductance step between adjacent levels.
- target_conductance(level)
- Nominal conductance for a given quantisation level.
- sample_d2d(level, rng)
- Sample actual conductance with device-to-device variability.
- sample_rw(conductance, rng)
- Apply read/write noise to a conductance value.
- drift(conductance, elapsed_s, alpha)
- Model conductance drift over time.
- thermal_shift(conductance, temp_c, ref_c)
- Temperature-dependent conductance shift.
Class SneakPathModel¶
Estimates sneak-path leakage in passive crossbar arrays.
In an M×N passive crossbar, selecting cell (r,c) exposes parallel leakage paths through unselected devices. Worst-case sneak current is proportional to (M+N-2) × G_off.
- worst_case_sneak(rows, cols, g_off, v_read)
- Worst-case sneak current (A) through unselected paths.
- signal_to_sneak_ratio(g_on, g_off, rows, cols)
- Ratio of desired signal current to sneak current.
Class IRDropModel¶
Models interconnect wire resistance and voltage drop.
- voltage_drop(row, col)
- Accumulated IR drop at cell (row, col) from corner.
- effective_conductance(g_nominal, row, col, v_read)
- Conductance seen at read amplifier after IR drop.
Class StuckFaultMap¶
Map of stuck-at ON/OFF devices in a crossbar.
- generate(cls, rows, cols, fault_rate, seed)
- Generate random stuck faults at given rate.
- is_stuck(row, col)
- Return 'on', 'off', or None.
- num_faults()
- Return the total count of stuck-on and stuck-off devices.
- fault_rate()
- Return the fraction of crossbar cells that are faulty.
Class AgingReport¶
Results of aging simulation.
Class AgingSimulator¶
Simulates conductance drift over device lifetime.
- init(model, alpha)
- simulate(conductances, elapsed_s)
- Apply drift to all conductances, return (drifted, report).
Class SCAbsorbEncoder¶
Adjusts SC encoding thresholds to absorb known device variability.
Instead of compensating post-silicon, pre-distorts the bitstream encoding thresholds so that the effective computation matches ideal.
- compute_adjusted_thresholds(ideal_weights, actual_conductances, model, q_bits)
- Return Q8.8 adjusted thresholds that absorb device error.
Class WriteVerifyResult¶
Outcome of iterative write-verify programming.
Class WriteVerifyProtocol¶
Iterative program-verify loop for memristor cells.
- init(model, max_iterations, tolerance, seed)
- program_cell(target_level)
- Program a single cell to target level with verify.
Class CrossbarPowerEstimate¶
Power and performance estimate for a crossbar tile.
Class CrossbarEstimator¶
Estimates power, latency, and area for crossbar arrays.
- estimate(cls, crossbar)
- Estimate read/write power, latency and area for a crossbar array.
Class CrossbarTopology¶
Physical wiring topology of a memristor crossbar array.
Class CrossbarArray¶
Physical crossbar array specification.
- num_devices()
- Return the device count, doubling for differential topologies.
- conductance_model()
- Return the conductance model for this array's technology.
Class VariabilityInjector¶
Injects fab-realistic conductance variability into weight matrices.
- init(model, seed)
- quantize_weights(weights)
- Map floating-point weights [0, 1] to conductance levels.
- inject_d2d(levels)
- Apply device-to-device variability to quantised levels.
- inject_rw(conductances)
- Apply read/write noise to conductance values.
- inject_full(weights)
- Full pipeline: quantise → D2D → R/W noise. Returns (levels, conductances).
- compute_error(weights, conductances)
- Compute variability-induced error statistics.
Class CompensationStrategy¶
Strategy for compensating memristor conductance non-idealities.
Class CompensationLUT¶
Per-device compensation lookup table.
Maps nominal level → compensated threshold to absorb known D2D variability at design time (program-verify or digital pre-distortion).
- build(cls, device_id, model, measured_g)
- Build compensation LUT from measured or modelled conductances.
- max_compensation()
- Maximum compensation ratio (deviation from 1.0).
Class CrossbarMapping¶
Mapping of a weight matrix to a crossbar array.
Class MappingResult¶
Full result of a memristor mapping pass.
Class MemristorMapper¶
Maps SC network weight matrices to physical crossbar arrays.
- init(technology, topology, max_crossbar_size, compensation, seed)
- map_weights(weights)
- Map a weight matrix (or list of matrices) to crossbar arrays.
Class MonteCarloReport¶
Results from Monte Carlo variability co-simulation.
Class MonteCarloSimulator¶
Monte Carlo co-simulation with variability injection.
Runs N trials of a crossbar multiply-accumulate operation with independently sampled D2D + R/W variability to estimate output error distributions and yield.
- init(model, num_trials, tolerance, seed)
- simulate_mac(weights, inputs)
- Simulate multiply-accumulate with variability.
Class VerilogEmitter¶
Generates crossbar-aware SystemVerilog with compensation LUTs.
- init(bit_width, frac_bits)
- emit_crossbar(mapping, module_name)
- Generate SystemVerilog for a single crossbar tile.
- emit_top(result, module_name)
- Generate top-level module instantiating all crossbar tiles.
Module meta_plasticity.meta_plasticity¶
Class STDPParams¶
Mutable STDP parameters.
- to_vector()
- from_vector(cls, v)
Class STPParams¶
Mutable short-term plasticity parameters.
- to_vector()
- from_vector(cls, v)
Class HomeostaticParams¶
Homeostatic plasticity: target rate + gain modulation.
- adapt(measured_rate_hz)
- Adjust gain to push firing rate toward target.
Class BitstreamParams¶
Mutable SC bitstream parameters.
Class PlasticityRuleSet¶
Complete set of mutable plasticity rules.
This is the "genome" that the meta-controller evolves.
- to_vector()
- Serialise all mutable params to a flat vector.
- from_vector(cls, v, gen)
- vector_dim()
- copy()
Class MetaSignalType¶
Types of meta-control signals from L16.
Class MetaControlSignal¶
One meta-control directive.
Class MetaController¶
SC-domain meta-controller that rewrites plasticity rules.
Observes network performance metrics (surprise, novelty, GCI, firing rates) and emits rule modifications. The controller itself uses SC bitstream logic for decision-making.
- init(sensitivity, rng_seed)
- observe(metrics)
- Record one observation of network state.
- decide()
- Decide what meta-control signals to emit.
- apply_signals(rules, signals)
- Apply meta-control signals to a rule set (in-place).
Class RuleEvolver¶
Evolutionary engine for plasticity rule sets.
Maintains a population of candidate rules, evaluates fitness, and evolves via selection + crossover + mutation.
- post_init()
- evaluate_fitness(rules, metrics)
- Compute fitness from network performance metrics.
- select_parents()
- Tournament selection of two parents.
- crossover(p1, p2)
- Uniform crossover of two rule sets.
- mutate(rules)
- Gaussian mutation of rule parameters.
- evolve()
- Run one generation of evolution.
- best()
- mean_fitness()
Class NeuromodulatorType¶
Class NeuromodulatorState¶
Simulated neuromodulatory tone that modulates meta-plasticity.
- update(novelty, surprise, gci)
- Update neuromodulator levels from network state.
- modulation_factor(param)
- Get a combined modulation factor for a specific parameter type.
Class EngineConfig¶
Configuration for the meta-plasticity engine.
Class MetaPlasticityEngine¶
Top-level orchestrator for self-evolving meta-plasticity.
Connects ArcaneNeuron populations, the meta-controller, and the rule evolver into a single lifelong learning system.
- step(metrics)
- Process one timestep of meta-plasticity.
- status()
Class RuleCheckpoint¶
Serialisable snapshot of a PlasticityRuleSet at a point in time.
- restore()
Class CheckpointStore¶
Persistent store for rule checkpoints.
- save(rules, step, tag)
- restore_best()
- restore_by_tag(tag)
- count()
Class EWCProtection¶
Elastic Weight Consolidation for plasticity parameters.
Penalises large deviations from previously learned rule vectors to protect against catastrophic forgetting.
- consolidate(rules)
- Set the current rules as the anchor point.
- penalty(rules)
- Compute EWC penalty for deviating from anchor.
- regularise(rules, max_penalty)
- Pull rules back toward anchor if penalty exceeds threshold.
Class CuriositySignal¶
Intrinsic curiosity based on prediction error of network state.
Tracks expected next-state and computes curiosity as the prediction error magnitude. High curiosity → explore (increase meta-plasticity).
- update(state_vector)
- Update prediction model and return curiosity score.
Class MetaLearningRate¶
Learning rate of the learning rate.
Adapts the meta-controller sensitivity based on whether recent rule changes improved fitness.
- update(fitness_delta)
- Adjust meta_lr from fitness delta. Positive = good → speed up.
Class SleepPhase¶
Offline memory consolidation via experience replay.
Stores recent metric snapshots and replays them during sleep to stabilise rule sets without new input.
- record(metrics)
- sleep(engine_step_fn)
- Run consolidation by replaying buffered experiences.
- buffer_size()
Class SynapticTag¶
Synaptic tag for early→late LTP conversion.
- is_expired()
Class TaggingModel¶
Synaptic tagging and capture model.
Early-phase LTP creates a tag. If a consolidation signal arrives before the tag decays, it is "captured" into late-phase LTP.
- create_tag(synapse_id, strength, time_ms)
- decay_tags(dt_ms)
- consolidate(consolidation_strength)
- Attempt capture on all active tags. Returns count of captured.
- prune_expired()
- active_tags()
Class ContextRuleBank¶
Maintains separate rule sets per context/task.
Allows rapid switching between learned plasticity configurations without catastrophic interference.
- store(context, rules)
- switch(context)
- contexts()
- num_contexts()
Class FitnessTrajectory¶
Tracks fitness over time and detects trends.
- record(fitness)
- trend()
- Return slope of fitness over recent window. >0 = improving.
- is_improving()
- is_stagnant()
- best_ever()
Class RuleConstraints¶
Hard constraints on plasticity parameters to prevent pathological values.
- enforce(rules)
- Clamp all parameters to valid ranges.
- is_valid(rules)
- Check if all parameters are within constraints.
Function population_diversity(evolver)¶
Compute diversity as mean pairwise L2 distance of rule vectors.
Function inject_diversity(evolver, n_random)¶
Replace worst individuals with fresh random rule sets.
Module model_zoo.configs¶
Function mnist_classifier(n_hidden)¶
784-128-10 feedforward SNN for MNIST-like digit classification.
Architecture follows Zenke & Ganguli 2018 (SuperSpike), Table 1: input Poisson layer -> hidden LIF -> output LIF. Weights are Xavier-uniform initialised (not trained).
Reference: Zenke & Ganguli, Neural Computation 30(6), 2018.
Function dvs_gesture_classifier(n_classes)¶
Event-camera gesture recognition SNN (Amir et al. 2017 / IBM DVS128).
2-layer feedforward: 256 input -> 256 hidden -> n_classes output. Poisson input simulates DVS event stream at 500 Hz.
Reference: Amir et al., CVPR 2017.
Function shd_speech_classifier()¶
Spiking Heidelberg Digits (SHD) recurrent architecture.
Recurrent hidden layer with sparse recurrent connectivity, projecting to 20-class readout. Topology matches Cramer et al. 2020, Table 2: 700 input -> 256 recurrent -> 20 out.
Reference: Cramer et al., IEEE TNNLS 33(7), 2022.
Function brunel_balanced_network(n_exc, n_inh, g, eta)¶
Brunel 2000 sparse balanced E/I network.
Parameters default to the synchronous irregular (SI) regime: g=5.0 (inhibitory strength ratio), eta=2.0 (external rate / threshold rate). Connectivity probability = 0.1 (epsilon in the paper).
Reference: Brunel, J. Comput. Neurosci. 8(3), 2000, Sec. 2.
Function cortical_column(n_layers)¶
Potjans-Diesmann 2014 cortical microcircuit (scaled down).
4-layer column (L2/3, L4, L5, L6) with E and I populations per layer, using Pospischil RS neurons (excitatory) and Golomb FS neurons (inhibitory). Sizes scaled to ~5% of the original model.
Reference: Potjans & Diesmann, Cerebral Cortex 24(3), 2014.
Function central_pattern_generator(n_oscillators)¶
Half-centre CPG for quadruped locomotion.
Pairs of mutually inhibiting HindmarshRose oscillators produce alternating burst patterns. Adjacent pairs are coupled with phase lag ~pi/2 (walk gait).
Reference: Ijspeert, Neural Networks 21(4), 2008, Sec. 3.
Function decision_making_circuit(n_per_pool)¶
Wang 2002 / Wong & Wang 2006 spiking attractor decision circuit.
Two selective excitatory pools compete via a shared inhibitory population. Uses HH neurons for excitatory pools and WangBuzsaki for inhibitory interneurons.
Reference: Wang, Neuron 36(5), 2002, Fig. 1.
Function working_memory_circuit(n_neurons)¶
Build the legacy SC project-derived working-memory approximation.
Ring of NMDA-based excitatory neurons with distance-dependent connectivity and uniform inhibition. Transient cue creates a persistent activity bump encoding a remembered location.
This 500-cell convenience network is inspired by spatial working-memory attractors but does not reproduce the Compte et al. 2000 2,560-cell network and therefore carries no source-equivalence claim.
Function auditory_processing(n_channels)¶
Cochlear filterbank -> SNN spectro-temporal processing.
Tonotopic input layer (one population per frequency channel) -> lateral inhibition (onset detection) -> integration layer. HodgkinHuxley neurons model auditory nerve fibre dynamics.
Reference: Goodman & Brette, Front. Neurosci. 4, 2010.
Function visual_cortex_v1(n_orientation, n_per_orientation)¶
Simple/complex cell model of primary visual cortex.
Orientation-tuned simple cells (HodgkinHuxley) feed into complex cells (WangBuzsaki) that pool over phase. Cross-orientation inhibition sharpens selectivity.
Reference: Hubel & Wiesel, J. Physiol. 160, 1962; Carandini & Heeger, Nat. Rev. Neurosci. 13, 2012.
Module model_zoo.model_zoo¶
Class NeuronState¶
Generic state container for neuron models.
- getitem(key)
- Return a state variable by name.
- setitem(key, value)
- Assign a state variable by name.
- copy()
- Return an independent copy of this neuron state.
- as_dict()
- Return state variables as a plain dictionary.
Class PluginMeta¶
Metadata carried by every neuron plugin.
Class NeuronPlugin¶
Abstract base class for pluggable neuron models.
- meta()
- Return metadata describing this neuron plugin.
- default_state()
- Return the default state for a new neuron instance.
- default_params()
- Return default parameters for the neuron dynamics.
- ode_dynamics(state, current, params, dt)
- Advance the neuron state by one timestep dt.
- threshold_check(state, params)
- Return True if the neuron has fired.
- reset(state, params)
- Reset state after a spike.
- simulate(current_trace, dt, params)
- Simulate the neuron response to a current trace.
Class LIFPlugin¶
Leaky Integrate-and-Fire neuron model.
- meta()
- Return LIF plugin metadata and parameter documentation.
- default_state()
- Return the resting LIF membrane state.
- default_params()
- Return default SI-valued LIF parameters.
- ode_dynamics(state, current, params, dt)
- Advance LIF membrane voltage by one Euler step.
- threshold_check(state, params)
- Return whether the LIF voltage crosses threshold.
- reset(state, params)
- Reset LIF membrane voltage after a spike.
Class IzhikevichPlugin¶
Izhikevich (2003) simple model of spiking neurons.
- meta()
- Return Izhikevich plugin metadata and parameter documentation.
- default_state()
- Return regular-spiking Izhikevich default state.
- default_params()
- Return regular-spiking Izhikevich default parameters.
- ode_dynamics(state, current, params, dt)
- Advance Izhikevich membrane and recovery variables.
- threshold_check(state, params)
- Return whether the Izhikevich spike cutoff is crossed.
- reset(state, params)
- Apply Izhikevich post-spike reset to voltage and recovery.
Class AdExPlugin¶
Adaptive Exponential Integrate-and-Fire (Brette & Gerstner 2005).
- meta()
- Return AdEx plugin metadata and parameter documentation.
- default_state()
- Return the default AdEx voltage and adaptation state.
- default_params()
- Return Brette-Gerstner style AdEx default parameters.
- ode_dynamics(state, current, params, dt)
- Advance AdEx voltage and adaptation current by one Euler step.
- threshold_check(state, params)
- Return whether the AdEx spike cutoff is crossed.
- reset(state, params)
- Apply AdEx spike reset and adaptation increment.
Class HodgkinHuxleyPlugin¶
Hodgkin–Huxley conductance-based model (1952).
- meta()
- Return Hodgkin-Huxley plugin metadata and parameter documentation.
- default_state()
- Return resting Hodgkin-Huxley voltage and gating variables.
- default_params()
- Return canonical Hodgkin-Huxley conductance parameters.
- ode_dynamics(state, current, params, dt)
- Advance Hodgkin-Huxley voltage and gating variables.
- threshold_check(state, params)
- Return whether the Hodgkin-Huxley voltage threshold is crossed.
- reset(state, params)
- Return an independent no-op reset copy for Hodgkin-Huxley.
Class PluginRegistry¶
Discovers and manages neuron model plugins.
- init()
- Create an empty plugin registry.
- register(plugin)
- Register a neuron plugin under its metadata name.
- get(name)
- Return a registered plugin by name, if present.
- list_plugins()
- Return registered plugin names in deterministic order.
- len()
- Return the number of registered plugins.
- contains(name)
- Return whether a plugin name is registered.
- with_builtins(cls)
- Create a registry pre-loaded with all built-in neuron models.
Class VerilogGenerator¶
Generates synthesisable SystemVerilog from a NeuronPlugin.
- init(bit_width, frac_bits)
- Configure fixed-point width for generated plugin modules.
- generate(plugin)
- Produce a complete SystemVerilog module for the given plugin.
Class DocGenerator¶
Generates markdown documentation from plugin metadata.
- generate(plugin)
- Generate Markdown documentation for one plugin.
- generate_index(registry)
- Generate a summary index for all registered plugins.
Module model_zoo.pretrained¶
Function load_pretrained(name)¶
Build a model-zoo network and load its shipped pretrained weights.
Parameters¶
name:
Registered pretrained model name. Supported values are "mnist",
"shd", and "dvs_gesture".
Returns¶
Network
A freshly built network whose projection CSR arrays were replaced by
validated arrays from the matching .npz archive.
Raises¶
ValueError If the name is unknown, the registry/schema wiring is inconsistent, the built network projection layout does not match the archive schema, or any archive member is malformed. FileNotFoundError If the expected pretrained archive is missing.
Module models.zoo¶
Class SCDigitClassifier¶
Pre-configured SC Network for MNIST-like Digit Classification. Uses: Conv Layer -> Vectorized Dense Layer
- init()
- forward(image)
- Classify a 28x28 image.
Class SCKeywordSpotter¶
Dense MFCC keyword spotter (e.g. "Yes"/"No").
Classifies a fixed-length 16-dimensional MFCC feature vector with a single vectorized SC dense layer. This is the feed-forward baseline; a recurrent variant for variable-length audio sequences is not yet implemented.
- init(n_keywords)
- predict(mfcc_features)
Module nas.darts_sc_nas¶
Class BitstreamCandidate¶
SC bitstream candidate that injects variance for one stream length.
- init(length, lut_cost, power_cost)
- forward(x)
- Return the candidate output with training-time SC variance noise.
Class SCMixedOp¶
Continuous relaxation over discrete SC bitstream configurations.
- init(c_in, c_out, kernel_size, stride, padding)
- forward(x)
- Return the mixed convolution output under DARTS bitstream weights.
- expected_resource_cost()
- Return expected LUT and power costs from architecture weights.
- extract_optimal_config()
- Return the bitstream length with the largest architecture logit.
Class SCNASNetwork¶
Small differentiable hardware-aware search network for SC-NAS.
- init()
- forward(x)
- Return class logits from the differentiable SC-NAS network.
- hardware_penalty()
- Return expected LUT and power penalties across search layers.
Module nas.equiv¶
Class EquivResult¶
Result of a formal equivalence check.
- summary()
- Return a one-line verdict for the equivalence proof result.
Function generate_miter(dut_module, ref_module, top_name, data_width, fraction)¶
Generate a Verilog miter circuit for two modules.
Both modules must have identical port signatures: clk, rst_n, leak_k, gain_k, I_t, noise_in -> spike_out, v_out
Function generate_sby(top_name, verilog_files, depth, engine)¶
Generate a SymbiYosys .sby proof script.
Function check_equivalence(dut_verilog, ref_verilog, depth, run)¶
Check formal equivalence between DUT and reference.
Parameters¶
dut_verilog : str DUT module name (must exist in hdl/). ref_verilog : str Reference module name (must exist in hdl/equiv/). depth : int BMC depth (number of clock cycles to check). run : bool If True, actually run SymbiYosys. Requires sby + z3 installed. If False, generate proof files and return without running.
Returns¶
EquivResult
Module nas.sc_nas_engine¶
Class DecorrelationStrategy¶
Supported bitstream decorrelation generators for SC-NAS candidates.
Class NeuronType¶
Neuron model families available to the hardware-aware NAS search.
Class FPGAResourceBudget¶
Hardware resource constraints for the target FPGA.
- utilisation(luts, ffs, bram, dsp)
- Return per-resource utilisation ratios for a candidate design.
Class NASObjective¶
Search objectives and constraints.
Class LayerConfig¶
Configuration for a single network layer.
- lut_cost()
- Return estimated LUT cost for this layer.
- ff_cost()
- Return estimated flip-flop cost for this layer.
- dsp_cost()
- Return estimated DSP block cost for this layer.
- bram_cost_kb()
- Return estimated BRAM storage cost in kibibytes.
- power_cost()
- Return estimated dynamic power cost in milliwatts.
Class SCCandidate¶
A candidate SC network architecture.
- evaluate_resources()
- Update aggregate resource estimates from the candidate layers.
- meets_budget(budget)
- Return whether this candidate fits within an FPGA resource budget.
- fingerprint()
- Return a deterministic non-cryptographic architecture fingerprint.
Class SCFitnessEvaluator¶
Pure-Python SC simulation fitness evaluator.
Uses the SC variance model: for a bitstream of length N encoding probability p, the variance is p*(1-p)/N. Accuracy is estimated as 1 − mean_variance across all layers.
- init(seed)
- evaluate(candidate, target_p)
- Evaluate candidate accuracy via SC variance model.
Class EvolutionaryNAS¶
µ+λ evolutionary search with tournament selection.
- init(objective, budget, population_size, num_generations, mutation_rate, seed, convergence_patience, surrogate_optimizer)
- search()
- Run the evolutionary search. Returns the final Pareto front.
Class NASReport¶
Summary report from an SC-NAS search.
- best_accuracy()
- Return the best accuracy in the Pareto front, or zero when empty.
- most_efficient()
- Return the lowest-LUT candidate in the Pareto front, if present.
- summary()
- Return a deterministic human-readable search summary.
Class NASVerilogEmitter¶
Emits SystemVerilog for Pareto-optimal SC-NAS candidates.
- emit(candidate, module_name)
- Generate SystemVerilog for a searched architecture.
- emit_pareto(front)
- Emit Verilog for all Pareto-optimal candidates.
Function pareto_front(candidates, objectives)¶
Extract the Pareto-optimal front (NSGA-II non-dominated sorting).
Maximises accuracy, minimises resource usage.
Function run_nas(objective, budget, population_size, num_generations, seed, convergence_patience, surrogate_optimizer)¶
Run an SC-NAS search and return its report.
Module nas.search¶
Class NASResult¶
Result of a NAS run.
- best_accuracy()
- Architecture with highest accuracy on the Pareto front.
- best_efficiency()
- Architecture with lowest energy on the Pareto front.
- summary()
- Return a line-oriented summary of the Pareto front.
Function nas(space, target, population_size, generations, max_luts, accuracy_fn, seed)¶
Run hardware-aware NAS using NSGA-II.
Parameters¶
space : SearchSpace Architecture search space definition. target : str FPGA target for hardware cost evaluation. population_size : int Number of architectures per generation. generations : int Number of evolutionary generations. max_luts : int, optional Hard LUT budget. Architectures exceeding this are penalized. If None, uses the target's total LUT count. accuracy_fn : callable, optional Function(Architecture) -> float accuracy in [0, 1]. If None, uses a proxy based on network capacity. seed : int Random seed.
Returns¶
NASResult Pareto front + all evaluated architectures.
Module nas.search_space¶
Class Architecture¶
One point in the NAS search space.
- n_layers()
- Return the number of layers encoded by this architecture.
- layer_sizes()
- Return adjacent layer dimensions for hardware cost estimation.
- total_params()
- Return the dense connection count across all encoded layers.
Class SearchSpace¶
Configurable NAS search space.
Parameters¶
n_inputs : int Input dimension. n_outputs : int Output dimension (width of final layer). min_layers, max_layers : int Range of hidden layer count. width_choices : list of int Candidate widths per layer. neuron_choices : list of str Candidate neuron models. L_choices : list of int Candidate bitstream lengths. delay_choices : list of int Candidate max-delay values.
- random_architecture(rng)
- Sample a random architecture from the space.
- mutate(arch, rng)
- Mutate one random gene in the architecture.
- crossover(a, b, rng)
- Uniform crossover between two architectures of equal layer count.
- space_size()
- Approximate total architectures in the search space.
Module nas.surrogate_bridge¶
Class SupportsSurrogateOptimise¶
Minimal optimiser interface required by SC-NAS integration.
- optimise(network)
- Return a surrogate report for NAS layer profiles.
Class NASPolicyLayer¶
Per-layer compiler policy attached to an SC-NAS candidate.
Class NASPolicyPlan¶
Surrogate optimiser policy projected onto an SC-NAS candidate.
Class NASPolicyEvaluation¶
Result of calling the surrogate optimiser from inside NAS evaluation.
Function candidate_layer_profiles(candidate)¶
Convert an SC-NAS candidate into optimiser layer profiles.
Function optimise_candidate_policy(candidate, optimiser)¶
Run the surrogate optimiser for a candidate and optionally apply its policy.
Function evaluate_candidate_with_surrogate(candidate, optimiser)¶
Score a candidate through the surrogate optimiser for NAS search loops.
Function build_nas_policy_plan(candidate, report)¶
Project a surrogate optimiser report onto a NAS candidate.
Function apply_surrogate_policy(candidate, report)¶
Return a candidate copy with compatible bitstream/decorrelator settings.
Module network._cortical_column_backends¶
Class NativeBackends¶
Native kernels discovered for one import of the public module.
Function discover_native_backends(public_module_file, logger, import_module)¶
Discover optional Rust, Julia, Go, and Mojo cortical-column kernels.
Discovery is invoked by the public module on every import or reload so its historical module-level capability flags remain truthful and monkeypatchable. Missing optional runtimes fail closed to the Python implementation.
Module network._cortical_column_parameters¶
Function population_sizes(scale)¶
Return Potjans population sizes at scale without building connectivity.
The full published column has roughly 77k neurons and hundreds of millions of synapses. Size contracts must therefore be observable without materialising the full synapse graph.
Module network._torch_bridge¶
Class NetworkTorchBridge¶
Differentiable bridge for a bounded subset of declarative Network graphs.
- init(populations, projections, surrogate_fn)
- forward(inputs)
- Run the differentiable bridge on
(T, batch, input_dim)current input. - sync_to_network()
- Copy learned bridge weights back into the underlying CSR projections.
Module network.cortical_column¶
Class CorticalColumn¶
Potjans & Diesmann 2014 8-population cortical microcircuit.
Parameters¶
scale : float, optional
Population-size multiplier in (0, 1]. Default 0.1
(≈ 7700 neurons), which is the smallest size where the
published Table 4 firing rates are reproduced within
tolerance. scale=1.0 yields the full ~77 000-neuron model.
bg_rate : float, optional
Background Poisson rate per channel (Hz). Defaults to the
published 8.0; setting to 0.0 disengages the drive (useful
for fidelity tests that confirm cells go silent).
g_inh : float, optional
Relative inhibitory weight. Defaults to the published 4.0.
scale_correction : bool, optional
When True (default), scales per-synapse weights by 1/scale
so that mean drive per cell is preserved at sub-full scale
(van Albada et al. 2015). Disable to study finite-size
effects directly.
seed : int or None, optional
Per-instance RNG seed for connectivity, voltages and
background Poisson. None → fresh entropy.
- init(scale, bg_rate, g_inh, scale_correction, delay_distribution, n_delay_bins, use_block_csr, seed, backend)
- population_sizes(scale)
- Return Potjans population sizes at
scalewithout building connectivity. - step(dt)
- Advance the network by one timestep
dt(ms). - simulate(duration_ms, dt)
- Run the network for
duration_msms. - population_rates(rasters, dt, burn_in_ms)
- Return mean firing rate (Hz) per population.
- total_indegree(target)
- Return mean total synaptic in-degree of a target cell.
- reset_state()
- Re-randomise voltages, currents and refractory state.
- repr()
- Return a concise debug representation of the cortical column.
- population_names()
- Return the ordered cortical population names.
Module network.export¶
Function export_verilog(network, output_dir, target)¶
Export a LIF-based network to Verilog files.
Module network.gamma_oscillation¶
Class PINGCircuit¶
Conductance-based PING circuit (Börgers-Kopell 2003).
Parameters mirror the publication; defaults reproduce the 40 Hz
weak-PING regime from Fig 2A. Override i_drive_e_mean to scan
drive-frequency curves; override w_EI / w_IE to scan the
gain-loop strength.
- post_init()
- Validate the population sizes and initialise oscillator state.
- step(dt)
- Advance one timestep (dt in ms); return (spikes_e, spikes_i).
- reset_state()
- Re-initialise voltages, conductances and refractory state.
- population_rate(spike_log, dt, bin_ms)
- Bin per-step spike booleans into a population rate (Hz).
- dominant_frequency(spike_log, dt, bin_ms, f_min, f_max)
- Return the dominant frequency (Hz) in the population rate.
Module network.monitor¶
Class SpikeMonitor¶
Records (neuron_idx, timestep) pairs from a population.
- init(population, label)
- record(spikes, t_step)
- Store spike events for this timestep (from binary spike vector).
- record_event(neuron_id, t_step)
- Store a single spike event directly (from Rust backend).
- spike_times()
- All spike timesteps as 1-D array.
- spike_trains()
- Per-neuron spike timestep arrays.
- count()
- Total number of spikes recorded.
- raster_data()
- Return (timesteps, neuron_ids) arrays for raster plots.
- firing_rates(n_steps, dt)
- Mean firing rate (Hz) per neuron over the simulation.
- isi(neuron)
- Inter-spike intervals (timestep units) for a single neuron.
- cross_correlation(i, j, max_lag)
- Cross-correlogram between neurons i and j.
Class StateMonitor¶
Records state variable traces from a population.
- init(population, variables, record)
- snapshot(t_step)
- Capture current state variables.
- traces()
- Variable traces as {name: (n_steps, n_neurons)} arrays.
- t()
- Return the recorded snapshot timestep array.
Class RateMonitor¶
Population firing rate in time bins.
- init(population, bin_ms)
- record(spikes, t_step, dt)
- Accumulate spikes; flush when a bin completes.
- rate()
- Firing rate (Hz) per bin.
- t()
- Bin edge timestep array.
Module network.mpi_runner¶
Class MPIRunner¶
MPI-distributed network simulation.
Partitions populations across MPI ranks via round-robin assignment.
Each rank steps only its local populations; spikes propagate via
MPI_Allgatherv every timestep.
Each rank steps supported local populations through the Rust engine's
step_population API when the extension is importable and every
local model on the rank is supported. Otherwise the runner falls back
to Population.step_all for CPU-only environments. spike_gating
and fim_lambda are unsupported by this runner — the
Network._run_mpi dispatcher raises NotImplementedError when
either is requested with backend='mpi'.
- init(network)
- run(n_steps, dt)
- Run the distributed simulation for n_steps timesteps.
Module network.network¶
Class Network¶
Declarative network: collects objects, runs the simulation loop.
- init()
- add(obj)
- Register a simulation object by type.
- run(duration, dt, progress, backend, spike_gating)
- Run the simulation for duration seconds at timestep dt.
- to_torch(surrogate_fn)
- Build an explicit differentiable bridge without altering NumPy/Rust execution.
Module network.population¶
Class Population¶
A group of N identical neurons with vectorized state access.
- init(model, n, params, label)
- Create n neurons of model (class or string name).
- quiescent_signature()
- Return the state this population's model holds under zero input.
- step_all(currents, spike_gating)
- Advance all neurons one timestep; return binary spike vector.
- reset_all()
- Reset every neuron to its initial state.
- get_states()
- Collect all neuron states into arrays keyed by variable name.
- set_voltages(voltages)
- Sync voltages from an external source (e.g. Rust backend) into neurons.
- voltages()
- Current membrane voltages (read-only view).
Module network.population_seeds¶
Function derive_population_seeds(base_seed, count, domain)¶
Derive one distinct seed per neuron, reproducibly.
Parameters¶
base_seed : int The seed the population was asked for. It is the only entropy used, so two populations built with the same base seed and count are identical. count : int How many neurons need a seed.
Returns¶
list of int
count distinct seeds in [1, 65535], in neuron order.
Raises¶
ValueError
If count is negative, or exceeds the number of distinct seeds the
domain holds. Refusing is deliberate: the alternative is handing two
neurons the same stream, which is the defect this exists to remove.
Module network.projection¶
Class Projection¶
Synaptic projection from source to target population.
Parameters¶
delay : float, array-like, or 0
Axonal delay in timesteps, not in milliseconds. The unit is the
integration step the network is run at, so the same number means a
different physical delay at a different dt.
- 0: no delay (default).
- scalar > 0: uniform axonal delay, shared by every synapse.
- 1-D array of length ``n_synapses``: per-synapse delay, for
heterogeneous axonal delays.
A non-integral value is **rounded to the nearest whole step** —
half to even, so both ``1.5`` and ``2.5`` become 2 — and a positive
value below half a step still occupies one, because a spike that is
delayed at all cannot arrive in the step it was emitted. Read
:attr:`delay_steps` for what actually runs; ``delay`` keeps the value
that was asked for, and the two differ whenever the request was not a
whole number of steps.
The two forms round differently, which is stated rather than tidied
away: a **scalar** below half a step is floored at one, while the same
value in a **per-synapse array** rounds to zero. Changing either would
move existing runs, so both are pinned by tests instead.
The graph surface refuses a non-integral delay outright rather than
rounding. This facade rounds because it predates that rule and callers
depend on it; the difference is stated here rather than left to be
discovered.
- init(source, target, weight, probability, delay, topology, plasticity, seed, weight_threshold)
- Create projection with CSR connectivity and optional delay/plasticity.
- n_synapses()
- Number of synaptic connections.
- delay_mode()
- Delay mode: 'none', 'uniform', or 'per_synapse'.
- delay_steps()
- The delay that actually runs, in whole timesteps.
- max_delay()
- Maximum delay in timesteps across all synapses.
- propagate(source_spikes)
- Compute target currents from source spikes through CSR connectivity.
- update_plasticity(src_spikes, tgt_spikes, a_plus, a_minus, tau, directional_bias)
- Trace-based STDP weight update.
Function validate_csr_topology(indptr, indices, data, n_source, n_target)¶
Validate and normalize CSR connectivity arrays.
Module network.quiescence¶
Class Steppable¶
A neuron a population can drive one timestep with a scalar input.
- step(current)
- Advance one timestep under current and return the spike flag.
Function state_signature(neuron)¶
Return the exact signature of every attribute a neuron carries.
Function quiescent_signature(neuron)¶
Return the signature of a state the zero-input map leaves unchanged.
Parameters¶
neuron : object A neuron in the state whose quiescence is in question, usually a freshly constructed or reset instance. It is not modified: the probe runs on a copy.
Returns¶
tuple or None
The signature a neuron must match to be skippable, or None when this
model does not hold still — because a copy stepped with zero input
spiked, moved an attribute, refused the call, or could not be copied at
all. None means this model's populations are never gated.
Examples¶
from sc_neurocore.neurons.models.lapicque import LapicqueNeuron quiescent_signature(LapicqueNeuron()) is not None True resting = LapicqueNeuron() resting.v += 5.0 quiescent_signature(resting) is None True
Function is_quiescent(neuron, signature)¶
Return whether a neuron sits exactly at the measured quiescent state.
Module network.rust_dispatch¶
Function population_divergence(population)¶
Return why the native bridge cannot build this population, or "".
Parameters¶
population : Population The population a caller assembled.
Returns¶
str Empty when every neuron equals the neuron the bridge builds from the model name, so dispatching preserves the network. Otherwise a one-line reason naming the population and what differs.
Examples¶
from sc_neurocore.network import Population population_divergence(Population("AdExNeuron", 3)) '' population_divergence(Population("AdExNeuron", 3, {"v_rest": -60.0})) "population 'AdExNeuron' carries v_rest, which the native bridge cannot receive"
Function network_divergences(populations)¶
Return one reason per population the native bridge cannot build faithfully.
Parameters¶
populations : iterable of Population Every population of the network.
Returns¶
list of str Empty when the whole network can be dispatched without changing it.
Module network.sc_compte_wm¶
Class SCCompteCellSpec¶
Intrinsic LIF parameters for one population in source units.
- post_init()
Class SCCompteProtocolSpec¶
Reproducible SC protocol choices for cue, delay, and response epochs.
- post_init()
Class SCCompteWMNetworkSpec¶
Exact public specification of the SC 2,560-cell working-memory ring.
The default is the paper-derived control parameter set. modulated=True
applies the reported 20 percent NMDA and 40 percent GABAA recurrent
conductance increases. structured_ei=True selects the separately
reported tuned E-to-I footprint; the default E-to-I projection is uniform.
- post_init()
- n_cells()
- Return the fixed total population size (2,560).
- preferred_angles_deg(population)
- Return uniformly spaced preferred cues for one ring population.
- recurrent_conductance_ns(projection)
- Return the selected control or modulated recurrent conductance.
- connectivity_footprint(projection, source_angle_deg, target_angles_deg)
- Return an exactly unit-mean footprint over the supplied targets.
- cue_current_pa(center_deg, target_angles_deg)
- Return the SC compact raised-cosine cue current on the ring.
Class SCCompteWMActivityStatistics¶
Frozen population observables for one explicitly bounded time window.
Function circular_distance_deg(angles_deg, center_deg)¶
Return shortest signed distances from center_deg in [-180, 180).
Function circular_displacement_deg(before_deg, after_deg)¶
Return the signed shortest displacement from before_deg to after_deg.
Function summarize_activity(spec, excitatory_spike_counts, inhibitory_spike_counts, window_ms)¶
Compute rates and circular bump observables from one spike-count window.
Module network.sc_compte_wm_backends¶
Class SCCompteWMBackendUnavailable¶
Raised when an explicitly selected native runtime cannot execute.
Class SCCompteWMBackendStatus¶
Availability of one explicitly named full-network runtime.
Class SCCompteWMBackendRun¶
One selected-backend receipt with native execution timing.
Function sc_compte_wm_backend_status()¶
Return deterministic availability details for all five runtimes.
Function run_sc_compte_wm_network(duration_ms)¶
Execute one explicitly selected complete runtime without fallback.
timeout_s=None permits long scientific runs. A finite timeout must be
positive. Native v1 backends accept the fixed public constants plus the
seed and three documented mode flags; incompatible parameter changes fail
before process launch.
Module network.sc_compte_wm_behavior¶
Class SCCompteWMBehaviorProtocol¶
Frozen 2.5-second SC working-memory behavior protocol in milliseconds.
- post_init()
- epoch_starts_ms()
- Return cue, distractor, and response start times.
- stimuli()
- Return the localized cue/distractor and global response stimuli.
Class SCCompteWMBehaviorAcceptance¶
Predeclared v1 thresholds for classifying one protocol receipt.
Class SCCompteWMBehaviorMetrics¶
Circular and rate observables extracted from one ten-window receipt.
Class SCCompteWMBehaviorTrial¶
One selected-runtime, one-seed behavior classification and custody.
Class SCCompteWMBehaviorEnsemble¶
Aggregate acceptance for the reference seeds and all runtime anchors.
Function assess_sc_compte_wm_behavior(run)¶
Classify one complete backend receipt against the frozen v1 protocol.
Function run_sc_compte_wm_behavior_trial()¶
Execute and classify one modulated-network behavior trial.
Function summarize_sc_compte_wm_behavior_ensemble(trials)¶
Require three reference seeds, bidirectional drift, and exact route anchors.
Module network.sc_compte_wm_drive¶
Class CounterPoissonReceipt¶
Auditable receipt for one population input sample.
Class CounterPoissonDrive¶
Deterministic per-cell Poisson counts from a counter-addressed stream.
rate_hz * dt_ms / 1000 is the Poisson mean for one cell and timestep.
The inverse CDF is built once through a residual tail below 1e-15.
Counts are returned as signed 64-bit integers for portable FFI transport.
- post_init()
- mean_events()
- Return the expected event count per cell and timestep.
- sample(step_index)
- Return all cell counts and their canonical little-endian digest.
Module network.sc_compte_wm_network¶
Class SCCompteWMNetworkState¶
Complete mutable state of the 2,560-cell network.
- copy()
- Return a deep state copy suitable for checkpointing.
- sha256()
- Return a canonical digest of every state scalar and array.
Class SCCompteWMStimulus¶
One bounded excitatory-population current epoch in source pA units.
- post_init()
Class SCCompteWMStepReceipt¶
Events and provenance emitted by one atomic network step.
Class SCCompteWMWindowReceipt¶
Population statistics for one explicit run window.
Class SCCompteWMRunReceipt¶
Bounded aggregate evidence from one network execution.
Class SCCompteWMNetwork¶
Execute the frozen SC 2,560-cell network with deterministic receipts.
- init(spec)
- state()
- Return a deep copy of the complete current state.
- reset()
- Reset dynamic state while preserving the specification and streams.
- step(direct_exc_current_pa)
- Advance one atomic midpoint-RK2 step and return complete event receipts.
- run(duration_ms)
- Execute an integral number of steps and return bounded run evidence.
Module network.stimulus¶
Class TimedArray¶
Time-varying current from a pre-computed array.
- init(values, dt)
- get_current(t_step)
- Return the value at timestep t_step (clamps to last value).
Class PoissonInput¶
Random Poisson spike input producing weighted current.
- init(n, rate_hz, weight, dt, seed)
- get_current(t_step, dt)
- Generate Poisson spikes and return weighted current vector.
Class StepCurrent¶
Rectangular step current between onset and offset timesteps.
- init(onset, offset, amplitude)
- get_current(t_step, dt)
- Return amplitude if within [onset, offset), else 0.
Module network.topology¶
Function random_connectivity(n_src, n_tgt, p, weight, seed)¶
Erdos-Renyi random connectivity.
Function small_world(n, k, p_rewire, weight, seed)¶
Watts-Strogatz small-world graph (n-by-n adjacency).
Function scale_free(n, m, weight, seed)¶
Generate a Barabasi-Albert preferential-attachment graph.
Parameters¶
n : int
Number of source and target nodes. Must be at least two.
m : int
Number of existing nodes sampled for each new node. Must satisfy
1 <= m < n.
weight : float
Finite synaptic weight assigned to every emitted edge.
seed : int, default=42
Seed for deterministic preferential-attachment sampling.
Returns¶
tuple of ndarray
CSR (indptr, indices, data) arrays for the symmetric adjacency.
Raises¶
ValueError
If n, m, or weight falls outside the Barabasi-Albert domain.
Function ring_topology(n, k, weight)¶
Ring topology with k nearest neighbours in each direction.
Function grid_topology(rows_count, cols_count, radius, weight)¶
2D lattice connectivity within Manhattan radius.
Function all_to_all(n_src, n_tgt, weight)¶
Full connectivity (every source to every target).
Module neuro_symbolic.agent¶
Class PredictiveAgentConfig¶
Configuration for a hybrid symbolic-spiking predictive agent.
- post_init()
Class SCErrorSignature¶
SC-domain prediction-error signature.
xor_bits is the stochastic-computing error carrier. popcount
is the integer error magnitude used by hardware-friendly decision
logic.
- to_dict()
- Return a JSON-compatible representation.
Class HybridInferenceResult¶
Result of one high-level neuro-symbolic predictive pass.
- to_dict()
- Return a compact JSON-compatible summary.
Class NeuroSymbolicPredictiveAgent¶
Hybrid predictive-coding agent for symbolic-spiking workflows.
- init(config)
- num_symbols()
- Number of registered symbolic labels.
- register_symbols(symbols)
- Register additional symbolic labels.
- observe(observation)
- Run one predictive-symbolic observation pass.
Function build_sc_error_signature(observation, prediction)¶
Build an XOR/popcount error signature from observation and prediction.
Module neuro_symbolic.predictive_coding¶
Class BindOp¶
Supported HDC binding operations.
Class ReasoningStep¶
Single step in a symbolic reasoning trace.
Class ReasoningTrace¶
Captures a symbolic reasoning chain for audit and formal verification.
Each step records the symbol query, the operation applied, the similarity score to the best match, and a confidence metric derived from the Hamming margin between the best and second-best candidates.
- add(symbol, operation, similarity, confidence)
- Append a timestamped reasoning step to the trace.
- length()
- Return the number of recorded reasoning steps.
- mean_confidence()
- Return the mean confidence across all reasoning steps.
- is_complete()
- Return whether the trace has been finalised with at least one step.
- finalize()
- Stamp the trace end time to mark reasoning as complete.
- to_dict()
- Serialise the trace and its steps into a plain dictionary.
Class Hypervector¶
Packed binary hypervector (pure-Python mirror of the Rust Hypervector).
Uses np.uint64 packed bitstream layout compatible with the
neuro_symbolic crate's Vec<u64> representation.
- init(data, length)
- zeros(cls, dim)
- Construct an all-zero hypervector of the given dimensionality.
- random(cls, seed, dim)
- Construct a seeded pseudo-random binary hypervector.
- bind(other)
- XOR binding (self-inverse, dimension-preserving).
- permute(shift)
- Cyclic right rotation by shift bits.
- hamming_distance(other)
- Normalised Hamming distance (0.0 = identical, 1.0 = opposite).
- similarity(other)
- Cosine-like similarity: 1 − 2·hamming.
- popcount()
- Return the number of set bits across the packed words.
- density()
- Return the fraction of bits that are set (0.0–1.0).
- threshold_bundle(vectors)
- Majority-vote bundle across N vectors.
Class SymbolEncoder¶
Deterministic symbol → hypervector mapping (mirrors Rust SymbolEncoder).
- init(base_seed)
- encode(symbol)
- Return the cached or freshly generated hypervector for a symbol.
- encode_sequence(symbols)
- Bind a symbol sequence into one position-aware hypervector.
- vocabulary_size()
- Return the number of distinct symbols encoded so far.
Class PredictiveCodingLayer¶
Single layer in a hierarchical predictive coding network.
Maintains a generative model: top-down predictions are compared against bottom-up observations to produce prediction errors that drive weight updates and symbolic trace emission.
- init(input_dim, hidden_dim, lr, precision, seed)
- predict(hidden)
- Generate a top-down prediction from the hidden state.
- compute_error(observation, hidden)
- Bottom-up prediction error: weighted residual.
- update(observation, hidden)
- One-step gradient update on both weights and hidden state.
- mean_recent_error()
- Return the mean absolute error over the last 50 updates.
- converged()
- Return whether recent errors are stable below the threshold.
Class VerifiableInference¶
Wraps prediction + HDC symbol matching with an auditable trace.
- init(encoder, layer, symbol_library)
- register_symbol(name)
- Register a symbol into the lookup library.
- register_symbols(names)
- Register several symbols into the lookup library.
- num_symbols()
- Return the number of symbols in the lookup library.
- infer(observation, top_k)
- Run inference: prediction → error → HDC symbol match.
Module neuro_symbolic.self_verification¶
Class VerificationStatus¶
Status of one self-verification obligation.
Class VerificationObligation¶
One checked condition in a self-verification trace.
- to_dict()
- Return a JSON-ready obligation.
Class NeuroSymbolicSelfVerificationTrace¶
Machine-checkable summary of a neuro-symbolic inference result.
- passed()
- Whether every obligation passed.
- failed_obligations()
- Names of failed obligations.
- to_dict()
- Return a JSON-ready trace.
Class NeuroSymbolicSelfVerifier¶
Build checked self-verification traces for inference outputs.
- verify_result(result)
- Verify a high-level hybrid inference result against its observation.
- verify_trace_only(trace)
- Verify a trace when only symbolic evidence is available.
Function build_self_verification_trace(result)¶
Verify a high-level neuro-symbolic inference result against its observation.
Module neurons._stochastic_threshold¶
Class Lfsr16Threshold¶
Stateful advance-before-compare Bernoulli sampler with replayable reset.
- init(seed)
- initial_seed()
- Return the normalised seed restored by :meth:
reset. - state()
- Return the last emitted LFSR sample/state.
- trial(probability)
- Take one eight-advance sample and perform one quantised trial.
- restore(state)
- Restore a validated live state returned by a native backend.
- reset()
- Restore the exact explicit or entropy-derived initial seed.
Function normalise_lfsr16_seed(seed)¶
Return a valid non-zero 16-bit seed.
None requests independent entropy for ordinary Python model instances.
Explicit zero uses the documented hardware fallback seed so that a C ABI or
RTL parameter can never lock the maximal-length recurrence in the all-zero
state.
Function lfsr16_advance(state)¶
Advance the canonical right-shift x^16+x^14+x^13+x^11+1 LFSR.
Function lfsr16_trial_sample(state)¶
Return the decimated sample used by one Bernoulli trial.
Eight primitive advances suppress the strong adjacent-state correlation of a raw shift-register word. Eight is coprime with the 65,535-state period, so decimation retains the complete non-zero state cycle and exact rate quantisation rather than shortening the generator period.
Function probability_to_lfsr16_threshold(probability)¶
Map p to an unbiased comparator threshold over 65,535 states.
A trial advances the LFSR first and compares its non-zero sample with the
returned 17-bit threshold. For 0 < p < 1 the realised probability is
floor(p * 65535) / 65535; the absolute quantisation error is therefore
strictly below one LFSR period quantum. Zero never fires and one always
fires, while both still consume one RNG sample.
Module neurons._units¶
Function require_pint()¶
Function is_quantity(value)¶
Function require_quantity(value, label)¶
Function quantity_to_base(value)¶
Function build_quantity_namespace()¶
Function validate_quantity_expression(expr, env)¶
Module neurons.base¶
Class BaseNeuron¶
Abstract base class for stochastic neuron models.
All neurons should expose: - step(input_current) -> spike (0 or 1) - reset_state() - get_state() -> dict
- step(input_current)
- Advance the neuron by one time step and return a spike (0 or 1).
- reset_state()
- Reset the internal state to default / initial values.
- get_state()
- Return a dict with the internal state (e.g., membrane potential).
Module neurons.behavior_taxonomy¶
Function behavior_tag_definition(tag)¶
Return the observable definition of a behaviour tag.
Raises¶
ValueError
If tag is not in the controlled vocabulary.
Function validate_behavior_tags(tags)¶
Validate a behaviour-tag collection and return a sorted, unique tuple.
A model is either excitable or quiescent but never both, and a
quiescent model cannot also carry a firing-pattern tag — these
contradictions signal a corrupted or hand-edited tag set and are rejected.
Parameters¶
tags:
An iterable of tag strings (for example the behavior_tags field of a
descriptor or the output of the probe).
Returns¶
tuple[str, ...] The tags, de-duplicated and sorted, ready to store or compare.
Raises¶
ValueError
If tags is not an iterable of strings, names a tag outside the
vocabulary, or carries a contradictory combination.
Module neurons.dendritic¶
Class StochasticDendriticNeuron¶
XOR-nonlinearity neuron with shunting inhibition.
Implements d1 + d2 - 2*d1*d2 (XOR truth table for binary inputs).
Based on Koch, Biophysics of Computation, 1999, Ch. 12.
- step(input_a, input_b)
- reset_state()
- Reset internal state to defaults.
- get_state()
- Return dict with internal state.
Module neurons.descriptor_generator¶
Function generate_descriptor_payload(class_name)¶
Return a curatable v2 descriptor payload for a registered model.
Parameters¶
class_name: Registered model class name (a key of the model registry).
Returns¶
dict[str, Any] A descriptor payload using the v2 section layout, with introspected and carried-over values filled and curation-only fields left empty.
Raises¶
ValueError
If class_name is not a public Python identifier.
KeyError
If class_name is not registered.
Function generate_descriptor(class_name)¶
Return a validated :class:ModelDescriptor skeleton for a model.
Parameters¶
class_name: Registered public model class name to introspect.
Returns¶
ModelDescriptor Parsed descriptor generated from the model code and any curated v1 schema fields.
Raises¶
ValueError
If class_name is not a public Python identifier.
KeyError
If class_name is not registered.
Function merge_descriptor_payloads(curated, regenerated)¶
Merge a curated descriptor onto a freshly regenerated one.
Structural fields (which parameters and state variables exist, their
defaults and initial values, the timestep) always follow the regenerated
payload, which is read from the model code — so the corpus can never drift
from the implementation. Curation fields (parameter units/ranges/meaning,
state semantics, taxonomy, the backend matrix, reproducibility, notes,
validation evidence, silicon evidence anchors, the curated display name and
documentation slug, and any richer provenance, dynamics, or display fields)
are preserved from the curated payload. The curated metadata.name and
documentation.slug are authoritative overlays: a hand-written descriptive
name (e.g. "Ermentrout-Kopell Theta Euler Map") is never overwritten by the
generic generator default. A curated state entry whose name the regeneration
classified as a parameter is dropped rather than preserved, so a variable
reclassified in the code cannot end up declared in both tables. The result is
the regenerated payload with curation overlaid, ready to be re-serialised.
Parameters¶
curated:
The existing on-disk descriptor payload (may carry curation).
regenerated:
A freshly generated payload from :func:generate_descriptor_payload.
Returns¶
dict[str, Any] The merged descriptor payload.
Module neurons.descriptor_tiers¶
Class CompletenessTiers¶
A model's readiness on both catalogue-to-silicon axes.
Parameters¶
science:
Science-axis tier in 0-5 (S0-S5).
silicon:
Silicon-axis tier in 0-5 (H0-H5), or None when the model has
no committed silicon evidence yet.
- science_label()
- The science tier as an
S<n>label. - silicon_label()
- The silicon tier as an
H<n>label, or"none"when unattempted.
Function science_tier(descriptor)¶
Return the science-axis tier (0-5) the descriptor reaches.
S0-S3 are the curation kernel from
:func:~sc_neurocore.neurons.model_descriptor.descriptor_completeness_tier.
A descriptor only climbs above S3 when its evidence facets carry the proof:
- S4 — faithful dynamics: declared dynamics plus a confirmed three-way
agreement with the publication (
validation.dynamics_faithful). - S5 — class-validated: a non-trivial metric and committed evidence
(
validation.is_class_validated).
Parameters¶
descriptor: The model descriptor to score.
Returns¶
int
The science tier in 0-5.
Function silicon_tier(descriptor)¶
Return the silicon-axis tier (0-5) the descriptor reaches, or None.
None means the model has no compile-clean RTL yet (no silicon evidence).
Otherwise the ladder climbs one rung at a time, each rung credited only when
both its boolean flag and its proof anchor are present:
- H0 —
silicon.compiles(iverilog-valid RTL). - H1 — co-simulation evidence recorded (
cosim_validated+cosim_evidence); which boundary it compares (float model, bit-true kernel or RTL) is stated by that evidence, not by the rung. - H2 — synthesisable (
synthesised+synth_report). - H3 — timing-closed and resource-characterised (
timing_closed+timing_report+clock_mhz). - H4 — formally equivalent (
formally_equivalent+equivalence_proof). - H5 — tool-level signed PPA (
ppa_signed+ppa_report).
Parameters¶
descriptor: The model descriptor to score.
Returns¶
int | None
The silicon tier in 0-5, or None when no RTL compiles.
Function completeness_tiers(descriptor)¶
Return both axis tiers for a descriptor.
Parameters¶
descriptor: The model descriptor to score.
Returns¶
CompletenessTiers
The science (0-5) and silicon (0-5 or None) tiers together.
Function is_perfect(descriptor)¶
Return whether a model is perfect by the master-plan acceptance contract.
A model is perfect when it reaches S5 on the science axis and meets the
terminal silicon tier its deployability class declares
(silicon.target_tier). A model whose terminal tier is undeclared cannot
be certified perfect: without the deployability class the required silicon
tier is unknown, so this returns False rather than guessing.
Parameters¶
descriptor: The model descriptor to judge.
Returns¶
bool
True only when S5 is reached and the declared terminal H-tier is met.
Module neurons.dsl_cli¶
Function cmd_list(args)¶
List all bundled schemas.
Function cmd_validate(args)¶
Validate schemas.
Function cmd_info(args)¶
Show model information.
Function cmd_compile(args)¶
Compile model to Verilog with optional hardware target profile.
Function cmd_simulate(args)¶
Simulate model for N steps.
Function cmd_precision(args)¶
Show precision diagnostics for a model at every supported format.
Analyses all 9 precision modes, checking parameter range, dt encoding, and providing a recommended mode.
Function cmd_platforms(args)¶
List all available hardware target profiles.
Function main()¶
Parse CLI arguments and dispatch to the requested subcommand.
Module neurons.equation_builder¶
Class EquationNeuron¶
Neuron defined by arbitrary ODE equations as strings.
Each equation is a right-hand-side expression for dX/dt.
Variables can reference other state variables, parameters,
and the special variable I (input current).
units="strict" enables opt-in pint-based dimensional
validation before the expressions are compiled for runtime.
- init(equations, parameters, state, threshold, reset, constants, dt, method, units, input_unit, detection, substeps, rate_expression, probability_expression, rng_seed, noise_rng)
- Initialise an equation-defined neuron from ODE strings.
- initial_threshold_active()
- Return whether the threshold condition holds on the INITIAL committed state.
- uses_diffusion_noise()
- Whether any authored expression references the diffusion-noise symbol
xi. - step(I)
- Advance the neuron by one macro timestep; return 1 if it spikes.
- get_state()
- Return current state, with units if in strict mode.
- escape_rng_initial_seed()
- Return the emitted stochastic-threshold seed (legacy API name).
- escape_rng_state()
- Return the live stochastic-threshold state (legacy API name).
- stochastic_rng_initial_seed()
- Return the emitted stochastic-threshold seed, or
Nonewhen unused. - stochastic_rng_state()
- Return the live stochastic-threshold LFSR state, or
Nonewhen unused. - reset()
- Reset state to initial values.
- repr()
- Human-readable representation of the neuron equations.
Function from_equations()¶
Build an EquationNeuron from Brian2-style equation strings.
noise_rng seeds the diffusion-noise symbol xi; without it the
process-global numpy.random stream is used.
Examples¶
Build a leaky integrate-and-fire neuron::
lif = from_equations(
"dv/dt = -(v - E_L)/tau_m + I/C",
threshold="v > -50",
reset="v = -65",
params=dict(E_L=-65, tau_m=10, C=1),
init=dict(v=-65),
)
Use units="strict" with pint quantities to validate the
equation dimensions before runtime compilation.
Module neurons.equation_namespace¶
Function build_eval_namespace()¶
Return the maths namespace exposed to compiled equation expressions.
The returned dict is fresh on every call so a neuron may own its namespace without aliasing another's. The bindings are the exact functions the fixed-point emitter mirrors; keep them identical to preserve co-simulation bit-exactness (see the module docstring).
Module neurons.equation_safety¶
Class ExpressionSafetyValidator¶
Validate equation expression strings against the AST allowlist.
Holds the allowed node set, the blocked-name set, and the maximum AST depth,
and exposes :meth:validate, which raises :class:ValueError on any
disallowed construct. The same validator instance is reused for a neuron's
dynamics, threshold, reset rules, and (for exponential Euler) its symbolic
Jacobian, so every expression that reaches an eval site has passed the
same gate.
- init()
- Create a validator with the given maximum AST depth.
- validate(expr)
- Validate an expression against the AST whitelist.
Module neurons.equation_units_runtime¶
Class StrictRuntime¶
Base-unit runtime values and unit maps produced by strict validation.
parameters/state/constants/dt are the base-unit floats the
integrator steps; runtime_units maps each name (and the input I) to
its base unit for converting runtime inputs; base_state_units and
display_state_units let :meth:EquationNeuron.get_state re-attach the
caller's display units to each state variable.
Function prepare_strict_runtime()¶
Convert pint quantities to base-unit floats for runtime.
Function convert_runtime_value()¶
Convert a runtime value from pint quantity to float.
Module neurons.evidence_references¶
Class EvidenceReference¶
One parsed and resolved evidence reference.
Parameters¶
raw:
The reference text exactly as written in the descriptor.
kind:
Reference kind; see the module docstring.
path:
Repository-relative path the reference names (empty for prose and
inline configurations).
node:
Class::test node path for test-node references, else empty.
resolution:
resolved when the named file (and node) exists; missing-file or
missing-node when it does not; unresolvable for prose and inline
configurations, which name nothing on disk.
- is_locatable()
- True when the reference names a file that could be checked on disk.
- is_resolved()
- True when the named file (and node) exists.
- to_public_dict()
- Return a JSON-compatible projection.
Function split_evidence_field(value)¶
Split a descriptor evidence field into its reference tokens.
Tokens are separated by semicolons; surrounding whitespace is dropped and empty tokens are ignored.
Parameters¶
value: Raw evidence field text.
Returns¶
tuple[str, ...] Non-empty reference tokens in field order.
Function classify_reference(token)¶
Classify one reference token without touching the filesystem.
Parameters¶
token:
One stripped token from :func:split_evidence_field.
Returns¶
tuple[ReferenceKind, str, str]
(kind, path, node).
Function resolve_reference(token, repo_root)¶
Classify one token and resolve it against repo_root.
Parameters¶
token:
One stripped token from :func:split_evidence_field.
repo_root:
Repository root the paths are relative to.
Returns¶
EvidenceReference The typed and resolved reference.
Function parse_evidence_field(value, repo_root)¶
Parse and resolve every reference in one descriptor evidence field.
Parameters¶
value: Raw evidence field text. repo_root: Repository root the paths are relative to.
Returns¶
tuple[EvidenceReference, ...] References in field order; empty for an empty field.
Function node_is_defined(test_file, node)¶
Return whether node (Class::test[param]) is defined in test_file.
Parameters¶
test_file:
Absolute path of the test module.
node:
Node path after the :: that follows the file name; a trailing
parametrisation suffix in square brackets is ignored.
Returns¶
bool
True when a class or function with that path is defined.
Function sha256_file(path)¶
Return the SHA-256 hex digest of one file's bytes.
Function sha256_tree(paths, relative_to)¶
Return one digest over several files, independent of iteration order.
Parameters¶
paths:
Files to include; each is hashed and listed with its path relative to
relative_to.
relative_to:
Root the listed paths are made relative to.
Returns¶
str SHA-256 hex digest of the sorted lines, each holding one relative path, a NUL separator and that file's digest.
Function sha256_canonical_json(payload)¶
Return the SHA-256 hex digest of a canonical JSON rendering.
Module neurons.expression_derivative¶
Class exprel¶
SymPy image of the DSL exprel(x) = (exp(x) - 1) / x (exprel(0) = 1).
- fdiff(argindex)
- Return d/dx (exp(x) - 1)/x = (exp(x)·(x - 1) + 1) / x².
Class sigmoid¶
SymPy image of the DSL logistic sigmoid(x) = 1/(1 + exp(-x)).
- fdiff(argindex)
- Return sigmoid(x)·(1 - sigmoid(x)).
Class ExpressionDifferentiationError¶
Raised when an expression cannot be faithfully differentiated in-grammar.
Function differentiate(expr, wrt)¶
Return ∂expr/∂wrt as an equation string in the DSL grammar.
Parameters¶
expr:
The right-hand-side of d(wrt)/dt — an equation string already valid
under the neuron-DSL grammar.
wrt:
The state-variable name to differentiate with respect to.
Returns¶
str
The partial derivative as a new equation string using only DSL-grammar
tokens. "0" when the expression does not depend on wrt.
Raises¶
ExpressionDifferentiationError
If the expression depends on wrt through a construct whose derivative
is not expressible in the smooth grammar (abs/clip/min/
max, a comparison, a conditional, %, //, or an unknown
function).
Module neurons.facet_receipts¶
Class FacetReceiptError¶
Raised when a receipt payload violates the receipt contract.
Class FacetSpec¶
Definition of one readiness facet.
Parameters¶
name:
Facet identifier (backend:rust, cosim, …).
axis:
science (S4/S5), software (per-backend completion) or
silicon (H0–H5 and the physical rung beyond them).
rung:
Tier rung the facet credits on its axis, or None when it credits no
tier (per-backend completion, bounded safety, physical measurement).
required_subjects:
Subject kinds a creditable receipt must carry.
optional_subjects:
Subject kinds a receipt may carry; they are checked for freshness when
present.
evidence_field:
Descriptor field holding the declared evidence, "" when the
descriptor has no field for the facet.
claim_scope:
Claim scope a receipt must state, "" when unconstrained.
- subjects()
- Every subject kind whose change invalidates the facet.
Class Subject¶
One content-addressed input of a facet receipt.
Parameters¶
kind:
Subject kind from :data:SUBJECT_KINDS.
path:
Repository-relative path (a file, or a directory for tree scope).
sha256:
Digest of the subject at recording time.
scope:
file (whole file), contract-sections (the descriptor sections
that fix the model contract, so documentation edits do not invalidate
evidence) or tree (every .py file under a directory).
- to_payload()
- Return the JSON projection.
Class FacetReceipt¶
One immutable record of an executed evidence command.
Every field is a recorded fact of the run; none is derived by the verifier.
- to_payload()
- Return the JSON payload, with the seal digest when
sealed. - sealed()
- Return a copy whose
receipt_sha256seals the current content. - subject_kinds()
- Return the subject kinds the receipt carries.
Function facets_invalidated_by(kind)¶
Return the facets whose receipts a change of kind invalidates.
Function seal_digest(unsealed_payload)¶
Return the seal digest of a receipt payload without receipt_sha256.
Function parse_receipt(payload)¶
Validate a receipt payload and return a :class:FacetReceipt.
Structural validation only: the seal, the outcome and the subject
freshness are judged by :func:credit_problems and the verifier.
Raises¶
FacetReceiptError If a required field is missing or malformed.
Function load_receipt(path)¶
Load and structurally validate one receipt file.
Function credit_problems(receipt)¶
Return why a receipt cannot credit its facet; empty when it can.
Freshness of the subjects is not judged here (it needs the repository);
see :func:sc_neurocore.neurons.readiness.verify_receipt.
Parameters¶
receipt: The receipt to judge. class_name: When given, the class the receipt is being read for; a receipt for a different class is a wrong-subject receipt.
Function receipt_filename(class_name, facet, recorded_at)¶
Return the canonical receipt file name for one run.
Function iter_receipts(directory)¶
Yield every receipt file in directory in file-name order.
Raises¶
FacetReceiptError If any receipt file is malformed; a broken receipt is an error, not a silently ignored file.
Function latest_receipts(directory)¶
Return the newest receipt per (class_name, facet, profile).
Newest is decided by recorded_at and then by file name, so an
append-only successor always supersedes its predecessor.
Function descriptor_contract_digest(payload)¶
Return the digest of the descriptor sections that fix the model contract.
Identity, state, parameters, integration, dynamics and scientific acceptance criteria take part. A documentation or evidence-pointer edit alone does not change this digest; evidence selection is independently checked on use.
Function descriptor_contract_digest_of(path)¶
Return :func:descriptor_contract_digest of a descriptor TOML file.
Module neurons.fixed_point_lif¶
Class FixedPointLIFNeuron¶
Bit-true fixed-point model of the Verilog sc_lif_neuron.
All arithmetic is performed in signed Q(FRACTION) fixed-point with explicit bit-width masking so that overflow/wrap behaviour matches the hardware exactly.
Parameters¶
data_width : int Total bit width of all fixed-point values (default 16). fraction : int Number of fractional bits (default 8, giving Q8.8). v_rest, v_reset, v_threshold : int Membrane parameters in Q(FRACTION) fixed-point. refractory_period : int Number of clock cycles to hold after a spike.
Example¶
neuron = FixedPointLIFNeuron() spike, v = neuron.step(leak_k=240, gain_k=16, I_t=100) spike in (0, 1) True neuron.reset()
- post_init()
- step(leak_k, gain_k, I_t, noise_in)
- Execute one clock cycle — bit-true match to Verilog RTL.
- reset()
- Reset neuron state to power-on defaults.
- reset_state()
- Reset internal state (alias for :meth:
reset). - get_state()
- Return dict with internal state.
Class FixedPointLFSR¶
Bit-true model of the 16-bit LFSR in sc_bitstream_encoder.v.
Polynomial: x^16 + x^14 + x^13 + x^11 + 1 Taps (0-indexed): 15, 13, 12, 10
Example¶
lfsr = FixedPointLFSR(seed=0xACE1) vals = [lfsr.step() for _ in range(10)] len(set(vals)) > 1 # produces varying pseudo-random values True
- post_init()
- step()
- Advance one clock cycle; return new register state.
- reset(seed)
Class FixedPointBitstreamEncoder¶
Bit-true model of sc_bitstream_encoder.v.
Combines LFSR + comparator to produce a stochastic bitstream where P(bit=1) ~ x_value / (2^DATA_WIDTH - 1).
Example¶
enc = FixedPointBitstreamEncoder(seed_init=0xACE1) bits = [enc.step(x_value=128) for _ in range(100)] all(b in (0, 1) for b in bits) True
- post_init()
- step(x_value)
- Return 1 if LFSR < x_value, else 0 (one clock cycle).
- reset()
Module neurons.homeostatic_lif¶
Class HomeostaticLIFNeuron¶
LIF neuron with homeostatic threshold adaptation.
Self-regulates firing rate toward a target setpoint via exponential moving average of spike rate. Based on Turrigiano (2012).
Example¶
neuron = HomeostaticLIFNeuron(target_rate=0.1, noise_std=0.0) for _ in range(200): ... neuron.step(1.5) neuron.v_threshold != 1.0 # threshold adapted True
- post_init()
- step(input_current)
- get_state()
Module neurons.model_catalogue¶
Class CatalogueCoverage¶
Aggregate descriptor coverage across the registered model catalogue.
Parameters¶
total_models:
Number of registered models.
described:
Number of models with a committed descriptor.
tier_counts:
Count of described models at each science-kernel tier (keys 0-3);
the legacy curation view, retained for backward compatibility.
science_tier_counts:
Count of described models at each full science-axis tier (keys 0-5,
S0-S5).
silicon_tier_counts:
Count of described models at each silicon-axis tier, keyed by label
("none" for no compile-clean RTL, then "H0"-"H5").
citeable:
Number of described models with citeable provenance.
fully_curated_parameters:
Number of described models whose every parameter has unit, range, and
meaning.
- to_public_dict()
- Return a JSON-compatible coverage summary.
Function descriptor_path(class_name)¶
Return the committed descriptor path for a model class.
Parameters¶
class_name: Public Python class identifier for the model descriptor.
Returns¶
pathlib.Path
Absolute path under neurons/model_descriptors.
Raises¶
ValueError
If class_name is empty, private, dotted, path-like or unregistered.
Function load_descriptor_payload(class_name)¶
Return the raw committed descriptor payload.
Parameters¶
class_name: Public Python class identifier for the model descriptor.
Returns¶
dict[str, Any] | None
Parsed TOML payload when the descriptor is committed, otherwise
None.
Raises¶
ValueError
If class_name is empty, private, dotted, or path-like.
Function load_descriptor(class_name)¶
Return the validated committed descriptor for a model.
Parameters¶
class_name: Public Python class identifier for the model descriptor.
Returns¶
ModelDescriptor | None
Validated descriptor when the TOML file exists, otherwise None.
Raises¶
ValueError
If class_name is empty, private, dotted, or path-like.
Function catalogue_descriptor_coverage()¶
Return descriptor coverage over every registered model.
Returns¶
CatalogueCoverage Aggregate coverage over the current model registry and committed descriptor corpus.
Module neurons.model_descriptor¶
Class ParameterSpec¶
A single model parameter with its physical semantics.
Parameters¶
name:
Parameter identifier matching the model's constructor field.
default:
Default numeric value.
unit:
Physical unit (for example mV, ms, pA); empty when uncurated.
value_range:
Optional (min, max) admissible range.
biological_range:
Optional (min, max) biologically plausible range.
meaning:
Human-readable description; empty when uncurated.
- is_curated()
- True when the parameter has a unit, a range, and a meaning.
Class StateVariableSpec¶
A model state variable with its initial value and semantics.
init is None for a variable whose initial value is not a single
number — a compartment vector, a population activity profile, a filter
buffer. Such a variable is state like any other and must be declared; what
it does not have is a scalar to declare as its start. Writing 0.0 there
would state something about the model that is not true, so the declaration
omits the value instead of inventing one.
Class Provenance¶
Citation and licensing provenance for a model.
- is_citeable()
- True when authors, a year, and a valid DOI are all present.
Class BackendSupport¶
Implementation status and numeric parity for one compute backend.
Class Reproducibility¶
Reference-run reproducibility anchors for a model.
golden_trace_sha256_variants is a finite allowlist for measured
byte-level variants of the same numerically bounded trace, such as NumPy
transcendental kernels selected by different x86 SIMD capabilities. The
primary digest remains mandatory for a reproducible descriptor.
- is_reproducible()
- True when a reference config and a golden trace digest are present.
- golden_trace_digests()
- Return the primary digest followed by measured compatible variants.
Class Validation¶
Class-correct validation evidence for a model's dynamics.
Records the outcome of two checks (§3-§4 of the catalogue-to-silicon master
plan): whether the model's discretised dynamics were confirmed faithful to
the publication (dynamics_faithful — the three-way schema/class/paper
agreement), and by which metric the model was validated for its class, with
committed evidence. Every field is a recorded outcome, never derived, so the
science tier can read them as ground truth.
Parameters¶
dynamics_faithful:
True when the schema-DSL equations, parameters, dt, threshold, and reset
were confirmed to match the publication (and the hand class where one
exists). Gates the faithful-dynamics tier S4.
metric:
The class-appropriate validation metric from :data:VALIDATION_METRICS
("none" until validated).
operating_point:
Human-readable statement of the operating point the validation used
(for example an input drive or a parameter regime).
tolerance:
The honest agreement tolerance achieved (for example "0 spikes" or a
distributional distance), as a citeable string.
evidence:
A path, citation, or digest pointing at the committed validation evidence.
Together with a non-"none" metric this gates the validated tier S5.
- is_class_validated()
- True when a non-trivial metric and committed evidence are both present.
Class Silicon¶
Ladder of committed silicon-realisation evidence for a model.
Each rung of the silicon axis (H0-H5) is only credited when its evidence
anchor is recorded, so a silicon tier can never be claimed ahead of proof
(master plan invariant I7). compiles is the H0 anchor (iverilog-valid
RTL); each higher boolean requires its companion report to count.
Parameters¶
compiles:
RTL lowers to iverilog-valid Verilog (compile-clean). The H0 anchor.
cosim_validated:
Python<->Verilog agreement by the class-correct metric was demonstrated;
credited for H1 only alongside cosim_evidence.
synthesised:
Passes a real synthesis flow (for example Yosys); credited for H2 only
alongside synth_report.
timing_closed:
Meets a stated clock on a target device with reported resources;
credited for H3 only alongside timing_report and clock_mhz.
formally_equivalent:
Machine-checked Python-semantics<->RTL equivalence in CI; credited for H4
only alongside equivalence_proof.
ppa_signed:
Tool-level RTL->GDSII signoff (open PDK) with clean DRC/LVS/STA; credited
for H5 only alongside ppa_report.
cosim_evidence, synth_report, timing_report, equivalence_proof, ppa_report:
Paths, citations, or digests pointing at the committed proof for each rung.
target_device:
The device the timing/resource numbers were characterised on.
clock_mhz:
The clock the design closes at (MHz); required for the H3 credit.
target_tier:
The terminal H-tier this model's deployability class is expected to reach,
from :data:SILICON_TARGET_TIERS ("" until declared).
terminal_reason:
Why the model terminates at target_tier (for example a research
multicompartment model that need not reach signed PPA).
Class ModelDescriptor¶
The full declarative descriptor for one neuron model.
Class ModelDescriptorError¶
Raised when a descriptor payload violates the schema contract.
Function descriptor_completeness_tier(descriptor)¶
Return the science-axis completeness kernel (0-3) a descriptor satisfies.
This is the S0-S3 base of the science axis — the discovery-and-curation
tiers that need no execution evidence. The full science axis (adding the
faithful-dynamics tier S4 and the class-validated tier S5) and the silicon
axis (H0-H5) are derived from this kernel plus the descriptor's evidence
facets by :mod:sc_neurocore.neurons.descriptor_tiers.
Tier 0 — exists and identifies a real model (class, module, params, state). Tier 1 — discovery taxonomy declared (family and category). Behaviour tags are an optional measured facet, not a tier requirement, so a tier never depends on running a simulation. Tier 2 — scientifically curated: citeable provenance (authors + year + DOI) and every parameter curated (unit + range + meaning). Tier 3 — engineering-verified: at least two implemented backends and a reproducibility anchor (reference config + golden trace digest).
Function parse_model_descriptor(payload)¶
Validate a descriptor payload and return a :class:ModelDescriptor.
Parameters¶
payload:
A loaded descriptor mapping (from TOML/JSON), using the v2 section
layout: metadata, provenance, state, parameters,
integration, dynamics, backends, reproducibility,
documentation.
Returns¶
ModelDescriptor The validated descriptor.
Raises¶
ModelDescriptorError If any required identifier is missing or a controlled-vocabulary field carries an unknown value.
Module neurons.model_identity¶
Class ModelIdentityError¶
Raised when a catalogue identity cannot be resolved unambiguously.
Class SchemaProfile¶
One schema-DSL profile bound to a model identity.
Parameters¶
stem:
Schema file stem under neurons/model_schemas.
basis:
"alias-table" when :mod:schema_module_aliases names the class,
"module-stem" when the stem resolves through the model module.
Class SourceLocator¶
Where a model's defining source lives.
Parameters¶
basis:
Which locator establishes the identity.
doi, url, paper_title, authors, year:
Provenance fields copied from the descriptor.
doi_is_translation:
True when the DOI points at a translation of the primary source.
Class ModelIdentity¶
Canonical identity record of one catalogue class.
Parameters¶
class_name:
Public Python class name.
module:
Module stem under neurons/models (or the alias re-export module).
kind:
Identity kind; see the module docstring.
counts_in_source_catalogue:
True only for source-literature and project-original.
family, category:
Curated taxonomy family and category slug (empty for aliases).
canonical_class:
The identity an alias resolves to; the class itself otherwise.
aliases:
Historical import names resolving to this identity.
schema_profiles:
Schema-DSL profiles bound to this identity.
source:
Source locator.
public_status:
Row status on the public fidelity page.
public_label:
Row label on the public fidelity page, empty when unlisted.
revalidation:
For strict-promoted identities: whether the promotion is bound to an
independent source receipt that this package ships and that names the
model; a descriptor path to an absent receipt binds nothing.
missing_gates:
Evidence gates the descriptor does not yet claim.
- to_public_dict()
- Return a JSON-compatible projection of the record.
Class NetworkIdentity¶
A network-level identity that is distinct from any cell component.
Parameters¶
class_name:
Public network class name.
module:
Dotted module path of the class.
kind:
Identity kind (sc-compatibility for retained project networks).
cell_identity:
The neuron identity the network is built from.
Class CatalogueCounts¶
Every catalogue number derived from the identity registry.
Parameters¶
registered: Registered model classes (aliases excluded). source_catalogue: Identities that count in the public source catalogue. source_literature, project_original, sc_compatibility, api_aliases: Identity kind totals. network_identities: Registered network-level identities. polyglot_complete_source, polyglot_complete_sc: Strict-promoted rows on the public page, split by count membership. runtime_validated, compatibility_runtime: Rows in the two non-promoted public tables. remaining_source: Source-catalogue identities not strict-promoted. receipt_bound_complete, not_revalidated_complete: Strict-promoted source identities with and without an independent source receipt. schema_profiles: Schema-DSL stems bound to an identity.
- to_public_dict()
- Return the counts as a plain mapping.
Function identity_registry()¶
Return the canonical identity record for every registered class and alias.
Returns¶
dict[str, ModelIdentity] Class name (including aliases) to identity record, sorted by name.
Raises¶
ModelIdentityError If any join is ambiguous or names an unknown class.
Function resolve_identity(class_name)¶
Return the canonical identity for a class or alias name.
Parameters¶
class_name: Registered class name or historical alias.
Returns¶
ModelIdentity The record of the canonical identity the name resolves to.
Raises¶
ModelIdentityError If the name is neither registered nor an alias.
Function iter_source_catalogue()¶
Yield identities that count in the public source catalogue.
Function schema_for_class(class_name)¶
Return the schema-DSL profile Studio and the generators use for a class.
Two registered classes may share one module (a source identity and its
retained SC compatibility identity), so a module-based lookup would hand
the compatibility class the source profile. The class's own bound profiles
decide: the module's canonical schema when the class owns it, otherwise the
class's first bound profile; a class without a bound profile falls back to
the module lookup so unbound models keep their historical behaviour.
Parameters¶
class_name: Registered class name or import alias.
Returns¶
str Schema stem.
Function public_fidelity_bindings()¶
Return the public page label and status bound to each listed class.
Returns¶
dict[str, tuple[str, PublicStatus]]
Class name to (row label, status).
Function catalogue_counts()¶
Derive every catalogue number from the identity registry.
Returns¶
CatalogueCounts
Counts computed over :func:identity_registry.
Module neurons.model_profile¶
Class ModelProfileError¶
Raised when a schema's profile contradicts the schema or the contract.
Class ProfileAdmissionError¶
Raised when an override or protocol is not admissible under a profile.
Class StateVariable¶
One state variable and its role in the profile.
Parameters¶
name:
Variable name as declared in [state].
role:
biological (a quantity of the scientific model) or auxiliary (a
deterministic register that exists only to realise the numerical
scheme or the event logic).
init:
Initial value from the schema.
unit:
Declared unit, empty when not declared.
meaning:
Authored meaning for auxiliary registers, empty otherwise.
- to_public_dict()
- Return the JSON projection.
Class Parameter¶
One schema parameter and its role in the profile.
Parameters¶
name:
Parameter name as declared in [parameters].
role:
source (defined by the scientific source), implementation (a
maintained choice such as an observation threshold) or timebase
(bound to integration.dt and read by the expressions).
default:
Default value from the schema.
unit:
Declared unit, empty when not declared.
meaning:
Authored meaning, empty when not declared.
- to_public_dict()
- Return the JSON projection.
Class EventContract¶
How the realisation turns state into events.
Parameters¶
detection:
Threshold detection mode from the schema (level, crossing,
escape_rate, poisson) or the schema's free text for a
descriptive record.
condition:
Threshold condition expression, empty when none.
stochastic_expression:
Escape-rate or Poisson probability expression, empty when none.
reset:
Reset rules per state variable.
edge_detection:
Whether the runtime engages rising-edge logic (crossing with no
reset rule); a resetting model uses the level path under either mode.
refractory_register:
State variable that encodes the refractory hold inside the dynamics,
empty when the model has none.
- to_public_dict()
- Return the JSON projection.
Class RandomnessContract¶
Which random draws a realisation makes and whether they replay.
Parameters¶
kind:
none; lfsr16-threshold (a model-scoped 16-bit LFSR decides
stochastic threshold trials from seed); diffusion-noise-global-rng
(an expression names xi, drawn from NumPy's process-global stream);
or both.
seed:
Initial LFSR seed when the threshold is stochastic, else None.
reproducible:
True only when every draw comes from the model-scoped seeded LFSR.
- to_public_dict()
- Return the JSON projection.
Class ScientificModel¶
The authored scientific content of a schema.
Parameters¶
name:
Model name from the schema metadata.
author, year, doi:
Source locator fields from the metadata (empty or None when absent).
equations:
Authored right-hand sides (or map updates) per state variable.
biological_state:
State variables that belong to the scientific model.
source_parameters:
Parameters the source defines.
published_equations:
science.equations_as_published when authored, else empty.
- to_public_dict()
- Return the JSON projection.
Class NumericalRealisation¶
How the scientific model is advanced in time.
Parameters¶
method:
Integration method (euler, map, rk4, exp_euler,
gauss_seidel) or the schema's free label for a descriptive record.
family:
ode (the equations are derivatives), map (the equations are the
next state) or event-only (no state at all).
exactness:
Exactness class of the update; see :data:METHOD_TABLE.
exactness_claimed:
True when the exactness came from an authored claim that the
resolver admitted, False when it is the derived class.
dt:
Integration step from the schema.
time_unit:
Unit of dt (ms for the conductance and IF corpus; iteration
for a recurrence without a continuous timebase; empty when unstated).
substeps:
Inner steps per public step.
substep_kind:
time-subdivision (each sub-step advances dt; the public step is
substeps * dt), stage-iteration (the sub-steps are stages of one
scheme folded into a map; the public step is one dt) or none.
macro_step:
Duration of one public step() in time_unit; None for a
descriptive record, whose sub-step convention is not the runtime's.
evaluation_order:
Phases of one public step in execution order.
auxiliary_registers:
State variables that exist only to realise the scheme or the events.
implementation_parameters:
Parameters that are maintained implementation choices.
timebase_parameters:
Parameters bound to dt and read by the expressions.
admissible_methods:
Methods a consumer may select for this scientific model without leaving
its family; the declared method is always first.
randomness:
Randomness contract.
event:
Event contract.
- to_public_dict()
- Return the JSON projection.
Class LoweringProfile¶
What the RTL emitter can lower from the realisation.
Parameters¶
rtl_supported:
True when the equation compiler accepts the realisation as declared.
limits:
Reasons the realisation cannot be lowered, or the limits it is lowered
under (pipelining excluded for sub-stepped or stochastic datapaths).
cosim_methods:
Admissible methods Studio co-simulates against the golden.
recommended_precision:
hints.recommended_precision when authored, else empty.
- to_public_dict()
- Return the JSON projection.
Class ModelProfile¶
The resolved profile of one schema document.
Parameters¶
contract:
Contract identifier (:data:PROFILE_CONTRACT).
stem:
Schema stem when resolved from a bundled schema, else empty.
realisation_kind:
executable when UniversalNeuron can run the schema, otherwise
descriptive-record (the schema records a hand model whose method or
detection is outside the executable vocabulary).
authored:
True when the schema carries a [profile] section.
scientific, numerical, lowering:
The three separated layers.
problems:
Contradictions between the authored profile and the schema, or between
schema fields. Non-empty means an executable consumer must refuse.
notes:
Authored free-text note from the profile section.
- is_executable()
- Whether the schema runs through the equation runtime.
- to_public_dict()
- Return the JSON projection with a stable field order.
Class AdmittedOverrides¶
Overrides accepted under a profile, with the timebase propagated.
Parameters¶
dt:
Effective integration step.
method:
Effective method.
parameters:
Effective parameter overrides, including timebase parameters set to
dt when the step was overridden.
rng_seed:
Effective LFSR seed, None when the profile draws no randomness.
derived:
True when the effective realisation differs from the declared one.
- realisation(profile)
- Return the effective numerical realisation as a public record.
Function expression_names(expression)¶
Return the identifiers an expression reads, with _prev aliases folded.
Parameters¶
expression: A DSL expression (Python expression syntax).
Returns¶
frozenset[str]
Identifier names; x_prev is reported as x. An unparsable
expression (a descriptive record's prose) yields the empty set.
Function resolve_profile(schema)¶
Resolve the profile of one schema document.
Parameters¶
schema:
Parsed schema mapping (as returned by
:func:~sc_neurocore.neurons.universal_dsl.load_schema).
stem:
Bundled schema stem, when known.
Returns¶
ModelProfile
The separated scientific model, numerical realisation and lowering
profile, with every contradiction listed in problems.
Function admit_overrides(profile)¶
Admit consumer overrides under a profile or refuse them.
Parameters¶
profile:
Resolved profile of the schema being instantiated.
dt:
Requested integration step, None to keep the schema's.
method:
Requested method, None to keep the schema's.
parameters:
Requested parameter overrides.
rng_seed:
Requested LFSR seed, None to keep the schema's.
Returns¶
AdmittedOverrides The effective step, method, parameter overrides (timebase parameters follow the step) and seed.
Raises¶
ProfileAdmissionError If the schema itself is contradictory, is a descriptive record, or the override leaves the profile's family, contradicts its timebase, changes the step of a recurrence without a timebase, or seeds a deterministic model.
Function parse_profile(payload)¶
Rebuild a :class:ModelProfile from its public projection.
Parameters¶
payload:
A mapping produced by :meth:ModelProfile.to_public_dict.
Returns¶
ModelProfile A profile equal to the one that produced the payload.
Raises¶
ModelProfileError If the payload does not carry the contract or a required field.
Module neurons.model_receipts¶
Function referenced_receipt_name(reference)¶
Return the receipt file a descriptor reference names.
Parameters¶
reference : str
The descriptor's reproducibility.reference_config value.
Returns¶
str or None
The bare *.json file name, or None when the reference names no
receipt or names one outside the receipt directory.
Function load_bound_receipt(class_name, reference)¶
Load the receipt a descriptor reference binds to class_name.
Parameters¶
class_name : str
The catalogue class the descriptor describes.
reference : str
The descriptor's reproducibility.reference_config value.
directory : Path
The receipt directory; the installed package's own by default.
Returns¶
Mapping or None
The receipt, or None when the reference names no receipt, the file
is absent or unreadable, it is not a JSON object, or it is bound to
another model.
Module neurons.model_taxonomy¶
Function canonical_model_name(class_name)¶
Return the catalogue identity for class_name, resolving aliases.
Function model_family(class_name)¶
Return (family, category_slug) for a model, or None if unclassified.
Function families()¶
Return the family display name to category slug mapping.
Function classified_models()¶
Return canonical catalogue model names.
Historical aliases remain accepted by :func:model_family, but they are
not independent catalogue identities and therefore must not inflate the
model inventory.
Module neurons.models.adaptive_threshold_if¶
Class AdaptiveThresholdIFNeuron¶
Composite reduced adaptive-threshold leaky integrate-and-fire neuron.
The membrane equation is the leaky integrate-and-fire relaxation
tau_m * dV/dt = -(V - v_rest) + I,
integrated with the exact constant-input flow over one dt interval.
The threshold equation is
dtheta/dt = -(theta - theta_rest) / tau_theta,
which is the Mihalas and Niebur (2009) threshold equation
dTheta/dt = a(V - E_L) - b(Theta - Theta_inf) taken at zero voltage
coupling (a = 0), integrated with the same exact relaxation. A spike
is emitted when the candidate membrane potential reaches the candidate
threshold; the membrane potential then resets to v_reset and the
threshold increases by the fixed amount delta_theta — the fixed
post-spike threshold shift derived in Platkiewicz and Brette (2010).
Reduction boundary: the Mihalas–Niebur voltage-coupling term a(V - E_L)
and the Platkiewicz–Brette voltage-dependent threshold equilibrium
theta_inf(V) are outside this reduced model, as is any adaptation
current. Defaults are catalogue/model-family choices, not source-derived
parameters.
References¶
Mihalas, S. and Niebur, E. (2009). A generalized linear integrate-and-fire neural model produces diverse spiking behaviors. Neural Computation 21(3), 704–718. https://doi.org/10.1162/neco.2008.12-07-680
Platkiewicz, J. and Brette, R. (2010). A threshold equation for action potential initiation. PLoS Computational Biology 6(7), e1000850. https://doi.org/10.1371/journal.pcbi.1000850
- post_init()
- Normalise scalar fields and reject an invalid configuration.
- step(current)
- Advance one exact-relaxation interval and return a binary spike event.
- simulate(current)
- Run one atomic piecewise-constant-input batch on a maintained backend.
- reset()
- Restore the documented rest state while preserving configuration.
Module neurons.models.adaptive_threshold_moe¶
Class AdaptiveThresholdMoENeuron¶
Adaptive threshold MoE spiking neuron (SpikingBrain).
Parameters¶
k : float Firing rate control (higher k -> lower threshold -> more spikes). Default: 4.0 (SpikingBrain recommended). ema_alpha : float EMA decay for running mean of |input|. Default: 0.1.
- post_init()
- step(current)
- Advance one timestep. Returns integer spike count (>= 0).
- step_collapsed(activation)
- Time-collapsed single-step: s_INT = round(x / V_th).
- sparsity()
- Current activation sparsity (1.0 if below threshold, 0.0 if firing).
- reset()
- Reset state to initial conditions.
Module neurons.models.adex¶
Class AdExNeuron¶
Adaptive Exponential Integrate-and-Fire. Brette & Gerstner 2005.
dv/dt = -(v - v_rest)/tau + delta_T * exp((v - v_rh)/delta_T) / tau - w/C + I/C dw/dt = (a * (v - v_rest) - w) / tau_w if v >= v_threshold: v = v_reset, w += b
Reference: Brette, R. & Gerstner, W. (2005). J. Neurophysiol. 94:3637–3642.
Integrator options:
- baseline_euler preserves the historical explicit-Euler path
- rk4 is an explicit higher-order alternative path
- rosenbrock is a linearly implicit stiff-system path over the same
AdEx ODEs
simulate exposes the baseline-Euler Python, Rust, Julia, Go and Mojo
paths. auto follows the committed measured order Rust, Julia, Go,
Mojo, then Python.
- post_init()
- brette_gerstner_2005(cls)
- Return the regular-spiking fit reported by Brette and Gerstner (2005).
- step(current)
- simulate(n_steps, current, backend)
- Advance
n_stepsupdates from the current state, returning(trace, spikes). - simulate_complete(n_steps, current, backend)
- Return aligned post-step voltage, adaptation, and event traces.
- reset()
Module neurons.models.ai_optimized¶
Class MultiTimescaleNeuron¶
Three-compartment memory neuron with fast/medium/slow timescales.
dv_fast/dt = (-v_fast + I) / tau_fast dv_medium/dt = (-v_medium + alpha * spike_fast) / tau_medium dv_slow/dt = (-v_slow + beta * v_medium) / tau_slow theta_eff = theta_base - gamma * v_slow
Spike when v_fast >= theta_eff. The slow compartment accumulates context over seconds, modulating excitability.
Reference: Custom SC-NeuroCore model — no external publication.
- step(current)
- reset()
Class AttentionGatedNeuron¶
Spiking neuron with learned sigmoid attention gate.
gate = sigmoid(w_key * I + w_query * v) dv/dt = (-v + gate * I) / tau
Each neuron learns which input magnitudes to attend to and which to suppress, via key/query weights.
- step(current)
- reset()
Class PredictiveCodingNeuron¶
Fires only on prediction errors.
dpred/dt = (I - pred) / tau_pred surprise = |I - pred| dv/dt = (-v + surprise) / tau
Silent when input matches prediction. Fires on novel stimuli.
- step(current)
- reset()
Class SelfReferentialNeuron¶
Introspects on its own spike history to modulate dynamics.
self_rate = count(recent_spikes) / window effective_tau = tau * (1 + self_rate / target_rate) theta_eff = theta * (1 + regularity)
Regular firing lowers threshold (maintain pattern). Chaotic firing raises threshold (stabilize).
- step(current)
- reset()
Class CompositionalBindingNeuron¶
Phase-coding neuron for variable binding.
dphi/dt = omega + coupling * sin(phi_input - phi) dA/dt = (-A + I) / tau Spike when A * cos(phi) > theta.
Two neurons in-phase encode bound concepts. Phase offset encodes relational structure.
- step(current)
- reset()
Class DifferentiableSurrogateNeuron¶
Spiking neuron with learnable surrogate gradient parameters.
Forward: spike = int(v >= theta) Backward: surrogate = 1 / (1 + beta * |v - theta|)^2 [conceptual] v = alpha * v * (1 - spike) + I
alpha (decay), beta (steepness), theta (threshold) all trainable.
- step(current)
- reset()
- surrogate_grad()
- Smooth surrogate gradient for backprop.
Class ContinuousAttractorNeuron¶
Ring attractor for continuous working memory.
u_i += (-u_i + f(sum_j w_ij u_j) + I_i) / tau * dt f(x) = max(0,x)^2 / (1 + max(0,x)^2) w_ij = A * exp(-d_ij^2 / (2*sigma_e^2)) - B (Mexican hat)
Holds a continuous value (angle/position) in persistent activity. Output: position of the activity bump.
- post_init()
- step(current)
- bump_position()
- reset()
Class MetaPlasticNeuron¶
Neuron with self-regulating meta-learning rate.
dv/dt = (-v + I) / tau error_trace += (-error_trace + |reward - expected|) / tau_meta * dt meta_lr = lr0 * sigmoid(kappa * (error_trace - target_error))
High error: faster learning. Low error: stabilize.
- step(current)
- update_meta(reward)
- meta_lr()
- reset()
Module neurons.models.aihara_map_neuron¶
Class AiharaMapNeuron¶
Aihara's graded one-state chaotic neuron.
Parameters¶
y : float, default=0.1
Current internal state. The default is the initial condition used for
the source parameter sweep.
k : float, default=0.7
Refractory-memory decay factor; the source requires 0 <= k < 1.
alpha : float, default=1.0
Positive refractory scaling coefficient.
bias : float, default=0.3968
Constant effective stimulus a. The default is the chaotic example
in the primary-author manuscript's Figure 4.
epsilon : float, default=0.01
Positive logistic steepness. The default is the Figure 4 value.
- post_init()
- Normalise scalar fields and reject an invalid configuration.
- x()
- Return the source graded output
x=f(y). - output()
- Return the source graded output
x=f(y). - step(current)
- Advance one map step and return the source thresholded output.
- simulate(current)
- Run an atomic piecewise-stimulus batch on a maintained backend.
- reset()
- Restore the source initial state while preserving parameters.
Module neurons.models.akida_neuron¶
Class AkidaNeuron¶
BrainChip Akida 2021 — event-domain rank-order IF neuron.
Membrane integrates weighted spikes with rank-order decay: V += weight * modulation^rank Spike when V >= threshold. No leak between events.
Reference: BrainChip Inc. (2021). Akida Neuromorphic Processor Reference Manual.
- step(weight)
- Process one input spike event with given synaptic weight.
- reset()
Module neurons.models.alpha¶
Class AlphaNeuron¶
Dual excitatory/inhibitory alpha-synapse leaky integrate-and-fire neuron.
The membrane equation is the leaky integrate-and-fire relaxation
tau_v * dV/dt = -(V - v_rest) + i_exc - i_inh,
and each synaptic current is carried by a two-state alpha cascade
(rise a, current i) that reproduces Rall's alpha kernel
alpha(t) ~ (t/tau) * exp(1 - t/tau) for a pulse input. A spike is
emitted when the candidate membrane potential reaches v_threshold;
only the membrane potential resets (v <- v_rest); the synaptic
cascade states are preserved across spikes.
The maintained numerical step is the exact piecewise-constant-input flow: each alpha filter relaxes exactly, and the membrane update integrates the alpha currents with the exact convolution, including the equal-time-constant limit. This exact flow is the engineering contract, not a biological publication claim.
Defaults tau_v=20, tau_exc=5, tau_inh=10, v_rest=0,
v_threshold=1, and dt=1.0 are catalogue/model-family choices,
not source-derived parameters.
References¶
Rall, W. (1967). Distinguishing theoretical synaptic potentials computed for different soma-dendritic distributions of synaptic input. Journal of Neurophysiology 30(5), 1138–1168. (The alpha kernel.)
Gerstner, W. & Kistler, W.M. (2002). Spiking Neuron Models. Cambridge University Press, §4.1. https://doi.org/10.1017/CBO9780511815706
- post_init()
- Normalise scalar fields and reject an invalid configuration.
- step(exc_current, inh_current)
- Advance one exact-flow interval and return a binary spike event.
- simulate(exc_current, inh_current)
- Run one atomic piecewise-constant-input batch on a maintained backend.
- reset()
- Restore the documented rest state while preserving configuration.
Module neurons.models.alpha_motor_neuron¶
Class AlphaMotorNeuron¶
Alpha motor neuron with WB Na/K, PIC, and Ca-dependent AHP dynamics.
The integrator is still the documented explicit substep path, but mutable runtime state is validated before integration and all substep candidates are computed locally before committing. Invalid state, unstable exponentials, or non-finite membrane/calcium candidates fail closed without poisoning the neuron state.
- post_init()
- step(current)
- reset()
Module neurons.models.amari_field¶
Class AmariNeuralField¶
Discretize Amari's homogeneous single-layer field on a periodic ring.
The maintained equation is Amari (1977), Eq. (3), with the paper's
source-level Heaviside output and a declared difference-of-exponentials
lateral-inhibition kernel. current supplies the combined homogeneous
level h and deviational input s(x,t). A scalar drive is broadcast;
a vector drive must contain exactly n finite samples.
One call performs a simultaneous explicit-Euler update and returns the mean pulse-emission rate (active-site fraction). This is a continuous population-rate model; the returned value is not a spike event.
Parameters¶
n:
Number of uniformly spaced sites on the periodic ring; at least two.
tau:
Positive field time constant.
a_exc, a_width:
Non-negative local-excitation amplitude and positive inverse width.
b_inh, b_width:
Non-negative distal-inhibition amplitude and positive inverse width.
dx, dt:
Positive spatial and temporal discretization steps.
u:
Optional finite initial field state of shape (n,).
Raises¶
ValueError
If configuration, input, or a candidate state is invalid. Failed
updates leave u unchanged.
- post_init()
- Validate configuration and build the circular interaction matrix.
- step(current)
- Advance one atomic Euler step and return mean source-level activity.
- simulate(currents)
- Run a complete drive batch through one maintained execution lane.
- reset()
- Zero every dynamic site while preserving numerical configuration.
Module neurons.models.arcane_neuron¶
Class ArcaneNeuron¶
Unified self-referential cognition neuron for persistent identity.
- step(current)
- reset()
- identity_state()
- The deep compartment value — the accumulated identity.
- confidence()
- novelty()
- identity_drift()
- Cumulative absolute magnitude of identity mutation.
- meta_learning_rate()
- get_recent_pre_activity()
- Get proxy for pre-synaptic activation (recent spike behavior).
- get_state()
Module neurons.models.astrocyte¶
Class AstrocyteModel¶
Li & Bhatt 1994 — astrocyte Ca2+ signaling via IP3 receptor.
3 ODEs: Ca (cytosolic), h (IP3R de-inactivation), IP3. Ca release from ER through IP3 receptor + SERCA pump + leak.
Reference: Postnov, D.E. et al. (2009). Neural Comput. 21:2746–2782.
- post_init()
- step(current)
- Return cytosolic Ca concentration (uM). current = glutamate-driven IP3 production.
- reset()
Module neurons.models.astrocyte_adapter¶
Class AstrocyteNeuron¶
Population-compatible wrapper for AstrocyteModel.
Parameters¶
ca_threshold : float Ca²⁺ concentration (µM) above which the astrocyte "fires" (releases gliotransmitter). Default 0.3 µM. dt : float Timestep in seconds.
- post_init()
- Initialise the wrapped astrocyte model and exposed pseudo-voltage.
- step(current)
- Advance one timestep and return the thresholded release event.
- ca()
- Current cytosolic calcium concentration in micromolar.
- ip3()
- Current IP3 concentration in micromolar.
- reset()
- Reset the wrapped astrocyte state and pseudo-voltage.
Module neurons.models.astrocyte_lif¶
Class AstrocyteLIFNeuron¶
Astrocyte-LIF hybrid with tripartite synapse feedback.
Runtime state is revalidated before every step. Calcium and membrane candidates are computed locally and committed only after both are finite and physiologically admissible, preventing corrupted glial state from leaking into downstream membrane dynamics.
- post_init()
- step_with_pre(i_ext, pre_spike)
- Step with external current and presynaptic spike indicator.
- step(current)
- Step without presynaptic spike info (no glial calcium increment).
- reset()
- Reset state to initial conditions.
Module neurons.models.atype_k_neuron¶
Class ATypeKNeuron¶
A-type K+ neuron with Wang-Buzsaki core and transient IA current.
- post_init()
- step(current)
- reset()
Module neurons.models.av_ron_cardiac¶
Class AvRonCardiacNeuron¶
Av-Ron, Parnas & Segel cardiac ganglion Type III burster.
The four-state conductance model uses instantaneous sodium activation, voltage-dependent h/n/s gate relaxation, and candidate-first RK4 integration so invalid states cannot partially mutate the neuron.
- step(current)
- reset()
Module neurons.models.balanced_resonate_and_fire¶
Class BalancedResonateAndFireNeuron¶
Balanced RF neuron with refractory threshold and smooth reset.
State variables follow the paper notation u = x + i y and refractory
state q. One scalar update computes:
b_t = p(omega) - b_offset - q_{t-1}
u_t = u_{t-1} + dt * ((b_t + i * omega) * u_{t-1} + current)
theta_t = theta_c + q_{t-1}
z_t = Heaviside(Re(u_t) - theta_t)
q_t = gamma * q_{t-1} + z_t
Reference: Higuchi, Kairat, Bohte, and Otte (2024), "Balanced Resonate-and-Fire Neurons", Proceedings of ICML 2024, Algorithm 1.
- post_init()
- p_omega()
- Current divergence boundary for
omegaanddt. - damping()
- Current smooth-reset damping
b_tbefore the next step. - dynamic_threshold()
- Current refractory threshold
theta_c + q. - step(current)
- Advance one BRF timestep and return the binary spike
z_t. - reset()
- Reset membrane and refractory state to rest.
- state()
- Return a compact state snapshot for reproducibility tests.
Function sustain_oscillation_boundary(omega, dt)¶
Return the BRF divergence boundary p(omega).
p(omega) = (-1 + sqrt(1 - (dt * omega)^2)) / dt.
The value is real only when 0 < dt * omega <= 1.
Module neurons.models.benda_herz¶
Class BendaHerzNeuron¶
Benda–Herz universal rate adaptation with deterministic phase spikes.
The chosen paper example is f0(x) = onset_gain * sqrt(max(x-rheobase, 0))
with gamma(f)=0 and A_inf(f)=adaptation_slope*f. The phase follows
dphase/dt=f/1000 and resets exactly to zero at threshold one.
Reference: Benda, J. & Herz, A. V. M. (2003), Neural Computation 15, 2523–2564, DOI 10.1162/089976603322385063.
- post_init()
- step(current)
- Advance one sample and emit the paper's deterministic phase spike.
- reset()
- Restore the paper state variables to their initial values.
Module neurons.models.bertram_phantom¶
Class BertramPhantomBurster¶
Four-state phantom burster of Bertram et al. (2000).
The ionic equations and defaults follow equations 1–10 and the authors'
BJ_00.ode implementation. n is a dynamic fast potassium gate;
s1 and s2 are the 1 s and 120 s negative-feedback gates. The
production integrator is simultaneous fixed-step RK4, rather than the
authors' adaptive CVODE run. current is an additive external-current
extension in fA. Events are sampled upward v_threshold crossings and
do not reset any state.
Reference: Bertram R, Previte J, Sherman A, Kinard TA, Satin LS (2000), Biophysical Journal 79(6):2880–2892, doi:10.1016/S0006-3495(00)76525-8.
- post_init()
- step(current)
- reset()
Module neurons.models.bk_neuron¶
Class BKNeuron¶
BK calcium-activated K+ channel neuron.
Runtime calcium, gate, and membrane candidates are computed locally and committed only after all finite/probability/bounds checks pass. This keeps the documented explicit substep path while preventing non-finite calcium or voltage state from being silently reset after poisoning downstream currents.
- post_init()
- step(current)
- Advance one dt. Returns 1 if spike, 0 otherwise.
- reset()
- Reset to default initial conditions.
Module neurons.models.booth_rinzel¶
Class BoothRinzelNeuron¶
Booth & Rinzel 1995 — bistable motoneuron, 2-compartment.
C dVs/dt = -I_Na(Vs) - I_K(Vs) - I_L(Vs) - gc(Vs - Vd)/p + I/p C dVd/dt = -I_Ca(Vd) - I_KCa(Vd) - I_L(Vd) - gc(Vd - Vs)/(1-p) dq/dt = (q_inf(Vd) - q) / tau_q dCa/dt = -f * (alpha_Ca * I_Ca + k_Ca * Ca)
Reference: Booth, V. & Rinzel, J. (1995). J. Neurophysiol. 73:1934–1945.
- post_init()
- step(current)
- reset()
Module neurons.models.brainscales_adex¶
Class BrainScaleSAdExNeuron¶
BrainScaleS-2 — analog AdEx (1000x real-time). Schemmel 2010.
Reference: Schemmel, J. et al. (2010). Proc. ISCAS 2010: 1947–1950.
- post_init()
- step(current)
- reset()
Module neurons.models.brunel_wang¶
Class BrunelWangNeuron¶
Brunel-Wang pyramidal LIF cell with four aggregate synaptic gates.
Reference: Brunel, N. & Wang, X.J. (2001). Effects of neuromodulation in a cortical network model of object working memory dominated by recurrent inhibition. J Comput Neurosci 11:63-85.
This is the excitatory-cell specialization from Methods 2.2--2.3. The
four values supplied to :meth:step are already-summed channel gating
variables, not spike counts and not internally integrated synapses. One
public step holds those gates constant and applies explicit midpoint RK2,
matching the paper's stated second-order integration class at 0.1 ms.
Attributes¶
ref_remaining : float
Absolute refractory time remaining, in milliseconds. This is dynamic
state rather than a construction parameter: it starts at zero, is set
to tau_ref by a threshold crossing, and decays by dt per step
while positive. The name is the one the committed descriptor declares
in its [state] table and the one :meth:get_state returns, so a
run observes it directly on the instance. A private spelling would
make it declared state that no run can record.
Notes¶
The retained tau_* synaptic parameters document the source boundary
and remain configurable metadata for network adapters. They do not imply
that this single-cell object owns presynaptic channel states.
- post_init()
- step(i_ampa_ext, s_ampa_rec, s_nmda_rec, s_gaba)
- Advance one source-level midpoint-RK2 timestep atomically.
- simulate(i_ampa_ext, s_ampa_rec, s_nmda_rec, s_gaba)
- Run a complete four-gate batch through one maintained backend.
- reset()
- Reset dynamic state while preserving every configuration field.
- get_state()
- Return the complete dynamic membrane/refractory state.
Module neurons.models.butera_respiratory¶
Class ButeraRespiratoryNeuron¶
Butera, Rinzel & Smith 1999 pre-Botzinger respiratory neuron.
This is the paper's three-state Model 1: membrane voltage v, delayed-
rectifier activation n, and persistent-sodium inactivation h_nap.
current passed to :meth:step is the applied current I_app in pA;
the tonic conductance current remains independently configurable. The
continuous source equations are integrated with the repository's explicit
candidate-first RK4 specialization. Invalid input cannot partially mutate
state.
- post_init()
- step(current)
- reset()
Module neurons.models.cazelles_map¶
Class CazellesMapNeuron¶
Cazelles et al. (2001) scalar four-branch bursting map.
- post_init()
- step(current)
- Advance once; rejected candidates leave
xunchanged. - simulate(n_steps, current, backend)
- Return the post-step scalar trace and slow-regime entry count.
- reset()
- Restore Figure 1's initial state while preserving parameters.
Module neurons.models.cerebellar_basket_neuron¶
Class CerebellarBasketNeuron¶
Cerebellar basket cell with A-type and Ca-dependent K currents.
- post_init()
- step(current)
- reset()
Module neurons.models.cfc¶
Class ClosedFormContinuousNeuron¶
Hasani et al. 2022 — closed-form continuous-depth neuron (CfC).
Analytical solution of the LTC ODE between timesteps: x(t+dt) = x(t)exp(-dt/tau_eff) + f_target(1 - exp(-dt/tau_eff)) where tau_eff and f_target depend on input.
Reference: Canavier, C.C. et al. (1993). Biophys. J. 65:2373–2382.
- post_init()
- step(current)
- reset()
Module neurons.models.chandelier_neuron¶
Class ChandelierNeuron¶
Axo-axonic fast-spiking interneuron with Kv1 and Kv3 currents.
- post_init()
- step(current)
- reset()
Module neurons.models.chay¶
Class ChayNeuron¶
Chay 1985 pancreatic beta-cell burster with guarded stiff integration.
Reference: Chay, T.R. (1985). Physica D 16:233-242.
- step(current)
- Advance one timestep and return an upward-threshold spike flag.
- reset()
Module neurons.models.chay_keizer¶
Class ChayKeizerNeuron¶
Chay & Keizer 1983 pancreatic beta-cell minimal model (five-state burster).
The original five-dimensional model: membrane potential v, the
Hodgkin-Huxley activation/inactivation gates m/h of the inward
calcium current, the delayed-rectifier potassium activation n, and the
free cytosolic calcium concentration ca (the slow variable that packages
spikes into bursts). Calcium enters through the voltage-gated calcium channel
during the active phase, gradually activating a calcium-dependent potassium
conductance until it terminates the burst; calcium then decays through the
silent phase until the next burst begins. With the published parameters the
model produces square-wave bursts with a period of order ten to twenty
seconds and a cytosolic calcium oscillation of order one micromolar.
The conductances follow the Hodgkin-Huxley convention written as
g (E_rev - V) (inward positive). The gate rate functions are the
Hodgkin-Huxley 1952 forms with the membrane potential shifted by v_prime
for the calcium gates and v_star for the potassium gate, scaled by the
temperature factor phi; calcium influx is the surface-to-volume scaled
calcium current minus a first-order pump removal.
Reference: Chay, T.R. & Keizer, J. (1983). Minimal model for membrane oscillations in the pancreatic beta-cell. Biophys. J. 42:181-190. DOI 10.1016/S0006-3495(83)84384-7. Parameters are the paper's Table I with the burst calcium-removal rate of Fig. 1b; cross-checked against the Wolfram Demonstrations reference implementation.
- step(current)
- Advance one timestep and return an upward-threshold spike flag.
- reset()
Module neurons.models.chay_keizer_minimal¶
Class ChayKeizerMinimalNeuron¶
Reduced three-state Chay-Keizer pancreatic beta-cell burster.
The essential bursting dynamics of the original five-state Chay-Keizer model
reduced to three variables: membrane potential v, the delayed-rectifier
potassium activation n, and the free cytosolic calcium c (the slow
variable). The calcium-current activation is taken at its instantaneous
steady state, so the fast spikes are generated by the v-n subsystem
while calcium slowly accumulates through the active phase, activates a
calcium-dependent potassium conductance, and terminates the burst; calcium is
then pumped down through the silent phase. A constant ATP-sensitive potassium
conductance sets the excitability (the glucose handle).
Currents follow the convention g (V - E_rev) (outward positive) in the
physical units of the reference (picosiemens, femtofarads, femtoamperes,
millivolts, micromolar, milliseconds). With the published parameters the cell
bursts autonomously: fast spikes ride an active-phase plateau near -20 mV with
a silent phase near -65 mV, while cytosolic calcium traces a slow sawtooth.
Reference: Bertram, R., Marinelli, I., Fletcher, P.A., Satin, L.S. & Sherman, A.S. (2023). Deconstructing the integrated oscillator model for pancreatic beta-cells. Mathematical Biosciences 365:109085, Table 1 (DOI 10.1016/j.mbs.2023.109085); the reduced model of Chay & Keizer (1983), Biophys. J. 42:181-189.
- step(current)
- Advance one timestep and return an upward-threshold spike flag.
- reset()
Module neurons.models.chialvo_map¶
Class ChialvoMapNeuron¶
Chialvo (1995) two-dimensional discrete map neuron.
Parameters¶
x, y : float Fast and recovery state variables. a, b, c, k : float Published dimensionless map parameters. The defaults reproduce a parameter set used in the source paper. x_threshold : float Maintained upward-crossing observation level; not a source parameter.
- post_init()
- step(current)
- Advance one simultaneous map iteration.
- simulate(n_steps, current, backend)
- Advance several map iterations through a selected backend.
- simulate_complete(n_steps, current, backend)
- Advance several iterations and expose both dynamical states.
- reset()
- Restore the two state variables while preserving configured parameters.
Module neurons.models.clif¶
Class ComplementaryLIFNeuron¶
Complementary LIF with separate positive and negative leaky paths.
The public spike contract is ternary: +1 for positive-threshold crossing, -1 for negative-threshold crossing, and 0 for no spike.
- post_init()
- step(current)
- reset()
Module neurons.models.coba_lif¶
Class COBALIFNeuron¶
Brette et al. conductance-based integrate-and-fire benchmark cell.
C dV/dt = -g_L(V - E_L) - g_e(V - E_e) - g_i(V - E_i) + I dg_e/dt = -g_e / tau_e, dg_i/dt = -g_i / tau_i.
Boundary conductance increments are applied before integration. Outside
refractory periods, the full (v, g_e, g_i) candidate is advanced with
coupled RK4. After a spike the voltage remains at v_reset for the
source's 5 ms refractory interval while both conductances continue their
RK4 decay. Every update is candidate-first and mutation-atomic.
The continuous equations and factory defaults reproduce Benchmark 1 in Brette et al. (2007). RK4 is the maintained repository discretisation; the paper compared Euler, second-order Runge--Kutta, and spike-interpolated Euler implementations rather than prescribing RK4.
References¶
Brette, R. et al. (2007). Simulation of networks of spiking neurons: a review of tools and strategies. Journal of Computational Neuroscience, 23, 349--398. doi:10.1007/s10827-007-0038-6.
- post_init()
- step(current, delta_ge, delta_gi)
- Advance one candidate-first RK4 timestep.
- simulate(n_steps, current, delta_ge, delta_gi, backend)
- Advance a constant-input trace through Python or a native backend.
- reset()
- Restore the membrane to leak reversal and clear conductances.
Module neurons.models.cochlear_hair_cell¶
Class CochlearHairCell¶
Cochlear inner hair cell with Boltzmann MET channel activation.
Parameters¶
g_max : float Maximum MET channel conductance. Default: 10.0. e_met : float MET channel reversal potential (mV). Default: 0.0. g_l : float Leak conductance. Default: 1.0. e_l : float Leak reversal / resting potential (mV). Default: -60.0. cap : float Membrane capacitance (pF). Default: 10.0. x0 : float Boltzmann half-activation displacement (nm). Default: 0.0. delta : float Boltzmann slope factor (nm). Default: 0.1. dt : float Integration timestep (ms). Default: 0.01.
- post_init()
- p_open(displacement)
- Boltzmann activation of MET channels.
- step(displacement)
- Step with basilar membrane displacement.
- reset()
- Reset state to resting potential.
- state()
- Return a compact state and parameter snapshot for reproducibility.
Module neurons.models.compte_wm¶
Class CompteWMNeuron¶
Compte et al. pyramidal LIF cell with incoming AMPA/NMDA/GABAA gates.
The class implements the excitatory-cell and channel equations from Compte et al., Cerebral Cortex 10(9), 910--923 (2000), DOI 10.1093/cercor/10.9.910. external_spike increments the external AMPA gate, the compatibility argument spike_in increments the recurrent NMDA precursor, and inhibitory_spike increments the GABAA gate. A postsynaptic output spike resets the membrane and starts the source 2 ms refractory interval; it does not create an inhibitory autapse.
Conductances use microSiemens, voltages millivolts, currents nanoamps, capacitance nanofarads, and time milliseconds. The default conductances are the paper's control-set pyramidal pathways: 3.1 nS external AMPA, 0.381 nS recurrent NMDA, and 1.336 nS interneuron-to-pyramidal GABAA. One public step applies event jumps, then an explicit midpoint RK2 flow at the source 0.02 ms timestep. Threshold detection is sampled at the end of the step; the paper's within-step firing-time interpolation is not claimed.
Attributes¶
ref_remaining : float
Absolute refractory time remaining, in milliseconds. This is dynamic
state rather than a construction parameter: it starts at zero, is set
to tau_ref by a threshold crossing, and decays by dt per step
while positive. The name is the one the committed descriptor declares
in its [state] table and the one :meth:get_state returns, so a
run observes it directly on the instance. A private spelling would
make it declared state that no run can record.
Notes¶
This scalar reference model does not include the paper's 2,560-cell ring.
The connectivity footprints, Poisson drive, tuned persistent bumps,
distractor resistance, and network statistics are retained as the
separately named SC-COMPTE-WM-NETWORK project modification, with their
own evidence boundary.
- post_init()
- Normalise construction scalars and establish valid dynamic state.
- step(current, spike_in)
- Advance one atomic source-level midpoint-RK2 timestep.
- simulate(currents, recurrent_events, external_events, inhibitory_events)
- Run complete state/event traces through one maintained backend.
- reset()
- Reset all dynamic state while preserving configuration.
- get_state()
- Return the complete membrane, channel, and refractory state.
Module neurons.models.connor_stevens¶
Class ConnorStevensNeuron¶
Connor-Stevens-family A-current model with the 1977 parameterization.
State variables are membrane voltage v plus sodium activation m,
sodium inactivation h, delayed-rectifier potassium activation n,
A-type potassium activation a, and A-type inactivation b. One
public step advances the 1 ms macro-step with candidate-first RK4
sub-steps and commits only finite, physically bounded candidates.
- post_init()
- step(current)
- Advance one macro-step and return an upward-threshold spike flag.
- simulate(n_steps, current, backend)
- Advance
n_stepsmacro-steps, returning(v_trace, spikes). - reset()
Module neurons.models.courage_nekorkin_map¶
Class CourageNekorkinMapNeuron¶
Courbage-Nekorkin-Vdovin map with the source Figure-4 profile.
- post_init()
- step(current)
- Advance one map iteration; rejected candidates leave state unchanged.
- simulate(n_steps, current, backend)
- Return the post-step x trace and upward-crossing event count.
- reset()
- Restore the source-profile protocol initial state.
Module neurons.models.dcn_neuron¶
Class DCNNeuron¶
Deep cerebellar nuclei neuron — main output of the cerebellum.
WB Na⁺/K⁺ core + T-type Ca²⁺ (rebound bursting), Ih (pacemaker), persistent Na⁺ (subthreshold), Ca²⁺-dependent AHP. 7 currents total.
Reference: Llinás & Mühlethaler (1988) J Physiol 404:241; Jahnsen (1986) J Physiol 372:129.
- post_init()
- step(current)
- reset()
Module neurons.models.de_schutter_purkinje¶
Class DeSchutterPurkinjeNeuron¶
Single-compartment Purkinje-cell conductance model after De Schutter & Bower.
The maintained Python model exposes the seven compact state variables
(v, h_na, n_k, m_cap, h_cap, q_kca, ca). It is a compact point-neuron
approximation; use the audit index before treating it as the full
multi-compartment reconstruction from the original paper.
The production update is candidate-first RK4 over all seven states. Five
internal substeps are retained to preserve the existing model time base, but
the public step commits only after every substep candidate is finite. The
historical explicit Euler path remains available through
integrator="baseline_euler" for regression comparisons.
Reference: De Schutter, E. & Bower, J.M. (1994). J. Neurophysiol. 71:375–400.
- post_init()
- Validate the selected integration method before simulation.
- step(current)
- Advance the compact conductance model and return a spike indicator.
- reset()
- Restore voltage, gates, and calcium state to their defaults.
Module neurons.models.dendrify¶
Class DendrifyNeuron¶
Pagkalos, Chavlis & Poirazi 2023 — Dendrify active-dendrite 2-compartment model.
Soma: standard LIF with reset. Dendrite: has a dendritic spike mechanism (NMDA-like) that produces a supralinear calcium plateau when input exceeds d_threshold.
Reference: Pagkalos, M. et al. (2023). Nat. Commun. 14:3234.
- step(current)
- reset()
Module neurons.models.dendritic_nmda¶
Class DendriticNMDANeuron¶
Two-compartment neuron with NMDA Mg2+ block (Jahr & Stevens 1990).
Parameters¶
g_nmda : float
NMDA conductance. Default: 1.5.
e_nmda : float
NMDA reversal potential (mV). Default: 0.0.
mg_conc : float
Extracellular Mg2+ concentration (mM). Default: 1.0.
g_coupling : float
Soma-dendrite coupling conductance. Default: 0.5.
tau_soma : float
Soma time constant (ms). Default: 20.0.
tau_dend : float
Dendrite time constant (ms). Default: 50.0.
theta : float
Spike threshold (mV). Default: -50.0.
dt : float
Integration timestep (ms). Default: 0.1.
integrator : {"rk4", "baseline_euler"}
Numerical integration path. "rk4" is the production default;
"baseline_euler" preserves the historical dendrite-first Euler
update as an explicit comparison path.
- post_init()
- mg_block(v)
- Mg2+ block factor: B(V) = 1/(1 + [Mg]/3.57 * exp(-0.062*V)).
- step(i_soma, glutamate)
- Step with somatic input current and dendritic glutamate.
- reset()
- Reset state to resting potential.
Module neurons.models.destexhe_thalamic¶
Class DestexheThalamicNeuron¶
Destexhe et al. 1996 — thalamocortical relay with T-current and I_h.
6 ODEs: V, m_Na, h_Na, n_K, m_T, h_T (+ optional h-current).
Reference: Destexhe, Bal, McCormick & Sejnowski (1996). Ionic mechanisms underlying synchronized oscillations and propagating waves in a model of ferret thalamic slices. J Neurophysiol 76:2049-2070.
- step(current)
- reset()
Module neurons.models.direction_selective_rgc¶
Class DirectionSelectiveRGC¶
Direction-selective retinal ganglion cell.
Parameters are finite and physical: positive tau, theta and dt;
non-negative centre/surround weights; finite preferred direction and state.
- post_init()
- new_on(cls)
- Create an On-centre cell.
- new_off(cls)
- Create an Off-centre cell.
- step_rf(intensity, surround_mean)
- Step with local intensity and surround mean intensity.
- step(current)
- Simple step with no surround input.
- reset()
- Reset state to initial conditions.
Module neurons.models.dpi_neuron¶
Class DPINeuron¶
Current-mode conductance-based DPI silicon neuron.
This class advances the coupled subthreshold equations derived for the differential-pair-integrator circuit by Indiveri, Stefanini, and Chicca (2010), Eqs. (2)--(3):
.. math::
I_{fb} = I_0^{1/(\kappa+1)} I_{mem}^{\kappa/(\kappa+1)} \left[1 + e^{-\alpha(I_{mem}-I_{th})}\right]^{-1}
.. math::
\tau \dot I_{mem} = \frac{I_{mem}}{I_\tau} \left(\frac{I_{rest}+I_{inj}}{1 + I_{mem}/I_g} - I_\tau + I_{fb} - I_{ahp}\right)
.. math::
\tau_{ahp} \dot I_{ahp} = \frac{I_{ahp}}{I_{\tau ahp}} \left(\frac{I_{spk} r(t)}{1 + I_{ahp}/I_{ga}} - I_{\tau ahp}\right).
r(t) is one for the programmable refractory pulse and zero otherwise.
The paper identifies the circuit paths that generate spikes, reset the
membrane, impose refractoriness, and drive adaptation. This maintained
digital realisation adds dimensionless factory parameters, i_rest as a
constant component of I_in, simultaneous explicit-Euler integration,
post-step level detection, and a subsequent-step pulse that holds
i_mem at i_reset. Those numerical choices are not values or a
discrete recurrence printed by the paper.
References¶
Indiveri, G., Stefanini, F., & Chicca, E. (2010). Spike-based learning with a generalized integrate and fire silicon neuron. ISCAS, doi:10.1109/ISCAS.2010.5536980.
Indiveri, G. et al. (2011). Neuromorphic Silicon Neuron Circuits. Frontiers in Neuroscience 5:73, doi:10.3389/fnins.2011.00073.
- post_init()
- step(current)
- Advance one mutation-atomic Euler update of the published circuit.
- simulate(n_steps, current, backend)
- Return membrane trace and aggregate count through one backend.
- simulate_complete(n_steps, current, backend)
- Return aligned state/events and atomically commit the final state.
- reset()
- Restore the physical leakage-current baseline and clear the pulse.
Module neurons.models.durstewitz_dopamine¶
Class DurstewitzDopamineNeuron¶
Durstewitz, Seamans & Sejnowski 2000 — PFC neuron with D1 modulation.
A minimal Hodgkin-Huxley prefrontal pyramidal cell with fast Na⁺
(instantaneous activation m_∞, dynamic inactivation h_na), a
delayed-rectifier K⁺ (n_k), an NMDA current with the Jahr & Stevens
(1990) Mg²⁺ block, and an ohmic leak — the three-state (V, h_na, n_k)
system. D1 agonism (d1_level in [0, 1]) enhances NMDA
(g_nmda_scale), shifts the Na⁺ half-activation (v_shift_na), and
enhances K⁺ (g_k_scale), stabilising persistent up-states.
The production integrator is candidate-first RK4 over the three-state
system: each sub-step evaluates the full right-hand side from one consistent
state, forms the RK4 candidate, and commits it only once finite. The
historical hard-coded forward-Euler update — which advanced the gates from
the old voltage and then the voltage from the freshly updated gates, mixing
two inconsistent states — remains reachable only through the explicit
integrator="baseline_euler" regression option, which now evaluates a
single consistent right-hand side.
Reference: Durstewitz, D., Seamans, J. K. & Sejnowski, T. J. (2000). Dopamine-mediated stabilization of delay-period activity in a network model of prefrontal cortex. J. Neurophysiol. 83:1733–1750.
- post_init()
- mg_block(v)
- Jahr & Stevens (1990) Mg²⁺ block
B(V) = 1/(1 + [Mg]/3.57 · exp(-0.062 V)). - step(current)
- Advance the neuron by one
dtstep and report a threshold crossing. - reset()
- Restore the resting potential and gating defaults.
Module neurons.models.e_prop_alif¶
Class EPropALIFNeuron¶
Bellec et al. 2020 — ALIF with eligibility traces for e-prop.
Adaptive LIF: threshold increases after each spike and decays. Eligibility trace e_t tracks how synaptic weight changes affect future spiking, enabling three-factor learning.
Reference: Bellec, G. et al. (2020). Nat. Commun. 11:3625.
- post_init()
- step(current)
- reset()
Module neurons.models.energy_lif¶
Class EnergyLIFNeuron¶
Fardet-Levina eLIF using the authors' 0.1 ms Brian RK4 profile.
The two coupled states are membrane potential v in mV and normalized
available energy epsilon. alpha is energetic health, delta is
the per-spike energy cost, and epsilon_c is the energy firing gate.
Reference¶
Fardet & Levina (2020), PLOS Computational Biology 16:e1008503, DOI 10.1371/journal.pcbi.1008503.
- post_init()
- Validate the complete eLIF state and parameter contract.
- step(current)
- Advance one source RK4 sample and return the sampled spike event.
- reset()
- Restore the source equilibrium-oriented reset state.
Module neurons.models.ermentrout_kopell_map_neuron¶
Class ErmentroutKopellMapNeuron¶
Ermentrout-Kopell 1986 canonical Type I (theta neuron) map.
The canonical model for Type I (saddle-node) excitability. Phase variable θ advances on a circle; spike occurs when θ crosses π.
θ(n+1) = θ(n) + dt · [(1 - cos θ) + (1 + cos θ) · I]
Reference: Ermentrout & Kopell (1986) SIAM J Appl Math 46:233–253.
- post_init()
- step(current)
- simulate(n_steps, current, backend)
- Advance
n_stepsfrom the current state, returning(trace, spikes). - reset()
Module neurons.models.ermentrout_kopell_pop¶
Class ErmentroutKopellPopulation¶
Represent the exact macroscopic QIF firing-rate equations.
The public class name is retained for compatibility. Its dynamics are
equations (12a–b) of Montbrió, Pazó, and Roxin (2015), not the single-cell
Ermentrout–Kopell theta model. tau restores an explicit membrane time
scale to the dimensionless source equations, so the maintained flow is
dr/dt = delta/(pi*tau**2) + 2*r*v/tau
dv/dt = (v**2 + eta_bar + I + j*tau*r - (pi*tau*r)**2)/tau.
One call to :meth:step applies a simultaneous explicit-Euler update.
That solver is an implementation contract; the publication specifies the
continuous ordinary differential equations.
Parameters¶
r : float, default=0.1 Initial population firing rate. It must be non-negative. v : float, default=-2.0 Initial mean membrane potential. tau : float, default=1.0 Positive membrane time scale. delta : float, default=1.0 Non-negative half-width of the Lorentzian excitability distribution. eta_bar : float, default=-5.0 Centre of the excitability distribution. j : float, default=15.0 Recurrent coupling strength. dt : float, default=0.01 Positive explicit-Euler step.
References¶
Montbrió, E., Pazó, D., and Roxin, A. (2015), Physical Review X 5, 021028. https://doi.org/10.1103/PhysRevX.5.021028
- post_init()
- Normalise scalar fields and reject an invalid configuration.
- step(ext_input)
- Advance one Euler step atomically and return the firing rate.
- simulate(ext_input)
- Run one atomic batch through a maintained execution backend.
- reset()
- Restore the two dynamic states while preserving parameters.
Module neurons.models.escape_rate¶
Class EscapeRateNeuron¶
Gerstner 2000 — stochastic threshold (escape noise model).
Membrane dynamics use the exact constant-current RC flow before evaluating the finite-step escape hazard.
Reference: Gerstner, W. (2000). Neural Comput. 12:43–89.
- post_init()
- initial_seed()
- Return the concrete seed used by this instance.
- rng_state()
- Return the current canonical LFSR16 state.
- step(current)
- simulate(n_steps, current, backend)
- Run a constant-current trace on Python or one real native backend.
- reset()
Module neurons.models.expif¶
Class ExpIFNeuron¶
Profile-explicit Fourcaud-Trocmé exponential integrate-and-fire neuron.
The deterministic voltage flow is
tau * dv/dt = -(v - v_rest) + delta_t * exp((v - v_rh) / delta_t) + current.
v_rh is the soft threshold of the exponential current;
v_threshold is the finite numerical cutoff at which a spike is emitted
and v resets. Runge-Kutta stages are bounded at that event surface, so
stages that overshoot the cutoff cannot evaluate an irrelevant divergent
voltage. refractory_period=1.7 reproduces the refractory duration used
for the paper's fitted Wang-Buzsáki comparison; the zero default is the
deterministic schema-to-RTL contract.
Parameters¶
v:
Initial membrane voltage in millivolts.
v_rest:
Leak reversal voltage in millivolts.
v_reset:
Post-spike reset voltage in millivolts.
v_threshold:
Finite numerical spike cutoff in millivolts.
v_rh:
Soft exponential threshold in millivolts.
delta_t:
Positive exponential slope factor in millivolts.
tau:
Positive membrane time constant in milliseconds.
dt:
Positive integration timestep in milliseconds.
refractory_period:
Non-negative post-spike hold duration in milliseconds.
refractory_remaining:
Non-negative runtime remainder of the refractory hold.
profile:
"fourcaud_trocme_2003" selects the deterministic source
specialization; "sc_rk4" retains the historical SC recurrence.
References¶
Fourcaud-Trocmé, N., Hansel, D., van Vreeswijk, C. & Brunel, N. (2003). Journal of Neuroscience, 23(37), 11628–11640. doi:10.1523/JNEUROSCI.23-37-11628.2003.
- post_init()
- fourcaud_trocme_2003(cls)
- Return the fitted source protocol's deterministic zero-noise profile.
- sc_rk4_compatibility(cls)
- Return the historical SC candidate-first RK4/Q32.32 contract.
- analytical_tail_ms()
- Return the source approximation from the handoff to divergence.
- step(current)
- Advance one timestep and return
1on a spike, otherwise0. - simulate(n_steps, current, backend)
- Advance a sequential trace through Python, Rust, Julia, Go, or Mojo.
- simulate_complete(n_steps, current, backend)
- Return aligned post-step voltage, refractory, and event traces.
- reset()
- Restore resting voltage and clear any refractory hold.
Module neurons.models.fitzhugh_nagumo¶
Class FitzHughNagumoNeuron¶
FitzHugh-Nagumo 1961 two-state excitable-system model.
dv/dt = v - v^3 / 3 - w + I dw/dt = epsilon * (v + a - b*w)
The production default is RK4 over the published two-state ODE. The
historical explicit-Euler path remains available only through the explicit
baseline_euler integrator option for compatibility experiments.
- post_init()
- step(current)
- simulate(n_steps, current, backend)
- Advance
n_stepsRK4 steps from the current state, returning(trace, spikes). - reset()
Module neurons.models.fitzhugh_rinzel¶
Class FitzHughRinzelNeuron¶
FitzHugh-Rinzel three-state qualitative bursting model.
dv/dt = v - v^3/3 - w + y + I dw/dt = delta * (a + v - bw) dy/dt = mu * (c - v - dy)
Runtime integration uses RK4 over the published three-state ODE with current held constant for one step.
- post_init()
- step(current)
- Advance the model by one RK4 step.
- simulate(n_steps, current, backend)
- Advance
n_stepsRK4 steps from the current state, returning(trace, spikes). - reset()
Module neurons.models.fractional_lif¶
Class FractionalLIFNeuron¶
Fractional-order LIF — memory-dependent dynamics.
Uses Grünwald-Letnikov fractional derivative approximation. D^α v(t) = -(v - v_rest) + R·I, where 0 < α ≤ 1. α < 1 introduces memory (power-law decay instead of exponential). Lundstrom et al. 2008.
Reference: Teka, W. et al. (2014). PLoS Comput. Biol. 10:e1003526.
- post_init()
- step(current)
- reset()
Module neurons.models.galves_locherbach¶
Class GalvesLocherbachNeuron¶
Galves-Löcherbach 2013 — stochastic point process neuron.
P(spike at t | history) = φ(V(t)) V(t) = Σ w_j · spike_j(past) · decay + leak Purely probabilistic, no ODE.
Reference: Galves, A. & Löcherbach, E. (2013). J. Stat. Phys. 151:896–921.
- post_init()
- step(weighted_input)
- reset()
Module neurons.models.gamma_motor_neuron¶
Class GammaMotorNeuron¶
Gamma motor neuron — innervates intrafusal fibres of muscle spindles.
Simple LIF with spike-frequency adaptation. Two subtypes: dynamic (bag1, velocity-sensitive) and static (bag2/chain, length-sensitive).
Reference: Prochazka & Hulliger (1989) Prog Brain Res 80; Taylor et al. (1999) J Physiol 519(3).
- post_init()
- static_type(cls)
- Static gamma — bag2/chain intrafusal fibres (length-sensitive).
- step(drive)
- reset()
Module neurons.models.gamma_renewal¶
Class GammaRenewalNeuron¶
Gamma renewal process neuron. Keat et al. 2001.
ISI ~ Gamma(k, k/rate). Hazard h(t) evaluated at elapsed time since last spike. P(spike in dt) = 1 - exp(-h(t)*dt).
Reference: Gerstner, W. et al. (2014). Neuronal Dynamics. Cambridge Univ. Press, §7.4.
- post_init()
- step(rate_override)
- reset()
Module neurons.models.gated_lif¶
Class GatedLIFNeuron¶
Yao et al. 2022 NeurIPS — LIF with learnable gates.
Reference: Yao, M. et al. (2022). Proc. NeurIPS 35:19606–19618.
- post_init()
- step(current)
- reset()
Module neurons.models.gif_population¶
Class GIFPopulationNeuron¶
Generalized integrate-and-fire population neuron with escape-rate spiking.
The deterministic subthreshold flow solves the coupled linear membrane and spike-history adaptation equations exactly over one fixed-current time step. Spiking then follows the Mensi et al. escape-rate hazard with a bounded Poisson interval probability.
Reference: Mensi, S. et al. (2012). J. Neurophysiol. 107:1756-1775.
- post_init()
- step(current)
- reset()
Module neurons.models.glif¶
Class GLIFNeuron¶
Teeter et al. GLIF5 with five source states and fitted reset rules.
The defaults form a source-consistent normalised operating profile. They
are not attributed to one Allen Cell Types Atlas specimen. current is
constant over each exact-flow interval and uses the same current units as
i_asc1 and i_asc2.
- post_init()
- theta()
- Return the instantaneous composite spike threshold.
- step(current)
- Advance one exact-flow interval and return the strict GLIF5 event.
- simulate(n_steps, current, backend)
- Run a failure-atomic constant-current batch and return voltage/events.
- reset()
- Restore the source-consistent operating-profile state.
Module neurons.models.glm_neuron¶
Class GLMNeuron¶
Pillow et al. 2008 — generalized linear model (point-process GLM).
lambda(t) = exp(k . stim(t) + h . spike_history(t) + mu) P(spike in dt) = lambda(t) * dt
k: stimulus filter (length n_k) h: post-spike filter (length n_h), typically negative (refractoriness)
Reference: Pillow, J.W. et al. (2008). Nature 454:995–999.
The exponential nonlinearity, log-rate clip to [-20, 20], and
Bernoulli per-bin sampling are the repository's discrete-time
specialisation of the paper's point process. Pass seed for a
reproducible generator, and uniform to :meth:step to supply
the Bernoulli sample explicitly (exact cross-backend parity).
- post_init()
- step(stimulus, uniform)
- reset()
Module neurons.models.golgi_cell¶
Class GolgiCell¶
Cerebellar Golgi cell — Solinas et al. 2007 full model.
11 ionic currents: INa_t (m³h), INa_p, IKdr (n⁴), IKA (a³b), IKM (w), ICaT (mT²s), ICaN (c²), IBK (V+Ca²⁺), ISK (Ca²⁺), Ih (r), IL. Spontaneously active 3–10 Hz.
Reference: Solinas et al. (2007) Front Cell Neurosci 1:2.
- step(current)
- reset()
Module neurons.models.golomb_fs¶
Class GolombFSNeuron¶
Golomb et al. 2007 — fast-spiking cortical interneuron with a Kv3 current.
The membrane potential follows
C dV/dt = -I_Na - I_Kd - I_Kv3 - I_L + I_ext
with transient sodium I_Na = g_Na m_inf^3 h (V - E_Na) (instantaneous
activation), delayed-rectifier I_Kd = g_Kd n^4 (V - E_K), the fast
high-threshold I_Kv3 = g_Kv3 p^2 (V - E_K) that sharpens spikes and sustains
high-frequency firing, and an ohmic leak. All gating variables relax through
sigmoidal steady states, so the right-hand side has no removable singularities.
The production integrator is candidate-first RK4 over the four-state
(V, h, n, p) system: each sub-step evaluates the full right-hand side from
one consistent state, forms the RK4 candidate, and commits it only once finite.
The historical hard-coded forward-Euler update — which staggered the gate and
membrane increments against mismatched states — remains reachable only through
the explicit integrator="baseline_euler" regression option.
Reference: Golomb, D., Donner, K., Shacham, L., Shlosberg, D., Amitai, Y. & Hansel, D. (2007). Mechanisms of firing patterns in fast-spiking cortical interneurons. J. Neurophysiol. 97:3831–3843.
- post_init()
- step(current)
- Advance the neuron by one
10 * dtstep and report a threshold crossing. - reset()
- Restore the resting membrane potential and gating defaults.
Module neurons.models.granule_cell¶
Class GranuleCell¶
Cerebellar granule cell — D'Angelo et al. 2001 model.
Smallest and most numerous neuron in the brain. 7 ionic currents: INa (m³h), IKdr (n⁴), IKA (a³b), ICaT (mT²s), IKCa (Hill), Ih (r), plus tonic GABA. Ca²⁺ dynamics with KCa half-saturation.
Reference: D'Angelo et al. (2001) J Neurosci 21:759–770.
- post_init()
- step(current)
- reset()
Module neurons.models.gutkin_ermentrout¶
Class GutkinErmentroutNeuron¶
Gutkin-Ermentrout persistent-sodium conductance neuron.
The model keeps voltage v and delayed-rectifier activation n as
dynamic states. Persistent sodium activation is instantaneous through
m_inf(v). The implementation advances the coupled ODE with a
candidate-first fourth-order Runge-Kutta step and commits the candidate
only when the complete numeric contract remains finite and biologically
bounded.
Parameters¶
v:
Membrane voltage state in the inherited normalized millivolt scale.
n:
Delayed-rectifier potassium activation gate. Must remain in [0, 1].
g_na:
Persistent sodium conductance. Must be non-negative.
g_k:
Delayed-rectifier potassium conductance. Must be non-negative.
g_l:
Leak conductance. Must be non-negative.
e_na:
Sodium reversal potential.
e_k:
Potassium reversal potential.
e_l:
Leak reversal potential.
dt:
Integration step. Must be positive and finite.
v_threshold:
Upward voltage-crossing spike threshold.
Raises¶
ValueError If the initial parameters violate the finite-state, conductance, gate, or timestep contract.
Notes¶
The historical SC-NeuroCore surface uses an implicit unit membrane capacitance for this reduced model. Spike output is an event marker from the threshold crossing; voltage is not reset by this model.
References¶
Gutkin, B. S., & Ermentrout, G. B. (1998). Dynamics of membrane excitability determine interspike interval variability: A link between spike generation mechanisms and cortical spike train statistics. Neural Computation, 10(5), 1047-1065.
- post_init()
- Validate the initial state and parameters.
- step(current)
- Advance one RK4 step under constant external current.
- reset()
- Restore the documented default voltage and potassium gate.
Module neurons.models.hay_l5¶
Class HayL5PyramidalNeuron¶
Reduced Layer 5 thick-tufted pyramidal-cell model after Hay et al. 2011.
The maintained production surface is a compact three-compartment reduction
with soma, apical trunk, and apical tuft voltages plus six gates/calcium
state variables. It preserves the public dual-input API
step(current_soma, current_tuft=0.0) while moving the default numerical
path to candidate-first RK4. The historical explicit Euler path remains
available through integrator="baseline_euler" for regression and
benchmark comparisons.
Reference: Hay, E. et al. (2011). PLoS Comput. Biol. 7:e1002107.
- post_init()
- Validate the selected integrator and numeric configuration.
- step(current_soma, current_tuft)
- Advance the model by one public step and return a spike indicator.
- reset()
- Restore voltage, gate, and calcium state to documented defaults.
Module neurons.models.hill_tononi¶
Class HillTononiNeuron¶
Hill and Tononi's hybrid integrate-and-fire neuron.
The continuous state is (V, theta, D, m_h, m_T, h_T). A spike sets
both V and the dynamic threshold theta to E_Na and enables
a brief potassium repolarisation pulse. D is the generic
depolarisation measure used by I_DK; the paper explicitly does not
integrate intracellular sodium or calcium concentration.
Defaults select the paper's cortical-excitatory waking profile. Sodium and
potassium leaks, I_NaP, and I_DK are active. I_h and I_T
remain available with zero default conductance because the source assigns
them only to specific intrinsically bursting or thalamic cell types. The
recurrence uses source step dt=0.25 ms and classical RK4. Synaptic
conductance dynamics, minis, and the full network are outside this
single-cell catalogue model.
Primary source: Hill & Tononi, J Neurophysiol 93:1671–1698 (2005),
doi:10.1152/jn.00915.2004. Maintained NEST ht_neuron equations
disambiguate parentheses in the printed I_NaP, D, and I_T
formulae.
- post_init()
- m_h_inf(v)
- tau_m_h(v)
- m_t_inf(v)
- tau_m_t(v)
- h_t_inf(v)
- tau_h_t(v)
- d_k_inf(v)
- step(current)
- Advance one source timestep and return
1on spike emission. - reset()
- Restore the source cortical-excitatory waking initial state.
Module neurons.models.hindmarsh_rose¶
Class HindmarshRoseNeuron¶
Hindmarsh-Rose 1984 — 3D chaotic bursting model.
dx/dt = y - x³ + bx² - z + I dy/dt = 1 - 5x² - y dz/dt = r(s(x - x_rest) - z)
Reference: Hindmarsh, J.L. & Rose, R.M. (1984). Proc. R. Soc. Lond. B 221:87–102.
- post_init()
- step(current)
- simulate(n_steps, current, backend)
- Advance
n_stepsRK4 steps from the current state, returning(trace, spikes). - reset()
Module neurons.models.hodgkin_huxley¶
Class HodgkinHuxleyNeuron¶
Hodgkin-Huxley 1952 — 4-ODE ion channel model.
C_m dv/dt = -g_Na m³h(v-E_Na) - g_K n⁴(v-E_K) - g_L(v-E_L) + I dm/dt = α_m(1-m) - β_m·m dh/dt = α_h(1-h) - β_h·h dn/dt = α_n(1-n) - β_n·n
Reference: Hodgkin, A.L. & Huxley, A.F. (1952). J. Physiol. 117:500–544.
The source rest-relative voltage is shifted to the maintained modern absolute-voltage coordinate. The default production recurrence is the historical gate-first explicit-Euler profile; paired schemas separately represent simultaneous RK4. Public steps validate and commit atomically.
Integrator options:
- baseline_euler preserves the historical explicit-Euler sub-step path
- rk4 is an explicit higher-order alternative path over the same
sub-step schedule
- rosenbrock is a linearly implicit stiff-system path over the same
Hodgkin-Huxley ODEs
- post_init()
- step(current)
- Advance one macro step and commit only a finite physical candidate.
- simulate(n_steps, current, backend)
- Advance
n_stepsupdates, returning(v_trace, spikes). - reset()
Module neurons.models.huber_braun¶
Class HuberBraunNeuron¶
Braun, Huber et al. 1998 — cold receptor, temperature-dependent.
4 ODEs: V, a_sd (slow depolarizing), a_sr (slow repolarizing), a_r.
Reference: Braun, H.A. et al. (1998). Int. J. Bifurcation Chaos 8:881–889.
- step(current)
- reset()
Module neurons.models.hybrid_linear_attention¶
Class HybridLinearAttentionNeuron¶
Hybrid linear attention spiking neuron.
Parameters¶
dim : int Dimension of recurrent KV state. Default: 16. lambda_decay : float Exponential decay for recurrent state. Default: 0.95. window_size : int Sliding window size for local attention. Default: 16.
- post_init()
- step_qkv(query, key, value)
- Step with explicit query, key, value (scalar projections).
- step(current)
- Simple step (input treated as combined qkv). Returns spike (0 or 1).
- reset()
- Reset state to initial conditions.
Module neurons.models.ibarz_tanaka_map¶
Class IbarzTanakaMapNeuron¶
Ibarz et al. (2007) analysis profile of the Shilnikov-Rulkov map.
Parameters¶
v, u : float Fast membrane-like state and slow recovery state. The defaults reproduce the map placement used for Fig. 2(a) of the source at zero current. alpha : float Fast-map geometry parameter from Eq. 3. mu : float Positive slow timescale from Eq. 2. sigma : float Slow-nullcline offset from Eq. 2.
- post_init()
- step(current)
- Advance Eqs. 2-3 once and return the reset-branch event.
- simulate(n_steps, current, backend)
- Advance the map and return the fast-state trace plus event count.
- reset()
- Restore the source example's initial state without changing parameters.
Module neurons.models.ih_neuron¶
Class IhNeuron¶
Ih (HCN) neuron — WB base + hyperpolarisation-activated cation current.
Ih activates upon hyperpolarisation and conducts a mixed Na⁺/K⁺ current with reversal ≈ -40 mV. Produces voltage sag, rebound excitation, and pacemaker oscillations.
r∞ = 1 / (1 + exp((v + 80) / 10)) τ_r = 100 + 200 / (1 + exp((v + 70) / 10))
Reference: Robinson & Siegelbaum (2003) Annu Rev Physiol 65:453; Pape (1996) Annu Rev Physiol 58:299.
- post_init()
- step(current)
- reset()
Module neurons.models.ilif¶
Class InhibitoryLIFNeuron¶
Inhibitory LIF — 2025, temporal inhibitory mechanism.
After spiking, a decaying inhibitory trace suppresses the membrane for a learned duration, shaping temporal coding.
Reference: Fourcaud-Trocmé, N. et al. (2003). J. Neurosci. 23:11628–11640.
- post_init()
- step(current)
- reset()
Module neurons.models.inhomogeneous_poisson¶
Class InhomogeneousPoissonNeuron¶
Cox 1955 — doubly stochastic Poisson (time-varying rate).
Reference: Gerstner, W. et al. (2014). Neuronal Dynamics. Cambridge Univ. Press, §7.3.
- post_init()
- step(rate_hz)
- reset()
Module neurons.models.iqif¶
Class IntegerQIFNeuron¶
Wu et al. (2021) piecewise-linear integer QIF soma.
Parameters¶
v : int, default=128
Live integer membrane state.
v_rest : int, default=128
Resting state and state restored by :meth:reset.
v_threshold : int, default=200
Upper piecewise-force reference, not the spike threshold.
v_reset : int, default=128
State committed after a candidate exceeds v_max.
a, b : int, default=1
Non-negative Q0.3 numerator coefficients. The recurrence applies
(coefficient * difference) >> 3.
v_max, v_min : int, default=255, 0
Strict upper event boundary and inclusive lower state clamp.
Notes¶
The branch point is trunc((b*v_threshold + a*v_rest)/(a+b)).
One step computes the source force from the pre-step state, applies the
Q0.3 arithmetic shift and current, emits when the candidate is strictly
greater than v_max, then hard-resets to v_reset. Otherwise the
candidate is clamped only at v_min.
References¶
Wu, W.-C., Yeh, C.-F., White, A. J., et al. (2021). Integer Quadratic Integrate-and-Fire (IQIF): A Neuron Model for Digital Neuromorphic Systems. https://doi.org/10.1109/AICAS51828.2021.9458572
- post_init()
- Normalise and validate the complete source contract.
- branch_point()
- Return the source's C++-truncated piecewise boundary.
- step(current)
- Advance one integer tick and return a binary spike indicator.
- simulate(n_steps, current, backend)
- Return an exact post-step trace through one maintained backend.
- reset()
- Restore
v_restwithout changing any parameter.
Module neurons.models.izhikevich2007¶
Class Izhikevich2007Neuron¶
Izhikevich 2007 biophysical quadratic integrate-and-fire neuron.
Equations from Izhikevich, E. M. (2007), Dynamical Systems in
Neuroscience, using the NeuroML 2 izhikevich2007Cell parameterisation:
C dv/dt = k (v - vr) (v - vt) - u + I
du/dt = a (b (v - vr) - u)
If v >= vpeak after integration, the neuron emits one spike and applies
v <- c and u <- u + d. Units are the NeuroML base units used by the
importer: pF, nS, mV, ms, and pA.
- post_init()
- step(input_current)
- simulate(n_steps, current, backend)
- Advance
n_stepsRK4 steps from the current state, returning(trace, spikes). - reset_state()
- get_state()
Module neurons.models.jansen_rit¶
Class JansenRitUnit¶
Represent one Jansen–Rit cortical-column neural mass.
The six first-order states implement equation (6) from Jansen and Rit
(1995). e0 is half the maximum firing rate because :meth:_sigmoid
returns 2 * e0 / (1 + exp(r * (v0 - v))). The default explicit-Euler
step is 0.1 ms, matching the pinned Brian2 implementation used for the
source-bound trace; the continuous equations do not prescribe a solver.
Parameters¶
y0, y3, y1, y4, y2, y5 : float, default=0.0
Initial postsynaptic-potential states and their first derivatives.
a_exc, b_exc : float
Excitatory and inhibitory synaptic gains A and B in mV.
a_rate, b_rate : float
Excitatory and inhibitory inverse time constants in s⁻¹.
c : float
Base connectivity C1. Derived couplings are C2=0.8*C1 and
C3=C4=0.25*C1.
e0, v0, r : float
Sigmoid half-maximum rate, midpoint, and slope.
dt : float, default=0.0001
Explicit-Euler step in seconds.
References¶
Jansen, B. H. and Rit, V. G. (1995), Biological Cybernetics 73, 357–366. https://doi.org/10.1007/BF00199471
- post_init()
- Normalise scalar fields and reject an invalid configuration.
- step(p_ext)
- Advance one explicit-Euler step and return the post-update EEG proxy.
- simulate(p_ext)
- Run an atomic batch on one maintained execution backend.
- reset()
- Restore all six dynamic states while preserving parameters.
Module neurons.models.klif¶
Class KLIFNeuron¶
KLIF — LIF with learnable scaling factor k.
V[t+1] = alpha * V[t] + k * I; spike when V >= threshold. The scaling factor k is a trainable parameter for SNN backprop.
Reference: Jiang, C. & Zhang, Y. (2024). Neural Comput. 36(8):1546–1564.
- post_init()
- step(current)
- reset()
Module neurons.models.lapicque¶
Class LapicqueNeuron¶
Lapicque 1907 polarization threshold with an explicit SC LIF profile.
For the source profile, with source voltage V, series resistance
R, membrane/polarization resistance rho, capacitance K, and
polarization v, Lapicque derives
K dv/dt = (V - v) / R - v / rho.
A constant-voltage pulse has the exact flow
v(t+h) = v_inf + (v(t)-v_inf) exp(-h/beta),
where v_inf = V*rho/(R+rho) and beta = K*R*rho/(R+rho).
The first threshold attainment emits one latched excitation. There is no
source-defined automatic reset.
LapicqueNeuron() preserves the historical SC exact-flow LIF recurrence
tau*dv/dt = -(v-v_rest) + resistance*current with hard reset.
LapicqueNeuron.lapicque_1907() constructs the count-bearing source
profile. Its normalized defaults preserve the paper's R > rho regime
and beta=1 ms; they are maintained reproducibility choices rather than
claimed experimental constants.
Reference¶
Lapicque, L. (1907). Journal de Physiologie et de Pathologie Generale, 9, 620-635. English translation: doi:10.1007/s00422-007-0189-6.
- post_init()
- lapicque_1907(cls)
- Construct the source-equation polarization-threshold profile.
- sc_lif_compatibility(cls)
- Construct the preserved hard-reset SC exact-flow LIF profile.
- source_beta()
- Return Lapicque's physical time constant
K R rho/(R+rho). - source_alpha()
- Return the infinite-duration threshold voltage
v*(R+rho)/rho. - source_threshold_voltage(duration)
- Return the source voltage required to reach threshold in
duration. - step(drive)
- Advance one exact constant-drive step and return a binary event.
- simulate(n_steps, current, backend)
- Advance a complete batch and return its state trace and event count.
- simulate_complete(n_steps, drive, backend)
- Return aligned post-step state and event traces, committing atomically.
- reset()
- Re-arm the experiment or restore the SC membrane to rest.
Class SCLapicqueLIFNeuron¶
Count-neutral preserved exact-flow, hard-reset SC LIF identity.
This explicit name prevents the later repetitive reset convention from being mistaken for the complete Lapicque 1907 source experiment.
- init(v, v_rest, v_reset, v_threshold, tau, resistance, dt)
Module neurons.models.larter_breakspear¶
Class LarterBreakspearNeuron¶
Three-state Larter-Breakspear cortical neural mass.
The transition follows the excitatory-voltage, potassium-channel, and
inhibitory-voltage equations of Breakspear, Terry, and Friston (2003).
coupling is the external excitatory firing-rate term denoted by the
population-average :math:Q_V in the source model. The default parameters
are the maintained Larter-Breakspear profile used by The Virtual Brain.
A fixed-step classical RK4 grid is an implementation specialisation. The equations are continuous, produce continuous population activity, and do not define a spike/reset event.
References: Breakspear, Terry & Friston, Network 14 (2003), 703-732, doi:10.1088/0954-898X/14/4/305.
- post_init()
- step(coupling)
- Advance one observation step and return excitatory voltage.
- reset()
- Restore the maintained source-profile initial state.
Module neurons.models.leaky_compete_fire¶
Class LeakyCompeteFireNeuron¶
Oster, Douglas & Liu 2009 — winner-take-all with lateral inhibition.
Reference: Oster, M. et al. (2009). Neural Comput. 21(9):2437–2465.
- post_init()
- step(currents)
- reset()
Module neurons.models.lnm¶
Class LearnableNeuronModel¶
Fully parameterized learnable neuron.
V[t+1] = alpha * V[t] + beta * I[t] + gamma * f(V[t]) where alpha, beta, gamma are trainable scalars and f is a learnable activation (here sigmoid) — a trainable generalisation of the simple threshold models fitted to cortical recordings by Jolivet et al.
Reference: Jolivet, Rauch, Lüscher & Gerstner (2006). Predicting spike timing of neocortical pyramidal neurons by simple threshold models. J Comput Neurosci 21:35-49.
- post_init()
- step(current)
- reset()
Module neurons.models.loihi2¶
Class Loihi2Neuron¶
Intel Loihi 2, 2021 — programmable 3-state-variable neuron.
State variables (s1, s2, s3) with configurable decay, threshold, and cross-coupling. Generalises CUBA, COBA, and Izhikevich on-chip. All integer arithmetic with configurable bit-shift decays.
Reference: Intel Corp. (2021). Loihi 2 Neuromorphic Processor Technical Brief.
- step(weighted_input)
- reset()
Module neurons.models.loihi_cuba¶
Class LoihiCUBANeuron¶
Loihi CUBA LIF — Intel Loihi fixed-point neuron. Davies 2018.
Reference: Davies, M. et al. (2018). IEEE Micro 38:82–99.
- step(weighted_input)
- reset()
Module neurons.models.ltc¶
Class LiquidTimeConstantNeuron¶
Hasani et al. 2021 — liquid time-constant neuron.
dx/dt = -(1/tau(x,I)) * x + (1/tau(x,I)) * f(x,I) where tau depends on input, making the neuron's time constant adaptive and input-driven.
Reference: Hasani, R. et al. (2021). Proc. AAAI Conf. Artif. Intell. 35(9):7657–7666.
- step(current)
- reset()
Module neurons.models.lugaro_cell¶
Class LugaroCell¶
Cerebellar Lugaro cell — rare fusiform granular layer interneuron.
LIF with adaptation, serotonin (5-HT) modulation, depolarised leak for spontaneous firing. Inhibits Golgi cells and molecular layer INs.
Reference: Dieudonné & Dumoulin (2000). Serotonin-driven long-range inhibitory connections in the cerebellar cortex. J Neurosci 20:1837-1848.
- post_init()
- with_serotonin(cls, level)
- step(current)
- reset()
Module neurons.models.mainen_sejnowski¶
Class MainenSejnowskiNeuron¶
Mainen & Sejnowski 1996 — axonal Na spike initiation model.
2-compartment: soma (passive) + axon (active Na + K). Axon initiates spike via fast Na kinetics; soma follows passively. C_s dV_s/dt = -g_L(V_s - E_L) + gc(V_a - V_s) + I C_a dV_a/dt = -I_Na - I_K + gc(V_s - V_a)
Reference: Mainen, Z.F. & Sejnowski, T.J. (1996). Nature 382:363–366.
The Euler substepping and the in-loop voltage clips to [-200, 200] mV
are repository-specific specialisations, not publication-exact
claims. Canonical rate evaluation uses numerically stable analytic
removable-singularity limits (expm1 linoid form); the historical
additive 1e-12 denominator regularisation — which returned a zero
rate exactly at each singular voltage — remains reconstructible via
legacy_epsilon_rates=True as a count-neutral legacy
configuration.
- post_init()
- step(current)
- reset()
Module neurons.models.marder_stg¶
Class MarderSTGNeuron¶
Liu-Golowasch-Marder-Abbott 1998 stomatogastric ganglion neuron.
Single-compartment crustacean STG model with seven voltage-gated currents (Na, CaT, CaS, A, KCa, Kd, H) plus a leak, in the Prinz/LGMA unit convention (conductances in mS/cm², capacitance in µF/cm², calcium in µM, voltage in mV, time in ms). All gates use the published voltage-dependent steady states and time constants; the calcium reversal is computed from the Nernst equation, and intracellular calcium relaxes towards rest with a 20 ms time constant driven by the two calcium currents. The thirteen-state vector is integrated with classical fourth-order Runge-Kutta.
Parameters¶
v : float Membrane potential (mV). m_na, h_na, m_cat, h_cat, m_cas, h_cas, m_a, h_a, m_kca, m_kd, m_h : float Gating variables in [0, 1]. ca : float Intracellular calcium concentration (µM, ≥ 0). cm : float Specific membrane capacitance (µF/cm²). g_na, g_cat, g_cas, g_a, g_kca, g_kd, g_h, g_l : float Maximal conductances (mS/cm²). e_na, e_k, e_h, e_l : float Reversal potentials (mV). The calcium reversal is Nernst-derived. ca_out : float Extracellular calcium concentration (µM) for the Nernst equation. ca_rest : float Resting calcium concentration (µM). tau_ca : float Calcium relaxation time constant (ms). f_ca : float Calcium-current-to-concentration coupling (µM·cm²/µA). celsius : float Temperature (°C) for the Nernst equation. dt : float Integration time step (ms). v_threshold : float Voltage at which a spike is registered (mV).
References¶
Liu, Z., Golowasch, J., Marder, E. & Abbott, L.F. (1998). A model neuron with activity-dependent conductances regulated by multiple calcium sensors. J. Neurosci. 18(7):2309–2320. Channel kinetics: ModelDB accession 93321.
- post_init()
- step(current)
- Advance one
dtand return 1 on an upward threshold crossing. - reset()
- Restore the resting initial condition.
Module neurons.models.martinotti_neuron¶
Class MartinottiNeuron¶
Martinotti cell — adapting interneuron targeting layer 1 apical dendrites.
Pospischil 2008 gating with fast Na⁺, delayed-rectifier K⁺, a very strong
M-current (Kv7) that gives the pronounced spike-frequency adaptation
characteristic of the type, a low-threshold T-type Ca²⁺ current for rebound,
and an ohmic leak — the six-state (V, m, h, n, p, s) system (T-type
activation m_T is instantaneous; unlike the SST cell there is no Ih).
The sodium and potassium activation rates follow the Traub-Miles
x/(exp(±x/k)-1) form and use the L'Hôpital limit at the removable
singularity. The β_m numerator is the published V - V_T - 40 offset; an
earlier revision shared the -17 offset of α_h, which lowered β_m enough to
drive the cell into depolarisation block (it fired two or three spikes then
stuck near threshold for any stimulus). The corrected kinetics restore a
monotone frequency-current relation.
The production integrator is candidate-first RK4 over the six-state system:
each sub-step evaluates the full right-hand side from one consistent state,
forms the RK4 candidate, and commits it only once finite. The historical
hard-coded forward-Euler update — which staggered the gate and membrane
increments against mismatched states — remains reachable only through the
explicit integrator="baseline_euler" regression option.
Reference: Silberberg, G. & Markram, H. (2007). Disynaptic inhibition between neocortical pyramidal cells mediated by Martinotti cells. Neuron 53:735–746; Toledo-Rodriguez et al. (2005); Pospischil et al. (2008) Biol. Cybern. 99:427.
- post_init()
- step(current)
- Advance the neuron by one
4 * dtstep and report a threshold crossing. - reset()
- Restore the resting potential and gating defaults.
Module neurons.models.mat¶
Class MATNeuron¶
Non-resetting MAT* neuron from Kobayashi, Tsubo, and Shinomoto (2009).
v is measured relative to the resting potential. The membrane follows
forward Euler, while the two spike-history terms use their exact
exponential decay. A spike raises the adaptive threshold but never resets
the membrane voltage. The default parameter set is the paper's regular-
spiking (RS) example, not a universal cortical-cell calibration.
Reference: R. Kobayashi, Y. Tsubo, and S. Shinomoto, Frontiers in Computational Neuroscience 3:9 (2009), doi:10.3389/neuro.10.009.2009.
- post_init()
- Validate the complete source-model contract before first use.
- regular_spiking(cls)
- Construct the paper's regular-spiking example profile.
- intrinsically_bursting(cls)
- Construct the paper's intrinsically-bursting example profile.
- fast_spiking(cls)
- Construct the paper's fast-spiking example profile.
- threshold()
- Return the instantaneous adaptive threshold in millivolts.
- step(current)
- Advance one paper-MAT* step and return
1on a spike. - reset()
- Restore zero-rest voltage, spike history, and refractory state.
Module neurons.models.mcculloch_pitts¶
Class McCullochPittsNeuron¶
McCulloch and Pitts' 1943 all-or-none logical neuron.
Parameters¶
theta : int, default=1 Positive number of simultaneously active excitatory afferents required to excite the neuron when no inhibitory afferent is active.
Notes¶
:meth:step maps afferent activity at one network instant to activity one
synaptic delay later. The delay belongs to the network scheduler; the
formal neuron has no evolving membrane state. Any active inhibitory
afferent is an absolute veto, independent of the excitatory count.
References¶
McCulloch, W. S., & Pitts, W. (1943). A logical calculus of the ideas immanent in nervous activity. Bulletin of Mathematical Biophysics, 5, 115--133. https://doi.org/10.1007/BF02478259
- post_init()
- Normalise the fixed excitatory-count threshold.
- step(excitatory_count, inhibitory_active)
- Return the source-faithful all-or-none output for one delay.
- simulate(excitatory_counts, inhibitory_flags, backend)
- Evaluate a varying-input batch through one maintained backend.
- reset()
- Validate the fixed parameter; the formal neuron has no live state.
Function encode_hardware_input(excitatory_count, inhibitory_active)¶
Encode the two-input source contract on the signed Q32.0 RTL port.
Non-negative values carry the active excitatory-afferent count. -1 is
the sole inhibitory-veto sentinel. Because theta is strictly positive,
the schema condition I >= theta is equivalent to the public two-input
rule for every valid input.
Module neurons.models.mckean¶
Class McKeanNeuron¶
McKean's discontinuous FitzHugh-Nagumo caricature.
The equations are the source-bound space-clamped system of Tonnelier
(2003), equations (1.3)-(1.6), following McKean (1970):
dv/dt=-lambda*v+mu*H(v-a)-w+I and dw/dt=b*v.
The numerical specialization declares H(0)=1 and samples an event on
upward crossing of the switching line; the ODE has no spike reset.
- post_init()
- Validate source state and parameter constraints.
- step(current)
- Advance one RK4 sample atomically and report a switching-line crossing.
- reset()
- Restore the source equilibrium state.
Module neurons.models.medvedev_map¶
Class MedvedevMapNeuron¶
Medvedev (2005) calibrated slow-calcium first-return map.
Parameters¶
u : float
Slow calcium state. The default is the calibrated saddle-node return
u_SN.
beta_0, beta_hc, beta_sn, delta : float
Source bifurcation parameters defining u_0, u_HC and u_SN.
decay_t0, alpha_t0 : float
Calibrated Eq. 4.4 relaxation and Eq. 4.8 affine-return coefficients.
f_0, f_1 : float
Calibrated fast-subsystem averages on the active and homoclinic branches.
homoclinic_exponent, d : float
Eq. 4.13 boundary-layer exponent and scale.
input_gain : float
Maintained gain for the external perturbation on active returns.
- post_init()
- step(current)
- Advance one first-return iteration without partial state mutation.
- simulate(n_steps, current, backend)
- Advance a constant-current first-return trajectory.
- reset()
- Restore only the slow-calcium state to the calibrated
u_SNreturn.
Module neurons.models.mihalas_niebur¶
Class MihalasNieburNeuron¶
Source-form Mihalaş-Niebur generalized linear IF neuron.
Defaults use the paper's common Figure 1 constants and the Figure 1C
spike-frequency-adaptation value a = 5 s⁻¹. Rates are expressed per
millisecond, voltages in volts, and i1, i2, and current in volts
per millisecond after division by capacitance.
Reference¶
Mihalaş, Ş. and Niebur, E. (2009), Neural Computation 21(3), 704–718, doi:10.1162/neco.2008.12-07-680, equations (2.1)–(2.2), Table 1.
- post_init()
- step(current)
- Advance one sampled RK4 interval and return one on a source event.
- simulate(n_steps, current, backend)
- Advance a constant-current trajectory through the selected runtime.
- reset()
- Restore the paper-profile resting state without changing parameters.
Module neurons.models.morris_lecar¶
Class MorrisLecarNeuron¶
Morris-Lecar 1981 — calcium-potassium oscillator.
C dv/dt = -g_Ca m_∞(v)(v-E_Ca) - g_K w(v-E_K) - g_L(v-E_L) + I dw/dt = λ(v)(w_∞(v) - w)
Reference: Morris, C. & Lecar, H. (1981). Biophys. J. 35:193–213.
Integrator options:
- rk4 is the maintained default fourth-order path over the Morris-Lecar ODEs
- baseline_euler preserves the historical explicit-Euler path for comparison
- rosenbrock is a linearly implicit stiff-system path over the same
conductance equations
- post_init()
- step(current)
- simulate(n_steps, current, backend)
- Advance
n_stepsupdates, returning(v_trace, spikes). - reset()
Module neurons.models.motor_unit¶
Class MotorUnit¶
Motor unit — alpha motor neuron + muscle fibre.
Each spike triggers a muscle twitch. Force output is summation of overlapping twitches (rate coding). Twitch modelled as critically- damped second-order: f(t) = A · (t/τ) · exp(1 - t/τ).
Reference: Fuglevand et al. (1993) J Neurophysiol 70(6); Heckman & Enoka (2012) Compr Physiol 2(4).
- slow(cls)
- Slow motor unit (type S): small, fatigue-resistant, low force.
- fast(cls)
- Fast motor unit (type FF): large, fatigable, high force.
- step(drive)
- reset()
Module neurons.models.multicompartment_mcn¶
Class MulticompartmentMCNNeuron¶
Multi-compartment neuron (Spiking-WM, PNAS 2025).
The production update is candidate-first RK4 over the three coupled state
variables (u, v_basal, v_apical). Basal, apical, and somatic drives are
held constant across each RK4 stage; the stage apical voltage gates the
stage basal-to-soma coupling, so all derivatives are evaluated from one
consistent state. The historical explicit Euler path remains available only
through integrator="baseline_euler" for regression comparisons.
Parameters¶
tau : float Soma time constant. Default: 2.0. tau_b : float Basal dendrite time constant. Default: 2.0. tau_a : float Apical dendrite time constant. Default: 2.0. g_ratio : float Basal-to-soma conductance ratio (g_B/g_L). Default: 1.0. beta : float Sigmoid steepness for apical gating. Default: 1.0. v_th : float Spike threshold. Default: 1.0. dt : float Integration timestep. Default: 1.0. integrator : {"rk4", "baseline_euler"} Numerical integration path. Default: "rk4".
- post_init()
- step_compartments(x_basal, x_apical, i_soma)
- Advance one step with basal, apical, and direct somatic drives.
- step(current)
- Advance one step with
currentdelivered to the basal dendrite. - reset()
- Reset soma, basal, and apical state to initial conditions.
Module neurons.models.nagumo_sato_map_neuron¶
Class NagumoSatoMapNeuron¶
Nagumo and Sato's discontinuous refractory neuron map.
Parameters¶
y : float, default=0.1
Current internal state, matching Aihara's Figure 3 initial condition.
k : float, default=0.6
Refractory-memory damping factor; the source requires 0 <= k < 1.
alpha : float, default=1.0
Positive refractory decrement following a firing output.
bias : float, default=0.2
Constant transformed stimulus a.
- post_init()
- Normalise scalar fields and reject invalid configuration.
- x()
- Return the current all-or-none firing output
H(y). - output()
- Return the current all-or-none firing output
H(y). - step(current)
- Advance one source-equation step and return
H(y[t+1]). - simulate(current)
- Run an atomic batch on Python, Rust, Julia, Go, or Mojo.
- reset()
- Restore the source initial state while preserving parameters.
Module neurons.models.neurogrid¶
Class NeuroGridNeuron¶
Boahen-style reduced Neurogrid two-compartment analog neuron.
The model couples a passive dendritic integrator to an EIF-like soma. The
production path uses candidate-first RK4 for the continuous two-state flow
and applies the discrete Neurogrid spike/reset rule once to the accepted
public-step candidate. The historical dendrite-first explicit Euler update
remains available through integrator="baseline_euler" for regression
comparisons.
Reference: Benjamin, B.V. et al. (2014). Proc. IEEE 102:699-716.
- post_init()
- Validate the integrator choice and initial numeric configuration.
- step(current)
- Advance the neuron by one public step and return a spike indicator.
- reset()
- Restore soma and dendrite voltages to rest.
Module neurons.models.nlif¶
Class NonlinearLIFNeuron¶
Quadratic nonlinear LIF neuron with slow adaptation.
The membrane follows
c_m dV/dt = a(V - v_rest)(V - v_crit) - w + I
and the adaptation current follows
tau_w dw/dt = b(V - v_rest) - w.
The parameter validation is intentionally fail-closed: invalid geometry, non-finite state, or unstable integration constants are rejected before any state mutation can occur.
- post_init()
- step(current)
- Advance one candidate-first RK4 step and return
1on spike. - reset()
- Restore dynamic state without changing model parameters.
Module neurons.models.nmda_neuron¶
Class NMDANeuron¶
Wang (1999) pyramidal LIF neuron with an NMDA autapse.
The scalar model combines Wang's equations (1), (2), (4), and (5):
a pyramidal leaky integrate-and-fire membrane, optional calcium-activated
potassium adaptation, and the two-stage saturating NMDA gate. The recurrent
gate receives the neuron's own emitted events, matching the NMDA-only
autapse experiment in Figure 3. current is the paper's applied current
I_app in nA.
The source used second-order Runge--Kutta integration at 0.02--0.05 ms and interpolated spike times. This deterministic scalar specialization uses midpoint RK2 at 0.05 ms and sampled upward threshold detection.
Reference: Wang, X.-J. (1999), J Neurosci 19(21):9587--9603; Jahr & Stevens (1990), J Neurosci 10(9):3178--3182.
- post_init()
- step(current)
- Advance one source-grid step and return the sampled spike event.
- reset()
- Restore dynamic state while preserving the configured source profile.
Module neurons.models.non_resetting_lif¶
Class NonResettingLIFNeuron¶
Source-faithful one-timescale MAT(1) non-resetting LIF neuron.
The membrane follows equation 1 of Kobayashi, Tsubo, and Shinomoto
(2009). theta stores the single exponentially decaying spike-history
contribution from equations 2-3; the instantaneous threshold is
omega + theta. A spike raises that history and starts the paper's
2 ms absolute refractory interval, but never resets v.
The paper identifies 50 ms as the optimal MAT(1) threshold timescale but fits threshold amplitude and baseline per neuron. The defaults therefore form a documented numerical specialization, not a universal cell fit.
Reference: R. Kobayashi, Y. Tsubo, and S. Shinomoto, Frontiers in Computational Neuroscience 3:9 (2009), doi:10.3389/neuro.10.009.2009.
- post_init()
- Validate the complete MAT(1) state and parameter contract.
- threshold()
- Return the instantaneous adaptive threshold in millivolts.
- step(current)
- Advance one source MAT(1) sample and return
1on a spike. - reset()
- Restore zero-rest voltage, threshold history, and refractory state.
Module neurons.models.perfect_integrator¶
Class PerfectIntegratorNeuron¶
Perfect integrator with source and preserved SC threshold profiles.
The source profile implements Naud and Gerstner's equations
dV/dt = I(t)/C and V > V_T -> V_r. The exact held-current update is
V(t+h) = V(t) + I*h/C. PerfectIntegratorNeuron() preserves the
historical inclusive SC comparator; use :meth:naud_gerstner_2012 for the
count-bearing source profile.
The normalized defaults are maintained reproducibility choices, not experimental measurements reported by the source.
Reference¶
Naud, R. and Gerstner, W. (2012). The Performance (and Limits) of Simple Neuron Models: Generalizations of the Leaky Integrate-and-Fire Model, section 1.1. doi:10.1007/978-94-007-3858-4_6.
- post_init()
- naud_gerstner_2012(cls)
- Construct the source-equation profile with a strict threshold.
- sc_inclusive_compatibility(cls)
- Construct the preserved inclusive-threshold SC profile.
- step(current)
- Advance one exact held-current step and return a binary event.
- simulate(n_steps, current, backend)
- Advance a batch and return its post-step trace and event count.
- simulate_complete(n_steps, current, backend)
- Return aligned state/event traces and commit valid state atomically.
- reset()
- Apply the source-defined reset operation explicitly.
Class SCInclusivePerfectIntegratorNeuron¶
Count-neutral identity for the preserved inclusive SC recurrence.
- init(v, c_m, v_threshold, v_reset, dt)
Module neurons.models.pernarowski¶
Class PernarowskiNeuron¶
Pernarowski 1994 pancreatic beta-cell burster.
Three coupled ODEs over (v, w, z) with one fast cubic state and
two slower recovery/adaptation variables. The public implementation uses
candidate-first RK4 integration and preserves continuous threshold-crossing
semantics without an artificial reset during normal evolution.
Reference: Pernarowski, M. (1994). SIAM J. Appl. Math. 54:814–832.
- post_init()
- step(current)
- simulate(n_steps, current, backend)
- Advance
n_stepsRK4 updates from the current state, returning(trace, spikes). - reset()
Module neurons.models.persistent_na_neuron¶
Class PersistentNaNeuron¶
Persistent Na⁺ (INaP) neuron — WB base + non-inactivating Na⁺ current.
INaP activates at subthreshold voltages (-60 to -40 mV) and does not inactivate, providing a sustained depolarising drive for subthreshold oscillations, plateau potentials, and burst generation.
p∞ = 1 / (1 + exp(-(v + 48) / 5)) τ_p = 10 + 40 / (1 + ((v + 48) / 10)²)
Reference: Crill (1996) Annu Rev Physiol 58:349; French et al. (1990) Neuroscience 42:363.
- post_init()
- step(current)
- reset()
Module neurons.models.pinsky_rinzel¶
Class PinskyRinzelNeuron¶
Pinsky-Rinzel 1994 two-compartment CA3 pyramidal cell.
Reduction of the 19-compartment Traub CA3 model to a soma compartment
carrying the fast Na⁺/delayed-rectifier K⁺ spike currents and a dendrite
compartment carrying the Ca²⁺, Ca-dependent K⁺ afterhyperpolarisation, and
voltage/Ca-dependent K⁺ currents, coupled by gc. Eight states are
integrated with a fixed-step fourth-order Runge-Kutta scheme; the somatic
sodium activation m is taken at its instantaneous steady state m∞.
The voltages use the physiological convention (rest ≈ −60 mV); reversal potentials and gating rates equal the original rest=0 mV formulation shifted by −60 mV. Parameters and kinetics follow the published model and the ModelDB 35358 reference channels.
Parameters¶
v_s, v_d : float
Somatic and dendritic membrane potential (mV).
h, n, s, c, q : float
Gating variables in [0, 1]: Na⁺ inactivation h, delayed-rectifier
activation n, Ca²⁺ activation s, voltage/Ca-dependent K⁺
activation c, and Ca-dependent afterhyperpolarisation q.
ca : float
Dimensionless dendritic calcium concentration (≥ 0).
cm : float
Membrane capacitance (µF/cm²); default 3.0 per Pinsky & Rinzel (1994).
gc : float
Soma-dendrite coupling conductance (mS/cm²).
p : float
Somatic membrane-area fraction in (0, 1).
g_na, g_kdr, g_ca, g_kahp, g_kc, g_l : float
Maximal conductances (mS/cm²) for the Na⁺, K-DR, Ca²⁺, K-AHP, K-C, and
leak currents.
e_na, e_k, e_ca, e_l : float
Reversal potentials (mV).
dt : float
Integration time step (ms).
v_threshold : float
Somatic voltage at which a spike is registered (mV).
References¶
Pinsky, P.F. & Rinzel, J. (1994). Intrinsic and network rhythmogenesis in a reduced Traub model for CA3 neurons. J. Comput. Neurosci. 1:39–60. doi:10.1007/BF00962717. Reference channel kinetics: ModelDB accession 35358.
- post_init()
- step(current_soma, current_dend)
- Advance one
dtand return 1 on a rising somatic threshold crossing. - reset()
- Restore the published resting initial condition.
Module neurons.models.plant_r15¶
Class PlantR15Neuron¶
Plant 1981 — Aplysia R15 parabolic burster, 5 ODEs.
dV/dt = (-I_Na - I_K - I_Ca - I_L - I_KCa + I_ext) / C dm/dt = (m_inf(V) - m) / tau_m(V) dh/dt = (h_inf(V) - h) / tau_h(V) dn/dt = (n_inf(V) - n) / tau_n(V) dCa/dt = -k_Ca * I_Ca - Ca / tau_Ca
Reference: Plant, R.E. & Kim, M. (1976). Biophys. J. 16:227–244.
- step(current)
- reset()
Module neurons.models.plif¶
Class ParametricLIFNeuron¶
Fang et al. 2021 — Parametric LIF (PLIF) with learnable decay.
V(t+1) = alpha * V(t) * (1 - spike(t)) + I(t) alpha = sigmoid(a) (learnable parameter) spike = Theta(V - threshold)
Reference: Fang, W. et al. (2021). Proc. AAAI Conf. Artif. Intell. 35(3):2661–2669.
- post_init()
- alpha()
- step(current)
- reset()
Module neurons.models.poisson¶
Class PoissonNeuron¶
Generate homogeneous Poisson events in discrete binary time bins.
Parameters¶
rate_hz : float, default=100.0
Non-negative homogeneous event rate in hertz.
dt_ms : float, default=1.0
Positive bin width in milliseconds. Multiple arrivals within one bin
collapse to one event.
seed : int or None, default=0xACE1
Replay seed for the canonical 16-bit LFSR. None draws one concrete
non-zero seed from system entropy and retains it for subsequent resets.
Notes¶
Each accepted bin uses the exact finite-interval event probability
1 - exp(-rate_hz * dt_ms / 1000) and advances the shared LFSR16 by
exactly one trial (eight primitive shifts). The generator therefore models
a binary-bin observation of a homogeneous Poisson process, not an
unbounded within-bin arrival count.
References¶
Gerstner, W., Kistler, W. M., Naud, R., & Paninski, L. (2014). Neuronal Dynamics, Sections 7.2 and 7.7. https://doi.org/10.1017/CBO9781107447615
- post_init()
- Validate physical parameters and initialise the replayable RNG.
- initial_seed()
- Return the concrete seed restored by :meth:
reset. - rng_state()
- Return the live canonical LFSR16 state.
- step(rate_override)
- Advance one binary time bin and return whether an event occurred.
- simulate(n_steps, rate_override, backend)
- Return the binary event trace from Python or one real native backend.
- reset()
- Restore the construction-time replay seed.
Module neurons.models.pospischil¶
Class PospischilNeuron¶
Pospischil et al. 2008 — minimal Hodgkin-Huxley cortical/thalamic neuron.
The membrane potential follows
C dV/dt = -I_Na - I_Kd - I_M - I_L + I_ext
with transient sodium I_Na = g_Na m^3 h (V - E_Na), delayed-rectifier
potassium I_Kd = g_Kd n^4 (V - E_K), the slow voltage-gated potassium
adaptation current I_M = g_M p (V - E_K), and an ohmic leak. The Traub-Miles
activation kinetics are written against the shifted potential V - V_T and the
M current uses the Yamada p_inf/tau_p relaxation. The slow I_M
conductance selects the firing class: g_M = 0.07 regular spiking (default),
g_M = 0 fast spiking, g_M = 0.03 intrinsically bursting.
The production integrator is candidate-first RK4 over the five-state
(V, m, h, n, p) system: every sub-step evaluates the full right-hand side
from one consistent state, forms the RK4 candidate, and commits it only once it
is finite. The historical hard-coded forward-Euler update — which evaluated the
gates and the membrane against mismatched states — remains reachable only through
the explicit integrator="baseline_euler" option for regression comparison.
Reference: Pospischil, M. et al. (2008). Minimal Hodgkin-Huxley type models for different classes of cortical and thalamic neurons. Biol. Cybern. 99:427–441.
- post_init()
- step(current)
- Advance the neuron by one
4 * dtstep and report a threshold crossing. - reset()
- Restore the resting membrane potential and gating defaults.
Module neurons.models.prescott¶
Class PrescottNeuron¶
Prescott 2008 two-state excitability model with M-current tuning.
Reference: Prescott, S.A. et al. (2008). PLoS Comput. Biol. 4:e1000198.
- post_init()
- step(current)
- reset()
Module neurons.models.psn¶
Class ParallelSpikingNeuron¶
k-order sliding Parallel Spiking Neuron — Fang et al. (2023).
Streaming form of the PSN family (paper Eqs. 14–15):
H[t] = sum_{i=0}^{k-1} W_i * X[t-k+1+i], with X[j] = 0 for j < 0 S[t] = Theta(H[t] - v_threshold)
weights[i] is W_i, so weights[k-1] multiplies the newest
input X[t] and weights[0] the oldest retained input X[t-k+1];
the sum is accumulated sequentially from i = 0 to k-1 so every
backend reproduces the same binary64 result bit-for-bit. The
right-continuous Theta(0) = 1 convention follows the paper. No
PSN variant has a reset: firing never clears the input history, and
:meth:reset only re-zeroes the retained inputs. The paper trains
W and v_threshold per task and publishes no universal
default; the uniform W_i = 1/k, v_threshold = 1.0 and
kernel_size = 8 defaults are repository defaults.
Reference: Fang, W., Yu, Z., Zhou, Z., Chen, D., Chen, Y., Ma, Z., Masquelier, T. & Tian, Y. (2023). Parallel Spiking Neurons with High Efficiency and Ability to Learn Long-term Dependencies. NeurIPS 2023. DOI 10.48550/arXiv.2304.12760.
- post_init()
- step(current)
- reset()
Module neurons.models.pv_fast_spiking_neuron¶
Class PVFastSpikingNeuron¶
PV+ (parvalbumin) fast-spiking interneuron (Wang-Buzsáki 1996 + Kv3.1).
The membrane potential follows
C dV/dt = -I_Na - I_K - I_Kv3 - I_L + I_ext
with transient sodium I_Na = g_Na m_inf^3 h (V - E_Na) (instantaneous
activation), delayed-rectifier I_K = g_K n^4 (V - E_K), the fast Kv3.1
current I_Kv3 = g_Kv3 p (V - E_K) that narrows the action potential and
sustains >200 Hz firing without adaptation, and an ohmic leak. The h and
n gates carry the Wang-Buzsáki temperature factor phi.
The production integrator is candidate-first RK4 over the four-state
(V, h, n, p) system: each sub-step evaluates the full right-hand side from
one consistent state, forms the RK4 candidate, and commits it only once finite.
The historical hard-coded forward-Euler update — which staggered the gate and
membrane increments against mismatched states — remains reachable only through
the explicit integrator="baseline_euler" regression option.
Reference: Wang, X.-J. & Buzsáki, G. (1996). Gamma oscillation by synaptic inhibition in a hippocampal interneuronal network model. J. Neurosci. 16:6402–6413.
- post_init()
- step(current)
- Advance the neuron by one 0.5 ms step and report a threshold crossing.
- reset()
- Restore the resting membrane potential and gating defaults.
Module neurons.models.quadratic_if¶
Class QuadraticIFNeuron¶
Quadratic IF with Latham-source and preserved SC profiles.
dv/dt = v² + I Reset when v >= v_peak.
QuadraticIFNeuron() preserves the historical symmetric SC boundary.
:meth:latham_2000 constructs the count-bearing isolated scalar
normalisation of Latham et al. equations (1), (2), and (5a):
v=-1, v_reset=-3, v_peak=31/3, and dt=0.05. Here +1 is
the unstable equilibrium, not the event apex. The exact held-current
Riccati map is a catalogue numerical specialisation of the source ODE.
Reference: Latham, P.E. et al. (2000). J. Neurophysiol. 83:808–827. doi:10.1152/jn.2000.83.2.808.
- post_init()
- Validate the finite ordered state and integration contract.
- latham_2000(cls)
- Construct Latham et al.'s normalized numerical source profile.
- sc_symmetric_compatibility(cls)
- Construct the preserved symmetric finite-boundary SC profile.
- step(current)
- Advance one exact constant-current Riccati-flow update.
- simulate(n_steps, current, backend)
- Advance a batch and return its post-step trace and event count.
- simulate_complete(n_steps, current, backend)
- Return aligned voltage/events and commit valid final state atomically.
- reset()
- Restore the runtime voltage while preserving configured parameters.
Class SCSymmetricQuadraticIFNeuron¶
Count-neutral explicit identity for the preserved symmetric SC profile.
- init(v, v_reset, v_peak, dt)
Module neurons.models.quantum_inspired_lif¶
Class QuantumInspiredLIFNeuron¶
Quantum-inspired LIF with complex amplitude and stochastic firing.
Parameters¶
tau : float Membrane time constant (ms). Default: 20.0. theta : float Firing threshold for |z|. Default: 1.0. dt : float Integration timestep (ms). Default: 0.1. v_reset : float Reset value for z_re and z_im after spike. Default: 0.0. seed : int Initial RNG state for xorshift64. Default: 12345.
- post_init()
- step_complex(i_re, i_im)
- Step with real and imaginary current components.
- step(current)
- Step with real-only current (imaginary = 0).
- reset()
- Reset state to initial conditions.
Module neurons.models.rall_cable¶
Class RallCableNeuron¶
Rall 1962 N-compartment passive cable with an implicit step.
The step solves the sealed-end passive cable operator as a tridiagonal
backward-Euler system with distal current held constant over dt.
State is committed only after the finite candidate solve succeeds.
Reference: Rall, W. (1959). Exp. Neurol. 1:491–527.
- post_init()
- step(current)
- Advance one implicit cable step and return the somatic spike flag.
- reset()
- Reset all compartments to the leak reversal potential.
Module neurons.models.renshaw_cell¶
Class RenshawCell¶
Renshaw cell — spinal inhibitory interneuron for recurrent inhibition.
WB gating core with strong adaptation to produce burst-then-decay response to motor axon collateral input.
Reference: Renshaw (1941); Windhorst (1996) Prog Neurobiol 46(5).
- step(current)
- reset()
Module neurons.models.resonate_and_fire¶
Class ResonateAndFireNeuron¶
Damped complex resonator from Izhikevich (2001).
The source defines z = x + i y and
dz/dt = (b + i * omega) * z + I.
x is current-like and y is voltage-like. A spike is emitted on an
upward sampled crossing of y = threshold. The source post-spike reset
is z = i; the generalized implementation therefore installs
(x, y) = (0, threshold). The maintained numerical step is the exact
constant-real-input flow over one dt interval.
Defaults b=-1, omega=10, and threshold=1 are the parameter set
used for most illustrations in the source paper. dt=0.01 is an
implementation sampling interval, not a parameter asserted by the paper.
Reference¶
Izhikevich, E. M. (2001). Resonate-and-fire neurons. Neural Networks 14(6-7), 883-894. https://doi.org/10.1016/S0893-6080(01)00078-8
- post_init()
- Normalise scalar fields and reject an invalid configuration.
- step(current)
- Advance one exact-flow interval and return a binary spike event.
- simulate(current)
- Run one atomic piecewise-constant-input batch on a maintained backend.
- reset()
- Restore the quiescent initial state while preserving parameters.
Module neurons.models.rulkov_map¶
Class RulkovMapNeuron¶
Rulkov (2002) three-branch spiking-bursting map.
current is the paper's fast beta_n input specialization. sigma
remains the slow-nullcline control parameter of the autonomous map. The
default state and sigma=-1.6 form SC-NeuroCore's quiescent operating
profile; they are not represented as a source figure's unique defaults.
- post_init()
- step(current)
- Advance one source-map iteration and report the reset-branch event.
- simulate(n_steps, current, backend)
- Advance a failure-atomic batch and return
(x_trace, events). - reset()
- Restore the repository operating profile's initial state.
Module neurons.models.sc_adaptive_threshold_map_neuron¶
Class SCAdaptiveThresholdMapNeuron¶
Bounded SC sigmoid map with a slow adaptive threshold.
The simultaneous update is
x' = clamp(-x + k*sigmoid(4*(x-theta)) + current, -5, 5)
theta' = clamp(beta*theta + gamma*H(x-theta_spike), -5, 5).
The returned event is an upward crossing of x_threshold by x'.
- post_init()
- Normalise scalar fields and reject invalid configuration.
- step(current)
- Advance atomically and return an upward-threshold crossing event.
- simulate(current)
- Run an atomic complete-state batch on a maintained backend.
- reset()
- Restore both project-model states while preserving parameters.
Module neurons.models.sc_chaotic_map_neuron¶
Class SCChaoticMapNeuron¶
Run the bounded two-state SC engineering map.
Both candidates read the previous x and y and commit
simultaneously. The returned event is an upward crossing of
x_threshold. This project-defined recurrence has no publication or
biological-model attribution; :class:AiharaMapNeuron is the distinct
source-faithful paper model.
- post_init()
- step(current)
- Commit one simultaneous bounded update and return an upward crossing.
- simulate(current)
- Run an atomic batch on a parity-checked maintained backend.
- reset()
- Clear both states while preserving the configured parameters.
Module neurons.models.sc_clipped_logistic_bursting_map¶
Class SCClippedLogisticBurstingMapNeuron¶
Retained project-defined two-state clipped-logistic bursting recurrence.
x(n+1) = f(x(n)) - y(n) + I y(n+1) = y(n) + epsilon * (x(n) - sigma)
f(x) = ax(1 - x) (logistic-like fast dynamics)
Bursting arises from slow y modulation of fast x.
This is a project-defined recurrence without whole-model publication attribution.
- step(current)
- simulate(n_steps, current, backend)
- Advance
n_stepsfrom the current state, returning(trace, spikes). - reset()
Module neurons.models.sc_clipped_rational_recovery_map¶
Class SCClippedRationalRecoveryMapNeuron¶
Retained clipped rational-recovery project recurrence.
- post_init()
- step(current)
- Advance once; rejected candidates leave both states unchanged.
- simulate(n_steps, current, backend)
- Return the post-step x trace and upward-crossing event count.
- reset()
- Restore the retained project initial state.
Module neurons.models.sc_decoupled_adaptation_ion_mass¶
Class SCDecoupledAdaptationIonMassNeuron¶
Retain the former project ion-mass recurrence without paper attribution.
- post_init()
- step(coupling)
- Advance the retained project recurrence atomically.
- reset()
- Restore dynamic state without changing configuration.
Module neurons.models.sc_exponential_tc_lif¶
Class SCExponentialTwoCompartmentLIFNeuron¶
SC exponential two-compartment LIF — preserved engine recurrence.
Historical production-engine model formerly published under the
TwoCompartmentLIFNeuron name. It is structurally distinct from
both the Zhang et al. (2024) TC-LIF and the SC leaky variant:
per-step exponential decay factors, additive wholesale coupling of
the freshly decayed dendrite into the soma, per-compartment external
currents, and a HARD soma reset:
V_d[t] = exp(-dt/tau_d) * V_d[t-1] + I_dend[t] V_s[t] = exp(-dt/tau_s) * V_s[t-1] + I_soma[t] + kappa * V_d[t] Spike when V_s >= theta; V_s -> V_reset, V_d unchanged.
Count-neutral SC identity: it consumes no source-catalogue slot and
makes no publication-exact claim. The production Rust engine keeps
this recurrence verbatim as SCExponentialTwoCompartmentLIF,
anchored to the pre-2026-08-27 built engine trajectories.
- post_init()
- step(i_soma, i_dend)
- reset()
Module neurons.models.sc_four_state_glif¶
Class SCFourStateGLIFNeuron¶
Historical four-state GLIF project neuron.
The four dynamic states are advanced with candidate-first RK4. Spike reset is applied only after the finite candidate reaches the adaptive threshold. This count-neutral project recurrence has no whole-model paper attribution.
- post_init()
- step(current)
- simulate(n_steps, current, backend)
- Advance
n_stepsRK4 updates from the current state, returning(trace, spikes). - reset()
Module neurons.models.sc_leaky_tc_lif¶
Class SCLeakyTwoCompartmentLIFNeuron¶
SC leaky two-compartment LIF — preserved repository recurrence.
Historical repository model formerly published under the
TwoCompartmentLIFNeuron name. It is structurally distinct from
the Zhang et al. (2024) TC-LIF: both compartments leak toward
v_rest, the soma couples one-way to the dendrite through
kappa * (v_d - v_s), each compartment takes its own external
current, and the soma HARD-resets to v_reset on threshold
crossing while the dendrite is untouched.
Soma: tau_s dV_s/dt = -(V_s - V_rest) + kappa*(V_d - V_s) + I_soma Dendrite: tau_d dV_d/dt = -(V_d - V_rest) + I_dend Spike when V_s >= theta; V_s -> V_reset, V_d unchanged.
Count-neutral SC identity: it consumes no source-catalogue slot and makes no publication-exact claim. Finite-input trajectories are preserved bit-for-bit from the pre-2026-08-27 implementation.
- post_init()
- step(i_soma, i_dend)
- reset()
Module neurons.models.sc_non_resetting_adaptive_lif¶
Class SCNonResettingAdaptiveLIFNeuron¶
Retained SC exact-relaxation adaptive LIF with no voltage reset.
This is the historical project recurrence formerly exposed as
NonResettingLIFNeuron. Both voltage and threshold use exact affine
relaxation over one configured sample. A level event raises threshold by
delta_theta; voltage is never reset and no refractory gate is applied.
The recurrence is project-defined and intentionally carries no external
paper attribution. Use :class:NonResettingLIFNeuron for source MAT(1).
- post_init()
- Validate the complete project recurrence before first use.
- step(current)
- Advance one exact-relaxation sample with atomic failure.
- reset()
- Restore voltage and adaptive threshold to their configured rests.
Module neurons.models.sc_normalized_energy_lif¶
Class SCNormalizedEnergyLIFNeuron¶
Retain the project's normalized two-state energy-gated LIF exactly.
- post_init()
- Validate the retained SC state before first use.
- step(current)
- Advance one retained exact-flow sample and return its event.
- reset()
- Restore the retained normalized resting state.
Module neurons.models.sc_resetting_mat¶
Class SCResettingMATNeuron¶
SC candidate-first RK4 adaptive-threshold neuron with voltage reset.
This project model preserves the historical SC-NeuroCore MATNeuron
recurrence under an explicit identity. It is not attributed to the
non-resetting MAT* equations of Kobayashi et al. (2009).
- post_init()
- Validate the numerical contract before the first integration step.
- step(current)
- Advance one SC resetting-MAT step and return
1on a spike. - reset()
- Restore voltage and adaptive thresholds to the SC resting state.
Module neurons.models.sc_resetting_psn¶
Class SCResettingParallelSpikingNeuron¶
SC resetting windowed neuron — preserved repository recurrence.
Historical repository model formerly published under the
ParallelSpikingNeuron name. It is structurally distinct from the
Fang et al. (2023) sliding PSN in two ways: the retained-input
buffer is zeroed whenever the neuron fires (the PSN family has no
reset), and a replaced kernel is dotted against circular buffer
slots rather than time-ordered inputs, so for non-uniform kernels
the weight-to-input pairing rotates with the write pointer. During
warm-up the score divides by the full kernel_size, which for
the default uniform kernel matches zero-padded pre-history.
score[t] = kernel[:n] . buffer[:n], n = min(t+1, kernel_size) spike when score >= v_threshold, then buffer[:] = 0.
Count-neutral SC identity: it consumes no source-catalogue slot and makes no publication-exact claim. Finite-input trajectories are preserved bit-for-bit from the pre-2026-08-27 implementation.
- post_init()
- step(current)
- reset()
Module neurons.models.sc_resetting_wilson_hr¶
Class SCResettingWilsonHRNeuron¶
Preserve the former unit-capacitance, hard-reset project recurrence.
This model is an SC-NeuroCore specialisation. It is not attributed to the
continuous Wilson (1999) equations, which are implemented by
:class:~sc_neurocore.neurons.models.wilson_hr.WilsonHRNeuron.
- post_init()
- step(current)
- Advance one project-RK4 step and apply the historical hard reset.
- simulate(n_steps, current, backend)
- Run a failure-atomic batch through a selected maintained runtime.
- reset()
- Restore the historical project state.
Module neurons.models.sc_scaled_reset_adaptive_if¶
Class SCScaledResetAdaptiveIFNeuron¶
Historical four-state project recurrence with a scaled voltage reset.
- post_init()
- step(current)
- Advance the retained recurrence and return its level event.
- simulate(n_steps, current, backend)
- Advance the retained trajectory through one explicit runtime.
- reset()
- Restore the retained default state without changing parameters.
Module neurons.models.sc_sigma_delta_accumulator¶
Class SCSigmaDeltaAccumulatorNeuron¶
Retained bipolar accumulate/one-quantum-subtract recurrence.
This is exactly the historical project behavior formerly exposed as
SigmaDeltaNeuron. It emits at most one signed event per sample and
carries any remaining threshold excess forward. It is project-defined and
intentionally carries no external paper attribution.
- post_init()
- step(current)
- Advance the frozen bipolar project recurrence by one sample.
- reset()
- Clear the accumulator while retaining its threshold.
Module neurons.models.sc_six_state_thalamocortical¶
Class SCSixStateThalamocorticalNeuron¶
Preserved SC six-state thalamocortical oscillator.
A conductance-based cell with fast Na⁺ (instantaneous m_∞, dynamic
inactivation h_na), delayed-rectifier K⁺ (n_k), a hyperpolarisation-
activated Ih (m_h), a low-threshold T-type Ca²⁺ current (instantaneous
m_T, dynamic inactivation h_t), a sodium-dependent K⁺ current
(I_KNa gated by intracellular na_i through a Hill function), and an
ohmic leak — the six-state (V, h_na, n_k, m_h, h_t, na_i) system. The
intracellular sodium accumulates from the sodium current and is removed by a
saturating Na/K pump.
The production integrator is candidate-first RK4 over the six-state system:
each sub-step evaluates the full right-hand side from one consistent state,
forms the RK4 candidate, and commits it only once finite. The historical
hard-coded forward-Euler update — which advanced the gates from the old
voltage and then the voltage and sodium from the freshly updated gates,
mixing inconsistent states — remains reachable only through the explicit
integrator="baseline_euler" regression option.
The sodium concentration is clamped to be non-negative once per committed
step, matching the preserved SC recurrence. The conductance powers use explicit
multiplication and the I_KNa Hill exponent 3.5 is evaluated as
b·b·b·sqrt(b) (an IEEE-754 exact decomposition of b**3.5) so the
Rust, Julia, Go, and Mojo kernels reproduce the trajectory bit-for-bit
rather than depending on a per-platform pow implementation.
This recurrence is retained for compatibility with earlier SC-NeuroCore releases. It is deliberately not attributed to Hill and Tononi (2005), whose source model is a hybrid integrate-and-fire system with a dynamic threshold.
- post_init()
- step(current)
- Advance the neuron by one
dtstep and report a threshold crossing. - reset()
- Restore the resting potential, gating defaults, and sodium baseline.
Module neurons.models.sc_stochastic_rate_adaptation¶
Class SCStochasticRateAdaptationNeuron¶
SC logistic rate adaptation with exponential-hazard spike sampling.
This count-neutral project model preserves the former BendaHerzNeuron
behavior. It is not attributed to the deterministic Benda–Herz phase
generator.
- post_init()
- step_with_uniform(current, uniform)
- Advance using an explicit uniform variate for backend parity.
- step(current)
- reset()
Module neurons.models.sc_three_state_phantom¶
Class SCThreeStatePhantomBurster¶
Retained project phantom recurrence with two slow variables.
C dV/dt = -(I_Ca + I_K + I_s1 + I_s2 + I_L) + I_ext ds1/dt = (s1_inf(V) - s1) / tau_s1 ds2/dt = (s2_inf(V) - s2) / tau_s2
Two slow variables (s1, s2) with different timescales produce bursting via a phantom slow manifold.
This count-neutral compatibility model preserves the former
BertramPhantomBurster behavior. It is not the four-state Bertram et al.
publication model and carries no paper attribution.
- post_init()
- step(current)
- reset()
Module neurons.models.sc_triangular_mckean¶
Class SCTriangularMcKeanNeuron¶
Retained SC triangular piecewise-linear FitzHugh-Nagumo oscillator.
The model evolves the two-state ODE using candidate-first RK4 while preserving the three piecewise-linear voltage branches of McKean's analytically tractable Nagumo equation.
This project recurrence is not attributed to McKean's Heaviside system.
- post_init()
- step(current)
- simulate(n_steps, current, backend)
- Advance
n_stepsRK4 updates from the current state, returning(trace, spikes). - reset()
Module neurons.models.sc_unit_capacitance_respiratory¶
Class SCUnitCapacitanceRespiratoryNeuron¶
Retain the historical SC respiratory recurrence without paper attribution.
The legacy implementation omitted the Butera Model 1 whole-cell
capacitance divisor, which is equivalent to fixing capacitance to one in
the repository's RK4 recurrence. This count-neutral identity preserves
that established timing and event behavior while the literature-labelled
class uses the source C = 21 pF equation.
Module neurons.models.sc_upward_crossing_rulkov_map¶
Class SCUpwardCrossingRulkovMapNeuron¶
Retained configurable upward-crossing observation convention.
- post_init()
- step(current)
- Advance once and report the historical rising threshold crossing.
- simulate(n_steps, current, backend)
- Advance a failure-atomic retained batch and return trace plus events.
Module neurons.models.sc_wb_nmda_magnesium_block¶
Class SCWBNMDAMagnesiumBlockNeuron¶
Retained SC Wang--Buzsaki plus input-driven NMDA recurrence.
The magnesium block is the Jahr--Stevens component and the fast-spiking membrane uses Wang--Buzsaki rates. The saturating current-to-gate drive, asymmetric gate relaxation, threshold reset, and their combination are an SC-NeuroCore project recurrence rather than a published neuron model.
- post_init()
- step(current)
- reset()
Module neurons.models.sfa¶
Class SFANeuron¶
Benda-Herz spike-frequency adaptation IF with RK4 candidates.
Reference: Benda, J. & Herz, A.V.M. (2003). Neural Comput. 15:2523–2564.
The membrane and adaptation conductance state is advanced as a coupled
(v, g_sfa) RK4 candidate. The candidate is committed only after finite
and envelope checks pass. A spike resets voltage and adds delta_g to
the RK4 adaptation candidate.
- post_init()
- step(current)
- Advance one candidate-first RK4 timestep.
- reset()
- Restore voltage to rest and clear adaptation conductance.
Module neurons.models.sherman_rinzel_keizer¶
Class ShermanRinzelKeizerNeuron¶
Sherman, Rinzel & Keizer 1988 reduced pancreatic beta-cell burster.
- step(current)
- Advance one constant-current RK4 step and return threshold crossing.
- reset()
Module neurons.models.siegert¶
Class SiegertTransferFunction¶
Siegert 1951 — mean-field LIF firing rate.
Analytical stationary firing rate of a LIF neuron driven by Gaussian white noise: r = [tau_rp + tau_m * sqrt(pi) * integral(exp(u^2)*(1+erf(u)), u_reset..u_thresh)]^{-1} Uses Gauss-Hermite quadrature approximation.
Reference: Siegert, A.J.F. (1951). Phys. Rev. 81:617–623.
- post_init()
- step(current)
- Return instantaneous firing rate (Hz) for given mean input current.
- reset()
Module neurons.models.sigma_delta¶
Class SigmaDeltaNeuron¶
Discrete-time specialization of Yoon's APSDM encoder.
sigma is the output of the disclosed integrating prefilter and
reconstruction is the local feedback signal. Each sample implements
equations 20-27 and the exponentially decaying reconstruction of equation
40 from WO2016022241A1: integrate the input, decay the reconstruction,
compare their difference with the upper threshold delta / 2, then add
one reconstruction quantum delta for a unipolar event.
This clocked specialization is source-bound but does not claim exact
continuous-time event timing. The former bipolar accumulator is retained
separately as :class:SCSigmaDeltaAccumulatorNeuron.
Reference: Y. C. Yoon, IEEE TNNLS 28(5), 2017, doi:10.1109/TNNLS.2016.2526029; primary equations WO2016022241A1.
- post_init()
- Validate the complete encoder state and configuration.
- error()
- Return the current prefilter-minus-reconstruction error.
- step(current)
- Advance one atomic sampled APSDM transition and return 0 or 1.
- reset()
- Clear both dynamic encoder states while retaining configuration.
Module neurons.models.sigmoid_rate¶
Class SigmoidRateNeuron¶
Scalar rate relaxation with a stable logistic transfer.
tau dr/dt = -r + sigma(beta * (input - theta))
Wilson and Cowan (1972) derive the coupled population framework that
motivates this reduced single-unit motif. The complete excitatory and
inhibitory model is represented separately by WilsonCowanUnit.
- post_init()
- step(current)
- simulate(n_steps, current, backend)
- Return a post-step rate trace through one maintained backend.
- reset()
- Restore the dynamic rate without changing configuration.
Module neurons.models.sk_neuron¶
Class SKNeuron¶
SK (Small Conductance Ca²⁺-Activated K⁺) channel neuron.
Wang-Buzsáki base extended with an SK (KCa2.x) current that depends solely on intracellular Ca²⁺ (no voltage dependence). SK channels have slower kinetics than BK and produce the medium afterhyperpolarisation (mAHP) lasting 50–200 ms.
SK∞ = [Ca²⁺]² / ([Ca²⁺]² + 0.25) (Hill function, n=2) τ_Ca = 150 ms (slower than BK's 50 ms)
Reference: Stocker (2004) Nat Rev Neurosci 5:758–770; Wang & Buzsáki (1996) base model. The threshold-reset event, the spike-triggered Ca²⁺ increment, and the specific Hill constants are repository-specific specialisations of that review material, not a publication-exact recurrence.
- post_init()
- step(current)
- reset()
Module neurons.models.spike_response¶
Class SpikeResponseNeuron¶
Spike Response Model (SRM0) — kernel-based, no ODEs.
v(t) = η(t - t_last) + Σ κ(t - t_in) · w Spike when v(t) ≥ threshold. Gerstner 1995.
Reference: Gerstner, W. (1995). Phys. Rev. E 51:738–758.
- post_init()
- step(weighted_input)
- reset()
Module neurons.models.spinnaker2¶
Class SpiNNaker2Neuron¶
TU Dresden / SpiNNaker2 2024 — ARM Cortex-M4F software LIF.
Fixed-point LIF on M4F with exponential decay via integer multiply-shift. Includes refractory counter and configurable precision.
Reference: Mayr, C. et al. (2019). Proc. DATE 2019: 1547–1552.
- step(current)
- reset()
Module neurons.models.spinnaker_lif¶
Class SpiNNakerLIFNeuron¶
SpiNNaker LIF with exact constant-current membrane flow.
The SpiNNaker software LIF model evolves one membrane state v under a
constant input current plus tonic i_offset during each integration
interval. SC-NeuroCore evaluates that linear ODE analytically instead of
using forward Euler, while retaining the documented hard threshold, reset,
and absolute refractory timer semantics.
References¶
Furber, S. B. et al. (2014). The SpiNNaker Project. Proceedings of the IEEE, 102(5), 652-665.
- post_init()
- Validate and normalise public scalar parameters.
- step(current)
- Advance one exact-flow step and return a binary spike indicator.
- reset()
- Restore voltage and refractory state to the documented rest state.
Module neurons.models.srm0¶
Class SRM0Neuron¶
Spike Response Model with exact constant-current kernel flow.
The zeroth-order Spike Response Model keeps membrane potential v and a
refractory afterhyperpolarisation kernel eta. During one step, external
current is held constant and the coupled linear system for (v, eta) is
integrated analytically. This avoids the first-order membrane Euler error
while preserving the SRM0 threshold/reset semantics.
Parameters¶
v:
Membrane potential state.
v_rest:
Rest potential and post-spike voltage reset.
v_threshold:
Spike threshold. A spike is emitted when the exact-flow candidate
reaches or exceeds this value.
tau_m:
Membrane time constant. Must be positive and finite.
tau_eta:
Refractory-kernel decay time constant. Must be positive and finite.
eta_reset:
Positive refractory-kernel amplitude. On spike, eta is set to
-eta_reset.
resistance:
Current-to-voltage gain.
dt:
Integration step. Must be positive and finite.
Raises¶
TypeError If a scalar parameter is not numeric. ValueError If a parameter is non-finite or a positive contract is violated.
References¶
Gerstner, W., & Kistler, W. M. (2002). Spiking Neuron Models: Single Neurons, Populations, Plasticity. Cambridge University Press, chapter 4.
- post_init()
- Initialise private kernel state after validating public parameters.
- step(current)
- Advance one exact-flow SRM0 step.
- reset()
- Restore voltage, refractory kernel, and internal clock state.
- get_state()
- Return the current diagnostic SRM0 state.
Module neurons.models.sst_neuron¶
Class SSTNeuron¶
SST+ (somatostatin) low-threshold spiking interneuron.
Pospischil et al. 2008 LTS parameterisation: fast Na⁺ and delayed-rectifier
K⁺ for the spike, an M-current (Kv7) for spike-frequency adaptation, a
low-threshold T-type Ca²⁺ current for rebound bursting, Ih for the
hyperpolarisation sag, and an ohmic leak — the seven-state
(V, m, h, n, p, s, r) system (T-type activation m_T is instantaneous).
The sodium and potassium activation rates follow the Traub-Miles
x/(exp(±x/k)-1) form and use the L'Hôpital limit at the removable
singularity. The β_m numerator is the published V - V_T - 40 offset; an
earlier revision shared the -17 offset of α_h, which lowered β_m enough to
drive the cell into depolarisation block (it fired three spikes then stuck near
threshold for any stimulus). The corrected kinetics restore a monotone
frequency-current relation.
The production integrator is candidate-first RK4 over the seven-state system:
each sub-step evaluates the full right-hand side from one consistent state,
forms the RK4 candidate, and commits it only once finite. The historical
hard-coded forward-Euler update — which staggered the gate and membrane
increments against mismatched states — remains reachable only through the
explicit integrator="baseline_euler" regression option.
Reference: Pospischil, M. et al. (2008). Minimal Hodgkin-Huxley type models for different classes of cortical and thalamic neurons. Biol. Cybern. 99:427–441.
- post_init()
- step(current)
- Advance the neuron by one
4 * dtstep and report a threshold crossing. - reset()
- Restore the resting potential and gating defaults.
Module neurons.models.stellate_cell¶
Class StellateCell¶
Cerebellar stellate cell — fast-spiking molecular layer interneuron.
WB Na⁺/K⁺ core + Kv3.1 for narrow APs. Feedforward inhibition onto Purkinje cell dendrites. Smaller than basket cells.
Reference: Sultan & Bower (1999) J Comp Neurol 409:63; Häusser & Clark (1997) Neuron 19:665.
- post_init()
- step(current)
- reset()
Module neurons.models.stochastic_if¶
Class StochasticIFNeuron¶
Brunel & Hakim 1999 — Ornstein-Uhlenbeck driven IF.
Reference: Tuckwell, H.C. (1988). Introduction to Theoretical Neurobiology, Vol. 2. Cambridge Univ. Press.
- post_init()
- step(current)
- reset()
Module neurons.models.superspike_neuron¶
Class SuperSpikeNeuron¶
Zenke & Ganguli 2018 — LIF with SuperSpike surrogate gradient.
Uses Van Rossum filtered eligibility traces and a smooth surrogate gradient sigma'(V) = 1/(beta * |V - V_th| + 1)^2.
Reference: Zenke, F. & Ganguli, S. (2018). Neural Comput. 30:1514–1541.
- post_init()
- surrogate_grad()
- step(current)
- reset()
Module neurons.models.tc_lif¶
Class TwoCompartmentLIFNeuron¶
TC-LIF — Zhang et al. (2024) two-compartment spiking neuron.
Discrete map (paper Eqs. 10–12, exact ordering U_D → U_S → S):
U_D[t] = U_D[t-1] + beta1 * U_S[t-1] + I[t] - gamma * S[t-1] U_S[t] = U_S[t-1] + beta2 * U_D[t] - v_th * S[t-1] S[t] = Theta(U_S[t] - v_th)
One external input I[t] enters the dendritic compartment; both
compartments reset softly through the delayed spike S[t-1]
(subtraction terms). beta1 = -sigmoid(c1) and
beta2 = sigmoid(c2) are trained per task in the paper, so
beta1 in (-1, 0) and beta2 in (0, 1); defaults here are the
published S-MNIST feedforward profile (Table 5), and every Table 5
profile is exposed via :data:TC_LIF_PROFILES /
:meth:from_profile. The right-continuous Theta(0) = 1
convention and the [0, 10] public bound on gamma are repository
specialisations.
Reference: Zhang, S., Yang, Q., Ma, C., Wu, J., Li, H. & Tan, K.C. (2024). AAAI 38(15):16838–16847. DOI 10.1609/aaai.v38i15.29625.
- post_init()
- from_profile(cls, profile)
- Construct the neuron from a named Table 5 profile.
- step(i_ext)
- reset()
Module neurons.models.terman_wang¶
Class TermanWangOscillator¶
Terman & Wang 1995 relaxation oscillator for LEGION networks.
The model evolves a fast excitatory variable v and slow recovery
variable w under the published cubic/sigmoid ODE. Runtime integration
uses candidate-first RK4 so invalid derivatives or candidates cannot poison
state.
Reference: Terman, D. & Wang, D.L. (1995). Physica D 81:148-176.
- post_init()
- step(current)
- simulate(n_steps, current, backend)
- Advance
n_stepsRK4 updates from the current state, returning(trace, spikes). - reset()
Module neurons.models.theta¶
Class ThetaNeuron¶
Theta neuron — canonical Type-I on the unit circle.
dθ/dt = (1 - cos θ) + (1 + cos θ) · I Spike when θ crosses π. Ermentrout & Kopell 1986.
Reference: Ermentrout, G.B. & Kopell, N. (1986). SIAM J. Appl. Math. 46:233–253.
This is the paper's constant-parameter equation (2.5), or equation (3.3)
under a frozen slow drive. It is not the full coupled parabolic-bursting
system. current is the source's dimensionless parameter a.
simulate_complete exposes aligned phase/event packets through the
Python reference and all four compiled acceleration lanes.
- post_init()
- step(current)
- simulate(n_steps, current, backend)
- Return post-step phase plus aggregate event count through one backend.
- simulate_complete(n_steps, current, backend)
- Return aligned phase/events and atomically commit the final phase.
- reset()
- Restore the runtime phase while preserving the integration step.
Module neurons.models.threshold_linear_rate¶
Class ThresholdLinearRateNeuron¶
Threshold-linear continuous-rate transfer with cached output.
Parameters¶
r: Initial cached output rate. It must be finite and non-negative. theta: Finite input threshold. gain: Finite, non-negative slope above threshold.
Notes¶
Each call evaluates gain * max(0, current - theta) directly. No time
integration or hidden history is part of this model.
- post_init()
- step(current)
- Evaluate one finite input and atomically cache the resulting rate.
- simulate(n_steps, current, backend)
- Return a post-evaluation rate trace through one maintained backend.
- reset()
- Clear the cached output while preserving threshold and gain.
Module neurons.models.traub_miles¶
Class TraubMilesNeuron¶
Traub & Miles 1991 — reduced hippocampal CA3 pyramidal.
Reference: Traub, R.D. & Miles, R. (1991). Neuronal Networks of the Hippocampus. Cambridge Univ. Press.
- post_init()
- step(current)
- reset()
Module neurons.models.truenorth¶
Class TrueNorthNeuron¶
Merolla 2014 — IBM TrueNorth digital neuron.
Reference: Merolla, P.A. et al. (2014). Science 345:668–673.
- step(weighted_input)
- reset()
Module neurons.models.tsodyks_markram¶
Class TsodyksMarkramNeuron¶
Tsodyks & Markram 1997 — LIF with short-term synaptic plasticity.
LIF membrane: tau_m dV/dt = -(V - V_rest) + RI_syn + RI_ext dx/dt = (1 - x)/tau_d - uxdelta(spike_in) du/dt = (U - u)/tau_f + U(1-u)delta(spike_in) I_syn = A * u * x on presynaptic spike
Reference: Tsodyks, M. et al. (1998). Neural Comput. 10:821–835.
- step(current, presynaptic_spike)
- reset()
Module neurons.models.ttype_ca_neuron¶
Class TTypeCaNeuron¶
T-type Ca²⁺ (IT) neuron — WB base + low-voltage-activated Ca²⁺ current.
IT activates at subthreshold voltages (-65 to -50 mV) and inactivates slowly. When de-inactivated by hyperpolarisation, IT produces a low-threshold spike (LTS) that can trigger a burst of Na⁺ spikes.
m_T∞ = 1 / (1 + exp(-(v + 52) / 5)) s∞ = 1 / (1 + exp((v + 81) / 4)) τ_s = 30 + 100 / (1 + exp((v + 75) / 10))
Reference: Huguenard (1996) Annu Rev Physiol 58:329; Destexhe, Bal, McCormick & Sejnowski (1996) J Neurophysiol 76:2049. The WB spiking base follows Wang & Buzsáki (1996) J Neurosci 16:6402; the threshold-reset event and the spike-triggered inactivation collapse (s ×= 0.3) are repository-specific specialisations, not publication-exact claims.
- post_init()
- step(current)
- reset()
Module neurons.models.unipolar_brush_cell¶
Class UnipolarBrushCell¶
Unipolar brush cell (UBC) — excitatory vestibular cerebellum interneuron.
LIF with slow NMDA-like persistent current that prolongs mossy fibre bursts into sustained granule cell activation. Giant 1:1 synapse.
Reference: Mugnaini & Floris (1994) J Comp Neurol 339:174-180 (discovery/anatomy); Diana et al. (2007) J Neurosci 27:3823-3838 (bimodal firing physiology).
- post_init()
- step(current)
- reset()
Module neurons.models.upper_motor_neuron¶
Class UpperMotorNeuron¶
Upper motor neuron — layer 5 pyramidal cell, corticospinal projection.
Pospischil 2008 RS parameterisation with Na⁺, K⁺, M-current (Kv7 for adaptation) + high-threshold Ca²⁺ for dendritic Ca²⁺ spikes.
Reference: Pospischil et al. (2008) Biol Cybern 99:427–441; Larkum (2013) Trends Neurosci 36(3).
- post_init()
- step(current)
- reset()
Module neurons.models.vip_neuron¶
Class VIPNeuron¶
VIP (vasoactive intestinal peptide) irregular-spiking interneuron.
The membrane potential follows
C dV/dt = -I_Na - I_K - I_A - I_L + I_ext
with transient sodium I_Na = g_Na m_inf^3 h (V - E_Na) (instantaneous
activation), delayed-rectifier I_K = g_K n^4 (V - E_K), a transient A-type
I_A = g_A a^3 b (V - E_K) (Kv4) whose slow inactivation produces the firing
accommodation typical of the small high-input-resistance VIP soma, and an ohmic
leak. Every gating variable relaxes through a sigmoidal steady state, so the
right-hand side has no removable singularities.
The production integrator is candidate-first RK4 over the five-state
(V, h, n, a, b) system: each sub-step evaluates the full right-hand side
from one consistent state, forms the RK4 candidate, and commits it only once
finite. The historical hard-coded forward-Euler update — which staggered the
gate and membrane increments against mismatched states — remains reachable only
through the explicit integrator="baseline_euler" regression option.
Reference: Porter, J.T., Cauli, B., Tsuzuki, K., Lambolez, B., Rossier, J. & Audinat, E. (1998). Selective excitation of subtypes of neocortical interneurons by nicotinic receptors. J. Neurosci. 19:5228–5235; Bhatt et al. (2019).
- post_init()
- step(current)
- Advance the neuron by one
4 * dtstep and report a threshold crossing. - reset()
- Restore the resting membrane potential and gating defaults.
Module neurons.models.wang_buzsaki¶
Class WangBuzsakiNeuron¶
Wang-Buzsáki 1996 — fast-spiking GABAergic interneuron.
3 ODEs. Simplified HH with only Na + K delayed rectifier. Designed for gamma (30-80 Hz) oscillation modelling.
Reference: Wang, X.-J. & Buzsáki, G. (1996). J. Neurosci. 16:6402–6413.
- post_init()
- step(current)
- reset()
Module neurons.models.wendling¶
Class WendlingNeuron¶
Wendling et al. 2002 — extended Jansen-Rit with slow GABA_B inhibition.
10 ODEs: 4 populations (pyramidal, excitatory, fast inhibitory, slow inhibitory) x 2 states each + 2 for slow inhibitory PSP. Reproduces epileptiform EEG patterns.
Reference: Wendling, F. et al. (2002). Biol. Cybern. 86:97–108.
- post_init()
- step(p_ext)
- reset()
Module neurons.models.wilson_cowan¶
Class WilsonCowanUnit¶
Normalised Wilson-Cowan excitatory/inhibitory population-rate model.
τ_e dE/dt = -E + S(w_ee·E - w_ei·I + I_ext) τ_i dI/dt = -I + S(w_ie·E - w_ii·I) S(x) = 1/(1 + exp(-a(x-θ))) - 1/(1 + exp(aθ))
This maintained reduction omits the original availability/refractory factors and an independent inhibitory external drive. It preserves the coupled E/I population structure and shifted sigmoid, and advances both continuous rates with fixed-step RK4.
- post_init()
- step(ext_input)
- Advance one finite excitatory-drive sample and return the E rate.
- simulate(n_steps, current, backend)
- Return atomic post-step E/I traces through one maintained backend.
- reset()
- Reset the two rates while preserving the configured dynamics.
Module neurons.models.wilson_hr¶
Class WilsonHRNeuron¶
Wilson's 1999 continuous polynomial cortical-neuron model.
CdV/dt = -(17.81 + 47.71V + 32.63V^2)(V - 0.55) - 26R(V + 0.92) + I dR/dt = (-R + 1.35*V + 1.03) / tau_R
The maintained production path advances the coupled (V, R) state with
candidate-first RK4 and commits only finite candidates. Events are sampled
upward crossings of v_peak; the source flow is continuous and never
resets either state variable.
- post_init()
- step(current)
- simulate(n_steps, current, backend)
- Advance
n_stepsRK4 updates from the current state, returning(trace, spikes). - reset()
Module neurons.models.wong_wang¶
Class WongWangUnit¶
Reduced two-choice decision circuit from Wong and Wang (2006).
Parameters¶
s1, s2 : float, default=0.1 Initial NMDA gating fractions for the two selective populations. noise1, noise2 : float, default=0.0 Initial Ornstein-Uhlenbeck input-current states in nA. tau_s : float, default=0.1 NMDA gating time constant in seconds. tau_ampa : float, default=0.002 AMPA input-noise time constant in seconds. gamma : float, default=0.641 NMDA kinetic conversion factor. j_n : float, default=0.2609 Recurrent self-coupling in nA. j_cross : float, default=0.0497 Cross-population inhibitory coupling magnitude in nA. i_0 : float, default=0.3255 Constant background current in nA. sigma : float, default=0.02 Stationary input-current noise amplitude in nA. dt : float, default=0.0001 Explicit-Euler step in seconds. The default is the 0.1 ms step stated in the paper; the pinned author-lab trial code uses 0.5 ms.
Notes¶
A call returns the firing rates computed from the pre-update state. The
caller-visible random path consumes two standard-normal samples per step.
:meth:step_with_gaussian_samples exposes the same update deterministically
for accelerator parity and source-oracle replay.
- post_init()
- Normalise parameters and validate the initial dynamic state.
- step_with_gaussian_samples(stim1, stim2, xi1, xi2)
- Advance one published Euler/OU step with supplied noise samples.
- step(stim1, stim2)
- Advance one stochastic Euler/OU step.
- simulate(stim1, stim2, xi)
- Run an atomic deterministic-sample batch on one maintained runtime.
- reset()
- Restore the four dynamic states while preserving parameters.
Module neurons.models.yamada¶
Class YamadaNeuron¶
Yamada, Kashimori & Kambara 1989 — subcritical Hopf burster.
3 ODEs: V, n (fast K recovery), q (slow variable for bursting). Exhibits square-wave bursting via slow modulation of a Hopf bifurcation.
Reference: Yamada, W.M. et al. (1989). In: Methods in Neuronal Modeling. MIT Press, pp. 97–133.
- post_init()
- step(current)
- reset()
Module neurons.profile_registry¶
Class ValidatorBinding¶
One declared validator bound to one facet of one profile.
Parameters¶
facet:
Facet name the validator is declared for.
origin:
descriptor (the descriptor's evidence field for the facet) or
schema (the schema's [validation].evidence).
scope:
profile when the validator belongs to this profile (a schema
validator, or a descriptor validator on the class's canonical profile);
class when it is a descriptor validator listed on a non-canonical
profile, where it documents the class but cannot admit the profile.
reference:
Parsed and resolved evidence reference.
- executable()
- Whether the reference names an existing test file or test node.
- admits()
- Whether the validator can admit this profile (executable and profile-scoped).
- to_public_dict()
- Return the JSON projection.
Class FacetRegistryEntry¶
Validator registry of one facet for one profile.
Parameters¶
facet: Facet name. declared: Whether the descriptor declares the facet. status: Readiness status of the facet for this profile. receipt: Newest receipt file name for this profile, empty when none. validators: Every declared validator for the facet, executable or not.
- executable_validators()
- Validators that name an existing test file or node.
- admitting_validators()
- Executable validators scoped to this profile.
- to_public_dict()
- Return the JSON projection.
Class ProfileRow¶
One (class, profile) row of the inventory.
Parameters¶
class_name:
Registered class the profile is bound to.
stem:
Schema stem of the profile.
identity_kind:
Identity kind of the class.
counts_in_source_catalogue:
Whether the class counts in the public source catalogue.
canonical:
Whether this stem is the class's canonical profile (the one Studio and
the generators use).
profile:
Resolved model profile.
descriptor_method, descriptor_dt:
The descriptor's own integration label and step (the hand class's
numerics), empty and None without a descriptor.
method_agreement:
same when the descriptor label equals the profile method,
differs when it names another realisation (a hand class may keep a
different default than its schema profile), no-descriptor otherwise.
readiness:
Readiness record verified for exactly this profile.
registry:
Validator registry per facet.
admission:
admitted, blocked or not-executable.
admission_reasons:
Why the profile is not admitted, empty when admitted.
unvalidated_backends:
Backends the descriptor declares implemented without any validator
field to bind them; reported, not decided, until the native admission
contract defines the field.
- entry(facet)
- Return the registry entry of one facet by name.
- to_public_dict()
- Return the JSON projection with a stable field order.
Function profile_row(identity, stem)¶
Build the inventory row of one bound profile.
Parameters¶
identity:
Identity record of the class.
stem:
One of the identity's bound schema stems.
repo_root:
Repository root the evidence paths are relative to.
receipts:
Newest receipts per (class, facet, profile) as returned by
:func:~sc_neurocore.neurons.facet_receipts.latest_receipts; read
from the receipt store when omitted.
Function profile_inventory()¶
Return one row per bound (class, profile), sorted by class and stem.
Parameters¶
repo_root: Repository root the evidence paths are relative to.
Function validator_registry(rows)¶
Return the validator registry keyed by (class_name, stem).
Function summarise_inventory(rows)¶
Return count summaries over the inventory.
Function method_table()¶
Return the method → exactness → family → lowering mapping table.
Module neurons.readiness¶
Class FacetVerification¶
Verification outcome of one facet for one model.
- to_public_dict()
- Return a JSON-compatible projection.
Class ReadinessRecord¶
Declared and verified readiness of one registered class.
- declared_science_label()
- Declared science tier as
S<n>. - declared_silicon_label()
- Declared silicon tier as
H<n>ornone. - verified_science_label()
- Verified science tier as
S<n>. - verified_silicon_label()
- Verified silicon tier as
H<n>ornone. - facet(name)
- Return the verification of one facet by name.
- to_public_dict()
- Return a JSON-compatible projection with a stable field order.
- evidence_by_field()
- Return the parsed references of every non-empty descriptor evidence field.
Function declared_facets(descriptor)¶
Return which facets a descriptor declares, under tier semantics v1.
The predicates are exactly the anchors :mod:descriptor_tiers credits, so
a declared facet here is a declared rung there.
Function facet_evidence_field(descriptor, spec)¶
Return the raw evidence text the descriptor holds for spec.
Function compiler_subjects(repo_root)¶
Return the compiler subjects shared by every generated-RTL receipt.
Function current_digest(subject, repo_root)¶
Recompute a subject's digest from the current repository, None if absent.
Function derive_subjects(class_name, facet)¶
Derive the current subjects a receipt for facet must cover.
Parameters¶
class_name: Registered class the receipt is for. facet: Facet name. repo_root: Repository root. evidence_refs: Evidence references to take validator and report subjects from; the descriptor's own field for the facet is always included. extra_subjects: Subjects the caller adds: the committed RTL a formal or synthesis lane covers (the recorder resolves it through the formal inventory tool) or a native backend source the registry cannot derive.
Returns¶
tuple[Subject, ...]
Subjects with digests of the current content, de-duplicated by
(kind, path) and sorted.
Function verify_receipt(receipt)¶
Judge one receipt against the current repository.
Returns¶
tuple[FacetStatus, tuple[str, ...], tuple[str, ...]]
(status, changed_subject_paths, problems) where status is
invalid (cannot credit), stale (creditable but a subject
changed or vanished) or bound.
Function verify_model(class_name)¶
Verify every facet of one registered class.
Parameters¶
class_name:
Registered class name (aliases are resolved by the caller).
repo_root:
Repository root the evidence paths are relative to.
receipts:
Newest receipts per (class_name, facet, profile); read from
:data:~sc_neurocore.neurons.facet_receipts.RECEIPT_DIR when omitted.
profile:
Exact schema profile. Without a selection, a multi-profile model cannot
receive a class-wide verified claim from one profile's evidence.
Function readiness_report()¶
Verify every registered class (aliases excluded), keyed by class name.
Function summarise(records)¶
Return count summaries of declared versus verified readiness.
Module neurons.receipt_execution¶
Function evidence_selection_problems(selected, declared)¶
Reject validator selections outside a descriptor's reviewed evidence.
Parameters¶
selected : Sequence[str] Evidence references selected for this particular execution. declared : str Descriptor evidence field containing reviewed files or exact test nodes.
Returns¶
tuple[str, ...] Missing or foreign test selections. A file declaration permits its nodes, but a node declaration does not permit another test in the same file.
Function pytest_command(command)¶
Return whether argv directly invokes pytest, without a shell wrapper.
Parameters¶
command : Sequence[str] Executable and arguments.
Returns¶
bool Whether pytest owns the invocation rather than appearing as an argument.
Function junit_checks(xml)¶
Derive counts and executed validator names from the actual report.
Parameters¶
xml : str Complete pytest JUnit XML retained in a receipt.
Returns¶
tuple[dict[str, int], tuple[str, ...]] Counts derived from testcase elements and their dotted identities.
Raises¶
ValueError If the report is malformed, empty, declares a DTD or entities, or lacks testcase identities. External references are never resolved.
Function execution_problems(command, evidence_refs, validator, counts)¶
Check that a receipt's declared validators actually appear in its run.
Parameters¶
command : Sequence[str] Recorded direct invocation. evidence_refs : Sequence[str] Declared test files or node IDs; prose alone cannot identify a validator. validator : Mapping[str, str] Execution contract and retained JUnit XML. counts : Mapping[str, int] Recorded check totals, compared against the XML testcase elements.
Returns¶
tuple[str, ...] Reasons why this execution cannot credit the scientific claim.
Module neurons.reference_trace_contracts¶
Class FeatureTolerance¶
Absolute and relative tolerance for one scalar trace feature.
Parameters¶
absolute: Absolute error allowed between simulated and reference feature values. relative: Relative error allowed as a fraction of the reference value magnitude.
- accepts(actual, expected)
- Return whether
actuallies inside the configured tolerance.
Class ReferenceTraceProvenance¶
Provenance attached to one reference trace.
Parameters¶
kind:
Reference class, for example analytic_closed_form.
source:
Human-readable source for the reference values.
equation:
Equation or feature-generation statement used to derive the values.
citation:
Optional publication or DOI string when the trace is external.
Class ReferenceTraceProtocol¶
Simulation protocol for one reference trace.
Parameters¶
dt:
Simulation timestep in the units used by the model schema.
steps:
Number of timesteps to execute.
inputs:
Constant keyword inputs passed to UniversalNeuron.step.
state_variables:
State variables to record after each timestep. May be empty for a
genuinely stateless deterministic threshold model; event features are
still recorded.
parameter_overrides:
Optional schema parameter values that define the enrolled operating
profile without changing the bundled schema defaults.
Class ReferenceTraceSpec¶
Committed reference-trace specification.
Parameters¶
name:
Stable corpus identifier.
schema_name:
Bundled UniversalNeuron schema name.
runner:
Production runner name. The v1 corpus supports universal_dsl.
protocol:
Deterministic simulation protocol.
provenance:
Reference source and derivation metadata.
expected_features:
Scalar reference features keyed by stable feature names.
tolerances:
Per-feature tolerance map.
Class TraceSimulationResult¶
Trace and feature values produced by the current implementation.
Parameters¶
name:
Reference-trace name that was simulated.
steps:
Number of executed timesteps.
trace:
Recorded state values after each timestep.
spikes:
Spike indicator emitted by each timestep.
features:
Scalar feature map extracted from trace and spikes.
Class FeatureMismatch¶
One failed scalar-feature comparison.
Parameters¶
feature:
Feature name whose value drifted.
expected:
Reference feature value.
actual:
Current simulation feature value.
tolerance:
Tolerance that was applied.
absolute_error:
Absolute difference between actual and expected.
Class TraceValidationReport¶
Validation report for one reference trace.
Parameters¶
name: Reference-trace name. passed: Whether every expected feature matched within tolerance. simulation: Trace produced by the current implementation. mismatches: Failed feature comparisons, empty on success.
Module neurons.reference_trace_io¶
Function reference_trace_spec_from_payload(payload)¶
Parse and validate a reference-trace corpus payload.
Parameters¶
payload:
JSON-compatible mapping using schema
sc-neurocore.reference-trace.v1.
Returns¶
ReferenceTraceSpec Validated immutable reference-trace specification.
Raises¶
ValueError If any required field is missing, malformed, non-finite, or references an unsupported runner or bundled neuron schema.
Function list_reference_trace_specs()¶
Return all committed deterministic Universal-DSL trace names.
Returns¶
tuple[str, ...] Sorted stable identifiers for every deterministic scalar-feature payload in the corpus. Hand-model and seeded statistical artefacts use dedicated validators, so they are not coerced into this trace contract.
Function load_reference_trace_spec(name)¶
Load one committed reference-trace specification.
Parameters¶
name: Stable corpus identifier.
Returns¶
ReferenceTraceSpec Validated reference-trace specification.
Raises¶
ValueError
If name is not present in the committed corpus.
Module neurons.reference_trace_mutations¶
Class ControlOutcome¶
Result of applying one negative control to one reference trace.
Attributes¶
name : str
Corpus identifier of the trace under control.
mutation : str
Which control was applied.
status : str
detected, refused, undetected or inapplicable.
reason : str
Why the control reached that status, in words an operator can act on.
mismatched_features : int
How many features violated tolerance; zero unless detected.
- caught()
- Return whether this control demonstrated the trace catches the error.
- to_public_dict()
- Return a JSON-safe row for reports and documentation.
Class NegativeControlReport¶
Every control outcome for the committed corpus.
Attributes¶
version : str Negative-control contract version. outcomes : tuple of ControlOutcome One outcome per trace and control.
- for_trace(name)
- Return every outcome recorded for one trace.
- with_status(status)
- Return every outcome with one status.
- uncontrolled_traces()
- Return traces no control could catch — a vacuous trace, if any.
- to_public_dict()
- Return a JSON-safe report of every control outcome.
Function run_negative_control(spec, mutation)¶
Apply one negative control to one reference trace.
Parameters¶
spec : ReferenceTraceSpec
The trace to control. It is never modified; mutations act on copies.
mutation : str
One of :data:MUTATIONS.
Returns¶
ControlOutcome What the control demonstrated, including why it could not apply.
Raises¶
ValueError
mutation is not a known control.
Function negative_control_report(names)¶
Apply every control to every deterministic trace in the corpus.
Parameters¶
names : iterable of str, optional Restrict the report to these traces. Defaults to the whole corpus.
Returns¶
NegativeControlReport One outcome per trace and control, in corpus order.
Module neurons.reference_trace_provenance¶
Class ReferenceTraceAdjudicationError¶
Raised when a trace's provenance cannot be adjudicated.
Class SpecAdjudication¶
How independent one reference trace is, and of what.
Attributes¶
name : str
Corpus identifier of the adjudicated trace.
kind : str
The provenance.kind the trace declares.
derivation : str
How the expected values were produced.
attribution : str
What the formulation is sourced from.
independence : str
The class a public claim about this trace may use.
citation : str or None
The citation as declared.
- meaning()
- Return what this trace's independence class licenses as a claim.
- to_public_dict()
- Return a JSON-safe row for reports and generated documentation.
Class CorpusAdjudication¶
The corpus-wide honest replication boundary.
Attributes¶
version : str Adjudication contract version. rows : tuple of SpecAdjudication One adjudication per deterministic corpus trace, by name.
- counts()
- Return how many traces fall in each independence class.
- by_class(independence)
- Return the trace names in one independence class, sorted.
- to_public_dict()
- Return a JSON-safe report of the whole adjudication.
Function adjudicated_kinds()¶
Return every provenance.kind this build knows how to adjudicate.
Function derivation_of_kind(kind)¶
Return how a declared provenance.kind produced its expected values.
Parameters¶
kind : str
The provenance.kind a trace declares.
Returns¶
str The derivation recorded for that kind.
Raises¶
ReferenceTraceAdjudicationError The kind is not in the adjudicated vocabulary. A new kind is a decision about what a trace proves, so it is declared here rather than accepted as free text.
Function classify_citation(citation)¶
Return what a citation string attributes the formulation to.
Parameters¶
citation : str or None The declared citation.
Returns¶
str
"resolvable_source" for a DOI or URL, "project_retained" when the
citation names this project's own recurrence, and "named_source"
otherwise — a publication named without a locator resolvable from here.
Raises¶
ReferenceTraceAdjudicationError The citation is absent. Every trace states what it is derived from; an unstated source cannot be adjudicated, and silently treating it as external is the overstatement this module exists to prevent.
Function adjudicate_spec(spec)¶
Adjudicate one reference trace's independence.
Parameters¶
spec : ReferenceTraceSpec A loaded deterministic corpus trace.
Returns¶
SpecAdjudication Derivation, attribution and the independence class a claim may use.
Raises¶
ReferenceTraceAdjudicationError
The declared provenance.kind is not in the adjudicated vocabulary,
or no citation is declared.
Notes¶
A citation naming the project's own recurrence demotes the trace to
project_formulation whatever the declared kind says. A hand re-derivation
of a recurrence this repository invented is independent of the
implementation, but there is no published formulation for it to be
independent of.
Function adjudicate_corpus()¶
Adjudicate every deterministic trace in the committed corpus.
Returns¶
CorpusAdjudication The honest replication boundary: which identities rest on a published source and which rest on this repository's own formulation.
Raises¶
ReferenceTraceAdjudicationError Any trace declares an unadjudicated kind or no citation.
Module neurons.reference_trace_runner¶
Function simulate_reference_trace(spec_or_name)¶
Run a reference-trace protocol through UniversalNeuron.
Parameters¶
spec_or_name: Reference-trace specification or committed corpus name.
Returns¶
TraceSimulationResult Recorded state trace, spike sequence, and extracted feature map.
Function validate_reference_trace(name)¶
Validate one committed reference trace by name.
Parameters¶
name: Stable corpus identifier.
Returns¶
TraceValidationReport Feature-level validation report.
Function validate_reference_trace_spec(spec)¶
Validate one in-memory reference-trace specification.
Parameters¶
spec: Reference-trace specification to simulate and compare.
Returns¶
TraceValidationReport Feature-level validation report.
Function validate_all_reference_traces()¶
Validate every committed reference trace.
Returns¶
tuple[TraceValidationReport, ...] Sorted reports for the current corpus.
Function extract_trace_features(trace, spikes)¶
Return the scalar features a reference trace pins.
This is the whole comparison surface: a trace constrains the model exactly as far as these features constrain it. Negative controls extract features the same way, so a control and the production validator can never disagree about what was measured.
Parameters¶
trace : mapping of str to tuple of float Recorded value sequence per state variable. spikes : tuple of int Emitted event per timestep.
Returns¶
mapping of str to float
spike_count, first_spike_step (-1 when silent) and
final/min/max/mean per recorded state variable.
Module neurons.sc_izhikevich¶
Class SCIzhikevichNeuron¶
Stochastic Izhikevich neuron (software-only).
Standard Izhikevich model (IEEE TNN 14(6), 2003): v' = 0.04v^2 + 5v + 140 - u + I + noise u' = a(bv - u)
When v >= 30 mV: spike, then v <- c, u <- u + d.
Example¶
neuron = SCIzhikevichNeuron(noise_std=0.0) spikes = [neuron.step(10.0) for _ in range(100)] sum(spikes) > 0 # regular spiking with I=10 True
Integrator options:
- baseline_half_euler preserves the historical two-half-step path
- rk4 is an explicit higher-order alternative path
- post_init()
- step(input_current)
- reset_state()
- get_state()
Module neurons.schema_contracts¶
Function stateless_event_kind(schema)¶
Return the supported event-only contract declared by schema.
A schema is event-only only when both its state and dynamics tables are present and empty. Deterministic schemas must provide a non-empty level threshold; stochastic Poisson schemas must provide a non-empty probability expression. Free-form extension labels are deliberately ignored.
Parameters¶
schema: Parsed schema mapping.
Returns¶
StatelessEventKind or None
The exact supported event contract, or None when the schema must
declare ordinary state and dynamics.
Module neurons.schema_module_aliases¶
Function schema_for_module(module)¶
Return the schema stem for a models/ module stem (identity if unmapped).
Function module_for_schema(schema)¶
Return the models/ module stem for a schema stem (identity if unmapped).
Function class_for_schema(schema)¶
Return the descriptor class name for a schema stem, if known.
Function resolve_schema_join(schema)¶
Return (module, class_name_or_none) for a schema stem.
Module neurons.schema_validator¶
Class SchemaError¶
A single validation error.
- init(level, message, section)
- repr()
Function validate_schema_dict(data, name)¶
Validate a parsed schema dictionary.
Returns a list of SchemaError objects. Empty list = valid.
Function validate_schema(name)¶
Validate a bundled schema by name.
Checks both TOML and JSON versions if they exist, and verifies parity.
Function validate_all_bundled()¶
Validate all bundled schemas.
Returns a dict mapping schema name to its list of errors/warnings.
Module neurons.seed_domain¶
Class SeedOutOfDomain¶
Raised when a seed falls outside the domain its model declares.
Parameters¶
model : str
The model the seed was meant for.
seed : int
The value offered.
domain : tuple of int
The inclusive (low, high) bounds the model declares.
- init(model, seed, domain)
Function seed_domain(model)¶
Return the seeds a model accepts.
Parameters¶
model : type or None
The model class, or None when the caller has no class to ask.
Returns¶
tuple of int
The inclusive (low, high) bounds the model declares, or
:data:UNIVERSAL_SEED_DOMAIN when it declares none. An undeclared
model is given the narrowest domain rather than the widest, because a
seed that is too small is always accepted and one that is too large is
refused by the constructor after the run was admitted.
Examples¶
from sc_neurocore.neurons.models.poisson import PoissonNeuron seed_domain(PoissonNeuron) (0, 65535) seed_domain(None) (1, 65535)
Function check_seed(model_name, seed, domain)¶
Return seed when the domain admits it, or raise :class:SeedOutOfDomain.
Module neurons.stochastic_lif¶
Class StochasticLIFNeuron¶
Discrete-time noisy leaky integrate-and-fire neuron.
dv/dt = -(v - v_rest) / tau_mem + R * I + noise
Parameters use normalised units (voltage [0,1], time in ms). Defaults from Gerstner & Kistler, Spiking Neuron Models, 2002.
Example¶
neuron = StochasticLIFNeuron(v_threshold=1.0, tau_mem=20.0, noise_std=0.0) spikes = [neuron.step(1.5) for _ in range(50)] sum(spikes) > 0 True neuron.get_state() # membrane voltage + refractory counter
Process a bitstream as input current:
import numpy as np bits = np.array([1, 0, 1, 1, 0, 1, 0, 0], dtype=np.uint8) neuron.reset_state() out = neuron.process_bitstream(bits, input_scale=2.0) out.shape (8,)
- post_init()
- step(input_current)
- reset_state()
- get_state()
- process_bitstream(input_bits, input_scale)
- Process a bitstream (array of 0s and 1s) as input current.
Module neurons.universal_dsl¶
Class UniversalNeuron¶
Schema-driven neuron model — parallel meta-layer over existing models.
Does NOT replace hand-crafted model files. Delegates simulation to
:class:~sc_neurocore.neurons.equation_builder.EquationNeuron, ensuring
all existing AST safety, integration methods, and compilation paths
remain available.
Every schema is resolved to its :class:~sc_neurocore.neurons.model_profile.ModelProfile
before anything runs. A schema whose authored profile contradicts it, or that is a
descriptive record outside the executable vocabulary, is refused. Overrides are
admitted through the profile: a method must stay in the profile's family (a
published map is never integrated as an ODE), a timestep override moves the
profile's timebase parameters with it and is refused for a recurrence without a
continuous timebase, and a seed is refused for a model that draws no randomness.
Parameters¶
schema : dict
Parsed schema dictionary (from :func:load_schema).
parameter_overrides : dict, optional
Override default parameter values (e.g. for parameter sweeps).
dt_override : float, optional
Override the schema's default timestep.
method_override : str, optional
Override the integration method.
rng_seed_override : int, optional
Override the stochastic-threshold LFSR seed.
Raises¶
ValueError
If the schema defines no dynamics and no event-only contract, or the
profile refuses the schema or an override
(:class:~sc_neurocore.neurons.model_profile.ProfileAdmissionError).
- init(schema)
- Initialise from a validated schema dictionary.
- from_schema(cls, source)
- Create a UniversalNeuron from a schema file or bundled name.
- from_dict(cls, schema)
- Create from an in-memory schema dictionary.
- step()
- Advance one timestep. Keyword args are external inputs (e.g. I=10.0).
- reset()
- Reset state to initial conditions.
- state()
- Current state variable values.
- name()
- Model name from metadata.
- doi()
- DOI of the source publication, if available.
- schema()
- Return a deep copy of the underlying schema.
- extensions()
- Forward-compatible extension fields.
- profile()
- Resolved model profile: scientific model, numerical realisation, lowering.
- admitted_overrides()
- Overrides admitted under the profile, with the timebase propagated.
- realised_profile()
- Return the effective numerical realisation as a public record.
- science()
- Authored science layer (schema v2), empty for v1 schemas.
- validation()
- Authored validation layer (schema v2), empty for v1 schemas.
- provenance()
- Authored provenance layer (schema v2), empty for v1 schemas.
- hints()
- Optional engineering hints (schema v2), empty for v1 schemas.
- to_json()
- Export the model schema as JSON (Studio interchange format).
- to_toml()
- Export the model schema as TOML (version control format).
- to_equation_neuron()
- Return the underlying EquationNeuron instance.
- to_verilog(module_name)
- Compile the model to Verilog via the equation compiler.
- list_state_variables()
- Return the names of all state variables.
- list_parameters()
- Return the names of all parameters.
- list_equations()
- Return the ODE right-hand sides.
- repr()
- Return a human-readable summary string.
Function load_schema(source)¶
Load a neuron model schema from a TOML or JSON file.
Parameters¶
source : str or Path
Path to a .toml or .json schema file, or a bare name
(e.g. "lif") which is resolved against the bundled schemas.
Returns¶
dict Parsed schema dictionary.
Raises¶
FileNotFoundError If the schema file cannot be found. ValueError If the schema version is unsupported.
Function schema_to_json(schema)¶
Export a schema dictionary as a JSON string (for Studio interchange).
Parameters¶
schema : dict
A schema dictionary (as returned by :func:load_schema).
Returns¶
str JSON string with 2-space indentation.
Function schema_to_toml(schema)¶
Export a schema dictionary as a TOML string (for version control).
Parameters¶
schema : dict A schema dictionary, including authored science, validation, provenance, hints and extension fields. Values must be representable in TOML.
Returns¶
str TOML document preserving all fields, nested tables and empty sections.
Raises¶
TypeError
If a value cannot be represented in TOML, for example None.
Function list_bundled_schemas()¶
Return names of all bundled model schemas (without extensions).
Returns¶
list of str Sorted list of available schema names.
Module nir_bridge.export¶
Function to_nir(network, path)¶
Export an SC-NeuroCore SCNetwork to NIR format.
Parameters¶
network : sc_neurocore.nir_bridge.parser.SCNetwork The network to export. path : str or Path, optional If provided, write the NIR graph to this file.
Returns¶
nir.NIRGraph
Module nir_bridge.fpga_aer_interconnect¶
Function build_aer_interconnect(module_name, qgraph)¶
Generate weighted event-bus top-level interconnect.
The emitted datapath keeps the same population instances as the direct interconnect but routes spike-producing source populations through an address-event fan-out block. All active source spikes in a cycle contribute their signed fixed-point weights to every destination accumulator, so simultaneous events preserve the dense affine semantics of the NIR graph. External analogue inputs and analogue source populations remain direct fixed-point multiply-accumulate terms because they are not sparse events.
Parameters¶
module_name : str Top-level module name. qgraph : QuantisedGraph Quantised graph. data_width : int Fixed-point data width. fraction : int Fractional bits for analogue multiply downshift. bitstream_length : int SC-NIR bitstream length recorded in the generated top module. scnir_stream_count : int Number of semantic streams recorded in the SC-NIR document. scnir_source_module_count : int Number of materialised stochastic source modules. scnir_hierarchy : Sequence[SCNIRHierarchyInstance] Typed hierarchy boundaries instantiated by the network top. scnir_semantic_hierarchy_stream_ids : frozenset[str] Hierarchy stream identifiers that provide semantic connection weights.
Returns¶
str Verilog top-level module source.
Raises¶
ValueError If hierarchy metadata cannot be represented by the address-event interconnect contract.
Module nir_bridge.fpga_compilation_result¶
Class SCNIRExternalInputManifestEntry¶
Stable flattened input-bus layout entry for one external source.
- as_dict()
- Return deterministic JSON-ready external input metadata.
Class FoldedResourceMetrics¶
Architectural resource summary of a folded (time-multiplexed) interconnect.
Quantifies what the shared-datapath fold buys versus the direct interconnect's
one-module-instance-per-neuron unrolling: one processing element per distinct
neuron type is reused across every neuron of that type (a per-type PE pool), with
per-neuron state held in BRAM, at the cost of cycles_per_tick cycles to advance
the whole network by one timestep.
Attributes¶
neurons : int
Total neurons sharing the datapath across all folded populations.
state_vars_per_neuron : int
Widest per-neuron state-variable count across the folded types (the largest
BRAM word = state_vars_per_neuron × data width). Equal to the single type's
count for a homogeneous network.
pe_instances : int
Physical processing elements instantiated: one per distinct neuron type. A
single population, or several populations all of one type, share one PE.
shared_multipliers : int
Multipliers in the shared weighted fan-in, summed over external-source columns
across all populations and reused across each population's neurons. Spiking
fan-in (recurrent or inter-population) is spike-gated and uses none.
state_ram_bits : int
Total BRAM-backed neuron-state storage, in bits, summed over populations
(each population contributes neurons × its type's state-var count × data width).
cycles_per_tick : int
Clock cycles to advance the whole network by one timestep
(neurons process cycles + 1 commit cycle).
direct_neuron_instances : int
Neuron module instances the direct interconnect would unroll (= neurons);
the count the fold collapses to pe_instances.
populations : int
Number of folded populations sharing the one sequencer and the global spike bus.
param_rom_bits : int
Total per-neuron parameter-ROM storage, in bits, for heterogeneous populations
(each contributes neurons × its count of per-neuron-varying parameters × data
width). Zero for a network whose populations all have uniform parameters (the PE
bakes them). The parameter-space analogue of state_ram_bits.
- as_dict()
- Return a deterministic plain-
intmapping for manifests/JSON.
Class NetworkCompilationResult¶
All artefacts from a network-level FPGA compilation.
Attributes¶
neuron_modules : dict[str, str]
Mapping from neuron type to Verilog source.
weight_rom : str
Weight ROM Verilog source.
top_module : str
Top-level interconnect Verilog source.
module_name : str
Top-level module name.
total_neurons : int
Total neuron count.
total_synapses : int
Total synapse count.
q_format : str
Q-format label (e.g. "Q8.8").
interconnect : str
"direct", "aer", or "folded" (the time-multiplexed shared datapath).
folded_metrics : FoldedResourceMetrics | None
Architectural fold resource summary when interconnect == "folded"; None
for the direct/AER paths.
warnings : list[str]
Quantisation and compilation warnings.
scnir_document : SCNIRDocument
SC-aware metadata document consumed by the compilation artefacts.
scnir_source_modules : dict[str, str]
Concrete stochastic source HDL modules keyed by Verilog module name.
scnir_source_manifest : tuple[SCNIRHDLSourceManifestEntry, ...]
Deterministic manifest mapping SC-NIR streams to source modules.
scnir_external_inputs : tuple[SCNIRExternalInputManifestEntry, ...]
Deterministic flattened input-bus layout for external source names.
scnir_hierarchy_modules : dict[str, str]
Standalone SC-NIR hierarchy boundary modules keyed by module name.
Module nir_bridge.fpga_compiler¶
Function compile_network_to_fpga(graph)¶
Compile a NeuronGraph to synthesisable Verilog RTL.
End-to-end pipeline:
- Quantise all parameters to the target Q-format.
- Generate one Verilog module per unique neuron type.
- Generate a combined weight ROM.
- Generate a top-level interconnect module (direct or AER).
Parameters¶
graph : NeuronGraph
Network description (from from_scnetwork()).
module_name : str
Top-level Verilog module name.
data_width : int
Fixed-point total width (16 for Q8.8, 32 for Q16.16).
fraction : int
Fractional bits.
bitstream_length : int
SC-NIR bitstream length metadata propagated into compilation artefacts.
source_kind : {"lfsr", "sobol"}
Hardware stochastic source family materialised from SC-NIR metadata.
base_seed : int
First deterministic source seed; stream index increments from this base.
target : str
FPGA target for resource estimation hints.
online_learning : Mapping[str, Mapping[str, Any]] | None
Optional validated per-weight-stream SC-NIR online-learning annotations,
keyed by deterministic stream id such as "conn.src_to_dst.weight".
interconnect : str | None
None (default) auto-selects direct (small) or AER (large) wiring;
"direct" forces direct; "folded" opts into the time-multiplexed
shared-datapath interconnect (one PE per neuron type + per-population BRAM
state, swept by a single sequencer), which supports the :func:_can_fold
subset: any number of populations with external-weighted, recurrent, or
inter-population spiking fan-in.
Returns¶
NetworkCompilationResult All generated Verilog sources and compilation metadata.
Raises¶
ValueError If the graph is empty or contains unsupported neuron types.
Module nir_bridge.fpga_connection_routing¶
Function validate_connection_routing(graph)¶
Validate connection shapes, external lanes, and delay vectors before lowering.
The SC-NIR conversion and all three interconnect emitters index connection
matrices by source column. Validating the matrix rank first converts malformed
direct NeuronGraph input into a stable ValueError instead of leaking an
IndexError from a downstream conversion step.
Parameters¶
graph : NeuronGraph Network graph whose connection layout will be lowered to RTL.
Raises¶
ValueError If a connection matrix, endpoint width, bias, threshold, or delay is inconsistent with its source and destination populations.
Module nir_bridge.fpga_direct_interconnect¶
Function build_direct_interconnect(module_name, qgraph)¶
Generate direct-wired per-neuron top-level interconnect.
Every neuron gets its own instance of the type-specific module. NIR affine weights are emitted explicitly in fixed-point arithmetic:
- external analogue inputs use
(input * weight) >>> fraction; - analogue source populations use
(v_out * weight) >>> fraction; - spiking source populations contribute their fixed-point weight on spikes and zero otherwise;
- all fan-in terms and biases accumulate in a widened signed accumulator before saturation back to the neuron input Q-format.
Parameters¶
module_name : str Top-level module name. qgraph : QuantisedGraph Quantised graph. data_width : int Fixed-point data width. fraction : int Fractional bits for fixed-point multiply downshift. bitstream_length : int SC-NIR bitstream length recorded in the generated top module. scnir_stream_count : int Number of semantic streams recorded in the SC-NIR document. scnir_source_module_count : int Number of materialised stochastic source modules. scnir_hierarchy : Sequence[SCNIRHierarchyInstance] Typed hierarchy boundaries instantiated by the network top. scnir_semantic_hierarchy_stream_ids : frozenset[str] Hierarchy stream identifiers that provide semantic connection weights.
Returns¶
str Verilog top-level module source.
Raises¶
ValueError If the graph or hierarchy metadata cannot be represented by the direct interconnect contract.
Module nir_bridge.fpga_folded_interconnect¶
Function can_fold(qgraph)¶
Return True if the graph is in the folded interconnect's supported subset.
The folded interconnect time-multiplexes any number of populations of supported neuron types over a per-type PE pool and one global spike bus. A graph folds when every population has an ODE template, every population's heterogeneous per-neuron parameters are datapath parameters the PE can carry on a port (streamed from a per-neuron parameter ROM — a parameter varying in something other than an ODE parameter cannot be streamed and falls back to the direct path), and every connection is one of:
- connection-less — neurons driven only by their own external
I_extlane; - external-weighted — fed by external (non-population) source columns;
- spiking fan-in — recurrent (self) or inter-population spikes from another
population, read from the prior-tick global spike bus, optionally delayed or
gated by a source/destination NIR
Thresholdtransform; - analogue fan-in — an analogue source population (
li/cuba_li/integrator, whose output is the membrane voltage), read from the prior-tick global voltage bus (optionally delayed via a voltage-bus history register) and multiplied (or threshold-gated) by the weight.
Connections may also carry a per-destination-neuron bias constant. Only a delayed external (non-population) source connection is not folded — a synaptic delay has registered semantics only from a neuron population — and falls back to the direct interconnect.
Parameters¶
qgraph : QuantisedGraph Quantised network graph to classify. data_width : int Fixed-point data width used to compare per-neuron parameters.
Returns¶
bool
True when the graph can use the shared-datapath interconnect.
Function folded_resource_metrics(qgraph)¶
Summarise the shared-datapath resources of a foldable graph.
Counts one PE per distinct neuron type (the per-type pool), the shared weighted-fan-in multipliers (external-source and analogue-voltage-source columns — spiking recurrent or inter-population fan-in is spike-gated and uses none), the BRAM state-word storage summed over populations, the per-neuron parameter-ROM storage for heterogeneous populations, the cycles-per-tick, and the direct-path instance count the fold collapses.
Parameters¶
qgraph : QuantisedGraph
A graph satisfying :func:can_fold.
data_width : int
Fixed-point data width (BRAM word sizing).
Returns¶
FoldedResourceMetrics The architectural fold summary.
Function build_folded_interconnect(module_name, qgraph)¶
Generate a time-multiplexed (folded) top plus its per-type datapath PE pool.
One combinational PE (:func:compile_to_datapath) per distinct neuron type and
one BRAM-backed state array per population are shared across every neuron: a
single sequencer steps one neuron per cycle, walking each population in turn,
reading the addressed neuron's packed state from its BRAM, driving the population's
PE with that state and the neuron's input current, and writing the next state back.
Spikes accumulate over a tick into a global accumulator and commit to a single
spike_bus in a dedicated cycle (tick_done pulses), so the bus is race-free
and stable for the whole next tick. Recurrent and inter-population spiking fan-in
read that prior-tick spike_bus at the source population's bit offset — the same
double-buffer the direct interconnect's registered spikes provide. An analogue
source population's membrane voltage is committed the same way to a global v_bus
(one DATA_WIDTH word per analogue source neuron), so analogue fan-in reads the
prior-tick voltage exactly like the direct path's registered v_out.
Restricted to the :func:can_fold subset. Returns
({neuron_module_key: pe_source}, top_module_source) with one PE source per
distinct neuron type, keyed "{neuron_type}_pe" for the compilation artefacts.
Parameters¶
module_name : str
Verilog module name for the folded network top.
qgraph : QuantisedGraph
Quantised graph accepted by :func:can_fold.
data_width : int
Fixed-point word width.
fraction : int
Number of fractional bits in each fixed-point word.
Returns¶
tuple[dict[str, str], str] Per-type processing-element sources and the folded top-level Verilog.
Raises¶
ValueError If the graph is outside the supported folded subset.
Module nir_bridge.fpga_neuron_rtl¶
Function build_neuron_module(neuron_type, pop)¶
Build a Verilog module for one canonical neuron type.
Uses the existing equation_compiler.compile_to_verilog() with
canonical ODE templates.
Parameters¶
neuron_type : str
Canonical neuron type ("lif", "if", etc.).
pop : NeuronSpec
Representative population (for parameter defaults).
data_width : int
Fixed-point data width.
fraction : int
Fractional bits.
Returns¶
str Synthesisable Verilog module source.
Raises¶
ValueError If the neuron type or one of its parameters has no canonical FPGA template contract.
Module nir_bridge.fpga_scnir_hierarchy¶
Function resolve_hierarchy_weight_literals(document, qgraph)¶
Resolve flattened weights referenced by hierarchy output ports.
Parameters¶
document : SCNIRDocument Typed hierarchy and stream metadata for the compilation. qgraph : QuantisedGraph Quantised graph that owns the referenced connection weights.
Returns¶
dict[str, tuple[int, ...]] Flattened integer weights keyed by semantic SC-NIR stream identifier.
Raises¶
ValueError If a weight port references an unknown stream or incompatible packed width.
Function build_scnir_hierarchy_modules(document)¶
Emit standalone boundary modules for preserved SC-NIR hierarchy instances.
Parameters¶
document : SCNIRDocument Typed hierarchy metadata to lower. weight_literals : dict[str, tuple[int, ...]] Flattened fixed-point weights keyed by semantic stream identifier.
Returns¶
dict[str, str] Synthesisable Verilog keyed by hierarchy module name.
Raises¶
ValueError If module names collide or a hierarchy boundary is malformed.
Function build_scnir_hierarchy_instance_block(hierarchy)¶
Emit top-level hierarchy instances and typed connecting wires.
Parameters¶
hierarchy : Sequence[SCNIRHierarchyInstance] Typed hierarchy instances to connect at the network top. data_width : int Active fixed-point data width used for canonical weight wires.
Returns¶
list[str] Verilog declarations, zero-driven inputs, and instance blocks.
Raises¶
ValueError If a hierarchy port has a non-positive width.
Module nir_bridge.fpga_weight_rom¶
Function build_weight_rom(qgraph)¶
Generate a combined weight ROM for all connections.
All connection weight matrices are flattened into a single ROM addressed by a global index. Each connection gets a base address offset.
Parameters¶
qgraph : QuantisedGraph Quantised graph with integer weight matrices. data_width : int Weight data width.
Returns¶
str Verilog weight ROM module source.
Module nir_bridge.hardware_targets¶
Class SCMappingConstraints¶
SC-specific constraints used before lowering NIR graphs to a target.
- to_dict()
- Return a JSON-serialisable representation.
Class NeuromorphicHardwareProfile¶
NIR extension profile for a named neuromorphic target.
- to_manifest()
- Return the profile in deterministic manifest form.
Class HardwareNoiseAnnotation¶
Measured target noise that can be replayed in simulation.
- to_dict()
- Return a JSON-serialisable noise annotation.
Function available_hardware_profiles()¶
Return all known hardware profiles in deterministic order.
Function get_hardware_profile(target_id)¶
Return one hardware profile by identifier.
Function build_nir_hardware_manifest(targets)¶
Build a deterministic manifest for NIR hardware-extension planning.
Function build_noise_annotation(target_id, observations)¶
Validate measured hardware noise and prepare it for simulation replay.
Module nir_bridge.interchange_notes¶
Class InterchangeNote¶
One point where crossing the NIR boundary was not exact.
Parameters¶
kind:
assumed, approximated or not-carried.
subject:
The graph ("") or the dotted path of the node or edge concerned.
detail:
What happened, in words a user can check against the source graph.
- to_dict()
- Return the note as a JSON-compatible mapping.
Function read_nir_file_version(path)¶
Return the NIR version a .nir file records, if it records one.
Parameters¶
path:
The .nir (HDF5) file.
Returns¶
str or None
The version string, or None when the file stores no version.
Function import_notes(graph, network)¶
Record what importing graph as network assumed or approximated.
Parameters¶
graph:
The NIR graph that was imported.
network:
The parsed SCNetwork, before any execution.
dt:
The timestep the importer used.
reset_mode:
The reset rule the importer gave spiking nodes.
Returns¶
list of InterchangeNote Graph-level notes first, then per-node and per-edge notes in graph order.
Function export_notes(network)¶
Record what exporting network to NIR does not carry.
Parameters¶
network:
The SCNetwork about to be exported.
Returns¶
list of InterchangeNote Graph-level notes first, then per-node notes.
Module nir_bridge.neuromorphic_adapters¶
Class NeuromorphicAdapterPackage¶
Deterministic handoff package for one neuromorphic hardware target.
- manifest()
- Return a JSON-serialisable adapter manifest.
- files()
- Return deterministic package files keyed by relative path.
Function build_neuromorphic_adapter_package(source, target_id, config)¶
Build one Loihi 2 or SpiNNaker2 adapter handoff package.
Function build_neuromorphic_adapter_bundle(source, targets, config)¶
Build deterministic adapter packages for multiple targets.
Function write_neuromorphic_adapter_bundle(output_dir, source, targets, config)¶
Write Loihi 2/SpiNNaker2 adapter manifests and reports to disk.
Module nir_bridge.neuron_graph_builder¶
Function from_scnetwork(network, dt)¶
Convert a parsed SCNetwork to the FPGA-targeted neuron graph.
Parameters¶
network : SCNetwork
Parsed SC-NeuroCore network returned by :func:from_nir.
dt : float or None, optional
Simulation timestep override. When omitted, each neuron node retains
its imported timestep and the first population supplies the graph
timestep.
Returns¶
NeuronGraph Ordered populations, lowered weighted connections, graph boundaries, and preserved nested hierarchy metadata.
Raises¶
ValueError If nested graph boundaries are ambiguous, pass-through metadata cannot be represented exactly, or no neuron population remains after lowering.
Module nir_bridge.neuron_graph_contracts¶
Class NeuronSpec¶
Describe one neuron population in the compiled graph.
Parameters¶
name : str
Unique population identifier matching the NIR node name.
neuron_type : str
Canonical neuron type such as "lif", "if", "li",
"cuba_lif", or "cuba_li".
n_neurons : int
Number of neurons in the population.
params : dict[str, numpy.ndarray]
Canonical neuron parameters stored as arrays.
dt : float
Simulation timestep inherited from NIR import.
Class ConnectionSpec¶
Describe a weighted edge between neuron populations.
Parameters¶
src : str
Source population name.
dst : str
Destination population name.
weights : numpy.ndarray
Weight matrix with shape (n_dst, n_src).
bias : numpy.ndarray or None
Optional destination bias vector with shape (n_dst,).
delay_steps : int or tuple[int, ...]
Scalar delay or one explicit delay per source column.
source_threshold : numpy.ndarray or None
Optional threshold applied before the weight matrix.
destination_threshold : numpy.ndarray or None
Optional threshold applied after affine accumulation.
Class HierarchyInstanceSpec¶
Preserve provenance for a nested graph flattened into hardware IR.
Parameters¶
instance_id : str Parent-graph node name of the nested graph instance. module_name : str Stable HDL module identifier assigned to the instance boundary. node_name_prefix : str Namespace prefix applied to the nested nodes during flattening.
Class NeuronGraph¶
Describe a complete network ready for FPGA compilation.
Parameters¶
populations : list[NeuronSpec] Populations in deterministic topological order. connections : list[ConnectionSpec] Weighted connections between populations. input_pop : str Input boundary or first population name. output_pop : str Output boundary or final population name. dt : float Global simulation timestep. hierarchy : tuple[HierarchyInstanceSpec, ...] Nested instances flattened for hardware lowering.
- total_neurons()
- Return the neuron count across all populations.
- total_synapses()
- Return the matrix-entry count across all connections.
- neuron_types()
- Return the canonical neuron types present in the graph.
- summary()
- Return a deterministic human-readable graph summary.
Module nir_bridge.node_map¶
Class SCInputNode¶
Graph entry point — passes input through unchanged.
- forward(x)
Class SCOutputNode¶
Graph exit point — collects output.
- forward(x)
Class SCLIFNode¶
LIF neuron mapped from NIR LIF primitive.
NIR LIF: taudv/dt = (v_leak - v) + RI, spike when v > v_threshold Euler: v += ((v_leak - v) + R*I) * dt/tau
- from_nir(cls, name, node, dt, reset_mode)
- post_init()
- forward(x)
- reset()
Class SCIFNode¶
IF neuron — integrator with threshold, no leak.
NIR IF: dv/dt = RI, spike when v > v_threshold Euler: v += RI*dt
- from_nir(cls, name, node, dt, reset_mode)
- post_init()
- forward(x)
- reset()
Class SCLINode¶
Leaky integrator — LIF without threshold.
NIR LI: taudv/dt = (v_leak - v) + RI
- from_nir(cls, name, node, dt)
- post_init()
- forward(x)
- reset()
Class SCAffineNode¶
Dense linear transform with bias: y = Wx + b
- from_nir(cls, name, node)
- forward(x)
Class SCLinearNode¶
Matrix multiply without bias: y = Wx
- from_nir(cls, name, node)
- forward(x)
Class SCScaleNode¶
Element-wise scaling: y = s * x
- from_nir(cls, name, node)
- forward(x)
Class SCThresholdNode¶
Spike threshold: y = 1 if x > threshold else 0
- from_nir(cls, name, node)
- forward(x)
Class SCFlattenNode¶
Reshape tensor — flatten dimensions.
- from_nir(cls, name, node)
- forward(x)
Class SCIntegratorNode¶
Pure integrator: dv/dt = RI (no leak, no threshold). Euler: v += RI*dt
- from_nir(cls, name, node, dt)
- n_neurons()
- Number of integrator state channels.
- post_init()
- forward(x)
- reset()
Class SCDelayNode¶
Temporal delay: output = input(t - delay).
NIR Delay: I(t - tau). Implemented as a circular buffer per element. Delay values are rounded to integer timesteps.
- from_nir(cls, name, node, dt)
- post_init()
- forward(x)
- reset()
Class SCCubaLIFNode¶
Current-based LIF with synaptic filter.
NIR CubaLIF: tau_syn * dI_syn/dt = -I_syn + w_in * I tau_mem * dv/dt = (v_leak - v) + R * I_syn spike when v > v_threshold, reset to v_reset
- from_nir(cls, name, node, dt, reset_mode)
- post_init()
- forward(x)
- reset()
Class SCCubaLINode¶
Current-based leaky integrator (CubaLIF without threshold).
NIR CubaLI: tau_syn * dI_syn/dt = -I_syn + w_in * I tau_mem * dv/dt = (v_leak - v) + R * I_syn
- from_nir(cls, name, node, dt)
- post_init()
- forward(x)
- reset()
Class SCSumPool2dNode¶
2D sum pooling: sum over spatial kernel windows.
- from_nir(cls, name, node)
- forward(x)
Class SCAvgPool2dNode¶
2D average pooling: SumPool / kernel_area.
- from_nir(cls, name, node)
- forward(x)
Class SCConv1dNode¶
1D convolution: y = conv1d(x, weight) + bias.
- from_nir(cls, name, node)
- forward(x)
Class SCConv2dNode¶
2D convolution: y = conv2d(x, weight) + bias.
- from_nir(cls, name, node)
- forward(x)
Function map_node(name, node)¶
Convert a single NIR node to its SC-NeuroCore equivalent.
Module nir_bridge.parser¶
Class SCSubgraphNode¶
Executable wrapper for a nested NIR subgraph (single I/O port).
- post_init()
- forward(x)
- reset()
Class SCMultiPortSubgraphNode¶
Executable wrapper for a nested NIR subgraph with multiple I/O ports.
Supports modular architectures where subgraphs expose multiple named inputs and outputs (e.g., encoder-decoder, skip connections).
- post_init()
- input_ports()
- output_ports()
- forward(x)
- Single-input convenience: feeds x to first input, returns first output.
- forward_multi(inputs)
- Multi-port forward: provide named inputs, get named outputs.
- reset()
Class SCNetwork¶
Executable network parsed from a NIR graph.
Nodes are stored by name. Edges define the forward pass order.
Calling run() feeds input through the graph for the given
number of timesteps and returns the output node's accumulated result.
Recurrent edges (cycles) are automatically handled by inserting unit-delay nodes that feed from the previous timestep.
- from_nir(cls, source, dt, reset_mode)
- Build an
SCNetworkdirectly from a NIR graph or file path. - to_hardware()
- Compile this parsed network to the existing FPGA artefact bundle.
- topo_order()
- step(inputs)
- Execute one timestep through the graph.
- run(inputs, steps)
- Run the network for multiple timesteps.
- reset()
- Reset all stateful nodes.
- summary()
- Human-readable network summary.
Function from_nir(source, dt, reset_mode)¶
Convert a NIR graph to an executable SC-NeuroCore network.
Parameters¶
source : nir.NIRGraph or str or Path NIR graph object, or path to a .nir file. dt : float Timestep for leaky integrator dynamics. reset_mode : str Spike reset mechanism: "reset" (v = v_reset, NIR spec default) or "subtract" (v = v - v_threshold, used by snnTorch).
Returns¶
SCNetwork
Executable network with topologically sorted forward pass. Its
interchange_notes list what the import assumed or approximated,
and nir_version is the version a .nir file records.
Raises¶
ValueError
dt is not a positive finite number, reset_mode is neither
"reset" nor "subtract", or the graph is malformed.
Module nir_bridge.quantise_params¶
Class QuantisedGraph¶
NeuronGraph with all parameters converted to Q-format integers.
Attributes¶
populations : list[NeuronSpec] Populations with integer-valued parameters (Q-encoded). connections : list[ConnectionSpec] Connections with integer-valued weight matrices (Q-encoded). q : Q88 The fixed-point format configuration used. input_pop : str Input population name. output_pop : str Output population name. dt : float Global timestep. warnings : list[str] Overflow/underflow warnings generated during quantisation. total_neurons : int Total neuron count. total_synapses : int Total synapse count.
Function quantise_graph(graph, q)¶
Convert all floating-point parameters to Q-format integers.
Parameters¶
graph : NeuronGraph Network with float32 parameters. q : Q88 Target fixed-point format.
Returns¶
QuantisedGraph Network with integer-valued parameters and quantisation warnings.
Module nir_bridge.silicon_mapping¶
Class SiliconMappingConfig¶
Configuration for NIR silicon mapping report generation.
- post_init()
Function build_silicon_mapping_report(source, config)¶
Build a deterministic target-mapping report for a parsed NIR network.
Function write_silicon_mapping_report(output_dir, source, config)¶
Write nir_silicon_mapping_report.json in deterministic form.
Module online_learning.eprop¶
Class EpropTrainer¶
E-prop online trainer for a single-layer recurrent SNN.
Parameters¶
n_inputs : int Input dimension. n_neurons : int Number of LIF neurons. n_outputs : int Output dimension. tau_mem : float Membrane time constant (ms). tau_trace : float Eligibility trace decay time constant (ms). threshold : float Spike threshold. lr : float Learning rate. dt : float Timestep (ms).
- post_init()
- reset()
- Reset all internal state and eligibility traces.
- step(x, target)
- Process one timestep with optional learning.
- train_sequence(inputs, targets)
- Train on one sequence, return mean loss.
- predict_sequence(inputs)
- Run inference on a sequence without learning.
- memory_per_step()
- Memory usage per timestep in parameters (O(1) in T).
Module online_learning.online_trainer¶
Class OnlineLIFLayer¶
Single LIF layer with online (eligibility-based) learning.
Parameters¶
n_inputs : int n_neurons : int tau_mem : float Membrane time constant. threshold : float lr : float Learning rate for local weight updates.
- post_init()
- reset()
- step(x)
- Forward one timestep. Returns spike vector.
- apply_learning_signal(signal)
- Apply a top-down learning signal to update weights.
Class OnlineTrainer¶
Feedforward online trainer: stacks OnlineLIFLayers with eligibility learning.
Parameters¶
layer_sizes : list of int [n_input, n_hidden1, ..., n_output] tau_mem : float threshold : float lr : float
- post_init()
- reset()
- step(x, target)
- Forward one timestep through all layers with optional learning.
- train_sequence(inputs, targets)
- Train on one sequence, return mean loss.
- n_layers()
- memory_per_step()
- Total parameters stored per timestep (O(1) in T).
Module optics._photonic_compiler¶
Class CompilationResult¶
Result of a photonic compilation pass.
- post_init()
- Validate compilation metadata before export.
- to_gdsii(filename, mzi_length_um, pitch_um)
- Export the compiled MZI cascade to GDSII through gdsfactory.
Class PhotonicCompiler¶
Compile an SC bitstream into optical mapping, netlist, and co-simulation.
- init(target)
- compile_bitstream(bitstream, run_fdtd, fdtd_steps)
- Compile one non-empty binary SC bitstream to a photonic deployment.
- generate_mzi_verilog(bit_width)
- Generate SystemVerilog for an MZI modulator.
- generate_microring_verilog(bit_width)
- Generate SystemVerilog for a microring resonator.
Module optics._photonic_conversion¶
Class BitstreamToOptical¶
Convert SC bitstreams into optical pulse trains.
- init(target)
- convert(bitstream, pulse_duration_ps)
- Map a binary SC bitstream to an optical pulse train.
- to_phase_array(bitstream)
- Return the vectorised phase encoding in radians.
- to_amplitude_array(bitstream)
- Return the vectorised normalised amplitude encoding.
- optical_power_profile(bitstream, input_power_mw)
- Compute output power after the target insertion loss.
Module optics._photonic_crosstalk¶
Class WaveguidePair¶
Physical contract for one pair of adjacent optical waveguides.
- post_init()
- Validate the coupled-mode domain before numerical evaluation.
- effective_index_diff()
- Return the Marcatili-form even/odd effective-index difference.
- coupling_coefficient()
- Return coupling coefficient κ per micrometre.
- coupling_ratio()
- Return power coupling ratio at the end of the parallel run.
- isolation_db()
- Return pair isolation in decibels with a 300 dB numeric ceiling.
Class CrosstalkModel¶
Evaluate evanescent crosstalk between parallel waveguide runs.
- init()
- add_pair(pair)
- Append one validated waveguide pair to the analyzer batch.
- transfer_matrix(pair)
- Return the two-by-two unitary directional-coupler matrix.
- compute_crosstalk(pair, input_power)
- Return output power on both waveguides for two input amplitudes.
- worst_case_isolation()
- Return minimum isolation across registered pairs in decibels.
- analyze_bank(waveguides, gap_nm, coupling_length_um, wavelength_nm, core_index, cladding_index)
- Analyze adjacent and next-nearest pairs in a uniform waveguide bank.
- analyze_pairs(pair_indices, gaps_nm, coupling_lengths_um, wavelength_nm, core_index, cladding_index)
- Analyze per-pair crosstalk for arbitrary waveguide geometry.
Module optics._photonic_emitter¶
Class PhotonicEmitter¶
Emit photonic netlists in dependency order for a selected PDK.
- init(target_pdk)
- emit_lumerical_netlist(ir_graph)
- Emit a Lumerical-compatible photonic netlist from an IR graph.
Module optics._photonic_fdtd¶
Class FDTDSolver¶
One-dimensional Yee-grid solver for waveguide co-simulation.
The solver applies a quadratic-ramp multiplicative absorbing boundary at
each end. It is a bounded reference implementation for pulse propagation,
dispersion, and loss checks; use :class:FDTD2DSolver when split-field
Berenger PML is required.
- init(grid_size, dx_um, dt_factor, refractive_index, boundary_cells)
- set_loss(loss_db_per_cm)
- Set non-negative propagation loss in decibels per centimetre.
- inject_pulse(position, wavelength_nm, amplitude, phase)
- Inject a Gaussian-envelope optical pulse at a grid position.
- step(n_steps)
- Advance the simulation by
n_stepstimesteps. - field_energy()
- Return total squared electromagnetic field energy.
- snapshot()
- Return independent copies of the electric and magnetic fields.
Class FDTD2DSolver¶
Two-dimensional TE Yee-grid solver with split-field Berenger PML.
- init(nx, ny, dx_um, dy_um, dt_factor, pml_layers)
- set_waveguide(y_center, width_cells, refractive_index, x_start, x_end)
- Define a horizontal waveguide stripe on the material map.
- inject_source(x, y, wavelength_nm, amplitude, sigma_cells)
- Inject a two-dimensional Gaussian electric-field source.
- step(n_steps)
- Advance the TE simulation by
n_stepstimesteps. - field_energy()
- Return total squared electromagnetic field energy.
- field_at_point(x, y)
- Return the electric field at one in-bounds grid point.
- cross_section(x)
- Return an independent electric-field cross-section at
x. - snapshot()
- Return independent copies of all field components.
Module optics._photonic_meep¶
Class MeepAdapter¶
Build and execute Meep waveguide simulations when Meep is installed.
- is_available()
- Return whether the optional Meep dependency is importable.
- build_waveguide_geometry(target, waveguide_width_um, length_um, substrate_index)
- Build a serialisable Meep waveguide-geometry description.
- run_simulation(geometry, run_time)
- Execute a real Meep simulation and return its transmission record.
Module optics._photonic_types¶
Class OpticalModulation¶
Optical modulation scheme.
Class PhotonicTarget¶
Hardware target specification for a photonic backend.
- post_init()
- Validate target metadata before it reaches a compiler backend.
- lightmatter(cls)
- Return a Lightmatter-style photonic target profile.
- silicon_photonics(cls)
- Return a generic silicon-photonics target profile.
- two_d_waveguide(cls)
- Return a two-dimensional-material waveguide target profile.
Class OpticalPulse¶
Single optical pulse with phase and amplitude.
- post_init()
- Validate the physical pulse boundary.
Module optics.photonic_layer¶
Class PhotonicBitstreamLayer¶
Simulates a Photonic Stochastic Computing Layer. Uses Phase Noise (Laser Interference) to generate bitstreams.
- simulate_interference(length)
- Simulates the interference of two laser beams with phase noise.
- forward(input_probs, length)
- Generates bitstreams where '1' occurs if interference intensity < input_prob.
Module optimizer.feedback_loop¶
Class SynthesisFeedbackResult¶
Result of one measured-evidence optimiser feedback pass.
Function optimise_from_synthesis_reports()¶
Parse synthesis reports and immediately rerun the SC optimiser.
This helper is the local closed loop for the first production path: report files are parsed into strict evidence, evidence becomes measured observations, and those observations bias the surrogate optimiser for the supplied layer network. It never invokes vendor tools or fabricates missing metrics; callers must provide reports and measured accuracy.
Function optimise_from_evidence_payload()¶
Rerun the SC optimiser from an in-memory evidence payload.
Module optimizer.observation_loader¶
Class ObservationLoadError¶
Raised when a benchmark/synthesis observation cannot be trusted.
Function load_observations(path)¶
Load benchmark observations from a JSON evidence file.
Function load_synthesis_observation(report_paths)¶
Load one observation from Vivado/Quartus report files plus design metadata.
Raw vendor reports do not describe the compiler decision that produced the hardware, and many do not carry model accuracy. The caller must therefore provide the design fields and measured accuracy explicitly.
Function observation_from_synthesis_reports(reports)¶
Build one observation from raw Vivado/Quartus text reports.
Function observations_from_payload(payload)¶
Convert an in-memory benchmark/synthesis payload into observations.
Module optimizer.resource_optimizer¶
Class OptimizationStep¶
One step in the optimization process.
Class OptimizationResult¶
Result of the resource optimization process.
- summary()
- Render a multi-line human-readable report of the optimization outcome.
Function fit_to_target(layer_sizes, weights, target, max_iterations, min_bitstream_length, initial_bitstream_length)¶
Automatically compress an SNN to fit a target FPGA.
Iteratively applies: 1. Bitstream length reduction (halving L) 2. Weight pruning (increasing threshold) 3. Weight quantization (reducing bit width)
Stops when the energy estimator says the network fits on the target.
Parameters¶
layer_sizes : list of (n_inputs, n_neurons) weights : list of ndarray target : str FPGA target ('ice40', 'ecp5', 'artix7', 'zynq'). max_iterations : int Maximum optimization steps. min_bitstream_length : int Minimum allowed L. initial_bitstream_length : int Starting bitstream length.
Returns¶
OptimizationResult
Module optimizer.sc_optimizer¶
Class DecorrelationStrategy¶
Class ComputeMode¶
Class HardwareBudget¶
Class LayerProfile¶
Class LayerConfig¶
Class OptimizerReport¶
- summary()
Class SCOptimizer¶
- init(budget)
- optimize(network)
- Greedy knapsack optimization maximizing weighted accuracy.
- optimize_annealing(network)
- Simulated annealing for larger design spaces.
Module optimizer.surrogate_sc_optimizer¶
Class TargetHardwareProfile¶
Target device budget and compiler preference weights.
Class BenchmarkObservation¶
Measured or externally supplied design-point observation.
The optimiser treats these as higher-priority training points than its analytical generated points. Callers should only pass observations that come from real benchmark or synthesis outputs.
Class SurrogateLayerConfig¶
Selected SC compiler settings for one layer.
Class SurrogateOptimizerReport¶
Budgeted per-layer compiler configuration.
- feasible()
- Whether every layer received a configuration.
Class SurrogateSCOptimizer¶
Compiler optimiser using a learned surrogate over SC design points.
- init(target)
- optimise(network)
- Select budgeted layer settings for
network.
Module optimizer.synthesis_evidence¶
Function load_design(path)¶
Load explicit compiler-design metadata for one synthesis observation.
Function observation_to_record(observation)¶
Convert an optimiser observation into the stable evidence JSON shape.
Function build_payload_from_reports()¶
Build an evidence payload from report files and explicit metadata.
Function build_payload(args)¶
Build an evidence payload from parsed command-line arguments.
Function energy_payload(observation)¶
Compute report-derived energy only when workload metadata is explicit.
Function write_payload(payload, output)¶
Write evidence JSON to a file or stdout.
Function build_parser()¶
Build the command-line parser.
Function main(argv)¶
Run the evidence collector.
Module physics.heat¶
Class FeynmanKacHeatSolver¶
Solve the 1D heat equation via Feynman-Kac path-integral expectation.
PDE: ∂u/∂t = α · ∂²u/∂x² on x ∈ [0, L] with
reflective BC u'(0,t) = u'(L,t) = 0
and initial condition u(x, 0) = f(x).
Solution (Feynman-Kac):
u(x_eval, T) = E[ f(X_T) | X_0 = x_eval ]
where X_t is reflected Brownian motion on [0, L] with
variance 2α t.
Parameters¶
length : float
Domain extent L (same units as the diffusion coefficient
squared per unit time). Defaults to a 1.0-unit interval.
diffusivity : float
α — the heat-equation diffusion coefficient (m²/s in SI;
units are caller's responsibility).
num_walkers : int
Number of Monte Carlo walkers; estimator variance scales
as 1/sqrt(N).
dt : float
Time step for the Euler-Maruyama integration of the
Brownian motion. Must be small enough that
sqrt(2 α dt) << L so reflection is well-resolved.
seed : int
RNG seed for reproducibility.
- post_init()
- set_initial_distribution(f, n_grid)
- Sample walker positions from the initial distribution f(x).
- set_initial_delta(x_0)
- All walkers start at position x_0 (delta-function initial condition).
- step(n_substeps)
- Advance walkers by
n_substepsBrownian steps. - evolve_to(T)
- Step walkers from current time to
T(T > current t). - get_density(n_bins)
- Return the Monte Carlo histogram density over [0, L].
- expectation(observable)
- Compute the Feynman-Kac expectation
E[observable(X_T)]. - time()
- Current simulation time.
Module physics.wolfram_hypergraph¶
Class WolframHypergraph¶
Simulates the Wolfram Physics Project Hypergraph. Universe is a set of relations (Hyperedges).
- post_init()
- evolve(steps)
- Applies a rewrite rule.
- dimension_estimate()
- Estimate effective dimension via BFS neighborhood growth.
Module pipeline.ingestion¶
Class MultimodalDataset¶
Validated multimodal training dataset.
Parameters¶
data: Mapping from modality names to normalized arrays. The first axis is the sample axis and must have the same length for every modality. labels: Label array whose first axis matches the modality sample count.
- post_init()
- Validate dataset shape invariants after construction.
- get_sample(idx)
- Return the per-modality arrays for one sample index.
Class DataIngestor¶
Normalize raw multimodal arrays into a MultimodalDataset.
Parameters¶
label_key: Reserved key used to extract labels from the raw input mapping.
- init(label_key)
- Initialize the ingestor with the reserved label key.
- prepare_dataset(raw_data)
- Normalize and package raw multimodal data.
Module pipeline.training¶
Class SCTrainingLoop¶
Standard and Reinforcement Learning loops for SC Networks.
- run_rl_epoch(agent, env_step_func, input_data, generations)
- Runs a reinforcement learning epoch.
- train_multimodal_fusion(fusion_layer, dataset, epochs)
- Train weights in a multimodal fusion layer via per-sample updates.
Module privacy.dp_snn¶
Class PrivacyAccountant¶
Track cumulative privacy budget across training steps.
Uses simple composition theorem: total epsilon = sum of per-step epsilons. For tighter bounds, use Renyi DP (future extension).
Parameters¶
target_epsilon : float Privacy budget limit. target_delta : float Failure probability.
- record_step(step_epsilon)
- Record privacy cost of one training step.
- spent_epsilon()
- remaining_epsilon()
- budget_exhausted()
- summary()
Class SpikeLevelDP¶
Spike-level differential privacy mechanism.
Adds stochastic spike noise to provide (epsilon, delta)-DP. Two mechanisms: - Spike randomized response: each spike independently flipped with probability p - Spike subsampling: randomly drop spikes with probability 1-q
Parameters¶
epsilon : float Per-step privacy budget. mechanism : str 'randomized_response' or 'subsampling'. seed : int
- init(epsilon, mechanism, seed)
- privatize(spikes)
- Apply DP mechanism to a spike tensor.
- per_step_epsilon()
Class MembershipAudit¶
Audit SNN for membership inference vulnerability.
Given a trained model (as a callable), test whether it leaks information about training data membership. Uses shadow model methodology: compare model confidence on training vs non-training samples.
Parameters¶
run_fn : callable Model function: takes spikes (T, N) → output (N_out,).
- init(run_fn)
- audit(member_samples, non_member_samples)
- Run membership inference audit.
Module privacy.governance¶
Class ConsentBoundary¶
Participant-level legal basis and telemetry permissions.
- post_init()
- Validate consent identity, legal basis, telemetry flag, and token fields.
- to_dict()
- Return this consent boundary as a deterministic mapping.
- from_dict(cls, data)
- Build a consent boundary from a manifest section.
Class RetentionPolicy¶
Retention windows for neural telemetry and artefacts.
- post_init()
- Validate retention windows and enforce the maximum retention horizon.
- to_dict()
- Return this retention policy as a deterministic mapping.
- from_dict(cls, data)
- Build a retention policy from a manifest section.
Class RedactionPolicy¶
Field-level redaction policy for protected telemetry and logs.
- post_init()
- Validate redaction activation, field list, and replacement marker.
- to_dict()
- Return this redaction policy as a deterministic mapping.
- from_dict(cls, data)
- Build a redaction policy from a manifest section.
Class TelemetryPolicy¶
Telemetry sink and sampling policy.
- post_init()
- Validate telemetry activation, sink name, and sampling interval.
- to_dict()
- Return this telemetry policy as a deterministic mapping.
- from_dict(cls, data)
- Build a telemetry policy from a manifest section.
Class ProvenanceRecord¶
Cryptographic provenance record for model and dataset artefacts.
- post_init()
- Validate provenance artefact identity, hash, and source-system fields.
- to_dict()
- Return this provenance record as a deterministic mapping.
- from_dict(cls, data)
- Build a provenance record from one manifest list item.
Class IntegratorResponsibility¶
Operational responsibilities for an integrator in a deployment pipeline.
- post_init()
- Validate integrator contact details and approval responsibility fields.
- to_dict()
- Return this integrator responsibility record as a deterministic mapping.
- from_dict(cls, data)
- Build an integrator responsibility record from a manifest section.
Class PrivacyFeatureFlags¶
Feature activation and audit flags for a governed workflow.
- post_init()
- Validate feature toggles and the audit-flag activation contract.
- to_dict()
- Return this privacy feature flag set as a deterministic mapping.
- from_dict(cls, data)
- Build privacy feature flags from a manifest section.
Class GovernanceContract¶
Full privacy governance contract for BCI/neural workflows.
- post_init()
- Enforce cross-section privacy governance invariants.
- audit_required_features()
- Return sorted feature keys that require audit flags.
- active_features()
- Return names of enabled privacy features in deterministic order.
- to_dict()
- Return a deterministic JSON-serialisable representation.
- from_dict(cls, data)
- Build a full governance contract from a manifest mapping.
Module profiler.platform_profiler¶
Class PlatformResult¶
Performance result for one platform.
Function compare(layer_sizes, duration, dt, bitstream_length, platforms)¶
Compare SNN performance across platforms.
Parameters¶
layer_sizes : list of (n_inputs, n_neurons) Network architecture. duration : float Simulation duration in seconds. dt : float Timestep. bitstream_length : int SC bitstream length for FPGA estimates. platforms : list of str, optional Platforms to compare. Default: all available. Options: 'python', 'rust', 'fpga_ice40', 'fpga_artix7'
Returns¶
list of PlatformResult One result per platform, sorted by energy efficiency.
Function format_table(results)¶
Format comparison results as a readable table.
Module profiling.energy¶
Class EnergyMetrics¶
Running operation counts and the per-operation energies applied to them.
Attributes¶
E_AND, E_XOR, E_ADD : float
Energy in joules attributed to one gate operation at a 45 nm CMOS
equivalent. Assumed values; see the module docstring on provenance.
E_MEM : float
Energy in joules attributed to reading one bit of memory, same basis.
total_ops_and, total_ops_xor, total_bits_mem : int
Counts accumulated since the last :meth:reset.
- reset()
- Zero every accumulated count, leaving the energy constants alone.
- estimate_energy()
- Return the energy the accumulated counts imply, in joules.
- co2_emission_g(carbon_intensity_g_per_kwh)
- Return the CO2 the estimated energy implies, in grams.
Function track_energy(func)¶
Wrap a layer call so its operation counts reach the global profiler.
Parameters¶
func : Callable The layer call to wrap. Its dimensions determine the counts added.
Returns¶
Callable
The same call, adding to :data:profiler on each invocation. It
accumulates counts, not measurements.
Module profiling.spike_profiler¶
Class Severity¶
Class Pathology¶
One detected training pathology.
Class LayerStats¶
Accumulated statistics for one layer across recorded steps.
Class ProfileReport¶
Complete profiling report with per-layer stats and detected pathologies.
- summary()
- has_critical()
Class SpikeProfiler¶
Instruments SNN training to detect pathologies and compute diagnostics.
Record spike tensors, voltage tensors, and optionally gradient tensors per layer per training step. Call report() to get a ProfileReport with detected pathologies and fix suggestions.
Parameters¶
dead_threshold : float Firing rate below which a neuron is considered dead (default 0.01). saturated_threshold : float Firing rate above which a neuron is considered saturated (default 0.95). gradient_explosion_ratio : float Max/mean gradient norm ratio above which gradient explosion is flagged.
- init(dead_threshold, saturated_threshold, gradient_explosion_ratio)
- record_step(layer, spikes, voltages, gradients)
- Record one timestep of data for a layer.
- reset()
- Clear all accumulated data.
- report()
- Analyze accumulated data and return a ProfileReport.
Module qat.lsq¶
Class LSQQuantizer¶
Learned-step-size fake quantiser for signed weights.
Parameters¶
n_bits : int
Quantiser bit width (>= 2). The signed grid is
[-2**(n_bits-1), 2**(n_bits-1) - 1].
per_channel : bool
Learn one step per channel along ch_axis instead of a single
scalar step.
ch_axis : int
Channel axis used when per_channel is set.
num_channels : int, optional
Channel count; required when per_channel is set.
Attributes¶
step : torch.nn.Parameter The learned step size(s). Lazily initialised from the first input.
- init(n_bits)
- forward(x)
- Fake-quantise
xat the learned step, with the LSQ gradient. - integer_weights(x)
- Return integer codes and the step(s) for hardware export.
Class LSQLinear¶
Linear layer whose weights are quantised by a learned step size.
Per-channel (per output neuron) quantisation is the default, matching the granularity that recovers most of the accuracy lost to low-bit weights.
Parameters¶
in_features, out_features : int Layer dimensions. n_bits : int Weight quantiser bit width. per_channel : bool Learn one step per output neuron (default) or a single scalar step. bias : bool Whether to include a full-precision bias.
- init(in_features, out_features)
- forward(x)
- Apply the layer with LSQ-quantised weights.
- export_quantized()
- Export integer weights, the learned step(s), and the bias.
Module qat.observers¶
Class MinMaxObserver¶
Per-tensor running min/max range observer.
Parameters¶
n_bits : int Quantiser bit width the derived scale targets. symmetric : bool Use a symmetric (zero-centred) mapping — the default for weights. unsigned : bool Target an unsigned integer grid (e.g. non-negative activations). eps : float Scale floor guarding against a zero-width observed range.
- init(n_bits)
- observe(x)
- Fold
xinto the running range and return it unchanged. - calculate_qparams()
- Return the
(scale, zero_point)for the observed range. - quantize(x)
- Fake-quantise
xwith the currently observed scale.
Class PerChannelMinMaxObserver¶
Per-channel running min/max range observer.
Tracks an independent min/max — and therefore an independent scale — for
every slice along ch_axis. For a weight tensor shaped
(out_features, in_features) the default ch_axis=0 yields one scale
per output neuron.
Parameters¶
n_bits : int Quantiser bit width the derived scales target. ch_axis : int Axis whose length is the channel count. symmetric : bool Use a symmetric (zero-centred) mapping — the default for weights. unsigned : bool Target an unsigned integer grid. eps : float Scale floor guarding against a zero-width observed range.
- init(n_bits)
- observe(x)
- Fold
xinto the running per-channel range and return it unchanged. - calculate_qparams()
- Return the per-channel
(scale, zero_point)vectors. - quantize(x)
- Fake-quantise
xwith the observed per-channel scales.
Function fake_quantize(x, scale, zero_point)¶
Quantise then de-quantise x (simulated quantisation, no STE).
This is the inference-time / calibration-time fake-quant used to evaluate
an observer's scales; for training use the learned-step quantisers in
:mod:sc_neurocore.qat.lsq. scale and zero_point broadcast against
x, so per-channel parameters must already be reshaped onto the channel
axis by the caller.
Parameters¶
x : torch.Tensor
Tensor to fake-quantise.
scale, zero_point : torch.Tensor
Quantiser parameters, broadcastable to x.
n_bits : int
Quantiser bit width.
unsigned : bool
Whether the integer grid is unsigned.
Returns¶
torch.Tensor
The de-quantised approximation of x on the integer grid.
Module qat.pact¶
Class PACTActivation¶
Parameterised clipping activation with uniform quantisation.
Parameters¶
n_bits : int
Activation quantiser bit width (>= 2). The activation grid has
2**n_bits - 1 positive levels over [0, alpha].
alpha_init : float
Initial clipping bound.
Attributes¶
alpha : torch.nn.Parameter The learned clipping bound.
- init(n_bits, alpha_init)
- forward(x)
- Clip
xto[0, alpha]and quantise ton_bitslevels. - quantize(x)
- Return integer activation codes and the scale for export.
- extra_repr()
- Return the compact module representation.
Module qat.quantize¶
Class TernaryWeights¶
Ternary weight quantization: {-1, 0, +1}.
94% memory reduction. Each weight is one of three values. Threshold-based: weights with |w| < threshold become 0.
Parameters¶
threshold_ratio : float Fraction of max(|w|) below which weights are zeroed.
- init(threshold_ratio)
- quantize(weights)
- sparsity(weights)
Class QuantizedSNNLayer¶
SNN layer with quantization-aware forward pass.
During training: weights quantized in forward, full-precision in backward (STE). At export: weights are already at target precision.
Parameters¶
n_inputs : int n_neurons : int weight_bits : int Target weight precision (2, 4, 8, 16). threshold : float tau_mem : float
- post_init()
- forward(x, dt)
- Quantization-aware forward pass.
- export_weights()
- Export quantized weights for hardware deployment.
- reset()
Function quantize_aware_train_step(layer, x, target, lr)¶
One QAT training step with STE.
Parameters¶
layer : QuantizedSNNLayer x : ndarray of shape (n_inputs,) target : ndarray of shape (n_neurons,) lr : float
Returns¶
dict with 'output', 'loss'
Module qat.torch_qat¶
Class QuantizedLinear¶
Linear layer with STE weight quantization.
- init(in_features, out_features, n_bits, bias)
- forward(x)
- export_quantized()
- Export integer weights at target precision.
Class QuantizedLIFNet¶
Feedforward SNN with quantized weights for QAT.
Drop-in replacement for SpikingNet with configurable bit precision.
Example¶
net = QuantizedLIFNet(784, 128, 10, n_bits=4) x = torch.randn(25, 32, 784) # (T, batch, features) spikes, mem = net(x) spikes.shape torch.Size([32, 10])
- init(n_input, n_hidden, n_output, n_layers, n_bits, beta, surrogate_fn)
- forward(x)
- x: (T, batch, n_input). Returns (spike_counts, membrane_acc).
- export_quantized()
- Export all layers as quantized integer weights.
- effective_bits()
- Average effective bits across all weights (for reporting).
Class SCAwareLinear¶
Linear layer with SC noise injection during training.
During training: injects Gaussian noise with std = sqrt(p*(1-p)/L) to simulate bitstream variance. Weights clamped to [-1, 1].
During eval: no noise, standard linear.
- init(in_features, out_features, bitstream_length, bias)
- forward(x)
Class SCAwareLIFNet¶
SNN with SC-aware training: noise injection + weight clamping.
Trains the model to be robust to stochastic computing bitstream variance. Weights are constrained to [-1, 1] (bipolar SC range).
Example¶
net = SCAwareLIFNet(784, 128, 10, bitstream_length=256) x = torch.randn(25, 32, 784) spikes, mem = net(x)
- init(n_input, n_hidden, n_output, n_layers, bitstream_length, beta, surrogate_fn)
- forward(x)
- x: (T, batch, n_input). Returns (spike_counts, membrane_acc).
- export_bipolar_weights()
- Export weights clamped to [-1, 1] for bipolar SC deployment.
Class LSQPACTLIFNet¶
Feedforward SNN with LSQ weights and a PACT-quantised analogue input.
Combines the learned-step per-channel weight quantiser
(:class:~sc_neurocore.qat.lsq.LSQLinear) with the parameterised-clipping
activation quantiser (:class:~sc_neurocore.qat.pact.PACTActivation): the
continuous input current is clipped and quantised by a learned bound before
the first layer, and every dense layer's weights carry an independently
learned per-output-neuron step size. Inter-layer signals are binary spikes,
so only the input needs activation quantisation.
Parameters¶
n_input, n_hidden, n_output : int Layer dimensions. n_layers : int Number of hidden layers. weight_bits : int Bit width of the LSQ weight quantiser. act_bits : int Bit width of the PACT input-activation quantiser. beta : float LIF membrane decay. surrogate_fn : Callable Surrogate-gradient spike function. per_channel : bool Learn a per-output-neuron weight step (default) or a single scalar step.
Example¶
net = LSQPACTLIFNet(784, 128, 10, weight_bits=4, act_bits=4) x = torch.randn(25, 32, 784) # (T, batch, features) spikes, mem = net(x) spikes.shape torch.Size([32, 10])
- init(n_input, n_hidden, n_output, n_layers, weight_bits, act_bits, beta, surrogate_fn, per_channel)
- forward(x)
- x: (T, batch, n_input). Returns (spike_counts, membrane_acc).
- export_quantized()
- Export LSQ integer weights per layer plus the PACT input scale.
Function ste_quantize(x, n_bits, symmetric)¶
Quantize tensor with straight-through estimator.
Module quantum.hardware_bridge¶
Class QuantumHardwareLayer¶
Executes a Quantum-Classical Hybrid Layer on Qiskit/PennyLane. Maps bitstream probability -> Qubit Rotation -> True Measurement.
- post_init()
- forward(input_bitstreams)
- input_bitstreams: (n_qubits, length)
Module quantum.hybrid¶
Class QuantumStochasticLayer¶
Simulates a Quantum-Classical Hybrid Layer. Input bitstream probability -> Qubit Rotation -> Measurement Probability.
Mapping: p_in -> theta = p_in * pi P_out = |<0|Ry(theta)|0>|^2 = cos^2(theta/2) This non-linearity is useful for classification.
- post_init()
- forward(input_bitstreams)
- input_bitstreams: (n_qubits, length)
Module quantum.hybrid_pipeline¶
Class HybridQuantumClassicalPipeline¶
- init(n_qubits, n_layers, noise_model)
- circuit(params)
- Parameterized Ry-CNOT circuit → ⟨Z⊗Z⟩ expectation.
- train(n_steps, lr)
- VQE-style optimization: minimize ⟨Z⊗Z⟩.
- evaluate(params)
Module quantum.noise_models¶
Class HeronR2NoiseParams¶
IBM Heron r2 calibration parameters (2024).
Class HeronR2NoiseModel¶
- init(params)
- depolarizing_channel(p)
- Kraus operators for single-qubit depolarizing channel.
- amplitude_damping(gamma)
- Kraus operators for amplitude damping (T1 decay).
- phase_damping(gamma)
- Kraus operators for phase damping (T2 decay).
- apply_single_qubit_noise(rho)
- Apply single-qubit noise channel to density matrix.
- apply_readout_noise(measurement)
- Apply asymmetric readout error.
- gate_fidelity_1q()
- gate_fidelity_2q()
Module quantum.param_shift¶
Class ParameterShiftOptimizer¶
- init(circuit_fn, n_params, lr)
- compute_gradient(params)
- step(params)
Function parameter_shift_gradient(circuit_fn, params, shift)¶
Gradient via parameter-shift rule.
f'(θ_i) = [f(θ_i + s) - f(θ_i - s)] / (2 sin(s))
Module quantum.qec¶
Class QecShield¶
Repetition code QEC shield for stochastic-quantum bitstreams.
- init(code_type, distance)
- encode(bitstream)
- repetition code (d=3): 0 -> 000, 1 -> 111
- extract_syndromes(physical_bits)
- decode(physical_bits)
- get_error_rate(syndromes)
Class SurfaceCodeShield¶
Distance-d rotated surface code for stochastic-quantum bitstreams.
Encodes 1 logical qubit into d² physical data qubits. X and Z stabilizers detect bit-flip and phase-flip errors. Decoding uses a lookup table for d=3.
Ref: Fowler et al., "Surface codes: Towards practical large-scale quantum computation", Phys. Rev. A 86, 032324 (2012).
- init(distance)
- encode(bitstream)
- Encode logical bitstream into surface code physical qubits.
- measure_syndrome(physical_bits)
- Measure X and Z stabilizer syndromes.
- decode(physical_bits)
- Decode surface code: measure syndromes, correct single-qubit errors, majority vote.
- get_error_rate(x_syn, z_syn)
- Estimated error rate from syndrome density.
Module quantum.sc_quantum_compiler¶
Class QuantumGate¶
A quantum gate applied to specific qubits.
Class SCQuantumCircuit¶
Quantum circuit compiled from SC operations.
- simulate()
- Simulate the circuit and return the full statevector.
- output_probability()
- Simulate and return P(output_qubit = |1⟩).
- simulate_noisy(noise_model)
- Simulate with noise: evolve density matrix through Kraus channels.
- output_probability_noisy(noise_model, n_shots)
- Simulate with noise and return P(output=1) via measurement sampling.
- summary()
Function sc_prob_to_statevector(p)¶
Encode SC probability as a single-qubit state vector.
|ψ⟩ = √(1-p)|0⟩ + √p|1⟩ → P(measure |1⟩) = p exactly.
Function statevector_to_prob(sv)¶
Extract SC probability from a single-qubit state vector via Born rule.
Function ry_gate(theta)¶
Ry rotation gate: encodes probability via rotation angle.
Function prob_to_ry_angle(p)¶
Compute Ry angle that encodes probability p: sin²(θ/2) = p.
Function compile_sc_multiply(p_a, p_b)¶
Compile SC AND gate (multiplication) to a quantum circuit.
SC: P(a AND b) = P(a) * P(b) for independent streams. Quantum: encode probabilities as Ry rotations, use CNOT for correlation.
Function compile_sc_layer(weights, input_probs)¶
Compile an SC dense layer to quantum gate descriptions.
Parameters¶
weights : np.ndarray Shape (n_neurons, n_inputs), values in [0, 1]. input_probs : np.ndarray Shape (n_inputs,), SC input probabilities.
Returns¶
list of dicts, one per neuron, each containing: 'neuron_idx': int 'ry_angles': list of (input_angle, weight_angle) pairs 'expected_output': float — SC computation result 'quantum_output': float — quantum simulation result
Module quantum_cognition.__main__¶
Function cmd_learn(args)¶
Run one bounded learning pass over a repository.
Parameters¶
args
Parsed learn sub-command arguments, including the repository path,
state-file path, model override, and SNN stimulus directory.
Returns¶
int
Process-style exit code, 0 after the learning pass and state write
complete.
Function cmd_daemon(args)¶
Run the continuous repository-learning daemon.
Parameters¶
args
Parsed daemon sub-command arguments, including cycle size, sleep
interval, state-file path, optional dashboard flag, and stimulus directory.
Returns¶
int
Process-style exit code, 0 after graceful shutdown and final state
persistence.
Function cmd_status(args)¶
Print a saved learning-state summary.
Parameters¶
args
Parsed status sub-command arguments containing the state-file path.
Returns¶
int
0 when a readable state file is summarised, 1 when the file is
absent, empty, or unreadable.
Function main(argv)¶
Dispatch the quantum-cognition CLI.
Parameters¶
argv
Optional argument vector. None uses sys.argv through
:mod:argparse.
Returns¶
int
Process-style exit code from the selected sub-command, or 0 after
printing help when no sub-command is provided.
Module quantum_cognition.bridge_adapter¶
Class FisherPosnerQuantumBridge¶
Bridge between SpinPoolMPS and quantum hardware / orchestrator.
Supports three operational modes:
- Emulated (default): Pure NumPy phase optimisation via the MPS emulator. No external dependencies required.
- PennyLane: Gradient-based phase optimisation using PennyLane autograd on simulated qubits.
- Orchestrator: Accepts global phase vectors from the scpn-phase-orchestrator and combines them with local optimisation.
Parameters¶
n_qubits : int
Number of qubits / spin sites.
backend : str
Backend selection: "auto", "pennylane", "ibm_qiskit",
or "emulated".
- init(n_qubits, backend)
- backend()
- Active backend name.
- execute_non_local_sync(entangle_pairs)
- Execute non-local synchronisation via entanglement.
- execute_posner_circuit(shots)
- Dispatch an actual 8q Posner Hamiltonian circuit to IBM QPU.
- optimize_phases(target_coherence, learning_rate, n_steps)
- Optimise qubit phases towards target coherence.
- apply_orchestrator_bias(global_phases, target_coherence, learning_rate)
- Combine global orchestrator phases with local optimisation.
- to_qpu_artifact_metadata()
- Produce metadata for QPUBridgeArtifact integration.
- repr()
Function compute_max_qubits(safety_factor)¶
Compute maximum PennyLane qubits that fit in available RAM.
PennyLane default.qubit uses a dense state vector of shape
(2**n_qubits,) with complex128 (16 bytes per amplitude).
This function reads available RAM and computes the largest qubit
count that stays within the safety budget.
Falls back to /proc/meminfo if psutil is unavailable
(common on minimal containers).
Parameters¶
safety_factor : float Fraction of available RAM to allow (0, 1]. Default 0.5.
Returns¶
int
Maximum qubit count, clamped to [_QUBIT_FLOOR, _QUBIT_CEILING].
Module quantum_cognition.content_indexer¶
Class ContentChunk¶
A single indexed content chunk from a GOTM repository.
Attributes¶
repo_name : str
Repository name (e.g. "SC-NEUROCORE").
file_path : str
Relative path within the repository.
chunk_index : int
Sequential index within the file.
text : str
Raw text content of the chunk.
content_type : str
One of "docstring", "comment", "markdown", "code",
"metadata".
weight : float
Priority weight based on file type.
sha256 : str
SHA-256 hash of the chunk text (provenance).
- post_init()
- summary()
- First 200 characters of the chunk text.
- to_dict()
- Serialise to JSON-compatible dict.
Function index_file(file_path, repo_name, repo_root)¶
Index a single file into content chunks.
Parameters¶
file_path : Path Absolute path to the file. repo_name : str Name of the repository. repo_root : Path Root directory of the repository.
Returns¶
list[ContentChunk] Extracted content chunks with provenance metadata.
Function index_gotm_repo(repo_path, repo_name)¶
Index an entire GOTM repository into content chunks.
Parameters¶
repo_path : str or Path Path to the repository root. repo_name : str, optional Override repository name (default: directory name).
Returns¶
list[ContentChunk] All indexed chunks sorted by weight (descending).
Function embed_chunks(chunks, n_dims, seed)¶
Convert content chunks to numerical vectors for neural input.
Uses a lightweight deterministic hashing approach (not a neural embedding model) to produce fixed-size feature vectors. Each dimension captures a different statistical property of the text:
- Character frequency distribution (dims 0–25)
- Text length features (dim 26–27)
- Weight and content type (dim 28–29)
- Hash-derived features (dim 30–31)
Parameters¶
chunks : list[ContentChunk] Content chunks to embed. n_dims : int Output vector dimensionality (default 32). seed : int Random seed for hash-derived features.
Returns¶
np.ndarray[Any, Any]
Shape (len(chunks), n_dims), values normalised to [0, 1].
Function embed_tfidf(chunks, n_dims, min_df, max_df_ratio)¶
Compute proper TF-IDF vectors from a corpus of chunks.
Unlike embed_chunks() which uses character statistics, this
computes true TF-IDF with corpus-wide Inverse Document Frequency:
TF(t,d) = log(1 + count(t,d))
IDF(t) = log(N / df(t))
TF-IDF(t,d) = TF(t,d) × IDF(t)
Parameters¶
chunks : list[ContentChunk] Corpus of content chunks. n_dims : int Number of top-IDF terms to use as feature dimensions. min_df : int Minimum document frequency for a term to be included. max_df_ratio : float Maximum document frequency ratio (terms in >85% of docs removed).
Returns¶
tuple[np.ndarray[Any, Any], dict[str, int]]
- TF-IDF matrix of shape (len(chunks), n_dims), L2-normalised.
- Vocabulary mapping {term: dimension_index}.
Module quantum_cognition.dashboard¶
Class TerminalDashboard¶
ANSI terminal dashboard for quantum cognition monitoring.
Parameters¶
max_raster_steps : int Number of recent steps to show in the spike raster. clear_screen : bool Whether to clear terminal before drawing.
- init(max_raster_steps, clear_screen)
- draw(brain)
- Render a single dashboard frame.
- repr()
- Return a concise representation of the dashboard window size.
Module quantum_cognition.fisher_posner¶
Class HybridFisherPosnerLIF¶
LIF neuron with quantum-metabolic coupling via spin pool.
Parameters¶
neuron_id : int Site index in the spin pool (determines entanglement location). spin_pool : SpinPoolMPS Shared spin pool providing non-local ATP modulation. dt : float Integration timestep in ms. v_rest : float Resting membrane potential in mV. v_threshold : float Spike threshold in mV. v_reset : float Post-spike reset potential in mV. tau_m : float Membrane time constant in ms. atp_initial : float Initial ATP level (normalised, 0–1). atp_consumption : float ATP consumed per spike. atp_basal_regeneration : float First-order ATP recovery rate independent of Posner singlet yield. Posner efficiency modulates this baseline rather than replacing cellular metabolism.
- init(neuron_id, spin_pool, dt, v_rest, v_threshold, v_reset, tau_m, atp_initial, atp_consumption, atp_basal_regeneration)
- step(I_in)
- Advance the neuron by one timestep.
- get_state()
- Return full neuron state for checkpointing.
- reset_state()
- Reset to resting potential and full ATP.
- reset()
- Alias for reset_state (NeuronProtocol compatibility).
- v()
- Membrane voltage alias for Population compatibility.
- v(value)
- Assign a finite membrane voltage through the Population alias.
- repr()
- Return compact debug telemetry for the coupled neuron.
Class HybridFisherPosnerLIFNeuron¶
Population-compatible wrapper for HybridFisherPosnerLIF.
This class creates its own SpinPoolMPS and wraps step() to return
0 or 1 (integer spike flag) instead of (Vm, bool), making it
compatible with Population(model='HybridFisherPosnerLIFNeuron', n=N).
The underlying SpinPoolMPS is shared among all neurons in the same Population via class-level pool management.
- init(dt, v_rest, v_threshold, v_reset, tau_m, atp_initial, atp_consumption, atp_basal_regeneration, n_sites)
- step(I_in)
- Advance one timestep, return 1 if spiked else 0.
- v()
- Return the inner neuron's membrane voltage.
- v(value)
- Assign a finite membrane voltage through the wrapper alias.
- v_threshold()
- Return the inner neuron's spike threshold.
- v_rest()
- Return the inner neuron's resting membrane potential.
- get_state()
- Return the inner neuron's checkpointable state.
- reset()
- Reset the wrapped neuron state for NeuronProtocol compatibility.
- reset_state()
- Reset the wrapped neuron state to rest and full ATP.
- repr()
- Return compact debug telemetry for the population wrapper.
Module quantum_cognition.fs_watcher¶
Class GOTMWatcher¶
Watch the GOTM collection for new/modified files.
Parameters¶
watch_path : str or Path
Root directory to monitor.
repo_name : str
Repository name for content chunks.
debounce_s : float
Minimum seconds between re-processing the same file.
poll_interval_s : float
Polling interval when using the fallback backend.
use_polling : bool or None
Force polling mode. None = auto-detect (use watchdog if
available, poll otherwise).
- init(watch_path, repo_name, debounce_s, poll_interval_s, use_polling)
- start()
- Start the watcher in a background daemon thread.
- stop()
- Stop the watcher gracefully.
- get_chunks(max_items)
- Drain the chunk queue (non-blocking).
- is_running()
- Whether the watcher thread is active.
- repr()
Module quantum_cognition.gotm_brain¶
Class LearningStep¶
Record of a single learning step for telemetry.
- to_dict()
- Serialise to JSON-compatible dict.
Class GOTMBrain¶
Self-learning brain for the God of the Math collection.
Composes quantum cognition classes with a local LLM to create a neural system that learns from GOTM content.
Parameters¶
n_neurons : int
Number of neurons (also determines spin pool sites and qubit count).
bridge_backend : str
Quantum bridge backend ("emulated", "pennylane",
"ibm_aer", "ibm_qiskit", or "auto"). The default is
explicit emulation so repository learning never silently switches to
an expensive simulator because an optional package is installed.
seed : int or None
Random seed for reproducibility.
- init(n_neurons, bridge_backend, seed, llm_endpoint)
- get_llm_guidance(context_summary)
- Query the configured local LLM for a learning directive.
- process_content(input_vector, directive)
- Process a content vector through the neural network.
- learn_step(chunk, vector)
- Execute a single learning step on one content chunk.
- learn_from_repo(repo_path, repo_name, max_chunks)
- Index and learn from an entire GOTM repository.
- get_learning_state()
- Return full learning state for inspection and persistence.
- get_history()
- Return learning history as a list of dicts.
- save_state(path)
- Persist full brain state (v_deep) to a JSON file.
- load_state(path)
- Restore brain state (v_deep) from a previously saved JSON file.
- reset()
- Reset all neurons, spin pool, and history.
- repr()
- Return a concise representation of the brain learning state.
Module quantum_cognition.kane_mapper¶
Class KaneRegisterLayout¶
Physical layout of a Si:P qubit register.
Attributes¶
n_qubits : int
Number of ³¹P donor qubits.
qubit_positions : np.ndarray[Any, Any]
Shape (n_qubits, 2) — (x, y) coordinates in nanometres.
coupling_matrix : np.ndarray[Any, Any]
Shape (n_qubits, n_qubits) — exchange coupling J(d) in meV.
Symmetric, diagonal is zero.
depth_nm : float
Implantation depth below Si surface.
t2_budget_ms : float
T₂ decoherence budget for the register in milliseconds.
max_gate_depth : int
Maximum circuit depth achievable within the T₂ budget.
gate_schedule : list[dict]
Ordered list of gate operations with timing.
- to_dict()
- Serialise to JSON-compatible dict.
Class KaneSiliconMapper¶
Map SpinPoolMPS sites to a Kane-architecture Si:P register.
Parameters¶
spacing_nm : float
Target inter-donor spacing in nanometres (default 20 nm).
depth_nm : float
Implantation depth below silicon surface (default 20 nm).
topology : str
Layout topology: "linear", "grid", "triangular", or
"hexagonal".
- init(spacing_nm, depth_nm, topology)
- map_pool_to_register(n_sites)
- Compute physical qubit placement and coupling matrix.
- get_constraints(n_sites)
- Return design constraints for a register of given size.
- repr()
- Return a concise constructor-style mapper description.
Module quantum_cognition.radical_pair¶
Class RadicalPairParams¶
Parameters for a radical pair system.
Attributes¶
hyperfine_a : float
Isotropic hyperfine coupling constant in MHz for the exact default
one-nucleus model. Posner-specific calculations must pass explicit
tensors via hyperfine_tensors_1 and/or hyperfine_tensors_2.
exchange_j : float
Exchange coupling in MHz.
Typical: 0–10 MHz for separated radicals in Posner molecules.
recombination_rate : float
Radical pair recombination rate in µs⁻¹.
Typical: 0.01–1.0 µs⁻¹.
lifetime_us : float
Radical pair lifetime in µs.
Posner molecules: ~1–1000 µs (protected by Ca₉(PO₄)₆ cage).
hyperfine_tensors_1, hyperfine_tensors_2 : list[np.ndarray[Any, Any]]
3×3 hyperfine tensors in MHz for nuclei coupled to electron 1 and
electron 2 respectively.
quadrature_order : int
Gauss-Legendre points for finite-lifetime recombination integration.
Class RadicalPairModel¶
Density-matrix radical pair mechanism for ATP hydrolysis gating.
Computes singlet yield (probability of productive ATP hydrolysis) as a function of local magnetic field and radical pair parameters.
Parameters¶
params : RadicalPairParams, optional RPM parameters. Defaults are an exact one-nucleus isotropic RPM, not a Posner molecule parameterization.
- init(params)
- from_hyperfine_tensors(cls)
- Construct an exact RPM model from explicit 3×3 hyperfine tensors.
- singlet_yield(b_local)
- Compute singlet yield Φ_S for the current parameters.
- singlet_yield_field_sweep(b_range)
- Compute singlet yield over a range of magnetic fields.
- atp_efficiency(b_local, entanglement_boost)
- Compute ATP hydrolysis efficiency from singlet yield.
- get_state()
- Return parameters as a dict for serialisation.
- repr()
- Return a concise representation of the active RPM parameters.
Module quantum_cognition.spin_pool¶
Class SpinCouplingTensor¶
Two-spin coupling tensor in MHz.
tensor_mhz[a, b] multiplies S_i^a S_j^b for
a,b ∈ {x,y,z}. This supports isotropic exchange, anisotropic
dipolar coupling, and off-diagonal tensor terms without adding hidden
model constants.
Class SpinPoolMPS¶
Non-local spin storage using true Matrix Product States.
Simulates entangled :sup:31\ P nuclear spins in Posner molecules.
Each site corresponds to a phosphorus nuclear spin represented as a
rank-3 tensor A[α, σ, β] where:
- α, β are bond indices (dimension bond_dim)
- σ is the physical index (0 = spin-up, 1 = spin-down)
The full state |Ψ⟩ = Σ Tr(A¹[σ₁]·A²[σ₂]·…·Aⁿ[σₙ]) |σ₁…σₙ⟩
Parameters¶
n_sites : int Number of nuclear spin sites. bond_dim : int Maximum bond dimension (controls entanglement capacity). correlation_length : float Initialisation parameter for inter-site correlation decay. update_rate : float Mixing rate α for entanglement map updates on spike events.
- init(n_sites, bond_dim, correlation_length, update_rate, seed)
- to_statevector()
- Return the exact statevector represented by this MPS.
- set_statevector(statevector)
- Load a statevector into MPS form without silent truncation.
- evolve_exact(couplings, time_us)
- Evolve under explicit two-spin coupling tensors.
- apply_measurement(site_idx, intensity)
- Apply a Born-rule projective measurement at one spin site.
- get_local_atp_efficiency(site_idx)
- Return ATP hydrolysis probability at a given site.
- rho()
- Return site-0 reduced density matrix (backward compat).
- get_status()
- Return summary status for telemetry and visualisation.
- get_state()
- Return full internal state for checkpointing.
- set_state(state)
- Restore internal state from a checkpoint dictionary.
- reset()
- Reset to product state.
- to_scpn_payload()
- Produce metadata compatible with SCPNDatastream format.
- repr()
- Return a concise diagnostic summary for logs and dashboards.
Module quantum_cognition.studio_hook¶
Class QuantumCognitionLayerMetadata¶
Structured metadata for the quantum cognition visualisation layer.
- to_dict()
- Serialise to a JSON-compatible dict.
Class QuantumStudioHook¶
Telemetry endpoint for quantum cognition layer visualisation.
Provides structured metadata and streaming data for SNN Visual Studio and SCPN Studio frontends.
Parameters¶
spin_pool : SpinPoolMPS The spin pool to observe. bridge : FisherPosnerQuantumBridge The quantum bridge to observe.
- init(spin_pool, bridge)
- get_layer_metadata()
- Return layer metadata for the Studio layer panel.
- get_layer_metadata_dict()
- Return layer metadata as a plain dict (JSON-serialisable).
- get_realtime_data()
- Return streaming data for live entanglement graph.
- get_entanglement_snapshot()
- Return a timestamped snapshot of entanglement and ATP state.
- to_json_event(event_type)
- Produce a JSON event string for external frontend streaming.
- repr()
- Return debug representation with observed pool and bridge handles.
Module quantum_cognition.tests.fisher_posner_support¶
Function pool_and_neuron()¶
Module quantum_cognition.tests.test_dashboard¶
Class FakeNeuron¶
Minimal neuron telemetry record consumed by the dashboard renderer.
Class FakePool¶
Minimal spin-pool telemetry record consumed by the dashboard renderer.
- init(entanglement_map)
- Store a deterministic entanglement map for dashboard rendering.
Class FakeBrain¶
Small dashboard-compatible brain fixture exercising the public draw path.
- init(history)
- Initialise deterministic dashboard telemetry.
- get_learning_state()
- Return the state dictionary read by the dashboard header.
- get_history()
- Return spike and directive history entries for raster rendering.
Function test_dashboard_draw_covers_terminal_fallback_and_history_bands(monkeypatch, capsys)¶
Draw uses fallback terminal size and renders all spike-raster bands.
Function test_dashboard_draw_reports_hidden_neuron_count(monkeypatch, capsys)¶
Draw reports hidden neuron counts when the terminal is narrow.
Function test_bar_handles_non_positive_scale()¶
Bar renderer returns an empty-scale bar for non-positive maxima.
Function test_dashboard_repr_reports_raster_window()¶
The dashboard repr includes the configured raster window.
Module quantum_cognition.tests.test_fisher_posner_hybrid_fisher_posner_lif¶
Class TestHybridFisherPosnerLIF¶
- test_resting_state(pool_and_neuron)
- test_subthreshold_no_spike(pool_and_neuron)
- Small input should not trigger a spike.
- test_suprathreshold_spike(pool_and_neuron)
- Large input should trigger a spike.
- test_metabolic_failure(pool_and_neuron)
- Depleted ATP should prevent spiking (metabolic failure).
- test_atp_regeneration(pool_and_neuron)
- ATP should regenerate over time via quantum efficiency.
- test_spike_feeds_back_to_pool(pool_and_neuron)
- Spiking should call apply_measurement on the spin pool.
- test_v_property(pool_and_neuron)
- v property should alias Vm.
- test_reset(pool_and_neuron)
- test_get_state(pool_and_neuron)
- test_invalid_neuron_id()
- test_invalid_type()
Module quantum_cognition.tests.test_fisher_posner_hybrid_fisher_posner_lif_neuron¶
Class TestHybridFisherPosnerLIFNeuron¶
- test_wrapper_step()
- Wrapper step should return int (0 or 1).
- test_wrapper_v_property()
Module quantum_cognition.tests.test_gotm_brain_inline_gotm_brain_llm¶
Class TestGOTMBrainLLM¶
- test_fallback_directive()
- Without LLM, should return STABILIZE.
- test_process_content()
- process_content should return list of spike indices.
Module quantum_cognition.tests.test_gotm_brain_inline_gotm_brain_misc¶
Class TestGOTMBrainMisc¶
- test_reset()
- test_get_learning_state()
- test_repr()
- test_learning_step_to_dict()
Module quantum_cognition.tests.test_gotm_brain_inline_gotm_brain_persistence¶
Class TestGOTMBrainPersistence¶
- test_save_load_roundtrip(tmp_path)
- State should survive save → load cycle.
- test_load_mismatched_neurons(tmp_path)
- Loading state with wrong neuron count should raise.
Module quantum_cognition.tests.test_gotm_brain_llm_contracts¶
Function test_gotm_brain_import_detects_local_llm(monkeypatch)¶
Importing with a local llm module enables the LLM directive path.
Function test_gotm_brain_invalid_llm_directive_falls_back(monkeypatch)¶
Unknown local LLM replies fall back to the stable directive.
Function test_gotm_brain_llm_exception_falls_back(monkeypatch)¶
Local LLM runtime errors fall back to the stable directive.
Module quantum_cognition.tests.test_kane_mapper¶
Class TestKaneSiliconMapper¶
Contract tests for the Kane silicon register mapper.
- test_linear_positions()
- Linear topology should place qubits in a line.
- test_grid_positions()
- Grid topology should place qubits in a 2D arrangement.
- test_triangular_positions_stagger_odd_rows()
- Triangular topology staggers every odd row by half a spacing.
- test_hexagonal_positions_stop_after_requested_site_count()
- Hexagonal topology fills only the requested number of donor sites.
- test_coupling_matrix_symmetry()
- Coupling matrix must be symmetric with zero diagonal.
- test_coupling_decay()
- Coupling should decay with distance.
- test_coupling_positive()
- All coupling values should be non-negative.
- test_exchange_coupling_returns_prefactor_at_zero_distance()
- Co-located donors use the Kane exchange prefactor directly.
- test_t2_budget()
- T₂ budget must be positive.
- test_single_qubit()
- Single qubit register should work.
- test_zero_sites_are_rejected()
- Zero-site registers are invalid because no donor can be placed.
- test_constraints()
- Constraints dict should contain all expected fields.
- test_constraints_infeasible()
- Wide spacing should be infeasible (coupling too weak).
- test_serialisation()
- to_dict should produce JSON-compatible output.
- test_invalid_spacing()
- Non-positive donor spacing is rejected.
- test_invalid_topology()
- Unknown lattice topology names are rejected.
- test_repr()
- The repr reports spacing and topology for diagnostics.
Module quantum_cognition.tests.test_radical_pair_contracts¶
Function test_rejects_invalid_quadrature_order()¶
Constructor rejects quadrature rules that cannot integrate an interval.
Function test_explicit_hyperfine_tensor_state_counts()¶
Explicit tensor construction records nuclei on both radicals.
Function test_invalid_hyperfine_tensor_shape_is_rejected()¶
Tensor validation reports the exact radical-side tensor index.
Function test_zero_nucleus_singlet_density_has_electron_dimension()¶
The no-bath helper returns pure electron singlet density matrices.
Function test_dense_hamiltonian_rejects_oversized_nuclear_bath()¶
Dense exact evolution fail-closes before allocating huge spin operators.
Function test_singlet_yield_rejects_non_positive_rates(params, message)¶
Singlet-yield validation rejects non-positive kinetic parameters.
Module quantum_cognition.tests.test_radical_pair_radical_pair_model¶
Class TestRadicalPairModel¶
- test_singlet_yield_zero_field()
- At zero field, singlet yield depends only on exchange/hyperfine ratio.
- test_singlet_yield_range()
- Singlet yield must be bounded [0, 1].
- test_strong_exchange_preserves_singlet()
- Strong exchange coupling should preserve singlet character.
- test_weak_exchange_reduces_singlet()
- Weak exchange coupling leads to more mixing → lower singlet yield.
- test_field_sweep()
- Field sweep should return array of correct length.
- test_atp_efficiency_rejects_entanglement_boost()
- Classical boost is not a radical-pair Hamiltonian parameter.
- test_atp_efficiency_range()
- ATP efficiency is singlet-yield-derived and bounded.
- test_get_state()
- State dict should contain all params.
- test_repr()
Module quantum_cognition.tests.test_radical_pair_radical_pair_params¶
Class TestRadicalPairParams¶
- test_defaults()
- test_custom()
Module quantum_cognition.tests.test_spin_pool¶
Class TestSpinPoolMPS¶
Contract tests for the exact spin-pool MPS publication path.
- test_init_defaults()
- Default construction creates an eight-site product-state pool.
- test_entanglement_map_normalised()
- Entanglement map should sum to 1 after init.
- test_measurement_updates_map()
- Measurement at a site should shift entanglement towards that site.
- test_normalisation_preserved()
- Entanglement map should remain normalised after measurements.
- test_atp_efficiency_range()
- ATP efficiency is a singlet probability in [0, 1].
- test_invalid_site_index()
- Measurement rejects negative and out-of-range spin-site indices.
- test_negative_intensity()
- Measurement intensity must be non-negative.
- test_reset()
- Reset restores the product state and clears measurement metadata.
- test_state_roundtrip()
- get_state → set_state should preserve state.
- test_scpn_payload()
- SCPN payload exposes entanglement and ATP observable arrays.
- test_invalid_params()
- Constructor rejects invalid site, bond, and update parameters.
- test_singlet_statevector_roundtrip_preserves_atp_observable()
- Singlet import/export preserves the ATP singlet observable.
- test_statevector_import_rejects_invalid_public_contracts()
- Statevector import/export rejects invalid public contracts.
- test_statevector_import_rejects_silent_bond_truncation()
- Statevector import rejects states exceeding configured bond rank.
- test_checkpoint_without_map_recomputes_quantum_diagnostics()
- Checkpoint restore recomputes diagnostics when the map is absent.
- test_corrupted_checkpoint_zero_norm_fails_on_statevector_export()
- Corrupted zero-norm checkpoint tensors fail on exact export.
- test_single_site_pool_rejects_two_site_atp_observable()
- A one-site pool cannot expose the two-site ATP observable.
- test_atp_observable_rejects_out_of_range_public_site()
- ATP observable rejects public site indices outside the spin pool.
- test_exact_evolution_rejects_invalid_coupling_contracts()
- Exact dense evolution rejects invalid time, size, and couplings.
- test_exact_evolution_preserves_norm_for_valid_public_coupling()
- Exact dense evolution accepts a valid coupling tensor and stays unitary.
- test_status_and_repr_report_public_telemetry()
- Status and repr expose stable telemetry fields for dashboards.
- test_internal_heisenberg_same_site_is_noop()
- Internal same-site Heisenberg routing leaves the state unchanged.
- test_internal_tebd_gate_rejects_non_adjacent_sites()
- Internal TEBD gate rejects non-adjacent site pairs explicitly.
- test_internal_heisenberg_adjacent_gate_preserves_state_norm()
- Internal adjacent Heisenberg routing preserves state norm.
- test_internal_heisenberg_nonadjacent_swap_network_preserves_state_norm()
- Internal non-adjacent Heisenberg routing preserves state norm.
Module recorders.spike_recorder¶
Class BitstreamSpikeRecorder¶
Record a binary spike train and compute basic spike statistics.
Parameters¶
dt_ms:
Duration represented by one recorded sample in milliseconds. A value of
0.0 is accepted for legacy zero-duration dry runs and produces a
firing rate of 0.0.
spikes:
Existing spike samples to seed the recorder with. Values must be binary
integers where 1 means a spike occurred at that sample.
- post_init()
- Validate seeded recorder state.
- record(spike)
- Append one binary spike sample.
- reset()
- Remove all recorded spike samples while preserving
dt_ms. - as_array()
- Return the recorded spike train as a NumPy
uint8array. - total_spikes()
- Return the number of recorded spike samples equal to
1. - firing_rate_hz()
- Return the mean firing rate in hertz.
- isi_histogram(bins)
- Compute a histogram of inter-spike intervals in milliseconds.
Module refusals¶
Class AuthoredRefusal¶
A deliberate caller-facing refusal, compatible with ValueError handlers.
Raise this type or a domain subclass only with text written for callers. Do not wrap generated exception text in it. HTTP boundaries should accept their own domain subclass and use a fixed message for every other fault.
Module reservoir.auto_reservoir¶
Class ReservoirMetrics¶
Reservoir quality metrics.
- summary()
Class AutoCriticalReservoir¶
Spiking Liquid State Machine with automatic criticality tuning.
Parameters¶
n_inputs : int n_neurons : int Reservoir size. n_outputs : int Readout dimension. threshold : float LIF spike threshold. leak : float Membrane leak factor (0-1). Higher = faster decay. connectivity : float Fraction of possible synapses that exist (sparsity). seed : int
- init(n_inputs, n_neurons, n_outputs, threshold, leak, connectivity, seed)
- spectral_radius()
- reset()
- step(x)
- Process one timestep, return reservoir state (spikes).
- run(inputs)
- Run input sequence through reservoir, return state matrix.
- fit_readout(states, targets, ridge)
- Train readout via ridge regression.
- predict(states)
- Predict from reservoir states.
- train_and_predict(train_inputs, train_targets, test_inputs)
- Full pipeline: run train, fit readout, run test, predict.
- metrics(inputs)
- Compute reservoir quality metrics.
Module residual.blocks¶
Class MembraneShortcutBlock¶
MS-ResNet residual block with membrane shortcut.
Skips the inter-block LIF neuron. Residual connection adds directly to membrane potential, not to spikes.
Parameters¶
n_features : int threshold : float tau_mem : float
- init(n_features, threshold, tau_mem, seed)
- forward(x)
- Forward pass: x -> W1 -> LIF -> W2 -> add residual -> LIF -> spikes.
- reset()
- Reset the block membrane potential to zero.
Class SEWBlock¶
SEW-ResNet block: activation-before-addition.
spike(W@x) + x instead of spike(W@x + x). Prevents identity mapping issues in spiking residual networks.
Parameters¶
n_features : int threshold : float
- init(n_features, threshold, seed)
- forward(x)
- Forward: spike(W@x) + x (element-wise, clamped to [0,1]).
- reset()
- Reset the block membrane potential to zero.
Class DeepSNNStack¶
Stack of residual blocks for building deep SNNs.
Parameters¶
n_features : int n_blocks : int block_type : str 'ms' for MembraneShortcut, 'sew' for SEW.
- init(n_features, n_blocks, block_type)
- forward(x)
- Propagate the input through every residual block in sequence.
- reset()
- Reset the membrane potential of every block in the stack.
- n_blocks()
- Return the number of residual blocks in the stack.
- depth()
- Return the effective depth (two weight layers per block).
Module resilience.fault_suite¶
Class FaultType¶
Class FaultModel¶
One fault injection configuration.
Class FaultResult¶
Result of one fault injection run.
Class ResilienceReport¶
Full fault resilience report.
- degradation_curve(fault_type)
- Get (fault_rate, degradation) pairs for one fault type.
- most_vulnerable_layer()
- Return the layer index with highest average degradation.
- summary()
Class FaultResilienceSuite¶
Systematic fault injection and resilience analysis.
Parameters¶
eval_fn : callable Function(weights) -> accuracy. Takes list of weight matrices, returns accuracy in [0, 1]. weights : list of ndarray Baseline (unfaulted) weight matrices.
- init(eval_fn, weights)
- baseline_accuracy()
- inject_fault(fault)
- Apply a fault model to weights, return faulted copies.
- run_single(fault)
- Run one fault injection experiment.
- sweep(fault_type, rates, per_layer)
- Sweep fault rate and optionally per-layer.
- full_audit()
- Run all fault types at standard rates, per-layer.
Module robotics.cpg¶
Class StochasticCPG¶
Central Pattern Generator using two mutually inhibiting neurons. Generates rhythmic alternating outputs (e.g., Left/Right leg).
- post_init()
- step()
Module robotics.swarm¶
Class SwarmCoupling¶
Synchronize two learning agents by mutually attracting their weights.
- synchronize(agent_a, agent_b)
- Adjust both agents toward a shared weight configuration.
Module runtime_lanes¶
Class LaneContract¶
How a distribution provides one execution lane.
Parameters¶
lane:
The lane's name, as the kernels' backend arguments use it.
distribution:
bundled ships in every distribution, optional-package needs a
separately installed package, source-checkout needs a checkout.
requirement:
What an installation needs for the lane, in words a user can act on.
Class LaneStatus¶
Whether this installation has one lane's resources.
Parameters¶
lane: The lane's name. distribution: How distributions provide it. resources_present: Whether the packages and files the lane needs are present here. detail: What was found, or what is missing and how to provide it.
Function lane_statuses()¶
Report, for every lane, whether this installation has its resources.
Parameters¶
accel_root:
The sc_neurocore.accel directory to inspect; this installation's by
default.
Returns¶
tuple of LaneStatus One status per lane, in contract order. A lane without its resources carries both what is missing and the contract's requirement.
Module safety_cert.certification¶
Class CertificationPackage¶
In-memory safety-evidence reports ready for deterministic materialisation.
- post_init()
- Validate package metadata and every checklist row.
- checklist_coverage()
- Return the fraction with explicit evidence, including partial rows.
- checklist_report()
- Render checklist state without upgrading any evidence status.
- artifacts()
- Return the five deterministic report filenames and their contents.
- content_sha256()
- Return a full digest over metadata and all report contents.
- write(directory)
- Atomically materialise reports and a hash manifest in a new directory.
Class CertificationGenerator¶
Assemble caller-supplied records without fabricating assurance evidence.
- generate(standard, target_sil, modules, formal_properties, network_config)
- Build one evidence package from explicit records and assumptions.
Class SafetyManualGenerator¶
Render a clearly labelled safety-manual template from explicit inputs.
- generate(product_name, sil_level, modules, wcet_ns)
- Generate a non-certifying manual template for later expert review.
Module safety_cert.change_impact¶
Class ChangeRecord¶
One tracked change affecting safety.
- post_init()
- Validate one change record and its affected identifiers.
Class ChangeImpactTracker¶
Tracks changes and their impact on certification artifacts.
- init()
- add_change(change)
- Add one unique change and derive its re-verification flag.
- affected_requirements()
- Return sorted unique requirement IDs affected by recorded changes.
- high_risk_count()
- Return the number of changes labelled high risk.
- needs_re_certification()
- Return the legacy screen for at least one high-risk change.
Module safety_cert.compliance¶
Class ChecklistItem¶
One item in a compliance checklist.
- post_init()
- Validate one checklist row and its evidence state.
Class ComplianceChecklist¶
Generate fail-closed checklist skeletons from curated clause labels.
Clause descriptions and suggested artifact locations are navigation aids, not normative text. Users remain responsible for licensed standards, applicability analysis, evidence review, and conformity assessment.
- generate(cls, standard)
- Create a checklist, marking only caller-supplied evidence partial.
Class SWClass¶
IEC 62304 software safety-class labels.
Class IEC62304Assessment¶
IEC 62304 software safety classification for medical devices.
- post_init()
- Validate the software-class assessment inputs.
- requires_unit_testing()
- Return whether the legacy class screen calls for unit-test evidence.
- requires_architectural_design()
- Return whether the legacy class screen calls for architecture evidence.
- from_sil(sil)
- Return the legacy, non-normative SIL-to-software-class crosswalk.
Class CrossStandardMapper¶
Navigate curated clause relationships without asserting equivalence.
- equivalent_clauses(standard, clause)
- Return a copy of curated related-clause labels.
- coverage_overlap(checklist_a, checklist_b)
- Count shared compliance coverage between two checklists.
Module safety_cert.evidence¶
Class EvidenceItem¶
One relative evidence filename with optional full SHA-256 digest.
- post_init()
- Validate metadata and reject unsafe or ambiguous paths.
Class EvidenceBag¶
Ordered manifest of uniquely named evidence artifacts.
- init()
- Create an empty evidence manifest.
- add(item)
- Add one item while preserving filename uniqueness.
- add_from_package(package)
- Index every in-memory package report with its real content digest.
- file_count()
- Return the number of validated manifest rows.
- manifest()
- Render a Markdown manifest including declared digests.
- content_sha256()
- Return the full digest of all canonical manifest fields.
- compute_hashes()
- Return the historical 32-character prefix of the manifest digest.
- verify(directory)
- Verify all declared digests against regular non-symlink files.
Module safety_cert.failure_analysis¶
Class FailureCategory¶
Failure-effect categories used by the FMEDA arithmetic.
Class FailureMode¶
One failure mode in the FMEDA.
- post_init()
- Validate one caller-supplied failure-mode record.
- safe_failure_fraction()
- Fraction of failures that are safe or detected dangerous.
Class FMEDA¶
Failure Modes, Effects, and Diagnostic Analysis.
Aggregates failure modes for SC neuromorphic modules and computes Safe Failure Fraction (SFF) and Diagnostic Coverage (DC).
- init()
- add_failure_mode(fm)
- Add one uniquely identified failure mode.
- add_sc_standard_modes(component)
- Add the legacy synthetic profile after explicit acknowledgement.
- total_failure_rate()
- Return the sum of caller-supplied FIT values.
- safe_failure_fraction()
- SFF = (safe + no_effect + DC*dangerous_detected) / total.
- diagnostic_coverage()
- Return the FIT-weighted coverage of detected-dangerous modes.
- residual_risk_fit()
- Dangerous-undetected failure rate (residual risk).
- sff_by_component()
- Per-component safe failure fraction.
- max_achievable_sil()
- Return a legacy SFF/DC screening label, not a SIL determination.
- generate_report()
- Render the supplied FMEDA arithmetic and its provenance warning.
Class ReliabilityMetrics¶
System-level reliability from FMEDA data.
- post_init()
- Validate system-level FIT values.
- mtbf_hours()
- Mean Time Between Failures (hours).
- mtbf_years()
- Return mean time between failures in 365-day years.
- pfh_d()
- Probability of dangerous failure per hour.
- pfh_sil()
- Return the legacy PFH-only screening label, not a SIL determination.
- from_fmeda(fmeda)
- Build metrics from explicitly populated FMEDA arithmetic.
Module safety_cert.fault_tolerance¶
Class CCFDefence¶
One defence against common cause failures.
- post_init()
- Validate one common-cause screening defence.
Class CCFAnalysis¶
Non-normative beta-factor screening helper.
Default reductions are legacy modelling assumptions, not measured evidence or a conformity determination.
- init()
- mark_implemented(defence_id)
- Mark one known defence present, returning false for an unknown ID.
- beta_factor()
- Resulting β-factor (start at 0.10, reduce by implemented defences).
- implemented_count()
- Return the number of defences marked present.
- sil_compatible(target_sil)
- Check if β is low enough for the target SIL.
Class HFTLevel¶
Hardware-fault-tolerance screening labels.
Class HFTAssessment¶
Hardware Fault Tolerance assessment per IEC 61508 Table 2.
- post_init()
- Validate screening inputs.
- required_hft()
- Determine required HFT from SFF and target SIL.
- is_simplex_ok()
- Return whether the legacy table screen yields HFT zero.
Module safety_cert.formal_evidence¶
Class FormalProperty¶
One formally verified property.
- post_init()
- Validate a formal-property evidence record.
Class FormalProofCertificate¶
Immutable-content identifier and report for formal-property evidence.
- post_init()
- Validate the certificate container and its property records.
- add_property(prop)
- Append one formal-property evidence record.
- proven_count()
- Return the number of properties explicitly marked proven.
- total_count()
- Return the number of property records.
- pass_rate()
- Return the proven fraction, or zero for an empty certificate.
- content_sha256()
- Return the full SHA-256 digest of every material property field.
- compute_hash()
- Set and return the historical 32-character certificate identifier.
- generate_report()
- Render the formal-property evidence as Markdown.
Class ProofTestCoverage¶
Screen formal-proof completeness without making a compliance claim.
- coverage_from_proofs(properties)
- Formal proof coverage = proven / total asserts.
- dc_to_sil(dc)
- Return the legacy DC-only screening label.
- uncovered_modules(properties, all_modules)
- Modules with no formal proofs.
Class PropertyGap¶
One module with insufficient formal coverage.
- post_init()
- Validate the formal-property gap counts.
- coverage()
- Return the proven fraction, or zero when no properties exist.
Class FormalPropertyGapDetector¶
Detects modules with insufficient formal verification coverage.
- detect(cls, properties, required_modules)
- Return missing or incomplete formal-property coverage by module.
- is_fully_covered(cls, properties, required_modules)
- Return whether every required module passes the configured screen.
Module safety_cert.safety_monitor¶
Class SafetyLimits¶
Configurable safety thresholds matching SV parameters.
Class SafetyMonitor¶
Software mirror of the hardware neuro_safe_monitor.
Enforces all 6 formally proven properties: [P1] monitor_soundness — halt when current/voltage/coherence out of bounds [P2] safe_transition — coherence must not decrease (monotone) [P3] sc_precision_bound — popcount must be in [0, N] [P4] sc_add_preserves_range — SC addition result ≤ denominator [P5] lif_membrane_bounded — membrane ≤ v_max [P6] correlation_range — |SCC numerator| ≤ denominator
- reset()
- Reset monitor state (equivalent to rst_n pulse).
- check(current, voltage, coherence, popcount_k, sc_add_result, membrane, scc_numerator, scc_denominator)
- Check all 6 safety properties. Returns True if any violation detected.
- property_names()
- Return names of violated properties.
Module safety_cert.standards¶
Class SafetyStandard¶
Standards for which the library can organise user-supplied evidence.
Class SILLevel¶
Safety Integrity Level labels used in reports and screening utilities.
Class ASILLevel¶
Automotive Safety Integrity Level labels used by a legacy crosswalk.
Module safety_cert.timing_analysis¶
Class WCETPath¶
Worst-case execution time for one SC computation path.
- post_init()
- Validate one formula-derived timing path.
- total_cycles()
- Return the sum of validated stage-cycle counts.
- wcet_ns(clock_mhz)
- Convert cycles to nanoseconds at a caller-supplied clock.
Class WCETAnalyzer¶
Formula model for SC pipeline cycle counts.
This is not a synthesis timing report or a measured hardware bound. It uses the following caller-reviewable stage assumptions: - LFSR encoding: bitstream_length cycles - Dot product: num_inputs cycles - LIF evaluation: fixed (3 cycles) - AER encoding: num_neurons worst-case - STP update: 1 cycle
- analyze(cls, bitstream_length, num_inputs, num_neurons, has_stp)
- Build a single-layer path from explicit dimension assumptions.
- analyze_multistage(cls, layers)
- Analyze a multi-layer SC network.
Module safety_cert.traceability¶
Class Requirement¶
One safety requirement with traceability links.
- post_init()
- Validate the requirement and its initial traceability links.
Class TraceabilityMatrix¶
Requirement → implementation → verification traceability.
Each requirement links to: - Implementation artifacts (RTL files, Python modules) - Verification artifacts (formal proofs, UVM results, tests)
- init()
- add_requirement(req)
- Add one uniquely identified requirement.
- link_implementation(req_id, impl_ref)
- Link an implementation artifact, returning false for an unknown ID.
- link_verification(req_id, verif_ref)
- Link a verification artifact, returning false for an unknown ID.
- coverage()
- Return the fraction of requirements with both link types.
- open_count()
- Return the number of requirements with no implementation link.
- implemented_count()
- Return the number with implementation but no verification link.
- verified_count()
- Return the number with implementation and verification links.
- generate_report()
- Generate a Markdown traceability report.
Module scpn.datastream¶
Class SCPNDatastream¶
In-memory representation of one deterministic SCPN stream.
- n_steps()
- Number of timesteps in the stream.
- n_layers()
- Number of SCPN layer channels in the stream.
- firing_rates()
- Mean spike probability per layer over this stream window.
- rotation_angles_rad()
Ryangles for quantum-control bridges: firing rate times pi.- quantum_amplitudes()
- Real amplitude encoding of firing rates as
[alpha, beta]pairs. - to_json_dict()
- Serialise the datastream to a stable JSON-compatible mapping.
- from_json_dict(cls, payload)
- Load and validate a datastream from a JSON-compatible mapping.
Function generate_scpn_datastream()¶
Generate a deterministic 16-layer stream for inter-repository tests.
The probability envelope is a bounded phase oscillator driven by the
canonical SCPN natural frequencies and a small normalised coupling
bias derived from K_nm. The binary spike train is sampled from
that envelope with a local RNG seeded by seed.
Function validate_scpn_datastream(stream)¶
Validate shape, bounds, and canonical matrix invariants.
Function write_scpn_datastream(path, stream)¶
Write a stream payload to JSON.
Function read_scpn_datastream(path)¶
Read a stream payload from JSON.
Function generate_scpn_datastream_payload()¶
Generate a JSON-compatible stream payload in one call.
Module scpn.dcls_tent_kernel¶
Class DclsForwardResult¶
Result of one DCLS-max tent contraction.
Attributes¶
output_q88 : int
Saturated Q8.8 synapse output.
accumulator_q16_16 : int
Saturated Q16.16 accumulator before the output shift.
overflow : bool
True when accumulator or output saturation occurred.
active_tap_count : int
Number of non-zero spike taps consumed by the contraction.
max_gate_q88 : int
Largest Q8.8 tent gate applied to an active spike tap.
Class DclsBatchResult¶
Per-channel results of a batched DCLS-max tent contraction.
Each array is indexed by output channel and has length B (the number of
centre/sigma pairs supplied).
Attributes¶
outputs_q88 : numpy.ndarray
Saturated Q8.8 outputs, int16.
accumulators_q16_16 : numpy.ndarray
Saturated Q16.16 accumulators, int32.
overflow : numpy.ndarray
Saturation flags, bool_.
active_tap_counts : numpy.ndarray
Active spike-tap counts per channel, int64.
max_gates_q88 : numpy.ndarray
Largest applied tent gate per channel, int16.
Function tent_gate_q88(tap_index, centre_q88, sigma_q88)¶
Return the Q8.8 triangular tent gate for a delay tap.
The gate is max(0, 1 - |delay - centre| / sigma) evaluated in Q8.8 with
truncating integer division, so it matches the synthesisable RTL exactly.
Parameters¶
tap_index : int
Zero-based delay tap; the delay is tap_index in Q8.8 whole units.
centre_q88 : int
Learnable tent centre in Q8.8.
sigma_q88 : int
Tent half-width in Q8.8; must be positive.
Returns¶
int
Tent gate in [0, 256] Q8.8 (256 is 1.0).
Raises¶
ValueError
If sigma_q88 is not positive or tap_index is negative.
Function dcls_max_forward_q88(spikes, weights_q88, centre_q88, sigma_q88)¶
Run one DCLS-max tent contraction in bit-true Q8.8 arithmetic.
Parameters¶
spikes : array_like
Per-tap spike flags; any non-zero entry marks an active tap.
weights_q88 : array_like
Per-tap synaptic weights in Q8.8, same length as spikes.
centre_q88 : int
Learnable tent centre in Q8.8.
sigma_q88 : int
Tent half-width in Q8.8; must be positive.
Returns¶
DclsForwardResult Saturated Q8.8 output, Q16.16 accumulator and saturation diagnostics.
Raises¶
ValueError
If the inputs are empty, length-mismatched or sigma_q88 is not
positive.
Function dcls_max_forward_batch_q88(spikes, weights_q88, centres_q88, sigmas_q88, n_taps)¶
Pure-Python batched DCLS-max contraction — the bit-true floor reference.
Each output channel b contracts its own n_taps-long spike/weight row
through a tent kernel with channel-specific learnable centre/sigma.
Parameters¶
spikes : array_like
Flattened n_channels * n_taps spike flags (row-major per channel).
weights_q88 : array_like
Flattened n_channels * n_taps Q8.8 weights (row-major per channel).
centres_q88 : array_like
Per-channel learnable tent centres in Q8.8, length n_channels.
sigmas_q88 : array_like
Per-channel tent half-widths in Q8.8, length n_channels; positive.
n_taps : int
Number of delay taps per channel.
Returns¶
DclsBatchResult Per-channel saturated outputs, accumulators and diagnostics.
Raises¶
ValueError
If shapes are inconsistent or any sigma is non-positive.
Function available_backends()¶
Probe which acceleration backends can run the DCLS batch kernel.
Returns¶
dict
Mapping of backend name to availability, in fastest-first order. The
python floor is always True.
Function dcls_max_forward_batch(spikes, weights_q88, centres_q88, sigmas_q88, n_taps)¶
Run the batched DCLS-max tent kernel through the fastest available backend.
Parameters¶
spikes, weights_q88, centres_q88, sigmas_q88, n_taps
See :func:dcls_max_forward_batch_q88.
backend : str, optional
"auto" (default) picks the fastest available backend in
:data:FASTEST_FIRST_BACKENDS order. A specific name ("rust",
"mojo", "julia", "go", "python") forces that backend.
Returns¶
DclsBatchResult Identical to the pure-Python floor for every backend (bit-exact).
Raises¶
ValueError
If backend is not a known name.
ImportError
If an explicitly requested accelerator backend is unavailable.
Module scpn.layers.l10_boundary¶
Class L10_StochasticParameters¶
Stochastic configuration parameters for the L10 boundary firewall layer.
Class L10_BoundaryLayer¶
Topological firewall with dissonance rejection.
- init(params)
- step(dt, l9_input, external_noise)
- Advance the firewall one timestep and return its boundary state.
- get_global_metric()
- Return the scalar boundary-integrity metric for this layer.
Module scpn.layers.l11_morphic¶
Class L11_StochasticParameters¶
Stochastic configuration parameters for the SCPN morphic resonance / noospheric layer.
Class L11_MorphicLayer¶
Noospheric spin-glass with memetic spreading dynamics.
- init(params)
- step(dt, l10_input)
- Advance the morphic resonance / noospheric layer one timestep and return its output state.
- get_global_metric()
- Return the scalar global metric summarising this layer's state.
Module scpn.layers.l12_quantum_info¶
Class L12_StochasticParameters¶
Class L12_QuantumInfoLayer¶
ENAQT-inspired ecological coherence transport.
- init(params)
- step(dt, l11_input)
- get_global_metric()
Module scpn.layers.l13_temporal¶
Class L13_StochasticParameters¶
Stochastic configuration parameters for the SCPN source / temporal binding layer.
Class L13_TemporalLayer¶
Temporal binding via cross-correlation within a sliding window.
- init(params)
- step(dt, l12_input)
- Advance the source / temporal binding layer one timestep and return its output state.
- get_global_metric()
- Return the scalar global metric summarising this layer's state.
Module scpn.layers.l14_integration¶
Class L14_StochasticParameters¶
Stochastic configuration parameters for the SCPN transdimensional integration layer.
- post_init()
- Validate and finalise the layer parameters after construction.
Class L14_IntegrationLayer¶
Weighted integration across SCPN layer metrics.
- init(params)
- step(dt, layer_metrics, l13_input)
- Advance the transdimensional integration layer one timestep and return its output state.
- get_global_metric()
- Return the scalar global metric summarising this layer's state.
Module scpn.layers.l15_meta¶
Class L15_StochasticParameters¶
Class L15_MetaLayer¶
Self-monitoring meta-cognitive layer with GCI computation.
- init(params)
- step(dt, l14_input)
- get_global_metric()
Module scpn.layers.l16_director¶
Class L16_StochasticParameters¶
Class L16_DirectorLayer¶
Cybernetic closure with PI control and Lyapunov monitoring.
- init(params)
- step(dt, l15_input)
- get_global_metric()
Module scpn.layers.l1_quantum¶
Class L1_StochasticParameters¶
Parameters for the Stochastic L1 Layer.
Class L1_QuantumLayer¶
Stochastic implementation of the Quantum Cellular Field.
- init(params)
- step(dt, external_field)
- Advance the layer by one time step.
- get_global_metric()
- Return the global coherence metric (Phi-like).
Module scpn.layers.l2_neurochemical¶
Class L2_StochasticParameters¶
Parameters for the Stochastic L2 Neurochemical Layer.
Class L2_NeurochemicalLayer¶
Stochastic implementation of the Neurochemical Signaling Layer.
Models receptor-ligand binding, neurotransmitter dynamics, and second messenger cascades using bitstream representations.
- init(params)
- step(dt, nt_release, l1_input)
- Advance the layer by one time step.
- release_neurotransmitter(nt_type, amount)
- Trigger neurotransmitter release.
- get_global_metric()
- Return the global neurochemical activity metric.
- get_neuromodulation_state()
- Return named neurotransmitter levels for external use.
Module scpn.layers.l3_genomic¶
Class L3_StochasticParameters¶
Parameters for the Stochastic L3 Genomic Layer.
Class L3_GenomicLayer¶
Stochastic implementation of the Genomic-Epigenomic Layer.
Models gene expression, epigenetic modifications, and bioelectric pattern formation using bitstream representations.
- init(params)
- step(dt, l2_input, bioelectric_signal)
- Advance the layer by one time step.
- get_global_metric()
- Return the global genomic activity metric.
- get_ciss_coherence()
- Return CISS spin coherence metric.
Module scpn.layers.l4_cellular¶
Class L4_StochasticParameters¶
Parameters for the Stochastic L4 Cellular Layer.
Class L4_CellularLayer¶
Stochastic implementation of the Cellular-Tissue Synchronization Layer.
Models collective cellular behavior, gap junction coupling, and tissue-level pattern formation using bitstream representations.
- init(params)
- step(dt, l3_input, external_stimulus)
- Advance the layer by one time step.
- get_global_metric()
- Return the global synchronization metric (Kuramoto order parameter).
- get_tissue_pattern()
- Return 2D tissue activity pattern.
Module scpn.layers.l5_organismal¶
Class L5_StochasticParameters¶
Parameters for the Stochastic L5 Organismal Layer.
Class L5_OrganismalLayer¶
Stochastic implementation of the Organismal-Psychoemotional Layer.
Models whole-organism integration, autonomic regulation, and emotional dynamics using bitstream representations.
- init(params)
- step(dt, l4_input, external_event)
- Advance the layer by one time step.
- get_global_metric()
- Return the global organismal coherence metric.
- get_emotional_valence()
- Return current emotional valence.
Module scpn.layers.l6_ecological¶
Class L6_StochasticParameters¶
Parameters for the Stochastic L6 Ecological Layer.
Class L6_EcologicalLayer¶
Stochastic implementation of the Ecological-Planetary Layer.
Models planetary-scale electromagnetic fields, Schumann resonances, and biospheric network dynamics using bitstream representations.
- init(params)
- step(dt, l5_input, solar_activity, lunar_phase)
- Advance the layer by one time step.
- get_global_metric()
- Return the global planetary coherence metric.
- get_schumann_spectrum()
- Return current Schumann resonance spectrum.
- get_circadian_time()
- Return current circadian time (0-24 hours).
Module scpn.layers.l7_symbolic¶
Class L7_StochasticParameters¶
Parameters for the Stochastic L7 Symbolic Layer.
Class L7_SymbolicLayer¶
Stochastic implementation of the Geometric-Symbolic Layer.
Models sacred geometry patterns, symbolic resonances, and acupuncture point dynamics using bitstream representations.
- init(params)
- step(dt, l6_input, symbol_input, acupoint_stimulus)
- Advance the layer by one time step.
- get_global_metric()
- Return the global symbolic coherence metric.
- get_glyph_vector_normalized()
- Return normalized glyph vector for external use.
- stimulate_meridian(meridian_id, intensity)
- Stimulate a specific meridian.
- get_acupoint_map()
- Return clinically common named acupoint activations.
Module scpn.layers.l8_phase_field¶
Class L8_StochasticParameters¶
Stochastic configuration parameters for the SCPN cosmic phase-locking layer.
- post_init()
- Validate and finalise the layer parameters after construction.
Class L8_PhaseFieldLayer¶
Stochastic cosmic phase-locking via Kuramoto-coupled PTA oscillators.
- init(params)
- step(dt, l7_input)
- Advance the cosmic phase-locking layer one timestep and return its output state.
- get_global_metric()
- Return the scalar global metric summarising this layer's state.
Module scpn.layers.l9_memory¶
Class L9_StochasticParameters¶
Stochastic configuration parameters for the SCPN holographic memory layer.
Class L9_MemoryLayer¶
Hopfield associative memory with stochastic bitstream encoding.
- init(params)
- store(pattern)
- Hebbian imprint: W += pattern ⊗ pattern.
- step(dt, l8_input, boundary_cue, ebs_context)
- Advance the holographic memory layer one timestep and return its output state.
- get_global_metric()
- Return the scalar global metric summarising this layer's state.
Module scpn.params¶
Function build_knm_matrix(n_layers)¶
Build the Knm inter-layer coupling matrix.
Construction: exponential decay baseline, calibration anchor overrides, cross-hierarchy boosts, symmetrisation, zero diagonal.
Module security.checkpoint_loading¶
Class CheckpointTrustError¶
Raised when a checkpoint is not present in the trusted digest set.
Function safe_load_checkpoint(path)¶
Load a tensor/state-dict checkpoint only after SHA-256 verification.
The trust map accepts either the file name or the resolved full path as key.
PyTorch is always invoked with weights_only=True after digest validation.
Function safe_load_legacy_checkpoint(path)¶
Load a metadata checkpoint through pickle only after SHA-256 verification.
Use this only for legacy internal checkpoints whose dictionaries contain
non-state-dict metadata and cannot yet be represented by weights_only.
Module security.ethics¶
Class ActionRequest¶
Class AsimovGovernor¶
Implements the Three Laws of Robotics. Vetoes actions that violate ethical constraints.
- check_laws(action)
- Returns True if action is allowed, False if vetoed.
Module security.immune¶
Class DigitalImmuneSystem¶
Artificial Immune System (AIS) for Agent Security. Detects anomalies (Non-Self) and neutralizes threats.
- train_self(normal_state)
- Learn a 'Self' pattern (Normal behavior).
- scan(current_state)
- Check if current state matches 'Self'.
Module security.side_channel_benchmark¶
Class SideChannelBenchmarkError¶
Raised when side-channel benchmark inputs or outputs are invalid.
Class SideChannelBenchmarkArm¶
One benchmark arm with class-activity leakage proxy evidence.
- post_init()
Class SideChannelBenchmarkRecord¶
Per-sample benchmark record with realised protected probability.
- post_init()
Class SideChannelDeployManifest¶
Deploy/evidence manifest for an analytic side-channel benchmark.
- post_init()
Class SideChannelBenchmarkReport¶
Analytic baseline-versus-protected side-channel benchmark report.
- post_init()
Function run_side_channel_leakage_benchmark()¶
Compare correlated baseline streams against activity-balanced streams.
Function write_side_channel_benchmark_report(output_path)¶
Run the analytic benchmark and write a canonical JSON artifact.
Module security.side_channel_metrics¶
Class SideChannelMetricError¶
Raised when side-channel metric inputs are malformed or unsupported.
Class SwitchingActivitySummary¶
Transition-count summary for a rectangular binary bitstream matrix.
Class ClassActivityProxy¶
Class-conditioned analytic proxy for activity-dependent leakage.
label_activity_correlation is Pearson correlation between numeric labels
and per-sample mean switching rate. It is None when either side has zero
variance, avoiding fabricated correlation claims.
Function compute_switching_activity(bitstreams)¶
Compute per-stream switching activity for rows of binary bitstreams.
Function compute_class_activity_proxy(bitstreams_by_sample, labels)¶
Summarise class-conditioned switching activity for simulated samples.
Module security.thermal_sc_encoding¶
Class ThermalSCEncodingError¶
Raised when thermal side-channel encoder inputs violate the contract.
Class ThermalSCEncodingConfig¶
Configuration for deterministic activity-balanced SC encoding.
Class ActivityBalancedEncoding¶
A single activity-shaped stochastic-computing bitstream.
Class ActivityBalancedEncodingSummary¶
Batch-level analytic evidence for activity-shaped encodings.
Class ActivityBalancedEncodingBatch¶
Batch result for activity-shaped stochastic encodings.
Function encode_activity_balanced_probability(probability, config)¶
Encode one probability with distributed ones and deterministic rotation.
Function encode_activity_balanced_probabilities(probabilities, config)¶
Encode a probability batch and attach analytic class-activity evidence.
Module security.watermark¶
Class WatermarkInjector¶
Injects a backdoor watermark into an SC layer.
- inject_backdoor(layer, trigger_pattern, target_neuron_idx)
- Modifies weights of 'target_neuron_idx' so it fires maximally
- verify_watermark(layer, trigger_pattern, target_neuron_idx)
- Returns the activation of the target neuron for the trigger.
Module security.zkp¶
Class ZKPVerifier¶
Zero-Knowledge Proof for Neuromorphic Spike Validity. Proves that a spike sequence matches a committed input without revealing input.
- commit(bitstream)
- Creates a cryptographic commitment (hash) of the bitstream.
- generate_challenge(commitment)
- Simulates a random index challenge.
- verify(commitment, challenge_idx, revealed_bit, bitstream_slice)
- Verifies that the revealed bit and slice match the original commitment.
Module sensors.adc_to_spike_kernel¶
Class ADCSpikeWindowConfig¶
Fixed-point and decimation contract for the ADC-to-spike encoder.
Attributes¶
adc_width : int
Raw ADC sample width in bits (must exceed one).
q_int : int
Q-format integer bits (must be positive).
q_frac : int
Q-format fractional bits (must be non-negative).
decimation : int
Number of ADC samples averaged into one spike window (must be positive).
signed_input : bool
True if the ADC delivers two's-complement samples, False for
offset-binary samples centred at mid-scale.
threshold_q : int
Q-format magnitude that emits one spike (must be positive).
- q_total()
- Total Q-format bit width.
- q_min()
- Most negative representable Q-format code.
- q_max()
- Most positive representable Q-format code.
- validate()
- Raise :class:
ValueErrorif any field is out of contract.
Class ADCSpikeWindowResult¶
Per-window outputs of the ADC-to-spike encoder.
Each array is indexed by completed decimation window.
Attributes¶
window_values_q : numpy.ndarray
Sign-aware averaged Q-format window codes, int32.
spike_counts : numpy.ndarray
Deterministic per-window spike counts (|window| // threshold),
int32.
polarities : numpy.ndarray
True where the window code is negative, bool_.
Function quantise_adc(sample, config)¶
Centre and quantise one raw ADC sample to a Q-format code.
Mirrors ADCToSpikeReference.quantise_adc: two's-complement or offset-binary
centring, Q-format up-shift or sign-aware round-down, then saturation.
Parameters¶
sample : int Raw ADC sample. config : ADCSpikeWindowConfig Fixed-point contract.
Returns¶
int Saturated Q-format code.
Function adc_to_spike_windows_q(samples, config)¶
Pure-Python ADC-to-spike window encoder — the bit-true floor reference.
Parameters¶
samples : array_like
Raw ADC samples; the first n_windows * decimation are consumed.
config : ADCSpikeWindowConfig, optional
Fixed-point/decimation contract (defaults to Q8.8, decimation 8).
Returns¶
ADCSpikeWindowResult Per-window averaged codes, spike counts and polarities.
Raises¶
ValueError
If the config is invalid or fewer than decimation samples are given.
Function available_backends()¶
Probe which acceleration backends can run the ADC-to-spike kernel.
Returns¶
dict
Mapping of backend name to availability, in fastest-first order. The
python floor is always True.
Function adc_to_spike_windows(samples, config)¶
Encode ADC samples into spike windows through the fastest available backend.
Parameters¶
samples : array_like
Raw ADC samples.
config : ADCSpikeWindowConfig, optional
Fixed-point/decimation contract.
backend : str, optional
"auto" (default) selects the fastest available backend in
:data:FASTEST_FIRST_BACKENDS order; a specific name forces that backend.
Returns¶
ADCSpikeWindowResult Bit-identical to the Python floor for every backend.
Raises¶
ValueError
If backend is not a known name.
ImportError
If an explicitly requested accelerator backend is unavailable.
Module sensors.dvs¶
Class DVSLoader¶
Load and preprocess DVS event camera data.
Parameters¶
width : int Sensor width in pixels. height : int Sensor height in pixels.
- n_pixels()
- Return the total number of pixels in the DVS frame.
- from_numpy(events)
- Load events from structured numpy array.
- from_tonic(dataset_name, index)
- Load events from a Tonic dataset (requires tonic package).
Function events_to_spike_trains(events, width, height, dt_us, duration_us)¶
Convert DVS events to binary spike train matrix.
Parameters¶
events : structured ndarray with x, y, t, p fields width, height : int Sensor dimensions. dt_us : float Time bin width in microseconds (default 1000 = 1ms). duration_us : float, optional Total duration. If None, inferred from event timestamps.
Returns¶
ndarray of shape (n_bins, width * height * 2) Binary spike trains. Channels: [ON pixels, OFF pixels].
Function events_to_frames(events, width, height, dt_us, duration_us)¶
Convert DVS events to event count frames.
Parameters¶
events : structured ndarray width, height : int dt_us : float Frame duration in microseconds (default 10000 = 10ms). duration_us : float, optional
Returns¶
ndarray of shape (n_frames, 2, height, width) Event count frames with ON and OFF channels.
Module serve.server¶
Class SpikeServer¶
Streaming SNN inference server.
Parameters¶
network : SCNetwork or Network The SNN to run. host : str Bind address (default '0.0.0.0'). port : int Listen port (default 8001).
- init(network, host, port)
- step(inputs)
- Run one network timestep and return output spikes.
- start(blocking)
- Start the HTTP server.
- stop()
- Shut down the server.
Module sleep.circadian_optimizer¶
Class Chronotype¶
Sleep chronotype labels (after Michael Breus' model).
Class CircadianProfile¶
A chronotype's circadian parameters.
Attributes¶
chronotype : Chronotype The chronotype label. bedtime_hour : float Ideal bedtime in decimal hours (0-24, can exceed 24 for next-day). wake_hour : float Ideal wake time in decimal hours. default_protocol : str Name of the recommended sleep audio protocol. melatonin_peak_hour : float Hour at which endogenous melatonin peaks (typically ~2 h after bedtime onset for most chronotypes). core_body_temp_nadir_hour : float Hour of the core body temperature nadir (~2 h after melatonin peak).
Class CircadianOptimizer¶
Chronotype-aware circadian rhythm optimizer.
Parameters¶
chronotype : Chronotype The user's chronotype.
Example::
opt = CircadianOptimizer(Chronotype.BEAR)
profile = opt.get_profile()
print(opt.melatonin_level(23.0)) # near-peak for a Bear
- init(chronotype)
- get_profile()
- Return the full circadian profile for the configured chronotype.
- get_sleep_window()
- Return
(bedtime_hour, wake_hour). - get_recommended_protocol()
- Return the default protocol name for this chronotype.
- is_in_sleep_window(hour)
- Check whether hour (0-24) falls inside the sleep window.
- melatonin_level(hour)
- Estimate melatonin level at hour using a sinusoidal model.
- to_dict()
- Serialise the optimizer state to a plain dict.
Module sleep.protocol_library¶
Class StageAudioParams¶
Audio-entrainment parameters for a single sleep stage.
Attributes¶
binaural_hz : float
Binaural beat frequency (Hz).
noise_color : str
Background noise colour ("pink", "brown", "white", etc.).
base_freq_hz : float
Carrier / base tone frequency (Hz).
volume : float
Relative volume in [0, 1].
isochronic_hz : float
Isochronic pulse frequency (Hz); 0 disables.
spatial_rotation : float
Spatial audio rotation speed in degrees per second.
Class SleepProtocol¶
A named sleep-entrainment protocol.
Attributes¶
name : str Human-readable identifier (must match the registry key). description : str Short description of the protocol's therapeutic goal. stage_audio : Dict[SleepStage, StageAudioParams] Audio parameters keyed by target stage. stage_targets : Dict[SleepStage, float] Target fraction of total sleep time per stage (must sum to 1.0). total_duration_min : float Recommended session length in minutes.
- get_audio_for_stage(stage)
- Return audio parameters for stage, falling back to WAKE params.
- get_target_stage(progress)
- Return the ideal stage for a given session progress in [0, 1].
- to_dict()
- Serialise the protocol to a plain dict.
Function get_protocol(name)¶
Look up a protocol by name. Raises KeyError if not found.
Function list_protocols()¶
Return a sorted list of all available protocol names.
Module sleep.report_generator¶
Class SleepReport¶
Aggregate report for a completed sleep session.
Attributes¶
total_duration_min : float
Total session length in minutes.
sleep_onset_latency_min : float
Minutes from session start until the first non-WAKE epoch.
sleep_efficiency_pct : float
Percentage of total time spent asleep (non-WAKE).
quality_score : float
Composite quality score in [0, 100].
stage_durations_min : Dict[str, float]
Time (minutes) per stage.
stage_percentages : Dict[str, float]
Percentage of total time per stage.
stage_targets : Dict[str, float]
Protocol target percentages for comparison.
hypnogram : List[int]
Stage codes per epoch.
wakeups : int
Number of WAKE epochs that occurred after initial sleep onset.
reinductions : int
Number of re-induction sequences triggered.
recommendations : List[str]
Plain-language suggestions.
grade : str
Letter grade (A-F).
Class SleepReportGenerator¶
Generates a :class:SleepReport from a completed optimiser session.
- generate(optimizer)
- Analyse optimizer's tick history and return a report.
Module sleep.sleep_optimizer¶
Class SleepOptimizerConfig¶
Tuneable knobs for the optimiser loop.
Class SleepTick¶
Snapshot produced every stage_check_interval samples.
Attributes¶
tick : int Monotonic tick counter. elapsed_min : float Wall-clock minutes since session start. current_stage : SleepStage Detected stage at this tick. target_stage : SleepStage Protocol's ideal stage at this progress point. stage_match : bool Whether current == target. audio_params : StageAudioParams Audio parameters being delivered. band_powers : Dict[str, float] Most recent EEG band-power decomposition. reinduction_active : bool Whether a re-induction sequence is currently running.
Class SleepOptimizer¶
Closed-loop sleep optimiser.
Parameters¶
protocol : SleepProtocol or str The protocol instance (or its registry name) to follow. config : SleepOptimizerConfig, optional Operational parameters.
Example::
opt = SleepOptimizer("insomnia_relief")
opt.start_session()
for sample in eeg_stream:
opt.add_sample(sample)
tick = opt.check_and_adapt()
if tick is not None:
apply_audio(tick.audio_params)
report = opt.stop_session()
- init(protocol, config)
- start_session()
- Begin a new optimisation session, resetting all state.
- stop_session()
- End the current session and return the full tick history.
- add_sample(sample)
- Feed a single EEG voltage sample.
- add_samples(samples)
- Feed an array of EEG voltage samples.
- check_and_adapt()
- Run stage detection and protocol adaptation.
- get_history()
- Return a copy of all recorded ticks.
- get_stage_durations()
- Compute time (minutes) spent in each detected stage.
- get_hypnogram()
- Return the detected-stage sequence as a list of integer codes.
- get_state()
- Return a summary dict of the optimiser's current state.
Module sleep.sleep_stage_detector¶
Class SleepStage¶
AASM sleep-stage labels.
Class DetectorConfig¶
Parameters for the sleep-stage detector.
Class SleepStageDetector¶
Real-time sleep-stage detector from single-channel EEG.
Usage::
det = SleepStageDetector()
for sample in eeg_stream:
det.add_sample(sample)
stage = det.detect()
if stage is not None:
print(stage.name)
- init(config)
- add_sample(sample)
- Append a single EEG voltage sample to the internal buffer.
- add_samples(samples)
- Append an array of EEG voltage samples.
- detect()
- Return the smoothed sleep-stage classification, or
Noneif - get_band_powers()
- Return the most recently computed band-power dict, or
None. - reset()
- Clear all internal state.
Module snn_optimizer.passes¶
Class LayerNode¶
One layer in the SNN computation graph.
- n_params()
Class SNNGraph¶
SNN computation graph: sequence of layers.
- total_params()
- total_neurons()
- copy()
Class PassResult¶
Result of one optimization pass.
Class OptimizationReport¶
Report from running all optimization passes.
- compression_ratio()
- summary()
Function dead_neuron_elimination(graph, threshold)¶
Remove neurons that never fire (firing rate below threshold).
Requires firing_rates to be set on each layer (from profiling). Removes rows from weight matrices and corresponding columns from the next layer's weight matrix.
Function layer_fusion(graph)¶
Fuse adjacent linear layers with compatible dimensions.
If two consecutive layers have no nonlinearity between them (both LIF with same type), fuse W2 @ W1 into a single layer. Caveat: this is valid only when the intermediate layer has effectively linear behavior (high threshold, no spikes).
Function redundancy_elimination(graph, correlation_threshold)¶
Merge neurons with near-identical weight vectors.
If two neurons in the same layer have weight correlation > threshold, merge them: keep one, remove the other, scale outgoing weights by 2.
Function optimize(graph, passes)¶
Run optimization passes on an SNN graph.
Parameters¶
graph : SNNGraph passes : list of str, optional Pass names to run. Default: all passes. Options: 'dead_neuron_elimination', 'layer_fusion', 'redundancy_elimination'
Returns¶
(optimized_graph, OptimizationReport)
Module solvers.exact_lif¶
Class ExactLIFSolver¶
Event-driven exact integration for LIF neurons.
Reference: Rotter, S. & Diesmann, M. (1999). Biol. Cybern. 81:381–402.
- post_init()
- Validate and normalise the membrane parameters.
- evolve_to_time(v0, t, current)
- Compute V(t) given initial voltage v0 and constant current.
- next_spike_time(v0, current)
- Compute time until next spike under constant current.
- isi(current)
- Compute the inter-spike interval for constant current.
- firing_rate(current)
- Compute steady-state firing rate (Hz) for constant current.
- simulate(current, t_end, v0)
- Simulate LIF with constant current from t=0 to t=t_end.
Module solvers.exact_lif_profile¶
Class ExactCurrentLIFProfile¶
Immutable parameters and semantics for one exact-current LIF instance.
- post_init()
- to_payload()
- Return the complete canonical profile payload.
- digest()
- Return the SHA-256 of canonical profile JSON.
- to_json()
- Serialize the profile canonically.
- verify_source_binding()
- Fail closed if the shipped model source differs from this profile.
- from_json(cls, serialized)
- Parse strict canonical semantics; reject versions, fields and units.
Class CurrentDriveTick¶
One duration with simultaneous piecewise-constant current inputs.
- post_init()
- total_current()
- Return the order-independent sum delivered at tick start.
- to_payload()
Class ExactLIFState¶
Complete persistent runtime state at a shot-relative instant.
- post_init()
- to_payload()
Class ExactLIFStateSample¶
One ordered point in the complete execution state trace.
- to_payload()
Class ExactLIFEvent¶
One exact threshold-crossing event.
- to_payload()
Class ExactLIFExecutionPacket¶
Immutable complete trace and provenance packet for one execute call.
- to_payload()
- to_json()
- Serialize the packet canonically for deterministic evidence.
- from_json(cls, serialized)
- Validate a packet by strict parsing and deterministic replay.
Class ExactCurrentLIFSession¶
Stateful, failure-atomic executor for :class:ExactCurrentLIFProfile.
- init(profile)
- state()
- Return the current immutable persistent state.
- reset_shot(shot_id)
- Reset voltage and time explicitly at a new shot boundary.
- serialize_state()
- Serialize state with the exact profile digest.
- restore_state(serialized)
- Restore compatible state atomically; reject drift and unknown fields.
- execute(ticks)
- Execute a complete current sequence and commit state only on success.
Module solvers.ising¶
Class StochasticIsingGraph¶
Quantum-Inspired Ising Machine Solver.
Spins S_i in {-1, 1} (mapped to 0, 1 for SC). Energy E = -Sum(J_ij * S_i * S_j) - Sum(h_i * S_i). Goal: Find configuration that minimizes E.
- post_init()
- Initialise random spins and their bipolar
{-1, 1}representation. - step()
- Perform one parallel Metropolis-Hastings update and return the energy.
- get_energy()
- Calculate global energy.
- get_config()
- Return the current spin configuration as a
0/1int8 array.
Module solvers.ode¶
Class ODESolver¶
Base class for ODE solvers: dy/dt = f(t, y).
- step(f, y, t, dt)
- Advance one step. Returns (y_new, dt_used).
Class EulerSolver¶
Forward Euler — O(h).
y_{n+1} = y_n + h * f(t_n, y_n)
- step(f, y, t, dt)
- Advance one forward-Euler step; return
(y_new, dt_used).
Class HeunSolver¶
Heun's method (improved Euler / explicit trapezoidal) — O(h²).
k1 = f(t_n, y_n) k2 = f(t_n + h, y_n + h*k1) y_{n+1} = y_n + h/2 * (k1 + k2)
- step(f, y, t, dt)
- Advance one Heun (improved-Euler) step; return
(y_new, dt_used).
Class RK4Solver¶
Classical Runge-Kutta — O(h⁴).
k1 = f(t, y) k2 = f(t + h/2, y + h/2 * k1) k3 = f(t + h/2, y + h/2 * k2) k4 = f(t + h, y + h * k3) y_{n+1} = y_n + h/6 * (k1 + 2k2 + 2k3 + k4)
Reference: Kutta, W. (1901). Z. Math. Phys. 46:435–453.
- step(f, y, t, dt)
- Advance one classical RK4 step; return
(y_new, dt_used).
Class DormandPrinceSolver¶
Dormand-Prince adaptive RK45 — embedded pair for step-size control.
Uses the 7-stage, 5th-order solution with a 4th-order embedded error estimate. Step size is adapted to maintain local truncation error below the specified tolerance.
Reference: Dormand, J.R. & Prince, P.J. (1980). J. Comput. Appl. Math. 6:19–26.
- init(atol, rtol, max_factor, min_factor, safety)
- step(f, y, t, dt)
- Advance one adaptive RK45 step; return
(y_new, dt_used, dt_next). - integrate(f, y0, t_span, dt0)
- Integrate over [t0, tf]. Returns (t_array, y_array).
Class ExponentialEuler¶
Exponential Euler for linear ODEs: dy/dt = A*y + b.
Exact solution: y(t+dt) = exp(Adt) * y(t) + (exp(Adt) - I) * A^{-1} * b
For scalar diagonal systems (like LIF): y(t+dt) = y_rest + (y(t) - y_rest) * exp(-dt/tau) + R*I * (1 - exp(-dt/tau))
The callable f must return A*y + b; the solver extracts the decay constant.
- init(tau, y_rest, r_m)
- step(f, y, t, dt)
- Advance one exponential-Euler step; return
(y_new, dt_used).
Function get_solver(name)¶
Return an ODE solver instance selected by name.
Supported names: 'euler', 'heun', 'rk4', 'dp45', 'exponential_euler', 'rosenbrock', and 'rosenbrock_euler'.
Module solvers.stiff¶
Class RosenbrockEuler¶
Linearly implicit one-stage Rosenbrock solver.
The step solves (I - gamma*h*J) k = h*f(t, y) and returns
y + k. With gamma=1 this is the Rosenbrock-Euler method:
first-order, L-stable for linear stiff decay, and suitable as a
stiffness-specific alternative path for small neuron state vectors.
Reference: Hairer, E. & Wanner, G. (1996). Solving ODEs II. Springer.
- init(gamma, jacobian_epsilon)
- step(f, y, t, dt)
- Advance one Rosenbrock-Euler step; return
(y_new, dt_used).
Class ImplicitEuler¶
Backward (implicit) Euler — L-stable, 1st order.
y_{n+1} = y_n + h * f(t_{n+1}, y_{n+1})
Solved via fixed-point iteration: for stiff neuron ODEs, 3–5 iterations typically suffice.
Reference: Hairer, E. & Wanner, G. (1996). Solving ODEs II. Springer.
- init(max_iterations, tol)
- step(f, y, t, dt)
- Advance one backward-Euler step; return
(y_new, dt_used).
Class TrapezoidalRule¶
Trapezoidal rule (Crank-Nicolson) — A-stable, 2nd order.
y_{n+1} = y_n + h/2 * (f(t_n, y_n) + f(t_{n+1}, y_{n+1}))
Higher-order than implicit Euler while retaining A-stability. Solved via fixed-point iteration.
Reference: Crank, J. & Nicolson, P. (1947). Proc. Camb. Phil. Soc. 43:50–67.
- init(max_iterations, tol)
- step(f, y, t, dt)
- Advance one trapezoidal-rule step; return
(y_new, dt_used).
Module solvers.symplectic¶
Class StormerVerlet¶
Störmer-Verlet (velocity Verlet) — symplectic 2nd order.
For separable Hamiltonians H = T(p) + V(q): p_{1/2} = p_n - (h/2) * ∇V(q_n) q_{n+1} = q_n + h * ∇T(p_{1/2}) p_{n+1} = p_{1/2} - (h/2) * ∇V(q_{n+1})
Here we split the state y = [q, p] where q are position-like (voltage) and p are momentum-like (recovery/gating) variables.
Reference: Hairer, E. et al. (2006). Geometric Numerical Integration. Springer.
- step(f, y, t, dt)
- Advance one Störmer-Verlet step; return
(y_new, dt_used).
Class LeapfrogSolver¶
Leapfrog (kick-drift-kick) — symplectic 2nd order.
Equivalent to Störmer-Verlet but staggered: p_{n+1/2} = p_n + (h/2) * f_p(q_n) q_{n+1} = q_n + h * f_q(p_{n+1/2}) p_{n+1} = p_{n+1/2} + (h/2) * f_p(q_{n+1})
State vector: y = [q₀..q_{n-1}, p₀..p_{n-1}]
Reference: Yoshida, H. (1990). Phys. Lett. A 150:262–268.
- step(f, y, t, dt)
- Advance one leapfrog (kick-drift-kick) step; return
(y_new, dt_used).
Module sources.bitstream_current_source¶
Class BitstreamCurrentSource¶
Multi-channel bitstream current source.
- Takes scalar inputs x_i in [x_min, x_max]
- Encodes each into a bitstream via BitstreamEncoder
- Passes them through BitstreamSynapses
- Decodes the realised post-synaptic bitstreams into a per-cycle current trace for neuron simulation.
Static inputs and weights are encoded once at construction time. The stochastic realisation is then fixed until a new source is constructed with different parameters or seeds.
- post_init()
- Validate input/weight lengths and derive the input count.
- reset()
- Reset the realised current trace cursor to its first timestep.
- current_trace()
- Return the realised per-cycle decoded current trace.
- step()
- Return the current I_t at the current time index and advance.
- full_current_estimate()
- Return the mean current over the realised bitstream duration.
Module sources.quantum_entropy¶
Class QuantumEntropySource¶
Simulated quantum-measurement entropy source.
Injects simulated quantum indeterminacy into neural models by maintaining
a qubit state |psi>, applying Hadamard superposition and phase
rotations, and measuring (collapsing) the state to generate noise.
- post_init()
- Initialise the RNG and reset the qubit register to
|0>. - sample_normal(mean, std)
- Two independent measurements → Box-Muller → Gaussian sample.
- sample()
- Return one default normal sample from the simulated measurement source.
Module spatial.representations¶
Class VoxelGrid¶
A 3D Voxel Grid representation for SC. Each voxel stores a probability of being 'occupied'.
- post_init()
- set_voxel(x, y, z, prob)
- get_as_bitstream(length)
- Converts the voxel grid to a 4D bitstream (X, Y, Z, Length).
Class PointCloud¶
A Point Cloud representation. Each point has (x, y, z) coordinates and an associated probability/intensity.
- normalize()
Module spatial.transformer_3d¶
Class SpatialTransformer3D¶
A transformer block specialized for 3D spatial data. Processes voxel grids using SC attention.
- post_init()
- forward(voxel_grid)
- Input: voxel_grid (res, res, res)
Module spike_codec.aer_codec¶
Class AERCompressionResult¶
Compression result with AER codec metrics.
Class AERSpikeCodec¶
AER spike codec: event-list encoding for sparse spike data.
Converts spike raster (T, N) to a compact stream of (timestamp, neuron_id) events. Delta-encodes timestamps for further compression.
Parameters¶
timestamp_bits : int Bits for delta-coded timestamps. 16 = max gap of 65535 samples. Larger windows between spikes use escape codes. neuron_bits : int Bits for neuron ID. Auto-sized from N if 0.
- init(timestamp_bits, neuron_bits)
- compress(spikes)
- Compress spike raster to AER event stream.
- decompress(data, T, N)
- Decompress AER event stream to spike raster.
Module spike_codec.codec¶
Class CompressionResult¶
Result of spike train compression.
- summary()
- Return a human-readable one-line summary of the codec statistics.
Class SpikeCodec¶
ISI spike train codec with configurable entropy backend.
Compression strategy: 1. Extract per-neuron spike times from binary raster 2. Compute inter-spike intervals (ISIs) per neuron 3. Encode ISIs with chosen backend: 'varint': LEB128 variable-length integers (fast, simple) 'huffman': Adaptive Huffman (30-60% smaller on dense data)
Each neuron is encoded independently. No inter-channel modeling. For inter-channel compression, use DeltaSpikeCodec.
Parameters¶
mode : str 'lossless' (exact reconstruction) or 'lossy' (preserve rates only). timing_precision : int For lossy mode: quantize spike times to this resolution. entropy : str 'varint' (default) or 'huffman'.
- init(mode, timing_precision, entropy)
- compress(spikes)
- Compress a spike raster.
- decompress(data, T, N)
- Decompress to spike raster.
Module spike_codec.delta_codec¶
Class DeltaCompressionResult¶
Compression result with delta coding metrics.
Class DeltaSpikeCodec¶
Delta spike codec: compress inter-channel XOR residuals.
Channels are grouped spatially. Within each group, one reference channel is transmitted raw; others are XOR'd against the reference and ISI-compressed. When channels are correlated, the XOR residuals are much sparser than the raw data.
Parameters¶
group_size : int Channels per group. Larger groups = more sharing but weaker correlation with distant channels. 4-16 typical for probes. mode : str 'lossless' or 'lossy' for the underlying ISI codec. timing_precision : int For lossy mode: quantize timing resolution.
- init(group_size, mode, timing_precision)
- compress(spikes)
- Compress spike raster using inter-channel delta coding.
- decompress(data, T, N)
- Decompress delta-coded spike raster.
Module spike_codec.entropy¶
Class HuffmanEncoder¶
Encode integer streams using adaptive Huffman coding.
Builds code table from the input data, stores table in header, then encodes symbols as variable-length bit sequences.
- encode(values)
- Encode integer list to compressed bytes.
- decode(data, n_symbols)
- Decode compressed bytes to integer list.
Module spike_codec.predictive_codec¶
Class PredictiveCompressionResult¶
Compression result with predictive coding metrics.
Class PredictiveSpikeCodec¶
Predictive spike codec: compress prediction errors, not raw spikes.
Four predictor modes: 'ema' (default): float EMA rate tracking + threshold comparison. 'lfsr': Q8.8 fixed-point rate + LFSR comparator. Bit-true with sc_bitstream_encoder.v — maps directly to Verilog RTL. 'context': Markov context predictor. Hashes last K spike states per channel, predicts from accumulated statistics. 'world_model': Learnable autoregressive predictor (LMS-trained). Predicts spike[t] from spike[t-K:t] via linear model with sigmoid activation. Learns cross-channel correlations.
Compression pipeline: 1. For each timestep t: a. predicted[t] = predictor.predict() b. error[t] = actual[t] XOR predicted[t] c. predictor.update(actual[t]) 2. ISI-compress the error matrix (sparser than raw spikes) 3. Pack with header (predictor params for decoder sync)
Parameters¶
alpha : float EMA smoothing factor (ema mode). Ignored in lfsr/context mode. threshold : float Spike prediction threshold (ema mode). Ignored in lfsr/context mode. predictor : str 'ema', 'lfsr', or 'context'. alpha_q8 : int Q8.8 smoothing factor for lfsr mode. 1 = 1/256 ≈ 0.004. seed : int LFSR seed for lfsr mode (non-zero, 16-bit). context_bits : int Context history length for context mode (default 8 = last 8 spikes). base_mode : str 'lossless' or 'lossy' for the underlying ISI codec. timing_precision : int For lossy mode: quantize timing resolution.
- init(alpha, threshold, predictor, alpha_q8, seed, context_bits, base_mode, timing_precision)
- compress(spikes)
- Compress spike raster using predictive error coding.
- decompress(data, T, N)
- Decompress to spike raster.
Module spike_codec.registry¶
Function get_codec(name)¶
Get a codec by name.
Parameters¶
name : str One of: 'isi', 'predictive', 'delta', 'streaming', 'aer'. **kwargs Passed to the codec constructor.
Returns¶
Codec instance with compress/decompress methods.
Function list_codecs()¶
List available codec names.
Function recommend_codec(n_channels, firing_rate, latency_ms, correlated, neuromorphic)¶
Recommend a codec based on data characteristics.
Parameters¶
n_channels : int Number of recording channels. firing_rate : float Mean firing rate in Hz (per neuron). latency_ms : float Maximum acceptable latency in milliseconds. correlated : bool True if nearby channels are spatially correlated. neuromorphic : bool True if target is neuromorphic hardware (Loihi, SpiNNaker).
Returns¶
str — codec name
Module spike_codec.streaming_codec¶
Class StreamingCompressionResult¶
Compression result with streaming codec metrics.
Class StreamingSpikeCodec¶
Streaming spike codec: fixed-latency, independently decodable frames.
Each time window is compressed as a self-contained frame. No inter-frame dependencies. Worst-case latency = window_size samples.
Parameters¶
window_size : int Samples per frame. 20 = 1ms at 20kHz (typical BCI). Smaller = lower latency but less compression.
- init(window_size)
- compress(spikes)
- Compress spike raster into independently decodable frames.
- decompress(data, T, N)
- Decompress streaming frames to spike raster.
- compress_frame(window)
- Compress a single time window (for real-time streaming).
- decompress_frame(frame)
- Decompress a single frame.
Module spike_codec.waveform_codec¶
Class WaveformCompressionResult¶
Result of waveform compression.
Class WaveformCodec¶
End-to-end neural waveform codec.
Pipeline: detect → separate → compress each component optimally.
Parameters¶
threshold_sigma : float
Spike detection threshold in units of per-channel noise sigma.
Must be finite and positive. Typical: 4.0-5.0 (4 sigma catches
~99.99% of noise).
snippet_samples : int
Waveform samples to extract around each spike (before + after peak).
Must fit the one-byte wire header: 1-255 samples.
max_templates : int
Maximum number of spike waveform templates to maintain.
Must fit the two-byte wire header: 1-65535 templates.
template_threshold : float
Correlation threshold for template matching, inclusive range 0-1.
quantize_bits : int
Background signal quantization, inclusive range 1-8. Fewer bits
increase compression.
mode : str
Compression mode controlling what is preserved:
- "full": spike timing + waveform templates + background LFP (~137x)
- "waveform": spike timing + waveform templates, no background (~1700x)
- "spike": spike timing only, Neuralink-equivalent (~4500x)
- init(threshold_sigma, snippet_samples, max_templates, template_threshold, quantize_bits, mode)
- compress(waveform)
- Compress raw electrode waveform.
Module spike_dsp.filters¶
Class SpikeFIR¶
Finite Impulse Response filter in spike domain.
Computes weighted sum of delayed input spike trains. Output at time t = sum(coefficients[k] * input[t-k]) > threshold.
Parameters¶
coefficients : ndarray FIR tap weights. threshold : float Output spike threshold (on weighted sum).
- filter(spikes)
- Apply FIR filter to spike train.
Class SpikeIIR¶
Infinite Impulse Response filter using leaky integration.
Membrane-like dynamics: state = decay * state + input_spike. Fires when state exceeds threshold. Natural IIR in spike domain.
Parameters¶
decay : float Decay factor per timestep (0-1). threshold : float gain : float Input spike gain.
- filter(spikes)
- Apply IIR filter to spike train.
Function spike_convolve(spikes, kernel, threshold)¶
Convolve a spike train with a kernel in spike domain.
Parameters¶
spikes : ndarray of shape (T,) kernel : ndarray of shape (K,) threshold : float
Returns¶
ndarray of shape (T,), binary
Module spike_dsp.spectral¶
Function spike_fft(spikes, dt, window_size)¶
Compute FFT of a spike train.
Parameters¶
spikes : ndarray of shape (T,) or (T, N) Binary spike train(s). dt : float Timestep in seconds. window_size : int Sliding window for instantaneous rate estimation.
Returns¶
(frequencies, magnitudes) tuple frequencies: ndarray of shape (F,) magnitudes: ndarray of shape (F,) or (F, N)
Function spike_power_spectrum(spikes, dt, window_size)¶
Compute power spectral density of a spike train.
Returns¶
(frequencies, psd) tuple
Module spike_dsp.wavelets¶
Function spike_wavelet_decompose(spikes, n_scales, base_window)¶
Decompose spike train into frequency bands via multi-scale filtering.
Uses cascaded moving-average filters at doubling window sizes: scale 0: window=base_window, scale 1: window=2*base_window, etc. Each scale captures a different frequency band.
Parameters¶
spikes : ndarray of shape (T,) or (T, N) n_scales : int Number of wavelet scales. base_window : int Window size for finest scale.
Returns¶
list of ndarray One array per scale, shape (T,) or (T, N). Binary spike representation of activity at each frequency band.
Module spike_gnn.spike_gnn¶
Class SpikeGraphConv¶
Spike-based graph convolution layer.
Message passing: each node aggregates spike trains from neighbors, applies a learned weight transform via LIF integration.
Parameters¶
in_features : int Input feature dimension per node. out_features : int Output feature dimension per node. threshold : float tau_mem : float
- init(in_features, out_features, threshold, tau_mem, seed)
- forward(node_features, adjacency, T)
- Spike-based graph convolution.
Class SpikeGNNLayer¶
Multi-layer spike GNN for graph classification/regression.
Parameters¶
layer_dims : list of int [in_features, hidden1, ..., out_features] threshold : float T : int Simulation timesteps per layer.
- post_init()
- Build the per-layer spiking graph-convolution stack.
- forward(node_features, adjacency)
- Forward pass through all layers.
- graph_classify(node_features, adjacency)
- Classify a graph by global readout (sum pooling + argmax).
- n_layers()
- Return the number of graph-convolution layers.
Module spike_norm.normalizers¶
Class ThresholdDependentBN¶
tdBN: incorporates firing threshold into normalization.
BN(x) = gamma * (x - mean) / sqrt(var + eps) + beta where mean/var are computed across batch, adjusted by V_threshold.
Parameters¶
n_features : int threshold : float momentum : float
- post_init()
- forward(x, training)
Class PerTimestepBN¶
BNTT: separate BN statistics per timestep.
Each timestep t has its own mean_t, var_t, gamma_t, beta_t.
Parameters¶
n_features : int T : int Number of timesteps.
- post_init()
- forward(x, t, training)
Class TemporalEffectiveBN¶
TEBN: rescales presynaptic inputs per timestep.
Applies BN then per-timestep scaling factor lambda_t.
Parameters¶
n_features : int T : int
- post_init()
- forward(x, t, training)
Class MembranePotentialBN¶
MPBN: BN on membrane potential before spike function.
At inference: fold BN into threshold (zero overhead). new_threshold = (V_th - beta) * sqrt(var + eps) / gamma + mean
Parameters¶
n_features : int threshold : float
- post_init()
- forward(membrane, training)
- fused_threshold()
- Compute per-neuron threshold that absorbs BN at inference.
Class TemporalAccumulatedBN¶
TAB: normalizes accumulated membrane potential.
Tracks running accumulated potential across timesteps. Addresses Temporal Covariate Shift directly.
Parameters¶
n_features : int
- post_init()
- forward(x, training)
- reset()
Module spike_ode.ode_layer¶
Class ODELIFDynamics¶
LIF membrane ODE dynamics.
dv/dt = -(v - v_rest) / tau_mem + I(t) / C_mem
Parameters¶
tau_mem : float Membrane time constant (ms). v_rest : float v_threshold : float v_reset : float C_mem : float Membrane capacitance (normalized).
- dvdt(v, I)
- Compute membrane voltage derivative.
Class SpikingODELayer¶
Spiking Neural ODE layer with event-driven integration.
Integrates the membrane ODE with adaptive Euler stepping. Detects threshold crossings via bisection, emits spikes, resets.
Parameters¶
n_inputs : int n_neurons : int dynamics : ODELIFDynamics dt_init : float Initial integration step size. dt_min : float Minimum step size. max_steps_per_interval : int Max ODE steps per simulation interval. seed : int
- init(n_inputs, n_neurons, dynamics, dt_init, dt_min, max_steps_per_interval, seed)
- step(x, interval)
- Integrate ODE over one interval, return spike counts.
- forward(inputs, interval)
- Process a sequence of inputs.
- reset()
- Reset membrane voltages to the configured resting potential.
- voltage()
- Return a defensive copy of the current membrane voltages.
Module spintronic.spintronic_mapper¶
Class SpintronicTech¶
Class MaterialParams¶
Micromagnetic material parameters.
- cofeb_mgo(cls)
- CoFeB/MgO — standard STT-MTJ / SOT-MRAM stack.
- pt_co_multilayer(cls)
- Pt/Co multilayer — skyrmion host.
- w_cofeb(cls)
- W/CoFeB — SOT switching with heavy-metal underlayer.
Class SpintronicDeviceConfig¶
Configuration for a single spintronic device.
- post_init()
- from_tech(cls, tech)
- area_nm2()
- switching_energy_fj()
- Write-path switching energy, E = I² × R_write × t.
- thermal_stability()
- Thermal stability factor Δ = Ku × V / (kB × T).
- read_disturb_probability()
- Probability of read disturb (accidental flip during read).
- endurance_cycles()
- Estimated write endurance cycles.
Class VariabilityModel¶
Process variability for spintronic devices.
Models dimension, anisotropy, and DMI variations from fab data.
- apply(device, rng)
- Return a variability-injected copy of the device.
Class SpintronicCell¶
One cell in a spintronic array.
- resistance_ohm()
Class SpintronicArray¶
Crossbar array of spintronic devices for SC computation.
- init(rows, cols, tech, variability, rng_seed)
- total_cells()
- total_area_um2()
- program_weights(weights_q88)
- Program Q8.8 weights into the array.
- read_weights()
- Read weights back from the array.
- power_breakdown(bitstream_length)
- Per-array power breakdown in femtojoules.
Class MappingResult¶
Result of mapping SC bitstreams to a spintronic array.
Class SpintronicMapper¶
Maps SC bitstreams + weights to a spintronic crossbar.
Performs: 1. Weight quantisation to device states (P/AP) 2. Array sizing from network dimensions 3. Energy/timing estimation 4. Monte-Carlo variability yield analysis
- init(tech, variability, rng_seed)
- map_network(weights_q88, bitstream_length)
- Map a weight matrix to a spintronic array.
- monte_carlo_yield(weights_q88, n_trials, tolerance_q88)
- Run Monte-Carlo yield analysis.
Class MuMax3ScriptGenerator¶
Generates MuMax3 (.mx3) scripts for micromagnetic co-simulation.
- generate_switching(device, current_density_a_m2, duration_ns)
- generate_skyrmion(device)
Class SpintronicVerilogGenerator¶
Generates Verilog wrappers for spintronic crossbar arrays.
- generate(array_name, rows, cols, tech)
Class RacetrackShiftRegister¶
Domain-wall racetrack memory with current-driven bit shifting.
Models a nanotrack with N bit positions; SOT current pulses shift all domain walls one position per clock edge.
- post_init()
- load(data)
- shift_right(n, rng)
- shift_left(n, rng)
- shift_energy_fj()
Class SkyrmionHallCorrector¶
Corrects skyrmion trajectory for the skyrmion Hall effect.
Skyrmions drift at an angle θ_H to the applied current direction. θ_H = arctan(4π Q / (α D)) where Q is topological charge.
- hall_angle_deg()
- corrected_position(x_drive, track_width_nm)
- Return (x, y) position accounting for Hall drift.
- needs_confinement()
Class MLCConfig¶
Multi-level cell configuration for spintronic devices.
- post_init()
- resistance_margins()
- Resistance levels evenly spaced between R_P and R_AP.
- quantize_weight(weight_float)
- Quantize a [0, 1] weight to an MLC level.
- dequantize(level)
- density_improvement()
Class WriteVerifyResult¶
Result of a write-verify cycle.
- error()
Class AgingModel¶
Endurance degradation model for spintronic devices.
TMR and thermal stability degrade with write cycles.
- tmr_degradation(initial_tmr, endurance_limit)
- TMR degrades linearly as cycling approaches endurance limit.
- stability_degradation(initial_delta, endurance_limit)
- Thermal stability degrades with oxide breakdown.
- is_worn_out()
- write(n)
Class RadiationModel¶
SEU and TID models for spintronic devices in radiation environments.
- seu_rate(flux_particles_cm2_s, n_devices)
- SEU events per second.
- tid_degradation(dose_krad)
- Fraction of performance remaining after TID.
- is_rad_hard()
- Spintronic devices are inherently radiation-hard (non-charge-based).
Class DefectEntry¶
One defective cell in the array.
Class DefectMap¶
Tracks and remaps defective cells in a spintronic array.
- init()
- add_defect(row, col, defect_type)
- defect_count()
- defect_rate(total_cells)
- add_remap(bad, spare)
- is_defective(row, col)
- effective_address(row, col)
Class MuMax3Result¶
Parsed result from a MuMax3 simulation.
- magnetisation_magnitude()
Class MuMax3OutputParser¶
Parses MuMax3 table output for co-simulation integration.
- parse_table(text)
- Parse a MuMax3 .table output (TSV with header).
- is_switching_successful(result)
Function switching_current_vs_temperature(i_c0_ua, delta_0, temperature_k, temp_ref_k)¶
Ic(T) = Ic0 × (1 - T/T_ref × kBT/(Δ0 × kBT_ref)).
Simplified Néel-Arrhenius model for thermally activated switching.
Function switching_time_vs_temperature(t_sw0_ns, temperature_k, temp_ref_k)¶
Switching time increases with temperature due to thermal fluctuations.
Function retention_failure_probability(thermal_stability, time_seconds, attempt_freq_hz)¶
P_fail = 1 - exp(-t × f0 × exp(-Δ)).
Function write_verify(cell, target_q88, max_attempts, rng)¶
Program a cell with write-verify loop.
Module stochastic_doctor.diagnostics¶
Class AuditSeverity¶
Audit finding severity levels.
Class BitstreamAuditFinding¶
Single finding from a bitstream audit.
Class BitstreamAuditReport¶
Full bitstream-level audit report for a network layer.
JSON-serializable via to_json() for pipeline integration.
- to_dict()
- Serialize to a plain dict (JSON-compatible).
- to_json(indent)
- Serialize to JSON string.
Class DriftDetector¶
Exponential moving average drift detector for SCC monitoring.
Tracks the running EMA of SCC values. Flags a drift event when |EMA| exceeds the threshold.
Parameters¶
alpha : float EMA smoothing factor (0.0–1.0; lower = smoother). threshold : float Absolute SCC value above which to flag drift.
- init(alpha, threshold)
- observe(scc_value)
- Feed a new SCC observation. Returns True if drift detected.
- reset()
- Reset detector state.
- history()
- EMA history for plotting/logging.
Class StochasticDoctor¶
Bitstream-level stochastic diagnostics engine.
Parameters¶
correlation_threshold : float |SCC| above this triggers a WARNING (default 0.3). critical_threshold : float |SCC| above this triggers a CRITICAL (default 0.7).
- init(correlation_threshold, critical_threshold)
- compute_correlation(a, b)
- Compute SCC between two bitstreams.
- estimate_precision(bitstream)
- Estimate probability and variance bound for a bitstream.
- compute_histogram(bitstream, word_size)
- Compute per-word popcount histogram.
- audit_layer(layer_id, bitstreams)
- Audit a full layer of bitstreams.
Function compute_scc(a, b)¶
Compute SCC between two bitstreams.
Uses Rust PyO3 acceleration when available, falls back to pure Python.
Set SC_NEUROCORE_NO_RUST=1 to force Python path.
Module studio._event_training_runtime¶
Function verify_event_training_data(contract)¶
Verify dataset files and sample metadata against the declared manifest.
Parameters¶
contract: Structurally resolved input declaration.
Returns¶
pathlib.Path Absolute operator-configured root. It is never supplied by an HTTP request or included in exported checkpoints.
Raises¶
ValueError If the operator has not configured a root, the expected files are unavailable, or their digests, labels or groups differ.
Notes¶
Rebuilding the manifest checks sample metadata as well as file bytes. This is a content check, not an immutable filesystem snapshot; the operator must keep the dataset unchanged while training runs.
Module studio._training_conversion¶
Class ConversionOutcome¶
A finished conversion run, ready to be recorded by its job.
Attributes¶
model : torch.nn.Module The trained QCFS source network. architecture : str Layer sizes, input to output. model_info : dict Parameter counts and cell summary of the source. observed : dict Unrounded terminal metrics; the job rounds them for publication and judges a preregistered criterion on them as they are. report : dict The sealed conversion loss report. target_report : dict or None The sealed target calibration, when a target profile was named.
Function train_qcfs_conversion(resolved, context)¶
Run the conversion route to completion, or stop at a batch boundary.
Parameters¶
resolved : ResolvedTrainingConfig
A configuration whose model_kind is qcfs_conversion.
context : StudioJobContext or None
Job sandbox the conversion report is sealed into; None for a
direct in-process run, which keeps the report on the outcome only.
job_id : str
Identifier published in the configuration event.
emit : callable
Event sink of the supervising job.
stop_requested : callable
Cooperative cancellation probe.
Returns¶
ConversionOutcome or None
The finished run, or None after a stopped event.
Module studio._training_evidence¶
Function seal_training_status(context, status_payload)¶
Write the public status artifact and the evidence manifest bound to it.
Parameters¶
context : StudioJobContext Job sandbox receiving both artifacts. status_payload : dict The path-free public status. status : {'completed', 'failed', 'cancelled'} How the job ended, as the evidence manifest records it. error_message : str or None The failure, when there is one.
Function write_refused_evidence(context, message)¶
Seal failed evidence for a request that was refused before it ran.
Parameters¶
context : StudioJobContext Job sandbox to write the status and evidence artifacts into. message : str The refusal, as the caller will read it.
Notes¶
A refused configuration never builds a model, so there is no weight checkpoint and no event log to publish — only the reason. Writing it keeps the sandbox's account complete: every job that ends has an evidence artifact saying how.
Module studio._training_job¶
Class TrainingJob¶
Manage one Studio training run for thread or process execution.
Parameters¶
config : dict[str, Any]
Training request. It is resolved against the training contract here, so
an unsupported dataset, surrogate or layer width is refused before the
job exists rather than part-way through a run.
job_id : str or None, optional
Stable platform job identifier. A random legacy identifier is generated
when omitted.
cancelled : Callable[[], bool] or None, optional
Cooperative process-worker cancellation probe.
event_sink : Callable[[dict[str, object]], None] or None, optional
Sink used to persist path-free JSON events from a process worker.
initial_state_dict : Mapping[str, object] or None, optional
Verified model state loaded before the first optimisation step. On its
own this is a warm start: a new run beginning from those weights,
with a fresh optimiser and generator at epoch zero.
resume_state : TrainingResumeState or None, optional
Saved position of a run to continue exactly: the optimiser state,
the generator states and how many epochs are already done. Supplied
together with initial_state_dict; supplying it alone would restore
an optimiser onto weights it never saw.
Raises¶
TrainingConfigError The request names something the Studio cannot run.
- init(config)
- start()
- Start the legacy in-process training thread.
- stop()
- Request cooperative cancellation at the next training boundary.
- run_blocking(context)
- Run this training job inside a bounded Studio job context.
Module studio._training_live_attach¶
Function poll_live_attach(context, model, epoch)¶
Consume one pending control command and apply it when it is an attach.
Parameters¶
context : StudioJobContext Running job whose control channel is polled. model : torch.nn.Module The model being trained. epoch : int Epoch boundary at which the command is considered. job_id : str The running job, recorded in the attach evidence. emit : callable The job's event emitter.
Returns¶
dict or None The written attach evidence, or None when nothing was attached.
Function apply_live_attach(context, model, command, epoch)¶
Verify and load a live weight attach, rejecting on any failure.
Parameters¶
context : StudioJobContext Running job holding the control seeds. model : torch.nn.Module The model being trained; loaded strictly. command : mapping The attach command with its restore plan, fingerprint and seed paths. epoch : int Epoch boundary at which the attach happens. job_id : str The running job, recorded in the attach evidence. emit : callable The job's event emitter.
Returns¶
dict or None The written attach evidence, or None when the attach was rejected.
Module studio._training_weight_capture¶
Class CapturedWeightCheckpoint¶
Serialised terminal weights awaiting artifact publication.
Attributes¶
payload : bytes
The torch.save document, loadable with weights_only=True.
architecture : str
Layer sizes of the network the weights belong to.
parameter_count : int
Total parameters, for the published metadata.
Function capture_weight_checkpoint()¶
Serialise terminal weights, and the run position when there is one.
Parameters¶
model : torch.nn.Module The trained network. architecture : str Layer sizes, as the checkpoint records them. model_info : dict Architecture summary published alongside the weights. config : dict The resolved configuration the run executed. final_metrics : dict or None Terminal metrics, when the run reached them. resume_state : TrainingResumeState or None, optional The position the run reached. Present, a later run can continue this one exactly; absent, the weights support a warm start and nothing more.
Returns¶
CapturedWeightCheckpoint Bytes and metadata for artifact publication.
Notes¶
Everything written here is a tensor or a primitive, so the artifact loads
under weights_only=True. The generator states are integers and a hex
string for exactly that reason: a checkpoint arrives from a user, and
unpickling one would trade that guarantee for convenience.
Module studio.analysis¶
Function fi_curve_sweep(simulate_fn, i_min, i_max, i_steps)¶
Sweep a constant current and report the firing rate at each level.
Parameters¶
simulate_fn:
Callable accepting current= and returning a run result with
stats.rate_hz.
i_min, i_max, i_steps:
Inclusive current range and number of levels.
Returns¶
dict
currents, rates and the metric contract.
Function bifurcation_sweep(simulate_fn, base_config, param_name, param_min, param_max, n_values)¶
Sweep one parameter and record the late-run extrema of one state trace.
This is a numerical extrema sweep under the configured drive, not a
bifurcation continuation: no equilibrium branch is followed and no
stability is computed. At each parameter value the second half of the
trace is inspected; its local maxima and minima (up to
:data:ATTRACTOR_EXTREMA_KEPT of each, rounded to
:data:ATTRACTOR_DECIMALS) are reported as the attractor sample. A
trace without extrema reports its mean as a single fixed-point sample; a
trace with fewer than :data:ATTRACTOR_MIN_SAMPLES late samples is
reported as insufficient.
Parameters¶
simulate_fn:
Callable accepting params= (and the other base-config keys) and
returning a run result with raw traces.
base_config:
Run configuration shared by every sweep point (protocol is
reported).
param_name, param_min, param_max, n_values:
Swept parameter and its inclusive range.
variable:
State variable analysed; the first raw trace when None.
Returns¶
dict
param_name, param_values, attractors (one list per
value), attractor_kinds (extrema / fixed_point /
insufficient_samples), variable, protocol and the
metric contract.
Function sensitivity_analysis(simulate_fn, base_config, param_names, perturbation)¶
Rate elasticity of each parameter under a symmetric relative perturbation.
The elasticity is |rate(p + δ) − rate(p − δ)| / (2 δ) · |p| / rate(p)
with δ = perturbation · |p|. It is undefined (reported as null
with a reason) when the base rate is zero or when the parameter is zero,
because a relative perturbation of zero is no perturbation.
Parameters¶
simulate_fn:
Callable accepting params= and returning a run result with
stats.rate_hz.
base_config:
Run configuration; params holds the base values.
param_names:
Parameters to perturb.
perturbation:
Relative perturbation of each parameter.
Returns¶
dict
base_rate, sensitivities (sorted, undefined last) and the
metric contract; each row carries sensitivity (or null),
reason when undefined, rate_minus / rate_plus when
computed.
Function heatmap_2d(simulate_fn, base_config, param_x, x_min, x_max, x_steps, param_y, y_min, y_max, y_steps)¶
Sweep two parameters and compute the firing-rate map.
The sweep fails closed: when any grid point fails the whole request is rejected with every failure listed, so a partial map is never returned with silent zeros.
Function spike_triggered_average(time, voltage, spikes, dt, window_ms)¶
Average of the trace in a symmetric window around every complete spike.
Spikes whose window would leave the trace are excluded and counted
against n_spikes; the window half-width is window_ms / 2 rounded
down to whole steps (at least one step).
Function frequency_response(simulate_fn, base_config, freq_min, freq_max, n_freqs, bias, depth)¶
Measure how the firing rate follows a sinusoidally modulated current.
The drive is I(t) = bias · (1 + depth · sin(2π f t)): the current
stays about the operating point bias and, for depth < 1, never
changes sign. A mean-zero sine, which this analysis used before, drove
the Studio's default model outside its safety bounds, and reported the
mean rate alone.
At each frequency the result gives the mean rate, the amplitude of the
rate's first harmonic, the gain (that amplitude per unit of modulating
current, modulation / (depth · |bias|)), the phase by which the
response lags the drive, and the vector strength. A frequency whose
period is longer than the run is reported as not measured rather than
estimated from a fraction of a cycle.
Module studio.analysis_contract¶
Class MetricContract¶
What one analysis computed, in which units, and where it is valid.
Parameters¶
kind:
Stable identifier of the metric family ("fi-curve",
"precision-compare", "nullclines", …).
definition:
One-sentence statement of how the reported numbers are computed.
units:
Unit of every reported quantity, keyed by the payload field or the
quantity name; "model-defined" when the equation system carries no
declared unit.
applicability:
Conditions under which the metric is meaningful.
limitations:
Known limits of the computation (resolution, transients, protocol).
domain:
complete when every requested point was evaluated, partial
when some points were invalid and are reported, empty when no
point could be evaluated.
domain_detail:
Path-free detail of the invalid part (counts, fractions, reasons).
- post_init()
- Reject an empty kind or definition and an unknown domain verdict.
- to_public_dict()
- Return the path-free public contract block.
Function attach_contract(payload, contract)¶
Set payload["contract"] and return the same payload.
Function contract_summary(payload)¶
Return (kind, domain) of a payload's contract block, or (None, None).
The analysis manifest records these two values so an evidence bundle can tell a complete-domain result from a partial one without opening the payload.
Module studio.analysis_manifest¶
Class StudioAnalysisResultManifest¶
Path-free metadata for one Studio analysis response.
Parameters¶
analysis_type:
Stable analysis endpoint identifier such as "fi_curve".
source:
Input surface used to produce the analysis result.
input_sha256:
SHA-256 digest of the canonical request payload.
result_sha256:
SHA-256 digest of the canonical result payload without this manifest.
output_keys:
Sorted top-level keys present in the result payload before metadata.
evidence_classification:
Stable evidence lane label for analysis results.
status:
Terminal status for this analysis evidence object.
contract:
Kind of the payload's metric contract (payload["contract"]), or
None for a payload without one.
domain:
Domain verdict of that contract (complete / partial /
empty), or None.
- to_public_dict()
- Return the public, path-free analysis manifest.
Function build_analysis_result_manifest()¶
Build digest-backed reproducibility metadata for an analysis result.
Parameters¶
analysis_type: Stable analysis endpoint identifier. source: Input surface used to produce the result. request_payload: Request body used to run the analysis. result_payload: Result payload before or after metadata insertion.
Returns¶
StudioAnalysisResultManifest Path-free metadata suitable for UI display, exports, and evidence bundles.
Raises¶
ValueError If request or result payloads cannot be encoded as portable JSON, or the payload's contract block carries an unknown domain verdict.
Function attach_analysis_result_manifest()¶
Return an analysis result with a path-free metadata manifest attached.
Parameters¶
analysis_type: Stable analysis endpoint identifier. source: Input surface used to produce the result. request_payload: Request body used to run the analysis. result_payload: Mutable analysis result payload.
Returns¶
dict[str, Any]
The result with analysis_metadata set and its produced-evidence
receipt attached.
Function infer_analysis_source(request_payload)¶
Infer the Studio input surface from an analysis request payload.
Parameters¶
request_payload: Request body submitted to an analysis endpoint.
Returns¶
AnalysisSource
"model" when a model name is present, "ode" when equations are
present, "mixed" for comparison payloads, otherwise "unknown".
Module studio.api.adaptive_precision¶
Function build_adaptive_precision_router(context)¶
Build the adaptive-precision router over shared Studio runtime state.
Module studio.api.analysis_jobs¶
Class AnalysisJobValidationError¶
Raised when an analysis job request payload is invalid.
- init(code)
- to_public_detail()
- Return a path-free public error detail.
Function validate_analysis_job_request(req)¶
Validate the job request and return kind, payload dump, and cost hints.
Returns¶
tuple
(analysis, payload_dump, projected_simulations, duration_ms, dt_ms).
Raises¶
AnalysisJobValidationError When the payload does not match the selected analysis schema.
Function run_analysis_job_task(analysis, payload_dump, _job_context)¶
Execute one validated analysis payload and return a public result dict.
Function execute_analysis_process_task(job_context, payload)¶
Validate a named worker request and run the existing analysis implementation.
Parameters¶
job_context:
Context supplied by the registered process worker, never serialised.
payload:
JSON object with analysis, payload and parameter_order.
The explicit parameter-name sequence preserves stable sensitivity
ordering across transports that sort JSON object keys.
Returns¶
dict[str, object] Existing public analysis result, including its evidence metadata.
Raises¶
ValueError The envelope or selected analysis payload is invalid.
Function submit_analysis_job(job_manager, req)¶
Validate and submit one analysis job; return the public job receipt.
Parameters¶
job_manager : StudioJobService Existing job admission and custody owner. req : AnalysisJobRequest Scientific analysis request, validated before admission. request_id : str or None Middleware-normalized HTTP trace, if submitted through an HTTP route. This is neither an identity assertion nor an idempotency key.
Returns¶
dict[str, Any] Public receipt and projected analysis work with status route.
Raises¶
AnalysisJobValidationError The analysis input is invalid or job admission refuses the work.
Module studio.api.audit¶
Function build_audit_router(context)¶
Build the audit and evidence router over shared Studio runtime state.
Module studio.api.audit_archive_jobs¶
Function execute_quarantine_archive_task(context, payload)¶
Write a quarantine export snapshot through the existing archive owner.
Parameters¶
context : StudioJobContext
Registered worker's bounded artefact context.
payload : mapping
Exactly quarantine_export containing the path-free JSON export.
No audit sink, ledger path, clock override or callable is accepted.
Returns¶
dict[str, object] Existing archive receipt, manifest and summary. Artefact bytes and digests are produced by the original writer in this job's directory.
Raises¶
ValueError Envelope, export schema or artefact byte limits are invalid.
Function execute_quarantine_restore_task(context, payload)¶
Validate and materialise a quarantine archive without updating the live sink.
Parameters¶
context : StudioJobContext
Registered worker's bounded artefact context.
payload : mapping
Exactly archive and manifest; the latter may be null. The
existing writer revalidates their schema and digest relationship.
Returns¶
dict[str, object] Existing restore receipt naming generated JSONL and manifest artefacts.
Raises¶
ValueError Envelope or archive/manifest validation fails, or artefacts exceed limits.
Module studio.api.candidates¶
Class CandidateRequest¶
A candidate package, sent whole.
Class CandidateSimulateRequest¶
A candidate package and the run to perform with it.
Function build_candidates_router(context)¶
Build the candidate-package router.
Parameters¶
context: Shared runtime state; the candidate routes hold none of their own.
Module studio.api.catalogue¶
Function build_catalogue_router(context)¶
Build the catalogue and benchmark router over shared Studio runtime state.
Module studio.api.compiler¶
Function build_compiler_router(context)¶
Build the compiler router over shared Studio runtime state.
Module studio.api.cosim¶
Function build_cosim_router(context)¶
Build the co-simulation router over shared Studio runtime state.
Module studio.api.deploy¶
Function build_deploy_router(context)¶
Build the deployment pipeline router over shared Studio runtime state.
Module studio.api.design¶
Class ReviewCommentBody¶
A review comment on one revision.
Function build_design_router(context)¶
Build the project and network-design router over shared Studio runtime state.
Module studio.api.evidence_jobs¶
Class EvidenceInputLimitExceeded¶
Aggregate snapshot metadata and declared source bytes exceed policy.
Class EvidenceSeedInputs¶
Load one verified source artifact at a time while the manager writes seeds.
This mapping retains only declarations, never a cache of all binary payloads. The manager's existing per-seed limit remains independent of aggregate policy.
Parameters¶
records : sequence of StudioJobRecord Captured records whose ordered artifacts define deterministic seed names. reader : callable Trusted API-side artifact reader. Each lookup verifies returned metadata, size and digest; construction does not read payloads or write files.
- init(records, reader)
- len()
- Return the declared seed count without reading source files.
- iter()
- Yield deterministic seed names in source-record and artifact order.
- getitem(name)
- Read and verify one seed; reject unknown names or changed source bytes.
Function prepare_evidence_process_payload(inputs, records, max_input_bytes)¶
Validate complete snapshots and their total metadata-plus-artifact bytes.
No source bytes are read here. Exceeding the explicit aggregate limit raises
EvidenceInputLimitExceeded before job admission or seed directory writes.
Invalid writer inputs or records raise ValueError without dropping fields.
Parameters¶
inputs : mapping Every original writer input category, excluding executable callbacks. records : sequence of StudioJobRecord Complete source snapshots; declared artifact sizes contribute to the cap. max_input_bytes : int Positive aggregate byte ceiling for encoded metadata and all seed copies.
Returns¶
dict[str, object] Validated JSON-compatible envelope for the named process task.
Raises¶
EvidenceInputLimitExceeded Aggregate metadata and declared binary bytes exceed the configured cap. ValueError The limit, JSON input envelope or declared sizes are invalid.
Function execute_evidence_bundle_task(context, payload)¶
Recheck snapshots/seeds and invoke the original complete bundle writer.
Parameters¶
context : StudioJobContext Registered worker's bounded seed and output context. payload : mapping Exact inputs, complete records and API-selected max_input_bytes.
Returns¶
dict[str, object] Original bundle receipt; the existing writer owns all evidence semantics.
Raises¶
ValueError Envelope, record, byte budget, seed integrity or evidence validation fails.
Module studio.api.export¶
Function build_export_router(context)¶
Build the export and progress router over shared Studio runtime state.
Module studio.api.fit_jobs¶
Class MeasurementRequest¶
A complete scientific result and externally acquired receipts.
Class CohortRequest¶
The full versioned experiment document, without local path references.
Function execute_laboratory_task(context, payload)¶
Run an admitted scientific task with cancellation and durable artifacts.
Parameters¶
context: Existing confined process-worker context. payload: Validated operation and complete exported scientific problem.
Returns¶
dict Replayable fit, cohort or replay result; no local filesystem paths.
Function build_fit_jobs_router(context)¶
Register scientific jobs with the existing bounded process manager.
Module studio.api.fits¶
Class DomainBody¶
One fitted parameter's search domain.
Class ConstraintBody¶
A bounded linear combination of named parameter values.
Class RecordingBody¶
One stimulus and the observed response.
Class FitRequest¶
A fit: the model, what to fit, and the split cohort.
Class ReplayRequest¶
An exported fit result.
Function estimated_fit_steps(request)¶
Projected model steps for admission, not a hard execution-time guarantee.
Differential evolution evaluates population x parameters members per
generation, plus the initial population; the local polish and the
identifiability differences add a few evaluations per parameter, counted
here as one more generation.
Function refusal_message(exc)¶
Return the text a refused laboratory request may show its caller.
Parameters¶
exc: The exception that stopped the request.
Returns¶
str
The deliberate message of a LaboratoryRefusal, or
:data:MALFORMED_DOCUMENT for every other exception, including
generated conversion and Pydantic validation errors.
Function fit_problem(request)¶
Validate a request into the replayable scientific fitting problem.
Function fit_replay_request(result)¶
Validate replay optimiser limits through the same request schema as new fits.
Function build_fits_router(context)¶
Build the parameter-fitting router.
Parameters¶
context: Shared runtime state, including the existing background process manager.
Module studio.api.frontend¶
Function studio_frontend_candidates(app_module_file)¶
Return where a built frontend is looked for, in order.
The packaged build comes first, so an installation serves its own; the checkout's build follows, found from the application module.
Function studio_frontend_dir(candidates)¶
Return the first candidate holding a built frontend, or None.
Function studio_entry(origin, dist_dir)¶
Return the page a launched Studio opens and the lines announcing it.
Parameters¶
origin:
Scheme, host and port the API serves, without a trailing slash.
dist_dir:
The built frontend :func:studio_frontend_dir found, or None.
Returns¶
tuple The URL to open, and the lines to print before opening it. Without a frontend the root would be an empty page, so the API documentation opens instead and the first line says why.
Function mount_studio_frontend(app)¶
Mount the built frontend at :data:STUDIO_UI_PATH when one exists.
Parameters¶
app: FastAPI application receiving the root redirect and the static mount. app_module_file: Path of the application module, the anchor for the checkout's build.
Module studio.api.identity¶
Function build_identity_router(context)¶
Build the identity and browser-session router over shared Studio runtime state.
Module studio.api.jobs¶
Function build_jobs_router(context)¶
Build the job inspection router over shared Studio runtime state.
Module studio.api.model_scan_jobs¶
Function execute_model_scan_process_task(context, payload)¶
Validate the operating point and classify every model in the catalogue.
Parameters¶
context : StudioJobContext
Registered worker context. Process cancellation is enforced by the
supervisor; the scan also retains its cooperative stop callback.
payload : mapping
Exactly current (finite, model-native input units) and duration
(finite positive milliseconds). The HTTP route supplies these values.
Returns¶
dict[str, object]
Complete studio.model-scan.v1 response with configuration/result
digests and explicit per-model failures. No catalogue subset is used.
Raises¶
ValueError The envelope has missing/extra fields or invalid numeric values. StudioJobCancelled The cooperative callback requests cancellation before a model runs.
Module studio.api.presets¶
Function build_presets_router(context)¶
Build the preset and default-flow router over shared Studio runtime state.
Module studio.api.runtime¶
Class StudioApiContext¶
Hold the collaborators shared across Studio route responsibilities.
- run_studio_process_job_sync()
- Run one importable task through the bounded process worker.
Function build_studio_api_context(app, runtime_settings)¶
Build and expose the collaborators used by Studio routers.
Parameters¶
app: FastAPI application receiving the collaborators in its state. runtime_settings: Optional validated settings override.
Returns¶
StudioApiContext Shared mutable runtime state.
Module studio.api.schemas¶
Class SimulateRequest¶
Request body for direct equation-playground simulation in Studio.
The body is fail-closed: unknown keys are rejected, the protocol must be
one of the supported injection protocols (a typo never becomes
constant), the sine frequency is explicit, and the randomness
contract is explicit: seed fixes the diffusion-noise generator of a
stochastic run (xi in the equations), trial selects replay of a
trial (cacheable) or a fresh trial whose drawn seed is reported.
Class ModelSimulateRequest¶
Request body for model-catalogue simulation in Studio.
The body is fail-closed: unknown keys are rejected, parameter overrides and
the timestep must be finite numbers (booleans and strings are not numbers),
and the protocol must be one of the supported injection protocols. Model-
specific validation (unknown parameter names, integer fields, unsupported
step inputs) is performed by the run contract and reported as
:class:ModelInputErrorDetail.
Class ModelInputErrorDetail¶
422 detail for a model-run request rejected before any simulation step.
Class ExperimentRejectedDetail¶
422 detail for a simulation request the experiment contract refuses.
Class NativeToolUnavailableDetail¶
503 detail for an analysis that needs a native tool the host lacks.
Class ModelSimulationFailureDetail¶
422 detail for a validated model run that failed numerically at a step.
Class RequestValidationErrorItem¶
One body-validation error as produced by the request schema.
Class ModelRunErrorResponse¶
422 response body of every route that executes a catalogue model run.
Class NativeToolUnavailableResponse¶
503 response body when the host lacks the C compiler of the bit-true kernel.
Class FICurveRequest¶
Request body for firing-rate versus current sweeps.
Class DclsEvaluateRequest¶
Request body for DCLS kernel parity evaluation.
Class BenchmarkRunRequest¶
Request body for local Studio benchmark runs.
Class BenchmarkContributeRequest¶
Request body for benchmark-databank contribution uploads.
Class CompileRequest¶
Request body for equation-to-SystemVerilog compilation.
Class DirectCompileRequest¶
Direct RTL export with its historical default module name.
Class ModelCompileRequest¶
Request body for schema-backed catalogue-model RTL compilation.
Class ModelCosimRequest¶
Request body for real selected-model RTL co-simulation.
Class SynthesisTerminalRequest¶
Request body for digest-bound selected-model synthesis and PnR.
Class BifurcationRequest¶
Request body for one-parameter numerical extrema sweeps.
The response is labelled numerical-extrema-sweep: the late-run
extrema of one state trace per parameter value under the configured
drive, not a bifurcation continuation. The drive is protocol at
current (and frequency_hz for a sine); it was a sine regardless
of the request, which the Studio did not show and which drove some
catalogue models out of their safety bounds at any swept value.
Class SensitivityRequest¶
Request body for Studio model sensitivity analysis.
Class NullclineRequest¶
Request body for two-dimensional nullcline analysis.
current is the input the drift field is evaluated at and held
fixes every equation variable that is not swept (an unlisted one is held
at its initial value). Invalid grid samples are reported as validity
masks, never as zero derivatives.
Class PrecisionRequest¶
Request body for float64 versus bit-true fixed-point comparisons.
q_format names the word (Q8.8 = 16 bits, 8 fractional; 8 to 32
bits), overflow and rounding the kernel's accumulate and product
policies. Values the word cannot hold are rejected, never clamped.
Class AdaptivePrecisionAutoTuneRequest¶
Request body for adaptive synapse-precision auto-tuning.
Class AdaptivePrecisionFormalBundleRequest¶
Request body for adaptive-precision formal evidence bundles.
Class PresetActionResolveRequest¶
Request body for resolving one preset action template.
Class PresetActionsExecuteAllRequest¶
Request body for executing all actions attached to a preset.
Class PresetDefaultFlowRunRequest¶
Request body for running a preset's default action flow.
Class PresetDefaultFlowVerifyRequest¶
Request body for verifying a preset default-flow plan.
Class PresetDefaultFlowGuardedRunRequest¶
Request body for running a preset flow with fingerprint guards.
Class PresetDefaultFlowRunFromContractRequest¶
Request body for running a preset flow from a stored contract.
Class PresetDefaultFlowAttestRequest¶
Request body for attesting a completed preset flow run.
Class StudioIdentityServiceAccountUpdateRequest¶
Request body for admin service-account metadata updates.
Class StudioBrowserUserUpdateRequest¶
Request body for admin browser-user metadata updates.
Class StudioBrowserUserCreateRequest¶
Request body for admin browser-user creation.
Class StudioBrowserUserPasswordRotateRequest¶
Request body for admin browser-user password rotation.
Class StudioBrowserLoginRequest¶
Request body for browser-user login.
Class StudioEvidenceBundleRequest¶
Request body for admin evidence bundle export.
Class StudioAuditQuarantineArchiveRequest¶
Request body for admin audit quarantine archive creation.
Class StudioAuditQuarantineArchiveValidateRequest¶
Request body for admin audit quarantine archive validation.
Class StudioAuditQuarantineArchiveRestoreRequest¶
Request body for admin audit quarantine archive restore materialization.
Class StudioAuditQuarantineArchivePurgeRequest¶
Request body for admin audit quarantine archive retention purges.
Class StudioTrainingWeightRestoreRequest¶
Request body for admin training weight-restore materialization.
Class StudioTrainingWeightAttachRequest¶
Request body for admin training weight-restore attach.
mode names which of two different runs is being started.
warm_start begins a new run from the restored weights with a fresh
optimiser and generator at epoch zero. exact_resume continues the
source run from its recorded position, restoring the optimiser and
generator states and the epoch already reached; it is refused when the
saved position belongs to a different configuration or architecture.
Class StudioTrainingWeightLiveAttachRequest¶
Request body for admin training weight-restore live attach.
Class PresetDefaultFlowAttestationVerifyRequest¶
Request body for verifying a preset flow attestation.
Class CompareRequest¶
Request body for comparing two Studio simulation configurations.
Class FreqResponseRequest¶
Request body for frequency-response analysis.
The drive is bias · (1 + depth · sin(2π f t)). amplitude named the
mean-zero sine this analysis used before; a request that still sends it
is refused with that reason rather than read under the new definition.
Class HeatmapRequest¶
Request body for two-parameter response heatmap analysis.
Every grid point runs under protocol at current (frequency_hz
for a sine): the drive the Studio shows, not a fixed constant one.
Class AnalysisJobRequest¶
Request body for asynchronous heavy analysis job submission.
The analysis field selects the synchronous analysis kind. payload
must match the corresponding synchronous request schema (for example
:class:BifurcationRequest when analysis is bifurcation;
:class:ModelSimulateRequest or :class:SimulateRequest when
analysis is simulate, the route for a run the synchronous
simulation routes refuse as oversized).
Class NetworkRequest¶
Request body for balanced excitatory-inhibitory network simulation.
Weights are membrane jumps in millivolts in the post-pre convention
(w_ei is inhibitory-to-excitatory). ext_rate is the rate in hertz
of each of the 800 external excitatory inputs every neuron receives; about
9.4 Hz reaches threshold. See :mod:sc_neurocore.studio.network.
Class ModelExperimentExportRequest¶
Export request for one catalogue-model experiment.
Identical to :class:ModelSimulateRequest plus the mode discriminator,
so an export resolves through the same fail-closed contract that runs it:
the timestep, protocol, randomness and parameter overrides an export claims
are the ones the run would use.
Class OdeExperimentExportRequest¶
Export request for one equation-playground experiment.
Identical to :class:SimulateRequest plus the mode discriminator.
Module studio.api.security¶
Function install_studio_security_middleware(app, context)¶
Install request limits, policy checks, and response security headers.
Parameters¶
app: FastAPI application receiving the middleware. context: Shared runtime state used for policy and identity decisions.
Module studio.api.simulation¶
Function build_simulation_router(context)¶
Build the simulation and analysis router over shared Studio runtime state.
Module studio.api.synthesis¶
Function build_synthesis_router(context)¶
Build the synthesis and place-and-route router over shared Studio runtime state.
Module studio.api.system¶
Function build_system_router(context)¶
Build the system and capability router over shared Studio runtime state.
Module studio.api.training¶
Function build_training_router(context)¶
Build the training monitor router over shared Studio runtime state.
Module studio.api.training_weight_jobs¶
Function execute_training_weight_restore_task(context, payload)¶
Verify binary seeds and emit the existing path-free restore receipt.
Parameters¶
context : StudioJobContext
Registered worker context holding bounded metadata and checkpoint seeds.
payload : mapping
Exactly restore_plan and source_status from the source job.
The original materializer validates lengths and digests before loading.
Returns¶
dict[str, object] Restore evidence also written as the canonical JSON artifact. Loaded tensor state remains inside this worker and is not returned.
Raises¶
ValueError Envelope, plan, seed integrity or restricted checkpoint loading fails. StudioJobArtifactUnavailable A required submission seed is absent.
Module studio.api.training_weights¶
Function build_training_weights_router(context)¶
Build the training-weight lifecycle router over shared Studio runtime state.
Module studio.app¶
Function create_app(runtime_settings)¶
Create and configure the Visual SNN Studio FastAPI application.
Parameters¶
runtime_settings: Optional validated runtime settings. Environment-derived settings are used when omitted.
Returns¶
FastAPI Application with security middleware and responsibility routers mounted.
Module studio.behavior_probe¶
Class BehaviorObservation¶
One reproducibility-checked observation at a single drive current.
- to_public_dict()
- Return a JSON-compatible observation.
Class ModelBehaviorProfile¶
The measured behavioural envelope of one model over the current sweep.
- to_public_dict()
- Return a JSON-compatible behaviour profile.
Function derive_behavior_tags(observations)¶
Derive the behaviour tags from a model's sweep observations.
Pure and side-effect free, so the tag logic is testable without running any simulation. Excitability is read from the sign of the response (robust even for stochastic models); the firing-pattern tags are read only from reproducible observations, and are withheld entirely for a stochastic model.
Parameters¶
observations: The per-current observations, in any order. stochastic: Whether the model's spike train failed to reproduce at some drive.
Returns¶
tuple[str, ...] The validated, sorted behaviour tags. Empty when no current could be driven (an honest "no measured behaviour").
Function probe_model_behavior(name)¶
Probe one model across the current sweep and derive its behaviour tags.
Never raises for a model that cannot be driven: each failed drive is recorded as an error observation and the profile is still returned.
Function probe_all_models()¶
Probe every catalogue model and return a recordable evidence manifest.
The manifest is the source the fast catalogue gate compares descriptors
against: a per-model tag set plus the sweep configuration and digests, so a
committed behavior_tags field can be checked for equality with the
measurement without re-running any simulation.
Function load_behavior_evidence()¶
Load the recorded behaviour evidence manifest.
Raises¶
FileNotFoundError If the manifest has not been generated.
Function behavior_tags_for(name, evidence)¶
Return the recorded behaviour tags for a model (empty if unrecorded).
Module studio.benchmark_contribution¶
Function safe_environment()¶
Collect only the privacy-safe, aggregatable host facts.
Function run_local_benchmark(n_channels, n_taps, repeats, seed)¶
Time the DCLS kernel across the in-process-safe backends on this machine.
Returns a fully-formed submission (schema scpn.benchmark.submission.v1)
that the caller may inspect and, opt-in, hand to :func:store_contribution.
Julia is never run in the server process (see
:data:sc_neurocore.studio.dcls.IN_PROCESS_REFUSED_BACKENDS) and is reported
as parity-verified offline rather than timed live.
Function validate_submission(payload)¶
Return a list of schema/privacy violations; empty means the payload is OK.
Function store_contribution(payload, handle)¶
Validate and append a submission to the local databank (opt-in path).
Raises ValueError with the joined violations if the payload fails schema
or privacy validation, so an invalid or identifying submission never lands.
Function load_databank()¶
Return every stored contribution (already free of identifying fields).
Function databank_leaderboard()¶
Aggregate the databank into a per-CPU, per-backend speed-up leaderboard.
Module studio.bit_true_execution¶
Class NativeToolUnavailable¶
Raised when a required native tool is not installed on the host.
Parameters¶
tools: Names of the missing tools. purpose: What the tools were needed for, without repository paths.
- init(tools, purpose)
- to_public_detail()
- Return the path-free public error detail.
Class NativeExecutionError¶
Raised when a native compile or run fails or exceeds its time budget.
Class BitTrueTrace¶
Integer state words and spikes of one bit-true kernel run.
Parameters¶
module_name:
Name the kernel was generated under.
variables:
Equation variable names in declaration order (the word columns).
words:
(n_steps, len(variables)) post-step state words.
spikes:
(n_steps,) spike flag of every step.
drive_words:
(n_steps,) input words the kernel consumed.
fraction:
Fractional bits of the word format (for :meth:decoded).
kernel_sha256, harness_sha256:
Digests of the generated kernel source and of the harness main.
compiler:
First version line of the C compiler used.
- n_steps()
- Number of executed steps.
- decoded()
- Return every state trace decoded to float64 (
word / 2**fraction). - spike_steps()
- Return the raw step indices at which the kernel spiked.
Function resolve_native_tool(name)¶
Return the absolute path of a supported native tool, or None.
Function require_native_tools(names)¶
Resolve every tool in names or raise :class:NativeToolUnavailable.
Function run_native_command(command)¶
Run command without a shell and raise a bounded error on failure.
Function native_tool_version(path, name)¶
Return the first version line a tool prints, or a stable placeholder.
Function harness_main(neuron, module_name, data_width)¶
Return the C main that streams input words in and state rows out.
The harness reads little-endian int64 input words from the file named
by its first argument, calls <module>_step once per word and appends
one binary row [spike, <state words…>] of int64 to the file named
by its second argument. Binary rows avoid any text formatting of the
words on either side.
Function run_bittrue_kernel(neuron)¶
Compile the neuron's bit-true kernel and run it under drive_words.
Parameters¶
neuron:
Equation neuron whose equations, parameters, threshold and reset
rules are lowered (method must be euler or map).
data_width, fraction:
Fixed-point word geometry.
overflow, rounding:
Accumulate overflow and product rounding policies of the kernel.
drive_words:
One already-encoded signed input word per step. The caller is
responsible for representability; a word outside the data_width
range is rejected here rather than wrapped.
module_name:
Identifier for the generated kernel.
timeout_seconds:
Budget for each of the compile and the run.
Returns¶
BitTrueTrace Words and spikes of every step.
Raises¶
NativeToolUnavailable When no C compiler is installed. NativeExecutionError When compilation or execution fails or times out. ValueError For an empty or oversized drive, a word outside the format, or a kernel configuration the generator rejects.
Module studio.candidate_diff¶
Function compare_expressions(parent, candidate)¶
Compare two equations as text and as mathematics.
Returns¶
dict
status is unchanged (same text), equivalent (equal after
simplification), changed (with difference, candidate minus
parent), undecided (too large to simplify here) or
not_comparable (with reason).
Function diff_models(parent, candidate)¶
Return what candidate changes against parent, section by section.
Both are Universal DSL schema documents.
Function diff_candidate(document)¶
Diff a validated candidate against the catalogue model it names as parent.
Returns¶
dict The diff, or a statement of why there is none: the candidate names no parent, or the parent has no canonical schema to compare with.
Module studio.candidate_package¶
Class CandidateDiagnostic¶
One problem with a candidate, located by a JSON pointer.
- to_public_dict()
- Return the diagnostic as the API reports it.
Class CandidateValidation¶
The outcome of validating one candidate document.
- valid()
- Whether the document has no problem.
- to_public_dict()
- Return the validation as the API reports it.
Function candidate_sha256(document)¶
Return the digest of a candidate's canonical JSON form.
Function validate_candidate(document)¶
Validate a candidate document and locate every problem.
Parameters¶
document: The parsed candidate package. catalogue: Registered catalogue model names; taken from the registry when omitted. A candidate may not take a catalogue model's name, and its parent must be one.
Returns¶
CandidateValidation The problems, each with a JSON pointer, and the document digest when it is an object.
Module studio.candidate_run¶
Class CandidateRejected¶
The candidate is not valid, so it is not run.
- init(validation)
Function require_valid_candidate(document)¶
Refuse a candidate that is not valid.
Raises¶
CandidateRejected Carrying the located validation, when the candidate has any problem.
Function simulate_candidate(document)¶
Simulate a valid candidate under a constant current.
Raises¶
CandidateRejected
When the candidate is not valid; the exception carries the validation.
ValueError
When steps is outside 1 .. MAX_CANDIDATE_STEPS.
Function run_reference_tests(document)¶
Run every reference test a valid candidate proposes.
Each result states what was observed and, per expectation, whether it held.
Function review_packet(document)¶
Assemble the review packet of a valid candidate.
The packet carries the candidate unchanged, its validation, its diff against the parent, the reference-test results, the environment that produced them and what the packet does not establish, all under one digest.
Module studio.catalogue_query¶
Class CatalogueQueryRejected¶
A query names a filter value the catalogue cannot hold.
Class CatalogueQuery¶
What a catalogue query asks for; every field left at its default is no filter.
- from_params(cls, params)
- Build a query from HTTP query parameters, refusing what cannot be one.
Function query_catalogue(query)¶
Return the identities query admits and the facet counts around them.
Returns¶
dict
schema_version, the corpus_revision the answer was computed on,
total registered identities, matched count, the matching
models (names, sorted) and facets: for each facet, the count per
value over the models every other filter admits; for the verified tiers
and verified_perfect, counts over the matched models.
Module studio.characterize¶
Function characterize_model(simulate_fn, base_config)¶
Run a full characterisation suite on a neuron model.
Returns a dict with: - trace: simulation result at default current - pattern: firing pattern classification - fi_curve: firing rate vs current (20 points) - threshold_current: estimated rheobase (lowest current that produces spikes) - max_rate: maximum firing rate in the f-I sweep - isi_stats: ISI statistics at default current - sensitivity: top 5 most sensitive parameters - state_var_ranges: min/max of each state variable
Module studio.codegen¶
Function generate_experiment_script(spec, request)¶
Generate a standalone script that reproduces one resolved experiment.
Parameters¶
spec : ExperimentSpec
The resolved experiment the script must reproduce.
request : dict
The request fields that re-resolve to spec; a drawn seed must
already be pinned (see
:func:~sc_neurocore.studio.replay_pack.pinned_request).
Returns¶
str Python source. It re-resolves the request, refuses on a digest mismatch, runs the experiment through the public runner and reports the spike count, the effective time step and the final state.
Function generate_replay_script(pack_filename)¶
Generate a script that replays a saved pack and compares it in full.
Parameters¶
pack_filename : str
Name of the studio.replay-pack.v2 file the script reads, relative
to the script's working directory.
Returns¶
str Python source that verifies, runs and judges the pack, and exits 0 for reproduction, 1 for mismatch or 2 for refusal before execution. Refusal details are JSON on standard error, matching the public CLI.
Function generate_oneliner(spec, request)¶
Generate a copy-paste one-liner that runs the same experiment.
Parameters¶
spec : ExperimentSpec
The resolved experiment. Its source decides nothing here; the request
carries everything the contract needs.
request : dict
The request fields that re-resolve to spec.
Returns¶
str
A single line for a notebook or a python -c invocation. It runs the
same effective experiment as the exported script; it does not check the
digest, so use the script when reproducibility must be proven.
Module studio.compile_traceability¶
Class StudioCompileTraceability¶
Path-free source-to-RTL provenance for a Studio compile result.
Parameters¶
equations: ODE equation strings submitted by the operator. threshold: Optional spike-threshold expression. reset: Optional reset expression. params: Numeric parameter overrides used by the compiler. init: Initial state values supplied with the request. module_name: RTL module name requested by the operator. verilog: Generated Verilog/SystemVerilog source. source: Stable source-kind label for the compile request. output_language: RTL language emitted by the backend compiler. evidence_classification: Evidence lane label consumed by Studio evidence bundles. status: Terminal status for this compile traceability object. source_payload_override: Optional path-free payload for non-ODE sources such as catalogue models.
- to_public_dict()
- Return the public, path-free traceability payload.
Function build_compile_traceability()¶
Build path-free traceability for an equation-to-RTL compile result.
Parameters¶
equations: ODE equation strings submitted by the operator. threshold: Optional spike-threshold expression. reset: Optional reset expression. params: Numeric parameter overrides used by the compiler. init: Initial state values supplied with the request. module_name: RTL module name requested by the operator. verilog: Generated Verilog/SystemVerilog source.
Returns¶
StudioCompileTraceability Immutable traceability record with stable public JSON conversion.
Raises¶
ValueError If no equations are supplied.
Function build_model_compile_traceability()¶
Build path-free traceability for catalogue-model RTL compilation.
Module studio.compiler¶
Function build_ir_from_equation(equations, params, threshold, reset, dt)¶
Build an SC IR graph from ODE equations.
Uses the Rust ScGraphBuilder to construct a stochastic computing IR that represents the neuron's ODE as a hardware pipeline: input current → encode → multiply (leak, gain) → LIF step → output spike.
Function verify_ir(ir_text)¶
Parse and verify an IR text representation.
Function emit_systemverilog(ir_text)¶
Parse IR text and emit synthesisable SystemVerilog.
Function emit_sv_from_equation(equations, params, threshold, reset, init, module_name)¶
Direct equation → SystemVerilog via the Python equation compiler.
Function cosim_traces(equations, threshold, reset, params, init, dt, duration, current)¶
Run the float64 reference and the bit-true fixed-point kernel side by side.
This is the precision comparison of
:func:sc_neurocore.studio.precision_compare.precision_compare: the
fixed-point trace is the generated bit-true kernel executed natively,
not a float run with rounded parameters.
Module studio.dcls¶
Function probe_backends()¶
Report each backend's in-process status without ever crashing.
Each entry is {backend, available, live}: live is False for a
backend the server never runs in its own process
(:data:IN_PROCESS_REFUSED_BACKENDS), in which case available reflects
its declared support rather than a live probe.
Function dcls_benchmark()¶
Return the recorded multi-backend throughput benchmark, or None.
These are pre-measured numbers from benchmarks/results — a CPU-shielded
run on a known host — not a live timing, so the Studio reports honest,
reproducible figures with their measurement context rather than noisy
per-request samples. Backends are ordered fastest-measured-first; Python is
the 1x reference floor.
Function dcls_kernel_info()¶
Describe the DCLS-max kernel: provenance, fixed-point contract, evidence.
Function dcls_tent_profile(centre_q88, sigma_q88, n_taps)¶
Return the per-tap triangular gate profile of a learnable tent kernel.
Each delay tap t receives a Q8.8 gate from :func:tent_gate_q88; the
profile is what the learnable centre/sigma shape and what the synapse
convolves the spike taps against.
Function dcls_forward_parity(spikes, weights_q88, centre_q88, sigma_q88)¶
Run the contraction on every available backend and report the parity.
The Python floor is the reference; each accelerated backend must reproduce
its Q8.8 output bit-for-bit. The returned bit_exact flag is the evidence
that the learnable-delay kernel is hardware-faithful across the whole stack.
Module studio.event_training_budget¶
Function admit_event_training_input(contract, batch_size)¶
Check the operator's budget for encoded inputs and loader collation.
Parameters¶
contract: Structurally validated temporal input and complete split plan. batch_size: Requested positive batch size. Accounting uses the largest actual batch possible in the selected training and evaluation parts.
Returns¶
dict Path-free accounting receipt with explicit sample, collation and boolean encoding buffers, dimensions and operator limit.
Raises¶
ValueError Batch size cannot be represented by the loader, the operator limit is invalid, or the accounted input buffers exceed that limit.
Notes¶
This is an admission budget for input tensors, not a bound on total process memory. Raw recording arrays, model parameters, optimiser state, activations and library overhead require the worker's separate resource limits. No tensor is allocated to calculate this receipt.
Module studio.event_training_contract¶
Class EventTrainingContract¶
Portable event data custody, with no operator filesystem path.
Attributes¶
manifest: Every dataset file, sample, label, group and publisher declaration. split: Complete partition of one published source split by whole groups. encoder: Explicit event window, channel layout and late-event semantics. train_split, evaluation_split: Distinct non-empty parts of the plan used for optimisation and scoring.
- to_dict()
- Return the exact portable declaration used in training checkpoints.
- receipt()
- Return input digests, sample counts and temporal semantics for a run.
- digest()
- Return the SHA-256 of the complete canonical data contract.
Function resolve_event_training_contract(payload)¶
Validate event data declarations before allocating a training job.
Parameters¶
payload: Portable manifest, split, encoder and selected part names. dataset: Dataset requested by the training configuration. timesteps: Training window; must equal the declared encoder window.
Returns¶
EventTrainingContract Structurally verified declaration. Disk verification is a separate required admission step and is repeated by the training worker.
Raises¶
ValueError If the declaration, groups, geometry, polarity, time window or selected optimisation/evaluation parts cannot be honoured.
Module studio.event_training_data¶
Class EventTrainingDataset¶
Read and encode an admitted plan's samples lazily for a Torch loader.
Parameters¶
root: Verified operator root. contract: Portable file, split and encoder custody. part: A declared split part used by the training or evaluation loader.
- init(root, contract, part)
- len()
- Return the number of samples in this plan part.
- getitem(index)
- Return one float spike tensor
(timesteps,channels)and label.
Function event_training_loaders(contract, batch_size)¶
Build lazy train/evaluation loaders after verifying the full manifest.
Parameters¶
contract: Structurally resolved manifest, plan and encoder. batch_size: Requested batch size. Incomplete final batches are retained.
Returns¶
tuple
Torch loaders whose batches have shape (batch,timesteps,channels).
The runner transposes the first two axes for SpikingNet.
Module studio.evidence_chain¶
Class EvidenceChainEntry¶
The verdict reached for one subject in a pack.
Attributes¶
name : str
Pack-relative name of the subject, used for operator reporting.
verdict : str
One of the :data:EvidenceVerdict values.
receipt_id : str
Receipt identifier, empty for an unsealed subject.
reason : str
What the verifier observed, in words an operator can act on.
- to_public_dict()
- Return the entry as it is written into a chain document.
Class EvidenceChainReport¶
The result of verifying a whole pack.
Attributes¶
entries : tuple of EvidenceChainEntry One entry per subject, in the order supplied. verified : bool True when nothing in the pack contradicts anything else in it. complete : bool True when every subject was checkable and checked. A pack can be verified without being complete: exporting a run without its inputs leaves links this pack cannot check. verified_at_utc : str When the verification ran.
- verdict_counts()
- Return how many subjects reached each verdict.
- unverified()
- Return every entry that did not verify, including unsealed ones.
- contradicted()
- Return every entry whose verdict contradicts the rest of the pack.
- to_public_dict()
- Return the chain document written beside a bundle manifest.
Function verify_evidence_chain(subjects)¶
Verify a whole pack of evidence against its own receipts.
Parameters¶
subjects : mapping of str to mapping Pack-relative name to payload, as read back from the exported files. now : datetime, optional Verification time recorded in the report.
Returns¶
EvidenceChainReport One verdict per subject, plus whether the pack verified as a whole.
Raises¶
EvidenceReceiptError If a receipt is present but cannot be read. A malformed receipt is a broken pack, not a subject that merely failed.
Module studio.evidence_classification¶
Function validate_studio_evidence_classification(value)¶
Return a controlled Studio evidence class or fail closed.
Parameters¶
value: Candidate evidence class supplied by a Studio manifest.
Returns¶
StudioEvidenceClassification The validated evidence class.
Raises¶
ValueError
If value is not one of the supported Studio evidence classes.
Function validate_studio_evidence_status(value)¶
Return a controlled terminal evidence status or fail closed.
Parameters¶
value: Candidate terminal status supplied by a Studio manifest.
Returns¶
StudioEvidenceStatus The validated terminal evidence status.
Raises¶
ValueError
If value is not a supported terminal evidence status.
Module studio.evidence_receipt¶
Class EvidenceReceiptError¶
Raised when a receipt is malformed and cannot be read at all.
Class EvidenceDependency¶
One input a piece of evidence rests on.
Attributes¶
lane : str
Evidence class of the input, such as simulation.
key : str
Scope field that identifies the input, such as experiment_sha256.
value : str
Value that field must carry on the input.
- to_public_dict()
- Return the dependency as it is written into a receipt.
Class EvidenceReceipt¶
What one piece of evidence is, rests on, and was produced under.
Attributes¶
receipt_id : str
Content address <lane>.<first 32 characters of the seal>. It names
the sealed artefact, so the same artefact exported from any session
carries the same identifier; the run behind it is named by scope.
lane : str
Controlled evidence class.
status : str
Terminal status of the action that produced the subject.
binding : str
Whether the receipt attests production or only export; see
:data:EvidenceBinding.
seal_algorithm : str
Digest algorithm of seal_sha256.
seal_sha256 : str
Cross-runtime seal of the subject without its receipt.
scope : mapping of str to str
Identity the subject was produced under — model class, descriptor and
schema digests, numerical profile, experiment digest.
depends_on : tuple of EvidenceDependency
Inputs this evidence rests on.
produced_at_utc : str
Second-precision UTC timestamp, Z-suffixed.
- to_public_dict()
- Return the receipt block as it is embedded in a subject payload.
Function subject_of(payload)¶
Return the sealed part of a payload: everything but its own receipt.
Parameters¶
payload : mapping A payload that may already carry a receipt.
Returns¶
dict
The payload without :data:EVIDENCE_RECEIPT_KEY.
Function build_evidence_receipt(payload)¶
Seal a payload and describe what it rests on.
Parameters¶
payload : mapping
The evidence payload. Any receipt already present is excluded from the
seal, so re-sealing an exported payload reproduces the same receipt.
lane : str
Controlled evidence class.
status : str
Terminal status of the producing action.
binding : str
produced or exported; see :data:EvidenceBinding.
scope : mapping of str to str
Identity fields the subject was produced under.
depends_on : sequence of EvidenceDependency
Inputs this evidence rests on.
produced_at_utc : str
Second-precision UTC timestamp, Z-suffixed.
Returns¶
EvidenceReceipt The receipt for this payload.
Raises¶
EvidenceReceiptError If the lane, status or timestamp is not valid. EvidenceSealError If the payload cannot be sealed identically in both runtimes.
Function attach_evidence_receipt(payload)¶
Return the payload with its receipt embedded.
Parameters¶
payload : mapping
The evidence payload.
lane : str
Controlled evidence class.
status : str
Terminal status of the producing action.
binding : str
produced or exported; see :data:EvidenceBinding.
scope : mapping of str to str
Identity fields the subject was produced under.
depends_on : sequence of EvidenceDependency
Inputs this evidence rests on.
now : datetime, optional
Production time; the current UTC time when omitted.
Returns¶
dict
A new payload carrying :data:EVIDENCE_RECEIPT_KEY.
Function read_evidence_receipt(payload)¶
Return the receipt embedded in a payload, or None when absent.
Parameters¶
payload : mapping A payload that may carry a receipt.
Returns¶
EvidenceReceipt or None
The parsed receipt, or None for a payload written before receipts
existed.
Raises¶
EvidenceReceiptError If a receipt is present but malformed. A receipt that cannot be read is never treated as an absent one.
Function utc_timestamp(now)¶
Return a second-precision Z-suffixed UTC timestamp.
Parameters¶
now : datetime, optional Moment to render; the current UTC time when omitted.
Returns¶
str
For example 2026-09-06T11:22:33Z.
Function validate_lane(value)¶
Return a controlled evidence class or refuse the receipt.
Parameters¶
value : object Candidate lane read from a receipt.
Returns¶
StudioEvidenceClassification The validated evidence class.
Raises¶
EvidenceReceiptError If the value is not a Studio evidence class.
Function validate_status(value)¶
Return a controlled terminal status or refuse the receipt.
Parameters¶
value : object Candidate status read from a receipt.
Returns¶
StudioEvidenceStatus The validated terminal status.
Raises¶
EvidenceReceiptError If the value is not a terminal evidence status.
Function validate_binding(value)¶
Return a controlled receipt binding or refuse the receipt.
Parameters¶
value : object Candidate binding read from a receipt.
Returns¶
EvidenceBinding
produced or exported.
Raises¶
EvidenceReceiptError If the value names neither.
Function parse_timestamp(value)¶
Return the moment a Z-suffixed UTC timestamp names.
Parameters¶
value : str Timestamp text from a receipt.
Returns¶
datetime The parsed, timezone-aware moment.
Raises¶
EvidenceReceiptError If the text is not a UTC ISO-8601 timestamp.
Function is_sha256_hex(value)¶
Return whether value is a lowercase 64-character SHA-256 digest.
Module studio.evidence_scope¶
Function simulation_scope(payload)¶
Return the identity a simulation result was produced under.
Parameters¶
payload : mapping
A Studio simulation result carrying an experiment block.
Returns¶
dict of str to str Experiment digest, model identity and numerical profile, omitting any field the payload does not record.
Function analysis_scope(payload, request_payload)¶
Return the identity an analysis result was produced under.
Parameters¶
payload : mapping
The analysis result, carrying analysis_metadata.
request_payload : mapping
The request the analysis ran, which names the model when there is one.
Returns¶
dict of str to str Analysis type, input digest and model class where the request named one.
Function action_scope()¶
Return the identity of one worker-backed Studio action.
Parameters¶
job_id : str
Job that executed the action; what dependent evidence resolves against.
action_kind : str
Stable action identifier, such as studio.compile.
Returns¶
dict of str to str The job and action identity.
Function weight_restore_scope(payload)¶
Return the identity of a materialised training checkpoint.
The architecture and the weight digest live in the materialisation block, and they are what an attach has to agree with: attaching a checkpoint to a network of a different shape is the wrong-model case for this lane.
Function weight_restore_dependencies(payload)¶
Return the training job a materialised checkpoint rests on.
Function weight_restore_attach_scope(payload)¶
Return the identity of a checkpoint attached to a new training run.
Function weight_restore_attach_dependencies(payload)¶
Return the materialised checkpoint an attach rests on.
Function default_flow_run_scope(payload)¶
Return the identity of one guided default-flow run.
Function default_flow_attestation_scope(payload)¶
Return the identity of one guided default-flow attestation.
Function default_flow_attestation_dependencies(payload)¶
Return the guided-flow run an attestation rests on.
Function model_scan_scope(payload)¶
Return the identity of one catalogue scan.
Function project_scope(payload)¶
Return the identity of one saved project workspace.
Module studio.evidence_seal¶
Class EvidenceSealError¶
Raised when a value cannot be sealed identically in both runtimes.
Function seal_sha256(value)¶
Return the SHA-256 digest of the canonical form of value.
Parameters¶
value : object
Any JSON-shaped value: None, bool, int, float, str,
a mapping with string keys, or a sequence of the same.
Returns¶
str Lowercase 64-character hexadecimal digest.
Raises¶
EvidenceSealError If the value contains anything that would not survive a JSON round trip through the browser unchanged.
Function canonical_seal_text(value)¶
Return the canonical JSON text used as the seal input.
Parameters¶
value : object The value to encode.
Returns¶
str Canonical JSON: object keys in code-point order, no insignificant whitespace, numbers in the shared normal form, minimal string escapes.
Raises¶
EvidenceSealError If the value is not JSON-shaped, carries a non-finite float, an integer no double holds exactly, or an unpaired surrogate.
Module studio.experiment_spec¶
Class ExperimentRejected¶
Raised when a request cannot become one effective experiment.
Parameters¶
field : str
Request field that failed.
reason : str
Deliberately authored reason; never generated exception text.
execution_mode : {"refused", "job_required"}
job_required when the run is valid but too large for the
synchronous route and must be submitted as a job.
- init()
- to_public_detail()
- Return the path-free public error detail.
Class ExperimentSpec¶
The resolved, digest-bound specification of one Studio run.
public is the path-free specification (with experiment_sha256);
run_kwargs is the executable material for the run entrypoint and is
never returned to a client; cacheable is False for a fresh
stochastic trial.
- init(source, public, run_kwargs, cacheable, n_steps, dt, duration_ms)
- Snapshot inputs without retaining mutable aliases to callers or exports.
- public()
- Return an independent JSON projection of the sealed specification.
- run_kwargs()
- Return independent execution inputs; mutations cannot alter this run.
- experiment_sha256()
- Digest of the public specification: the cache key of the run.
- to_public_dict()
- Return the path-free experiment specification.
Function resolve_model_experiment(request)¶
Resolve a catalogue-model request into its effective experiment.
Parameters¶
request : mapping
Validated request fields: name, params, dt, duration,
current, protocol, frequency_hz, seed, trial.
max_steps : int
Largest step count this caller executes; a larger run is rejected
with execution_mode = job_required.
Raises¶
ModelInputError From the run contract (unknown model, parameter, unsupported step). ExperimentRejected Seed on a deterministic model, seed given twice, no complete step or an oversized run.
Function resolve_ode_experiment(request)¶
Resolve an equation-playground request into its effective experiment.
Raises¶
ExperimentRejected Unparsable equation, initial value for an undeclared variable, seed on noise-free equations, no complete step or an oversized run.
Function resolve_experiment(request)¶
Resolve a model or equation request into its effective experiment.
Function run_experiment(spec)¶
Execute a resolved experiment and attach its specification to the result.
Raises¶
ModelInputError, ModelSimulationFailure, ValueError From the run entrypoints.
Module studio.firing_pattern¶
Function classify_firing_pattern(spikes, n_steps, dt)¶
Classify the firing pattern of a spike train.
Parameters¶
spikes : list of int
Step indices at which the run spiked, in ascending order.
n_steps : int
Number of steps the run executed; with dt it gives the duration
the rate is computed over.
dt : float
Time step in milliseconds.
Returns¶
dict
pattern (silent, single_spike, bursting, adapting,
tonic, irregular or chaotic) and a human description.
Every pattern except silent also carries rate_hz; every pattern
with at least three spikes carries isi_cv; a burst additionally
carries burst_isi_ms and inter_burst_ms.
Module studio.model_capabilities¶
Function model_capabilities(name)¶
Return what each silicon operation can do for name here, or None.
Parameters¶
name:
A registered catalogue model.
tool_status:
An EDA tool snapshot as :func:~sc_neurocore.studio.synthesis.check_tools
returns; taken now when omitted.
formal_inventory:
The catalogue's formal-job inventory.
Returns¶
dict or None
None for a name the catalogue does not hold.
Module studio.model_catalogue¶
Class ModelMetadataError¶
Raised when Studio model metadata loading fails for a known model.
Class ModelDocumentationUnavailable¶
Raised when no reference-page directory is installed at all.
Distinct from a model simply having no page: the first is a packaging state that applies to every model, the second is a fact about one. Reporting the first as the second blames the model for the distribution.
Function readiness_seal_payload()¶
Return the verified-readiness seal of every registered catalogue model.
Function corpus_revision(models)¶
Return a digest identifying the catalogue corpus and its health.
Two clients holding the same revision hold the same identities in the same metadata states. The digest changes when a model is added or removed and when any entry's metadata state changes, so a client can tell a healthy corpus from a degraded one of the same size.
Parameters¶
models : list of dict
Catalogue entries as :func:list_models returns them.
Returns¶
str A 16-character hexadecimal digest.
Function list_models()¶
Return declared metadata for every registered neuron model.
Each entry is built from the model's committed descriptor (family, category,
maturity, provenance, parameter and state counts). Models without a descriptor
fall back to code introspection with an inferred category and
metadata_state "unavailable".
Every registered model is returned. A model whose metadata cannot be read
is reported with metadata_state "invalid" and a metadata_error,
never dropped: an omitted row shows a smaller success count instead of a
fault, and silently narrows every consumer that derives its scope from this
list — the runtime-state conformance matrix among them.
Results are cached after the first call. Concurrent first calls build the list once; the others wait for that build and return the same list.
Returns¶
list of dict One entry per registered model, sorted by identity.
Function get_model_detail(name)¶
Return the full declared metadata view for a single model.
Function model_facets()¶
Return the catalogue facet taxonomy, counts, and corpus health.
Returns¶
dict
total registered identities, a corpus_revision digest, a
metadata_states census, the invalid_models by name, and the
family, maturity, behaviour and tier facets.
Function documentation_root()¶
Return the directory holding the per-model reference pages, or None.
Returns¶
pathlib.Path or None
The packaged directory when the distribution carries one, otherwise the
checkout's docs/api/models when running from a working tree, and
None when neither is present.
Function model_documentation(name)¶
Return the rendered reference documentation for a model, or None.
The per-model reference page lives at docs/api/models/<module>.md in a
checkout and at sc_neurocore/studio/model_docs/<module>.md in a
distribution that packages them. The Studio serves the Markdown so the
documentation is browsable next to the live model.
Returns¶
dict or None
The page, or None when this model has none.
Raises¶
ModelDocumentationUnavailable When no reference-page directory is installed. Every model is then undocumented for the same reason, which is a fact about the distribution and not about any model.
Module studio.model_compile_configuration¶
Class ResolvedModelCompileConfiguration¶
Validated schema, compiler options and instantiated universal neuron.
- to_public_dict()
- Return the path-free configuration attached to Studio evidence.
- to_verilog()
- Compile the resolved neuron with the exact selected fixed-point geometry.
Function resolve_model_compile_configuration(payload)¶
Validate a model-mode compiler payload and instantiate its canonical schema.
The Q-format must be one Studio compiles at, and the neuron, with the requested parameter overrides, step and integrator, must be representable in it: a value the format would wrap, or a non-zero parameter, constant, initial state or step it would round to zero, refuses the compile rather than producing RTL for a different neuron.
Module studio.model_cosim¶
Class StimulusPhase¶
One stretch of a co-simulation schedule.
word is held on the input for steps cycles, after a reset of the
neuron to its initial state when reset_before is set.
- to_public_dict()
- Return the JSON projection.
Class ModelCosimExecution¶
Public parity report plus complete private artifacts for job custody.
Class PhaseSimulation¶
What one RTL and generated-kernel run printed, and the sources it ran.
Function stress_schedule(current_q, data_width)¶
Return the fixed stress schedule run after the requested one.
It holds the most negative and then the most positive input word, so the accumulate commit saturates in both directions; resets the neuron mid-run; replays the requested input from the initial state; and ends at zero input. Every phase starts after the requested run, from a reset neuron.
Function run_model_cosim(configuration)¶
Compile and compare real C-reference and RTL state traces cycle by cycle.
The requested constant current runs for n_steps cycles, then the
:func:stress_schedule runs in the same simulation; bit_exact holds
only when both traces agree. current must lie inside the Q-format's
range, since an input word outside it would wrap.
Function simulate_phases(neuron, rtl_source, module_name, phases)¶
Run rtl_source under Icarus and the generated C kernel through phases.
rtl_source must be the RTL of neuron compiled at the same word,
overflow and rounding the kernel is generated with. Each prints one row per
step: the spike and every state word.
Raises¶
ValueError
No bit-true kernel mirrors neuron at this configuration.
RuntimeError
A tool is unavailable or a command fails.
Module studio.model_numeric_contracts¶
Function studio_numeric_contracts(neuron)¶
Return the hardware numeric contract of neuron at every candidate format.
Parameters¶
neuron: The instantiated schema neuron Studio would compile.
Returns¶
dict
Contract per :data:STUDIO_Q_FORMATS label, in that order.
Function bit_true_mirrored(schema_name, integrator, q_format)¶
Return whether a generated bit-true C kernel mirrors the schema's RTL.
The co-simulation compares the RTL with that kernel, so an integrator is offered for it only when the kernel exists for the neuron as compiled with that integrator.
Module studio.model_run_contract¶
Class ModelInputError¶
Raised when a Studio model-run request is rejected before any simulation step.
Parameters¶
model : str or None
Catalogue identity the request named, or None when the name itself
was not a string.
field : str
Dotted request field that failed (name, params.tau_m, dt,
constructor, step, protocol, current, duration).
reason : str
Deliberately authored reason; never generated exception text.
- init()
- to_public_detail()
- Return the path-free public error detail.
Class ModelSimulationFailure¶
Raised when a validated model run fails numerically at a specific step.
Parameters¶
model : str Catalogue identity of the failed run. backend : {"python", "rust"} Backend that executed the failing step. step : int Zero-based step index at which the failure was detected. time_ms : float Simulated time of that step in milliseconds. diagnostic : str Deliberately authored failure reason, optionally naming a state variable. Original faults remain in the exception cause.
- init()
- to_public_detail()
- Return the path-free public error detail.
Class ParameterContract¶
One numerically overridable constructor field of a model class.
Attributes¶
name : str
Constructor keyword.
kind : {"float", "int"}
Numeric kind the model declares; int fields reject fractional values.
default : float or int or None
Declared default, or None when the field defaults to None.
Class ModelParameterContracts¶
Overridable numeric fields and the reasons other fields are not inputs.
Class DriveContract¶
How the Studio current protocol is delivered to step.
Attributes¶
parameter : str
Name of the first step parameter after self.
kind : {"float", "int"}
Declared type of that parameter; int models require integral samples.
positional_only : bool
Whether the parameter must be passed positionally.
Class ModelRunInputs¶
Validated effective inputs of one model run before any step executes.
- effective_parameters()
- Return every overridable field with the value the run will use.
- instantiate()
- Construct the model with the validated keywords; never retry or substitute.
Class DriveTrace¶
Validated current-injection protocol resolved against the run inputs.
Function bounded_diagnostic(exc)¶
Return a bounded exception description for local diagnosis only.
This text includes interpreter and library messages and must not be used in a caller-facing refusal or response.
Function model_parameter_contracts(cls)¶
Inventory the numerically overridable constructor fields of cls.
Parameters¶
cls : type Catalogue model class (dataclass or plain class with keyword defaults).
Returns¶
ModelParameterContracts
Overridable fields keyed by name plus the reason each other constructor
field is not an input (private state, derived init=False field,
factory-initialised field, non-numeric type).
Function model_drive_contract(model, cls)¶
Derive how the current protocol enters cls.step; reject unsatisfiable steps.
Raises¶
ModelInputError
When step takes no drive input or requires further inputs without
defaults that the Studio current protocol cannot supply.
Function declared_macro_step(name)¶
Return the sub-step and macro step of a model that steps in macro steps.
A model profile states how long one public step() lasts
(numerical.macro_step). For most models that is dt. A few
conductance models (Hodgkin-Huxley, Connor-Stevens, Wang-Buzsaki) run a
fixed macro step of substeps sub-steps of dt per call, and the
Studio used to time every call as dt: their time axis was short by
the factor substeps and every rate long by it (Hodgkin-Huxley at
10 µA/cm² reported 6330 Hz instead of 63 Hz).
Parameters¶
name : str Catalogue class name.
Returns¶
tuple of (float, float) or None
(sub-step dt, macro step) in ms when the profile declares a
time-subdividing macro step longer than dt; None when a call
lasts dt or the model has no executable profile.
Function macro_step_refusal(name)¶
Say why a macro-stepping model cannot join a network, or None.
A network advances every population once per dt; a model whose
step() is a longer macro step would run a slower clock than its
neighbours, and every projection between them would be mistimed.
Parameters¶
name : str Catalogue class name.
Returns¶
str or None
The reason, or None when one call of the model lasts one dt.
Function resolve_model_run_inputs(name, param_overrides, dt)¶
Validate a model-run request against the model's own constructor contract.
Parameters¶
name : object
Catalogue identity; must be a registered class name.
param_overrides : Mapping[str, object] or None
Constructor overrides. Every key must be an overridable numeric field;
every value a finite number of the declared kind.
dt : object
Explicit timestep in milliseconds, or None for the model default.
A model whose step is a fixed class attribute accepts only that value;
a model without any timestep accepts only the Studio default.
Returns¶
ModelRunInputs Effective inputs ready for construction. No model is constructed here.
Raises¶
ModelInputError On any unknown, mistyped, non-finite, fractional-integer or unsupported input, naming the field and reason.
Function resolve_drive_trace(inputs)¶
Validate the injection protocol and build the sample trace for the run.
Raises¶
ModelInputError
On an unsupported protocol, non-finite current, non-positive duration or
frequency, a duration shorter than one step, or fractional samples for
a model whose step declares an integer drive.
Function run_receipt(inputs, trace)¶
Return the effective-input receipt attached to a successful run payload.
Parameters¶
inputs, trace : ModelRunInputs, DriveTrace
The resolved run.
backend : {"python", "rust"}
Backend that executed the steps.
recorded_state : tuple of str
Declared variables recorded at every step.
excluded_state : tuple of (name, reason)
Declared variables not recorded per step and why.
display_points : int
Number of points in the display projection (the raw result keeps every
step; see raw and display on the payload).
Module studio.model_scan¶
Class ModelScanEntry¶
Path-free firing-pattern classification for one Studio model.
A model that could not be driven by the scan's constant current carries the
error pattern and a non-empty error_type so the failure is visible in
the result rather than aborting the whole scan.
- is_error()
- True when this entry records a simulation failure.
- to_public_dict()
- Return a JSON-compatible model scan entry.
Class StudioModelScanManifest¶
Path-free metadata for one complete Studio model scan.
Parameters¶
current: Constant input current used for each model simulation. duration: Simulation duration used for each model scan run. model_count: Number of successfully classified models in the result. pattern_counts: Count of each detected firing-pattern label. input_sha256: SHA-256 digest of the scan configuration. result_sha256: SHA-256 digest of the returned model classifications. evidence_classification: Controlled evidence class for the scan workflow. status: Controlled terminal status for the scan workflow.
- to_public_dict()
- Return the JSON-compatible model scan metadata.
Function scan_all_models(current, duration)¶
Simulate every model at a given current and classify its firing pattern.
Results are cached per (current, duration) pair so a scan for one
configuration cannot be served as evidence for another configuration.
Parameters¶
current, duration : float
The constant operating point every model is driven at.
should_stop : callable, optional
Consulted before each model. A scan that is asked to stop raises
:class:~sc_neurocore.studio.platform.jobs_models.StudioJobCancelled
and caches nothing: a partial sweep is not a scan of the catalogue, and
serving one as if it were would understate the catalogue silently.
Raises¶
StudioJobCancelled
should_stop returned True before the sweep finished.
Module studio.model_simulate¶
Class RustStudioBackendUnavailable¶
Raised when the Studio Rust batch-simulation path is unavailable.
Class RustStudioBackendError¶
Raised when the Studio Rust batch-simulation path fails at runtime.
Function simulate_model(name, param_overrides, dt, duration, current, protocol, frequency_hz, use_fast_path, max_steps, bias)¶
Simulate a named catalogue model under a fail-closed input contract.
Parameters¶
name : str
Registered catalogue class name.
param_overrides : dict[str, float] or None
Constructor overrides; every key must be an overridable numeric field of
the model and every value a finite number of the declared kind.
dt : float or None
Timestep in milliseconds. None uses the model default. A model whose
step is a fixed class attribute accepts only that value; a model without
any timestep accepts only the Studio default of 0.1 ms.
duration : float
Requested run length in milliseconds; capped at max_steps steps and
reported as steps_truncated in the receipt.
current : float
Protocol amplitude; must be finite. Integer-drive models additionally
require every sample of the protocol to be integral.
protocol : {"constant", "step", "ramp", "pulse", "sine"}
Current-injection protocol.
frequency_hz : float
Sine frequency; must be positive and finite.
bias : float
Level a sine oscillates about; must be finite, and zero for any
other protocol.
use_fast_path : bool
Allow the Rust batch backend when no override or explicit dt is
given. That lane transports one scalar trace, the soma voltage, and no
initial snapshot (sc-neurocore.runtime-state-packet.v1). It records
that trace only under a name the model declares: a model whose declared
state contains no v records no state at all, and its
state_layout says so. Callers that need complete-state custody pass
False.
max_steps : int
Step cap of this caller (MAX_STEPS for synchronous routes; a job
may pass more). A longer request is truncated and declared as
steps_truncated; the experiment contract refuses it before
reaching this point.
Returns¶
dict[str, Any]
The display projection (time, states, current_trace),
spike indices and statistics, the observation clock, the
state_layout with its custody verdict, exact initial_state and
final_state snapshots, the full-resolution raw block, the
display sample-index map and an effective_inputs receipt.
Raises¶
ModelInputError
When any input is unknown, mistyped, non-finite, fractional for an
integer field, unsupported for the model, or when the model cannot be
constructed or driven under the request.
ModelSimulationFailure
When a step raises or a recorded variable is non-finite or changes
kind or shape; the failure names the backend, the step index and the
simulated time at which that step started (step * dt).
RustStudioBackendError
When an available Rust backend fails for a reason other than an
unsupported model.
Module studio.network¶
Function simulate_ei_network(n_exc, n_inh, w_ee, w_ei, w_ie, w_ii, p_conn, ext_rate, duration, dt)¶
Simulate a balanced E-I network. Uses Rust engine when available.
Module studio.network_execution¶
Class GraphExecutionFailure¶
Raised when a lowered graph fails while running.
Parameters¶
reason : str Deliberately authored failure reason, optionally naming the population whose state is non-finite.
- init()
- to_public_detail()
- Return the path-free public error detail.
Class LoweredProjection¶
One public projection with its CSR arrays and the autapses removed.
- csr_sha256()
- Digest of the CSR arrays (indptr, indices, data) as int64/int64/float64 bytes.
Class LoweredGraph¶
The public objects of one resolved graph, ready for Network.run.
- network_dt_s()
- Timestep handed to
Network.run(seconds; scales stimuli only). - n_synapses()
- Total synapses across every projection.
Function csr_digest(indptr, indices, data)¶
Return the SHA-256 of the CSR arrays in their canonical dtypes.
Function connectivity_arrays(spec, n_source, n_target)¶
Return the CSR arrays of spec and the number of autapses removed.
random uses the public Erdős–Rényi generator with the projection seed;
all_to_all the public full generator. On a self-projection without
autapses the diagonal entries are removed; nothing else is added or
dropped.
Function lower_graph(spec)¶
Build the public network objects of spec without running them.
Function run_lowered_graph(lowered)¶
Run the reference Python loop; report a raising step or non-finite state.
Raises¶
GraphExecutionFailure When a neuron step raises or a population ends with a non-finite membrane voltage.
Function graph_result(lowered)¶
Assemble the public result of a run graph.
Function simulate_graph_spec(spec)¶
Lower, run and report one resolved graph.
Raises¶
GraphExecutionFailure
From :func:run_lowered_graph.
Module studio.network_graph¶
Class ModelDiscoveryError¶
Raised when Studio model discovery cannot produce a trustworthy list.
Class GraphEnvelopeRefusal¶
A deliberately authored refusal of a Studio graph envelope.
The message describes an envelope rule. Interpreter and library errors are not converted into this type with their original diagnostic text.
Function population_model_admission(name)¶
Return why catalogue model name cannot form a population, or None.
A population is admissible when the model has a float drive step that
the Studio protocol can satisfy and no seed constructor field (every
neuron of a population would otherwise share the seed and its noise).
Function population_model_contract(name)¶
Return the contract a population of model name is validated against.
The canvas creates a population with a model's defaults and then has to let
a user change them. It cannot do that honestly from a list of names: which
constructor fields are numerically overridable, what kind each is, what it
defaults to and why the others are not inputs are all decided by
:mod:sc_neurocore.studio.model_run_contract, and a browser that guessed
would be a second implementation of the contract, free to drift.
Parameters¶
name : str Catalogue model name.
Returns¶
dict or None
None when the model is not admissible for a population; otherwise
schema_version, model, the parameters a population may
override with their kind and default, the unsupported fields with
the reason each is not an input, and the drive parameter the
Studio protocol delivers the current through.
Function available_models()¶
Return the names of the catalogue models admissible for populations.
Raises¶
ModelDiscoveryError When the catalogue yields no admissible model.
Function create_population(label, model, count, neuron_type, x, y, params, drive)¶
Create a population node for the network canvas.
The node carries the fields the graph schema executes: catalogue model,
count, neuron_type, constructor params and the external
drive ({"kind": "none"} when omitted). Nothing is validated here;
:func:validate_graph reports every problem of the assembled graph.
Function create_projection(source_id, target_id, weight, delay, probability, rule)¶
Create a projection edge between two populations.
weight is signed (negative for an inhibitory source), delay is in
milliseconds and must be a whole number of graph timesteps, rule is
random (with probability) or all_to_all.
Function simulate_graph(graph)¶
Simulate a network graph through the public Network runtime.
Returns {"success": False, "errors": [...]} with every validation
message when the graph cannot be resolved, otherwise the
studio.network-graph-result.v1 payload of
:func:sc_neurocore.studio.network_execution.simulate_graph_spec.
Raises¶
GraphExecutionFailure When a resolved graph fails while running.
Function graph_to_envelope(graph)¶
Export a validated network graph as the Studio graph envelope (JSON).
Raises¶
GraphEnvelopeRefusal When the graph does not validate.
Function envelope_to_graph(nir_data)¶
Import a Studio graph envelope (JSON), current or legacy, to a network graph.
Every node type must be a catalogue model name, and an unknown type is
rejected rather than replaced by a default. Real NIR files are read by
:func:sc_neurocore.studio.network_nir.nir_file_to_graph.
A version-2 document carries the population label and each projection's connectivity rule with its probability, seed and autapse decision, so a round trip returns the network that was exported. A version-1 document carried none of those: its edges connect all-to-all, which is what it has always meant, and its populations are named by their identifiers.
The assembled graph is validated against the graph schema with the Studio default timestep, so an import that would not execute (sign conflicts, delays that are not whole default steps, inadmissible models, budgets) is rejected here instead of surfacing later on the canvas.
Raises¶
GraphEnvelopeRefusal On a malformed payload, a node type that is not a catalogue model, or an assembled graph that does not validate.
Module studio.network_graph_spec¶
Class GraphRejected¶
An authored refusal of a graph that cannot form an executable specification.
Graph validation replaces inherited model-constructor diagnostics with fixed reasons before constructing this exception.
Parameters¶
field : str
Dotted request field that failed (populations[1].count,
projections[0].delay, dt, …).
reason : str
Bounded, path-free reason.
- init()
- to_public_detail()
- Return the path-free public error detail.
Class GraphIssue¶
One validation failure: the request field and the human-readable message.
Class DriveSpec¶
External input of one population, lowered to a public stimulus object.
constant injects current into every neuron at every step
(StepCurrent over the whole run); poisson injects weight into a
neuron whenever its independent Poisson process at rate_hz fires
(PoissonInput); none injects nothing.
- to_public_dict()
- Return the path-free drive block.
Class PopulationSpec¶
One resolved population: catalogue model, validated constructor inputs, drive.
- to_public_dict()
- Return the path-free population block (effective parameters included).
Class ProjectionSpec¶
One resolved projection: rule, signed weight, exact delay steps, seed.
- to_public_dict()
- Return the path-free projection block.
Class GraphSpec¶
The resolved, digest-bound specification of one graph run.
- neuron_steps()
- Total neuron updates the run performs (
n_neurons * n_steps). - population(population_id)
- Return the population with
population_id. - to_public_dict()
- Return the path-free specification with its
graph_sha256digest.
Function derived_seed(graph_seed, kind, index)¶
Return the deterministic 32-bit seed of element index of kind.
The seed is spawned from numpy.random.SeedSequence(graph_seed,
spawn_key=(kind, index)) so projections and drives draw from independent
streams that a direct public-runtime script can reproduce from the graph
seed alone.
Function graph_issues(graph)¶
Return every validation issue of graph in request order (empty = valid).
Function validate_graph(graph)¶
Validate a network graph and return its error messages (empty = valid).
Structural errors (shapes, ids, endpoints), model-contract errors (unknown model or parameter, timestep the model cannot take, inadmissible drive or randomness), projection errors (sign against the source type, rule and probability conflicts, delays that are not whole timesteps, seeds, autapses) and budget errors (neuron cap, step cap, neuron-step cap) are all reported together.
Function resolve_graph(graph)¶
Resolve graph into its executable specification.
Raises¶
GraphRejected With the field and message of the first validation issue.
Module studio.network_hardware¶
Class HardwareLoweringRefused¶
The graph holds something the hardware lowering cannot reproduce exactly.
- init(reasons)
Class LoweredNetwork¶
A Studio network as the hardware compiler's graph, with its drive lanes.
- input_sha256()
- Return the digest every later artefact of this lowering is bound to.
Function lower_graph(graph)¶
Lower a Studio network graph to the hardware compiler's graph.
Raises¶
GraphRejected When the graph does not validate. HardwareLoweringRefused When any population, drive or projection cannot be reproduced exactly; the exception lists every reason.
Function lowering_public_dict(lowered)¶
Return the JSON projection of a lowering: what was compiled, and what it rounds.
Module studio.network_hardware_cosim¶
Class HardwareCosimUnavailable¶
The simulation tools the co-simulation needs are not installed.
Class NetworkCosim¶
The three rasters of one network, and the digests that bind them.
- rtl_matches_model()
- Whether the RTL and its bit-true model spike identically on every step.
- studio_first_divergence()
- The first step where the RTL and the Studio's run differ, if any.
- to_public_dict()
- Return the JSON receipt of this co-simulation.
Function compile_lowered(lowered)¶
Compile a lowered network with the direct interconnect the model reproduces.
Function cosimulate(lowered, graph, workdir)¶
Run the compiled RTL, its bit-true model and the Studio for the same steps.
Parameters¶
lowered:
The lowering of graph.
graph:
The Studio graph the lowering came from; the Studio's run uses it.
workdir:
An empty directory the sources, executables and outputs are written to.
steps:
Steps to run; the graph's own step count when omitted.
compiled:
The lowering already compiled by :func:compile_lowered; compiled here
when omitted.
Raises¶
HardwareCosimUnavailable When Icarus Verilog or a C compiler is not installed.
Function synthesis_source(compiled)¶
Return the design to synthesise: the top module and the neurons it instantiates.
The weight ROM and the stochastic-source modules are not instantiated by the direct top module; leaving them out keeps the synthesis tool from choosing one of them as the top.
Module studio.network_nir¶
Class NIRMappingRefused¶
A deliberately authored refusal of an unrepresentable graph or NIR file.
Generated parser and library diagnostics remain in the exception cause; only the authored message may be returned to a caller.
Class NIRExport¶
One written NIR file and what the writing could not carry exactly.
- to_public_dict()
- Return the JSON projection the Studio API serves.
Function graph_to_nir_file(graph)¶
Export a Studio network graph as a real NIR (HDF5) file.
Raises¶
GraphRejected When the graph does not validate. NIRMappingRefused When a population's model is not an NIR primitive.
Function nir_file_to_graph(content_base64)¶
Read an NIR file (base64 of its bytes) into a Studio network graph.
Returns¶
dict
graph (the Studio graph), origin (studio or foreign)
and notes (what the reading assumed).
Raises¶
NIRMappingRefused When the file is not NIR, holds a node the graph cannot represent, or its tensors do not match the Studio network its metadata describes. Malformed file fields receive authored fixed sentences; generated parser and library diagnostics remain only in the exception cause.
Function dense_weight(projection, n_source, n_target)¶
Return the realised connectivity as a dense [target, source] matrix.
Module studio.network_notebook¶
Function spike_events_sha256(result)¶
Digest every spike event of a graph result, in network-wide neuron indices.
Parameters¶
result:
A studio.network-graph-result.v1 payload.
Returns¶
str SHA-256 over the int64 bytes of the event steps, then the event neurons, sorted by step and then neuron.
Function network_notebook(spec)¶
Run a resolved graph and return a tutorial notebook that rebuilds it.
Parameters¶
spec:
A graph resolved by :func:~sc_neurocore.studio.network_graph_spec.resolve_graph.
Returns¶
dict An nbformat 4 notebook. Its metadata carries the graph digest and the sealed spike and connectivity digests of the Studio run.
Raises¶
GraphExecutionFailure When the graph fails while running.
Module studio.nir_compile¶
Function compile_nir_graph(graph)¶
Lower a parsed NIR graph to synthesisable Verilog and return the artefacts.
The result carries interchange_notes: what importing the graph assumed
(the timestep, the reset rule, recurrent delays) or approximated.
Function compile_nir_file_bytes(data)¶
Compile a standard .nir (HDF5) document supplied as raw bytes.
Options are forwarded to :func:compile_nir_graph. The result also
records nir_version, the NIR version the document stores (None
when it stores none).
Module studio.nullclines¶
Function nullclines_2d(equations, params, var_names, ranges, grid_size)¶
Compute both nullclines of a two-variable section of the drift field.
Parameters¶
equations:
Equation strings of the system (dx/dt = f(x, …) or map updates).
params:
Parameter values.
var_names:
The two swept variables (x, y); both must be equation variables.
ranges:
Inclusive (low, high) range per swept variable; a missing range
falls back to :data:DEFAULT_RANGES.
grid_size:
Samples per axis.
current:
Input current I the field is evaluated at (held constant).
held:
Values at which every other equation variable is held; an
unlisted variable is held at its equation-builder default (0).
Returns¶
dict
var_names, nullcline_0 / nullcline_1 (contour cell
corners and the contour cell count), the grid axes, one validity
mask per component (1 valid, 0 invalid; rows follow y,
columns x), the held variables and input, and the
:class:~sc_neurocore.studio.analysis_contract.MetricContract.
Raises¶
ModelInputError When fewer than two variables are given, a swept variable is not an equation variable, a held name is not an equation variable, a range is degenerate, or an expression references an unknown symbol.
Module studio.platform.action_evidence¶
Class StudioActionEvidence¶
Path-free manifest describing one Studio worker-backed action.
- to_public_dict()
- Return the path-free evidence payload.
Function write_studio_action_evidence_manifest(context)¶
Write a normalised evidence manifest for a worker-backed action.
Parameters¶
context:
Job sandbox used to write the path-confined evidence artifact.
action_kind:
Stable Studio action identifier, such as studio.compile.
result:
Portable JSON result payload whose canonical SHA-256 digest is recorded.
result_artifact:
Manifest entry for the result artifact produced by the same job.
evidence_artifact_path:
Relative path for the evidence manifest artifact.
evidence_classification:
Controlled evidence class used by bundle and operator views.
replay_route:
HTTP method and route template used to reproduce the action.
status:
Terminal action status.
request_id:
Optional request correlation identifier.
principal_id:
Optional authenticated principal identifier.
error_message:
Optional bounded terminal error message.
Returns¶
StudioActionEvidence Path-free evidence payload plus its artifact manifest entry.
Raises¶
ValueError
If any controlled field is invalid or result is not portable JSON.
Module studio.platform.analysis_limits¶
Class AnalysisBudgetError¶
Raised when a synchronous analysis request exceeds its execution budget.
Parameters¶
limit: Which budget dimension was violated. projected: Projected value for the violated dimension (integration steps or simulation count) computed from the request. allowed: Maximum value permitted for the violated dimension. message: Operator-facing summary that must not include local paths or secrets.
- init()
- to_public_detail()
- Return a JSON-serializable, path-free HTTP error detail payload.
Class AnalysisBudget¶
Ceilings that bound synchronous Studio analysis execution.
Parameters¶
max_steps_per_simulation:
Maximum integration steps (ceil(duration / dt)) for any single
simulation in a request.
max_total_steps:
Maximum summed integration steps across every simulation a request
drives (simulation_count * steps_per_simulation for a sweep).
max_simulations:
Maximum number of simulations a single request may drive, independent
of per-simulation cost.
- post_init()
- Validate that every budget ceiling is a positive integer.
- to_public_dict()
- Return a JSON-serializable, path-free budget payload.
Class AnalysisCost¶
Projected synchronous integration cost of an analysis request.
Parameters¶
simulation_count: Number of simulations the request drives. steps_per_simulation: Largest single-simulation integration-step count among the request's simulations. total_steps: Summed integration steps across every simulation in the request.
- to_public_dict()
- Return a JSON-serializable, path-free cost payload.
Class ModelCostFactors¶
What one model actually costs per millisecond of simulated time.
ceil(duration / dt) is not the work a model does. A model with a
substepped integrator advances several times per step, and one carrying
many state variables does several times the arithmetic per advance. A
budget that ignores both projects the same cost for a one-variable map and
a ten-variable conductance model and admits requests it should refuse.
Attributes¶
dt : float
Simulated time of one step() call, resolved from the model rather
than assumed: the timestep, or the macro step of a model that runs
substeps sub-steps per call. Taking the sub-step here counted a
Hodgkin-Huxley run's calls a hundred times over.
substeps : int
Integrator advances per step, from the model's numerical profile.
state_count : int
Declared state variables carried per advance, at least one.
- work_per_step()
- Return the arithmetic weight of one step relative to a scalar Euler step.
- to_public_dict()
- Return a JSON-serializable, path-free cost-factor payload.
Function simulation_step_count(duration, dt)¶
Return the integration-step count for one simulation.
Parameters¶
duration: Simulated time span in milliseconds. Must be finite and positive. dt: Integration timestep in milliseconds. Must be finite and positive.
Returns¶
int
ceil(duration / dt) integration steps.
Raises¶
AnalysisBudgetError
If duration or dt is non-finite or non-positive. The error uses
the "timestep" limit so callers can surface a path-free 422.
Function resolve_request_timestep(dt)¶
Return the timestep used to project a request's cost.
Parameters¶
dt:
Caller-supplied timestep in milliseconds, or None when the request
defers to the named model's default timestep.
Returns¶
float
dt when supplied, otherwise
:data:STUDIO_ANALYSIS_REFERENCE_TIMESTEP_MS. A supplied non-positive
dt is returned unchanged so the timestep gate rejects it.
Function resolve_model_cost_factors(name, dt)¶
Resolve one model's effective timestep, substeps and state count.
Falls back to the reference timestep and scalar weights when the model cannot be resolved: a budget that raises on an unknown name would turn a model-input error into a budget error and report the wrong thing.
Parameters¶
name : str
Catalogue model name.
dt : float, optional
Requested timestep, or None to take the model's own default.
Returns¶
ModelCostFactors The factors the projection should use.
Function evaluate_analysis_cost()¶
Project the cost of a request whose simulations share one duration/dt.
Parameters¶
simulation_count:
Number of simulations the request drives. Must be positive.
duration:
Shared simulated time span in milliseconds.
dt:
Shared integration timestep in milliseconds.
work_per_step:
Arithmetic weight of one step, from
:meth:ModelCostFactors.work_per_step. The default of 1 projects a
scalar single-substep model, which is what a request with no resolvable
model gets.
Returns¶
AnalysisCost
Projected per-simulation and total integration-step counts, weighted by
work_per_step.
Raises¶
AnalysisBudgetError
If simulation_count is non-positive ("simulations" limit) or the
timestep is invalid ("timestep" limit).
Function evaluate_multi_config_cost(configs)¶
Project the cost of a request whose simulations have distinct duration/dt.
Parameters¶
configs:
One (duration, dt) pair per simulation the request drives.
Returns¶
AnalysisCost
steps_per_simulation is the largest single-simulation cost and
total_steps is the summed cost across configs.
Raises¶
AnalysisBudgetError
If configs is empty ("simulations" limit) or any pair has an
invalid timestep ("timestep" limit).
Function evaluate_nullcline_grid_cost()¶
Project the synchronous point-evaluation cost of a nullcline grid.
Parameters¶
grid_size: Number of points per axis in the square nullcline grid. equation_count: Number of ODE right-hand-side expressions evaluated at each grid point.
Returns¶
AnalysisCost
Cost projection where each grid point is treated as one synchronous
unit of work and steps_per_simulation records the equation
evaluations performed at that point.
Raises¶
AnalysisBudgetError
If either count is non-positive. The "simulations" limit is used
because the grid point count is checked against the same synchronous
request fan-out ceiling as parameter sweeps.
Function evaluate_model_scan_cost()¶
Project the synchronous simulation cost of a Studio model scan.
Parameters¶
model_count:
Number of catalogue models the scan will simulate.
duration:
Shared simulated time span in milliseconds.
dt:
Timestep in milliseconds used for budget projection. Model-scan calls
currently defer to model defaults at execution time, so the route uses
:data:STUDIO_ANALYSIS_REFERENCE_TIMESTEP_MS for this projection.
Returns¶
AnalysisCost Cost projection where each catalogue model contributes one synchronous simulation.
Raises¶
AnalysisBudgetError
If model_count is non-positive ("simulations" limit) or the
timestep is invalid ("timestep" limit).
Function enforce_analysis_budget(cost, budget)¶
Reject a projected analysis cost that exceeds the configured budget.
Parameters¶
cost:
Projected request cost from :func:evaluate_analysis_cost or
:func:evaluate_multi_config_cost.
budget:
Active synchronous analysis ceilings.
Raises¶
AnalysisBudgetError If the simulation count, per-simulation steps, or total steps exceed the budget. The first violated dimension is reported, in simulations -> per-simulation -> total order.
Module studio.platform.api_process_lock¶
Class StudioApiProcessConflict¶
Another process already serves this identity store.
Class StudioApiLockUnavailable¶
The lock file beside the identity store cannot be created or opened.
Function api_lock_path(identity_path)¶
Return the file whose exclusive transaction marks the serving process.
Function hold_identity_store(identity_path)¶
Hold identity_path for this process, or refuse because another holds it.
Returns¶
pathlib.Path The lock file.
Raises¶
StudioApiProcessConflict When another process holds the store. StudioApiLockUnavailable When the lock file cannot be created or opened, for example because the identity store's directory is not writable by this account.
Module studio.platform.audit_quarantine_archive¶
Class StudioAuditQuarantineArchiveResult¶
Path-free result returned after writing a quarantine archive.
Parameters¶
archive_id: Stable archive identifier derived from the evidence job ID. manifest: JSON manifest describing the archive artifacts written by the job. summary: Path-free aggregate counts for operator review. artifact_paths: Archive-relative artifact paths written through the Studio job context.
- to_public_dict()
- Return the path-free quarantine archive result.
Class StudioAuditQuarantineArchiveValidation¶
Path-free validation result for one quarantine archive import candidate.
Parameters¶
valid: Whether the supplied archive and optional manifest satisfy the import contract. archive_id: Archive identifier when it can be read safely. summary: Recomputed path-free summary for a valid archive candidate. errors: Stable validation error codes for operator remediation. warnings: Stable validation warning codes for non-blocking operator review.
- to_public_dict()
- Return the path-free validation result.
Class StudioAuditQuarantineArchiveRetentionEntry¶
Path-free retention disposition for one quarantine archive job.
Parameters¶
archive_id: Stable archive identifier returned by the archive job. job_id: Studio job identifier that owns the archive artifacts. created_at_utc: Job creation timestamp from the job manager record. finished_at_utc: Terminal job timestamp when available. event_count: Number of quarantined audit rows captured in the archive. retained_event_count: Number of retained audit rows visible to the source quarantine export. artifact_paths: Path-free artifact identifiers declared by the archive job. disposition: Operator retention decision for this archive. summary: Archive summary copied from the validated job result.
- to_public_dict()
- Return this retention entry as a path-free JSON object.
Class StudioAuditQuarantineArchiveRetentionPlan¶
Path-free retention inventory for quarantine archive jobs.
Parameters¶
entries: Archive job entries sorted newest first. retain_latest: Number of newest archives marked for retention. skipped_record_count: Number of archive-owner job records that were incomplete or malformed.
- to_public_dict()
- Return the path-free retention plan for operator APIs.
Class StudioAuditQuarantineArchiveRestoreResult¶
Path-free result returned after materializing a restore artifact.
Parameters¶
archive_id: Validated archive identifier restored into job artifacts. manifest: JSON manifest describing the restore artifacts written by the job. summary: Path-free aggregate counts for operator review. artifact_paths: Restore-relative artifact paths written through the Studio job context.
- to_public_dict()
- Return the path-free quarantine archive restore result.
Class StudioAuditQuarantineArchivePurgeResult¶
Path-free result returned after purging archive prune candidates.
Parameters¶
purged_entries: Archive entries removed from the Studio job manager. retained_entries: Archive entries kept according to the retention policy. skipped_record_count: Number of archive-owner job records that were incomplete or malformed. retain_latest: Number of newest valid archives retained before purging older entries.
- to_public_dict()
- Return the path-free purge result for operator APIs.
Function write_studio_audit_quarantine_archive(context)¶
Write quarantined audit evidence into a confined Studio job archive.
Parameters¶
context:
Studio job context that owns the archive artifacts and enforces path
confinement, byte ceilings, and SHA-256 manifests.
quarantine_export:
Path-free payload returned by JsonlAuditSink.export_quarantine.
clock:
Optional UTC clock for deterministic tests.
Returns¶
StudioAuditQuarantineArchiveResult Path-free manifest and artifact list for the generated archive.
Raises¶
ValueError If the export payload is malformed or not the quarantine export schema.
Function validate_studio_audit_quarantine_archive(archive_payload)¶
Validate one quarantine archive before import or restore handling.
Parameters¶
archive_payload:
Candidate archive JSON object, normally loaded from
evidence/audit-quarantine/archive.json.
manifest_payload:
Optional candidate manifest JSON object, normally loaded from
evidence/audit-quarantine/manifest.json.
Returns¶
StudioAuditQuarantineArchiveValidation Path-free validation verdict with stable error codes.
Function build_studio_audit_quarantine_archive_retention_plan(records)¶
Build a non-destructive retention plan for quarantine archive jobs.
Parameters¶
records: Studio job records from the local job manager. retain_latest: Number of newest valid quarantine archives that should be retained.
Returns¶
StudioAuditQuarantineArchiveRetentionPlan Path-free inventory marking older valid archives as prune candidates.
Raises¶
ValueError
If retain_latest is not positive.
Function write_studio_audit_quarantine_restore(context)¶
Materialize validated quarantine archive rows into restore artifacts.
Parameters¶
context:
Studio job context that owns the restore artifacts and enforces path
confinement, byte ceilings, and SHA-256 manifests.
archive_payload:
Candidate archive JSON object from
evidence/audit-quarantine/archive.json.
manifest_payload:
Optional companion manifest JSON object from
evidence/audit-quarantine/manifest.json.
clock:
Optional UTC clock for deterministic tests.
Returns¶
StudioAuditQuarantineArchiveRestoreResult Path-free restore manifest and artifact list.
Raises¶
ValueError If archive validation fails before restore materialization.
Function purge_studio_audit_quarantine_archive_prune_candidates(records)¶
Purge archive jobs marked as retention prune candidates.
Parameters¶
records: Studio job records from the local job manager before deletion. purge_job: Callable that performs the path-confined job purge for one job ID. retain_latest: Number of newest valid quarantine archives to keep.
Returns¶
StudioAuditQuarantineArchivePurgeResult Path-free summary of purged and retained archive entries.
Raises¶
ValueError
If retain_latest is not positive.
Module studio.platform.auth_throttle¶
Class StudioLoginThrottleDecision¶
Decision returned before a browser login attempt is evaluated.
Parameters¶
allowed: Whether the login attempt may proceed to password verification. reason: Stable denial reason for audit rows and API responses. retry_after_seconds: Whole-second cooldown remaining when the attempt is denied.
Class StudioLoginThrottleSnapshot¶
Secret-free aggregate state for browser-login throttling.
Parameters¶
active_bucket_count:
Number of normalized login keys with live failure or lockout state.
locked_bucket_count:
Number of live buckets currently locked out.
max_retry_after_seconds:
Largest remaining retry interval across locked buckets, or 0 when
no bucket is locked.
- to_public_dict()
- Return a secret-free throttle aggregate for operator APIs.
Class StudioBrowserLoginThrottle¶
Windowed lockout guard for Studio browser-login attempts.
The guard stores only normalized login keys and failure timestamps in memory. It does not persist or inspect password material. A successful login clears the bucket for the normalized key.
- init()
- check(username)
- Return whether a browser-login attempt may proceed.
- record_failure(username)
- Record a failed browser-login attempt and return the new state.
- record_success(username)
- Clear the failure bucket after a successful browser login.
- snapshot()
- Return aggregate lockout state without exposing login keys.
Module studio.platform.backup_plan¶
Class StudioBackupPlanItem¶
One durable Studio state target that must be backed up.
Parameters¶
item_id: Stable item identifier for operator automation. target_kind: Expected filesystem object kind. description: Operator-facing state description. source_label: Path-free source label, normally an environment variable name or a documented Studio default. configured: Whether the target is configured for this runtime. exists: Whether the current target exists. required: Whether this target is required by the active deployment profile. backup_actions: Path-free actions for capturing the target. restore_actions: Path-free actions for restoring the target. local_path: Optional resolved path. This is emitted only when the operator requests local-path disclosure for an internal handoff.
- to_public_dict()
- Return a JSON-serializable item payload.
Class StudioBackupPlan¶
Machine-readable Studio backup and restore plan.
Parameters¶
deployment_profile: Active Studio deployment profile. storage_mode: Selected storage runtime. Isolated storage has no integrated authority yet. items: Durable state targets that an operator backup must capture. include_local_paths: Whether public serialization should include resolved local paths. schema_version: Stable schema identifier.
- missing_required_count()
- Return the number of required targets that are not configured.
- missing_existing_count()
- Return the number of configured targets that do not exist yet.
- ready_for_restore_drill()
- Return whether required targets and their runtime authority are ready.
- to_public_dict()
- Return a JSON-serializable backup-plan payload.
Function build_studio_backup_plan(settings)¶
Build the Studio durable-state backup and restore plan.
Parameters¶
settings: Runtime settings that define identity, audit, and job state locations. When omitted, settings are read from the current environment. include_local_paths: Include resolved local paths in the serialized plan. Keep this disabled for deployment logs that may leave the host. project_root: Optional Studio project workspace root for tests and embedded tools.
Returns¶
StudioBackupPlan Backup and restore manifest for the active Studio runtime profile.
Module studio.platform.bootstrap¶
Class StudioIdentityBootstrapResult¶
Result returned after creating a Studio service-account identity file.
Parameters¶
identity_file_path: Destination JSON identity file path. principal_id: Service-account principal written to the identity file. roles: Roles granted to the bootstrap service account. bearer_token: One-time bearer token returned to the operator. It is never written to disk by the bootstrap routine. token_sha256: SHA-256 digest persisted in the identity file. expires_at_utc: Optional UTC expiry timestamp written to the identity file. file_permissions_hardened: Whether the routine successfully applied owner-only file permissions on platforms that expose POSIX file modes. parent_directory_created: Whether the routine created the identity file parent directory.
- to_public_dict()
- Return bootstrap metadata without the bearer token.
Function bootstrap_studio_admin_identity(identity_file_path)¶
Create a local Studio admin identity file for first deployment.
Parameters¶
identity_file_path:
Destination for the JSON identity file consumed by
SC_NEUROCORE_STUDIO_IDENTITY_FILE.
principal_id:
Stable service-account principal recorded in audit rows.
roles:
Non-empty role set granted to the service account.
token_bytes:
Entropy bytes requested from token_factory. Values below
MIN_BOOTSTRAP_TOKEN_BYTES are rejected.
expires_at_utc:
Optional ISO-8601 timestamp. Values are normalised to UTC with a Z
suffix before being written.
overwrite:
Whether an existing identity file may be replaced atomically.
token_factory:
Token generator hook. Production callers use secrets.token_urlsafe;
tests may inject a deterministic generator.
Returns¶
StudioIdentityBootstrapResult Bootstrap metadata plus the one-time bearer token.
Raises¶
FileExistsError
If the destination exists and overwrite is false.
ValueError
If identity metadata is malformed.
OSError
If the destination cannot be written.
Module studio.platform.capabilities¶
Class CapabilityStatus¶
Runtime status for a Studio capability.
Class EvidenceClass¶
Evidence class attached to a Studio capability.
Class CapabilityRequirement¶
Requirement needed for a capability to be usable.
- to_public_dict()
- Return a public, non-secret representation.
Class CapabilityDescriptor¶
Static descriptor for a Studio capability.
Class CapabilityHealth¶
Runtime health projection for a Studio capability.
- to_public_dict()
- Return a public, non-secret API representation.
Class CapabilityRegistry¶
In-memory registry for Studio capabilities.
- init()
- register(descriptor)
- Register a capability descriptor.
- health(capability_id)
- Return runtime health for one capability.
- health_all()
- Return runtime health for all capabilities sorted by stable ID.
Function build_default_studio_capability_registry()¶
Build the default capability registry for the current Studio backend.
Module studio.platform.compile_process¶
Function run_compile_process_task(context, payload)¶
Compile one Studio ODE payload in an isolated process.
Parameters¶
context:
Job sandbox used to write path-confined result and evidence artifacts.
payload:
JSON object matching the public /api/compile request contract.
Returns¶
dict[str, object] Path-free compile response payload.
Raises¶
ValueError If the payload does not match the JSON-serializable compile contract.
Module studio.platform.deployment_profiles¶
Class StudioDeploymentProfilePackage¶
Machine-readable Studio deployment profile package.
Parameters¶
name:
Operator-facing deployment package name.
runtime_profile:
Studio runtime profile value exported through
SC_NEUROCORE_STUDIO_DEPLOYMENT_PROFILE.
summary:
Short profile summary for operator dashboards and release notes.
environment:
Environment variables required by this package. Values are placeholders
or concrete safe defaults and must not contain secrets.
required_operator_inputs:
Secret or path values that the operator must provide outside the
repository before launching Studio.
security_controls:
Controls that are active or required for the profile.
backup_items:
Durable state that must be included in local backup/restore plans.
preflight_command:
Command that validates the profile from the target launch environment.
launch_command:
Command used to launch the Studio process after environment setup.
schema_version:
Stable JSON schema identifier.
- to_public_dict()
- Return a JSON-serializable deployment package manifest.
- to_env_lines()
- Return sorted shell
exportlines for non-secret profile values.
Function build_studio_deployment_profile_package(name)¶
Build one Studio deployment-profile package.
Parameters¶
name:
Deployment package name. local targets single-operator loopback
use, lab targets private LAN or VPN-hosted research workstations,
and server targets reverse-proxied service deployment.
Returns¶
StudioDeploymentProfilePackage Path-placeholder manifest with environment, preflight, launch, and backup guidance.
Raises¶
ValueError
If name is not a supported Studio deployment package.
Function list_studio_deployment_profile_packages()¶
Return all supported Studio deployment-profile packages.
Module studio.platform.evidence_bundle¶
Class StudioEvidenceBundleResult¶
Path-free result returned after writing a Studio evidence bundle.
Parameters¶
bundle_id: Stable bundle identifier derived from the evidence job ID. manifest: JSON manifest describing every file written into the bundle. summary: Path-free aggregate counts for operator review and UI rendering. artifact_paths: Bundle-relative artifact paths written through the Studio job context.
- to_public_dict()
- Return the path-free evidence bundle result.
Function write_studio_evidence_bundle(context)¶
Write a path-confined Studio evidence bundle into a job context.
Parameters¶
context:
Studio job context that owns the bundle files and enforces artifact
path confinement, byte ceilings, and SHA-256 manifests.
project_payload:
Optional saved Studio project payload from load_project.
simulation_payloads:
Optional Studio simulation responses carrying run metadata. Both
studio.simulation-run.v2, which the Studio emits, and
studio.simulation-run.v1, which older exports carry, are accepted:
a bundle assembled from a saved workspace must not refuse the responses
that workspace was recorded with. v2 adds the custody fields —
raw_sha256 over the full-resolution block and
state_custody_complete — so a v1 payload in a bundle records a run
whose custody was never established, and says so by their absence.
analysis_payloads:
Optional Studio analysis responses carrying studio.analysis-result.v1
analysis metadata.
model_scan_payloads:
Optional Studio model-scan responses carrying studio.model-scan.v1
scan metadata classified as analysis evidence.
weight_restore_payloads:
Optional Studio training weight-restore responses carrying
studio.training.weight-restore.v1 materialization evidence classified
as training evidence.
weight_restore_attach_payloads:
Optional Studio training weight-restore attach responses carrying
studio.training.weight-restore-attach.v1 evidence classified as
training evidence.
default_flow_runs:
Optional guided default-flow run responses carrying reproducibility
fingerprints.
default_flow_attestations:
Optional guided default-flow attestations for the supplied run
responses.
job_records:
Completed or failed Studio job records to preserve with their declared
artifacts. Artifacts ending in evidence.json must carry the
studio.action-evidence.v1 contract and are classified as
first-class action evidence in the bundle manifest.
artifact_reader:
Reader used to fetch verified job artifact bytes. Required when
job_records contains artifacts. Returned metadata and bytes are
checked against the captured source record before copying; a newer
or substituted declaration cannot silently change that snapshot.
audit_export:
Optional path-free audit export payload.
command_replay:
Optional JSON replay metadata, such as API method, route, request
digest, and operator note.
clock:
Optional UTC clock for deterministic tests.
Returns¶
StudioEvidenceBundleResult Path-free manifest and artifact list for the generated bundle.
Raises¶
ValueError If replay metadata is not JSON-safe or job artifacts are supplied without an artifact reader.
Module studio.platform.evidence_limits¶
Function validate_evidence_input_limit(value)¶
Return a positive integer byte budget; reject booleans and coercions.
Parameters¶
value : int Aggregate encoded-metadata and binary-seed ceiling, in bytes.
Returns¶
int Unchanged validated byte limit; no settings or filesystem are modified.
Raises¶
ValueError The value is not a positive integer, including boolean inputs.
Function parse_evidence_input_limit(value)¶
Parse the environment override, preserving the default only when absent.
Parameters¶
value : str or None Explicit byte count, or None for the 256 MiB operational default.
Returns¶
int Validated aggregate input limit, independent of per-artifact limits.
Raises¶
ValueError An explicit value is empty, non-integral or non-positive.
Module studio.platform.identity¶
Class StudioIdentityLifecycleError¶
Raised when an identity mutation would break lifecycle invariants.
Class StudioIdentityRecord¶
Persistent Studio service-account identity.
Parameters¶
principal_id: Stable service-account identifier recorded in policy audit events. roles: Role names granted to the service account. token_sha256: Lowercase SHA-256 hex digest of the bearer token. Raw tokens are never stored in the identity file. expires_at_utc: Optional UTC expiry instant. Expired records fail authentication. active: Whether the identity is currently allowed to authenticate.
- to_public_record()
- Return a token-free operator representation of this identity.
Class StudioIdentityPublicRecord¶
Path-free and token-free service-account record for operators.
Parameters¶
principal_id: Stable service-account identifier. roles: Roles granted to the service account. expires_at_utc: Optional UTC expiry instant formatted as an ISO timestamp. active: Whether the service account can authenticate.
- to_public_dict()
- Return an API payload without token hashes or local paths.
Class StudioBrowserUserRecord¶
Persistent browser-login identity for Studio operators.
Parameters¶
username: Stable browser-login username. principal_id: Principal identifier recorded in audit events after login. roles: Role names granted to the browser user. password_pbkdf2_sha256: Encoded PBKDF2-HMAC-SHA256 password verifier. expires_at_utc: Optional UTC expiry instant. Expired users cannot log in. active: Whether the user can currently authenticate.
- to_public_record()
- Return a password-free operator representation of this user.
Class StudioBrowserUserPublicRecord¶
Path-free and password-free browser-user record for operators.
- to_public_dict()
- Return an API payload without password verifier material.
Class StudioIdentityStore¶
Validated Studio identity store loaded from a local JSON file.
- public_records()
- Return token-free service-account records for admin APIs.
- public_browser_users()
- Return password-free browser-user records for admin APIs.
Class StudioIdentityResult¶
Result of authenticating one Studio authorization header.
Class StudioIdentityAuthenticator¶
Authenticate Studio bearer tokens against a validated identity store.
- init(identity_store, clock)
- authenticate_authorization_header(authorization)
- Authenticate an HTTP
Authorizationheader. - authenticate_browser_user(username, password)
- Authenticate one browser user with username and password.
Function load_studio_identity_store(path)¶
Load and validate a Studio identity store from JSON.
Parameters¶
path:
JSON file containing sc-neurocore.studio.identity.v1 service
account records.
Returns¶
StudioIdentityStore Validated immutable service-account records.
Raises¶
ValueError If the file cannot be parsed into the supported identity schema.
Function list_studio_identity_public_records(path)¶
Load token-free Studio service-account records from an identity file.
Parameters¶
path: Persistent identity JSON file.
Returns¶
tuple[StudioIdentityPublicRecord, ...] Public service-account records sorted by principal identifier.
Function list_studio_browser_user_public_records(path)¶
Load password-free Studio browser-user records from an identity file.
Parameters¶
path: Persistent identity JSON file.
Returns¶
tuple[StudioBrowserUserPublicRecord, ...] Public browser-user records sorted by username.
Function update_studio_identity_record(path)¶
Atomically update mutable service-account metadata.
The raw bearer-token SHA-256 digest is preserved and never returned.
Parameters¶
path: Persistent identity JSON file. principal_id: Existing service-account identifier to update. roles: Replacement role set. The set must be non-empty. active: Replacement active flag. expires_at_utc: Optional replacement UTC expiry timestamp.
Returns¶
StudioIdentityPublicRecord Updated token-free service-account record.
Raises¶
KeyError
If principal_id is not present in the store.
ValueError
If replacement metadata is malformed.
Function update_studio_browser_user_record(path)¶
Atomically update mutable browser-user metadata.
The stored PBKDF2-HMAC-SHA256 password verifier is preserved and never returned.
Parameters¶
path: Persistent identity JSON file. username: Existing browser-login username to update. roles: Replacement role set. The set must be non-empty. active: Replacement active flag. expires_at_utc: Optional replacement UTC expiry timestamp.
Returns¶
StudioBrowserUserPublicRecord Updated password-free browser-user record.
Raises¶
KeyError
If username is not present in the store.
ValueError
If replacement metadata is malformed.
Function rotate_studio_browser_user_password(path)¶
Atomically rotate one browser user's password verifier.
Parameters¶
path: Persistent identity JSON file. username: Existing browser-login username to update. password: New raw password supplied through an authenticated admin request.
Returns¶
StudioBrowserUserPublicRecord Password-free browser-user record after verifier rotation.
Raises¶
KeyError
If username is not present in the store.
ValueError
If the username or replacement password is malformed.
Function add_studio_browser_user_record(path)¶
Atomically add one persistent browser-login user to an identity file.
Parameters¶
path: Persistent identity JSON file. username: Unique browser-login username. principal_id: Stable principal identifier recorded in policy audit events. roles: Non-empty role set granted after login. password: Raw password read from an operator-controlled secret channel. active: Whether the new browser user can authenticate immediately. expires_at_utc: Optional UTC expiry timestamp.
Returns¶
StudioBrowserUserPublicRecord Password-free representation of the new browser user.
Raises¶
ValueError If the new user metadata is malformed or conflicts with an existing browser username.
Module studio.platform.identity_passwords¶
Function make_browser_user_password_verifier(password)¶
Create an encoded PBKDF2-HMAC-SHA256 password verifier.
Parameters¶
password: Raw browser-user password.
Returns¶
str Encoded verifier containing algorithm, iteration count, salt, and hash.
Function verify_browser_user_password(password, encoded_verifier)¶
Verify a raw browser-user password against an encoded verifier.
Module studio.platform.identity_refusals¶
Class StudioIdentityRefused¶
A deliberate identity validation message suitable for callers.
Class StudioIdentityConflict¶
An identity mutation conflicts with an existing persistent identity.
Module studio.platform.jobs_admission¶
Class StudioJobQueueFull¶
Raised when both the running slots and the queue behind them are full.
Attributes¶
running : int Jobs occupying a slot when the request arrived. queued : int Jobs already waiting. limit : int The queue ceiling that was reached.
- init()
- to_public_detail()
- Return the path-free public error detail.
Class AdmissionSnapshot¶
What admission control is doing right now.
Attributes¶
running : int Jobs holding a slot. queued : int Jobs waiting for one. max_concurrent : int How many may run at once. max_queued : int How many may wait. admitted : int Jobs admitted since this controller started. refused : int Submissions refused because the queue was full.
- to_public_dict()
- Return a JSON-serializable, path-free admission snapshot.
Class StudioJobAdmission¶
A bounded number of running jobs, with a bounded queue behind them.
Parameters¶
max_concurrent : int
Jobs allowed to run at once.
max_queued : int
Jobs allowed to wait for a slot. A submission that arrives when both
are full is refused with :class:StudioJobQueueFull.
- init()
- reserve()
- Take a slot, waiting in the queue when they are all occupied.
- release()
- Give a slot back and wake one waiting submission.
- snapshot()
- Return the current admission state.
Module studio.platform.jobs_admission_recovery¶
Function recover_stopped_reservations(ledger)¶
Release dead-owner queues and terminal in-process work after reconciliation.
A dead supervisor proves its threads ended, not its child processes. Keep process reservations unless stored identity proves their group stopped. Unprobeable identities and expiry alone never justify release. The caller reconciles job state first; this function never invents outcomes.
Module studio.platform.jobs_admission_replay¶
Class StorageAdmissionReplay¶
One authenticated requester, server workspace and exact mutation identity.
The trusted storage service computes payload_sha256 from its validated
versioned request. A browser trace ID and the legacy job idempotency key do
not replace this identity.
- validate()
- Reject malformed replay identities before any reservation is opened.
Function read_admission_replay(connection)¶
Return an immutable prior outcome or reject a changed request digest.
Function write_admission_replay(connection)¶
Write the exact result inside the caller's job/capacity transaction.
Module studio.platform.jobs_admission_schema¶
Function migrate_purge_journal(connection)¶
Record exact directory custody before a filesystem/database purge begins.
Function migrate_purge_phases(connection)¶
Extend purge phases without inferring completion evidence for legacy rows.
The caller owns the transaction. Refuse custom indexes/triggers rather than silently destroying them while replacing the constrained table definition.
Function migrate_worker_custody(connection)¶
Add worker identity evidence without inferring identities for historical jobs.
Function migrate_admission(connection)¶
Create shared capacity tables and retain legacy occupied capacity.
The caller owns the migration transaction. Do not use executescript here: it would commit the surrounding migration early. Job records and transition history are not rewritten. Unknown jobs and explicitly unreaped outcomes retain a reservation; their capacity cannot be reclaimed from expiry alone.
Function migrate_storage_admission_replay(connection)¶
Add immutable exact-outcome replay without inferring legacy request digests.
Module studio.platform.jobs_context¶
Class StudioJobContext¶
Execution context passed to one local Studio job task.
- init()
- Bind one job identifier to its confined task resources.
- cancelled()
- Return whether the manager requested cooperative cancellation.
- artifacts()
- Return artifacts written through this context.
- check_cancelled()
- Raise when the manager requested cooperative cancellation.
- write_artifact(relative_path, payload)
- Write one size-bounded artifact below the job directory.
- append_artifact_event(relative_path, payload)
- Append one size-bounded JSON event to a confined live log.
- publish_existing_artifact(relative_path)
- Validate and declare an existing confined artifact in the manifest.
- read_seed_input(relative_path)
- Read one confined, size-bounded submission seed payload.
- poll_control_command()
- Consume one pending JSON control command exactly once.
- read_control_seed(relative_path)
- Read one confined, size-bounded control seed payload.
Module studio.platform.jobs_ledger¶
Class StudioJobLedger¶
A durable, transactional record of every local Studio job.
Parameters¶
root : pathlib.Path
The job root. The ledger file is created inside it, beside the per-job
sandbox directories it describes.
clock : callable, optional
Returns the current time; defaults to the system UTC clock.
supervisor : str, optional
Identity of the supervisor in this process; defaults to
:func:~sc_neurocore.studio.platform.jobs_ledger_supervisor.supervisor_identity.
lease_seconds : float
Finite positive seconds a lease stays valid without a heartbeat.
- init()
- path()
- Return the ledger file path.
- storage_identity()
- Return root and database device/inode evidence from initialization.
- supervisor()
- Return the identity this ledger stamps on leases it takes.
- close()
- Close this thread's connection, if it opened one.
- connection()
- Return this thread's connection, opening it on first use.
- transaction()
- Commit one unit of work; roll back on any failure, even one right after BEGIN.
- now()
- Return the ledger clock, truncated to whole seconds in UTC.
- timestamp()
- Return the ledger clock as a stable UTC string.
- lease_expiry()
- Return when a lease taken now would expire without a heartbeat.
- create()
- Admit one job, or return the one that already owns its key.
- transition(job_id, to_status)
- Move one job to a new status and append the transition.
- heartbeat(job_id)
- Extend this supervisor's lease; reject renewal by a different owner.
- delete(job_id)
- Remove one terminal job and its whole transition history.
- record(job_id)
- Return one job record, scoped to an actor and workspace when given.
- list_records()
- Return records in creation order, scoped to an actor and workspace.
- pending_purge_count()
- Count unresolved purge intents without initiating recovery.
- purge_snapshot()
- Read a bounded global operator page, without authorising any mutation.
- transitions(job_id)
- Return the append-only transition history of one job, in order.
- live_rows()
- Return the stored rows of every job that has not finished.
- reconcile()
- Resolve every job left alive by a supervisor that is no longer here.
Module studio.platform.jobs_ledger_creation¶
Function create_job(ledger)¶
Admit one job, or return the one that already owns its key.
Parameters¶
ledger : StudioJobLedger The ledger to write to. job_id : str Generated identifier for the new job. kind, actor, workspace : str What is running, for whom, and in which workspace. Actor and workspace scope every later read. request_id : str, optional The caller's request correlation id. idempotency_key : str, optional When given, a second submission with the same key by the same actor and workspace returns the first job instead of starting another. experiment_sha256 : str, optional Digest of the effective experiment this job runs, when it has one. admission : mapping, optional The admission decision recorded with the job. training_config : mapping, optional Canonical, bounded training configuration stored with admission. execution_model : {"thread", "process"} How the job is supervised. connection : sqlite3.Connection, optional This ledger's already active transaction, used by shared admission to commit reservation and job together. Other connections are rejected. lease_owner : str, optional Process generation verified by the storage service for a delegated admission. The ordinary in-process path uses this ledger's supervisor.
Returns¶
StudioJobSubmission The stored record and whether it was already there.
Module studio.platform.jobs_ledger_reads¶
Function read_pending_purge_count(ledger)¶
Count all unresolved journal phases without exposing SQL to manager clients.
Function read_purge_snapshot(ledger)¶
Read at most 1000 intents without recovery, filesystem reads or process probes.
Cursor ordering is lexical by job ID. Pages reflect current database state; concurrent changes can occur between requests. Invalid bounds/cursors raise ValueError before querying, including when called without HTTP validation.
Function read_record(ledger, job_id)¶
Return one job record, scoped to an actor and workspace when given.
A job that exists but belongs to a different actor or workspace raises
:class:KeyError, so an isolated caller cannot tell it apart from a job
that never existed.
Function read_records(ledger)¶
Return records in creation order, scoped to an actor and workspace.
Creation timestamps have one-second resolution, so two jobs submitted in
the same second tie. The tie is broken by insertion order (rowid), not
by job_id: an id is a digest, and ordering by it made "the latest job"
a matter of which random hex sorted higher. Retention decisions read this
order, so the wrong archive was kept whenever the ids happened to sort
against submission order.
Function read_transitions(ledger, job_id)¶
Return the append-only transition history of one job, in order.
Function read_live_rows(ledger)¶
Return the stored rows of every job that has not finished.
Module studio.platform.jobs_ledger_recovery¶
Class StudioJobReconciliation¶
What startup recovery decided about one job it found alive.
Attributes¶
job_id : str The job examined. previous_status : StudioJobStatus The status the ledger held before recovery. status : StudioJobStatus The status recovery assigned, or the previous one when it left the job alone because another live supervisor owns it. reason : str Why, in words a runbook can act on.
- to_public_dict()
- Return a path-free JSON representation of this decision.
Function reconcile_ledger(ledger)¶
Resolve every job left alive by a supervisor that is no longer here.
Parameters¶
ledger : StudioJobLedger The ledger to recover. A lease belonging to this process is probed like any other: constructing another manager or reconciling a live manager does not imply process death. The identity includes a process-start token, so a reused PID does not inherit an earlier process's jobs.
Returns¶
tuple of StudioJobReconciliation One decision per retained job examined, including those left running. Concurrently purged jobs are omitted; concurrent updates are retained.
Module studio.platform.jobs_ledger_rows¶
Class StudioJobLedgerCorrupt¶
Raised when the ledger file cannot be read as a Studio job ledger.
Function json_or_none(value)¶
Decode one stored JSON column, or None.
Function artifacts_from_json(value)¶
Rebuild an artifact manifest, refusing a malformed one.
Function artifacts_to_json(artifacts)¶
Serialise an artifact manifest deterministically.
Function record_from_row(row)¶
Rebuild one immutable public record from its stored row.
Function training_config_from_json(value)¶
Decode a validated training snapshot, preserving absent legacy values.
A snapshot whose exact stored bytes were validated before, under the same event-input admission limit, is returned as a fresh copy of that result without validating again; any other snapshot is validated in full.
Module studio.platform.jobs_ledger_schema¶
Class StudioJobSubmission¶
The outcome of asking the ledger to admit one job.
Attributes¶
record : StudioJobRecord
The stored record: the new one, or the existing one when the
idempotency key had already been admitted.
duplicate : bool
True when an earlier submission already owns this idempotency key,
so the caller must not start a second run.
Function migrate(connection)¶
Bring the stored schema forward, refusing a version from the future.
Raises¶
StudioJobLedgerCorrupt The file was written by a newer schema than this build understands. Downgrading a ledger would silently drop columns, so it is refused.
Function migrate_training_event_data(connection)¶
Add bounded per-job event custody and refuse mutation after admission.
Parameters¶
connection : sqlite3.Connection The owning ledger's active schema migration transaction.
Module studio.platform.jobs_ledger_supervisor¶
Function supervisor_identity(pid)¶
Return host/PID/start identity for this process or an observed local child.
Omit pid for the current process. An explicit pid is a caller observation, not an authenticated assertion. Unavailable metadata yields start token0; registration must refuse that unknown identity instead of certifying it.
Function supervisor_is_alive(identity)¶
Return whether a supervisor is running, or None when unknowable.
Parameters¶
identity : str
An identity produced by :func:supervisor_identity.
Returns¶
bool or None
True when the process is running, False when it provably is
not, and None when this host cannot tell — a malformed identity, a
different host, or a platform without process metadata. A zero or
malformed start token is unknown, not evidence of process death.
A different UID may deny the signal probe; readable matching proc
metadata still proves this exact process generation is alive.
Module studio.platform.jobs_ledger_writes¶
Function transition_job(ledger, job_id, to_status)¶
Move one job to a new status and append the transition.
The move is refused when the state machine does not allow it, so a terminal
record can never be rewritten and an interrupted job can never be quietly
completed. Repeating a terminal status is a no-op only when all supplied
fields match the stored values; a conflicting retry is refused. Repeating
a live status can still record accompanying fields. A supervisor reporting
running for a job that is already cancelling keeps the cancellation
visible and records only the start time.
With expected_record, a differing current record is returned without
changing it. The comparison includes every public field, serialised as JSON
to preserve numeric and boolean distinctions, and runs under the write lock.
supervisor names the lease owner acting through a storage service that
verified it; None means this ledger's own supervisor. Only the owner's
transition renews the lease.
An optional connection must be this ledger's active transaction, allowing the storage authority to commit a terminal record together with the release of its admission reservation.
Raises¶
ValueError
connection is not this ledger's active transaction.
KeyError
The job is not in the ledger.
StudioJobRejected
The transition is not allowed from the job's current status, or a
supplied field conflicts with the already sealed terminal record.
Function heartbeat_job(ledger, job_id)¶
Extend a live job's lease, checking its status in the write transaction.
Terminal and absent jobs remain unchanged. The transaction serialises this
check with transitions so a finished job cannot acquire another lease.
Only the recorded owner can renew a live lease, even after expiry; another
supervisor raises StudioJobRejected without changing any stored fields.
supervisor is a storage-verified delegated owner; None means this
ledger's own supervisor.
Returns¶
bool
True when the lease was renewed, False when the job is absent
or already terminal.
Function require_purgeable(connection, job_id)¶
Refuse missing, active or capacity-retaining jobs before discarding custody.
Function delete_job(ledger, job_id)¶
Remove one unreserved terminal job, worker identity and transition history.
An optional connection must be this ledger's active transaction, allowing the filesystem purge owner to serialize staging with record deletion.
Raises¶
KeyError The job is not in the ledger. StudioJobRejected The job is active or retains capacity; its custody is not disposable.
Module studio.platform.jobs_manager¶
Class StudioJobManager¶
Start and supervise local Studio jobs inside per-job sandbox directories.
Reading what those jobs did is the custody surface this inherits from
:class:~sc_neurocore.studio.platform.jobs_manager_custody.StudioJobCustody.
- init()
- Configure bounded execution over the durable job ledger.
- root()
- Return the directory holding the ledger and every job's sandbox.
- submit()
- Submit one local task to the bounded thread supervisor.
- submit_process_task()
- Submit one importable task to an isolated Python process.
- send_control_command(job_id)
- Atomically deliver control data to one running process job.
- cancel(job_id)
- Request cooperative cancellation for one job.
- wait(job_id, timeout_seconds)
- Wait for a local or retained shared-ledger job without changing it.
- status()
- Return aggregate path-free manager health.
Module studio.platform.jobs_manager_custody¶
Class StudioJobCustody¶
The durable read surface of a Studio job manager.
Every method annotates self as the manager state it needs. The mixin
carries no state of its own: it is the reading half of one object, split
from the supervising half so each file has one responsibility.
- record(job_id)
- Return the durable record for one job, scoped when asked.
- list_records()
- Return durable jobs in creation order, scoped when asked.
- list_snapshot()
- Return a path-free snapshot of every job visible to the caller.
- purge_snapshot()
- Read a bounded global operator journal page without initiating recovery.
- transitions(job_id)
- Return the append-only transition history of one job.
- reconcile()
- Recover dead supervisors and retry this supervisor's committed purge cleanup.
- last_reconciliation()
- Return the decisions of the most recent recovery pass.
- ledger_path()
- Return the durable ledger file backing this manager.
- purge_terminal_record(job_id)
- Delete one terminal job directory and its in-memory state.
- read_artifact(job_id, relative_path)
- Read and verify one manifest-declared artifact.
- read_live_artifact_bytes(job_id, relative_path)
- Read one bounded slice from a confined live artifact.
- unreaped_workers()
- Return the jobs whose worker was still running when they ended.
Module studio.platform.jobs_manager_supervision¶
Class StudioJobSupervision¶
The callbacks a Studio job supervisor makes on its manager.
Each method annotates self as the manager state it needs; the mixin
holds no state of its own.
Module studio.platform.jobs_models¶
Class StudioJobRejected¶
Raised when a Studio job request violates the local sandbox policy.
Class StudioJobCancelled¶
Raised inside a cooperative Studio job when cancellation is requested.
Class StudioJobArtifactUnavailable¶
Raised when a declared Studio job artifact cannot be safely served.
Class StudioJobArtifact¶
Path-free manifest entry for one Studio job artifact.
- to_public_dict()
- Return a path-free JSON representation of this artifact.
Class StudioJobRecord¶
Immutable public state for one local Studio job.
- to_public_dict()
- Return path-free job state suitable for operator APIs.
Class StudioJobResourceProfile¶
Path-free execution limits for one Studio job kind.
- to_public_dict()
- Return a JSON-serializable, path-free resource profile.
Class StudioJobStatusSnapshot¶
Path-free aggregate health for the local Studio job manager.
- to_public_dict()
- Return a JSON-serializable, path-free status snapshot.
Class StudioJobListSnapshot¶
Path-free list payload for Studio job operator views.
- to_public_dict()
- Return JSON-serializable job records without filesystem paths.
Class StudioJobArtifactPayload¶
Verified payload for one declared Studio job artifact.
Class StudioJobPurgeRecord¶
Operator journal evidence, without filesystem paths or process identity.
- to_public_dict()
- Return recorded evidence only; neither presence nor completion is inferred.
Class StudioJobPurgeSnapshot¶
Bounded live journal page; subsequent pages are not a frozen snapshot.
- to_public_dict()
- Serialize a versioned operator page with a lexical job-ID cursor.
Module studio.platform.jobs_process_state¶
Function process_exited(pid)¶
Return whether every thread of a process has exited.
A zombie still belongs to its process group, so killpg(group, 0) keeps
succeeding for it; treating it as running would report every ordinary reap
as a failure. A thread-group leader that exits while its other threads run
is also shown as a zombie, yet its process still executes, so each thread
is checked. A process or thread that vanished during the check has exited.
Function group_survivors(group_id)¶
Return the process ids still running in one group, zombies excluded.
Function group_is_gone(group_id)¶
Return whether nothing in the group is still running.
Module studio.platform.jobs_purge¶
Function purge_terminal_job(manager, job_id)¶
Purge unreserved job custody without erasing files before a database refusal.
A sibling staging directory retains the bytes until database deletion commits. Existing staging paths are never overwritten. If restoring after an error would overwrite a new path, retain the stage and report failure.
Module studio.platform.jobs_purge_paths¶
Function sync_directory(path)¶
Persist directory entry changes or propagate the OS error to recovery.
Function move_without_replace(source, destination)¶
Move a directory atomically, returning False if the target already exists.
Requires libc/kernel/filesystem renameat2 RENAME_NOREPLACE support. Other errors propagate to the caller's recovery handling; never fall back to a check-then-rename operation that could overwrite a concurrent destination. This excludes destination replacement, not concurrent source substitution.
Module studio.platform.jobs_purge_recovery¶
Class PurgeCustody¶
What purging and its recovery use from their owner.
The ledger and custody root, and the owner's local handles of jobs it supervises, which a purge forgets. The embedded manager is one owner; the storage authority is another, with no local handles.
Function recover_purges(manager)¶
Recover exact custody with committed cleanup-start and removal evidence.
Each phase rechecks ownership under its own writer transaction. Ambiguous intents never resolve automatically, and live foreign supervisors retain ownership. At most three phases run per intent; this is not a background retry loop.
Module studio.platform.jobs_reaper¶
Class ReapReport¶
What stopping one worker process group actually achieved.
Attributes¶
outcome : {"exited", "terminated", "killed", "unreaped"}
exited when the worker had already finished, terminated when it
stopped on SIGTERM, killed when SIGKILL was needed, and
unreaped when the group was still there afterwards.
group_id : int or None
The process group signalled, when one could be resolved.
returncode : int or None
The direct worker's exit status, when it was collected.
duration_seconds : float
Wall-clock time the reap took.
survivors : tuple of int
Process ids still alive in the group when the reap gave up. Empty
unless outcome is unreaped.
- reaped()
- Return whether the scoped worker cleanup was verified complete.
- to_public_dict()
- Return a path-free JSON representation of this reap.
Function process_group_of(process)¶
Return the worker's process group, or None when it has none.
A worker started with start_new_session=True leads its own group, so
the group id equals its pid. Reading it from the operating system rather
than assuming it keeps the reap honest when the process has already gone.
Function reap_process_group(process)¶
Stop the registered worker process group and report what happened.
SIGTERM to the group first, so a worker that handles it can seal its own files; SIGKILL to the group if the grace period passes; then a check that the group is actually gone. A descendant that leaves this group by creating another session or group is outside this cleanup scope.
Parameters¶
process : subprocess.Popen
The worker. It must have been started with start_new_session=True,
or it shares the supervisor's group and only the direct child is
signalled.
terminate_grace_seconds : float
How long the group may take to exit on SIGTERM.
kill_grace_seconds : float
How long the group may take to disappear after SIGKILL.
owned_group_id : int, optional
Group captured by the caller for a worker it started in its own session.
Retains descendant custody after the direct child has been collected.
Must equal that worker's PID and must not be the caller's group.
Returns¶
ReapReport The outcome for the worker group, or for the direct child when no separate owned group can be resolved; never an exception.
Module studio.platform.jobs_shared_admission¶
Class SharedJobAdmission¶
One root's capacity, with job-scoped reservations and release.
Opening an observer does not change configuration. The first submission establishes root limits; conflicting submission limits are rejected.
- init(ledger)
- admit()
- Atomically admit capacity and job, or return the existing scoped key.
- release()
- Release this supervisor's exact reservation; repeated release is a no-op.
- reconcile()
- Release only reservations whose stopped work has been proved after job recovery.
- mark_unreaped()
- Keep capacity occupied when a terminal job's worker has not stopped.
- snapshot()
- Read one consistent root-wide occupancy and cumulative counter snapshot.
Module studio.platform.jobs_snapshot¶
Function decode_job_snapshot(payload)¶
Decode an exact complete snapshot, retaining every custody field.
Parameters¶
payload : mapping Public record JSON, including nullable fields and artifact declarations.
Returns¶
StudioJobRecord Domain record reconstructed from JSON, without storage or identity claims.
Raises¶
ValueError Fields are missing, unknown, non-JSON or violate native record types. Training configuration and event declarations obey the ledger's independent byte limits; transport framing remains separately bounded.
Module studio.platform.jobs_worker_custody¶
Function register_worker(ledger, job_id, expected_supervisor, worker_identity, group_id)¶
Bind an observed child to its admitted job on the trusted authority side.
Persist host/PID/start-token identity, boot identity and process group in the job ledger. Refuse inactive jobs, mismatched ownership, absent capacity, duplicate workers and a supervisor whose liveness cannot be established. Registration is evidence of startup, not proof of later group termination.
Module studio.platform.jobs_worker_guard¶
Function arm_worker_guard(supervisor)¶
Arm before importing task code; refuse execution without a ready guard.
The guard shares the worker's dedicated group. It survives worker GIL stalls and is stopped with the group by normal supervisor reaping. It never signals a group supplied by an unrelated process: its own membership retains custody.
Function main()¶
Stop the worker's group on supervisor death or prolonged unknown liveness.
Poll every 100 ms; tolerate unknown metadata for at most one second. Exit with status 1 after stopping the group. This guards local supervised compute, not hostile processes escaping the session or a system where the guard itself cannot be scheduled.
Module studio.platform.jobs_worker_limits¶
Class StudioWorkerLimits¶
Per-process ceilings for embedded Studio jobs.
Parameters¶
max_data_bytes:
Private writable allocation ceiling in bytes.
max_open_files:
Maximum number of open file descriptors.
max_file_bytes:
Maximum size in bytes of any file written by the worker.
max_cpu_seconds:
CPU seconds per process. None derives a ceiling from the job's
wall-clock timeout and the host CPU count.
- post_init()
- Reject nonpositive, fractional and boolean resource ceilings.
- for_host(cls)
- Use half of physical RAM and bounded descriptor and file ceilings.
- worker_arguments(timeout_seconds)
- Encode limits for the worker launched with this job timeout.
Function apply_worker_limits()¶
Set POSIX hard ceilings in the worker before loading task code.
An inherited hard ceiling is never raised. The CPU soft limit can rise to
its hard ceiling, at most one second higher, so SIGXCPU can report
exhaustion before the kernel kills the worker. No per-UID RLIMIT_NPROC
is set.
Parameters¶
max_data_bytes:
Private writable allocation ceiling in bytes.
max_cpu_seconds:
CPU seconds before SIGXCPU.
max_open_files:
Maximum open file descriptors.
max_file_bytes:
Maximum bytes in one output file.
Module studio.platform.jobs_worker_recovery¶
Function worker_group_stopped(identity, boot_id, group_id)¶
Return true only for a validated old boot or a locally stopped group.
Missing metadata, foreign hosts, malformed identities and inaccessible process metadata retain capacity. A live group with a reused ID also stays occupied; this probe never signals it. A member counts as stopped only when every one of its threads has exited: zombies cannot execute or spawn work, but a zombie thread-group leader can still have running threads.
Module studio.platform.jobs_worker_registration¶
Function start_worker_registration(ledger, job_id, process, expected_supervisor)¶
Capture the owned child before polling, then commit asynchronously and grant once.
The supervisor continues timeout/cancellation monitoring while SQLite may wait for its writer lock. EOF is refusal. Identity arguments are observations of the trusted parent, not an interface for untrusted network assertions.
Function await_worker_registration(descriptor)¶
Require the exact parent grant within three seconds; EOF or malformed input refuses.
Module studio.platform.model_compile_process¶
Function run_model_compile_process_task(context, payload)¶
Resolve and compile one catalogue model through its canonical schema.
Module studio.platform.model_cosim_process¶
Function run_model_cosim_process_task(context, payload)¶
Resolve one selected model and emit real external-tool parity evidence.
Module studio.platform.operator¶
Class StudioOperatorCapabilityStatus¶
Aggregate health for the Studio capability registry.
- to_public_dict()
- Return a public capability-health aggregate.
Class StudioOperatorIdentityStatus¶
Path-free identity posture for Studio operator APIs.
- to_public_dict()
- Return public identity posture without service-account material.
Class StudioOperatorRoutePolicyStatus¶
Route-policy enforcement posture for Studio operator APIs.
- to_public_dict()
- Return public route-policy posture.
Class StudioOperatorResourceLimitStatus¶
Path-free runtime resource limits relevant to Studio operators.
- to_public_dict()
- Return configured resource ceilings without host paths.
Class StudioOperatorBrowserLoginStatus¶
Path-free browser-login lockout posture for Studio operators.
- to_public_dict()
- Return browser-login lockout limits without identity material.
Class StudioOperatorStatus¶
Path-free aggregate status for the Studio operator control plane.
- to_public_dict()
- Return the path-free operator status API payload.
Function build_studio_operator_status()¶
Build the aggregate operator status from live Studio platform components.
Module studio.platform.pipeline_process¶
Function run_pipeline_process_task(context, payload)¶
Run one Studio graph-to-synthesis pipeline in an isolated process.
Parameters¶
context:
Job sandbox used to write path-confined result and evidence artifacts.
payload:
JSON object matching the public /api/pipeline/run request contract.
Returns¶
dict[str, object] Path-free pipeline result payload.
Raises¶
ValueError If the payload does not match the JSON-serializable pipeline contract.
Module studio.platform.policy_audit¶
Class JsonlAuditSink¶
Append-only JSONL audit sink for Studio policy decisions.
- init(path)
- Configure an append-only audit log and bounded rotation policy.
- path()
- Return the configured JSONL audit log path.
- record(event)
- Append a Studio policy audit event as one JSON object.
- status()
- Return status for the persistent JSONL audit sink.
- export_recent(limit)
- Export the most recent persisted audit rows without exposing paths.
- export_quarantine(limit)
- Export quarantined retained audit rows without exposing local paths.
Module studio.platform.policy_gateway¶
Class RoutePolicyRegistry¶
Registry of Studio route policies keyed by HTTP method and path.
- init()
- Create an empty method-and-path policy registry.
- register(method, path_template, policy)
- Register one Studio route policy.
- policy_for(method, path_template)
- Return the policy for one HTTP method and path template.
- policies()
- Return registered route policies in stable method/path order.
- missing_policies(routes)
- Return route signatures that have no registered Studio policy.
Class PolicyGateway¶
Fail-closed Studio route authorization gateway.
- init(audit_sink, clock)
- Bind the required audit sink and optional deterministic clock.
- authorize(policy)
- Authorize a caller against a Studio route policy.
Module studio.platform.policy_models¶
Class AuditSinkError¶
Raised when a Studio audit sink cannot persist an event.
Class AuditSinkStatus¶
Operator-safe status for a Studio audit sink.
- to_public_dict()
- Return an operator-safe status dictionary without local paths.
Class AuditExport¶
Operator-safe export of persisted Studio audit rows.
- to_public_dict()
- Return a path-free JSON export payload for admin operators.
Class AuditQuarantineExport¶
Operator-safe export of quarantined retained Studio audit rows.
- to_public_dict()
- Return path-free quarantined audit rows for incident handoff.
Class RouteVisibility¶
Visibility class for a Studio API route.
Class Principal¶
Authenticated Studio caller identity.
Class RoutePolicy¶
Authorization policy attached to one Studio route.
- post_init()
- Validate fail-closed policy metadata.
Class PolicyDecision¶
Authorization decision returned by the Studio policy gateway.
Class AuditEvent¶
Audit event emitted for Studio policy decisions.
- to_json_dict()
- Return a JSON-serializable representation of the audit event.
Class AuditSink¶
Append-only sink for Studio policy audit events.
- record(event)
- Record a Studio policy audit event.
- status()
- Return operator-safe audit sink status.
Class InMemoryAuditSink¶
Append-only in-memory audit sink for local Studio policy tests.
- init()
- Create an empty process-local audit event buffer.
- events()
- Return recorded audit events in insertion order.
- record(event)
- Record a Studio policy audit event.
- status()
- Return status for the non-persistent in-memory audit sink.
Module studio.platform.policy_routes¶
Function build_default_studio_route_policy_registry()¶
Build route policies for the current Studio platform API surface.
Module studio.platform.preflight¶
Class StudioPreflightCheck¶
One secret-free Studio release-preflight check result.
Parameters¶
check_id:
Stable machine-readable identifier for the checked release invariant.
status:
"pass" when the invariant holds, "fail" when it is violated and
blocks release, or "warn" for a non-blocking advisory the operator
should resolve before production use.
message:
Operator-facing summary that does not include local paths or secrets.
evidence:
Small scalar evidence fields suitable for JSON reports.
remediation:
Operator actions that can resolve a failed or warned check. Entries
must not expose local filesystem paths or secret material.
- to_public_dict()
- Return a JSON-serializable, path-free check payload.
Class StudioPreflightReport¶
Machine-readable Studio release-preflight report.
Parameters¶
checks: Ordered release-readiness checks. deployment_profile: Parsed Studio deployment profile when runtime settings were valid. schema_version: Stable report schema identifier.
- passed()
- Return whether no preflight check failed (warnings do not block).
- warned()
- Return whether any check raised a non-blocking advisory warning.
- to_public_dict()
- Return a JSON-serializable, secret-free preflight payload.
Function run_studio_preflight(env)¶
Run Studio release-readiness checks from environment-style settings.
Parameters¶
env:
Optional environment mapping. When omitted, os.environ is used by
the runtime settings builder.
clock:
Optional UTC timestamp used for expiry-sensitive identity checks.
Returns¶
StudioPreflightReport Ordered path-free report. The report fails closed if settings cannot be parsed or any release invariant is missing.
Module studio.platform.process_worker¶
Function main(argv)¶
Run one importable Studio process task and persist a JSON result.
Parameters¶
argv:
Optional command-line argument sequence. None reads process
arguments from sys.argv through argparse.
Returns¶
int
0 when the imported task completed and wrote a result; 1 when
the task failed and the result file contains the public error string.
Module studio.platform.sessions¶
Class StudioBrowserSessionIssue¶
Issued Studio browser session.
Parameters¶
bearer_token: Raw bearer token returned once to the browser. principal: Principal bound to the issued session. expires_at_utc: UTC expiry timestamp for the session.
- to_public_dict()
- Return the login response payload.
Class StudioBrowserSessionRecord¶
Server-side browser session record stored without raw token material.
Class StudioBrowserSessionResult¶
Result of authenticating a browser bearer-session token.
Class StudioBrowserSessionManager¶
Issue, authenticate, and revoke ephemeral browser bearer sessions.
- init()
- issue(principal)
- Issue a new browser session for an authenticated principal.
- authenticate_authorization_header(authorization)
- Authenticate a bearer session from an HTTP
Authorizationheader. - revoke_authorization_header(authorization)
- Revoke a browser bearer session if the header contains one.
- revoke_principal(principal_id)
- Revoke all browser sessions for one principal identifier.
- public_session(authorization)
- Return the current session payload without token material.
Module studio.platform.settings¶
Class StudioRuntimeSettings¶
Runtime settings consumed by the Studio FastAPI application.
- post_init()
- Validate settings that affect Studio security boundaries.
Function build_default_studio_runtime_settings(env)¶
Build Studio runtime settings from environment-style values.
Module studio.platform.storage_admission_client¶
Class PendingNamedAdmission¶
Immutable exact transfer state for one correlated authority reply.
The original request object may contain mutable nested JSON; only these bytes were sent. The service identity and deadline are also snapshotted so a later caller cannot replace them with another configuration.
Function send_named_admission_request(channel)¶
Send validated metadata and exact seed bytes on one connected Unix stream.
The trusted API caller must construct the requester only from its middleware-authenticated principal. This function checks a frozen metadata and seed snapshot before sending, separates event declarations under their existing custody ceiling, uses configuration-owned limits, and closes the channel on every failure. On success the caller retains an immutable transfer snapshot and the channel for one correlated response. The service independently derives and checks its own content identity. Sending does not reserve capacity, admit a job or authorize a worker.
Parameters¶
channel : socket.socket Exclusively owned connected Unix stream to the configured service. request : StorageNamedAdmissionRequest Typed named metadata built from trusted API identity and route context. seed_inputs : mapping of str to bytes Exact immutable seed content corresponding to the request manifest. configuration : StorageBoundaryConfiguration Trusted workspace, service UID, byte budgets and transfer timeout.
Returns¶
PendingNamedAdmission Original sent metadata, expected content identity, service UID and absolute reply deadline. It grants no admission authority.
Raises¶
ValueError Request, workspace, metadata, manifest or seed bytes are invalid. PermissionError The connected service peer has the wrong kernel UID. TimeoutError The one absolute transfer deadline expires. OSError A socket transfer fails; the ambiguous stream is closed.
Function read_named_admission_result(channel)¶
Read one peer-verified result for the exact previously sent mutation.
The original send and this response share one absolute deadline. The channel is consumed and closed on success, refusal, timeout or corruption. A timeout or disconnect is ambiguous: the API must use the same mutation ID and content for a deliberate durable replay, never infer no admission.
Parameters¶
channel : socket.socket Same exclusively owned Unix stream used for the pending send. pending : PendingNamedAdmission Immutable snapshot returned by that send, never browser input.
Returns¶
str Correlated admitted job ID; read its complete record separately.
Raises¶
StudioJobQueueFull A correlated capacity refusal returned by the service. ValueError Pending state, framing, schema or response correlation is invalid. PermissionError The connected service peer UID differs from the sent snapshot. TimeoutError The original absolute transfer deadline expires. EOFError The service disconnects before a complete result arrives. OSError Socket transfer fails.
Module studio.platform.storage_admission_digest¶
Function derive_storage_admission_replay()¶
Hash one exact named admission without trusting a caller-supplied digest.
task must match the service's reviewed named-operation map and its
authorized route. requester must come from
its policy-allowed trusted API peer, and workspace from configuration.
Seeds must already have passed bounded ingress; this function hashes
their actual content and refuses aggregate bytes beyond max_seed_bytes.
The caller's HTTP trace, mutation ID and process generation are excluded
from content so a lost reply can replay after an API restart. This function
prepares the replay key; it does not authorize, admit or launch a worker.
Parameters¶
requester : Principal
Authenticated principal delegated by the trusted API peer.
mutation_id : str
Durable retry key, distinct from the HTTP trace identifier.
workspace : str
Server-configured workspace, never a browser-selected scope.
task : NamedStudioTask
Reviewed task selected for authorized_route.
authorized_route : str
Route whose existing policy the service has allowed.
payload_json : bytes
UTF-8 process object bounded by metadata plus the event custody ceiling.
Large event declarations are validated and represented by their complete
SHA and byte reference in the canonical replay identity.
seed_inputs : mapping of str to bytes or ReceivedStorageSeedFile
Actual received seed bytes or private staged files. Staged files are
rehashed in bounded chunks; their declared digests are not trusted.
execution_timeout_seconds, queue_wait_seconds : float or None
Worker deadline and distinct admission queue deadline.
admission, training_config : mapping or None
Existing job admission and validated training snapshot controls.
experiment_sha256 : str or None
Effective experiment digest, when one exists.
max_metadata_bytes, max_seed_bytes, max_seed_entries : int
Explicit service limits for small canonical controls and received seeds.
Previously admitted inline event controls retain their legacy digest;
large declarations use the separately bounded event content identity.
Returns¶
StorageAdmissionReplay Validated requester, mutation key and service-derived SHA-256 digest.
Raises¶
ValueError Invalid identity, JSON, nonfinite value, size or seed content.
Module studio.platform.storage_admission_protocol¶
Class StorageNamedAdmissionRequest¶
One named submission from a verified API peer, without worker authority.
The service separately checks the configured workspace, route policy,
reviewed task registry, delegated requester and peer process generation.
seed_manifest describes frames following this metadata request; the
service checks actual bytes before deriving durable replay identity.
No client-selected kind, owner, import path, digest or supervisor is valid.
Function decode_named_admission_request(payload)¶
Decode one exact metadata frame with no ambiguous JSON object names.
Parameters¶
payload : bytes Complete nonempty metadata frame from a peer-verified Unix stream. max_metadata_bytes : int Service-configured positive frame ceiling checked before parsing.
Returns¶
StorageNamedAdmissionRequest Strictly typed metadata, not an authorization or admission decision.
Raises¶
ValueError Bytes, JSON, schema version, operation, field types or size are invalid.
Notes¶
The caller must still verify the configured API UID and process generation, authorize the route, receive exact seed bytes and establish worker custody before durable admission. This decoder has no ledger or task import access.
Module studio.platform.storage_admission_response¶
Class StorageNamedAdmissionResponse¶
One exact admission or capacity-refusal outcome from the authority.
A caller must supply the result of its durable authority transaction; the codec cannot prove persistence from a Python object alone. A lost reply remains ambiguous until the same mutation ID and content are replayed against the authority's durable table.
- validate_outcome()
- Require mutually exclusive complete success and capacity shapes.
Function encode_named_admission_response()¶
Serialize one actual authority outcome within a trusted frame ceiling.
Parameters¶
request : StorageNamedAdmissionRequest Exact request already authorized and prepared by the service. replay : StorageAdmissionReplay Service-derived content identity used in the durable transaction. outcome : StudioJobSubmission or StudioJobQueueFull Admission or capacity refusal returned by the authority transaction. max_bytes : int Positive trusted maximum response-frame payload bytes.
Returns¶
bytes Strict versioned result to send over the peer-verified channel.
Raises¶
ValueError Correlation, domain outcome or complete frame size is invalid.
Function decode_named_admission_response(payload)¶
Return the admitted job ID or raise the exact durable queue refusal.
This codec checks a bounded response from a separately verified service peer. It cannot prove that the worker was launched or safely supervised; the service may emit success only after its own custody and admission gate. A lost reply is ambiguous and must use durable mutation replay, not an automatic fresh submission.
Parameters¶
payload : bytes Complete response frame from a separately peer-verified service. request : StorageNamedAdmissionRequest Exact submitted metadata retained by the trusted API caller. replay : StorageAdmissionReplay Client-computed expected digest of the frozen request and seed bytes. max_bytes : int Positive trusted maximum response-frame payload bytes.
Returns¶
str Correlated admitted job ID; fetch its complete record separately.
Raises¶
StudioJobQueueFull A correlated durable capacity refusal. ValueError Framing, JSON, schema, outcome or request correlation is invalid.
Module studio.platform.storage_artifact_chunks¶
Function receive_artifact_chunks(channel, artifact)¶
Read and verify one declaration under a locally trusted content ceiling.
Parameters¶
channel : socket.socket Exclusively owned storage connection, verified at every frame. artifact : FinishArtifact Strict declaration from the correlated authority response. expected_service_uid : int Configured storage UID. frame_max_bytes, max_artifact_bytes : int Independent frame and complete-content limits configured at the API. deadline : float Absolute deadline shared with the request and declaration transfer.
Returns¶
bytes Exact content after full size and digest verification.
Raises¶
ValueError A local budget is invalid. StudioJobArtifactUnavailable Declared content exceeds the budget, chunks have incorrect boundaries, or the full content digest differs. PermissionError, TimeoutError, EOFError, OSError Peer verification or transfer fails.
Module studio.platform.storage_artifact_client¶
Function artifact_request(workspace, job_id, relative_path)¶
Build a sealed artefact read with a fresh random request ID.
Function exchange_artifact(channel, request)¶
Read one sealed artefact over a connected, exclusively owned stream.
Parameters¶
channel : socket.socket Exclusively owned connection, closed after this exchange. request : StorageArtifactRequest Route-authorised read with a fresh correlation identifier. expected_service_uid : int Configured storage identity, checked for each frame. max_bytes, max_artifact_bytes : int Independent frame and complete-content ceilings from trusted settings. deadline : float Absolute monotonic deadline covering the entire exchange.
Returns¶
StudioJobArtifactPayload Complete bytes after exact chunk, size and digest verification.
Raises¶
PermissionError The peer is not the configured storage identity, or policy denied. KeyError The job or its declared artefact is not in the workspace. StudioJobArtifactUnavailable The authority could not serve trusted bytes, or the received bytes differ from the declaration. ValueError A reply is malformed or answers another request or artefact. TimeoutError, EOFError, OSError The exchange failed; reading again is safe.
Module studio.platform.storage_artifact_protocol¶
Class StorageArtifactRequest¶
Read one declared artefact of a job in the configured workspace.
Class StorageArtifactResponse¶
The declared artefact, or a fixed refusal.
- validate_artifact()
- Exactly an answered read carries the artefact.
Function encode_artifact_message(message)¶
Serialise a validated message as compact, sorted UTF-8 JSON.
Function decode_artifact_request(payload)¶
Decode one exact request frame.
Raises¶
ValueError Size, encoding, duplicate names, unknown fields, route or field is invalid.
Function decode_artifact_response(payload)¶
Decode a response that must answer request and name its artefact.
Raises¶
ValueError The frame is malformed, answers another request, or names another path. PermissionError The route's policy denied the requester. KeyError The job or the declared artefact is not in the workspace. StudioJobArtifactUnavailable The sealed bytes are missing or failed their integrity check.
Module studio.platform.storage_artifact_read¶
Function read_sealed_artifact(root, job_id, artifact)¶
Return the sealed bytes of artifact, or None when they cannot be trusted.
Parameters¶
root : Path
The authority root holding <job_id>/<relative path>.
job_id : str
Job whose sealed directory is read.
artifact : StudioJobArtifact
The declaration from the job's terminal record.
Function serve_artifact_read(channel)¶
Serve one peer-verified sealed artefact read.
Parameters¶
channel : socket.socket Connected Unix stream, closed by this handler on every outcome. ledger : StudioJobLedger Existing authority; its root holds the sealed copies. gateway : PolicyGateway Existing authorisation owner with its audit sink. workspace : str Nonempty server-bound workspace. expected_api_uid : int Configured API identity. max_bytes : int Frame ceiling for metadata and each content chunk. max_artifact_bytes : int Independent complete-content ceiling, checked before opening a seal. deadline : float Absolute monotonic wire deadline. initial_frame : bytes or None First frame already read by the owning listener, if any.
Raises¶
ValueError Configuration, request or workspace is invalid; nothing is answered. PermissionError The peer is not the configured API. TimeoutError, EOFError, OSError Wire transfer fails; reading again is safe. AuditSinkError The policy audit cannot persist its decision; nothing is read.
Module studio.platform.storage_artifact_seal¶
Class SealedArtifactWriter¶
Seal one job's artefacts under a private authority root.
Parameters¶
root : Path Authority root that holds the job ledger; it must be private to this identity. job_id : str Validated job identifier naming the job directory.
- init(root, job_id)
- Hold the authority root and the job directory, creating it if needed.
- seal(relative_path, payload)
- Seal one verified artefact at its canonical job-relative path.
- close()
- Synchronise and release the held job and root directories.
- enter()
- Return this writer for one finish request.
- exit(kind, value, traceback)
- Release the held directories on every outcome.
Module studio.platform.storage_cancel¶
Function apply_cancel(ledger, request)¶
Apply one decoded request whose workspace matched the service.
Function serve_cancel(channel)¶
Serve one peer-verified cancellation after the stop route's policy.
Parameters¶
channel : socket.socket Connected Unix stream, closed by this handler on every outcome. ledger : StudioJobLedger Existing authority. gateway : PolicyGateway Existing authorisation owner with its audit sink. workspace : str Nonempty server-bound workspace. expected_api_uid : int Configured API identity. max_bytes : int Frame ceiling for request and response. deadline : float Absolute monotonic wire deadline. initial_frame : bytes or None First frame already read by the owning listener, if any. max_content_bytes : int, optional Independent total snapshot limit; defaults to event custody plus one frame.
Raises¶
ValueError Configuration, request or workspace is invalid; nothing is answered. PermissionError The peer is not the configured API. TimeoutError, EOFError, OSError Wire transfer fails; repeating the request is safe. AuditSinkError The policy audit cannot persist its decision; nothing is changed.
Module studio.platform.storage_cancel_client¶
Function cancel_request(workspace, job_id)¶
Build a cancellation with a fresh random request ID.
Function exchange_cancel(channel, request)¶
Run one cancellation over a connected, exclusively owned stream.
Individual frames obey max_bytes; the complete snapshot independently
obeys max_content_bytes, defaulting to event custody plus one frame.
Returns¶
StudioJobRecord The job's complete record after the request.
Raises¶
PermissionError The peer is not the configured storage identity, or policy denied. KeyError The job is not in the workspace. ValueError The reply is malformed, answers another request, or names another job. TimeoutError, EOFError, OSError The exchange failed; repeating the request is safe.
Module studio.platform.storage_cancel_protocol¶
Class StorageCancelRequest¶
Record that one job of the configured workspace should stop.
Class StorageCancelResponse¶
The job's record after the request, or a fixed refusal.
- validate_record()
- Exactly an answered request carries the record.
Function encode_cancel_message(message)¶
Serialise a validated message as compact, sorted UTF-8 JSON.
Function decode_cancel_request(payload)¶
Decode one exact request frame.
Raises¶
ValueError Size, encoding, duplicate names, unknown fields or any field is invalid.
Function decode_cancel_response(payload)¶
Decode a response and require that it answers request.
Raises¶
ValueError The frame is malformed or answers another request or job. PermissionError The authority's policy denied the requester. KeyError The job is not in the workspace.
Module studio.platform.storage_configuration¶
Class StorageBoundaryConfiguration¶
Immutable role, path and resource intent, not proof of OS isolation.
Core fields are required. An optional view-content ceiling defaults to the existing event custody limit plus one frame. Three non-root OS identities must differ. Storage, spool and socket-parent trees must be canonical absolute disjoint paths. Limits carry explicit frame, metadata, seed, artefact, transfer and connection budgets. Actual ownership, ACLs, launcher and endpoint lifecycle are checked separately before a future isolated runtime can create its ledger or listener.
- validate_boundary()
- Refuse collapsed identities and overlapping or aliased namespaces.
Function parse_storage_boundary(value)¶
Decode explicit operator JSON without defaults or persistent side effects.
Parameters¶
value : str or None Boundary JSON from trusted configuration; absence preserves no boundary.
Returns¶
StorageBoundaryConfiguration or None Validated intent, never evidence of a launched isolated service.
Raises¶
ValueError JSON, duplicate fields, types, identity, paths or limits are invalid.
Module studio.platform.storage_connection¶
Function connect_storage_authority(configuration)¶
Return one peer-verified stream from the configured API identity.
The caller exclusively owns and closes the returned connection. This confirms endpoint and kernel peer identity before any frame is sent; it does not authenticate a browser principal or enable the isolated runtime. No path, credential or UID is accepted from a worker request.
Module studio.platform.storage_dispatch¶
Class StorageServices¶
The authority's collaborators and the configured limits they serve with.
admission serves the status view; admit_named and
authority_dirfd serve named admission. An operation whose collaborator
is absent is refused before its request is decoded.
Function serve_operation(channel, metadata, services)¶
Serve the operation named by metadata on channel.
Parameters¶
channel : socket.socket Connected stream whose peer and first frame the caller verified. metadata : bytes That first frame. services : StorageServices The service's collaborators and limits. deadline : float Absolute monotonic wire deadline.
Raises¶
ValueError The frame names no supported operation or its handler refused it. PermissionError A collaborator the operation needs is not configured, or a handler's peer or policy check refused. TimeoutError, EOFError, OSError Wire transfer fails.
Module studio.platform.storage_event_admission¶
Class EventAdmissionEnvelope¶
Small admission request bound to one separately transferred event declaration.
Function compact_event_admission(payload, training_config)¶
Separate a validated event contract while preserving all other request fields.
Parameters¶
payload, training_config : dict or None Full process payload and the corresponding training snapshot.
Returns¶
tuple Small payload, small snapshot and canonical event bytes, when present.
Raises¶
ValueError Configuration, event custody budget or payload/snapshot identity differs.
Function encode_event_admission(request)¶
Freeze a bounded header and the separately bounded event declaration.
Parameters¶
request : StorageNamedAdmissionRequest Full typed admission before transfer. max_metadata_bytes : int Unchanged metadata ceiling for the complete header.
Returns¶
tuple Exact metadata frame and optional canonical event content.
Function decode_event_admission(metadata)¶
Read a small request without receiving content before policy authorization.
Parameters¶
metadata : bytes Peer-verified bounded first frame. max_metadata_bytes : int Unchanged complete metadata ceiling.
Returns¶
tuple Small request and optional bounded event transfer declaration.
Function send_event_admission_content(channel, content)¶
Send admitted event bytes as exact frames under one deadline and peer UID.
Parameters¶
channel : socket.socket Exclusively owned authority connection. content : bytes, optional Canonical declaration returned by the admission encoder. expected_uid : int Configured storage identity. frame_max_bytes : int Unchanged positive per-frame ceiling. deadline : float Absolute transfer deadline shared with metadata and seeds.
Function receive_event_admission_content(channel, request, envelope)¶
Verify all declared bytes and restore the request only after authorization.
Parameters¶
channel : socket.socket Authorized API connection. request : StorageNamedAdmissionRequest Small request decoded from its first frame. envelope : EventAdmissionEnvelope, optional Typed declaration bounded by the existing 64 MiB event custody limit. expected_uid : int Configured API identity. frame_max_bytes : int Unchanged per-frame ceiling. deadline : float Same absolute transfer deadline as metadata and seeds.
Returns¶
StorageNamedAdmissionRequest Full request after exact frame lengths, content SHA and references agree.
Raises¶
ValueError Content length, SHA, configuration reference or canonical JSON differs.
Module studio.platform.storage_event_worker_configuration¶
Class EventJuliaRuntime¶
An explicit installed JuliaCall runtime, with one thread and signal policy.
The operator must provision a compatible PythonCall project beforehand. Declaring this object opts into Julia decoding; no package is installed.
- validate_runtime()
- Require existing operator executable and project paths.
Class EventWorkerConfiguration¶
Operator-owned event root, input budget and optional native decoders.
Paths must be readable by the configured compute identity. Validation checks their current availability to the launcher; it does not prove worker access, dependency compatibility or immutable file custody.
- validate_recordings()
- Require an existing root and existing absolute native library files.
- environment()
- Build only the declared event settings for the fixed worker environment.
Module studio.platform.storage_finish¶
Function decide_finish(ledger, request)¶
Decide whether the verified API generation may finish this job now.
Parameters¶
ledger : StudioJobLedger
Existing storage authority.
request : StorageFinishRequest
Decoded request whose workspace already matched the service.
supervisor : str
host:pid:token of the pidfd-verified API peer.
Returns¶
tuple
("ready", None) to receive artefacts, or a final reply and reason.
Function commit_finish(ledger, request)¶
Commit the terminal record for sealed artefacts and settle its capacity.
Both writes are one transaction: a crash never leaves a terminal job that
still holds its reservation, which an identical retry could not release.
An unreaped worker keeps the reservation, marked unreaped, as the
embedded supervisor does.
Parameters¶
ledger : StudioJobLedger Existing storage authority. request : StorageFinishRequest Request whose artefacts are already sealed. supervisor : str Delegated owner verified before the artefacts were received.
Returns¶
tuple
sealed, or the answer for a job that became terminal meanwhile.
Function serve_finish(channel)¶
Serve one peer-verified finish exchange and write its final answer.
Parameters¶
channel : socket.socket Connected Unix stream, closed by this handler on every outcome. ledger : StudioJobLedger Existing authority; artefacts are sealed under its root. workspace : str Nonempty server-bound workspace. expected_api_uid : int Configured API identity. frame_max_bytes : int Ceiling for every frame, including one artefact. max_artifact_bytes, max_artifact_entries : int Trusted aggregate artefact budgets. deadline : float Absolute monotonic deadline for the whole exchange. initial_frame : bytes or None First frame already read by the owning listener, if any.
Raises¶
ValueError Configuration, request, workspace or manifest is invalid; nothing is answered or sealed. PermissionError The peer is not the configured API or its generation cannot be proved. TimeoutError, EOFError, OSError Wire transfer fails; bytes sealed before the failure are only retained for an identical retry.
Module studio.platform.storage_finish_chunks¶
Class FinishChunkMismatch¶
An otherwise framed chunk does not match its declared artefact position.
Function receive_finish_artifact(channel)¶
Read exact full-size chunks and a final remainder under one deadline.
Parameters¶
channel : socket.socket Exclusively owned API connection, with identity checked per frame. size_bytes : int Declared size already admitted under the aggregate artefact budget. sha256 : str Manifest digest to verify over the complete received bytes. expected_api_uid : int Operator-configured API identity. frame_max_bytes : int Positive maximum frame payload; every nonfinal chunk has this size. deadline : float Absolute monotonic deadline shared by the complete finish operation.
Returns¶
bytes Complete content for independent digest verification before sealing. An empty artefact consumes no frames.
Raises¶
ValueError Limits or chunk sizes are invalid. PermissionError, TimeoutError, EOFError, OSError Verified transfer cannot finish. No content is sealed here.
Module studio.platform.storage_finish_client¶
Function spool_finish_request(job_directory)¶
Build a finish request and its artefact bytes from a stopped worker's spool.
Parameters¶
job_directory : int
Held descriptor of <spool>/<job>/<generation>/<job>.
workspace, job_id : str
Configured workspace and the admitted job.
outcome : FinishOutcome or None
The API's own verdict (cancelled/timed_out/failed) or
None to use the worker's report: completed only when the worker
reported completion and exited with status 0, as embedded.
exit_status : int or None
Leader exit status reported by the launcher, if it ran.
frame_max_bytes : int
Ceiling for the result metadata and each artefact chunk frame.
max_artifact_bytes, max_artifact_entries : int
Aggregate budgets the authority enforces; a worker declaring more is
refused before any artefact is read into memory.
error : str or None
The API's own error for an unsuccessful outcome; otherwise the worker's
error or the embedded supervisor's wording is used.
worker_reaped : bool
Whether the launcher confirmed that every process of the generation
ended.
Returns¶
tuple The validated request and the artefact bytes in manifest order.
Raises¶
ValueError The worker result or an artefact is missing its contract: absent or non-regular files, changed bytes, a digest or size different from the declaration, or an invalid manifest.
Function exchange_finish(channel, request, payloads)¶
Run one finish exchange over a connected, exclusively owned stream.
Parameters¶
channel : socket.socket Connected Unix stream to the storage authority, closed on every outcome. request : StorageFinishRequest Request to send. payloads : sequence of bytes Artefact bytes in manifest order. expected_service_uid : int Configured storage identity, checked before each frame. max_bytes : int Frame ceiling. deadline : float Absolute monotonic deadline for the whole exchange.
Returns¶
StorageFinishResponse The final answer.
Raises¶
ValueError
payloads do not match the manifest, or a reply is malformed.
PermissionError
The peer is not the configured storage identity.
TimeoutError, EOFError, OSError
The exchange failed; whether the authority sealed is unknown.
Module studio.platform.storage_finish_protocol¶
Class FinishArtifact¶
One declared artefact: a canonical job-relative path, its size and digest.
- validate_path()
- Accept only a printable, canonical path that stays inside the job.
Class StorageFinishRequest¶
Report a terminal outcome and declare the artefacts to seal.
As in the embedded supervisor, only completed carries a result and
never an error; failed and timed_out carry an error and
cancelled may. worker_reaped is false when the launcher could not
confirm that every process of the generation ended: the job becomes
terminal but keeps its capacity as unreaped. A completed job was reaped.
Artefact paths are unique; their bytes follow as frames in the listed order.
- validate_outcome()
- Match result, error and reaping to the outcome; refuse duplicate paths.
Class StorageFinishResponse¶
The authority's answer to one finish request.
ready is interim and asks for the artefact frames; every other reply
is final.
- validate_reply()
- Only a refusal carries a reason.
Function validate_artifact_budget(artifacts)¶
Hold declared artefacts to the trusted budgets before any byte moves.
Parameters¶
artifacts : Sequence[FinishArtifact] Declared artefacts, from a request or a worker's own manifest. frame_max_bytes : int Positive ceiling for each chunk frame; artefacts may span frames. max_artifact_bytes, max_artifact_entries : int Aggregate byte and entry budgets from trusted configuration.
Raises¶
ValueError The declaration exceeds a budget.
Function validate_finish_manifest(request)¶
Hold a request's manifest to the trusted artefact budgets.
Raises¶
ValueError
The manifest exceeds a budget; see :func:validate_artifact_budget.
Function encode_finish_message(message)¶
Serialise a validated request or response as sorted compact JSON.
Parameters¶
message : StorageFinishRequest or StorageFinishResponse Already validated message.
Returns¶
bytes UTF-8 JSON.
Function decode_finish_request(payload)¶
Decode one exact request frame from the verified API peer.
Parameters¶
payload : bytes Complete frame payload. max_bytes : int Configured frame ceiling.
Returns¶
StorageFinishRequest Strictly typed request; not an ownership decision.
Raises¶
ValueError Size, encoding, duplicate names, unknown fields or any field shape is invalid.
Function decode_finish_response(payload)¶
Decode a response and require exact correlation with the sent request.
Parameters¶
payload : bytes Complete frame payload from the verified storage peer. request : StorageFinishRequest The request this response must answer. max_bytes : int Configured frame ceiling.
Returns¶
StorageFinishResponse Correlated answer.
Raises¶
ValueError The frame is malformed, inconsistent or answers another request.
Module studio.platform.storage_generation_exchanges¶
Class GenerationRuntime¶
Trusted API settings for supervising launched worker generations.
connect returns a new peer-verified stream to the storage authority,
for example :func:storage_connection.connect_storage_authority bound to
the boundary configuration. max_artifact_bytes is the worker's
per-artefact budget; artifact_total_bytes and artifact_entries are
the aggregate budgets the authority enforces. attempts bounds each
resolution loop; transfer_timeout_seconds bounds each single exchange.
live is this API generation's registry of live worker directories.
Class GenerationJob¶
One admitted job whose delegated lease this API generation owns.
Class StartRefused¶
The authority did not register the worker; carries the finish verdict.
- init(outcome, error)
- Keep the outcome and error the job must finish with.
Class GenerationExchanges¶
Bounded exchanges of one API generation for one exact job generation.
- init(runtime)
- Bind the runtime to the job and its 128-bit generation.
- launcher(operation)
- Send one launcher request;
Nonewhen no valid reply arrived. - launch()
- Launch this generation;
Nonewhen no attempt was answered. - stop()
- Stop this generation;
Nonewhen termination was not confirmed. - register(worker)
- Have the authority register the verified worker before its grant.
- heartbeat()
- Renew the delegated lease;
Nonewhen the reply was lost. - finish(request, payloads)
- Deliver the finish, repeating it identically after a lost reply.
Module studio.platform.storage_generation_supervisor¶
Class GenerationSupervisor¶
Supervise one job generation from spool staging to its finish reply.
- init(runtime, job)
- Choose the generation; nothing is staged, launched or sent yet.
- generation()
- Return the 128-bit launch generation of this supervisor.
- run()
- Run the generation to the authority's final finish reply.
Function supervise_generation(runtime, job)¶
Supervise one admitted job's launched generation to its finish reply.
Parameters¶
runtime : GenerationRuntime
Trusted API settings and the storage connection factory.
job : GenerationJob
Admitted job whose delegated lease this API generation owns.
cancel : threading.Event
Set by the API to cancel the job; the worker is stopped and the job
finishes cancelled.
Returns¶
StorageFinishResponse The authority's final reply.
Raises¶
TimeoutError The finish was never answered.
Module studio.platform.storage_isolated_jobs¶
Class IsolatedJobManager¶
Serve the API's job methods through the storage authority and launcher.
- init(runtime, configuration)
- Bind the trusted runtime and boundary; nothing is contacted yet.
- submit_process_task()
- Admit a named process job and supervise its launched worker here.
- generation_failures()
- Return supervised generations that ended without a final finish reply.
- record(job_id)
- Return one record of the configured workspace.
- wait(job_id, timeout_seconds)
- Observe the record until terminal or the deadline, as embedded.
- list_records()
- Return the workspace's records in creation order, scoped when asked.
- list_snapshot()
- Return a path-free snapshot of every visible job.
- purge_snapshot()
- Read one operator purge journal page.
- unreaped_workers()
- Return jobs whose capacity is held because their workers were not reaped.
- status()
- Return aggregate path-free health from the authority's summary.
- cancel(job_id)
- Record the cancellation at the authority; stop a worker supervised here.
- read_artifact(job_id, relative_path)
- Read one sealed artefact through the route the request was authorised for.
- read_live_artifact_bytes(job_id, relative_path)
- Read one bounded slice from a live artefact of a job supervised here.
- send_control_command(job_id)
- Deliver a command and control seeds to a running job supervised here.
- purge_terminal_record(job_id)
- Purge one terminal job and its sealed directory at the authority.
Module studio.platform.storage_isolated_runtime¶
Function build_isolated_job_manager(boundary, launcher)¶
Return the isolated facade for this API process.
Parameters¶
boundary : StorageBoundaryConfiguration Validated identities, roots, workspace and transfer budgets. launcher : LauncherClientSettings Validated launcher endpoint, identity and supervision cadence. allowed_kinds : frozenset[str] Job kinds the API admits. default_timeout_seconds : float Execution timeout for jobs submitted without one. max_artifact_bytes : int Per-artefact budget handed to each worker, as the embedded setting.
Module studio.platform.storage_isolated_submit¶
Class GenerationThreads¶
The generations this API supervises, with their cancel and done events.
- init(runtime)
- Keep the runtime every supervised generation uses.
- failures()
- Return the generations that ended without a final finish reply.
- events(job_id)
- Return the cancel and done events of a supervised job, if any.
- is_service_task(job_id)
- Identify service custody from the admitted generation's registered task.
- start(job)
- Supervise an admitted generation and retain its registered custody.
Function submit_named(configuration, delegation)¶
Admit one named job for the delegated requester.
Returns¶
GenerationJob
The admitted job, ready for :meth:GenerationThreads.start once its
record shows it is still pending.
Raises¶
StudioJobRejected Kind, owner, workspace, task or timeout is not the reviewed contract. StudioJobQueueFull The authority refused for capacity. PermissionError, ValueError, TimeoutError, EOFError, OSError The admission exchange failed or was refused; an identical submission with the same idempotency key is answered with the same job.
Module studio.platform.storage_launcher_client¶
Function new_launcher_request(operation)¶
Build a request with a fresh random request ID.
Parameters¶
operation : {"launch", "stop", "status"}
Requested launcher operation.
job_id : str
Admitted job ID, sj_ plus 16 lowercase hexadecimal digits.
generation : str
Launch generation chosen once per attempt, 32 lowercase hex digits.
Returns¶
LauncherRequest Validated request.
Raises¶
pydantic.ValidationError An identifier does not match the wire grammar.
Function exchange_launcher_request(socket_path, request)¶
Deliver one request to the verified launcher and return its reply.
Parameters¶
socket_path : Path Configured launcher endpoint. request : LauncherRequest Request to send. launcher_uid : int Configured launcher identity that must own the accepting socket. deadline : float Absolute monotonic deadline for connect, send and receive.
Returns¶
LauncherResponse
Reply correlated with request.
Raises¶
PermissionError The endpoint is not owned by the configured launcher identity; no request bytes were sent. TimeoutError The deadline expired; whether the launcher acted is unknown. EOFError The launcher closed without a reply; whether it acted is unknown. ValueError The reply is malformed or does not answer this request. OSError The endpoint is missing or the transfer failed.
Module studio.platform.storage_launcher_client_settings¶
Class LauncherClientSettings¶
How the API reaches the launcher and supervises launched generations.
- canonical_socket(cls, value)
- Accept only an absolute canonical endpoint path.
Function parse_launcher_client(value)¶
Decode operator JSON for the launcher client; absence means none.
Raises¶
ValueError JSON, duplicate fields, types or values are invalid.
Module studio.platform.storage_launcher_configuration¶
Class LauncherConfiguration¶
Operator-owned launcher configuration; no request can change it.
python_path lists the import roots given to the fixed bootstrap. The
worker ceilings are passed to the bootstrap, which applies them before
reading any request data. max_records bounds retained generation
records used to answer lost-reply status queries.
event_input declares local recordings and native runtimes separately
from the API environment; job requests cannot set these paths.
- validate_paths()
- Require absolute normalised paths and at least one worker import root.
Function load_launcher_configuration(path)¶
Read the operator configuration file with strict, duplicate-free JSON.
Parameters¶
path : Path Operator-owned configuration file.
Returns¶
LauncherConfiguration Validated configuration.
Raises¶
ValueError Size, JSON or any field is invalid. OSError The file cannot be read.
Module studio.platform.storage_launcher_endpoint¶
Class LauncherEndpoint¶
Bind, and later remove, exactly one launcher socket inode.
The socket parent must be owned by the launcher and grant at most group traversal, so only the configured socket group (the API) can reach it. An existing entry is never adopted; shutdown unlinks only the unchanged inode this endpoint created.
- init(socket_path)
- Retain the configured endpoint path; nothing is bound yet.
- open()
- Bind and listen on a new socket through the held parent directory.
- close()
- Remove the endpoint only if it is still the inode this object bound.
Module studio.platform.storage_launcher_protocol¶
Class LauncherRequest¶
One operation for an exact admitted job generation.
generation is chosen by the API once per launch attempt and reused for
retries of that attempt, so a retry can never create a second generation.
Class LauncherResponse¶
The launcher's observed state for the requested job generation.
running carries the launched worker PID and its process start token.
stopped means the launcher confirmed that no process of the generation
it tracks remains, and carries the leader's exit status as
:attr:subprocess.Popen.returncode reports it. absent means this launcher has no record of the
generation. refused carries a fixed reason; with survivors a stop
could not yet confirm termination and the identity is retained.
- validate_state()
- Require the identity and reason fields that belong to each state.
Function encode_launcher_request(request)¶
Serialise a validated request as canonical bounded JSON.
Parameters¶
request : LauncherRequest Already validated request.
Returns¶
bytes
Sorted, compact UTF-8 JSON within :data:LAUNCHER_MESSAGE_MAX_BYTES.
Function decode_launcher_request(payload)¶
Decode one exact request frame received from the verified API peer.
Parameters¶
payload : bytes Complete frame payload.
Returns¶
LauncherRequest Strictly typed request; not an authorisation of the job itself.
Raises¶
ValueError Size, encoding, duplicate names, unknown fields, version or any field shape is invalid.
Function encode_launcher_response(response)¶
Serialise a validated response as canonical bounded JSON.
Parameters¶
response : LauncherResponse Already validated response.
Returns¶
bytes
Sorted, compact UTF-8 JSON within :data:LAUNCHER_MESSAGE_MAX_BYTES.
Function decode_launcher_response(payload)¶
Decode a response and require exact correlation with the sent request.
Parameters¶
payload : bytes Complete frame payload from the verified launcher peer. request : LauncherRequest The request this response must answer.
Returns¶
LauncherResponse Correlated launcher observation.
Raises¶
ValueError The frame is malformed, inconsistent, or answers a different request, operation, job or generation.
Module studio.platform.storage_launcher_service¶
Function main(argv)¶
Run the launcher service until SIGTERM or SIGINT.
Parameters¶
argv : Sequence[str] or None
--configuration PATH; None reads sys.argv.
Returns¶
int
0 after an orderly stop. Startup refusal raises instead.
Notes¶
ready is printed once the endpoint accepts connections. A refused or
malformed connection is closed and the service continues; it never
stops running workers on shutdown.
Module studio.platform.storage_listener¶
Class StorageRecordListener¶
Serve one bounded versioned request at a time from the configured API UID.
Startup inspects an existing service-owned namespace and an existing ledger.
It never creates a database, adopts a stale socket, repairs permissions, or
starts a worker. Named admission requires an explicitly supplied trusted
handler that establishes worker custody before returning a durable outcome.
A caller owns the service loop and calls :meth:serve_once repeatedly;
this class does not claim a deployed isolated profile.
- init(configuration)
- Retain explicit configuration and existing authority collaborators.
- start()
- Bind a new socket through held descriptors after strict path checks.
- serve_once()
- Accept and serve one request under finite accept and wire deadlines.
- stop()
- Close the listener and remove only its own unchanged socket inode.
- enter()
- Start the endpoint and return its single owner.
- exit(exc_type, exc_value, traceback)
- Close this listener without suppressing caller failures.
Module studio.platform.storage_live_spool¶
Class LiveSpools¶
This API generation's live worker directories, keyed by job.
- init()
- Keep
retainfinished directories; bound each control seed. - attach(job_id, work)
- Hold a duplicate of a staged worker directory for
job_id. - retire(job_id)
- Mark an attached
job_idfinished; close the oldest beyond the bound. - close()
- Close every held directory.
- read(job_id, relative_path)
- Return up to
max_bytesappended afteroffsetand the new offset. - deliver(job_id, command, seeds)
- Publish control seeds, then the command, into the job's live spool.
Module studio.platform.storage_mode¶
Function parse_storage_mode(value)¶
Parse the explicit environment selection without an unknown-value fallback.
An absent value preserves embedded compatibility. Empty, misspelled and
differently cased values raise ValueError; whitespace is stripped.
Parsing isolated expresses intent, not availability or qualification.
Parameters¶
value:
Environment value, or None when the option is absent.
Returns¶
StudioStorageMode Validated selection, without creating storage or changing permissions.
Raises¶
ValueError The supplied value is empty or not a supported mode name.
Function require_available_storage(mode)¶
Refuse an unknown storage selection before any runtime collaborator exists.
Embedded storage preserves the existing non-isolated filesystem contract.
Isolated startup additionally requires every check of
:func:storage_preflight.require_isolated_preflight to pass before any
collaborator is created; it never falls back to a local ledger.
Parameters¶
mode: Validated storage selection from runtime settings.
Raises¶
ValueError The caller supplied an unknown mode despite the typed contract.
Module studio.platform.storage_named_admission¶
Class PreparedNamedAdmission¶
Authorized service inputs with verified seed content and peer custody.
This value is not an admitted job. The service must establish a launcher
handshake and then call its transactional admission owner; disconnects
before that point have not created a replay outcome or reserved capacity.
The exact bounded request is retained as bytes so later code cannot mutate
nested payload or control mappings after replay identity was derived.
seed_files owns unlinked service files only until the listener returns
its response; the admission handler must transfer them before returning.
seed_inputs remains the bounded byte path for direct callers.
Function prepare_named_admission(channel)¶
Read and authorize a real connected API request without ledger mutation.
Event content follows a bounded header only after policy authorization; the restored request is retained under the separate event custody limit.
Parameters¶
channel : socket.socket Exclusively owned connected Unix stream from the configured API UID. gateway : PolicyGateway Existing route-policy audit authority; a failed audit refuses. workspace : str Server-configured scope, never selected by the request. expected_api_uid : int Trusted configured API OS identity. frame_max_bytes, max_metadata_bytes : int Framing and complete metadata byte ceilings. max_seed_bytes, max_seed_entries, max_manifest_bytes : int Explicit aggregate seed, entry and UTF-8 name-byte ceilings. deadline : float Absolute monotonic deadline shared by metadata and all seed frames. initial_frame : bytes or None Optional metadata frame already read through this verified channel by its listener before operation dispatch. Direct callers leave it unset. authority_dirfd : int or None Held private service-authority directory for file-backed seed ingress. When absent, use the existing bounded byte path for direct callers.
Returns¶
PreparedNamedAdmission Authorized named task, actual seed content, service-derived replay key and pidfd-verified API process generation; no job is admitted.
Raises¶
ValueError Request, task, workspace, frame or content contract is invalid. PermissionError Peer identity or the existing route policy refuses the requester. TimeoutError The shared transfer deadline expires. EOFError The peer disconnects before all declared bytes arrive. OSError A socket transfer fails. Any failure closes the ambiguous stream. AuditSinkError The policy audit cannot persist its decision.
Module studio.platform.storage_named_admit¶
Function named_process_admission(admission)¶
Return the service's handler that admits prepared named process jobs.
Parameters¶
admission : SharedJobAdmission The service's configured admission over its ledger. workspace : str The server-bound workspace every admitted job belongs to.
Module studio.platform.storage_named_tasks¶
Class NamedStudioTask¶
One reviewed process task and its preserved ledger and route identities.
name is the only selectable operation ID. kind and owner
preserve the current ledger classification. task_path is passed to a
trusted launcher outside storage; routes constrain policy delegation.
Constructing this value does not authorize or execute the task.
- owner_for(principal_id)
- Derive actor custody from the authenticated delegation when required.
- validate_admission()
- Bind laboratory operation and custody before connection or allocation.
Function resolve_named_studio_task(name)¶
Return one exact reviewed task for an already authorized POST route.
Unknown names and route/task mismatches refuse before any capacity or
filesystem mutation. The returned task_path is metadata for a trusted
launcher, never a module imported by the storage authority.
Parameters¶
name : str Exact operation identifier supplied by the trusted API adapter. authorized_route : str Route authenticated and authorized by the service policy gateway.
Returns¶
NamedStudioTask Preserved kind, service owner and launcher task for that route.
Raises¶
ValueError Name, route or their exact pairing is not in the reviewed catalogue.
Function named_studio_task_for_path(task_path)¶
Return the reviewed task that runs task_path on an authorised route.
The isolated API facade keeps the embedded submit_process_task
signature, whose callers name the task by import path; only a path that
the catalogue names for this exact route becomes a named submission.
Raises¶
ValueError No reviewed task runs that path on this route.
Module studio.platform.storage_namespace¶
Class StorageDirectoryDescriptors¶
Borrowed noninheritable directory handles valid only inside their context.
Callers must not close, retain or delegate these handles to lower-trust processes. Descriptors are ownership evidence for opened objects, not a complete mount, ACL, capability or process-isolation qualification.
Function open_storage_directories(configuration)¶
Hold existing authority and endpoint directories after ownership checks.
Parameters¶
configuration : StorageBoundaryConfiguration Validated role/path intent. Authority and endpoint parent must exist.
Yields¶
StorageDirectoryDescriptors Borrowed handles, closed on acquisition failure or context exit.
Raises¶
PermissionError Platform, current service IDs, ancestor ownership or final modes refuse. OSError A directory cannot be opened, including missing paths or symlinks.
Notes¶
Performs no mkdir, permission repair, ledger opening or listener binding. Authority mode must be exactly 0700; endpoint parent cannot admit group or other writes. Root/service-owned sticky ancestors are permitted. Privileged namespace changes, non-POSIX permissions and inherited capabilities require separate deployment checks. Same-UID tests do not establish worker isolation.
Module studio.platform.storage_operation¶
Function classify_storage_operation(metadata)¶
Select one exact versioned operation from a peer-verified frame.
The owning listener limits and authenticates the frame before calling this function. Each selected handler still validates the full operation schema.
Module studio.platform.storage_peer¶
Class StoragePeer¶
Linux PID/UID/GID at connection creation, not live process custody.
The PID is not a process generation token. UID/GID are OS identities, not authenticated HTTP principals or a workspace membership assertion.
Function require_storage_peer(channel)¶
Require an exact configured UID on a connected Linux Unix stream.
Parameters¶
channel : socket.socket Connected, exclusively owned socket. Peer rejection closes it. expected_uid : int Trusted configuration value, never a peer-supplied assertion. Valid OS UID from zero through uint32 maximum minus one; booleans are invalid.
Returns¶
StoragePeer Kernel-reported connection credentials. No liveness guarantee is implied.
Raises¶
ValueError Expected UID is invalid; no socket operations are attempted. PermissionError The platform/transport/peer is unsupported, unknown or not permitted. The rejected socket is closed without transferring framed bytes.
Function require_storage_supervisor_identity(channel)¶
Bind a connected trusted API peer to its kernel-anchored process generation.
The peer pidfd must still refer to the SO_PEERCRED PID while its proc start token is read. An exited peer, unsupported pidfd option or unavailable start token refuses before admission. The returned identity is suitable for the existing ledger lease, not a browser authorization decision.
Function read_verified_frame(channel)¶
Verify the OS peer before receiving a bounded storage frame.
Parameters¶
channel : socket.socket Exclusively owned connected Unix stream. expected_uid : int Trusted peer UID; not an application role or principal assertion. max_bytes : int Positive uint32 payload ceiling passed to the existing framing owner. deadline : float Absolute monotonic deadline, not renewed by peer verification.
Returns¶
bytes Complete nonempty payload from the verified connection.
Raises¶
PermissionError Peer verification refuses before any frame read. ValueError UID, frame limit, deadline or declared length is invalid. TimeoutError The original deadline expires. EOFError The peer closes before a complete frame arrives. OSError Frame transfer fails; the ambiguous socket is closed.
Function write_verified_frame(channel, payload)¶
Verify the OS peer before sending a bounded storage frame.
Parameters¶
channel : socket.socket Exclusively owned connected Unix stream. payload : bytes Nonempty payload within the explicit byte ceiling. expected_uid : int Trusted peer UID, checked before sending even a length header. max_bytes : int Positive uint32 payload ceiling passed to the framing owner. deadline : float Absolute monotonic deadline, not renewed by peer verification.
Raises¶
PermissionError Peer verification refuses before any frame write. ValueError UID, payload, frame limit or deadline is invalid. TimeoutError The original deadline expires. OSError Frame transfer fails; the ambiguous socket is closed.
Module studio.platform.storage_preflight¶
Class PreflightFailure¶
One failed check and why it failed.
Function isolated_preflight(settings)¶
Return every failed check for an isolated API with settings.
Parameters¶
settings : StudioRuntimeSettings
The runtime settings the API would start with.
sysctl_root : Path
Directory holding the fs link-protection values; the host's
/proc/sys/fs unless a caller inspects another tree.
Returns¶
tuple of PreflightFailure Empty when every check passed.
Function require_isolated_preflight(settings)¶
Refuse to start an isolated API while any check fails.
Returns¶
tuple The checked storage boundary and launcher client settings.
Raises¶
RuntimeError Names every failed check.
Module studio.platform.storage_purge¶
Class AuthorityCustody¶
The authority as a purge owner: its ledger and root, no local handles.
- init(ledger)
- Bind purging to the authority's ledger and the root that holds it.
Function apply_purge(custody, request)¶
Apply one decoded request whose workspace matched the service.
Function serve_purge(channel)¶
Serve one peer-verified purge after the archive purge route's policy.
Parameters¶
channel : socket.socket Connected Unix stream, closed by this handler on every outcome. custody : AuthorityCustody The authority's ledger and root. gateway : PolicyGateway Existing authorisation owner with its audit sink. workspace : str Nonempty server-bound workspace. expected_api_uid : int Configured API identity. max_bytes : int Frame ceiling for request and response. deadline : float Absolute monotonic wire deadline. initial_frame : bytes or None First frame already read by the owning listener, if any. max_content_bytes : int or None Independent complete snapshot ceiling, validated before purging.
Raises¶
ValueError Configuration, request or workspace is invalid; nothing is purged. PermissionError The peer is not the configured API. TimeoutError, EOFError, OSError Wire transfer fails; read the record to learn whether it was purged. AuditSinkError The policy audit cannot persist its decision; nothing is purged.
Module studio.platform.storage_purge_client¶
Function purge_request(workspace, job_id)¶
Build a purge with a fresh random request ID.
Function exchange_purge(channel, request)¶
Run one purge over a connected, exclusively owned stream.
Frames obey max_bytes; the full pre-purge snapshot independently obeys
max_content_bytes, defaulting to event custody plus one frame.
Returns¶
StudioJobRecord The record as it was before the purge.
Raises¶
PermissionError The peer is not the configured storage identity, or policy denied. KeyError The job is not in the workspace. StudioJobRejected The ledger refused the purge. ValueError The reply is malformed or names another job. TimeoutError, EOFError, OSError The exchange failed; read the record to learn whether it was purged.
Module studio.platform.storage_purge_protocol¶
Class StoragePurgeRequest¶
Purge one terminal job of the configured workspace.
Class StoragePurgeResponse¶
The purged record, a refusal text, or a fixed status.
- validate_outcome()
- Require a record for success and the ledger's reason for refusal.
Function encode_purge_message(message)¶
Serialise a validated message as compact, sorted UTF-8 JSON.
Function decode_purge_request(payload)¶
Decode one exact request frame.
Raises¶
ValueError Size, encoding, duplicate names, unknown fields or any field is invalid.
Function decode_purge_response(payload)¶
Decode a response and require that it answers request.
Raises¶
ValueError The frame is malformed or answers another request or job. PermissionError The authority's policy denied the requester. KeyError The job is not in the workspace. StudioJobRejected The ledger refused the purge; the message is the ledger's.
Module studio.platform.storage_query¶
Function apply_query(ledger, admission, request)¶
Answer one decoded request whose workspace matched the service.
Returns¶
bytes
The encoded response, within max_bytes.
Function serve_query(channel)¶
Serve one peer-verified query after the route's policy allowed it.
Parameters¶
channel : socket.socket Connected Unix stream, closed by this handler on every outcome. ledger : StudioJobLedger Existing authority; read only. admission : SharedJobAdmission The service's configured admission, for occupancy and limits. gateway : PolicyGateway Existing authorisation owner with its audit sink. workspace : str Nonempty server-bound workspace. expected_api_uid : int Configured API identity. max_bytes : int Frame ceiling for request and response. deadline : float Absolute monotonic wire deadline. initial_frame : bytes or None First frame already read by the owning listener, if any. max_content_bytes : int, optional Independent total page ceiling; defaults to the event custody ceiling plus one frame. Oversized records are refused without truncation.
Raises¶
ValueError Configuration, request or workspace is invalid; nothing is answered. PermissionError The peer is not the configured API. TimeoutError, EOFError, OSError Wire transfer fails. AuditSinkError The policy audit cannot persist its decision; nothing is read.
Module studio.platform.storage_query_client¶
Class QueryReader¶
Read whole views through a connection factory and bounded exchanges.
- init(connect)
- Keep the trusted endpoint settings; nothing is sent yet.
- records(requester)
- Return every record of the workspace in creation order.
- status(requester)
- Return the authority's aggregate summary for the workspace.
- purges(requester)
- Return one operator purge journal page.
Class StatusSummary¶
The authority's workspace summary, exactly as it serialises it.
- snapshot()
- Return the embedded status shape for this summary.
Function query_request(workspace, view)¶
Build a query with a fresh random request ID.
Raises¶
pydantic.ValidationError A field does not match the wire grammar.
Function exchange_query(channel, request)¶
Run one query over a connected, exclusively owned stream.
Each frame obeys max_bytes; the complete reply independently obeys
max_content_bytes, defaulting to the event custody ceiling plus one
frame. All frames share the original absolute deadline and peer identity.
Raises¶
PermissionError The peer is not the configured storage identity, or policy denied. ValueError The reply is malformed, answers another request or refused the cursor. TimeoutError, EOFError, OSError The exchange failed; reading again is safe.
Module studio.platform.storage_query_pages¶
Function fit_page(request, items, more)¶
Encode the longest prefix of items whose response fits the content limit.
Each item is measured by its own compact encoding plus one separator, and the envelope is measured with a cursor of full length, so the estimate never undercounts the encoded page. A shortened page carries a cursor to its last item, so the API continues where it stopped.
Raises¶
ValueError A single item does not fit the content limit: a configuration fault.
Function read_record_page(ledger, request)¶
Materialize only records that fit the independently bounded page.
Parameters¶
ledger : StudioJobLedger Authorized service ledger, read without transitions or recovery. request : StorageQueryRequest Workspace-bound records query and creation-order cursor. max_bytes : int Trusted total page ceiling, distinct from the wire frame limit.
Returns¶
tuple or None Complete records and whether another record remains; None for an unknown cursor. A cursor always names the last returned record, so budget cutoff never loses the first excluded item.
Raises¶
ValueError One complete record cannot fit the configured total page budget.
Notes¶
At most one next row is decoded beyond the returned page's memory. SQLite rows are consumed incrementally; a thousand 64 MiB declarations are never fetched into one Python list before the page budget is applied.
Module studio.platform.storage_query_protocol¶
Class StorageQueryRequest¶
One bounded read; status takes no cursor.
- validate_cursor()
- Refuse a cursor on the aggregate view.
Class StorageQueryResponse¶
The authority's answer; items and summary belong to the requested view.
- validate_view()
- Only an answered page carries items or a cursor; only status a summary.
Function encode_query_message(message)¶
Serialise a validated message as compact, sorted UTF-8 JSON.
Function decode_query_request(payload)¶
Decode one exact request frame.
Raises¶
ValueError Size, encoding, duplicate names, unknown fields or any field is invalid.
Function decode_query_response(payload)¶
Decode a response and require that it answers request.
Raises¶
ValueError The frame is malformed or answers another request or view, or the cursor was refused. PermissionError The authority's policy denied the requester.
Module studio.platform.storage_record¶
Function serve_record_read(channel)¶
Serve one peer-verified read with policy evaluation before ledger lookup.
Parameters¶
channel : socket.socket Connected Unix stream, owned and closed by this handler on every outcome. ledger : StudioJobLedger Existing authority; no client-selected root, SQL or embedded fallback. gateway : PolicyGateway Existing authorization owner with its configured audit sink. workspace : str Nonempty server-bound scope; a request cannot select another workspace. expected_api_uid : int Trusted API OS identity, distinct from workers in a qualified deployment. max_bytes : int Explicit byte limit for the request and each response frame. deadline : float Absolute monotonic wire deadline. Audit/SQLite execution has separate bounds; this is not a service-wide scheduling deadline. initial_frame : bytes or None Optional first frame already read through the same peer-verified channel by the owning listener. Direct callers leave this unset. max_content_bytes : int, optional Independent total response ceiling; defaults to the event custody ceiling plus one frame.
Raises¶
ValueError Configuration or wire request is invalid, or response exceeds its limit. PermissionError The connection peer is not the configured trusted API. TimeoutError A wire transfer exceeds the deadline. EOFError Peer disconnects during a frame. OSError Socket transfer fails. AuditSinkError Existing policy audit cannot persist its decision; no record is sent.
Notes¶
Denied/missing reads return path-free outcomes, not internal exception text. Admin access remains cross-owner within the server-bound workspace. No job state, reservation, lease or transition is changed by this operation.
Module studio.platform.storage_record_client¶
Function read_storage_record(channel)¶
Exchange one bounded request with a peer-verified storage authority.
Parameters¶
channel : socket.socket Connected Unix stream, exclusively owned and closed on every outcome. request : StorageRecordRequest Exact validated read request. Requester claims must come from the trusted API authentication adapter, never directly from a compute worker. expected_service_uid : int Service OS identity supplied by trusted configuration, not the peer. max_bytes : int Positive uint32 ceiling for each complete request and response frame. deadline : float Absolute monotonic deadline shared by both transfers, never renewed. max_content_bytes : int, optional Independent total response ceiling, checked before content receipt.
Returns¶
StudioJobRecord Complete correlated native snapshot, without creating a local ledger.
Raises¶
ValueError Configuration, framing, schema, correlation or snapshot is invalid. PermissionError Service peer identity or authority policy refuses the operation. KeyError Authority reports no record in the configured workspace. TimeoutError The transfer deadline expires. EOFError The authority disconnects before a complete response arrives. OSError Socket transfer fails.
Notes¶
No reconnect, retry, mutation, local fallback or isolated readiness claim. Connection establishment and protected endpoint configuration belong to the runtime lifecycle owner; this function consumes an already connected socket.
Function read_storage_record_at_endpoint(configuration)¶
Read one record over the configured, peer-verified service endpoint.
The caller must construct request.requester from the API's authenticated
principal. The server independently checks policy and binds the workspace.
A failed connection or read has no local ledger fallback and no retry.
Connection and frame exchange each have the configured finite timeout.
Module studio.platform.storage_record_protocol¶
Class StorageRequester¶
Exact delegated principal claim from the configured trusted API peer.
Class StorageRecordRequest¶
Versioned read-only operation, keeping trace and requester separate.
Class StorageRecordResponse¶
Exact read outcome; success requires a complete domain snapshot.
Function decode_record_request(payload)¶
Decode a bounded exact request without accepting ambiguous JSON objects.
Parameters¶
payload : bytes UTF-8 JSON payload already bounded by the peer-verified frame reader.
Returns¶
StorageRecordRequest Strict typed request, not an authorization decision.
Raises¶
ValueError Encoding, nesting, duplicate keys, constants, fields or types are invalid.
Notes¶
Nullable identity and trace fields remain mandatory. The optional
authorized_route selects only actor-owned laboratory reads; omission
retains the existing administrator read policy and original wire shape.
Workspace and requester checks belong to the authority before ledger access.
Function decode_record_response(payload)¶
Reconstruct one complete correlated record from a bounded response.
Parameters¶
payload : bytes Complete bounded UTF-8 response from the verified storage peer. request : StorageRecordRequest Original request, supplying expected trace, job and workspace.
Returns¶
StudioJobRecord Complete native snapshot; no ledger is constructed on the client.
Raises¶
ValueError Wire schema, JSON, correlation, outcome or snapshot is inconsistent. PermissionError Authority denied the read; no record was supplied. KeyError Authority found no record in the requested workspace.
Notes¶
Trace matching is not replay authentication. The connected peer is verified separately, and errors never expose a partial or mismatched record.
Module studio.platform.storage_requester¶
Class Delegation¶
The allowed request: who asked, through which route, under which trace.
Function delegated(principal)¶
Open the delegation of one authorised request for its duration.
Parameters¶
principal : Principal or None
The gateway-authenticated principal; None for a public route.
method, route : str
The HTTP method and route template the gateway authorised.
request_id : str
The request's trace identifier.
Function current_delegation()¶
Return the delegation of the request being served, if any.
Module studio.platform.storage_seed_files¶
Class ReceivedStorageSeedFile¶
One logical seed and the digest of bytes actually received from the wire.
Class ReceivedStorageSeedFiles¶
Own all private seed handles until admission transfers or rejects them.
- init(files)
- close()
- Release every unlinked seed file, including after a handler error.
- enter()
- exit()
Function receive_storage_seed_files(channel)¶
Stream one bounded transfer into unlinked files under a held authority.
The caller owns the returned handles and must close them after the admission handler has transferred the inputs. The authority directory descriptor remains owned by the caller. No request path becomes a disk path; each temporary file is private to the storage service UID. A failed or ambiguous transfer closes the channel and every staged file.
Module studio.platform.storage_seed_ingress¶
Function validate_storage_seed_manifest(manifest)¶
Validate one declared seed manifest and return deterministic frame order.
Parameters¶
manifest : mapping of str to int Canonical relative seed names and their nonnegative byte lengths. frame_max_bytes : int Positive upper bound for a single nonempty seed frame. max_seed_bytes, max_seed_entries, max_manifest_bytes : int Aggregate byte, entry and UTF-8 name-byte budgets from trusted settings. deadline : float One absolute monotonic transfer deadline.
Returns¶
tuple[str, ...] Validated names sorted in the exact sender/receiver transfer order.
Raises¶
ValueError Manifest, path, size, limits or deadline shape is invalid. TimeoutError The deadline has already expired.
Notes¶
The service and API client share this path, byte and resource contract. Validation does not read a socket or grant admission authority.
Function receive_storage_seeds(channel)¶
Read exactly the declared seeds in sorted-name order on one Unix stream.
The manifest is metadata already decoded from a bounded request frame. Each nonempty seed uses one or more nonempty frames, with no renewed deadline. Zero-byte seeds use no frames. The returned bytes are suitable for service-derived replay hashing; no claimed checksum is trusted. The caller still owns authorization, peer-process custody, the one-request connection lifecycle and the worker handoff.
Parameters¶
channel : socket.socket Exclusively owned connected Unix stream. manifest : mapping of str to int Exact relative seed names and declared byte lengths from a bounded versioned request; no checksum or path is trusted as an authority. expected_api_uid : int Service-configured OS identity of the trusted API process. frame_max_bytes : int Positive maximum payload size of each nonempty frame. max_seed_bytes, max_seed_entries, max_manifest_bytes : int Explicit aggregate seed, entry and UTF-8 name-byte ceilings. deadline : float Absolute monotonic deadline shared by every frame in this transfer.
Returns¶
dict[str, bytes] Complete received seed content, keyed by its validated relative name.
Raises¶
ValueError Manifest, limits, frame length or deadline is invalid. PermissionError The connected peer does not have the configured API identity. TimeoutError The deadline expires, including a zero-byte transfer. EOFError The peer closes before all declared bytes arrive. OSError The socket transfer fails. Errors after validation close the stream.
Function send_storage_seeds(channel)¶
Send received API seed bytes in the receiver's deterministic order.
The caller places manifest in its preceding versioned request frame.
This function checks it against a snapshot of the exact bytes before any
seed frame. Invalid content refuses before transfer; an ambiguous transfer
closes without retry. The caller owns the connection afterward.
Parameters¶
channel : socket.socket Exclusively owned connected Unix stream. seed_inputs : mapping of str to bytes Immutable seed bytes from the authenticated API request. manifest : mapping of str to int Name/size declarations already sent in the bounded request frame. expected_service_uid : int Trusted configured service OS identity. frame_max_bytes : int Positive maximum payload size of each nonempty frame. max_seed_bytes, max_seed_entries, max_manifest_bytes : int Explicit aggregate seed, entry and UTF-8 name-byte ceilings. deadline : float Absolute monotonic deadline shared by every frame in this transfer.
Raises¶
ValueError Seeds, limits or deadline are invalid before transfer. PermissionError The connected peer is not the configured service identity. TimeoutError The absolute transfer deadline expires. OSError The socket transfer fails. Ambiguous transfers close the stream.
Module studio.platform.storage_service¶
Class StorageServiceConfiguration¶
The boundary plus the service-owned admission limits, audit and cadence.
Class StorageService¶
The authority's ledger, admission, gateway and listener for one run.
- init(configuration)
- Open the ledger and collaborators; nothing is bound yet.
- reconcile()
- Finish committed purges, resolve abandoned jobs, release proven capacity.
- serve_once()
- Serve one request, or reconcile when idle and the interval elapsed.
Function load_service_configuration(path)¶
Read and strictly validate the service configuration file.
Raises¶
ValueError JSON, duplicate fields, types, values or the boundary are invalid. OSError The file cannot be read.
Function main(argv)¶
Run the storage authority until SIGTERM or SIGINT.
Parameters¶
argv : Sequence[str] or None
--configuration PATH; None reads sys.argv.
Returns¶
int
0 after an orderly stop. Startup refusal raises instead.
Module studio.platform.storage_spool_staging¶
Class StagedGeneration¶
Held descriptors of one staged generation and its worker directory.
The caller owns both descriptors and closes them with :meth:close; they
are never passed to a worker.
- close()
- Close both held descriptors.
- enter()
- Return this staged generation.
- exit(exc_type, exc_value, traceback)
- Close the descriptors without suppressing caller failures.
Function canonical_parts(relative_path)¶
Return the components of a printable, canonical, confined relative path.
Raises¶
ValueError The path is not text, not printable, escapes, or is not canonical.
Function stage_generation(spool_root, descriptor)¶
Create one generation's inputs and worker directory in the compute spool.
Parameters¶
spool_root : Path Absolute compute spool root from trusted configuration. descriptor : WorkerDescriptor Validated descriptor naming the job, generation and task. payload : bytes Task payload JSON already validated for this job. seeds : Mapping[str, bytes] Submission seeds by canonical relative path. group : int Compute group that must read the inputs and write the worker directory.
Returns¶
StagedGeneration Held generation and worker directories.
Raises¶
ValueError The spool root is relative or a seed path is not canonical. PermissionError A reused job directory has other ownership or mode. FileExistsError The generation, or any entry inside it, already exists. OSError A directory or file cannot be created, owned or written.
Module studio.platform.storage_supervision¶
Function apply_supervision(ledger, request)¶
Apply one decoded request on behalf of the verified API generation.
Parameters¶
ledger : StudioJobLedger
Existing storage authority.
request : SupervisionStartRequest or SupervisionHeartbeatRequest
Request whose workspace was already matched to workspace.
supervisor : str
host:pid:token of the pidfd-verified API peer.
workspace : str
Server-configured workspace; jobs elsewhere are reported not found.
Returns¶
StorageSupervisionResponse
Outcome correlated with request.
Function serve_supervision(channel)¶
Serve one peer-verified supervision request and write its outcome.
Parameters¶
channel : socket.socket Connected Unix stream, closed by this handler on every outcome. ledger : StudioJobLedger Existing authority. workspace : str Nonempty server-bound workspace. expected_api_uid : int Configured API identity. max_bytes : int Frame ceiling for request and response. deadline : float Absolute monotonic wire deadline. initial_frame : bytes or None First frame already read by the owning listener, if any.
Raises¶
ValueError Configuration, request or workspace is invalid; nothing is written. PermissionError The peer is not the configured API or its generation cannot be proved. TimeoutError, EOFError, OSError Wire transfer fails.
Module studio.platform.storage_supervision_client¶
Function supervision_start_request(configuration)¶
Build a start request for the configured workspace.
Parameters¶
configuration : StorageBoundaryConfiguration
Trusted boundary configuration supplying the workspace.
job_id : str
Admitted job ID.
worker : str
host:pid:token identity verified at the grant endpoint.
Returns¶
SupervisionStartRequest Validated request with a fresh random request ID.
Function supervision_heartbeat_request(configuration)¶
Build a heartbeat request for the configured workspace.
Parameters¶
configuration : StorageBoundaryConfiguration Trusted boundary configuration supplying the workspace. job_id : str Job whose delegated lease should be renewed.
Returns¶
SupervisionHeartbeatRequest Validated request with a fresh random request ID.
Function exchange_supervision(channel, request)¶
Exchange one request over a connected, exclusively owned stream.
Parameters¶
channel : socket.socket Connected Unix stream to the storage authority, closed on every outcome. request : SupervisionStartRequest or SupervisionHeartbeatRequest Request to send. expected_service_uid : int Configured storage identity, checked before each frame. max_bytes : int Frame ceiling for request and response. deadline : float Absolute monotonic deadline shared by both transfers.
Returns¶
StorageSupervisionResponse
Outcome correlated with request.
Raises¶
ValueError The reply is malformed or answers another request. PermissionError The peer is not the configured storage identity. TimeoutError, EOFError, OSError The exchange failed; whether the authority acted is unknown.
Function exchange_supervision_request(configuration, request)¶
Send one request to the configured, peer-verified storage endpoint.
Parameters¶
configuration : StorageBoundaryConfiguration Trusted endpoint, identities, frame ceiling and transfer timeout. request : SupervisionStartRequest or SupervisionHeartbeatRequest Request for the configured workspace.
Returns¶
StorageSupervisionResponse
Outcome correlated with request.
Raises¶
ValueError The request names another workspace, or the reply is malformed. PermissionError This process is not the configured API identity, or the service peer is not the configured storage identity. TimeoutError, EOFError, OSError The exchange failed; whether the authority acted is unknown.
Module studio.platform.storage_supervision_protocol¶
Class SupervisionStartRequest¶
Mark an admitted job running and bind the observed worker generation.
worker is the host:pid:token identity the API verified at its grant
endpoint; the authority checks it again before registration.
Class SupervisionHeartbeatRequest¶
Renew the delegated owner's lease on a live job.
Class StorageSupervisionResponse¶
The authority's outcome for one supervision request.
started answers start; renewed answers heartbeat;
cancelling answers either for a job whose cancellation is recorded, so
the owning API stops its worker; refused carries a fixed reason and changed nothing
except, for a start of a job already cancelling, its recorded start time.
- validate_outcome()
- Match outcome, operation and reason.
Function encode_supervision_message(message)¶
Serialise a validated request or response as sorted compact JSON.
Parameters¶
message : SupervisionStartRequest, SupervisionHeartbeatRequest or StorageSupervisionResponse Already validated message.
Returns¶
bytes UTF-8 JSON; every field is bounded by the schema.
Function decode_supervision_request(payload)¶
Decode one exact request frame from the verified API peer.
Parameters¶
payload : bytes Complete frame payload. max_bytes : int Configured frame ceiling.
Returns¶
SupervisionStartRequest or SupervisionHeartbeatRequest
Strictly typed request selected by operation; not an ownership
decision.
Raises¶
ValueError Size, encoding, duplicate names, unknown fields or any field shape is invalid.
Function decode_supervision_response(payload)¶
Decode a response and require exact correlation with the sent request.
Parameters¶
payload : bytes Complete frame payload from the verified storage peer. request : SupervisionStartRequest or SupervisionHeartbeatRequest The request this response must answer. max_bytes : int Configured frame ceiling.
Returns¶
StorageSupervisionResponse Correlated outcome.
Raises¶
ValueError The frame is malformed, inconsistent or answers another request.
Module studio.platform.storage_transport¶
Function read_frame(channel)¶
Receive one nonempty frame within an absolute deadline.
Parameters¶
channel : socket.socket Exclusively owned connected Unix stream; peer authentication is external. max_bytes : int Maximum permitted payload bytes, from one through uint32 maximum. deadline : float Absolute monotonic time in seconds, shared by header and payload reads. The remaining interval must fit the platform timeout range.
Returns¶
bytes Complete payload; the four-byte network-order header is not returned.
Raises¶
ValueError Invalid arguments or an empty/oversized declared payload. TimeoutError The absolute deadline expires. EOFError The peer closes before the complete frame arrives. OSError Socket transfer fails. Transfer failures close the connection.
Function write_frame(channel, payload)¶
Send one nonempty byte payload under a single absolute deadline.
Parameters¶
channel : socket.socket Exclusively owned connected Unix stream; peer authentication is external. payload : bytes Nonempty immutable payload, excluding the generated length header. max_bytes : int Maximum payload bytes, from one through uint32 maximum. deadline : float Finite absolute monotonic time in seconds for the entire transfer. The remaining interval must fit the platform timeout range.
Raises¶
ValueError Arguments or payload type/size are invalid; no transfer is attempted. TimeoutError The total transfer deadline expires, including sender backpressure. OSError Socket transfer fails. Transfer failures close the connection.
Notes¶
Header and body use separate sends to avoid a combined payload allocation. Success restores the caller's timeout. Failure never retries a mutation.
Module studio.platform.storage_view_content¶
Class StorageViewContent¶
Correlated small header binding one complete storage snapshot response.
Function view_content_limit(frame_max_bytes, maximum)¶
Validate independent view content and frame limits.
Parameters¶
frame_max_bytes : int Positive uint32 per-frame ceiling. maximum : int, optional Trusted operator content ceiling; defaults to the existing event custody ceiling plus one frame of controls, within uint32.
Returns¶
int Positive total content limit, independent of the frame ceiling.
Raises¶
ValueError Either supplied limit is not a positive uint32 integer.
Function send_view_content(channel, content)¶
Send a complete admitted response with exact chunk boundaries and SHA.
Parameters¶
channel : socket.socket Peer-verified connection whose read policy already allowed the response. content : bytes Complete serialized inner record or query response. content_schema : str Inner response grammar, bound again by the receiver. request_id : str, optional Correlation from the original read request. expected_uid : int Configured API peer identity. frame_max_bytes : int Unchanged individual frame ceiling. deadline : float Absolute deadline shared by every response frame. max_content_bytes : int, optional Independent trusted total response ceiling.
Raises¶
ValueError Limits or total content size are invalid, before any response is sent.
Function read_view_content(channel)¶
Read an inline or chunked response without weakening its inner grammar.
Parameters¶
channel : socket.socket Same exclusively owned authority connection as the original request. content_schema : str Expected inner grammar; a chunk header cannot select another one. request_id : str, optional Original correlation checked before allocating content. expected_uid : int Configured storage authority identity, checked on every frame. frame_max_bytes : int Unchanged positive uint32 frame ceiling. deadline : float One absolute request/response deadline. max_content_bytes : int, optional Independent trusted total response ceiling checked before content receipt.
Returns¶
bytes Exact complete response for the owning record/query decoder to validate.
Raises¶
ValueError Metadata, correlation, content size, chunk length or SHA is invalid.
Module studio.platform.storage_worker_bootstrap¶
Class WorkerDescriptor¶
API-written selection for one generation; the launcher never reads it.
supervisor is the API process generation the worker guard follows.
The task is selected by reviewed name and route, never by import path.
Function read_worker_descriptor(spool_root)¶
Read and check the API-written descriptor for one exact generation.
Parameters¶
spool_root : Path Absolute compute spool root from the launcher configuration. job_id, generation : str Launcher-supplied identifiers; the descriptor must repeat them. server_uid : int Configured API identity that must own every spool directory used.
Returns¶
WorkerDescriptor Strictly validated descriptor whose task pairing is in the catalogue.
Raises¶
ValueError Identifiers, size, JSON, schema or task pairing is invalid. PermissionError A spool directory or the descriptor is not API-owned or is writable by others, or a path component is a symbolic link. OSError A spool entry is missing.
Function main(argv)¶
Confine this process, read its descriptor and run the gated worker.
Parameters¶
argv : Sequence[str] or None
Launcher-built argument vector; None reads sys.argv.
Returns¶
int
The existing worker's exit status, or 2 when confinement or the
descriptor refuses before the worker starts. No task is imported on
any refusal path.
Module studio.platform.storage_worker_grant¶
Class ExpectedWorker¶
Worker process generation reported by the trusted launcher.
uid is the configured compute identity, pid and start_token
identify the launched process generation. The values are launcher
observations; the endpoint compares them with kernel peer credentials.
- post_init()
- Refuse root, non-positive or malformed expectations before any accept.
Class WorkerGrantEndpoint¶
Own one single-use grant socket inside a held API directory descriptor.
The caller keeps directory_fd open for the endpoint's lifetime and never
passes it to a worker. :meth:open refuses an existing entry, so a stale or
substituted socket is never adopted. :meth:close removes only the inode it
created. The endpoint grants at most one worker and then closes its listener.
- init(directory_fd, directory_path, name)
- Retain the held directory, its canonical path and the endpoint name.
- path()
- Return the absolute endpoint path the worker must connect to.
- open()
- Bind and listen on a new socket inode through the held directory.
- grant(expected)
- Verify the launched worker, commit its identity and send one grant.
- close()
- Close the listener and remove only this endpoint's unchanged socket.
- enter()
- Open the endpoint and return its single owner.
- exit(exc_type, exc_value, traceback)
- Close the endpoint without suppressing caller failures.
Function validate_grant_name(name)¶
Return the grant endpoint name when it is the fixed per-generation name.
Each launch generation has its own spool directory, so the endpoint name itself is constant and short enough to keep the full socket path within the Unix limit.
Parameters¶
name : str
Final path component; it must equal :data:GRANT_ENDPOINT_NAME.
Returns¶
str The unchanged name.
Raises¶
ValueError The name has any other value.
Function receive_socket_grant(path)¶
Connect to the API grant endpoint and require the exact ready grant.
Parameters¶
path : Path Absolute endpoint path supplied by the trusted launcher descriptor. expected_server_uid : int Configured API identity that must own the accepting socket.
Raises¶
ValueError The path is relative or its name does not match the grant grammar. PermissionError The connected server is not the configured API identity. RuntimeError EOF, a malformed token, trailing bytes or the three-second reader deadline refuses the grant; no task may be imported. OSError The endpoint is missing or refuses the connection.
Module studio.platform.storage_worker_launcher¶
Class WorkerLauncher¶
Serve bounded launch/stop/status requests from the configured API UID.
Call :meth:start, then :meth:serve_once repeatedly from one long-lived
thread, then :meth:stop. Every generation stays recorded until
max_records forces the oldest stopped record out, so retries and lost
replies resolve to the same outcome.
- init(configuration)
- Retain configuration; nothing is bound or spawned yet.
- privileged()
- Return whether this launcher can switch to a different compute UID.
- start()
- Become a subreaper and bind the API-only endpoint.
- maintain()
- Observe trees, collect leader exits and handle adopted processes.
- serve_once()
- Handle one request, or return after the transfer timeout with none.
- handle(request)
- Apply one decoded request and return the observed outcome.
- stop()
- Close the endpoint and remove only its own unchanged socket.
- enter()
- Start the launcher and return its single owner.
- exit(exc_type, exc_value, traceback)
- Close the endpoint without suppressing caller failures.
Module studio.platform.storage_worker_spawn¶
Function generation_spool_ready(root, job_id, generation, owner)¶
Return whether the API-prepared job and generation directories exist.
Parameters¶
root : Path Configured compute spool root. job_id, generation : str Validated identifiers from the launcher request. owner : int Configured API identity that must own both directories.
Returns¶
bool
True only when both components are real directories owned by
owner; symbolic links and missing entries yield False.
Function compute_identity_processes(uid)¶
Return PIDs of processes whose /proc entry is owned by uid.
A process that exits during the scan is skipped.
Function spawn_worker_bootstrap(config)¶
Start one fixed bootstrap for an exact job generation.
Parameters¶
config : LauncherConfiguration Operator configuration supplying interpreter, import roots, spool, API identity, compute identity and ceilings. job_id, generation : str Validated identifiers of the admitted job generation. privileged : bool Whether this launcher switches to the configured compute identity.
Returns¶
subprocess.Popen[bytes]
The bootstrap, leading its own session, with no inherited descriptors
and standard streams connected to /dev/null.
Raises¶
OSError The interpreter cannot be executed or the identity switch fails.
Module studio.platform.storage_worker_tree¶
Class TrackedProcess¶
One observed process generation held by an open pidfd.
start_token is the /proc/<pid>/stat start time read after the
pidfd was opened and while the parent relation was confirmed.
Class WorkerTree¶
Launcher custody of one worker leader and its observed descendants.
The tree owns every pidfd it opens and closes them in :meth:close.
leader must be a direct child of the launcher so the launcher can reap
it; descendants are reaped by their parents or by :func:reap_adopted.
- init(leader)
- Take ownership of the leader pidfd.
- leader()
- Return the launched worker leader.
- owns(pid)
- Return whether
pidis an observed member of this tree. - observe()
- Walk from every live member and track newly visible children.
- live()
- Return tracked members whose pidfd does not yet report exit.
- kill()
- SIGKILL every observed member until none is live or rounds run out.
- close()
- Close every pidfd held by this tree.
Function process_control(option, value)¶
Apply one Linux prctl option with a single integer argument.
Parameters¶
option : int
PR_* option number from linux/prctl.h.
value : int
First option argument; the remaining arguments are zero.
Raises¶
OSError The kernel refuses the call; the kernel errno is preserved.
Function become_child_subreaper()¶
Mark the calling process as a child subreaper.
Raises¶
OSError
The kernel refuses the prctl call.
Function process_start_token(pid)¶
Return the /proc start time of pid as a decimal string.
Raises¶
OSError The process metadata is unavailable.
Function reap_adopted(trees)¶
Reap adopted zombies and kill adopted processes no tree has attributed.
Parameters¶
trees : list[WorkerTree] Every tree the launcher currently holds. leaders : set[int] Worker leader PIDs whose status the launcher collects through their own process handles; they are never reaped here.
Returns¶
tuple[int, ...] PIDs of unattributed adopted processes that were sent SIGKILL.
Notes¶
Every listed process is a child of the calling launcher, which collects children only on its single serving thread. No other process can reap or reparent it first, so its PID cannot be reused while this call runs. A kill the kernel refuses to deliver leaves that process unreported.
Module studio.platform.studio_job_service¶
Class StudioJobService¶
Job submission, observation, control and custody used by the API.
- submit_process_task()
- Submit one process task and return its record.
- wait(job_id, timeout_seconds)
- Observe one job until terminal or the deadline.
- record(job_id)
- Return one job record.
- list_records()
- Return records in creation order, scoped when asked.
- list_snapshot()
- Return a path-free snapshot of every visible job.
- status()
- Return aggregate path-free health.
- purge_snapshot()
- Read one operator purge journal page.
- cancel(job_id)
- Request cooperative cancellation for one job.
- read_artifact(job_id, relative_path)
- Read and verify one declared artefact.
- read_live_artifact_bytes(job_id, relative_path)
- Read one bounded slice from a live artefact.
- send_control_command(job_id)
- Deliver a command and control seeds to a running job.
- purge_terminal_record(job_id)
- Purge one terminal job and its custody.
- unreaped_workers()
- Return jobs whose workers were not confirmed stopped.
Module studio.platform.synthesis_process¶
Function run_synthesis_process_task(context, payload)¶
Run one Studio synthesis request in an isolated process.
Parameters¶
context:
Job sandbox used to write path-confined result and evidence artifacts.
payload:
JSON object matching the public /api/synth/run request contract.
Returns¶
dict[str, object] Path-free synthesis result payload.
Raises¶
ValueError If the payload does not match the JSON-serializable synthesis contract.
Function run_multi_target_synthesis_process_task(context, payload)¶
Run one Studio multi-target synthesis request in an isolated process.
Parameters¶
context:
Job sandbox used to write path-confined result and evidence artifacts.
payload:
JSON object matching the public /api/synth/multi-target contract.
Returns¶
dict[str, object] Path-free multi-target synthesis result payload.
Raises¶
ValueError If the payload does not match the JSON-serializable synthesis contract.
Function run_pnr_process_task(context, payload)¶
Run one Studio PnR request in an isolated process.
Parameters¶
context:
Job sandbox used to write path-confined result and evidence artifacts.
payload:
JSON object matching the public /api/synth/pnr request contract.
Returns¶
dict[str, object] Path-free PnR result payload.
Raises¶
ValueError If the payload does not match the JSON-serializable PnR contract.
Function run_synthesis_terminal_process_task(context, payload)¶
Run digest-bound selected-model synthesis and PnR in one isolated job.
Module studio.platform.training_checkpoint¶
Class StudioTrainingCheckpoint¶
Path-free manifest for restoring a Studio Training Monitor run.
Parameters¶
job_id: Source Training Monitor job ID. config: JSON-serializable training configuration that can seed another Studio training run. status: Source job status at export time. final_metrics: Terminal metric map, when the source job reached a terminal state. evidence_summary: Optional path-free terminal evidence summary from the source job. weight_checkpoint: Optional path-free metadata for a job-managed binary weight artifact. generated_at_utc: UTC timestamp for the export operation. config_sha256: SHA-256 digest of the canonical configuration payload. checkpoint_sha256: SHA-256 digest of the checkpoint payload excluding this digest field.
- to_public_dict()
- Return the JSON-serializable checkpoint payload.
Function build_training_checkpoint()¶
Build a portable Training Monitor checkpoint manifest.
Parameters¶
job_id: Source Training Monitor job ID. config: Training configuration to preserve. status: Source job status at export time. final_metrics: Optional terminal metrics from the training status response. evidence_summary: Optional path-free terminal evidence summary. weight_checkpoint: Optional path-free metadata for a job-managed binary weight artifact. clock: Optional UTC timestamp override for deterministic tests.
Returns¶
StudioTrainingCheckpoint Digest-backed checkpoint manifest suitable for API export.
Raises¶
ValueError If any supplied payload cannot be represented as portable JSON.
Function import_training_checkpoint_payload(payload)¶
Validate a Training Monitor checkpoint import payload.
Parameters¶
payload:
JSON object supplied to POST /api/training/checkpoint/import.
Returns¶
dict[str, JsonValue] Path-free import result containing the restored training config and source checkpoint metadata.
Raises¶
ValueError If the checkpoint schema, hashes, or config payload are invalid.
Module studio.platform.training_config_storage¶
Function prepare_training_config(config)¶
Validate a public configuration and separate its complete event contract.
Parameters¶
config : mapping The complete public training configuration submitted with the payload.
Returns¶
tuple Canonical small configuration and an optional canonical event contract. Both belong to the same job admission transaction.
Raises¶
ValueError The training declaration is invalid or either independent byte limit is exceeded. Large hidden-layer declarations retain the 4096-byte limit.
Function restore_training_config(payload, event_json)¶
Verify stored event bytes before rebuilding a full public configuration.
Parameters¶
payload : dict Decoded configuration row, either a legacy inline value or a reference. event_json : str, optional The same row's separate immutable event declaration.
Returns¶
dict Complete public configuration; no internal reference is exposed.
Raises¶
ValueError A declaration is absent, altered, oversized, malformed or noncanonical, or a legacy row contains unexpected separate event data.
Module studio.platform.training_evidence¶
Class TrainingEvidenceSummary¶
Path-free operator summary of one Training Monitor evidence artifact.
- to_public_dict()
- Return the JSON-serializable evidence summary.
Function build_training_evidence_summary(record, artifact_reader)¶
Return a verified Training Monitor evidence summary when available.
Parameters¶
record:
Path-free Studio job record that may declare the Training Monitor
evidence artifact.
artifact_reader:
Verified artifact reader, normally StudioJobManager.read_artifact.
Returns¶
dict[str, object] | None
Public evidence summary for terminal training records, or None when
the record does not declare a Training Monitor evidence artifact.
Function validate_training_evidence_summary(payload)¶
Validate a portable Training Monitor evidence summary.
Parameters¶
payload:
Candidate studio.training.evidence-summary.v1 object, normally
embedded in a portable Training Monitor checkpoint.
Returns¶
dict[str, JsonValue] JSON-compatible, validated evidence summary.
Raises¶
ValueError If the summary is not verified training evidence, uses an unsupported status or classification, or contains malformed artifact metadata.
Module studio.platform.training_process¶
Function run_training_process_task(context, payload)¶
Run one Studio training job in an isolated process.
Parameters¶
context:
Job sandbox used to write path-confined status and evidence artifacts.
payload:
JSON object matching the public /api/training/start configuration
contract.
Returns¶
dict[str, object] Path-free terminal training metadata.
Raises¶
ValueError
If payload is not a JSON object suitable for a training
configuration.
Function run_training_attach_process_task(context, payload)¶
Run a warm-start training job seeded with restored, verified weights.
The worker reads the confined seed weight and metadata inputs, verifies and
materializes them through the shared materializer, then runs a training job
that loads the restored state dictionary at the epoch-zero checkpoint
boundary before training forward. On success it writes a path-free
studio.training.weight-restore-attach.v1 evidence artifact recording the
verified digests, the resolved target architecture, and the architecture
fingerprint that gated compatibility. A strict load of an incompatible
architecture fails the job before training begins.
Parameters¶
context:
Job sandbox holding the confined seed inputs and artifact outputs.
payload:
JSON object with config (the target training configuration),
restore_plan (the path-free restore plan), and
architecture_fingerprint.
Returns¶
dict[str, object] Path-free terminal training metadata augmented with the attach evidence.
Raises¶
ValueError If the payload is malformed or the restored weights are incompatible with the target architecture.
Module studio.platform.training_weight_loader¶
Function load_training_weight_state_dict(payload)¶
Deserialize a verified torch checkpoint payload into a state dictionary.
The loader is the trusted boundary that runs only after
:func:sc_neurocore.studio.platform.training_weights.materialize_training_weight_payload
has verified the payload digest and byte size against the restore plan. It
restricts unpickling to tensor storages and primitive containers through
weights_only=True and rejects any payload that does not carry the
expected portable training checkpoint schema or a string-keyed model state
dictionary.
Parameters¶
payload:
Raw bytes of a studio.training.torch-state-dict.v1 checkpoint that
was produced by the Studio Training Monitor and already passed digest
verification.
Returns¶
Mapping[str, object] The string-keyed model state dictionary extracted from the checkpoint.
Raises¶
ValueError If the payload cannot be safely deserialized, does not carry the expected schema, or does not contain a string-keyed model state dictionary.
Function load_training_resume_block(payload)¶
Deserialize the saved run position from a verified checkpoint payload.
Same trusted boundary and same weights_only=True restriction as
:func:load_training_weight_state_dict: the resume block holds optimiser
tensors and plain generator state, never opaque pickled objects, precisely
so this guarantee survives.
Parameters¶
payload: Raw bytes of a checkpoint that already passed digest verification.
Returns¶
Mapping[str, object]
The resume_state block, or an empty mapping when the checkpoint
was written by a build that recorded no position. An empty mapping
supports a warm start and nothing more.
Raises¶
ValueError The payload cannot be safely deserialized or carries an unsupported schema.
Module studio.platform.training_weights¶
Class StudioTrainingWeightCheckpoint¶
Path-free metadata for a terminal Training Monitor weight artifact.
Parameters¶
framework: Framework used to serialize the weight payload. format: Serialized payload format. architecture: Human-readable model architecture summary. parameter_count: Number of serialized model parameters. config_sha256: SHA-256 digest of the canonical training configuration. weights_artifact: Manifest entry for the binary weight artifact. metadata_artifact: Manifest entry for the JSON metadata artifact. final_metrics: Terminal metric payload associated with the weights. schema_version: Schema identifier for this metadata contract.
- to_public_dict()
- Return a path-free JSON-compatible checkpoint summary.
Class StudioTrainingWeightRestorePlan¶
Path-free contract for reloading a Training Monitor weight artifact.
Parameters¶
source_job_id: Studio job ID that owns the published weight artifacts. source_status: Source training job status reported by the checkpoint import. config_sha256: SHA-256 digest of the training configuration associated with weights. framework: Framework expected by the weight payload. format: Serialized payload format. architecture: Human-readable model architecture summary. parameter_count: Number of serialized model parameters. weights_artifact: Path-free manifest entry for the binary weight artifact. metadata_artifact: Path-free manifest entry for the JSON metadata artifact. artifact_route_template: Authenticated artifact download route template for this Studio API. loader_policy: Required loader trust boundary for clients that materialize weights. schema_version: Schema identifier for this restore-plan contract.
- to_public_dict()
- Return a JSON-compatible restore plan without local paths.
Class StudioTrainingWeightMaterialization¶
Trusted in-memory materialization of verified training weights.
Parameters¶
source_job_id: Studio job ID that owns the source weight artifacts. config_sha256: SHA-256 digest of the training configuration associated with weights. framework: Framework used by the trusted loader. format: Serialized payload format consumed by the trusted loader. architecture: Human-readable model architecture summary. parameter_count: Number of parameters declared by the checkpoint metadata. state_dict: In-memory state dictionary returned by the trusted loader. weights_sha256: Verified SHA-256 digest of the binary weight payload. metadata_sha256: Verified SHA-256 digest of the metadata payload. schema_version: Schema identifier for this materialization contract.
- to_public_dict()
- Return path-free materialization metadata without tensor payloads.
Function write_training_weight_checkpoint(context)¶
Write binary training weights and path-free metadata artifacts.
Parameters¶
context:
Confined Studio job context that owns artifact publication.
weights_payload:
Serialized weight payload. The context enforces the byte ceiling.
config:
Training configuration used to produce the weights.
architecture:
Human-readable architecture summary.
parameter_count:
Number of model parameters represented by weights_payload.
final_metrics:
Terminal training metrics attached to the checkpoint metadata.
Returns¶
StudioTrainingWeightCheckpoint Path-free summary suitable for status and checkpoint API payloads.
Raises¶
ValueError If the payload is empty, metadata is not portable JSON, or the context rejects either artifact.
Function build_training_weight_restore_plan()¶
Build a safe restore plan from validated weight metadata.
Parameters¶
source_job_id: Studio job ID that owns the published training weight artifacts. source_status: Source training job status associated with the checkpoint. weight_checkpoint: Path-free weight metadata from a portable training checkpoint. expected_config_sha256: Optional training config digest that the metadata must match.
Returns¶
StudioTrainingWeightRestorePlan Path-free restore plan that identifies the authenticated artifact route and digest checks required before a client materializes weights.
Raises¶
ValueError If source metadata is missing or the weight checkpoint is invalid.
Function materialize_training_weight_payload()¶
Validate and materialize a Training Monitor weight payload in memory.
Parameters¶
restore_plan:
studio.training.weight-restore-plan.v1 object produced by a
validated checkpoint import.
metadata_payload:
Raw bytes fetched from the authenticated metadata artifact route.
weights_payload:
Raw bytes fetched from the authenticated weight artifact route.
trusted_loader:
Loader that deserializes weights_payload after all schema, size,
and digest checks pass. Production PyTorch integrations should use a
loader that restricts deserialization to state dictionaries.
Returns¶
StudioTrainingWeightMaterialization Verified, path-free in-memory materialization metadata plus the loaded state dictionary.
Raises¶
ValueError If the restore plan, metadata payload, artifact digests, artifact sizes, or loader output is invalid.
Function build_training_weight_restore_evidence(materialization)¶
Wrap a verified weight materialization as path-free restore evidence.
The returned object is the studio.training.weight-restore.v1 payload that
a restore job persists as a confined evidence artifact. It carries only the
verified digests, parameter counts, and loaded-key totals from the
materialization; the in-memory tensor state dictionary is never serialized.
Parameters¶
materialization:
Verified, path-free materialization returned by
:func:materialize_training_weight_payload.
source_status:
Terminal status of the source training job that owns the restored
weight artifacts.
Returns¶
dict[str, JsonValue] JSON-compatible restore evidence classified as training evidence with a completed terminal status.
Raises¶
ValueError
If source_status is empty.
Function validate_training_weight_restore_evidence(payload)¶
Validate a path-free studio.training.weight-restore.v1 evidence object.
Parameters¶
payload: Candidate restore evidence object from a Studio API response or import.
Returns¶
dict[str, JsonValue] The JSON-compatible, validated restore evidence object.
Raises¶
ValueError If the schema, classification, status, source identifiers, or embedded materialization summary are invalid.
Function training_architecture_fingerprint(config)¶
Return a SHA-256 fingerprint of a training config's architecture fields.
The fingerprint folds only the configuration fields that determine the model
state-dictionary shape (dataset, hidden layer widths, and the learnable
beta/threshold flags, plus event input/output dimensions and a model kind
other than spiking). Two
configurations whose fingerprints match produce
architecturally compatible models, so the fingerprint identifies whether
restored weights can be attached to a target training configuration.
Parameters¶
config:
Training configuration following the /api/training/start contract.
Returns¶
str SHA-256 hex digest of the canonical architecture field projection.
Function build_training_weight_restore_attach_evidence(materialization)¶
Wrap a verified materialization as path-free attach evidence.
The returned studio.training.weight-restore-attach.v1 object records that
verified weights were attached to a target training job. It carries only the
verified digests from the materialization, the target job identity, the
resolved target architecture, and the architecture fingerprint that gated
compatibility; the in-memory tensor state dictionary is never serialized.
Parameters¶
materialization:
Verified, path-free materialization returned by
:func:materialize_training_weight_payload.
mode:
Attach delivery mode: warm_start, exact_resume or live.
target_job_id:
Studio job ID that received the attached weights.
target_architecture:
Resolved architecture summary of the target model.
target_parameter_count:
Number of parameters in the target model.
architecture_fingerprint:
SHA-256 architecture fingerprint that gated the attach.
Returns¶
dict[str, JsonValue] JSON-compatible attach evidence classified as training evidence with a completed terminal status.
Raises¶
ValueError If the mode, target identifiers, or fingerprint are invalid.
Function validate_training_weight_restore_attach_evidence(payload)¶
Validate a studio.training.weight-restore-attach.v1 evidence object.
Parameters¶
payload: Candidate attach evidence object from a Studio API response or import.
Returns¶
dict[str, JsonValue] The JSON-compatible, validated attach evidence object.
Raises¶
ValueError If the schema, classification, status, mode, target identifiers, fingerprint, or embedded materialization summary are invalid.
Function validate_training_weight_checkpoint_metadata(payload)¶
Validate imported Training Monitor weight metadata.
Parameters¶
payload:
Path-free weight metadata from a studio.training.checkpoint.v1
payload.
expected_config_sha256:
Optional checkpoint configuration digest that must match the weight
metadata configuration digest.
Returns¶
dict[str, JsonValue] JSON-compatible, validated weight metadata.
Raises¶
ValueError If the schema, framework, format, config digest, artifact paths, artifact sizes, artifact hashes, or metadata payload are invalid.
Module studio.precision_compare¶
Function resolve_word_format(q_format)¶
Parse a Studio Q-format label into (data_width, fraction).
Q8.8 is 16 bits with 8 fractional bits; the kernel supports total
widths from 8 to 32 bits with at least one integer bit.
Function precision_compare(equations, threshold, reset, params, init, dt, duration, current)¶
Run float64, bit-true fixed-point and parameter-quantised comparisons.
Parameters¶
equations, threshold, reset, params, init:
The equation system exactly as the playground runs it.
dt, duration, current, protocol, frequency_hz:
The experiment; the same drive samples feed all three runs (encoded
to words for the kernel).
q_format:
Word format label (Q8.8 = 16 bits, 8 fractional).
overflow, rounding:
Kernel accumulate overflow and product rounding policies.
max_steps:
Synchronous step ceiling of the reference run.
Returns¶
dict
float_result, fixed_result and
parameter_quantisation_result (each a complete custody payload),
the arithmetic statement of the kernel, the encoding of every
value, the per-variable and event comparison for both candidate
runs, the contract and the legacy error / quantized_params
summary (bit-true error of the first declared variable).
Raises¶
ModelInputError For an unsupported format or mode, a stochastic system, an integrator the kernel does not mirror, an unrepresentable value or an invalid protocol. ModelSimulationFailure When the float64 reference run fails numerically. NativeToolUnavailable When no C compiler is installed.
Module studio.presets¶
Function list_presets()¶
Return public metadata for all curated Studio presets.
Function get_preset(preset_id)¶
Return one curated Studio preset by identifier.
Function get_preset_actions(preset_id)¶
Return validated action definitions for one curated Studio preset.
Function get_preset_action(preset_id, action_id)¶
Return one action definition for a curated Studio preset.
Function list_preset_action_catalog()¶
Return the route-facing catalogue of preset action identifiers.
Module studio.project¶
Function save_project(name, state)¶
Save full Studio state as a new immutable revision.
Parameters¶
name:
Workspace name; one directory under the Studio project root.
state:
Complete Studio state to persist.
expected_revision:
The revision the caller edited. None means the caller believes the
workspace is new. A save from a revision that is no longer current is
refused with :class:~sc_neurocore.studio.workspace_store.WorkspaceConflict
rather than silently replacing the other editor's work.
Returns¶
dict[str, Any] Path-free evidence metadata, including the revision written and the revision it descends from.
Raises¶
ValueError The name is unusable, the state is not an object, or it carries an identifier that would later interpolate into HDL or MLIR source. WorkspaceConflict The workspace moved on while the caller was editing.
Function load_project(name)¶
Load one revision of a saved workspace, defaulting to the current one.
Parameters¶
name:
Workspace name.
revision:
Revision to read. None reads the current one; an earlier number
reads history, which no later save can have rewritten.
Returns¶
dict[str, Any]
The stored document, or {"error": ...} when the workspace or the
requested revision does not exist.
Raises¶
ValueError The name is unusable, the stored document is not a workspace this build reads, or it carries an unsafe HDL-facing identifier.
Function list_projects()¶
List every saved workspace with its current revision.
A workspace whose revisions cannot be read is reported with a null
revision rather than omitted, so a corrupt store is visible instead of
looking empty.
Function delete_project(name)¶
Move a workspace to the recoverable trash.
Nothing is erased: the workspace and its whole revision history move
aside, and :func:restore_project brings them back. The returned token
identifies the deleted copy.
Function list_deleted_projects()¶
List the workspaces waiting in the recoverable trash, newest first.
Function restore_project(token)¶
Restore one deleted workspace under its original name.
Restoring onto a name that is in use is refused rather than performed: overwriting a live workspace is the loss this store exists to prevent.
Function branch_refused_edit(name, state)¶
Keep an edit a save conflict refused, as a branch of its own.
A conflicting save is refused so it cannot overwrite the other editor's work. Without this the refused edit exists only in the browser that made it, and the conflict message asks for it to be reapplied by hand. Here it becomes the first revision of its own workspace, so both edits survive.
Parameters¶
name : str Workspace whose save was refused. state : Mapping[str, Any] The refused Studio state. base_revision : int Revision the editor was working from. branch_name : str, optional Name for the branch; defaults to one naming the source and revision.
Returns¶
dict
branched name, the source from, and base_revision; or an
error when the source workspace or revision does not exist.
Function fork_project(name, new_name)¶
Copy one revision of a workspace into a new one.
The source workspace is untouched; the fork starts at revision 1.
Function project_revisions(name)¶
Return every stored revision of one workspace, oldest first.
Function review_comments(name)¶
Return a workspace's review comments, each checked against its revision.
Raises¶
KeyError The workspace does not exist.
Function comment_on_revision(name, revision)¶
Append a review comment bound to one immutable revision.
Raises¶
KeyError The workspace or the revision does not exist. ValueError The comment is empty or too long, or replies to a comment on another revision.
Function export_project(name)¶
Return one revision as a self-contained document for transfer.
Function import_project(name, document)¶
Create a workspace from an exported document.
Function run_pipeline(graph, target)¶
Validate, simulate, lower, co-simulate and synthesise a Studio network.
The hardware is the network the caller drew: the graph is lowered with each
catalogue model's own step (:mod:sc_neurocore.studio.network_hardware) or
refused with every reason it cannot be. The compiled RTL is then run beside
its bit-true model and the Studio's own run
(:mod:sc_neurocore.studio.network_hardware_cosim); synthesis runs only
when the RTL reproduces its model on every co-simulated step. The result's
trace binds the lowering's input digest, the RTL, the model and the
synthesised source.
Before the lowering existed the step compiled one hardcoded leaky integrate-and-fire equation, ignoring the graph, and later refused every graph; neither was the caller's network.
Parameters¶
graph:
Studio network graph payload.
target:
Studio synthesis target identifier.
q_format:
Q8.8 or Q16.16, the fixed-point format of the hardware.
process_limits:
Optional host-supported CPU and address-space ceilings for the
downstream synthesis child process.
Returns¶
dict[str, Any]
success, the step it ended at, each step's payload under
steps, and trace once the RTL was built; a stop carries
error and, when the lowering refused, every reasons entry.
Raises¶
ValueError
When q_format is not one the pipeline compiles to.
Module studio.project_manifest¶
Class StudioProjectSaveManifest¶
Path-free metadata returned after persisting a Studio project.
Parameters¶
name: Sanitized project name. saved_at: Unix timestamp stored in the project payload. version: Studio project payload version. state_sha256: SHA-256 digest of the canonical project state JSON. project_sha256: SHA-256 digest of the canonical full project payload JSON. evidence_classification: Stable evidence lane label for saved project workspaces. status: Terminal status for this project-save evidence object.
- to_public_dict()
- Return the public, path-free project save response.
Function build_project_save_manifest()¶
Build digest-backed metadata for a persisted Studio project.
Parameters¶
name:
Sanitized project name.
saved_at:
Unix timestamp stored in the project payload.
version:
Studio project payload version.
state:
Project state object persisted under state.
project_payload:
Full persisted project payload.
Returns¶
StudioProjectSaveManifest Path-free metadata suitable for API responses, logs, and evidence manifests.
Raises¶
ValueError If the state or payload cannot be encoded as portable JSON.
Function dump_project_payload(payload)¶
Return the durable JSON representation for a saved project payload.
The writer keeps the human-readable indentation used by existing Studio project files, while rejecting non-standard JSON values such as NaN and Infinity so saved projects remain portable across runtimes.
Module studio.readiness_seal¶
Function checkout_available(repo_root)¶
Return whether repo_root is a checkout the receipts can be re-verified in.
Receipt subjects include the validator tests and the descriptor sources, so both trees must be present; an installation or an unpacked source distribution has neither the tests nor this layout.
Function build_seal(names, verified_detail)¶
Return the seal of names, each derived by verified_detail.
Function render_seal(seal)¶
Return the seal exactly as it is written: sorted keys, no timestamps.
Function sealed_detail(class_name, path)¶
Return the sealed verified block of one model.
A model the seal does not hold was not verified when the distribution was built; it is reported unverified with that reason, never given tiers.
Module studio.replay_notebook¶
Function model_citation(class_name)¶
Cite one catalogue model from its own descriptor, or say it names no source.
Parameters¶
class_name: The catalogue class name.
Returns¶
str A Markdown sentence naming the model and its source.
Function notebook_from_pack(pack)¶
Return a Jupyter notebook (nbformat 4) that cites and replays pack.
Parameters¶
pack:
A sealed replay pack, as :func:~sc_neurocore.studio.replay_pack.build_replay_pack
returns it.
Returns¶
dict
The notebook document, ready to be written as .ipynb JSON.
Module studio.replay_pack¶
Class ReplayRejected¶
Raised when a pack cannot be replayed, before anything is executed.
Parameters¶
stage : {"schema", "request", "identity", "revision", "runtime"} Which admission step refused. reason : str Deliberately authored explanation; never generated exception text. differences : sequence of str, optional Named blocks or fields that differ, for a drift refusal.
- init()
- to_public_detail()
- Return the path-free public error detail.
Class ReplayAdmission¶
The outcome of admitting a pack, before the experiment runs.
Attributes¶
spec : ExperimentSpec The experiment re-resolved in this process. identity_sha256 : str Identity digest of the re-resolved experiment; equal to the pack's. runtime_differences : tuple of str Runtime fields that differ from the sealed environment. Non-empty only when the caller admitted runtime drift explicitly.
Function experiment_identity(public)¶
Return the scientific blocks of a public specification.
Parameters¶
public : mapping
A public :class:~sc_neurocore.studio.experiment_spec.ExperimentSpec
projection.
Returns¶
dict
The blocks named in :data:IDENTITY_BLOCKS that the specification
actually carries, in that order.
Function experiment_identity_sha256(public)¶
Return the digest of a specification's scientific identity.
Function pinned_request(request, spec)¶
Return the request fields that re-resolve to this experiment.
A drawn or defaulted seed is written back into the request and the trial is
sealed as replay, so the pack reproduces the run it recorded instead of
drawing new randomness. A deterministic experiment carries no seed, because
the run contract refuses one.
Parameters¶
request : mapping The original request. Unknown keys are dropped here rather than travelling into the pack. spec : ExperimentSpec The experiment resolved from that request.
Returns¶
dict A JSON-safe request with pinned randomness.
Function replay_expectation(result)¶
Summarise a run result into the complete expectation a replay must meet.
Every scalar and vector trace contributes full samples and a float64 digest, permitting a pointwise error bound rather than a summary comparison. Spike events are carried in full: they are the observable a spiking experiment exists to produce.
Parameters¶
result : mapping
A result from
:func:~sc_neurocore.studio.experiment_spec.run_experiment.
Returns¶
dict The expectation block of a replay pack.
Raises¶
ReplayRejected When raw trajectories are omitted; display projections cannot replace them.
Function build_replay_pack(request)¶
Resolve, pin, execute and seal one experiment into a replay pack.
The pack is built from the pinned experiment, so what it promises is exactly what a replay of it produces. A fresh stochastic trial is executed once with the seed it drew.
Parameters¶
request : mapping
A Studio simulate request (catalogue model or equation playground).
max_steps : int
Largest synchronous step count; a larger run is refused by the
experiment contract with execution_mode = job_required.
Returns¶
dict
A studio.replay-pack.v2 document.
Raises¶
ModelInputError From the run contract: unknown model, parameter or unsupported step. ExperimentRejected From the experiment contract: invalid randomness, no complete step or an oversized run.
Function verify_replay_pack(pack)¶
Admit a pack for replay, refusing before any side effect.
The pack's request is re-resolved against the installed package and the resulting scientific identity is compared with the sealed one. Nothing is executed until every refusal has been ruled out.
Parameters¶
pack : mapping
A studio.replay-pack.v2 document.
allow_runtime_drift : bool
Admit a package, interpreter, NumPy or platform difference and report
it, instead of refusing. Never implicit.
max_steps : int
Largest synchronous step count for the re-resolved run.
Returns¶
ReplayAdmission The re-resolved experiment and any admitted runtime differences.
Raises¶
ReplayRejected Unsupported schema, unexecutable request, model or experiment drift, or unadmitted runtime drift.
Function compare_to_expectation(expectation, result)¶
Compare a replayed result with a sealed expectation.
Spike events are compared exactly; a spike train is an observable, not a rounding matter. Scalar and vector state traces are compared sample by sample when their digests differ. Legacy traces without samples are exact-only; extrema never establish a tolerance bound.
Parameters¶
expectation : mapping
The expectation block of a replay pack.
result : mapping
The result of replaying the pack's experiment.
tolerance : float
Largest absolute state deviation still called a match. Zero means the
replay must be bit-identical.
Returns¶
dict
verdict, the list of differences and the observed expectation.
Raises¶
ReplayRejected If tolerance is negative/nonfinite or complete raw evidence is unavailable.
Function replay_pack(pack)¶
Admit, execute and judge one replay pack.
Parameters¶
pack : mapping
A studio.replay-pack.v2 document.
allow_runtime_drift : bool
Admit and report a runtime difference instead of refusing.
tolerance : float
Largest absolute state deviation still called a match.
max_steps : int
Largest synchronous step count for the replay.
Returns¶
dict The comparison outcome with the admitted experiment digests and any runtime differences.
Raises¶
ReplayRejected
From :func:verify_replay_pack, before the experiment runs.
Function load_replay_pack(path)¶
Read a replay pack from a regular file.
Parameters¶
path : pathlib.Path Path to the pack. It must be a regular file (a directory, device or dangling symlink is refused) no larger than 32 MiB.
Returns¶
dict The parsed pack; its contents are validated on admission, not here.
Raises¶
ReplayRejected The path is not a readable regular file, is too large, or does not contain a JSON object.
Function main(argv)¶
Replay a pack from the command line.
Exit code 0 means the experiment reproduced, 1 that it did not, and 2 that the pack was refused before it ran.
Module studio.runtime_state_packet¶
Class ForeignRuntimeError¶
Raised when a foreign runtime returns something the boundary cannot use.
Class RuntimeStatePacket¶
What one foreign runtime transports across the boundary.
Attributes¶
runtime : str
Stable lane identifier, such as rust-batch.
exports : tuple of str
Declared-state variable names the lane can return, in the model's own
vocabulary. A lane that returns a value it cannot name in that
vocabulary declares nothing for it.
carries_initial_snapshot : bool
Whether the lane reports the state the run started from.
carries_parameters : bool
Whether the lane accepts parameter overrides. A lane that does not runs
the model's defaults whatever the caller asked for.
- to_public_dict()
- Return the packet as evidence and receipts record it.
Class PacketCoverage¶
How much of one model's declared state a packet accounts for.
Attributes¶
runtime : str The lane the coverage was computed for. carried : tuple of str Declared variables the lane returns, in declaration order. dropped : tuple of str Declared variables it does not return. unnameable : tuple of str Values the lane exports that this model does not declare. They cannot be placed in the payload under those names, because the model has no such state.
- complete()
- Return whether the lane carries every declared variable.
- names_nothing()
- Return whether the lane can name none of this model's state.
- to_public_dict()
- Return the coverage as evidence and receipts record it.
Function packet_coverage(packet, declared_names)¶
Return what a packet accounts for against one model's declared state.
Parameters¶
packet : RuntimeStatePacket The lane's transport contract. declared_names : sequence of str The model's declared state variables, in declaration order.
Returns¶
PacketCoverage Which declared variables the lane carries, which it drops, and which of its exports this model cannot name.
Function validate_scalar_trace(values)¶
Return one scalar trace from a foreign runtime, or refuse it.
Structure only: the trace must be one-dimensional real numbers of exactly the requested length. Whether the values are finite is the caller's question, because a diverged membrane voltage is a failed simulation rather than a malformed boundary.
Parameters¶
values : object Whatever the lane returned for this trace. runtime : str Lane identifier, named in the refusal. name : str Variable name, named in the refusal. n_steps : int Number of steps the run asked for.
Returns¶
numpy.ndarray The trace as float64.
Raises¶
ForeignRuntimeError
If the trace is not one-dimensional real numbers of length n_steps.
Function validate_spike_indices(values)¶
Return spike sample positions from a foreign runtime, or refuse them.
Parameters¶
values : object Whatever the lane returned for its spike indices. runtime : str Lane identifier, named in the refusal. n_steps : int Number of steps the run asked for; every index must fall inside it.
Returns¶
list of int The indices, in the order the lane produced them.
Raises¶
ForeignRuntimeError If the indices are not a one-dimensional integer series inside the run and in increasing order. Order matters: the statistics take differences between consecutive entries, and an unordered series would report a negative interval as a real measurement.
Module studio.simulation¶
Function simulate(equations, threshold, reset, params, init, dt, duration, current, protocol, frequency_hz, seed, max_steps, bias)¶
Run an equation-neuron simulation and return its complete raw result.
Parameters¶
equations : list[str]
Differential equations or map updates, one per state variable.
threshold, reset : str or None
Spike condition and reset assignments.
params, init : dict or None
Parameter values and initial state.
dt, duration : float
Step in milliseconds and requested run length; capped at
max_steps steps (:data:MAX_STEPS by default; the experiment
contract refuses a longer synchronous run instead of shortening it).
current, protocol, frequency_hz : float, str, float
Injection protocol.
bias : float
Level a sine oscillates about; zero, and refused for any other
protocol, unless given.
seed : int or None
Seed of the diffusion-noise generator (the xi symbol). None
draws from the process-global numpy.random stream, which is not
reproducible; the experiment contract always passes a seed for a
stochastic playground run and rejects one for noise-free equations.
Returns¶
dict[str, Any]
The display projection (time, states, current_trace),
spikes and statistics, the observation clock, the state_layout
(source equations), exact initial_state and final_state
snapshots, the full-resolution raw block and the display
sample-index map.
Raises¶
ValueError When the duration yields no complete step or the equations are invalid. ModelSimulationFailure When a step raises or a state variable becomes non-finite (reported with the step index and the time that step started, never as a NaN trace).
Function fi_curve(equations, threshold, reset, params, init, dt, duration, i_min, i_max, i_steps)¶
Sweep current and compute firing rate at each level.
Module studio.simulation_manifest¶
Class StudioSimulationRunManifest¶
Path-free metadata for one Studio simulation result.
Parameters¶
source:
Simulation surface that produced the result.
input_sha256:
SHA-256 digest of the canonical request payload.
result_sha256:
SHA-256 digest of the canonical result payload without this manifest.
raw_sha256:
SHA-256 digest of the canonical raw block (full-resolution traces,
spikes and clock rules), empty when the result carries no raw block.
dt:
Effective simulation time step in milliseconds.
n_steps:
Number of executed simulation steps.
sample_count:
Number of display samples returned in time.
spike_count:
Number of spikes detected during the simulation.
state_variables:
Sorted names of the state variables recorded at every step.
raw_included:
Whether the raw block carries the full-resolution traces.
layout_source:
Where the state layout came from (descriptor, equations or
undeclared), empty for a result without a layout.
state_custody_complete:
Whether every declared variable was recorded and nothing undeclared
changed during the run.
observation_clock:
Clock rule of the recorded samples (post-step), empty when the
result carries none.
experiment_sha256:
SHA-256 digest of the resolved experiment specification
(studio.experiment-spec.v1), empty when the result carries none.
trial:
replay (deterministic replay of a recorded trial) or fresh
(independent stochastic trial with a drawn seed), empty when absent.
evidence_classification:
Stable evidence lane label for simulation runs.
status:
Terminal status for this simulation evidence object.
- to_public_dict()
- Return the public, path-free simulation run manifest.
Function build_simulation_run_manifest()¶
Build digest-backed reproducibility metadata for a simulation result.
Parameters¶
source: Simulation surface that produced the result. request_payload: Request body used to run the simulation. result_payload: Result payload after classification, without relying on local paths.
Returns¶
StudioSimulationRunManifest Path-free metadata suitable for UI display, exported JSON, and evidence bundles.
Raises¶
ValueError If request or result payloads cannot be encoded as portable JSON.
Module studio.state_layout¶
Class DeclaredState¶
One state variable as the model declares it.
Parameters¶
name : str
Attribute name on the model instance (or variable name of an equation
neuron).
role : {"biological", "auxiliary", "unassigned"}
Role from the canonical schema profile; unassigned when the class
has no bound profile or the profile does not name the variable.
unit : str
Declared unit, empty when undeclared.
meaning : str
Declared meaning, empty when undeclared.
declared_init : float or None
Declared initial value, None when the declaration carries none.
Class ObservedState¶
A declared state variable with the shape observed on the instance.
Parameters¶
declared : DeclaredState
The declaration.
kind : {"scalar", "vector"} or None
Observed kind; None when the variable is not observable.
shape : tuple of int or None
Observed shape (() for a scalar); None when not observable.
observable : bool
Whether the run can record the variable.
reason : str
Why the variable is not observable (empty when it is).
trace : {"per-step", "snapshots-only", "none"}
How the run records the variable: every step, only in the initial and
final snapshots (a vector beyond the raw budget), or not at all.
- name()
- Attribute name of the variable.
- to_public_dict()
- Return the path-free public description of the variable.
Class StateLayout¶
The declared state layout of one run and its custody verdict.
Parameters¶
source : {"descriptor", "equations", "undeclared"} Where the declaration comes from. schema_profile : str Canonical schema stem whose profile assigned the roles, else empty. variables : tuple of ObservedState Every declared variable, observable or not. undeclared_mutable : tuple of str Instance attributes that changed between the initial and the final snapshot without being declared (private registers included).
- observable()
- Variables the run records.
- per_step()
- Variables recorded at every step.
- scalars()
- Observable scalar variables (the ones the display projection shows).
- incomplete_reasons()
- Return why the recorded state is not the complete declared state.
- complete()
- Whether every declared variable was recorded and nothing undeclared moved.
- with_undeclared_mutable(names)
- Return a copy carrying the start-to-end mutation audit.
- with_custody_notes(notes)
- Return a copy carrying backend custody limitations.
- to_public_dict()
- Return the path-free public layout with its custody verdict.
Class StateObservationError¶
Raised when an observable variable is not a finite value of its observed shape.
Parameters¶
name : str Variable name. reason : str Bounded description of the violation.
- init(name, reason)
Function declared_state(class_name)¶
Return the declared state of a catalogue class.
Parameters¶
class_name : str Registered catalogue class name.
Returns¶
tuple
(source, schema_profile, variables): descriptor with the
committed [state] table joined with the canonical profile roles, or
undeclared with no variables when the descriptor is absent or its
state has not been declared. The descriptor is the authority; the
profile only assigns roles.
A descriptor that asserts ``stateless`` answers ``descriptor`` with no
variables. Emptiness is then a declaration rather than a silence: the
run records everything the model declares, so its custody is complete,
where a model whose state nobody has declared stays ``undeclared`` and
incomplete. The assertion does not exempt the model from the mutation
audit — anything that moves is still reported as undeclared state.
Function equation_state(names, init)¶
Return the declared state of an equation-playground neuron.
Parameters¶
names : iterable of str
State variable names in the neuron's evaluation order.
init : mapping or None
Initial values the request declared; a variable without one carries
None.
Function scalar_value(value)¶
Return a declared state variable as a float, or None when it is not one.
A flag is state. LapicqueNeuron declares excited, which latches the
first threshold attainment and which its canonical schema lowers as 0.0 or
1.0 in the RTL, and a run that refused to record it published incomplete
custody for a register the model tracks exactly. A boolean is therefore read
as the number the rest of the toolchain already carries it as.
This function exists only to read declared state: an attribute nobody declared is never offered to it, so admitting flags here says nothing about an undeclared one.
Function vector_value(value)¶
Return value as a float64 array when it is a numeric vector.
A model may hold a compartment vector, a population activity profile or a filter buffer as a NumPy array or as a plain list — the choice is the model's, and it is not a statement about whether the quantity is state. A numeric sequence is therefore read as the vector it is; a string, a dictionary, a ragged sequence or a sequence carrying a non-number is not a vector and is refused, so an unrecordable value is still reported with its reason rather than coerced into a shape.
Function observe_layout(instance, source, schema_profile, declared)¶
Observe the shape of every declared variable on a constructed instance.
Parameters¶
instance : object
The model instance before its first step.
source, schema_profile : str
Provenance of the declaration (see :func:declared_state).
declared : iterable of DeclaredState
The declared variables.
n_steps : int
Steps the run will execute; decides whether a vector trace fits the
raw element budget.
element_budget : int
Maximum raw elements the run may return per variable trace.
Returns¶
StateLayout Every declared variable with its observed kind and shape, or the reason it cannot be recorded.
Function read_variable(instance, variable)¶
Read one observable variable and enforce its observed kind, shape and finiteness.
Raises¶
StateObservationError When the value is no longer of the observed kind or shape, or is not finite.
Function snapshot(instance, layout)¶
Return the exact value of every observable variable of the layout.
Function public_snapshot(values)¶
Return a snapshot as JSON values (vectors as nested lists).
Function attribute_fingerprints(instance)¶
Fingerprint every instance attribute (public and private) for the mutation audit.
Function undeclared_mutations(before, after, layout)¶
Return attributes that changed between two fingerprints without being declared.
A declared variable may be a public view of a private one. The library's
generator contract is exactly that: a model exposes rng_state as a
read-only property over a private generator, and the descriptor declares
the property. The generator object then moves under a name the layout never
names, but its movement is the declared variable's movement, so it is
accounted for rather than reported. A model that carries a generator
without declaring rng_state is not accounted for, and is reported.
Module studio.svg_export¶
Function traces_to_svg(time, states, spikes, model_name, dt, width, height)¶
Generate publication-quality SVG from simulation traces.
Returns a complete SVG string with axes, grid, legend, spike markers, and colour-coded polylines. Traces are downsampled to <=2000 points.
Module studio.synthesis¶
Class EdaProcessLimits¶
Optional process resource limits for external Studio EDA commands.
Parameters¶
cpu_seconds:
Maximum CPU seconds allowed for the child process on hosts that expose
POSIX RLIMIT_CPU. None leaves CPU accounting to the existing
wall-clock timeout.
address_space_bytes:
Maximum address space bytes allowed for the child process on hosts that
expose POSIX RLIMIT_AS. None leaves memory unconstrained by this
helper.
- post_init()
- Validate positive resource ceilings when they are configured.
Class SynthesisTerminalExecution¶
Public terminal report plus private implementation artifacts.
Function check_tools()¶
Detect which EDA tools are installed.
Function cell_cost(target, cell_type)¶
Return what one cell takes of the judged resources, or None if unknown.
Parameters¶
target : str Target identifier. cell_type : str The Yosys cell type.
Returns¶
dict[str, int] or None Resource amounts, empty for a cell that takes none, None for a cell whose cost the Studio does not know.
Function capacity_verdict(resources, capacity)¶
Say whether a synthesised design fits its target device.
Synthesis succeeding says the netlist exists, not that the device can hold it: a 20-neuron network synthesised to 6237 LUTs for a 5280-LUT UP5K and the pipeline reported it complete. Only resources the target's capacity lists are judged; a target without capacity data gets no verdict rather than a guessed one. Fitting by count is necessary, not sufficient: on iCE40 and ECP5 a LUT and a flip-flop share a logic cell (708 LUTs and 98 flip-flops took 752 UP5K cells), and placement and routing can still fail.
Parameters¶
resources : Mapping[str, Any] Counted resources of the design. capacity : Mapping[str, int] The device's capacity per resource. device : str or None, optional The device the capacity describes, named with the verdict. uncounted : Mapping[str, int] or None, optional Cells whose cost is unknown, by type. With any, the counts are a floor: they can prove a design does not fit, never that it does.
Returns¶
dict[str, Any]
fits_device (True, False, or None when unknown cells leave it
open), exceeds_capacity (per resource, what the design needs and
the device has), capacity_device and uncounted_cells; an empty
dict without capacity data.
Function capacity_device_name(target)¶
Name the device a target's capacity is judged against.
Parameters¶
target : str Target identifier.
Returns¶
str The device, or the target in capitals when none is named.
Function capacity_sentence(target, exceeds)¶
Say in words which resources a design needs beyond its device.
Parameters¶
target : str
Target identifier; its judged device is named.
exceeds : Mapping[str, Mapping[str, int]]
From :func:capacity_verdict.
Returns¶
str One sentence.
Function supported_targets()¶
Return synthesis targets accepted by the Studio EDA routes.
Function run_synthesis(verilog_source, target)¶
Run Yosys synthesis and return resource usage.
Parameters¶
verilog_source: SystemVerilog or Verilog source text to synthesise. target: Studio synthesis target identifier. process_limits: Optional host-supported CPU and address-space ceilings for the Yosys child process. tool_status: Optional path-free EDA tool status snapshot. When omitted, the backend captures a fresh snapshot for this result.
Returns¶
dict[str, Any] Path-free synthesis result with success state, target, resource counts, capacity metadata, utilisation, or a bounded error message.
Function run_synthesis_terminal(verilog_source, target)¶
Run digest-bound synthesis and PnR for one parity-verified model RTL source.
Function estimate_resources(ir_op_count, target)¶
Quick resource estimate from IR operation count, no Yosys needed.
Heuristic: each IR op maps to ~2 LUTs + 1 FF on average. LIF step op maps to ~12 LUTs + 8 FFs + 1 DSP (multiplier).
Function multi_target_synthesis(verilog_source)¶
Run synthesis on all supported targets and return a comparison.
Parameters¶
verilog_source: SystemVerilog or Verilog source text to synthesise. process_limits: Optional host-supported CPU and address-space ceilings applied to every Yosys child process.
Returns¶
dict[str, Any] Mapping with per-target synthesis results and the supported target list.
Function run_pnr(json_path, target)¶
Run nextpnr place-and-route and return timing report.
Parameters¶
json_path: Path to a Yosys JSON netlist. The path must point to a regular JSON file and must not be a symlink. target: Studio target identifier with nextpnr support. process_limits: Optional host-supported CPU and address-space ceilings for the nextpnr child process.
Returns¶
dict[str, Any] Path-free PnR result with success state, timing metadata, log excerpt, or a bounded error message.
Module studio.synthesis_provenance¶
Class StudioSynthesisToolProvenance¶
Version and availability evidence for one synthesis-related tool.
Parameters¶
key: Stable API key for the tool status entry. executable: Command name used by the Studio backend. role: Tool role in the synthesis workflow. available: Whether the tool was detected by the backend. version: First version line returned by the tool, when available.
- to_public_dict()
- Return a path-free public tool provenance payload.
Class StudioSynthesisTargetProvenance¶
Path-free provenance for one Studio synthesis target.
Parameters¶
target: Studio target identifier. capacity: Static capacity metadata used for resource utilisation. synthesis_command: Yosys synthesis command selected for the target. pnr_tool: Place-and-route command for the target, when one is configured. device: Device selector passed to the PnR tool, when configured. tools: Required tool provenance records for this target. evidence_classification: Stable evidence lane label for synthesis target provenance. status: Terminal status for this synthesis target provenance object.
- provenance_grade()
- Return the claim grade for this target's synthesis provenance.
- to_public_dict()
- Return the public, path-free target provenance payload.
Function build_synthesis_target_provenance(target)¶
Build provenance metadata for one Studio synthesis target.
Parameters¶
target:
Studio target identifier.
target_config:
Target configuration containing synthesis, PnR, and device selectors.
capacity:
Static target capacity metadata.
tool_status:
Path-free tool detection payload from check_tools.
Returns¶
StudioSynthesisTargetProvenance Path-free target provenance record.
Raises¶
ValueError If the target configuration lacks a synthesis command.
Function build_synthesis_target_provenance_matrix()¶
Build a path-free provenance matrix for all Studio synthesis targets.
Parameters¶
targets:
Mapping of target identifiers to backend target configuration.
capacities:
Mapping of target identifiers to static capacity metadata.
tool_status:
Path-free tool detection payload from check_tools.
Returns¶
dict[str, JsonValue] Matrix payload keyed by target with a stable SHA-256 digest.
Module studio.templates¶
Function list_templates()¶
Return all curated Studio equation templates.
Function get_template(name)¶
Return one curated Studio equation template by name.
Module studio.trace_projection¶
Class DisplayProjection¶
The sample-index set of the viewport projection.
Parameters¶
sample_index : numpy.ndarray
Sorted raw step indices the projection shows.
method : {"identity", "bucket-extrema"}
identity when the run fits the point budget, otherwise per-bucket
extrema of every series on a shared index set.
bucket_count : int
Number of buckets used (0 for identity).
max_points : int
The upper bound the projection was built against.
- point_count()
- Number of display points.
Function display_sample_indices(n_steps, series)¶
Choose the raw step indices a bounded viewport shows.
Parameters¶
n_steps : int
Number of raw steps.
series : sequence of numpy.ndarray
Every scalar trace whose extrema must survive (states and drive), each
of length n_steps and finite.
max_points : int
Hard upper bound on the number of display points.
Returns¶
DisplayProjection
Identity when n_steps <= max_points; otherwise the sorted union of
the first sample, the last sample and each bucket's argmin/argmax of
every series. With k series and b buckets the union holds at
most 2 + 2*k*b <= max_points points, so the bound is exact.
Raises¶
ValueError
When n_steps is not positive, max_points < 2 or a series has
the wrong length, contains non-finite values, or the point budget
cannot guarantee the endpoints and every series' extrema.
Function sample_times(n_steps, dt)¶
Return the post-step sample time of every raw step: (index + 1) * dt.
Function observation_block(dt)¶
Return the observation-clock contract of a run.
Function raw_block()¶
Return the full-resolution raw block of a run.
Parameters¶
dt, n_steps : float, int
Step and number of executed steps.
scalar_traces : mapping
Per-step float64 arrays of length n_steps for every scalar state.
vector_traces : mapping
Per-step arrays of shape (n_steps, *shape) for vector states that
fit the element budget.
vector_omitted : sequence of str
Vector states recorded in snapshots only.
drive : numpy.ndarray
The injected drive sample of every step.
spikes : sequence of int
Raw step indices at which the model reported a spike.
element_budget : int
Raw element budget the block was built against.
Returns¶
dict
included is False only when the scalar traces alone exceed the
budget; nothing is shortened silently, the reason is stated instead.
Function custody_payload()¶
Assemble the public result of a run: raw custody plus display projection.
The top-level time, states and current_trace fields are the
display projection (kept for existing consumers and labelled as such in
display); raw, initial_state and final_state carry the
complete result.
Function full_state_traces(result)¶
Return the full-resolution scalar state traces of a run result.
Consumers that compute on a trace (attractor detection, state ranges,
precision errors) must not use the display projection. When the result
carries an included raw block its traces are returned; a legacy or
raw-less result falls back to its states field.
Function full_state_trace(result, name)¶
Return one full-resolution scalar state trace (empty when absent).
Module studio.training¶
Function list_surrogates()¶
Return surrogate-gradient choices exposed by the Studio UI.
Returns¶
list[dict[str, Any]]
Ordered names with an available flag reflecting the installed Torch
training backend.
Function list_cell_types()¶
Return training cell types exposed by the Studio UI.
Returns¶
list[dict[str, Any]]
Ordered cell names with an available flag reflecting the installed
Torch training backend.
Function start_training(config, job_manager)¶
Start a Studio training job.
When job_manager is supplied, execution is delegated to the bounded
Studio process sandbox. Without it, the historical in-process training
thread is retained for direct callers.
Parameters¶
config : dict[str, Any] Training Monitor configuration. job_manager : StudioJobService or None, optional Bounded job manager used by the Studio HTTP route.
Returns¶
dict[str, Any]
Path-free job identifier and initial running status.
Function start_training_attach(source_job_id, config, job_manager)¶
Start a training job seeded with restored, verified weights.
mode names which of two different runs this is. warm_start begins a
new run from the restored weights with a fresh optimiser and generator at
epoch zero. exact_resume continues the source run from its recorded
position — optimiser state, generator states and epochs already completed —
and is refused when that position belongs to a different configuration or
architecture.
The source checkpoint and binary artifacts are verified before a bounded process job loads them at the epoch-zero boundary. Raw tensors remain inside the confined worker and never enter the API response.
Parameters¶
source_job_id : str
Completed source training job that published model weights.
config : dict[str, Any]
Target training configuration.
job_manager : StudioJobService
Bounded manager owning artifact reads and process submission.
expected_config_sha256 : str or None, optional
Optional digest that the source configuration must match.
mode : str, optional
"warm_start" (default) or "exact_resume".
Returns¶
dict[str, Any]
Job metadata including the mode, or a stable error code when a
source precondition is unavailable.
Raises¶
ValueError If source checkpoint metadata or its expected digest is invalid.
Function request_live_training_weight_attach(target_job_id, source_job_id, job_manager)¶
Deliver verified weights to a running training job.
The command is confined to the worker control channel and applied at the next epoch boundary. Incompatible artifacts are rejected without stopping the target job.
Parameters¶
target_job_id : str Running target training job. source_job_id : str Completed source training job that published model weights. job_manager : StudioJobService Manager owning artifact reads and control-command delivery. expected_config_sha256 : str or None, optional Optional digest that the source configuration must match.
Returns¶
dict[str, Any]
Attach-request metadata, or a stable error code for a failed
precondition.
Raises¶
ValueError If source checkpoint metadata or its expected digest is invalid.
Function stop_training(job_id, job_manager)¶
Request cooperative stop for a Studio training job.
Parameters¶
job_id : str Training Monitor job identifier. job_manager : StudioJobService or None, optional Manager used to propagate cancellation into a process worker.
Returns¶
dict[str, Any]
stopping metadata, or an error payload for an unknown job.
Function get_training_status(job_id, job_manager)¶
Return path-free status for one Studio training job.
Parameters¶
job_id : str Training Monitor job identifier. job_manager : StudioJobService or None, optional Manager used to reconcile process state and verified evidence.
Returns¶
dict[str, Any] Current training status, metrics, checkpoint metadata, and optional evidence summary; unknown jobs return an error payload.
Function stream_metrics(job_id, job_manager)¶
Yield Server-Sent Events for one Studio training job.
Parameters¶
job_id : str Training Monitor job identifier. job_manager : StudioJobService or None, optional Manager used to tail process-worker JSONL events.
Yields¶
str One SSE-formatted metric, heartbeat, terminal, or error event.
Function list_jobs(job_manager)¶
Return path-free summaries for known Studio training jobs.
Returns¶
list[dict[str, Any]]
Creation-order job identifiers, statuses, and configurations from
the durable manager when supplied. Historical ledger rows without a
configuration snapshot report config: null rather than inventing
what ran. Without a manager, the legacy local registry is returned.
Function export_training_checkpoint(job_id, job_manager)¶
Return a portable checkpoint for one Studio training job.
Parameters¶
job_id : str Training Monitor job identifier. job_manager : StudioJobService or None, optional Manager used to attach verified terminal worker evidence.
Returns¶
dict[str, Any]
studio.training.checkpoint.v1 payload, or an error payload for an
unknown job.
Function import_training_checkpoint(data)¶
Validate a portable checkpoint and return its training configuration.
Parameters¶
data : dict[str, Any]
JSON object submitted to /api/training/checkpoint/import.
Returns¶
dict[str, Any] Validated source metadata, configuration, and optional weight-restore plan.
Raises¶
ValueError If the checkpoint schema or any protected digest is invalid.
Module studio.training_contract¶
Class TrainingConfigError¶
Raised when a training request names something the Studio cannot run.
Attributes¶
field : str The request key that was refused. reason : str What is wrong, in words a caller can act on. supported : tuple of str The accepted values, when the field has a closed set.
- init(field, reason, supported)
- to_public_detail()
- Return the path-free public error detail.
Class ResolvedTrainingConfig¶
A training request that the runner is able to execute exactly.
Attributes¶
dataset : str
One of :data:SUPPORTED_DATASETS.
epochs, batch_size, timesteps : int
Positive integers.
learning_rate, max_grad_norm : float
Positive finite floats.
hidden_widths : tuple of int
One width per hidden layer, in order, each honoured as given.
surrogate : str
One of :data:SUPPORTED_SURROGATES.
learn_beta, learn_threshold : bool
Whether the cell parameters are learned.
seed : int
Seed applied to every relevant generator, so a run is replayable.
event_data : EventTrainingContract or None
Manifest-bound temporal input for an event dataset; absent for static data.
preregistration : TrainingPreregistration or None
The acceptance criterion declared before the run; stored with the
configuration at submission and judged on the finished run.
model_kind : str
One of :data:SUPPORTED_MODEL_KINDS. On qcfs_conversion,
timesteps is the QCFS step budget and the converted network's
timestep budget, and the surrogate and cell flags keep their unused
defaults.
target_profile : str or None
A registered hardware profile the converted network is calibrated
for; only on qcfs_conversion.
- architecture(n_inputs, n_outputs)
- Return the layer sizes this configuration builds, in order.
- to_public_dict()
- Return the resolved configuration as the checkpoint records it.
Function resolve_training_config(payload)¶
Resolve a training request, refusing anything the Studio cannot run.
Parameters¶
payload : mapping
The request as received. Absent keys take their default; unknown keys
are refused rather than ignored, because a silently dropped hiddens
is a request nobody honoured.
Returns¶
ResolvedTrainingConfig Exactly what the runner will execute.
Raises¶
TrainingConfigError Any field names something unsupported, is the wrong type, or is out of range. The refusal happens before the dataset is loaded and before a model is built, so a rejected request costs nothing and leaves nothing.
Function list_target_profiles()¶
Return the hardware profiles a conversion run can be calibrated for.
Returns¶
list of dict Name, vendor, family, class and fixed-point format of every registered profile, ordered by name.
Module studio.training_preregistration¶
Class TrainingPreregistration¶
One criterion a finished run must meet on its validation split.
Attributes¶
metric : str
val_accuracy (passes at or above the threshold), val_loss or
conversion_accuracy_drop (each passes at or below it).
threshold : float
Finite bound; an accuracy or accuracy-drop bound lies in [0, 1],
a loss bound is non-negative.
rationale : str
The hypothesis the criterion tests, as declared before the run.
- direction()
- Return
at_leastorat_mostfor the declared metric. - sha256()
- Return the digest of the criterion's canonical JSON form.
- to_public_dict()
- Return the stored criterion, including its digest.
- judge(observed)
- Judge an unrounded validation metric against the criterion.
Function resolve_training_preregistration(value)¶
Resolve an optional criterion, refusing anything that cannot be judged.
Parameters¶
value : object
None for no criterion, or an object with metric, threshold,
an optional rationale and, when resubmitting a stored criterion,
its schema_version and sha256.
Returns¶
TrainingPreregistration or None The criterion exactly as it will be judged.
Raises¶
ValueError Unknown fields, an unknown metric, a bound outside the metric's range, an over-long rationale, another schema version, or a stored digest that does not match the criterion it accompanies.
Module studio.training_resume¶
Class TrainingResumeMismatch¶
Raised when saved run state does not belong to the run being started.
Attributes¶
field : str What differs — the configuration, the architecture or the schema. expected : str What the saved state describes. actual : str What the run being started describes.
- init(field, expected, actual)
- to_public_detail()
- Return the path-free public error detail.
Class TrainingResumeState¶
Everything a run needs to continue where another one stopped.
Attributes¶
schema_version : str
Resume contract version.
epochs_completed : int
How many epochs finished before this state was taken. A resume starts
at this index, so it neither repeats nor skips one.
architecture : str
Layer sizes of the network the state belongs to.
config : mapping
The resolved configuration of the run being continued.
optimiser_state : mapping
The optimiser's state_dict. Dropping it is what makes a warm start
a different run: Adam's moment estimates are part of where the run is.
rng_state : mapping
Python, NumPy and Torch generator states at the epoch boundary, so the
shuffle order and any stochastic layer continue rather than restart.
dataset_fingerprint : str
Digest of the data the run was trained on; a resume onto different
data is a different experiment.
- resolved_config()
- Return the configuration this state belongs to, re-resolved.
- to_public_dict()
- Return the JSON-safe summary a status payload may carry.
Function capture_resume_state()¶
Take the state a later run needs in order to continue this one.
Parameters¶
epochs_completed : int
Epochs finished at the moment of capture.
architecture : str
Layer sizes of the network being trained.
config : mapping
The resolved configuration of the run.
optimiser : torch.optim.Optimizer
The live optimiser; its state_dict is copied.
dataset_fingerprint : str
Digest of the data the run is training on.
Returns¶
TrainingResumeState Captured at an epoch boundary, which is the only point where the generator states describe a clean position in the run.
Function apply_resume_state(state)¶
Restore a saved position and return the epoch to start from.
Parameters¶
state : TrainingResumeState The saved position. optimiser : torch.optim.Optimizer The optimiser to load the saved state into. architecture : str Layer sizes of the network this run built. config : mapping The resolved configuration of this run.
Returns¶
int The epoch index to begin at.
Raises¶
TrainingResumeMismatch The saved state belongs to a different schema, network or configuration. Resuming across any of those would report a continuation of a run that never existed.
Function resume_state_from_payload(payload)¶
Rebuild a saved position from a weight checkpoint payload.
Parameters¶
payload : mapping
A loaded weight checkpoint's resume_state block.
Returns¶
TrainingResumeState The position the run was in when the checkpoint was written.
Raises¶
TrainingResumeMismatch The block is absent or was written by a different resume schema. A checkpoint from a build that recorded no position supports a warm start and nothing more, and saying so is the point.
Function dataset_fingerprint(loader)¶
Return a digest of the data a loader will serve.
Parameters¶
loader : torch.utils.data.DataLoader The training loader.
Returns¶
str
sha256 over the dataset's length, the batch size, the shape and
dtype of one sample, and the bytes of the first and last samples.
Notes¶
This is a fingerprint, not a content hash: it detects a different dataset, a different split boundary or a different sample layout, and it does not detect a change confined to the middle of a large corpus. Hashing every sample of a full dataset on every run would cost more than the training step it protects, so the boundary is stated rather than implied.
Module studio.workspace_lifecycle¶
Function fork_workspace(store, name, new_name)¶
Copy one revision into a new workspace as its first revision.
Raises¶
KeyError The source workspace or revision does not exist. WorkspaceConflict The destination workspace already exists; forking never overwrites one.
Function branch_conflicting_edit(store, name, state)¶
Keep an edit that lost a save conflict, instead of asking for it again.
A save from a stale revision is refused so it cannot overwrite the other editor's work, which is correct — but the refused edit then exists only in the editor's browser, and the message asks them to reapply it. This stores it as the first revision of its own workspace, so both edits survive and either can be compared, exported or merged by hand afterwards.
The branch records the workspace and revision it diverged from in its name, which is what a reader needs to reconcile the two later.
Parameters¶
store : WorkspaceStore
Store holding the workspace whose save was refused.
name : str
Workspace the edit was made against.
state : Mapping[str, Any]
The refused state, exactly as the editor had it.
base_revision : int
The revision the editor was working from.
branch_name : str, optional
Name for the branch. Defaults to "<name> (from revision <n>)".
Returns¶
WorkspaceRevision The first revision of the branch.
Raises¶
KeyError
The source workspace or base_revision does not exist, so the edit
does not describe a divergence from anything.
WorkspaceConflict
A workspace of that name already exists; branching never overwrites one.
Function delete_workspace(store, name)¶
Move a workspace aside so it can be restored.
Retained legacy files stay byte-identical. A durable marker beside the lock prevents their automatic re-adoption after deletion, including after restart. Trash tokens include a random suffix so equal clock readings cannot combine two independent revision directories.
Returns¶
pathlib.Path Where the workspace now lives.
Raises¶
KeyError The workspace does not exist.
Function deleted_workspaces(store)¶
Return the workspaces waiting in the trash, newest first.
Function restore_workspace(store, token)¶
Bring one deleted workspace back under its original name.
Raises¶
KeyError No deleted workspace carries that token. WorkspaceConflict A live workspace already holds the name; restoring would overwrite it, which is the loss this store exists to prevent.
Function export_workspace(store, name)¶
Return one revision as a self-contained document.
Function import_workspace(store, name, document)¶
Create a workspace from an exported document.
Raises¶
WorkspaceSchemaError The document is not a workspace this build reads. WorkspaceConflict The destination already exists.
Module studio.workspace_lock¶
Class WorkspaceLockTimeout¶
Raised when another writer held a workspace for longer than the wait.
Attributes¶
name : str The workspace that was busy. timeout : float The wait that elapsed, in seconds.
- init()
- to_public_detail()
- Return the path-free public error detail.
Function lock_path(root, name)¶
Return the lock database of one workspace under a project root.
Parameters¶
root : pathlib.Path The project root holding the workspaces. name : str Workspace name, one path segment.
Raises¶
ValueError The name is not a single path segment. The callers validate names already; this refuses rather than trusting them, because the result is a filesystem path.
Function workspace_lock(root, name)¶
Hold one workspace against every other writer for the block's duration.
Parameters¶
root : pathlib.Path The project root holding the workspaces. name : str Workspace name. timeout : float, optional How long to wait for another writer before refusing.
Yields¶
None The block runs with the workspace held.
Raises¶
WorkspaceLockTimeout Another thread or process held the workspace for the whole wait. Nothing was written. ValueError The name is not a single path segment.
Module studio.workspace_review¶
Class ReviewComment¶
One comment on one revision.
Function add_comment(store, name, revision)¶
Append a comment on name at revision.
Raises¶
KeyError
The workspace or the revision does not exist.
ValueError
The body is empty or longer than :data:MAX_COMMENT_CHARS, or
reply_to is not a comment on the same revision.
Function list_comments(store, name)¶
Return a workspace's comments, each checked against its revision.
Raises¶
KeyError The workspace does not exist.
Module studio.workspace_schema¶
Class WorkspaceSchemaError¶
Raised when a stored workspace cannot be read as one.
Function migrate_document(document)¶
Bring one stored workspace document forward to this schema.
Parameters¶
document : mapping The parsed contents of a revision file, or a legacy single-file project payload.
Returns¶
dict The document at the current schema version.
Raises¶
WorkspaceSchemaError The document is not an object, is missing its state, or was written by a newer schema. A newer document is refused rather than downgraded: dropping fields a future build added would lose a user's work quietly.
Function dump_canonical(document)¶
Serialise a workspace document deterministically.
Function write_atomic(path, payload)¶
Write one file so a reader never sees a partial one.
The payload goes to a temporary file beside the target, is flushed and
fsynced, and is then moved into place with os.replace. The
directory is fsynced too, so the rename itself survives a power loss.
A failure anywhere before the replace leaves the existing file untouched
and removes the temporary one.
Parameters¶
path : pathlib.Path Target file. Its parent directory must exist. payload : str Complete file contents.
Function read_document(path)¶
Read and migrate one stored workspace document.
Raises¶
WorkspaceSchemaError The file is unreadable, is not JSON, or is not a workspace this build understands. The message never contains the path.
Module studio.workspace_store¶
Class WorkspaceConflict¶
Raised when a save is made from a revision that is no longer current.
Attributes¶
expected : int or None The revision the caller believed was current. actual : int The revision that is current.
- init()
- to_public_detail()
- Return the path-free public error detail.
Class WorkspaceRevision¶
One immutable saved revision of a workspace.
Attributes¶
name : str Workspace name. revision : int Monotonic revision number, starting at 1. saved_at : float Unix timestamp the revision was written. state_sha256 : str Digest of the canonical state JSON. parent : int or None The revision this one was saved from.
- to_public_dict()
- Return a path-free JSON representation of this revision.
Class WorkspaceStore¶
A directory of workspaces, each an append-only list of revisions.
Parameters¶
root : pathlib.Path
Directory holding one subdirectory per workspace.
clock : callable, optional
Returns the current Unix timestamp; defaults to :func:time.time.
lock_timeout : float, optional
How long an operation waits for another writer of the same workspace
before being refused with
:class:~sc_neurocore.studio.workspace_lock.WorkspaceLockTimeout.
- init()
- lock(name)
- Hold one workspace against every other writer, in this process and others.
- root()
- Return the directory this store keeps workspaces in.
- workspace_dir(name)
- Return the directory holding one workspace's revisions and head.
- now()
- Return this store's clock, so collaborators stamp the same time.
- adopt_legacy(name)
- Bring a pre-revision workspace file into the revision layout.
- exists(name)
- Return whether a workspace has at least one revision.
- head_revision(name)
- Return the current revision number, or
Nonefor a new workspace. - save(name, state)
- Append one revision, refusing a save made from a stale one.
- load(name)
- Return one revision's document, defaulting to the current one.
- revisions(name)
- Return every stored revision of one workspace, oldest first.
- list_workspaces()
- Return one summary per workspace, by name.
- fork(name, new_name)
- Copy one revision into a new workspace; see
workspace_lifecycle. - branch_conflicting_edit(name, state)
- Keep an edit refused by a save conflict; see
workspace_lifecycle. - delete(name)
- Move a workspace aside so it can be restored.
- deleted()
- Return the workspaces waiting in the trash, newest first.
- restore(token)
- Bring one deleted workspace back under its original name.
- export_document(name)
- Return one revision as a self-contained document.
- import_document(name, document)
- Create a workspace from an exported document.
Function state_digest(state)¶
Return the digest of one workspace state's canonical JSON.
Module swarm.agent¶
Class AgentConfig¶
Hyper-parameters for a single swarm agent.
The sensory layout reserves 20 channels for neighbour, obstacle, target, field, emotional, and chemical inputs. Motor output must include at least speed and turn channels.
- post_init()
- Validate neural dimensions, dynamics, actuation, and seed domains.
Class SwarmAgent¶
Spiking-neural-network agent with soft-LIF dynamics.
Parameters¶
cfg : AgentConfig Neuron and network parameters. agent_id : int Unique identifier within the swarm.
- init(cfg, agent_id)
- n_weights()
- Return the flat trainable-weight vector length.
- weights()
- Return all trainable weights as a flat 1-D vector.
- weights(flat)
- Replace trainable weights from a finite exact-size vector.
- think(sensory)
- Run one SNN tick and return
(speed, turn_angle). - act(speed, turn)
- Update position and heading given finite motor commands.
- reset(rng, width, height)
- Reset kinematic and neural state while preserving trainable weights.
Module swarm.collective_fields¶
Class FieldConfig¶
Field layer hyper-parameters.
Class CollectiveFields¶
Chemical, emotional, and symbolic field layers for swarm communication.
Parameters¶
cfg : FieldConfig Field configuration. env_width : float Physical width of the environment (for coordinate mapping). env_height : float Physical height of the environment. n_agents : int Number of agents (for emotional field sizing).
- init(cfg, env_width, env_height, n_agents)
- diffuse(dt)
- Apply Laplacian diffusion + exponential decay to the chemical field.
- deposit_chemical(x, y, amount)
- Add amount of chemical at world coordinate
(x, y). - get_chemical_gradient(x, y)
- Return normalised (dx, dy) chemical gradient at
(x, y). - synchronize_emotions(coupling)
- Pull each agent's emotional vector toward the swarm mean.
- get_symbolic_at(x, y)
- Return the 2-channel symbolic vector at
(x, y). - deposit_symbolic(x, y, channel, amount)
- Deposit into a symbolic channel at
(x, y). - update(agents, env, dt)
- Run one collective-field tick.
Module swarm.fitness¶
Class SwarmFitness¶
Static fitness functions for swarm evaluation.
- coverage_score(positions, area)
- Fraction of the arena covered by the swarm.
- cohesion_score(positions)
- Reward moderate inter-agent distance (not too spread, not too clumped).
- alignment_score(headings)
- Mean resultant length of heading angles (Rayleigh statistic).
- target_score(positions, targets)
- Proximity reward: inverse mean distance to nearest target per agent.
- obstacle_penalty(positions, obstacles)
- Fraction of agents inside any obstacle (surface penetration).
- composite(env)
- Weighted sum of all objectives.
Module swarm.neuroevolution_swarm¶
Class EvolverConfig¶
Neuroevolution hyper-parameters for homogeneous swarm agents.
- post_init()
- Validate population, selection, mutation, evaluation, and seed domains.
Class SwarmEvolver¶
Genetic algorithm that evolves SNN weights for swarm control.
Parameters¶
cfg : EvolverConfig Evolution and evaluation parameters.
- init(cfg)
- evaluate_individual(weights)
- Create environment, inject weights into every agent, run, score.
- evolve_generation()
- Evaluate population, select, reproduce. Return best fitness.
- get_best_weights()
- Return the weight vector with the highest fitness.
- run(n_generations)
- Run n_generations of evolution. Return list of best fitnesses.
Module swarm.swarm_env¶
Class EnvConfig¶
Environment hyper-parameters.
Class SwarmEnvironment¶
2-D continuous arena for swarm simulation.
Parameters¶
cfg : EnvConfig Environment configuration.
- init(cfg)
- get_positions()
- Return (n_agents, 2) position array.
- get_headings()
- Return (n_agents,) heading array.
- get_pairwise_distances()
- Return (n_agents, n_agents) Euclidean distance matrix.
- get_neighbor_distances(agent_idx, k)
- Return sorted distances to the k nearest neighbours.
- get_obstacle_distances(agent_idx, k)
- Distances to the k nearest obstacle surfaces (negative = inside).
- get_target_distances(agent_idx, k)
- Distances to the k nearest targets.
- step(dt, fields)
- Advance the simulation by one tick.
- get_state()
- Return a JSON-serialisable snapshot.
Module symbolic.spike_logic¶
Class SpikeGate¶
Spike-based logic gate.
Parameters¶
gate_type : str 'AND', 'OR', 'NOT', 'NAND', 'XOR'
- call()
- lif_config()
- LIF neuron configuration for this gate.
Class SpikeRegister¶
Spike-based register: stores N bits using SR latch pairs.
Each bit is held by two neurons in mutual inhibition (bistable). Write: inject spike to set/reset neuron. Read: check which neuron of each pair is active.
Parameters¶
n_bits : int Register width.
- init(n_bits)
- write(value)
- Write an integer value to the register.
- read()
- Read the register as an integer.
- write_bits(bits)
- Write raw bit array.
- read_bits()
- Read raw bit array.
- clear()
Class SpikeALU¶
Spike-based Arithmetic Logic Unit.
Operations: ADD, SUB, AND, OR, XOR, CMP, SHIFT_LEFT, SHIFT_RIGHT. All implemented via spike-gate compositions.
Parameters¶
n_bits : int Word width.
- init(n_bits)
- add(a, b)
- Ripple-carry addition. Returns (result, carry_out).
- sub(a, b)
- Subtraction via two's complement: a - b = a + (~b + 1).
- bitwise_and(a, b)
- bitwise_or(a, b)
- bitwise_xor(a, b)
- compare(a, b)
- Compare: returns -1, 0, or 1.
- shift_left(a, n)
- shift_right(a, n)
Function spike_sort(values, n_bits)¶
Sort integers using spike-based comparison network.
Uses a bubble-sort topology where each compare-and-swap is implemented via SpikeALU.compare.
Parameters¶
values : list of int n_bits : int
Returns¶
list of int, sorted ascending
Module synapses.bcm¶
Class BCMSynapse¶
BCM synapse with sliding modification threshold.
Parameters¶
eta : float Learning rate. tau_theta : float Time constant for sliding threshold (ms). theta_init : float Initial threshold value. w_min, w_max : float Weight bounds.
- post_init()
- step(pre_rate, post_rate, dt)
- Advance one timestep.
- reset()
Module synapses.clopath_stdp¶
Class ClopathSTDP¶
Voltage-based STDP (Clopath et al. 2010).
Parameters¶
a_ltd : float LTD amplitude. Default: 14e-5 (Clopath 2010, Table 1). a_ltp : float LTP amplitude. Default: 8e-5. tau_x : float Pre-synaptic trace decay (ms). Default: 15. tau_minus : float Slow voltage trace decay (ms). Default: 10. tau_plus : float Fast voltage trace decay (ms). Default: 7. theta_minus : float LTD voltage threshold (mV). Default: -70.6 (rest). theta_plus : float LTP voltage threshold (mV). Default: -45.3 (depolarization). w_min, w_max : float Weight bounds.
- post_init()
- step(pre_spike, u_post, dt)
- Advance one timestep.
- reset()
Module synapses.dopamine_stdp¶
Class DopamineStdpSynapse¶
Dopamine-gated STDP synapse (Izhikevich 2007).
Parameters¶
weight : float Synaptic weight. Default: 0.5. w_min : float Minimum weight. Default: 0.0. w_max : float Maximum weight. Default: 1.0. tau_e : float Eligibility trace time constant (ms). Default: 1000.0. tau_da : float Dopamine decay time constant (ms). Default: 200.0. tau_pre : float Pre-synaptic trace time constant (ms). Default: 20.0. tau_post : float Post-synaptic trace time constant (ms). Default: 20.0. a_plus : float LTP amplitude. Default: 1.0. a_minus : float LTD amplitude (negative). Default: -1.0. lr : float Learning rate. Default: 0.001. dt : float Integration timestep (ms). Default: 1.0.
- post_init()
- step(pre_spike, post_spike, reward)
- Advance one timestep with spike indicators and reward signal.
- reset()
- Reset state to initial conditions.
Module synapses.dot_product¶
Class BitstreamDotProduct¶
Bitstream-level dot product via SC synapses.
For each input i, applies synapse_i (AND gate), then sums decoded probabilities: y ~ sum_i w_i * x_i.
Example¶
import numpy as np from sc_neurocore import BitstreamSynapse syns = [BitstreamSynapse(w_min=0.0, w_max=1.0, w=0.5, length=256) ... for _ in range(3)] dp = BitstreamDotProduct(synapses=syns) pre = np.ones((3, 256), dtype=np.uint8) post_matrix, y_scalar = dp.apply(pre) post_matrix.shape (3, 256)
- post_init()
- n_inputs()
- apply(pre_matrix, y_min, y_max)
- Apply all synapses to the pre-synaptic bitstreams and compute
Module synapses.gap_junction¶
Class GapJunction¶
Bidirectional electrical synapse.
Parameters¶
conductance : float Gap junction conductance g_c (nS). Typical: 0.01-1.0 nS. Bennett & Zukin, Neuron 2004. rectification : float Rectification factor in [0, 1]. 0 = fully bidirectional (ohmic), 1 = fully rectifying (current flows in one direction only). Default 0 (standard gap junction).
- post_init()
- Validate the conductance and rectification parameters.
- current(v_pre, v_post)
- Compute gap junction current flowing INTO v_post.
- current_matrix(voltages, adjacency)
- Compute gap junction currents for a population.
Module synapses.r_stdp¶
Class RewardModulatedSTDPSynapse¶
Reward-modulated STDP synapse (Izhikevich, Cerebral Cortex 17(10), 2007).
Eligibility trace accumulates Hebbian coincidences; weight update fires only when a global reward signal arrives.
Example¶
syn = RewardModulatedSTDPSynapse(w_min=0.0, w_max=1.0, w=0.5, length=64) for _ in range(20): ... syn.process_step(pre_bit=1, post_bit=1) syn.apply_reward(reward=1.0) # positive reward → potentiate syn.w >= 0.5 True
- post_init()
- process_step(pre_bit, post_bit)
- apply_reward(reward)
- Global reward signal triggers weight update.
Module synapses.sc_synapse¶
Class BitstreamSynapse¶
Stochastic-computing synapse using bitstreams.
Each synapse has a weight w in [w_min, w_max]. SC multiplication via bitwise AND: P(out=1) ~ P(pre=1) * P(w=1).
Example¶
import numpy as np syn = BitstreamSynapse(w_min=0.0, w_max=1.0, w=0.5, length=1024, seed=42) pre = np.ones(1024, dtype=np.uint8) # all-ones input post = syn.apply(pre) abs(post.mean() - 0.5) < 0.1 # output ~50% ones True
- post_init()
- encode_weight(w)
- Encode scalar weight w into a unipolar bitstream.
- update_weight(new_w)
- Change synaptic weight and recompute its bitstream.
- apply(pre_bits)
- Apply synapse to a pre-synaptic bitstream.
- effective_weight_probability()
- Decode the weight bitstream's probability P(weight_bit=1).
Module synapses.short_term_plasticity¶
Class ShortTermPlasticitySynapse¶
Short-term plasticity synapse (Tsodyks-Markram 1997).
Parameters¶
x : float Available resources (depression). Default: 1.0. u : float Release probability (facilitation). Default: 0.5. u_base : float Baseline release probability U. Default: 0.5. tau_d : float Depression recovery time constant (ms). Default: 200.0. tau_f : float Facilitation decay time constant (ms). Default: 20.0. amplitude : float Maximum PSC amplitude. Default: 1.0. dt : float Integration timestep (ms). Default: 1.0.
- post_init()
- new_depressing(cls)
- Create a depressing synapse (cortical pyr-pyr).
- new_facilitating(cls)
- Create a facilitating synapse (cortical pyr-interneuron).
- step(pre_spike)
- Advance one timestep. Returns post-synaptic current.
- reset()
- Reset state to initial conditions.
Module synapses.stochastic_stdp¶
Class StochasticSTDPSynapse¶
Stochastic synapse with spike-timing-dependent plasticity.
LTP on pre→post coincidence, LTD on pre-without-post. Asymmetry ratio from Bi & Poo, J. Neurosci. 18(24), 1998.
Example¶
syn = StochasticSTDPSynapse(w_min=0.0, w_max=1.0, w=0.5, length=64) for _ in range(100): ... syn.process_step(pre_bit=1, post_bit=1) # correlated activity → LTP syn.w >= 0.5 # weight increased or stayed True
- post_init()
- process_step(pre_bit, post_bit)
- Process one timestep: compute output, update trace, apply STDP.
Module synapses.tripartite¶
Class TripartiteSynapse¶
Synapse with bidirectional astrocyte coupling.
Parameters¶
base_weight : float Baseline synaptic weight. glut_per_spike : float IP3 production rate per pre-synaptic spike (µM/s). ca_threshold : float Astrocyte Ca²⁺ threshold for gliotransmitter release (µM). facilitation : float Multiplicative gain when astrocyte is active (> 1 for facilitation). depression_rate : float Weight depression rate when astrocyte Ca²⁺ is below threshold. w_min, w_max : float Weight bounds.
- post_init()
- step(pre_spike, post_spike, dt)
- Advance one timestep.
- ca()
- Current astrocyte Ca²⁺ concentration (µM).
- ip3()
- Current astrocyte IP3 concentration (µM).
- effective_weight()
- Current effective synaptic weight.
- reset()
Module synapses.triplet_stdp¶
Class TripletSTDP¶
Triplet STDP synapse (Pfister-Gerstner 2006).
Parameters¶
tau_plus : float Pre-synaptic trace decay (ms). Default: 16.8 (visual cortex fit). tau_minus : float Post-synaptic trace decay (ms). Default: 33.7. tau_x : float Slow pre-synaptic trace decay (ms). Default: 101. tau_y : float Slow post-synaptic trace decay (ms). Default: 125. a2_plus : float Pair LTP amplitude. Default: 7.5e-10. a3_plus : float Triplet LTP amplitude. Default: 9.3e-3. a2_minus : float Pair LTD amplitude. Default: 7.0e-3. a3_minus : float Triplet LTD amplitude. Default: 2.3e-4. w_min : float Minimum weight. Default: 0.0. w_max : float Maximum weight. Default: 1.0.
- post_init()
- step(pre_spike, post_spike, dt)
- Advance one timestep.
- reset()
Module temporal_hierarchy.multi_clock¶
Class ClockDomain¶
One clock domain in a multi-clock SNN.
Parameters¶
name : str tick_interval : int Steps between updates (1 = every step, 10 = every 10th step). layers : list of str Layer names assigned to this clock domain.
Class HetSynLayer¶
Layer with heterogeneous per-synapse time constants.
Each synapse has its own tau, initialized log-normally (mean=5ms, std=1ms). The synaptic trace at each synapse decays at its own rate: trace[i,j] = exp(-dt/tau[i,j]) * trace[i,j] + input_spike[j]
Parameters¶
n_inputs : int n_neurons : int tau_mean : float Mean synaptic time constant (ms). tau_std : float Std of log(tau) for log-normal initialization. threshold : float seed : int
- init(n_inputs, n_neurons, tau_mean, tau_std, threshold, seed)
- step(x, dt)
- Process one timestep.
- reset()
- tau_stats()
Class MultiClockSNN¶
Multi-clock SNN with different temporal resolutions per layer.
Parameters¶
layers : list of HetSynLayer Network layers. clock_domains : list of ClockDomain Clock domain assignments.
- init(layers, layer_names, clock_intervals)
- step(x, dt)
- Process one global timestep.
- run(inputs, dt)
- Run full sequence.
- reset()
Module topology.analyzer¶
Class TopologyReport¶
Network topology analysis report.
- summary()
Class TopologyAnalyzer¶
Analyse SNN connectivity structure.
Parameters¶
adjacency : ndarray of shape (N, N)
Binary adjacency matrix or weight matrix (nonzero = edge).
directed : bool
If True, treat as directed graph.
n_path_samples : int
Maximum number of source nodes used by _avg_path_length.
For N <= n_path_samples the result is the true all-pairs
average; for larger graphs it is a sample mean over the first
n_path_samples nodes (deterministic, not randomised).
Default 100. Set to 0 or a very large value to force full
all-pairs (expensive at N >> 100).
- init(adjacency, directed, n_path_samples)
- analyze()
- Run full topology analysis.
Module training.delay_linear¶
Class DelayLinear¶
Linear layer with trainable per-synapse delays.
Parameters¶
in_features : int Number of input neurons. out_features : int Number of output neurons. max_delay : int Maximum delay in timesteps. Delay buffer stores this many steps. bias : bool Include bias term (default False for SNN). learn_delay : bool Make delays trainable (default True). init_delay : float Initial delay value for all synapses (default 1.0).
Forward pass¶
Call step(input_spikes) at each timestep. The module maintains
an internal spike history buffer. For each synapse (i, j):
delayed_input[j] = sum_i W[j,i] * interp(history, t - D[j,i])
where interp linearly interpolates between integer delay bins, making D differentiable.
Export¶
delays_int returns quantized integer delays for hardware deployment.
to_nir_delay_array() returns delays in the CSR format expected by
Projection(delay=array).
- init(in_features, out_features, max_delay, bias, learn_delay, init_delay)
- reset()
- Clear spike history. Call between sequences.
- step(x)
- Process one timestep.
- delays_int()
- Quantized integer delays for hardware export.
- to_nir_delay_array()
- Export delays as flat array matching CSR data order.
- extra_repr()
Module training.encoding¶
Function rate_encode(x, n_timesteps)¶
Poisson rate coding. Higher values spike more often.
x: values in [0, 1], shape (batch). Returns (T, batch).
Function latency_encode(x, n_timesteps, tau)¶
Time-to-first-spike latency coding. Stronger input → earlier spike.
x: values in [0, 1], shape (batch). Returns (T, batch).
Function delta_encode(x, threshold)¶
Delta coding: spike on temporal change exceeding threshold.
x: shape (T, *batch). Returns same shape with spikes where |dx| > threshold.
Module training.equilibrium_propagation¶
Class EPNetwork¶
Multi-layer Equilibrium Propagation network.
Parameters¶
layer_sizes : list of int Number of units per layer (including input and output). rng_seed : int Random seed for reproducibility.
- init(layer_sizes, rng_seed)
- train(x_batch, y_batch)
- Train on a mini-batch using the EP two-phase protocol.
- predict(x, n_settle)
- Predict output by settling in free phase.
- get_params()
- Return serialisable parameter dict.
Module training.loops¶
Function auto_device()¶
Select a usable supported device in priority order: CUDA, MPS, CPU.
Function train_epoch(model, loader, optimizer, n_timesteps, loss_fn, device, max_grad_norm, flatten_input)¶
One training epoch. Returns (avg_loss, accuracy).
Parameters¶
flatten_input : bool If True (default), flatten data to (batch, features) for feedforward SNNs. Set to False for convolutional models that need spatial dimensions.
Function evaluate(model, loader, n_timesteps, loss_fn, device, flatten_input)¶
Evaluate model. Returns (avg_loss, accuracy).
Module training.losses¶
Function spike_count_loss(spike_counts, targets)¶
Cross-entropy on spike counts. Bohte 2011.
Function membrane_loss(membrane_acc, targets)¶
Cross-entropy on accumulated membrane potential.
Function spike_rate_loss(spike_counts, targets, n_timesteps, target_rate)¶
MSE between output spike rates and one-hot target pattern.
Function spike_l1_loss(spike_counts, n_timesteps)¶
L1 penalty on mean spike rate. Encourages sparse firing.
Function spike_l2_loss(spike_counts, n_timesteps)¶
L2 penalty on mean spike rate. Penalizes high-firing neurons.
Module training.sc_correlation_regularizers¶
Function correlation_matrix(streams)¶
Return Pearson correlation matrix across bitstream rows.
Function pairwise_correlation_penalty(streams)¶
Penalize off-diagonal stream correlations above threshold.
Function correlation_penalty(observed)¶
Differentiable mean-square penalty toward a target correlation.
Module training.sc_estimators¶
Class DifferentiableSCConfig¶
Validated contract for differentiable SC training operators.
- post_init()
Class RelaxedSCProduct¶
Result bundle for a differentiable relaxed SC product.
- length_cost()
Class SCBitstreamSample¶
Sampled SC bitstreams with decoded values.
Class SCBitstreamStatistics¶
Rate, variance, and correlation evidence for sampled bitstreams.
Class SampledSCProduct¶
Decoded sampled SC multiply result and stream statistics.
Function sample_sc_bitstreams(values, config)¶
Sample deterministic SC bitstreams for training-time statistics.
Function estimate_bitstream_statistics(streams)¶
Return rate, variance, and Pearson correlation evidence for bitstreams.
Function relaxed_sc_multiply(input_value, weight_value, config)¶
Return differentiable expected SC multiplication under the config contract.
Function sampled_sc_multiply(input_value, weight_value, config)¶
Sample SC bitstreams, multiply them, and decode the empirical product.
Function finite_difference_gradients(input_value, weight_value, config)¶
Central finite-difference gradients for deterministic relaxed SC operators.
Module training.snn_modules¶
Class SCWeightNoiseModel¶
Deterministic export-time noise model for SC weight probabilities.
- post_init()
- metadata()
Class LIFCell¶
Single-step Leaky Integrate-and-Fire with surrogate backward.
v[t] = beta * v[t-1] + I[t] spike[t] = H(v[t] - threshold) v[t] -= spike[t] * threshold (subtract reset)
- init(beta, threshold, surrogate_fn, learn_beta, learn_threshold)
- beta()
- threshold()
- forward(current, v)
Class IFCell¶
Integrate-and-Fire (no leak, beta=1).
Simplest spiking model: v[t] = v[t-1] + I[t], fire when v >= threshold.
- init(threshold, surrogate_fn, learn_threshold)
- threshold()
- forward(current, v)
Class SynapticCell¶
Dual-exponential synaptic LIF. Two state variables: synapse current + membrane.
i_syn[t] = alpha * i_syn[t-1] + I[t] v[t] = beta * v[t-1] + i_syn[t]
- init(alpha, beta, threshold, surrogate_fn, learn_beta, learn_threshold)
- beta()
- threshold()
- forward(current, i_syn, v)
- Returns (spike, i_syn_next, v_next).
Class ALIFCell¶
Adaptive LIF. Bellec et al. 2020.
Threshold adapts based on recent spiking: theta[t] = theta_0 + beta_adapt * a[t] where a[t] = rho * a[t-1] + spike[t-1].
- init(beta, threshold, rho, beta_adapt, surrogate_fn)
- forward(current, v, a)
- Returns (spike, v_next, a_next).
Class ExpIFCell¶
Exponential Integrate-and-Fire. Fourcaud-Trocmé et al. 2003.
v[t] = beta * v[t-1] + delta_T * exp((v[t-1] - v_rh) / delta_T) + I[t] Exponential term creates sharp upstroke near threshold.
- init(beta, threshold, delta_t, v_rh, surrogate_fn, learn_beta, learn_threshold)
- beta()
- threshold()
- forward(current, v)
Class AdExCell¶
Adaptive Exponential IF. Brette & Gerstner 2005.
v[t] = beta * v[t-1] + delta_T * exp((v - v_rh) / delta_T) - w[t-1] + I[t] w[t] = rho * w[t-1] + a * (v[t-1] - v_rest) + b * spike[t]
- init(beta, threshold, delta_t, v_rh, a, b, rho, v_rest, surrogate_fn, learn_beta, learn_threshold)
- beta()
- threshold()
- forward(current, v, w)
Class LapicqueCell¶
SC hard-reset RC training cell with a historical public name.
This differentiable recurrent cell preserves the project's later LIF compatibility convention; it is not the complete Lapicque 1907 polarization-threshold experiment.
tau * dv/dt = -(v - v_rest) + R * I Discretised: v[t] = (1 - dt/tau) * v[t-1] + (R * dt / tau) * I[t]
- init(tau, r, dt, threshold, v_rest, surrogate_fn, learn_threshold)
- threshold()
- forward(current, v)
Class AlphaCell¶
Alpha synapse neuron. Rall 1967.
Two-state alpha function: i_exc and i_inh with separate time constants. v[t] = beta * v[t-1] + i_exc[t] - i_inh[t]
- init(alpha_exc, alpha_inh, beta, threshold, surrogate_fn, learn_beta, learn_threshold)
- beta()
- threshold()
- forward(exc_current, inh_current, i_exc, i_inh, v)
Class SecondOrderLIFCell¶
Second-order LIF with inertial term. Dayan & Abbott 2001.
Adds a second state variable (acceleration) for smoother dynamics: a[t] = alpha * a[t-1] + I[t] v[t] = beta * v[t-1] + a[t]
- init(alpha, beta, threshold, surrogate_fn, learn_beta, learn_threshold)
- beta()
- threshold()
- forward(current, a, v)
Class RecurrentLIFCell¶
LIF with trainable recurrent weights.
- init(n_neurons, beta, threshold, surrogate_fn, learn_beta, learn_threshold)
- forward(current, v, spike_prev)
Class SpikingNet¶
Multi-layer feedforward SNN for classification.
Architecture: [Linear -> LIF] x (hidden layers + 1) Readout: spike count and membrane accumulation over T timesteps.
Parameters¶
n_input : int
Input feature count.
n_hidden : int or sequence of int
One width for every hidden layer, or a single width repeated
n_layers times. A sequence is honoured exactly: [128, 64]
builds a 128-unit layer and then a 64-unit layer, never 128 twice.
n_output : int
Output class count.
n_layers : int
Hidden layer count when n_hidden is a single width. Ignored when
n_hidden is a sequence, which already states how many layers there
are; passing a contradicting value is refused rather than silently
resolved one way.
beta : float
Membrane decay for every cell.
surrogate_fn : callable
Surrogate gradient used by every cell.
learn_beta, learn_threshold : bool
Whether the cell parameters are learned.
Raises¶
ValueError
n_hidden names a non-positive width, or is a sequence whose
length contradicts an explicit n_layers. An empty sequence is
accepted: it builds the direct input-to-output layer.
- init(n_input, n_hidden, n_output, n_layers, beta, surrogate_fn, learn_beta, learn_threshold)
- forward(x)
- x: (T, batch, n_input). Returns (spike_counts, membrane_acc).
- to_sc_weights(include_bias, noise_model, encoding)
- Export weight matrices for SC bitstream deployment.
Class ConvSpikingNet¶
Convolutional SNN for image classification.
Conv2d(1,32,5)→LIF→AvgPool→Conv2d(32,64,5)→LIF→AvgPool→Flatten→Linear→LIF→Linear→LIF
- init(n_output, beta, surrogate_fn, learn_beta, learn_threshold)
- forward(x)
- x: (T, batch, 1, 28, 28). Returns (spike_counts, membrane_acc).
- to_sc_weights(include_bias, noise_model, encoding)
- Export weight matrices for SC bitstream deployment.
Module training.stochastic_backprop¶
Class SCTrainingObjectiveConfig¶
Weights and targets for SC-aware training objective components.
- post_init()
Class SCResourceProxy¶
Hardware proxy values used in SC-aware objective shaping.
- post_init()
- normalized_cost()
- Return a dimensionless bounded-scale resource proxy.
Class SCObjectiveBreakdown¶
Named scalar components of an SC-aware training objective.
Class SCBackpropDesignSpace¶
Discrete SC architecture choices exposed to differentiable joint training.
- post_init()
Class SCBackpropJointReport¶
Joint stochastic-backpropagation result with exportable SC design metadata.
Function relaxed_sc_linear(input_value, weight, bias, sc_config)¶
Linear layer whose multiply-accumulate path uses relaxed SC products.
Function stochastic_training_objective(task_loss)¶
Compose task loss with SC length, correlation, variance, and resource costs.
Function stochastic_backprop_joint_objective(inputs, targets)¶
Train a relaxed SC layer jointly over weights and SC architecture variables.
The selected config remains discrete and exportable, while length, encoding, and correlation costs are computed from differentiable proxies so one objective can update model parameters and stochastic-computing design variables in the same backward pass.
Module training.stochastic_backprop_export¶
Function build_stochastic_backprop_export_manifest(benchmark_report, sc_config)¶
Build a deterministic SC-NIR handoff manifest for stochastic backpropagation.
Function write_stochastic_backprop_export_manifest(path, benchmark_report, sc_config)¶
Write a canonical stochastic backpropagation SC-NIR export manifest.
Function write_stochastic_backprop_handoff_bundle(export_manifest, output_dir)¶
Materialise an auditable SC-NIR HDL handoff bundle from an export manifest.
Module training.surrogate¶
Function fast_sigmoid_custom_op(x, slope)¶
Heaviside forward, fast-sigmoid backward via torch.library.custom_op.
Function fast_sigmoid_legacy(x, slope)¶
Heaviside forward, fast-sigmoid backward via legacy autograd.
Function fast_sigmoid(x, slope)¶
Heaviside forward, fast-sigmoid backward.
Function superspike_custom_op(x, beta)¶
Heaviside forward, SuperSpike backward via torch.library.custom_op.
Function superspike_legacy(x, beta)¶
Heaviside forward, SuperSpike backward via legacy autograd.
Function superspike(x, beta)¶
Heaviside forward, SuperSpike backward.
Function atan_surrogate_custom_op(x, alpha)¶
Heaviside forward, arctan backward via torch.library.custom_op.
Function atan_surrogate_legacy(x, alpha)¶
Heaviside forward, arctan backward via legacy autograd.
Function atan_surrogate(x, alpha)¶
Heaviside forward, arctan backward.
Function sigmoid_surrogate_custom_op(x, slope)¶
Heaviside forward, sigmoid backward via torch.library.custom_op.
Function sigmoid_surrogate_legacy(x, slope)¶
Heaviside forward, sigmoid backward via legacy autograd.
Function sigmoid_surrogate(x, slope)¶
Heaviside forward, sigmoid backward.
Function straight_through_custom_op(x)¶
Heaviside forward, identity backward via torch.library.custom_op.
Function straight_through_legacy(x)¶
Heaviside forward, identity backward via legacy autograd.
Function straight_through(x)¶
Heaviside forward, identity backward (STE).
Function triangular_custom_op(x, width)¶
Heaviside forward, triangular backward via torch.library.custom_op.
Function triangular_legacy(x, width)¶
Heaviside forward, triangular backward via legacy autograd.
Function triangular(x, width)¶
Heaviside forward, triangular window backward.
Module training.utils¶
Class SpikeMonitor¶
Record spikes per layer during forward pass.
Attach to a SpikingNet or ConvSpikingNet to capture spike activity at each layer per timestep. Useful for raster plots and diagnostics.
monitor = SpikeMonitor(model)
spk, mem = model(x)
raster = monitor.get("lifs.0") # (T, batch, n_neurons)
monitor.reset()
- init(model)
- get(name)
- Get recorded spikes for a named module. Returns (T, *shape) or None.
- layer_names()
- Return names of modules that currently have spike hooks attached.
- reset()
- Clear recorded spike tensors while keeping hooks attached.
- remove()
- Remove forward hooks and clear all recorded spike tensors.
Function reset_states(monitors)¶
Clear SpikeMonitor recorded data.
Parameters¶
monitors : list of SpikeMonitor, optional Monitors to reset. If None, does nothing.
Note: this does NOT reset membrane voltages or adaptation variables.
To reset neuron state, re-initialize the model or call forward()
with fresh zero-initialized hidden states. To reset a single
monitor, call monitor.reset() directly.
Function model_info(model)¶
Quick architecture summary for SNN models.
Function population_decode(spike_counts, preferred_values)¶
Decode spike counts with a population-vector weighted average.
Instead of argmax, computes a weighted average of preferred values based on spike counts. More informative than winner-take-all.
Parameters¶
spike_counts : torch.Tensor Shape (batch, n_neurons). Spike counts per neuron. preferred_values : torch.Tensor or None Shape (n_neurons,) or (n_neurons, d). If None, uses neuron indices.
Returns¶
torch.Tensor Decoded values, shape (batch,) or (batch, d).
Module transfer.checkpoint¶
Class SNNCheckpoint¶
Complete dense-weight SNN checkpoint for transfer workflows.
Parameters¶
weights:
One two-dimensional weight matrix per layer. A matrix shape must be
(output_features, input_features) for the matching layer_sizes
entry (input_features, output_features).
layer_names:
Unique layer names in forward order.
layer_sizes:
(input_features, output_features) pairs for each layer.
neuron_types:
Optional neuron-model labels, either empty or one label per layer.
metadata:
JSON-serializable provenance or training metadata.
frozen_layers:
Layer names currently marked non-trainable.
- post_init()
- Normalize arrays and reject inconsistent checkpoint state.
- n_layers()
- Return the number of serialized layers.
- total_params()
- Return the total number of scalar weight parameters.
Function save_checkpoint(checkpoint, path)¶
Save an SNN checkpoint to path.npz plus path.json.
Parameters¶
checkpoint: Validated checkpoint to serialize. path: Base path without extension. Parent directories are created.
Function load_checkpoint(path)¶
Load and validate an SNN checkpoint from path.npz and path.json.
Parameters¶
path: Base path without extension.
Returns¶
SNNCheckpoint:
Reconstructed checkpoint with finite float64 weight arrays.
Module transfer.fine_tune¶
Class TransferConfig¶
Configuration for checkpoint-based SNN transfer learning.
Parameters¶
freeze_until:
Freeze all layers up to and including this layer name or index. -1
means do not add frozen layers.
lr_backbone:
Learning rate for frozen backbone layers, usually zero or a small value.
lr_head:
Learning rate for unfrozen task-head layers.
- post_init()
- Reject invalid freeze targets and learning rates.
Function freeze_layers(checkpoint, layer_names, until_index)¶
Mark checkpoint layers as frozen.
Parameters¶
checkpoint: Checkpoint to mutate. layer_names: Specific layer names to freeze. until_index: Freeze every layer with index less than or equal to this value.
Returns¶
SNNCheckpoint:
The same checkpoint object with frozen_layers updated.
Function unfreeze_layers(checkpoint, layer_names, all_layers)¶
Mark checkpoint layers as trainable.
Parameters¶
checkpoint: Checkpoint to mutate. layer_names: Specific layer names to unfreeze. all_layers: When true, clear every frozen-layer marker.
Returns¶
SNNCheckpoint:
The same checkpoint object with frozen_layers updated.
Function apply_transfer_config(checkpoint, config)¶
Apply a transfer config and return per-layer learning rates.
Parameters¶
checkpoint:
Checkpoint to mutate according to config.
config:
Validated transfer schedule.
Returns¶
tuple[SNNCheckpoint, list[float]]: The mutated checkpoint and one learning rate per layer.
Module transformers.block¶
Class StochasticTransformerBlock¶
Spiking transformer block (S-Former).
Structure: input -> multi-head attention -> add & norm -> feed forward -> add & norm -> output.
- post_init()
- Validate the block dimensions and build the attention heads and FFN.
- forward(x)
- Run the block on input of shape (d_model,) or (seq_len, d_model).
Module transformers.spikformer¶
Class SpikeDrivenAttention¶
Spike-Driven Self-Attention (SSA).
Replaces Q*K^T softmax with spike-based masking: Attention = SpikeFn(Q_linear(S)) * SpikeFn(K_linear(S))^T * V_linear(S)
All operations reduce to AND gates on binary spikes — zero multiplications, pure SC-compatible logic.
Parameters¶
embed_dim : int Embedding dimension. num_heads : int Number of attention heads. T : int Number of simulation timesteps. threshold : float Spike threshold for Q/K projections.
- post_init()
- Derive the head dimension and initialise the projection weights.
- forward(x)
- Forward pass: spike-driven attention over T timesteps.
- num_multiply_ops()
- Zero multiplications in the attention core (AND gates only).
Class SpikyStateSpace¶
Spiking State-Space Model (S4-SNN hybrid).
Combines linear state-space dynamics with spiking nonlinearity: h_t = A * h_{t-1} + B * spike_input_t y_t = C * h_t spike_t = IF(y_t > threshold)
Runs in O(1) memory per timestep (no BPTT unrolling needed). Reference: SpikySpace (2025).
Parameters¶
d_model : int Input/output dimension. d_state : int Hidden state dimension. threshold : float Spiking threshold. dt : float Discretization timestep.
- post_init()
- Initialise the discretised state-space matrices.
- reset()
- Reset hidden state and membrane potential.
- step(x)
- Process one timestep.
- forward(x_seq)
- Process a full sequence.
Class CPGPositionalEncoding¶
Central Pattern Generator positional encoding.
Replaces sinusoidal positional encoding with biologically-inspired CPG oscillators. Each dimension has a different frequency and phase, generating spike-compatible temporal position signals.
Parameters¶
d_model : int Encoding dimension. max_len : int Maximum sequence length.
- post_init()
- Sample the central-pattern-generator oscillator frequencies.
- encode(seq_len)
- Generate positional encoding.
- encode_spikes(seq_len, rng)
- Generate spike-encoded positional encoding.
Module utils.adapter_discovery¶
Function discover_adapters()¶
Discover adapter classes and register them in the global registry.
Parameters¶
include_first_party : bool, default=True
Register the built-in adapter importers declared by
:data:FIRST_PARTY_ADAPTERS. This source-level path keeps editable
checkouts wired even before packaging metadata is installed.
include_entry_points : bool, default=True
Load installed third-party plugins from
:data:ADAPTER_ENTRY_POINT_GROUP through importlib.metadata.
Returns¶
dict[str, type] Mapping from registry name to the discovered adapter class. Duplicate registry entries are tolerated so repeated discovery is idempotent.
Module utils.adaptive¶
Class AdaptiveInference¶
Manages Progressive Precision / Early Exit for SC.
- run_adaptive(step_func)
- Runs the SC process step-by-step until convergence or max_length.
Module utils.bitstreams¶
Class BitstreamEncoder¶
Helper for encoding continuous scalar values into SC bitstreams using linear unipolar mapping. Example
encoder = BitstreamEncoder(x_min=0.0, x_max=0.1, length=1024, seed=123) bitstream = encoder.encode(0.06) # 60% ones p_hat = bitstream_to_probability(bitstream) x_rec = encoder.decode(bitstream)
- post_init()
- encode(x)
- Encode one scalar into a stochastic bitstream.
- decode(bitstream)
- Decode a stochastic bitstream back into the configured value range.
Class BitstreamAverager¶
Sliding-window probability estimator for bitstreams.
Example¶
avg = BitstreamAverager(window=100) for _ in range(100): ... avg.push(1) avg.estimate() 1.0 avg.push(0) avg.estimate() < 1.0 True
- post_init()
- push(bit)
- Add one binary sample to the sliding window.
- estimate()
- Return the current sliding-window probability estimate.
- reset()
- Clear all buffered samples and reset the estimator state.
Function generate_bernoulli_bitstream(p, length, rng)¶
Generate a Bernoulli bitstream of given length with probability p of '1'. This is the core SC primitive: a sequence of 0/1 bits where the proportion of 1s ~ p. Parameters
p : float Probability of 1 (unipolar encoding, 0 <= p <= 1). length : int Number of bits in the stream. rng : RNG, optional RNG instance. If None, a fresh RNG is created. Returns
np.ndarray Array of shape (length,) with dtype=uint8, values in {0,1}.
Function generate_sobol_bitstream(p, length, seed)¶
Generate a bitstream using a Sobol sequence (Low Discrepancy Sequence). LDS provides faster convergence than random Bernoulli sequences (O(1/N) vs O(1/sqrt(N))).
Parameters¶
p : float Target probability. length : int Length of the bitstream. seed : int, optional Seed for the Sobol engine.
Returns¶
np.ndarray Array of shape (length,) with dtype=uint8, values in {0,1}.
Function bitstream_to_probability(bitstream)¶
Decode a unipolar bitstream back into a probability estimate. p_hat = (# of ones) / length
Function generate_bipolar_bitstream(x, length, rng)¶
Generate a bipolar SC bitstream encoding a value in [-1, +1].
Bipolar encoding: value x in [-1, 1] maps to probability p = (x + 1) / 2. Bit=1 with probability p, bit=0 with probability 1-p. Decoding: x = 2 * mean(bits) - 1.
Bipolar multiplication uses XNOR: P(A XNOR B) encodes A*B in bipolar.
Function bipolar_to_value(bitstream)¶
Decode a bipolar bitstream to a value in [-1, +1].
x = 2 * mean(bits) - 1
Function value_to_bipolar_prob(x)¶
Map a value in [-1, 1] to the unipolar probability used in bipolar encoding.
p = (x + 1) / 2. This p is then used with standard Bernoulli generation.
Function value_to_unipolar_prob(x, x_min, x_max, clip)¶
Map a scalar x from [x_min, x_max] into a unipolar probability [0,1]. Linear mapping: p = (x - x_min) / (x_max - x_min) If clip=True, x is clipped into [x_min, x_max].
Function unipolar_prob_to_value(p, x_min, x_max)¶
Map a unipolar probability p in [0,1] back to a scalar in [x_min, x_max]. Inverse of value_to_unipolar_prob.
Function adaptive_length(p, epsilon, confidence, method, min_length, max_length)¶
Compute minimum bitstream length for target precision.
Given probability p and error tolerance epsilon, returns the smallest L such that |p_hat - p| < epsilon with the given confidence.
Parameters¶
p : float Encoded probability in [0, 1]. epsilon : float Maximum acceptable absolute error. confidence : float Confidence level (e.g. 0.95 for 95%). method : str Bound type: "hoeffding" (tighter), "chebyshev", or "variance" (no confidence). min_length : int Minimum returned length. max_length : int Maximum returned length (hardware cap).
Returns¶
int Minimum bitstream length (rounded up to nearest power of 2 for Sobol compatibility).
Function sc_divide(numerator, denominator)¶
Stochastic computing division via CORDIV circuit.
Li, Qian, Riedel & Bazargan, IEEE Trans. Signal Process. 62(9), 2014.
Sequential circuit: at each bit position t, - x[t]=1 → z[t] = 1 - x[t]=0, y[t]=1 → z[t] = 0 - x[t]=0, y[t]=0 → z[t] = z[t-1] (hold)
Converges to P(z=1) ≈ P(x=1) / P(y=1) when P(x) ≤ P(y).
Parameters¶
numerator : np.ndarray Bitstream (uint8, {0,1}) of length L. denominator : np.ndarray Bitstream (uint8, {0,1}) of length L. Must have higher or equal density.
Returns¶
np.ndarray Quotient bitstream of length L.
Module utils.connectomes¶
Class ConnectomeGenerator¶
Generates biologically plausible connectivity matrices.
- generate_watts_strogatz(n_neurons, k_neighbors, p_rewire)
- Watts-Strogatz Small-World Model.
- generate_scale_free(n_neurons)
- Barabasi-Albert Scale-Free Model (Preferential Attachment).
Module utils.decorrelators¶
Class Decorrelator¶
Base class for bitstream decorrelators.
- process(bitstream)
Class ShufflingDecorrelator¶
Decorrelates a bitstream by randomly shuffling bits within a window. This preserves the exact bit count (probability) but destroys temporal correlations.
- post_init()
- process(bitstream)
Class LFSRRegenDecorrelator¶
Regenerates a new bitstream with the same probability estimate but using a different random source (LFSR-like or just new RNG).
- post_init()
- process(bitstream)
Module utils.deprecation¶
Function deprecated(since, removal, alternative)¶
Mark a function or class as deprecated.
Example::
@deprecated(since="3.11", removal="4.0", alternative="new_func")
def old_func():
...
Parameters¶
since : str Version where deprecation was introduced. removal : str Version where the function will be removed. alternative : str, optional Name of the replacement function/class.
Module utils.fault_injection¶
Class FaultInjector¶
Simulates hardware faults in Stochastic Computing bitstreams.
- inject_bit_flips(bitstream, error_rate)
- Randomly flips bits with probability 'error_rate'.
- inject_stuck_at(bitstream, fault_rate, value)
- Simulates Stuck-At-0 or Stuck-At-1 faults.
Module utils.fsm_activations¶
Class FSMActivation¶
Base class for FSM-based stochastic activation functions.
The FSM takes a bitstream input and transitions between states. The output bit is determined by the current state (e.g., if state > N/2, out=1). This implements saturating non-linearities like Tanh or Sigmoid efficiently.
- post_init()
- step(bit)
- process(bitstream)
Class TanhFSM¶
Implements a Tanh-like function using a linear FSM.
States: 0 to N-1 Input 0: state -> max(0, state - 1) Input 1: state -> min(N-1, state + 1) Output: 1 if state >= N/2 else 0
- init(states)
- step(bit)
Class ReLKFSM¶
Implements a Rectified Linear (ReLU-like) behavior. Can be complex in SC, often approximated or used with bipolar coding. Here we implement a simple saturating counter.
- init(states)
- step(bit)
Module utils.lds_decorrelation¶
Function generate_decorrelated_bitstreams(probabilities, length, method, seed)¶
Generate decorrelated bitstreams for a probability matrix.
Each element of the probability matrix gets its own LDS dimension, ensuring zero correlation between any pair of bitstreams.
Parameters¶
probabilities : np.ndarray[Any, Any] Probability matrix, any shape. Values in [0, 1]. length : int Bitstream length per element. method : str "sobol" or "halton". seed : int or None Random seed for scrambling.
Returns¶
np.ndarray[Any, Any] Shape (*probabilities.shape, length), dtype uint8.
Function star_discrepancy_estimate(samples, n_test)¶
Estimate star discrepancy of a sample set (quality metric for LDS).
Lower discrepancy → more uniform coverage → better SC precision.
Parameters¶
samples : np.ndarray[Any, Any] Shape (n_samples, d), values in [0, 1]. n_test : int Number of random test points.
Returns¶
float Estimated star discrepancy.
Module utils.logging¶
Class JSONFormatter¶
Emit log records as single-line JSON objects.
- format(record)
Function configure_logging(level, json, stream)¶
Configure the sc_neurocore logger hierarchy.
Parameters¶
level : str or int
Log level name ("DEBUG", "INFO", etc.) or numeric level.
json : bool
If True, use :class:JSONFormatter for machine-parseable output.
stream
Output stream. Defaults to sys.stderr.
Module utils.model_bridge¶
Class SCBridge¶
Bridge between standard DL frameworks (like PyTorch) and SC-NeuroCore.
- load_from_state_dict(state_dict, layer_mapping)
- Load weights from a state_dict (numpy or torch tensors) into SC layers.
- export_to_numpy(layers)
- Export SC weights back to numpy dictionary.
Function normalize_weights(weights)¶
Normalizes weights to [0, 1] range for unipolar SC.
Module utils.numerics¶
Function safe_exp(x)¶
exp() with argument clipped to [-500, 500] to prevent overflow.
Function safe_cosh(x)¶
cosh() with argument clipped to [-500, 500] to prevent overflow.
Function safe_tanh(x)¶
tanh() with argument clipped to [-500, 500].
Function boltzmann(v, v_half, k)¶
Boltzmann sigmoid: 1 / (1 + exp((v_half - v) / k)). Overflow-safe.
Function boltzmann_inv(v, v_half, k)¶
Inverse Boltzmann: 1 / (1 + exp((v - v_half) / k)). Overflow-safe.
Function clip_gating(x)¶
Clip gating variable to physiological range [0, 1].
Function clip_voltage(v, v_min, v_max)¶
Clip membrane voltage to safe range (default [-200, 100] mV).
Module utils.profiling¶
Function estimate_memory(layers, unit)¶
Estimate memory usage of a list of SC layers.
Example::
from sc_neurocore import VectorizedSCLayer
from sc_neurocore.utils.profiling import estimate_memory
layers = [
VectorizedSCLayer(n_inputs=50, n_neurons=128, length=256),
VectorizedSCLayer(n_inputs=128, n_neurons=10, length=256),
]
print(estimate_memory(layers))
# {'weights_bytes': 56320, 'packed_bytes': 112640, ...}
Parameters¶
layers : list
SC layer objects with .weights and .length attributes.
unit : str
"B", "KB", or "MB".
Returns¶
dict Breakdown: weights_bytes, packed_bytes, neuron_state_bytes, total_bytes, total_human.
Module utils.registry¶
Class ComponentRegistry¶
Thread-safe component registry with namespace support.
- init()
- register(namespace, name)
- Decorator to register a class under namespace/name.
- get(namespace, name)
- Retrieve a registered class. Raises
KeyErrorif missing. - list(namespace)
- Return sorted names in namespace.
- namespaces()
- Return all registered namespaces.
- clear(namespace)
- Remove all entries (or just one namespace).
Module utils.rng¶
Class RNG¶
Deterministic wrapper around NumPy's per-instance random generator.
The wrapper is intentionally small: it exposes the distributions used by stochastic-computing utilities while enforcing scalar parameter domains before NumPy mutates generator state. Scalar draws return Python scalars; shaped draws return dtype-stable NumPy arrays.
Example¶
rng = RNG(seed=42) vals = rng.random(5) vals.shape (5,) RNG(seed=42).random(5) == vals # deterministic array([ True, True, True, True, True])
- init(seed)
- Create an independent stream from a non-negative integer seed.
- normal(mean, std, size)
- Draw samples from a normal distribution.
- uniform(low, high, size)
- Draw samples from a bounded uniform distribution.
- bernoulli(p, size)
- Draw Bernoulli samples from a validated probability.
- random(size)
- Draw uniform samples from the half-open interval
[0, 1). - shuffle(x)
- Shuffle an array in place using this instance's random stream.
Module uvm_gen._benchmark¶
Class UVMBenchmark¶
Complete generated UVM testbench.
- to_dict()
- Return generated artefacts keyed by their output filenames.
Module uvm_gen._config¶
Class StimulusConfig¶
Configuration for randomised SC bitstream stimulus.
Class CoverageSpec¶
Functional coverage specification.
Class ScoreboardConfig¶
Scoreboard configuration for golden model comparison.
Class FormalLink¶
Link between UVM assertions and SymbiYosys formal proofs.
Class SimTarget¶
Simulation tool target for Makefile generation.
Module uvm_gen._generator¶
Class UVMGenerator¶
Generates complete UVM verification IP from an RTL module spec.
- init(stimulus, coverage, scoreboard)
- generate(rtl)
- Generate the complete UVM testbench for an RTL module.
- generate_multi(modules)
- Generate UVM testbenches for multiple modules.
- generate_formal_links(rtl)
- Generate formal-to-dynamic links for existing SymbiYosys modules.
Module uvm_gen._rtl¶
Class PortDirection¶
SystemVerilog port direction tokens accepted by the UVM generator.
Class PortType¶
SystemVerilog net/data type tokens emitted for module ports.
Class ModulePort¶
Parsed RTL port metadata used by generated UVM components.
- sv_decl()
- Return the SystemVerilog declaration for this parsed port.
- is_clock()
- Return whether the port name matches a supported clock convention.
- is_reset()
- Return whether the port name matches a supported reset convention.
Class ModuleParam¶
RTL module parameter.
Class RTLModule¶
Parsed RTL module specification.
- from_verilog_source(cls, source)
- Parse a Verilog/SystemVerilog module header.
- input_ports()
- Input ports excluding generated clock and reset controls.
- output_ports()
- Output ports monitored by the generated scoreboard and coverage.
- clock_port()
- First parsed clock-like port, if the RTL module declares one.
- reset_port()
- First parsed reset-like port, if the RTL module declares one.
- total_input_bits()
- Total data-input width excluding clock and reset ports.
- total_output_bits()
- Total output width observed by generated verification components.
Module verification.formal_proofs¶
Class Interval¶
- add(other)
- mul(other)
- repr()
Class FormalVerifier¶
Interval arithmetic checker for stochastic probability bounds and energy safety constraints. Not an SMT solver.
- verify_probability_bounds(input_interval, weight_interval)
- Prove that Output Probability is always in [0, 1].
- verify_energy_safety(energy, cost)
- Prove that operation will not consume more energy than available.
Module verification.safety¶
Class CodeSafetyVerifier¶
AST blocklist screen for auto-generated code.
Walks the AST and rejects code containing known-dangerous patterns: filesystem mutation, process spawning, network access, code execution, and unrestricted imports.
Limitations: this is a static blocklist, not a sandbox. It catches common dangerous patterns but cannot prove semantic safety, model data flow, or reason about values assembled before screening. Do not use as a security boundary without additional sandboxing.
- verify_code_safety(source_code)
- Return whether
source_codepasses the static blocklist. - verify_logic_invariant(func, input_sample, expected_condition)
- Return whether a dynamic invariant holds for one input sample.
Module verification.snn_standard¶
Class VerificationLevel¶
Evidence levels for SNN verification claims.
Class VerificationEvidenceKind¶
Kinds of evidence accepted by the standard.
Class VerificationClaimStatus¶
Status of one evidence item or standard requirement.
Class SNNVerificationEvidence¶
One evidence item used in a formal SNN verification claim.
- post_init()
- to_dict()
- Return a JSON-ready evidence record.
Class SNNVerificationRequirement¶
One mandatory or optional requirement in a standard profile.
- post_init()
- to_dict()
- Return a JSON-ready requirement.
Class SNNVerificationStandardProfile¶
Named set of requirements for a formal SNN verification claim.
- post_init()
- to_dict()
- Return a JSON-ready profile.
Class SNNVerificationRequirementResult¶
Evaluation of one profile requirement.
- to_dict()
- Return a JSON-ready requirement result.
Class SNNVerificationConformanceReport¶
Conformance report for a profile and evidence set.
- passed()
- Whether all mandatory requirements passed.
- missing_mandatory()
- Mandatory requirement ids with missing evidence.
- failed_mandatory()
- Mandatory requirement ids with failing evidence.
- mandatory_coverage()
- Coverage ratio for mandatory requirements.
- to_dict()
- Return a JSON-ready conformance report.
Class SNNVerificationStandard¶
Evaluate SNN verification evidence against a standard profile.
- init(profile)
- assess(evidence)
- Assess evidence against the configured profile.
Function publication_grade_snn_standard_profile()¶
Return the default formal SNN verification standard profile.
Function assess_snn_verification_standard(evidence, profile)¶
Assess evidence against the default or supplied SNN verification profile.
Module verification.temporal_properties¶
Class PropertyResult¶
Outcome states returned by temporal property verification checks.
Class Counterexample¶
Input that violates a property.
Class VerificationResult¶
Result of a temporal property check.
- summary()
- Format the verification outcome and optional counterexample.
Function fires_within(spikes, neuron_id, stimulus_times, max_latency)¶
Verify that neuron fires within max_latency steps of each stimulus.
Parameters¶
spikes : ndarray of shape (T, N) neuron_id : int stimulus_times : list of int Timesteps when stimulus was applied. max_latency : int Maximum allowed response latency in timesteps.
Function mutual_exclusion(spikes, neuron_set)¶
Verify that no two neurons in the set fire at the same timestep.
Parameters¶
spikes : ndarray of shape (T, N) neuron_set : list of int Neuron IDs that should never co-fire.
Function rate_bound(spikes, neuron_id, max_rate, window_size)¶
Verify firing rate stays below max_rate in every sliding window.
Parameters¶
spikes : ndarray of shape (T, N) neuron_id : int max_rate : float Maximum allowed firing rate (spikes per step). window_size : int Sliding window size in timesteps.
Function refractory_guarantee(spikes, neuron_id, min_gap)¶
Verify minimum inter-spike interval.
Parameters¶
spikes : ndarray of shape (T, N) neuron_id : int min_gap : int Minimum required gap between consecutive spikes (timesteps).
Function causal_order(spikes, neuron_a, neuron_b, max_delay)¶
Verify that neuron A fires before neuron B within max_delay.
For every spike of neuron B, there must be a spike of neuron A within the preceding max_delay timesteps.
Parameters¶
spikes : ndarray of shape (T, N) neuron_a, neuron_b : int max_delay : int
Function bounded_activity(spikes, neuron_set, window_size, max_total_spikes)¶
Verify total spike count in neuron set stays bounded per window.
Parameters¶
spikes : ndarray of shape (T, N) neuron_set : list of int window_size : int max_total_spikes : int
Module viz.neuro_art¶
Class NeuroArtGenerator¶
Generates Art (Images) from Neural State.
- generate_visual(state_vector)
- Maps a 1D state vector to a 2D RGB abstract image.
Module viz.plots¶
Function raster_plot(spike_monitor, ax, color, marker, s)¶
Spike raster from a SpikeMonitor.
Function voltage_trace(state_monitor, neuron_ids, ax)¶
Membrane voltage traces from a StateMonitor.
Function firing_rate_plot(spike_monitor, bin_ms, ax)¶
Population firing rate histogram (spikes per bin).
Function isi_histogram(spike_monitor, neuron_id, bins, ax)¶
Inter-spike interval distribution for a single neuron.
Function cross_correlogram(spike_monitor, i, j, max_lag_ms, ax)¶
Spike cross-correlation between neurons i and j.
Function population_activity(spike_monitor, bin_ms, ax)¶
Heatmap of binned spike counts per neuron.
Function phase_portrait(state_monitor, var_x, var_y, neuron_id, ax)¶
2-D phase-plane trajectory for a single neuron.
Function weight_matrix(projection, ax, cmap)¶
Connectivity weight heatmap from a Projection's CSR data.
Function network_graph(network, ax)¶
Node/edge diagram of populations and projections.
Function psd_plot(spike_monitor, neuron_id, ax)¶
Power spectral density of a single neuron's spike train.
Function instantaneous_rate_plot(spike_monitor, neuron_id, sigma_ms, ax)¶
Gaussian-kernel-smoothed instantaneous firing rate.
Function spike_train_comparison(trains, labels, ax)¶
Overlay multiple spike trains as event plots.
Parameters¶
trains : list of np.ndarray[Any, Any] Each element is a 1-D array of spike timesteps. labels : list of str, optional Labels for each train.
Module viz.web_viz¶
Class WebVisualizer¶
Generates a standalone HTML file to visualize the SC Network.
- generate_html(layers, filename)
Module world_model._lgssm_backends¶
Function probe_backend(backend)¶
Return runtime availability and a precise unavailability reason.
Function resolve_backend(backend)¶
Resolve an explicit or fastest-first automatic backend selection.
Function filter_native(backend, model, observations, controls)¶
Execute a resolved non-Python backend with validated float64 buffers.
Module world_model._lgssm_em¶
Class EMLearner¶
Estimate selected LGSSM parameters by expectation-maximisation.
Parameters¶
max_iter : int, default=50 Positive maximum number of E/M iterations. tol : float, default=1e-4 Non-negative absolute log-likelihood convergence threshold.
Notes¶
The M-step updates A, C, Q, R, mu_0, and
Sigma_0. B and D are treated as known, but their control
contributions are subtracted from the transition and observation
sufficient statistics as required by Shumway and Stoffer (1982).
Raises¶
ValueError
If max_iter or tol is outside its documented domain.
- init(max_iter, tol)
- fit(observations, initial_model, controls, backend)
- Estimate model parameters from one observation sequence.
Module world_model._lgssm_filter¶
Class KalmanFilter¶
Forward Kalman filter for a linear Gaussian state-space model.
Parameters¶
model : LinearGaussianSSM Validated model parameters shared by the Python and native paths.
- init(model)
- filter(observations, controls, backend)
- Filter an observation sequence.
Module world_model._lgssm_smoothing¶
Class RTSSmoother¶
Rauch-Tung-Striebel backward smoother.
Parameters¶
model : LinearGaussianSSM Model used to produce the corresponding forward-filter result.
Notes¶
The recursion follows Rauch, Tung, and Striebel (1965). The returned
lag-one covariance is oriented as Cov[x_t, x_{t+1} | y].
- init(model)
- smooth(filter_result)
- Smooth every state in a validated forward-filter result.
Module world_model._lgssm_types¶
Class LinearGaussianSSM¶
Parameters of a discrete-time linear Gaussian state-space model.
Parameters¶
A : numpy.ndarray, shape (d, d)
State-transition matrix.
B : numpy.ndarray, shape (d, m)
Control-input matrix. Use an empty second dimension when m = 0.
C : numpy.ndarray, shape (p, d)
Observation matrix.
D : numpy.ndarray, shape (p, m)
Direct control-to-observation matrix.
Q : numpy.ndarray, shape (d, d)
Symmetric positive-semidefinite process covariance.
R : numpy.ndarray, shape (p, p)
Symmetric positive-definite observation covariance.
mu_0 : numpy.ndarray, shape (d,)
Prior state mean.
Sigma_0 : numpy.ndarray, shape (d, d)
Symmetric positive-definite prior covariance.
Raises¶
ValueError If a parameter has an incompatible shape, non-finite value, or invalid covariance contract.
- post_init()
- Copy parameters into finite, C-contiguous float64 arrays and validate them.
- state_dim()
- Return the latent-state dimension
d. - obs_dim()
- Return the observation dimension
p. - control_dim()
- Return the control-input dimension
m. - random(cls, state_dim, obs_dim, control_dim, seed)
- Construct a stable random model for initialisation and examples.
Class FilterResult¶
Forward-filter posterior and one-step prediction moments.
Parameters¶
means : numpy.ndarray, shape (T, d) Filtered state means. covariances : numpy.ndarray, shape (T, d, d) Filtered state covariances. pred_means : numpy.ndarray, shape (T, d) One-step predicted state means before observing each sample. pred_covariances : numpy.ndarray, shape (T, d, d) One-step predicted state covariances. log_likelihood : float Sequence log-likelihood under the model.
- post_init()
- Validate result shapes, finiteness, symmetry, and covariance signs.
Class SmoothResult¶
Rauch-Tung-Striebel smoothed state moments.
Parameters¶
means : numpy.ndarray, shape (T, d)
Smoothed state means.
covariances : numpy.ndarray, shape (T, d, d)
Smoothed state covariances.
cross_covariances : numpy.ndarray, shape (T - 1, d, d)
Lag-one covariances Cov[x_t, x_{t+1} | y_{0:T-1}].
- post_init()
- Validate smoothed moment shapes, finiteness, and covariance signs.
Module world_model._predictive_world_model¶
Class PredictiveWorldModel¶
Forecast latent-state means and covariances through an LGSSM.
Parameters¶
state_dim : int Positive latent-state dimension. action_dim : int Non-negative action dimension. seed : int, default=42 Seed used to initialise the stable random LGSSM.
Notes¶
This class preserves the historical planning-facing API. Use
:class:LinearGaussianSSM, :class:KalmanFilter, and
:class:RTSSmoother when observations are available.
- post_init()
- Initialise a validated stable state-transition model.
- reset()
- Reset the stored belief moments to the model prior.
- predict_next_state(current_state, action)
- Predict the next latent-state mean.
- predict_next_state_with_cov(current_state, current_cov, action)
- Predict the next latent-state mean and covariance.
- forecast(initial_state, actions)
- Forecast a deterministic mean trajectory.
- forecast_with_cov(initial_state, initial_cov, actions)
- Forecast a mean and covariance trajectory.
Module world_model.planner¶
Class SCPlanner¶
A planner that uses a PredictiveWorldModel to select actions.
- propose_action(current_state, goal_state, n_candidates)
- Propose the best action among n_candidates based on predicted outcome.
- plan_sequence(current_state, goal_state, horizon)
- Simple greedy planning for a sequence of actions.
Module world_model.predictive_model¶
Function __getattr__(name)¶
Return the live historical Rust-availability flag on private access.
Module world_model.spike_predictor¶
Class SpikePredictor¶
Online autoregressive spike pattern predictor.
Learns to predict spike[t] from spike[t-K:t] per channel. Weight matrix W of shape (N, N*K) maps flattened history to per-channel firing probabilities. Binary prediction via threshold.
Training: LMS update after each timestep. W += lr * outer(error, history) where error = actual - predicted_prob.
Parameters¶
n_channels : int Number of spike channels. history_len : int Number of past timesteps to use as context (K). lr : float LMS learning rate. threshold : float Probability threshold for binary prediction. seed : int RNG seed for weight initialization.
- post_init()
- Seed the RNG and initialise the predictor weights.
- predict_probs()
- Predict per-channel firing probabilities from history.
- predict()
- Predict binary spike pattern.
- update(actual)
- Update weights with observed spike pattern (LMS rule).
- reset()
- Reset to initial state (same seed → same weights).
Function predict_and_xor_world_model(spikes, n_channels, history_len, lr, threshold, seed)¶
World-model predict-XOR loop for codec compression.
Returns (errors, correct_count).
Function xor_and_recover_world_model(errors, n_channels, history_len, lr, threshold, seed)¶
World-model XOR-recover loop for codec decompression.