use core::fmt::{self, Write};
use crate::lif_neuron::LIFNeuron;
#[cfg(feature = "std")]
use crate::lif_neuron::VoltageResolution;
#[cfg(feature = "std")]
use crate::network::SpikingNeuralNetwork;
#[cfg(feature = "std")]
use crate::{Error, Result};
#[cfg(feature = "std")]
const FORMAT: &str = "neuralos-trace v1";
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Kind {
Regression,
Reference,
Stranger,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Rows {
All,
Spikes,
}
#[cfg(feature = "std")]
pub fn header(
net: &SpikingNeuralNetwork,
case: &str,
kind: Kind,
steps: u32,
rows: Rows,
) -> Result<String> {
let Some(grid) = one_grid(net) else {
return Err(Error::MixedVoltageGrids);
};
if !is_case_name(case) {
return Err(Error::BadCaseName);
}
Ok(format!(
"# {FORMAT} case={case} kind={} n={} dt_us={} res={} plasticity={} divisor={} steps={steps} rows={}",
match kind {
Kind::Regression => "regression",
Kind::Reference => "reference",
Kind::Stranger => "stranger",
},
net.neurons().len(),
net.dt_us(),
match grid {
VoltageResolution::Millivolt => "mV",
VoltageResolution::CentiMillivolt => "cmV",
},
if net.plasticity_enabled() { "on" } else { "off" },
net.synaptic_input_divisor(),
match rows {
Rows::All => "all",
Rows::Spikes => "spikes",
},
))
}
#[cfg(feature = "std")]
pub(crate) fn one_grid(net: &SpikingNeuralNetwork) -> Option<VoltageResolution> {
let mut grids = net.neurons().iter().map(|n| n.voltage_resolution);
let first = grids.next()?;
grids.all(|g| g == first).then_some(first)
}
#[cfg(feature = "std")]
pub(crate) fn is_case_name(case: &str) -> bool {
!case.is_empty()
&& case
.bytes()
.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
}
#[allow(clippy::similar_names)]
pub fn row(
out: &mut impl Write,
step: u32,
time_us: u64,
fired: &[bool],
neurons: &[LIFNeuron],
) -> fmt::Result {
write!(out, "{step} {time_us} | ")?;
let mut sep = "";
for (id, &f) in fired.iter().enumerate() {
if f {
write!(out, "{sep}{id}")?;
sep = " ";
}
}
out.write_str(" | ")?;
let mut sep = "";
for n in neurons {
write!(out, "{sep}{}", n.membrane_potential)?;
sep = " ";
}
out.write_char('\n')
}
#[cfg(all(test, feature = "std"))]
mod tests {
use super::*;
use crate::lif_neuron::NeuronType;
fn on_grids(grids: &[VoltageResolution]) -> SpikingNeuralNetwork {
let neuron = |id, grid| LIFNeuron::new(id, NeuronType::Excitatory, grid);
let first = (0u16..).zip(grids).map(|(id, _)| neuron(id, grids[0]));
let mut net = SpikingNeuralNetwork::from_neurons(first.collect(), 500).expect("one grid");
for ((id, &grid), slot) in (0u16..).zip(grids).zip(net.neurons_mut()) {
*slot = neuron(id, grid);
}
net
}
#[test]
fn a_time_past_the_u32_range_prints_whole() {
let mut out = String::new();
row(
&mut out,
7,
5_000_000_000,
&[false],
&[LIFNeuron::new(
0,
NeuronType::Excitatory,
VoltageResolution::Millivolt,
)],
)
.expect("a String");
assert!(out.starts_with("7 5000000000 | "), "{out:?}");
assert!(out.ends_with('\n'), "{out:?}");
}
#[test]
fn the_header_is_what_the_network_says_and_the_run_it_is_given() {
let mut net = on_grids(&[VoltageResolution::CentiMillivolt; 2]);
net.set_synaptic_input_divisor(3).expect("in 1 to 32,767");
for (kind, word) in [
(Kind::Regression, "regression"),
(Kind::Reference, "reference"),
(Kind::Stranger, "stranger"),
] {
for (rows, rows_word) in [(Rows::All, "all"), (Rows::Spikes, "spikes")] {
assert_eq!(
header(&net, "two-lif-neurons", kind, 150, rows),
Ok(format!(
"# neuralos-trace v1 case=two-lif-neurons kind={word} n=2 dt_us=500 \
res=cmV plasticity=off divisor=3 steps=150 rows={rows_word}"
))
);
}
}
let mv = on_grids(&[VoltageResolution::Millivolt]);
assert!(header(&mv, "a", Kind::Regression, 1, Rows::All)
.is_ok_and(|h| h.contains(" n=1 dt_us=500 res=mV ")));
}
#[test]
fn a_network_on_two_grids_is_refused() {
let mixed = on_grids(&[
VoltageResolution::Millivolt,
VoltageResolution::CentiMillivolt,
]);
assert_eq!(
header(&mixed, "mixed", Kind::Regression, 1, Rows::All),
Err(Error::MixedVoltageGrids)
);
let one = on_grids(&[VoltageResolution::Millivolt; 2]);
assert!(header(&one, "one", Kind::Regression, 1, Rows::All).is_ok());
}
#[test]
fn n_counts_every_neuron_at_the_cap() {
let neurons = (0..u16::MAX)
.map(|id| LIFNeuron::new(id, NeuronType::Excitatory, VoltageResolution::Millivolt))
.collect();
let net = SpikingNeuralNetwork::from_neurons(neurons, 1_000).expect("neurons given");
assert!(header(&net, "big", Kind::Regression, 1, Rows::All)
.is_ok_and(|h| h.contains(" n=65535 ")));
}
#[test]
fn a_case_name_is_lowercase_letters_digits_and_dashes() {
let net = on_grids(&[VoltageResolution::Millivolt]);
for good in ["a", "0", "-", "chain-3", "snntorch-two-layer"] {
assert!(
header(&net, good, Kind::Regression, 1, Rows::All).is_ok(),
"{good:?}"
);
}
for bad in [
"",
"Chain-3",
"chain_3",
"chain 3",
"chain\n3",
"cha\u{ee}ne",
] {
assert_eq!(
header(&net, bad, Kind::Regression, 1, Rows::All),
Err(Error::BadCaseName),
"{bad:?}"
);
}
}
}