#![allow(clippy::format_push_string)]
use super::FixedSynapse;
use crate::lif_neuron::LIFNeuron;
use crate::network::SpikingNeuralNetwork;
use crate::trace::{self, Kind, Rows};
const PREAMBLE: &str = "\
// Generated by `cargo run -p gresil --example trace --features unstable-stdp,unstable-freeze -- write` from
// tests/traces/cases.rs (`cases::freeze`); do not edit it by hand.
// tests/traces.rs regenerates it and compares line for line.
//
// Every plasticity-off case of tests/traces/ as the arrays a FixedNetwork
// steps: N neurons and S synapses, the time step, the run, whether the
// trace keeps spiking steps only, the trace's header line verbatim, the
// neurons as built, each one a constructor call and one setter per
// parameter (every parameter written, default or not), the synapses in
// the CSR order, and the drive as runs of equal steps, (count,
// currents). plasticity-on is not here: a FixedNetwork has no
// plasticity.
//
// Included by #[path] with #[rustfmt::skip] on the `mod frozen;` line, so
// rustfmt leaves it as written: by tests/traces.rs, and by firmware, since
// it needs only core and gresil. One allow, builtin: dead_code, since
// an includer reads only the constants it needs.
#![allow(dead_code)]
";
#[must_use]
pub fn preamble() -> &'static str {
PREAMBLE
}
#[must_use]
pub fn module(
net: &SpikingNeuralNetwork,
case: &str,
kind: Kind,
steps: u32,
rows: Rows,
drive: &[(u32, Vec<i16>)],
) -> String {
assert!(
!net.plasticity_enabled(),
"{case}: plasticity is on, and a FixedNetwork has none"
);
assert_eq!(
net.time_us(),
0,
"{case}: the network has stepped, and a frozen file starts at 0"
);
assert!(
trace::one_grid(net).is_some(),
"{case}: the neurons store their potentials on two grids, and a trace names one"
);
assert!(
trace::is_case_name(case),
"{case:?}: a case name is lowercase ASCII letters, digits and -"
);
let header = trace::header(net, case, kind, steps, rows)
.expect("one grid and a case name by the rule, both checked above");
let neurons = net.neurons();
let synapses = FixedSynapse::from_network(net);
let dt_us = net.dt_us();
let spikes_only = matches!(rows, Rows::Spikes);
let name = case.replace('-', "_");
assert!(
drive
.iter()
.all(|(_, currents)| currents.len() == neurons.len()),
"{case}: one current per neuron in every run of the drive"
);
let mut out = format!("pub mod {name} {{\n");
out.push_str(" use gresil::{FixedSynapse, LIFNeuron, NeuronType, VoltageResolution};\n\n");
out.push_str(&format!(" pub const N: usize = {};\n", neurons.len()));
out.push_str(&format!(" pub const S: usize = {};\n", synapses.len()));
out.push_str(&format!(" pub const DT_US: u32 = {dt_us};\n"));
out.push_str(&format!(" pub const STEPS: u32 = {steps};\n"));
out.push_str(&format!(
" pub const SPIKES_ONLY: bool = {spikes_only};\n"
));
out.push_str(&format!(" pub const HEADER: &str = {header:?};\n"));
out.push_str(" pub const NEURONS: [LIFNeuron; N] = [\n");
for (i, neuron) in neurons.iter().enumerate() {
let (chain, rebuilt) = neuron_chain(case, i, neuron);
assert_eq!(
format!("{rebuilt:?}"),
format!("{neuron:?}"),
"{case}, neuron {i}: the emitted chain does not rebuild the neuron"
);
assert!(
usize::from(neuron.id) == i,
"{case}, neuron {i}: a neuron's id is its position in the array, \
which is what indexes it and what seeds its noise"
);
out.push_str(&format!(" {chain},\n"));
}
out.push_str(" ];\n");
if synapses.is_empty() {
out.push_str(" pub const SYNAPSES: [FixedSynapse; S] = [];\n");
} else {
out.push_str(" pub const SYNAPSES: [FixedSynapse; S] = [\n");
for s in &synapses {
out.push_str(&format!(
" FixedSynapse::new({}, {}, {}),\n",
s.pre, s.post, s.pulse_pa
));
}
out.push_str(" ];\n");
}
out.push_str(" pub const DRIVE: &[(u32, [i16; N])] = &[\n");
for (count, currents) in drive {
let currents: Vec<String> = currents.iter().map(i16::to_string).collect();
out.push_str(&format!(" ({count}, [{}]),\n", currents.join(", ")));
}
out.push_str(" ];\n}\n");
out
}
#[must_use]
pub fn tail(cases: &[&str]) -> String {
let mut out = String::from(
"/// Applies the caller's macro to every frozen case, in file order.\n\
macro_rules! for_each_frozen {\n ($m:ident) => {\n",
);
for case in cases {
out.push_str(&format!(" $m!({});\n", case.replace('-', "_")));
}
out.push_str(" };\n}\npub(crate) use for_each_frozen;\n");
out
}
fn neuron_chain(case: &str, i: usize, n: &LIFNeuron) -> (String, LIFNeuron) {
let LIFNeuron {
id,
neuron_type,
membrane_potential,
resting_potential,
threshold,
reset_potential,
voltage_resolution,
tau_membrane_us,
refractory_period_us,
refractory_remaining_us,
last_update_time_us,
last_spike_time_us,
synaptic_current_pa,
resistance_mohm,
noise_amplitude_pa,
adaptation_current_pa,
adaptation_enabled,
} = n;
assert!(
membrane_potential == resting_potential
&& *refractory_remaining_us == 0
&& *last_update_time_us == 0
&& *last_spike_time_us == 0
&& *synaptic_current_pa == 0
&& *adaptation_current_pa == 0,
"{case}, neuron {i}: the freezer writes a neuron at rest, before the first step"
);
let mut text = format!(
"LIFNeuron::new({id}, NeuronType::{neuron_type:?}, \
VoltageResolution::{voltage_resolution:?})"
);
let mut rebuilt = LIFNeuron::new(*id, *neuron_type, *voltage_resolution);
macro_rules! chain {
($($setter:ident => $value:expr),+ $(,)?) => {{
$(
text.push_str(&format!(".{}({})", stringify!($setter), $value));
rebuilt = rebuilt.$setter($value);
)+
}};
}
chain! {
with_resting_potential => *resting_potential,
with_threshold => *threshold,
with_reset_potential => *reset_potential,
with_tau_membrane_us => *tau_membrane_us,
with_refractory_period_us => *refractory_period_us,
with_resistance_mohm => *resistance_mohm,
with_noise_amplitude_pa => *noise_amplitude_pa,
with_adaptation_enabled => *adaptation_enabled,
}
(text, rebuilt)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::lif_neuron::{NeuronType, VoltageResolution};
fn quiet(id: u16, grid: VoltageResolution) -> LIFNeuron {
let mut n = LIFNeuron::new(id, NeuronType::Excitatory, grid);
n.noise_amplitude_pa = 0;
n
}
fn two() -> SpikingNeuralNetwork {
let neurons = vec![
quiet(0, VoltageResolution::CentiMillivolt),
quiet(1, VoltageResolution::CentiMillivolt),
];
let mut net = SpikingNeuralNetwork::from_neurons(neurons, 500).expect("neurons given");
net.add_synapse(0, 1, 5_000).expect("ids in range");
net.finalize_synapses();
net
}
fn silent() -> Vec<(u32, Vec<i16>)> {
vec![(3, vec![0, 0])]
}
#[test]
fn the_module_is_named_after_its_case_and_reads_the_network() {
let text = module(
&two(),
"two-quiet",
Kind::Stranger,
3,
Rows::Spikes,
&silent(),
);
assert!(text.starts_with("pub mod two_quiet {\n"), "{text}");
for line in [
" pub const N: usize = 2;\n",
" pub const S: usize = 1;\n",
" pub const DT_US: u32 = 500;\n",
" pub const STEPS: u32 = 3;\n",
" pub const SPIKES_ONLY: bool = true;\n",
" pub const HEADER: &str = \"# neuralos-trace v1 case=two-quiet kind=stranger n=2 \
dt_us=500 res=cmV plasticity=off divisor=10 steps=3 rows=spikes\";\n",
] {
assert!(text.contains(line), "{line:?} in {text}");
}
}
#[test]
fn the_tail_names_each_case_by_its_module() {
let text = tail(&["chain-3", "two"]);
assert!(
text.contains(" $m!(chain_3);\n $m!(two);\n"),
"{text}"
);
}
#[test]
#[cfg(feature = "unstable-stdp")]
#[should_panic(expected = "two: plasticity is on")]
fn plasticity_on_is_refused() {
let mut net = two();
net.set_plasticity_enabled(true);
let _ = module(&net, "two", Kind::Regression, 3, Rows::All, &silent());
}
#[test]
fn edges_out_of_pre_order_freeze_as_sorted() {
let wired = |sorted: bool| {
let neurons = (0..3)
.map(|id| quiet(id, VoltageResolution::CentiMillivolt))
.collect();
let mut net =
SpikingNeuralNetwork::from_neurons(neurons, 1_000).expect("neurons given");
net.add_synapse(1, 2, 5_000).expect("ids in range");
net.add_synapse(0, 1, 5_000).expect("ids in range");
if sorted {
net.finalize_synapses();
}
net
};
let frozen = |net: &SpikingNeuralNetwork| {
module(
net,
"out-of-order",
Kind::Regression,
1,
Rows::All,
&[(1, vec![0, 0, 0])],
)
};
let text = frozen(&wired(false));
assert_eq!(text, frozen(&wired(true)), "sorted or not, one module");
assert!(
text.contains(
" FixedSynapse::new(0, 1, 500),\n FixedSynapse::new(1, 2, 500),\n"
),
"by pre: {text}"
);
}
#[test]
#[should_panic(expected = "two: the network has stepped")]
fn a_stepped_network_is_refused() {
let mut net = two();
net.step(&[0, 0]).expect("two inputs");
let _ = module(&net, "two", Kind::Regression, 3, Rows::All, &silent());
}
#[test]
#[should_panic(expected = "mixed: the neurons store their potentials on two grids")]
fn two_grids_are_refused() {
let neurons = vec![
quiet(0, VoltageResolution::Millivolt),
quiet(1, VoltageResolution::Millivolt),
];
let mut net = SpikingNeuralNetwork::from_neurons(neurons, 1_000).expect("one grid");
net.neurons_mut()[1] = quiet(1, VoltageResolution::CentiMillivolt);
let _ = module(
&net,
"mixed",
Kind::Regression,
1,
Rows::All,
&[(1, vec![0, 0])],
);
}
#[test]
#[should_panic(expected = "\"Two\": a case name is lowercase")]
fn a_case_name_off_the_rule_is_refused() {
let _ = module(&two(), "Two", Kind::Regression, 3, Rows::All, &silent());
}
#[test]
#[should_panic(expected = "two: one current per neuron in every run of the drive")]
fn a_drive_short_of_a_current_is_refused() {
let _ = module(
&two(),
"two",
Kind::Regression,
3,
Rows::All,
&[(3, vec![0])],
);
}
#[test]
#[should_panic(expected = "restless, neuron 0: the freezer writes a neuron at rest")]
fn a_neuron_carrying_state_is_refused() {
let neurons = vec![
quiet(0, VoltageResolution::CentiMillivolt),
quiet(1, VoltageResolution::CentiMillivolt),
];
let mut net = SpikingNeuralNetwork::from_neurons(neurons, 1_000).expect("at rest");
net.neurons_mut()[0].membrane_potential += 1;
let _ = module(
&net,
"restless",
Kind::Regression,
1,
Rows::All,
&[(1, vec![0, 0])],
);
}
#[test]
#[should_panic(expected = "swapped, neuron 0: a neuron's id is its position")]
fn an_id_off_its_position_is_refused() {
let neurons = vec![
quiet(0, VoltageResolution::CentiMillivolt),
quiet(1, VoltageResolution::CentiMillivolt),
];
let mut net = SpikingNeuralNetwork::from_neurons(neurons, 1_000).expect("in place");
net.neurons_mut().swap(0, 1);
let _ = module(
&net,
"swapped",
Kind::Regression,
1,
Rows::All,
&[(1, vec![0, 0])],
);
}
}