use crate::lif_neuron::LIFNeuron;
#[cfg(feature = "std")]
use crate::network::SpikingNeuralNetwork;
#[cfg(feature = "std")]
use crate::{Error, Result};
#[cfg(all(feature = "std", feature = "unstable-freeze"))]
pub mod freeze;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct FixedSynapse {
pub pre: u16,
pub post: u16,
pub pulse_pa: i16,
}
#[cfg(feature = "std")]
impl FixedSynapse {
#[must_use]
#[allow(clippy::cast_possible_wrap)]
pub fn from_network(net: &SpikingNeuralNetwork) -> Vec<Self> {
let divisor = net.synaptic_input_divisor() as i16;
let mut synapses: Vec<Self> = net
.synapses()
.iter()
.map(|s| Self {
pre: s.pre_neuron_id,
post: s.post_neuron_id,
pulse_pa: s.weight / divisor,
})
.collect();
synapses.sort_by_key(|s| s.pre);
synapses
}
}
#[derive(Debug, Clone)]
pub struct FixedNetwork<const N: usize, const S: usize> {
neurons: [LIFNeuron; N],
synapses: [FixedSynapse; S],
dt_us: u32,
time_us: u64,
}
impl<const N: usize, const S: usize> FixedNetwork<N, S> {
#[must_use]
pub const fn new(neurons: [LIFNeuron; N], synapses: [FixedSynapse; S], dt_us: u32) -> Self {
Self {
neurons,
synapses,
dt_us,
time_us: 0,
}
}
pub fn step(&mut self, input: &[i16; N], fired: &mut [bool; N]) {
for n in &mut self.neurons {
n.decay_adaptation_current();
}
#[allow(clippy::cast_possible_truncation)]
let now_us = self.time_us as u32;
for ((n, ¤t_pa), spiked) in self.neurons.iter_mut().zip(input).zip(fired.iter_mut()) {
*spiked = n.integrate_and_fire(current_pa, self.dt_us, now_us);
}
for n in &mut self.neurons {
n.clear_synaptic_current();
}
for s in &self.synapses {
if fired.get(usize::from(s.pre)) == Some(&true) {
if let Some(post) = self.neurons.get_mut(usize::from(s.post)) {
post.add_synaptic_current(s.pulse_pa);
}
}
}
self.time_us = self.time_us.saturating_add(u64::from(self.dt_us));
}
#[must_use]
pub const fn neurons(&self) -> &[LIFNeuron; N] {
&self.neurons
}
#[must_use]
pub const fn synapses(&self) -> &[FixedSynapse; S] {
&self.synapses
}
#[must_use]
pub const fn dt_us(&self) -> u32 {
self.dt_us
}
#[must_use]
pub const fn time_us(&self) -> u64 {
self.time_us
}
}
#[cfg(feature = "std")]
impl<const N: usize, const S: usize> TryFrom<&SpikingNeuralNetwork> for FixedNetwork<N, S> {
type Error = Error;
fn try_from(net: &SpikingNeuralNetwork) -> Result<Self> {
if net.plasticity_enabled() {
return Err(Error::PlasticityEnabled);
}
if usize::from(net.neuron_count()) != N {
return Err(Error::NeuronCountMismatch);
}
if usize::try_from(net.synapse_count()) != Ok(S) {
return Err(Error::SynapseCountMismatch);
}
let neurons: [LIFNeuron; N] = net
.neurons()
.to_vec()
.try_into()
.map_err(|_| Error::NeuronCountMismatch)?;
let synapses: [FixedSynapse; S] = FixedSynapse::from_network(net)
.try_into()
.map_err(|_| Error::SynapseCountMismatch)?;
Ok(Self {
neurons,
synapses,
dt_us: net.dt_us(),
time_us: net.time_us(),
})
}
}
impl FixedSynapse {
#[must_use]
pub const fn new(pre: u16, post: u16, pulse_pa: i16) -> Self {
Self {
pre,
post,
pulse_pa,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[cfg(feature = "std")]
use crate::csr::SparseSynapseMatrix;
#[cfg(feature = "std")]
use crate::lif_neuron::{NeuronType, VoltageResolution};
fn quiet(id: u16) -> LIFNeuron {
let mut n = LIFNeuron::new(id, NeuronType::Excitatory, VoltageResolution::Millivolt);
n.noise_amplitude_pa = 0;
n
}
#[cfg(feature = "std")]
fn state(n: &LIFNeuron) -> (i16, u32, u32, u32, i16, i16) {
(
n.membrane_potential,
n.refractory_remaining_us,
n.last_update_time_us,
n.last_spike_time_us,
n.synaptic_current_pa,
n.adaptation_current_pa,
)
}
#[test]
fn a_synapse_is_six_bytes() {
assert_eq!(core::mem::size_of::<FixedSynapse>(), 6);
}
#[test]
fn the_clock_runs_past_the_u32_ceiling() {
let mut net = FixedNetwork::new([quiet(0)], [], 1_000);
net.time_us = u64::from(u32::MAX) - 400;
let mut fired = [false];
net.step(&[0], &mut fired);
assert_eq!(net.time_us(), u64::from(u32::MAX) + 600);
assert_eq!(net.neurons()[0].last_update_time_us, u32::MAX - 400);
net.step(&[0], &mut fired);
assert_eq!(net.time_us(), u64::from(u32::MAX) + 1_600);
assert_eq!(net.neurons()[0].last_update_time_us, 599);
}
#[cfg(feature = "std")]
#[test]
fn a_clock_past_the_u32_boundary_gives_the_same_noise() {
let noisy = |id: u16| {
let mut n = LIFNeuron::new(
id,
NeuronType::Excitatory,
VoltageResolution::CentiMillivolt,
);
n.noise_amplitude_pa = 5;
n
};
let run = |start_us: u64| {
let mut net = FixedNetwork::new([noisy(0), noisy(1), noisy(2), noisy(3)], [], 1_000);
net.time_us = start_us;
let mut fired = [false; 4];
let mut fold = 0u32;
for step in 0..2_000u32 {
net.step(&[150; 4], &mut fired);
for (id, &f) in (0u32..).zip(fired.iter()) {
if f {
fold = fold
.wrapping_mul(31)
.wrapping_add(step)
.wrapping_mul(31)
.wrapping_add(id);
}
}
}
fold
};
let before = run(1_234_000);
assert_ne!(before, 0, "the run fires, or the test shows nothing");
assert_eq!(run(1_234_000 + (1 << 32)), before);
}
#[test]
fn an_unsorted_array_delivers_in_array_order() {
let mut net = FixedNetwork::new(
[quiet(0), quiet(1), quiet(2)],
[
FixedSynapse {
pre: 2,
post: 0,
pulse_pa: -30_000,
},
FixedSynapse {
pre: 1,
post: 0,
pulse_pa: 30_000,
},
FixedSynapse {
pre: 1,
post: 0,
pulse_pa: 30_000,
},
],
1_000,
);
let mut fired = [false; 3];
net.step(&[0, 3_000, 3_000], &mut fired);
assert_eq!(fired, [false, true, true]);
assert_eq!(net.neurons()[0].synaptic_current_pa, 30_000);
}
#[test]
fn an_id_past_the_arrays_is_no_spike_and_no_target() {
let mut net = FixedNetwork::new(
[quiet(0), quiet(1)],
[
FixedSynapse {
pre: 0,
post: 9,
pulse_pa: 500,
},
FixedSynapse {
pre: 7,
post: 1,
pulse_pa: 500,
},
],
1_000,
);
let mut fired = [false; 2];
net.step(&[3_000, 0], &mut fired);
assert_eq!(fired, [true, false]);
assert_eq!(net.neurons()[1].synaptic_current_pa, 0);
assert_eq!(net.time_us(), 1_000);
}
#[cfg(feature = "std")]
fn chain_3() -> SpikingNeuralNetwork {
let neurons = (0..3)
.map(|id| {
let mut n = LIFNeuron::new(
id,
NeuronType::Excitatory,
VoltageResolution::CentiMillivolt,
);
n.noise_amplitude_pa = 0;
n
})
.collect();
let mut net =
SpikingNeuralNetwork::from_neurons(neurons, 1_000).expect("three neurons, 1 ms");
net.set_synaptic_input_divisor(1).expect("in 1 to 32,767");
net
}
#[cfg(feature = "std")]
#[must_use]
fn steps_alike(net: &mut SpikingNeuralNetwork, fixed: &mut FixedNetwork<3, 2>) -> [u32; 3] {
let mut spiked = [false; 3];
let mut counts = [0u32; 3];
for step in 0..100 {
let want: Vec<u16> = net
.step(&[600, 0, 0])
.expect("a built network steps")
.iter()
.map(|s| s.neuron_id)
.collect();
fixed.step(&[600, 0, 0], &mut spiked);
let got: Vec<u16> = (0..3u16).filter(|&id| spiked[usize::from(id)]).collect();
assert_eq!(got, want, "step {step}: the spikes");
for (f, s) in fixed.neurons().iter().zip(net.neurons()) {
assert_eq!(state(f), state(s), "step {step}: neuron {}", s.id);
}
assert_eq!(fixed.time_us(), net.time_us(), "step {step}: the time");
for &id in &got {
counts[usize::from(id)] += 1;
}
}
counts
}
#[cfg(feature = "std")]
#[test]
fn the_step_is_the_std_step_on_chain_3() {
let mut net = chain_3();
net.add_synapse(0, 1, 5_000).expect("ids in range");
net.add_synapse(1, 2, 5_000).expect("ids in range");
net.finalize_synapses();
let mut fixed =
FixedNetwork::<3, 2>::try_from(&net).expect("plasticity off, 3 neurons, 2 synapses");
let counts = steps_alike(&mut net, &mut fixed);
assert!(
counts.iter().all(|&n| n > 0),
"all three fire, 1 and 2 through the chain: {counts:?}"
);
}
#[cfg(feature = "std")]
#[test]
fn try_from_converts_edges_added_out_of_pre_order() {
let mut net = chain_3();
net.add_synapse(1, 2, 5_000).expect("ids in range");
net.add_synapse(0, 1, 5_000).expect("ids in range");
let mut fixed =
FixedNetwork::<3, 2>::try_from(&net).expect("never sorted: 3 neurons, 2 synapses");
let counts = steps_alike(&mut net, &mut fixed);
assert!(
counts.iter().all(|&n| n > 0),
"all three fire, 1 and 2 through the chain: {counts:?}"
);
}
#[cfg(feature = "std")]
#[test]
fn from_network_is_the_csr_order() {
let edges: [(u16, u16, i16); 5] = [
(2, 0, -125),
(0, 2, 7),
(2, 3, -250),
(1, 3, 40),
(0, 1, 125),
];
let mut net = SpikingNeuralNetwork::from_neurons(
(0..4)
.map(|id| LIFNeuron::new(id, NeuronType::Excitatory, VoltageResolution::Millivolt))
.collect(),
1_000,
)
.expect("four neurons, 1 ms");
for &(pre, post, weight) in &edges {
net.add_synapse(pre, post, weight)
.expect("ids in range, no self edge");
}
net.finalize_synapses();
net.set_synaptic_input_divisor(3).expect("in 1 to 32,767");
assert!(
!net.synapses()
.windows(2)
.all(|w| w[0].pre_neuron_id <= w[1].pre_neuron_id),
"the edges were added out of pre order, or the test proves nothing"
);
let mut csr = SparseSynapseMatrix::new(4, edges.len());
for (i, &(pre, post, weight)) in edges.iter().enumerate() {
csr.add(pre, post, weight, i);
}
csr.finalize();
let want: Vec<FixedSynapse> = (0..4)
.flat_map(|pre| {
csr.connections(pre)
.map(move |(post, weight, _)| FixedSynapse {
pre,
post,
pulse_pa: weight / 3,
})
})
.collect();
assert_eq!(FixedSynapse::from_network(&net), want);
let pre_0: Vec<u16> = FixedSynapse::from_network(&net)
.iter()
.filter(|s| s.pre == 0)
.map(|s| s.post)
.collect();
assert_eq!(
pre_0,
[2, 1],
"pre 0's synapses in the order added, not by post"
);
}
#[cfg(feature = "std")]
#[test]
fn from_network_divides_at_the_largest_divisor() {
let mut net = SpikingNeuralNetwork::from_neurons(
(0..3)
.map(|id| LIFNeuron::new(id, NeuronType::Excitatory, VoltageResolution::Millivolt))
.collect(),
1_000,
)
.expect("three neurons, 1 ms");
net.add_synapse(0, 1, i16::MIN).expect("ids in range");
net.add_synapse(1, 2, i16::MAX).expect("ids in range");
net.finalize_synapses();
net.set_synaptic_input_divisor(32_767)
.expect("the largest divisor");
let pulses: Vec<i16> = FixedSynapse::from_network(&net)
.iter()
.map(|s| s.pulse_pa)
.collect();
assert_eq!(pulses, [-1, 1]);
}
#[cfg(feature = "std")]
#[test]
fn try_from_refuses_plasticity_and_other_sizes() {
let mut net = SpikingNeuralNetwork::from_neurons(
(0..3)
.map(|id| LIFNeuron::new(id, NeuronType::Excitatory, VoltageResolution::Millivolt))
.collect(),
1_000,
)
.expect("three neurons, 1 ms");
net.add_synapse(0, 1, 100).expect("ids in range");
net.add_synapse(1, 2, 100).expect("ids in range");
net.finalize_synapses();
#[cfg(feature = "unstable-stdp")]
{
net.set_plasticity_enabled(true);
assert_eq!(
FixedNetwork::<3, 2>::try_from(&net).err(),
Some(Error::PlasticityEnabled),
"plasticity on"
);
net.set_plasticity_enabled(false);
}
assert_eq!(
FixedNetwork::<4, 2>::try_from(&net).err(),
Some(Error::NeuronCountMismatch),
"four neurons"
);
assert_eq!(
FixedNetwork::<3, 1>::try_from(&net).err(),
Some(Error::SynapseCountMismatch),
"one synapse"
);
for _ in 0..5 {
net.step(&[0, 0, 0]).expect("a built network steps");
}
let fixed = FixedNetwork::<3, 2>::try_from(&net).expect("plasticity off, 3 and 2");
assert_eq!((fixed.dt_us(), fixed.time_us()), (1_000, 5_000));
}
#[test]
fn the_clock_saturates_at_u64_max() {
let mut net = FixedNetwork::new([quiet(0)], [], 1_000);
net.time_us = u64::MAX - 400;
let mut fired = [false];
net.step(&[0], &mut fired);
assert_eq!(net.time_us(), u64::MAX);
net.step(&[0], &mut fired);
assert_eq!(net.time_us(), u64::MAX);
}
}