#![allow(clippy::module_name_repetitions)]
#![allow(
clippy::cast_possible_truncation,
clippy::cast_possible_wrap,
clippy::cast_sign_loss
)]
use core::num::{NonZeroU32, NonZeroU64};
pub const MEMBRANE_MV_MIN: i16 = -100;
pub const MEMBRANE_MV_MAX: i16 = 50;
#[inline]
#[must_use]
pub fn dt_over_tau(dt_us: u32, tau_membrane_us: u32) -> i64 {
let Some(tau) = NonZeroU32::new(tau_membrane_us) else {
return 0;
};
if dt_us <= u32::MAX / 1000 {
i64::from(dt_us * 1000 / tau)
} else {
dt_over_tau_wide(dt_us, tau)
}
}
#[cold]
#[inline(never)]
fn dt_over_tau_wide(dt_us: u32, tau_membrane_us: NonZeroU32) -> i64 {
let raw = (u64::from(dt_us) * 1000) / NonZeroU64::from(tau_membrane_us);
raw as i64
}
#[inline]
fn div_1000(x: i64) -> i64 {
if let Ok(y) = i32::try_from(x) {
i64::from(y / 1000)
} else {
div_1000_wide(x)
}
}
#[cold]
#[inline(never)]
fn div_1000_wide(x: i64) -> i64 {
x / 1000
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum VoltageResolution {
Millivolt,
CentiMillivolt,
}
impl VoltageResolution {
#[must_use]
pub const fn scale(self) -> i32 {
match self {
Self::Millivolt => 1,
Self::CentiMillivolt => 100,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum NeuronType {
Excitatory,
Inhibitory,
}
#[derive(Debug, Clone)]
pub struct LIFNeuron {
pub(crate) id: u16,
pub(crate) neuron_type: NeuronType,
pub(crate) membrane_potential: i16,
pub(crate) resting_potential: i16,
pub(crate) threshold: i16,
pub(crate) reset_potential: i16,
pub(crate) voltage_resolution: VoltageResolution,
pub(crate) tau_membrane_us: u32,
pub(crate) refractory_period_us: u32,
pub(crate) refractory_remaining_us: u32,
pub(crate) last_update_time_us: u32,
pub(crate) last_spike_time_us: u32,
pub(crate) synaptic_current_pa: i16,
pub(crate) resistance_mohm: u16,
pub(crate) noise_amplitude_pa: u8,
pub(crate) adaptation_current_pa: i16,
pub(crate) adaptation_enabled: bool,
}
impl LIFNeuron {
#[must_use]
pub const fn new(id: u16, neuron_type: NeuronType, resolution: VoltageResolution) -> Self {
let (threshold_mv, tau_membrane_us) = match neuron_type {
NeuronType::Excitatory => (-55, 20_000), NeuronType::Inhibitory => (-50, 10_000), };
let s = resolution.scale();
Self {
id,
neuron_type,
membrane_potential: (-70 * s) as i16,
resting_potential: (-70 * s) as i16,
threshold: (threshold_mv * s) as i16,
reset_potential: (-80 * s) as i16,
voltage_resolution: resolution,
tau_membrane_us,
refractory_period_us: 2_000,
refractory_remaining_us: 0,
last_update_time_us: 0,
last_spike_time_us: 0,
synaptic_current_pa: 0,
resistance_mohm: 100,
noise_amplitude_pa: 0,
adaptation_current_pa: 0,
adaptation_enabled: true,
}
}
#[must_use]
pub const fn with_resting_potential(mut self, quanta: i16) -> Self {
self.resting_potential = quanta;
self.membrane_potential = quanta;
self
}
#[must_use]
pub const fn with_threshold(mut self, quanta: i16) -> Self {
self.threshold = quanta;
self
}
#[must_use]
pub const fn with_reset_potential(mut self, quanta: i16) -> Self {
self.reset_potential = quanta;
self
}
#[must_use]
pub const fn with_tau_membrane_us(mut self, us: u32) -> Self {
self.tau_membrane_us = us;
self
}
#[must_use]
pub const fn with_refractory_period_us(mut self, us: u32) -> Self {
self.refractory_period_us = us;
self
}
#[must_use]
pub const fn with_resistance_mohm(mut self, mohm: u16) -> Self {
self.resistance_mohm = mohm;
self
}
#[must_use]
pub const fn with_noise_amplitude_pa(mut self, pa: u8) -> Self {
self.noise_amplitude_pa = pa;
self
}
#[must_use]
pub const fn with_adaptation_enabled(mut self, enabled: bool) -> Self {
self.adaptation_enabled = enabled;
self
}
#[must_use]
pub fn id(&self) -> u16 {
self.id
}
#[must_use]
pub fn neuron_type(&self) -> NeuronType {
self.neuron_type
}
#[must_use]
pub fn voltage_resolution(&self) -> VoltageResolution {
self.voltage_resolution
}
#[must_use]
pub fn membrane_potential(&self) -> i16 {
self.membrane_potential
}
#[must_use]
pub fn resting_potential(&self) -> i16 {
self.resting_potential
}
#[must_use]
pub fn threshold(&self) -> i16 {
self.threshold
}
#[must_use]
pub fn reset_potential(&self) -> i16 {
self.reset_potential
}
#[must_use]
pub fn tau_membrane_us(&self) -> u32 {
self.tau_membrane_us
}
#[must_use]
pub fn refractory_period_us(&self) -> u32 {
self.refractory_period_us
}
#[must_use]
pub fn refractory_remaining_us(&self) -> u32 {
self.refractory_remaining_us
}
#[must_use]
pub fn synaptic_current_pa(&self) -> i16 {
self.synaptic_current_pa
}
#[must_use]
pub fn resistance_mohm(&self) -> u16 {
self.resistance_mohm
}
#[must_use]
pub fn noise_amplitude_pa(&self) -> u8 {
self.noise_amplitude_pa
}
#[must_use]
pub fn adaptation_current_pa(&self) -> i16 {
self.adaptation_current_pa
}
#[must_use]
pub fn adaptation_enabled(&self) -> bool {
self.adaptation_enabled
}
#[inline]
pub fn integrate_and_fire(
&mut self,
input_current_pa: i16,
dt_us: u32,
current_time_us: u32,
) -> bool {
self.last_update_time_us = current_time_us;
if self.refractory_remaining_us > 0 {
self.refractory_remaining_us = self.refractory_remaining_us.saturating_sub(dt_us);
return false;
}
let noise = self.generate_noise(current_time_us);
let total_current = input_current_pa
.saturating_add(self.synaptic_current_pa)
.saturating_add(noise)
.saturating_sub(self.adaptation_current_pa);
let s = i64::from(self.voltage_resolution.scale());
let dt_over_tau = dt_over_tau(dt_us, self.tau_membrane_us);
let leak_term = i64::from(self.resting_potential) - i64::from(self.membrane_potential);
let current_term = div_1000(i64::from(total_current) * i64::from(self.resistance_mohm) * s);
let delta_v = div_1000(dt_over_tau.saturating_mul(leak_term + current_term));
let new_v = i64::from(self.membrane_potential)
.saturating_add(delta_v)
.clamp(
i64::from(MEMBRANE_MV_MIN) * s,
i64::from(MEMBRANE_MV_MAX) * s,
);
self.membrane_potential = new_v as i16;
if self.membrane_potential >= self.threshold {
self.spike(current_time_us);
true
} else {
false
}
}
fn spike(&mut self, current_time_us: u32) {
self.membrane_potential = self.reset_potential;
self.refractory_remaining_us = self.refractory_period_us;
self.last_spike_time_us = current_time_us;
if self.adaptation_enabled {
self.adaptation_current_pa = self.adaptation_current_pa.saturating_add(2);
}
}
pub fn add_synaptic_current(&mut self, current_pa: i16) {
self.synaptic_current_pa = self.synaptic_current_pa.saturating_add(current_pa);
}
pub fn clear_synaptic_current(&mut self) {
self.synaptic_current_pa = 0;
}
pub fn decay_adaptation_current(&mut self) {
if self.adaptation_current_pa > 0 {
self.adaptation_current_pa = self.adaptation_current_pa.saturating_sub(1);
}
}
pub fn reset(&mut self) {
self.membrane_potential = self.resting_potential;
self.refractory_remaining_us = 0;
self.last_update_time_us = 0;
self.last_spike_time_us = 0;
self.synaptic_current_pa = 0;
self.adaptation_current_pa = 0;
}
fn generate_noise(&self, current_time_us: u32) -> i16 {
if self.noise_amplitude_pa == 0 {
return 0;
}
let mut lfsr = u32::from(self.id) ^ current_time_us;
for _ in 0..4 {
lfsr = (lfsr >> 1) ^ (if lfsr & 1 != 0 { 0xB400_u32 } else { 0 });
}
let raw = (lfsr & 0xFF) as i16 - 128; (raw * i16::from(self.noise_amplitude_pa)) / 128
}
}
#[cfg(test)]
impl LIFNeuron {
fn set_voltage_resolution(&mut self, resolution: VoltageResolution) {
if resolution == self.voltage_resolution {
return;
}
let new_s = resolution.scale();
let old_s = self.voltage_resolution.scale();
let rescale = |v: i16| -> i16 { ((i32::from(v) * new_s) / old_s) as i16 };
self.membrane_potential = rescale(self.membrane_potential);
self.resting_potential = rescale(self.resting_potential);
self.threshold = rescale(self.threshold);
self.reset_potential = rescale(self.reset_potential);
self.voltage_resolution = resolution;
}
fn is_refractory(&self) -> bool {
self.refractory_remaining_us > 0
}
}
#[cfg(test)]
mod tests {
#![allow(clippy::shadow_unrelated)]
use super::*;
use crate::spike_recorder::SpikeRecorder;
use proptest::prelude::*;
#[test]
fn new_excitatory_neuron_has_default_params() {
let n = LIFNeuron::new(1, NeuronType::Excitatory, VoltageResolution::Millivolt);
assert_eq!(n.id, 1);
assert_eq!(n.neuron_type, NeuronType::Excitatory);
assert_eq!(n.membrane_potential, -70);
assert_eq!(n.threshold, -55);
assert_eq!(n.tau_membrane_us, 20_000);
assert_eq!(n.noise_amplitude_pa, 0);
}
#[test]
fn inhibitory_neuron_has_different_params() {
let n = LIFNeuron::new(2, NeuronType::Inhibitory, VoltageResolution::Millivolt);
assert_eq!(n.threshold, -50);
assert_eq!(n.tau_membrane_us, 10_000);
}
#[test]
fn neuron_fields_directly_configurable() {
let mut n = LIFNeuron::new(3, NeuronType::Inhibitory, VoltageResolution::Millivolt);
n.threshold = -45;
n.tau_membrane_us = 15_000;
assert_eq!(n.id, 3);
assert_eq!(n.neuron_type, NeuronType::Inhibitory);
assert_eq!(n.threshold, -45);
assert_eq!(n.tau_membrane_us, 15_000);
}
#[test]
fn resolution_switch_rescales_stored_potentials() {
let mut n = LIFNeuron::new(
10,
NeuronType::Excitatory,
VoltageResolution::CentiMillivolt,
);
n.membrane_potential = -6_000;
n.set_voltage_resolution(VoltageResolution::Millivolt);
assert_eq!(n.membrane_potential, -60);
assert_eq!(n.threshold, -55);
assert_eq!(n.reset_potential, -80);
}
#[test]
fn positive_current_raises_membrane_potential() {
let mut n = LIFNeuron::new(4, NeuronType::Excitatory, VoltageResolution::Millivolt);
let initial = n.membrane_potential;
let spiked = n.integrate_and_fire(100, 10_000, 10_000);
assert!(
n.membrane_potential > initial,
"membrane should rise with sustained positive input (was {}, now {})",
initial,
n.membrane_potential
);
assert!(!spiked, "single 10 ms step at 100 pA should not spike");
}
fn quiet_neuron(id: u16, r: VoltageResolution) -> LIFNeuron {
let mut n = LIFNeuron::new(id, NeuronType::Excitatory, r);
n.noise_amplitude_pa = 0;
n
}
#[test]
fn millivolt_trace_is_pinned_to_the_historical_arithmetic() {
let mut n = quiet_neuron(11, VoltageResolution::Millivolt);
let expected = [-67, -65, -63, -61, -59, -57];
for &want in &expected {
let spiked = n.integrate_and_fire(600, 1000, 0);
assert!(!spiked);
assert_eq!(n.membrane_potential, want);
}
let spiked = n.integrate_and_fire(600, 1000, 0);
assert!(spiked, "7th 600 pA step crosses −55");
assert_eq!(n.membrane_potential, -80, "spike reset");
}
#[test]
fn the_dead_zone_12pa_pair() {
let mut mv = quiet_neuron(12, VoltageResolution::Millivolt);
mv.integrate_and_fire(12, 1000, 0);
assert_eq!(mv.membrane_potential, -70, "mV grid: 12 pA ⇒ ΔV = 0");
let mut cmv = quiet_neuron(13, VoltageResolution::CentiMillivolt);
cmv.integrate_and_fire(12, 1000, 0);
assert_eq!(
cmv.membrane_potential,
-7_000 + 6,
"centi grid: 12 pA ⇒ 6 cV"
);
}
#[test]
fn above_threshold_current_blind_on_mv_spikes_on_centi() {
let mut mv = quiet_neuron(14, VoltageResolution::Millivolt);
let mut mv_spikes = 0;
for t in 0..100 {
if mv.integrate_and_fire(160, 1000, t) {
mv_spikes += 1;
}
}
assert_eq!(mv_spikes, 0, "mV grid is blind to 160 pA from rest");
assert_eq!(mv.membrane_potential, -70);
let mut cmv = quiet_neuron(15, VoltageResolution::CentiMillivolt);
let mut cmv_spikes = 0;
for t in 0..100 {
if cmv.integrate_and_fire(160, 1000, t) {
cmv_spikes += 1;
}
}
assert!(cmv_spikes >= 1, "centi grid fires on 160 pA (V_ss −54 mV)");
}
#[test]
fn centi_mode_constants_and_bounds() {
let n = quiet_neuron(16, VoltageResolution::CentiMillivolt);
assert_eq!(n.membrane_potential, -7_000);
assert_eq!(n.resting_potential, -7_000);
assert_eq!(n.threshold, -5_500);
assert_eq!(n.reset_potential, -8_000);
let mut m = quiet_neuron(17, VoltageResolution::CentiMillivolt);
m.membrane_potential = -9_999;
m.integrate_and_fire(-30_000, 1000, 0); assert!(m.membrane_potential >= -10_000, "clamped at scaled floor");
}
#[test]
fn rectification_at_the_sticking_point() {
let mut n = quiet_neuron(18, VoltageResolution::Millivolt);
for t in 0..50 {
n.integrate_and_fire(300, 1000, t);
}
assert_eq!(n.membrane_potential, -59, "sticks 4 mV under threshold");
n.integrate_and_fire(300, 1000, 100);
assert_eq!(n.membrane_potential, -59, "stays stuck under drive alone");
n.add_synaptic_current(12);
n.integrate_and_fire(300, 1000, 101);
assert_eq!(n.membrane_potential, -58, "positive pulse ratchets +1 mV");
n.clear_synaptic_current();
n.add_synaptic_current(-12);
n.integrate_and_fire(300, 1000, 102);
assert_eq!(n.membrane_potential, -58, "negative pulse absorbed");
}
#[test]
fn large_current_triggers_spike_and_refractory() {
let mut n = LIFNeuron::new(5, NeuronType::Excitatory, VoltageResolution::Millivolt);
n.threshold = -65;
let mut spiked = false;
let mut t = 0_u32;
for _ in 0..10 {
if n.integrate_and_fire(200, 10_000, t) {
spiked = true;
break;
}
t = t.saturating_add(10_000);
}
assert!(spiked, "200 pA over 10 ms steps should eventually spike");
assert_eq!(n.membrane_potential, n.reset_potential);
assert!(n.is_refractory());
}
#[test]
fn refractory_blocks_repeated_spikes() {
let mut n = LIFNeuron::new(6, NeuronType::Excitatory, VoltageResolution::Millivolt);
n.membrane_potential = n.threshold + 1;
let spiked = n.integrate_and_fire(0, 1000, 1000);
assert!(spiked);
let again = n.integrate_and_fire(1000, 1000, 2000);
assert!(!again, "must not spike during refractory");
}
#[test]
fn refractory_holds_through_its_last_microsecond() {
let mut n = LIFNeuron::new(6, NeuronType::Excitatory, VoltageResolution::Millivolt);
let rest = n.membrane_potential;
n.refractory_remaining_us = 1;
assert!(!n.integrate_and_fire(1000, 1000, 1000));
assert_eq!((n.membrane_potential, n.refractory_remaining_us), (rest, 0));
assert!(!n.integrate_and_fire(1000, 1000, 2000));
assert_eq!(n.membrane_potential, rest + 5);
}
#[test]
fn synaptic_current_accumulates_then_clears() {
let mut n = LIFNeuron::new(7, NeuronType::Excitatory, VoltageResolution::Millivolt);
n.add_synaptic_current(30);
n.add_synaptic_current(20);
assert_eq!(n.synaptic_current_pa, 50);
n.clear_synaptic_current();
assert_eq!(n.synaptic_current_pa, 0);
}
#[test]
fn reset_restores_initial_state() {
let mut n = LIFNeuron::new(8, NeuronType::Excitatory, VoltageResolution::Millivolt);
n.membrane_potential = -50;
n.synaptic_current_pa = 100;
n.adaptation_current_pa = 10;
n.spike(5000);
n.spike(6000);
n.reset();
assert_eq!(n.membrane_potential, n.resting_potential);
assert_eq!(n.synaptic_current_pa, 0);
assert_eq!(n.adaptation_current_pa, 0);
assert!(!n.is_refractory());
}
#[test]
fn firing_rate_uses_last_update_time_not_last_spike() {
let mut n = LIFNeuron::new(9, NeuronType::Excitatory, VoltageResolution::Millivolt);
let mut rec = SpikeRecorder::new();
n.membrane_potential = n.threshold + 1;
if n.integrate_and_fire(0, 1000, 1000) {
rec.record(1000);
}
for step in 2..=10_000 {
let t = step * 1000;
if n.integrate_and_fire(0, 1000, t) {
rec.record(t);
}
}
let rate_mhz = rec.firing_rate_mhz(n.last_update_time_us, 1_000_000);
assert_eq!(
rate_mhz, 0,
"no spikes in last 1 s — rate must be 0 (v0.1 would have returned > 0)"
);
}
#[test]
fn noise_is_zero_when_amplitude_is_zero() {
let mut n = LIFNeuron::new(12, NeuronType::Excitatory, VoltageResolution::Millivolt);
n.noise_amplitude_pa = 0;
for t in 0..1000_u32 {
assert_eq!(n.generate_noise(t), 0);
}
}
#[test]
fn noise_lies_in_minus_amp_to_127_amp_over_128() {
for (amp, lo, hi) in [
(1_u8, -1_i16, 0_i16),
(5, -5, 4),
(128, -128, 127),
(255, -255, 253),
] {
let mut n = LIFNeuron::new(0, NeuronType::Excitatory, VoltageResolution::Millivolt);
n.noise_amplitude_pa = amp;
let (mut min, mut max) = (i16::MAX, i16::MIN);
for t in 0..=u32::from(u16::MAX) {
let v = n.generate_noise(t);
min = min.min(v);
max = max.max(v);
}
assert_eq!((min, max), (lo, hi), "amplitude {amp}");
assert_eq!(hi, (127 * i16::from(amp)) / 128);
}
}
#[test]
fn noise_varies_with_time_for_same_id() {
let mut n = LIFNeuron::new(13, NeuronType::Excitatory, VoltageResolution::Millivolt);
n.noise_amplitude_pa = 5;
let samples: [i16; 8] = [
n.generate_noise(100),
n.generate_noise(101),
n.generate_noise(102),
n.generate_noise(103),
n.generate_noise(104),
n.generate_noise(105),
n.generate_noise(106),
n.generate_noise(107),
];
let first = samples[0];
let all_same = samples.iter().all(|&s| s == first);
assert!(
!all_same,
"noise must vary with time — got identical values across 8 samples (all = {first})"
);
}
#[test]
fn a_neuron_is_built_silent() {
for ty in [NeuronType::Excitatory, NeuronType::Inhibitory] {
for res in [
VoltageResolution::Millivolt,
VoltageResolution::CentiMillivolt,
] {
let n = LIFNeuron::new(7, ty, res);
assert_eq!(n.noise_amplitude_pa, 0, "{ty:?} on {res:?}");
}
}
}
#[test]
fn noise_reads_only_the_low_12_bits_of_its_seed() {
for id in [0u16, 1, 0x5A5A, u16::MAX] {
let mut n = quiet_neuron(id, VoltageResolution::Millivolt);
n.noise_amplitude_pa = 127;
for low in 0..=u32::from(u16::MAX) {
let want = n.generate_noise(low & 0xFFF);
for high in [0u32, 0x1_0000, 0xDEAD_0000, 0xFFFF_0000] {
assert_eq!(
n.generate_noise(high | low),
want,
"id {id}, time {:#x}",
high | low
);
}
}
}
}
#[test]
fn the_saturating_multiply_lands_where_an_unbounded_integer_would() {
let rows: [(&str, i16, i16, i16, u16, bool, i16); 4] = [
("mV, positive", -32768, 32767, 32767, 65535, false, 50),
("mV, negative", 32767, -32768, -32768, 65535, false, -100),
("centi, positive", -32768, 32767, 32767, 65535, true, 5000),
(
"centi, negative",
32767,
-32768,
-32768,
65535,
true,
-10000,
),
];
for (name, mp, rp, input, resistance, centi, expected) in rows {
let resolution = if centi {
VoltageResolution::CentiMillivolt
} else {
VoltageResolution::Millivolt
};
let mut n = LIFNeuron::new(0, NeuronType::Excitatory, VoltageResolution::Millivolt);
n.voltage_resolution = resolution;
n.membrane_potential = mp;
n.resting_potential = rp;
n.resistance_mohm = resistance;
n.threshold = i16::MAX;
n.tau_membrane_us = 1;
n.noise_amplitude_pa = 0;
n.synaptic_current_pa = 0;
n.adaptation_current_pa = 0;
n.refractory_remaining_us = 0;
let _ = n.integrate_and_fire(input, u32::MAX, 0);
let s = i128::from(resolution.scale());
let dtot = (i128::from(u32::MAX) * 1000) / i128::from(n.tau_membrane_us);
let leak = i128::from(rp) - i128::from(mp);
let current_term = (i128::from(input) * i128::from(resistance) * s) / 1000;
let product = dtot * (leak + current_term);
assert!(
product > i128::from(i64::MAX) || product < i128::from(i64::MIN),
"{name}: this row must actually saturate i64, |product| = {}",
product.abs()
);
let unbounded = (i128::from(mp) + product / 1000).clamp(
i128::from(MEMBRANE_MV_MIN) * s,
i128::from(MEMBRANE_MV_MAX) * s,
);
assert_eq!(i128::from(n.membrane_potential), unbounded, "{name}");
assert_eq!(n.membrane_potential, expected, "{name}");
}
}
#[test]
fn div_1000_is_exact_on_both_sides_of_the_guard() {
let (min, max) = (i64::from(i32::MIN), i64::from(i32::MAX));
let rows: [(i64, i64); 12] = [
(min - 1, -2_147_483),
(min, -2_147_483),
(max, 2_147_483),
(max + 1, 2_147_483),
(i64::MIN, -9_223_372_036_854_775),
(i64::MAX, 9_223_372_036_854_775),
(999, 0),
(-999, 0),
(1000, 1),
(-1000, -1),
(1001, 1),
(-1001, -1),
];
for (x, expected) in rows {
assert_eq!(x / 1000, expected, "the table: {x} / 1000");
assert_eq!(div_1000(x), expected, "div_1000({x})");
}
}
proptest! {
#[test]
fn prop_div_1000_equals_i64_division(
x in prop_oneof![any::<i32>().prop_map(i64::from), any::<i64>()],
) {
prop_assert_eq!(div_1000(x), x / 1000, "x = {}", x);
}
}
proptest! {
#[test]
fn prop_integrate_and_fire_is_exact_over_the_whole_domain(
mp in any::<i16>(),
rp in any::<i16>(),
input in any::<i16>(),
resistance in any::<u16>(),
tau_us in 1u32..=u32::MAX,
dt_us in 0u32..=u32::MAX,
centi in any::<bool>(),
) {
let resolution = if centi {
VoltageResolution::CentiMillivolt
} else {
VoltageResolution::Millivolt
};
let mut n = LIFNeuron::new(0, NeuronType::Excitatory, VoltageResolution::Millivolt);
n.voltage_resolution = resolution;
n.membrane_potential = mp;
n.resting_potential = rp;
n.tau_membrane_us = tau_us;
n.resistance_mohm = resistance;
n.threshold = i16::MAX; n.noise_amplitude_pa = 0;
n.synaptic_current_pa = 0;
n.adaptation_current_pa = 0;
n.refractory_remaining_us = 0;
let _ = n.integrate_and_fire(input, dt_us, 0);
let s = i128::from(resolution.scale());
let dtot = (i128::from(dt_us) * 1000) / i128::from(tau_us);
let leak = i128::from(rp) - i128::from(mp);
let current_term = (i128::from(input) * i128::from(resistance) * s) / 1000;
let delta = (dtot * (leak + current_term)) / 1000;
let expected = (i128::from(mp) + delta)
.clamp(i128::from(MEMBRANE_MV_MIN) * s, i128::from(MEMBRANE_MV_MAX) * s);
prop_assert_eq!(
i128::from(n.membrane_potential), expected,
"membrane {} != exact {} (mp={} rp={} input={} resistance={} dt={} tau={} centi={})",
n.membrane_potential, expected, mp, rp, input, resistance, dt_us, tau_us, centi
);
let bound = i128::from(MEMBRANE_MV_MAX) * s;
prop_assert!(
i128::from(n.membrane_potential).abs() <= bound.max(i128::from(MEMBRANE_MV_MIN).abs() * s),
"membrane {} left the voltage grid", n.membrane_potential
);
}
#[test]
fn prop_reset_clears_all_state(id in 0u16..=1000) {
let mut n = LIFNeuron::new(id, NeuronType::Excitatory, VoltageResolution::Millivolt);
n.add_synaptic_current(50);
n.adaptation_current_pa = 20;
n.spike(5000);
n.spike(6000);
n.reset();
prop_assert_eq!(n.membrane_potential, n.resting_potential);
prop_assert_eq!(n.synaptic_current_pa, 0);
prop_assert_eq!(n.adaptation_current_pa, 0);
prop_assert_eq!(n.refractory_remaining_us, 0);
}
#[test]
fn prop_membrane_potential_stays_bounded(
id in 0u16..=100,
input in -1000i16..=1000,
dt in 1u32..=10_000,
start_t in 0u32..=1_000_000,
) {
let mut n = LIFNeuron::new(id, NeuronType::Excitatory, VoltageResolution::Millivolt);
let mut t = start_t;
for _ in 0..100 {
let _ = n.integrate_and_fire(input, dt, t);
t = t.saturating_add(dt);
}
prop_assert!(n.membrane_potential >= MEMBRANE_MV_MIN);
prop_assert!(n.membrane_potential <= MEMBRANE_MV_MAX);
}
#[test]
fn prop_firing_rate_respects_refractory_bound(
id in 0u16..=50,
tau_ref in 500u32..=10_000,
) {
let mut n = LIFNeuron::new(id, NeuronType::Excitatory, VoltageResolution::Millivolt);
let mut rec = SpikeRecorder::new();
n.refractory_period_us = tau_ref;
n.threshold = -100; let mut t = 0_u32;
for _ in 0..100 {
if n.integrate_and_fire(1000, 1000, t) {
rec.record(t);
}
t += 1000;
}
let max_rate_mhz = 1_000_000_000_u32 / tau_ref;
let ceiling = max_rate_mhz + max_rate_mhz / 20; let actual = rec.firing_rate_mhz(n.last_update_time_us, t);
prop_assert!(
actual <= ceiling,
"rate {} mHz exceeds refractory ceiling {} mHz",
actual,
ceiling
);
}
}
#[test]
fn adaptation_decay_is_exact_minus_one_with_floor_zero() {
let mut n = quiet_neuron(21, VoltageResolution::Millivolt);
n.adaptation_current_pa = 3;
n.decay_adaptation_current();
assert_eq!(n.adaptation_current_pa, 2);
n.decay_adaptation_current();
assert_eq!(n.adaptation_current_pa, 1);
n.decay_adaptation_current();
assert_eq!(n.adaptation_current_pa, 0);
n.decay_adaptation_current();
assert_eq!(n.adaptation_current_pa, 0, "floors at zero, never negative");
}
#[test]
fn the_current_saturates_term_by_term() {
let mut n = quiet_neuron(0, VoltageResolution::Millivolt);
n.threshold = i16::MAX; n.synaptic_current_pa = i16::MAX;
n.adaptation_current_pa = i16::MAX;
n.integrate_and_fire(i16::MAX, 1_000, 0);
assert_eq!(n.membrane_potential, -70);
}
#[test]
fn a_spike_stamps_its_time() {
let mut n = quiet_neuron(0, VoltageResolution::Millivolt);
n.threshold = -100; assert!(n.integrate_and_fire(0, 1_000, 5_000));
assert_eq!(n.last_spike_time_us, 5_000);
assert!(!n.integrate_and_fire(0, 1_000, 6_000));
assert_eq!(n.last_spike_time_us, 5_000, "a silent step stamps nothing");
}
#[test]
fn adaptation_off_adds_nothing() {
let mut n = quiet_neuron(22, VoltageResolution::Millivolt).with_adaptation_enabled(false);
n.threshold = -100; n.refractory_period_us = 0;
for t in 0..10 {
assert!(n.integrate_and_fire(1000, 1000, t * 1000));
assert_eq!(n.adaptation_current_pa, 0, "step {t}");
}
n.decay_adaptation_current();
assert_eq!(n.adaptation_current_pa, 0);
n.reset();
assert!(!n.adaptation_enabled);
}
#[test]
fn spike_adds_exactly_two_adaptation_quanta() {
let mut n = quiet_neuron(22, VoltageResolution::Millivolt);
n.threshold = -100; let spiked = n.integrate_and_fire(1000, 1000, 0);
assert!(spiked);
assert_eq!(n.adaptation_current_pa, 2, "+2 per spike");
n.reset();
assert!(n.adaptation_enabled, "reset leaves the switch on");
}
#[test]
fn a_time_constant_longer_than_i32_no_longer_inverts_the_step() {
assert_eq!(dt_over_tau(1000, u32::MAX), 0, "tau >> dt is a zero step");
let mut n = quiet_neuron(24, VoltageResolution::Millivolt);
n.tau_membrane_us = u32::MAX;
n.threshold = i16::MAX; let before = n.membrane_potential;
let _ = n.integrate_and_fire(1000, 1000, 0);
assert_eq!(
n.membrane_potential, before,
"a 4295 s time constant must not move the membrane in a 1 ms step"
);
}
#[test]
fn a_time_step_past_the_i32_product_no_longer_overflows() {
assert_eq!(dt_over_tau(2_147_484, u32::MAX), 0);
assert_eq!(dt_over_tau(i32::MAX as u32, u32::MAX), 499);
assert_eq!(
dt_over_tau(u32::MAX, 1),
4_294_967_295_000,
"exact, not clamped"
);
assert_eq!(
dt_over_tau(1000, 20_000),
50,
"the physical default is untouched"
);
let mut n = quiet_neuron(25, VoltageResolution::Millivolt);
n.membrane_potential = MEMBRANE_MV_MIN;
n.threshold = i16::MAX;
let _ = n.integrate_and_fire(0, 2_147_484, 0);
assert_eq!(n.membrane_potential, MEMBRANE_MV_MAX);
}
#[test]
fn dt_over_tau_is_exact_on_both_sides_of_the_guard() {
let m = u32::MAX;
let rows: [(u32, u32, i64); 11] = [
(4_294_967, 1, 4_294_967_000),
(4_294_968, 1, 4_294_968_000),
(4_294_967, 7, 613_566_714),
(4_294_968, 7, 613_566_857),
(4_294_967, m, 0),
(4_294_968, m, 1),
(m, 1, 4_294_967_295_000),
(m, m, 1_000),
(1_000, 20_000, 50),
(0, 20_000, 0),
(1_000, 0, 0),
];
for (dt, tau, expected) in rows {
let formula = if tau == 0 {
0
} else {
(u64::from(dt) * 1000 / u64::from(tau)) as i64
};
assert_eq!(formula, expected, "the table: ({dt}, {tau})");
assert_eq!(dt_over_tau(dt, tau), expected, "dt_over_tau({dt}, {tau})");
}
}
proptest! {
#[test]
fn prop_dt_over_tau_equals_the_u64_formula(
dt in prop_oneof![0u32..=4_294_967, any::<u32>()],
tau in any::<u32>(),
) {
let formula = if tau == 0 {
0
} else {
(u64::from(dt) * 1000 / u64::from(tau)) as i64
};
prop_assert_eq!(dt_over_tau(dt, tau), formula, "dt = {} tau = {}", dt, tau);
}
}
#[test]
fn the_neuron_is_exact_where_the_batch_clamps() {
let mut n = quiet_neuron(26, VoltageResolution::Millivolt);
n.membrane_potential = -100;
n.resting_potential = -70;
n.tau_membrane_us = 20_000;
n.threshold = i16::MAX;
assert_eq!(dt_over_tau(40_000, 20_000), 2000, "dt/tau = 2, exactly");
let _ = n.integrate_and_fire(0, 40_000, 0);
assert_eq!(n.membrane_potential, -40, "the neuron takes the exact step");
}
#[test]
fn leak_convergence_large_dt_lands_on_rest_exactly() {
let mut n = quiet_neuron(23, VoltageResolution::Millivolt);
n.membrane_potential = -90;
let _ = n.integrate_and_fire(0, 20_000, 20_000);
assert_eq!(n.membrane_potential, n.resting_potential, "from below");
n.membrane_potential = -20;
let _ = n.integrate_and_fire(0, 20_000, 40_000);
assert_eq!(n.membrane_potential, n.resting_potential, "from above");
let _ = n.integrate_and_fire(0, 20_000, 60_000);
assert_eq!(n.membrane_potential, n.resting_potential, "stays at rest");
}
#[test]
fn the_neuron_is_40_bytes() {
assert_eq!(core::mem::size_of::<LIFNeuron>(), 40);
}
#[test]
fn the_neuron_has_seventeen_fields() {
let neuron = LIFNeuron {
id: 9,
neuron_type: NeuronType::Inhibitory,
membrane_potential: -6_612,
resting_potential: -6_612,
threshold: -4_900,
reset_potential: -7_100,
voltage_resolution: VoltageResolution::CentiMillivolt,
tau_membrane_us: 12_345,
refractory_period_us: 987,
refractory_remaining_us: 3,
last_update_time_us: 41,
last_spike_time_us: 40,
synaptic_current_pa: -17,
resistance_mohm: 33,
noise_amplitude_pa: 7,
adaptation_current_pa: 6,
adaptation_enabled: false,
};
let pretty = format!("{neuron:#?}");
let fields = pretty
.lines()
.filter(|line| {
line.strip_prefix(" ").is_some_and(|field| {
field.starts_with(|c: char| c.is_ascii_alphabetic()) && field.contains(": ")
})
})
.count();
assert_eq!(
fields, 17,
"a field was added to or taken from LIFNeuron (and the literal above compiled, \
so this count is the second word, not the first). Adding one is a decision in \
`fixed::freeze` (`neuron_chain`'s destructure, and its doc): bind it there \
and emit a setter for it, or state why its default is right for every \
frozen file ever written — and then PROVE that default, by replaying one frozen \
module kept in the old emitted form against its pinned trace (the obligation the \
ISA's round-43 close-out records). This number is edited last."
);
}
#[test]
fn add_synaptic_current_saturates_at_both_ends() {
let mut n = LIFNeuron::new(0, NeuronType::Excitatory, VoltageResolution::Millivolt);
n.add_synaptic_current(i16::MAX);
n.add_synaptic_current(1);
assert_eq!(n.synaptic_current_pa, i16::MAX);
n.clear_synaptic_current();
n.add_synaptic_current(i16::MIN);
n.add_synaptic_current(-1);
assert_eq!(n.synaptic_current_pa, i16::MIN);
}
#[test]
fn the_adaptation_current_saturates() {
let mut n = LIFNeuron::new(0, NeuronType::Excitatory, VoltageResolution::Millivolt)
.with_threshold(MEMBRANE_MV_MIN)
.with_refractory_period_us(0);
let mut t = 0u32;
for _ in 0..16_400 {
assert!(n.integrate_and_fire(0, 1_000, t), "every step fires");
t = t.wrapping_add(1_000);
}
assert_eq!(n.adaptation_current_pa, i16::MAX);
}
#[test]
fn noise_is_seeded_by_id_xor_time() {
let noisy = |id| {
LIFNeuron::new(id, NeuronType::Excitatory, VoltageResolution::Millivolt)
.with_noise_amplitude_pa(100)
};
let mut parts = 0;
for (id, t) in [(9u16, 1_000u32), (13, 2_000), (255, 7_000), (1_000, 3_000)] {
let seed = u32::from(id) ^ t;
assert_eq!(
noisy(id).generate_noise(t),
noisy(0).generate_noise(seed),
"id {id} at {t}"
);
if noisy(0).generate_noise(u32::from(id) + t) != noisy(0).generate_noise(seed) {
parts += 1;
}
}
assert!(
parts > 0,
"the pairs must tell xor from add, or the test proves nothing"
);
}
}