use std::path::{Path, PathBuf};
#[cfg(feature = "unstable-freeze")]
use gresil::fixed::freeze;
use gresil::nir::{NirImport, NirImportOptions, Thousandths};
use gresil::trace::{self, Kind, Rows};
use gresil::{LIFNeuron, NetworkTopology, NeuronType, SpikingNeuralNetwork, VoltageResolution};
pub const DIR: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/traces");
const DT_US: u32 = 1_000;
pub struct Case {
pub name: &'static str,
pub kind: Kind,
pub steps: u32,
pub rows: Rows,
pub build: fn() -> Run,
}
pub struct Run {
pub net: SpikingNeuralNetwork,
pub drive: Box<dyn Fn(u32) -> Vec<i16>>,
}
pub fn path(case: &Case) -> PathBuf {
Path::new(DIR).join(format!("{}.trace", case.name))
}
fn header(case: &Case, net: &SpikingNeuralNetwork) -> String {
trace::header(net, case.name, case.kind, case.steps, case.rows)
.expect("every case is on one grid and named by the rule")
}
#[cfg(feature = "unstable-freeze")]
pub fn frozen_path() -> PathBuf {
Path::new(DIR).join("frozen.rs")
}
#[cfg(feature = "unstable-freeze")]
pub fn freeze() -> String {
let mut out = String::from(freeze::preamble());
let mut frozen = Vec::new();
for case in CASES {
let Run { net, drive } = (case.build)();
if net.plasticity_enabled() {
continue;
}
let drive = runs(case.name, &*drive, case.steps, net.neurons().len());
out.push('\n');
out.push_str(&freeze::module(
&net, case.name, case.kind, case.steps, case.rows, &drive,
));
frozen.push(case.name);
}
out.push('\n');
out.push_str(&freeze::tail(&frozen));
out
}
#[cfg(feature = "unstable-freeze")]
fn runs(name: &str, drive: &dyn Fn(u32) -> Vec<i16>, steps: u32, n: usize) -> Vec<(u32, Vec<i16>)> {
let mut runs: Vec<(u32, Vec<i16>)> = Vec::new();
for step in 0..steps {
let currents = drive(step);
assert_eq!(
currents.len(),
n,
"{name} step {step}: one current per neuron"
);
match runs.last_mut() {
Some((count, last)) if *last == currents => *count += 1,
_ => runs.push((1, currents)),
}
}
runs
}
pub fn render(case: &Case) -> String {
let Run { mut net, drive } = (case.build)();
let mut out = header(case, &net);
out.push('\n');
for step in 0..case.steps {
let time_us = net.time_us();
let spikes = net.step(&drive(step)).expect("a built case steps");
if matches!(case.rows, Rows::Spikes) && spikes.is_empty() {
continue;
}
let ids: Vec<String> = spikes.iter().map(|s| s.neuron_id.to_string()).collect();
let membranes: Vec<String> = net
.neurons()
.iter()
.map(|n| n.membrane_potential().to_string())
.collect();
out.push_str(&format!(
"{step} {time_us} | {} | {}\n",
ids.join(" "),
membranes.join(" ")
));
}
out
}
fn neuron(id: u16, kind: NeuronType, res: VoltageResolution, noise_pa: u8) -> LIFNeuron {
LIFNeuron::new(id, kind, res).with_noise_amplitude_pa(noise_pa)
}
fn wired(neurons: Vec<LIFNeuron>, edges: &[(u16, u16, i16)]) -> SpikingNeuralNetwork {
let mut net = SpikingNeuralNetwork::from_neurons(neurons, DT_US).expect("neurons given");
for &(pre, post, w) in edges {
net.add_synapse(pre, post, w)
.expect("ids in range, no self edge");
}
net
}
const NIR_CHAIN: &[u8] = include_bytes!("../nir_fixtures/chain.json");
const SNNTORCH_TWO_LAYER: &[u8] = include_bytes!("../nir_fixtures/snntorch_two_layer_sim.json");
const TWO_LIF_NEURONS: &[u8] = include_bytes!("../nir_fixtures/two_lif_neurons_sim.json");
const fn regression(name: &'static str, steps: u32, build: fn() -> Run) -> Case {
Case {
name,
kind: Kind::Regression,
steps,
rows: Rows::All,
build,
}
}
pub const CASES: &[Case] = &[
Case {
name: "neuron-reference",
kind: Kind::Reference,
steps: 150,
rows: Rows::All,
build: neuron_reference,
},
Case {
name: "one-neuron-board",
kind: Kind::Regression,
steps: 10_000,
rows: Rows::Spikes,
build: one_neuron_board,
},
regression("chain-3", 100, chain_3),
regression("feedforward-8", 150, feedforward_8),
regression("recurrent-transmission", 30, recurrent_transmission),
regression("centi-mv-grid", 30, centi_mv_grid),
regression("inhibitory", 100, inhibitory),
regression("refractory", 40, refractory),
#[cfg(feature = "unstable-stdp")]
regression("plasticity-on", 150, plasticity_on),
regression("plasticity-off", 150, plasticity_off),
regression("saturation-floor-ceiling", 100, saturation_floor_ceiling),
regression("nir-chain-fixture", 100, nir_chain_fixture),
regression("ternary-weights", 100, ternary_weights),
regression("snntorch-two-layer", 150, snntorch_two_layer),
regression("two-lif-neurons", 150, two_lif_neurons),
];
fn neuron_reference() -> Run {
let n = neuron(
0,
NeuronType::Excitatory,
VoltageResolution::CentiMillivolt,
0,
)
.with_threshold(i16::MAX);
let net = wired(vec![n], &[]);
Run {
net,
drive: Box::new(|step| {
vec![match step {
0..=39 => 160,
40..=69 => i16::MAX,
70..=99 => i16::MIN,
_ => 0,
}]
}),
}
}
fn one_neuron_board() -> Run {
let net = wired(
vec![LIFNeuron::new(
0,
NeuronType::Excitatory,
VoltageResolution::CentiMillivolt,
)],
&[],
);
Run {
net,
drive: Box::new(|_| vec![160]),
}
}
fn chain_3() -> Run {
let ns = (0..3)
.map(|id| {
neuron(
id,
NeuronType::Excitatory,
VoltageResolution::CentiMillivolt,
0,
)
})
.collect();
let mut net = wired(ns, &[(0, 1, 5_000), (1, 2, 5_000)]);
net.set_synaptic_input_divisor(1).expect("in 1 to 32,767");
Run {
net,
drive: Box::new(|_| vec![600, 0, 0]),
}
}
fn feedforward_8() -> Run {
let mut net = SpikingNeuralNetwork::new_with_voltage_resolution(
8,
DT_US,
NetworkTopology::Feedforward { layers: &[3, 3, 2] },
VoltageResolution::CentiMillivolt,
)
.expect("8 neurons, 1 ms");
net.build_topology().expect("layers sum to 8");
net.set_synaptic_input_divisor(1).expect("in 1 to 32,767");
Run {
net,
drive: Box::new(|_| vec![600, 600, 600, 148, 148, 148, 199, 199]),
}
}
fn recurrent_transmission() -> Run {
let net = wired(
vec![
neuron(0, NeuronType::Excitatory, VoltageResolution::Millivolt, 0),
neuron(1, NeuronType::Inhibitory, VoltageResolution::Millivolt, 0),
],
&[(0, 1, 2_000)],
);
Run {
net,
drive: Box::new(|step| {
if step == 0 {
vec![3_000, 0]
} else {
vec![0, 0]
}
}),
}
}
fn centi_mv_grid() -> Run {
let net = wired(
vec![
neuron(
0,
NeuronType::Excitatory,
VoltageResolution::CentiMillivolt,
0,
),
neuron(
1,
NeuronType::Inhibitory,
VoltageResolution::CentiMillivolt,
0,
),
],
&[(0, 1, 125)],
);
Run {
net,
drive: Box::new(|step| {
if step == 0 {
vec![3_000, 0]
} else {
vec![0, 0]
}
}),
}
}
fn inhibitory() -> Run {
let net = wired(
vec![
neuron(
0,
NeuronType::Inhibitory,
VoltageResolution::CentiMillivolt,
0,
),
neuron(
1,
NeuronType::Excitatory,
VoltageResolution::CentiMillivolt,
0,
),
],
&[(0, 1, -10_000)],
);
Run {
net,
drive: Box::new(|_| vec![250, 250]),
}
}
fn refractory() -> Run {
let net = wired(
vec![neuron(
0,
NeuronType::Excitatory,
VoltageResolution::CentiMillivolt,
0,
)],
&[],
);
Run {
net,
drive: Box::new(|_| vec![3_000]),
}
}
fn plastic(enabled: bool) -> Run {
let ns = (0..2)
.map(|id| {
neuron(
id,
NeuronType::Excitatory,
VoltageResolution::CentiMillivolt,
0,
)
})
.collect();
let mut net = wired(ns, &[(0, 1, 1_000)]);
#[cfg(feature = "unstable-stdp")]
net.set_plasticity_enabled(enabled);
#[cfg(not(feature = "unstable-stdp"))]
assert!(!enabled, "no switch without `unstable-stdp`");
net.set_synaptic_input_divisor(1).expect("in 1 to 32,767");
Run {
net,
drive: Box::new(|_| vec![600, 200]),
}
}
#[cfg(feature = "unstable-stdp")]
fn plasticity_on() -> Run {
plastic(true)
}
fn plasticity_off() -> Run {
plastic(false)
}
fn saturation_floor_ceiling() -> Run {
let n =
neuron(0, NeuronType::Excitatory, VoltageResolution::Millivolt, 0).with_threshold(i16::MAX);
let net = wired(vec![n], &[]);
Run {
net,
drive: Box::new(|step| {
vec![match step {
0..=19 => i16::MAX,
20..=49 => 0,
50..=69 => i16::MIN,
_ => 0,
}]
}),
}
}
fn nir_chain_fixture() -> Run {
let g = NirImport::from_json(
NIR_CHAIN,
NirImportOptions::new(1_000, VoltageResolution::Millivolt),
)
.expect("the reference emission imports");
let (net, enc, _report) = g.build_network().expect("the chain assembles");
Run {
net,
drive: Box::new(move |_| enc.encode(&[&[4_000, 0, 0].map(Thousandths)])),
}
}
fn ternary_weights() -> Run {
let ns = (0..3)
.map(|id| neuron(id, NeuronType::Excitatory, VoltageResolution::Millivolt, 0))
.collect();
let mut net = wired(ns, &[(0, 1, 2_400), (0, 2, 900), (1, 2, -1_500)]);
let gamma = net.ternarize_weights();
assert_eq!(gamma, 1_600, "the mean magnitude of 2,400, 900 and 1,500");
net.set_synaptic_input_divisor(1).expect("in 1 to 32,767");
Run {
net,
drive: Box::new(|_| vec![600, 300, 300]),
}
}
fn witness(json: &'static [u8], drive: fn(u32) -> Thousandths) -> Run {
let g = NirImport::from_json(json, NirImportOptions::sim_units(100))
.expect("the converted witness imports");
let (net, enc, _report) = g.build_network().expect("the two-layer graph assembles");
Run {
net,
drive: Box::new(move |step| enc.encode(&[&[drive(step)]])),
}
}
fn snntorch_two_layer() -> Run {
witness(SNNTORCH_TWO_LAYER, |step| {
Thousandths(i32::from(matches!(step, 0..=9 | 50..=59)) * 1_000)
})
}
fn two_lif_neurons() -> Run {
witness(TWO_LIF_NEURONS, |_| Thousandths(1_000))
}