use super::{SnnBackend, SnnCapabilities, SnnStepOutput};
use crate::error::{CortexError, Result};
use neuromod::{NeuroModulators, SeedableRng, SpikingNetwork, StdRng};
struct SeededRng {
seed: u64,
rng: StdRng,
}
impl SeededRng {
fn new(seed: u64) -> Self {
Self {
seed,
rng: StdRng::seed_from_u64(seed),
}
}
}
pub struct NeuromodNetwork {
network: SpikingNetwork,
pub modulators: NeuroModulators,
rng: Option<SeededRng>,
}
impl NeuromodNetwork {
pub fn new(num_lif: usize, num_izh: usize, num_channels: usize) -> Result<Self> {
let mut network = SpikingNetwork::with_dimensions(num_lif, num_izh, num_channels);
let (_, w_max) = network.stdp_config.weight_bounds();
for (idx, neuron) in network.neurons.iter_mut().enumerate() {
if let Some(weight) = neuron.weights.get_mut(idx) {
*weight = w_max;
}
}
Self::checked(network)
}
pub fn from_network(network: SpikingNetwork) -> Result<Self> {
Self::checked(network)
}
fn checked(network: SpikingNetwork) -> Result<Self> {
let lif = network.neurons.len();
if lif != network.num_channels {
return Err(CortexError::InvalidConfig(format!(
"neuromod SpikingNetwork has {lif} LIF neurons but {} channels; the SnnBackend contract requires one LIF neuron per channel (the {} Izhikevich neurons do not count: neuromod reports LIF spikes only)",
network.num_channels,
network.iz_neurons.len()
)));
}
let channels = network.num_channels;
for (idx, neuron) in network.neurons.iter().enumerate() {
let in_range = &neuron.weights[..neuron.weights.len().min(channels)];
if let Some(ch) = in_range.iter().position(|w| !w.is_finite()) {
return Err(CortexError::InvalidConfig(format!(
"neuromod SpikingNetwork LIF neuron {idx} has a non-finite weight on channel {ch}; it would poison the membrane potential"
)));
}
if !in_range.iter().any(|w| *w > 0.0) {
return Err(CortexError::InvalidConfig(format!(
"neuromod SpikingNetwork LIF neuron {idx} has no positive weight on channels 0..{} (of {channels}), so channel {idx} can never spike; seed its weights (e.g. via network_mut()) before wrapping it",
in_range.len()
)));
}
}
Ok(Self {
network,
modulators: NeuroModulators::default(),
rng: None,
})
}
pub fn with_seed(mut self, seed: u64) -> Self {
self.set_seed(Some(seed));
self
}
pub fn set_seed(&mut self, seed: Option<u64>) {
self.rng = seed.map(SeededRng::new);
}
pub fn seed(&self) -> Option<u64> {
self.rng.as_ref().map(|r| r.seed)
}
pub fn network(&self) -> &SpikingNetwork {
&self.network
}
pub fn network_mut(&mut self) -> &mut SpikingNetwork {
&mut self.network
}
fn into_output(
result: std::result::Result<Vec<usize>, neuromod::StepError>,
) -> Result<SnnStepOutput> {
result
.map(|spikes| SnnStepOutput { spikes })
.map_err(|err| match err {
neuromod::StepError::InputLenMismatch { expected, got } => {
CortexError::InputLengthMismatch { expected, got }
}
neuromod::StepError::NonFiniteStimulus { index, class } => {
let value = match class {
neuromod::NonFiniteClass::PosInfinity => f32::INFINITY,
neuromod::NonFiniteClass::NegInfinity => f32::NEG_INFINITY,
_ => f32::NAN,
};
CortexError::SnnInvalidStimulus {
channel: index,
value,
}
}
other => CortexError::SnnBackend(other.to_string()),
})
}
}
impl SnnBackend for NeuromodNetwork {
fn channels(&self) -> usize {
self.network.num_channels
}
fn step(&mut self, stimulus: &[f32]) -> Result<SnnStepOutput> {
let result = match self.rng.as_mut() {
Some(seeded) => self
.network
.step_with_rng(stimulus, &self.modulators, &mut seeded.rng),
None => self.network.step(stimulus, &self.modulators),
};
Self::into_output(result)
}
fn step_frozen(&mut self, stimulus: &[f32]) -> Result<SnnStepOutput> {
let result = match self.rng.as_mut() {
Some(seeded) => {
self.network
.step_frozen_with_rng(stimulus, &self.modulators, &mut seeded.rng)
}
None => self.network.step_frozen(stimulus, &self.modulators),
};
Self::into_output(result)
}
fn reset(&mut self) {
self.network.reset();
if let Some(seeded) = self.rng.as_mut() {
*seeded = SeededRng::new(seeded.seed);
}
}
fn capabilities(&self) -> SnnCapabilities {
SnnCapabilities {
backend_name: "neuromod::SpikingNetwork",
frozen_evaluation: true,
plasticity: true,
caller_rng: self.rng.is_some(),
neuromodulation: true,
}
}
}