#![allow(clippy::module_name_repetitions)]
#![allow(
clippy::cast_possible_truncation,
clippy::cast_possible_wrap,
clippy::cast_sign_loss
)]
use crate::Error;
pub const SCALE: i32 = 1000;
#[derive(Debug, Clone)]
pub struct Synapse {
pub(crate) pre_neuron_id: u16,
pub(crate) post_neuron_id: u16,
pub(crate) weight: i16,
#[cfg(feature = "unstable-stdp")]
pub(crate) max_weight: i16,
#[cfg(feature = "unstable-stdp")]
pub(crate) min_weight: i16,
#[cfg(feature = "unstable-stdp")]
pub(crate) raw_stdp_delta: i64,
#[cfg(feature = "unstable-stdp")]
pub(crate) absorbed_delta: i64,
}
impl Synapse {
pub fn new(pre_id: u16, post_id: u16, weight: i16) -> Result<Self, Error> {
if pre_id == post_id {
return Err(Error::SelfConnection);
}
#[cfg(feature = "unstable-stdp")]
let (max_weight, min_weight) = bounds_by_sign(weight);
Ok(Self {
pre_neuron_id: pre_id,
post_neuron_id: post_id,
weight,
#[cfg(feature = "unstable-stdp")]
max_weight,
#[cfg(feature = "unstable-stdp")]
min_weight,
#[cfg(feature = "unstable-stdp")]
raw_stdp_delta: 0,
#[cfg(feature = "unstable-stdp")]
absorbed_delta: 0,
})
}
#[must_use]
pub fn pre(&self) -> u16 {
self.pre_neuron_id
}
#[must_use]
pub fn post(&self) -> u16 {
self.post_neuron_id
}
#[must_use]
pub fn weight(&self) -> i16 {
self.weight
}
#[cfg(feature = "unstable-stdp")]
#[must_use]
pub fn max_weight(&self) -> i16 {
self.max_weight
}
#[cfg(feature = "unstable-stdp")]
#[must_use]
pub fn min_weight(&self) -> i16 {
self.min_weight
}
#[cfg(feature = "unstable-stdp")]
#[must_use]
pub fn raw_stdp_delta(&self) -> i64 {
self.raw_stdp_delta
}
#[cfg(feature = "unstable-stdp")]
#[must_use]
pub fn absorbed_delta(&self) -> i64 {
self.absorbed_delta
}
#[cfg(feature = "unstable-stdp")]
pub fn update_weight(&mut self, delta_weight: i16) {
let target = self
.weight
.saturating_add(delta_weight)
.clamp(self.min_weight, self.max_weight);
let applied = target - self.weight;
self.raw_stdp_delta += i64::from(delta_weight);
self.absorbed_delta += i64::from(delta_weight) - i64::from(applied);
self.weight = target;
}
}
#[cfg(all(test, feature = "unstable-stdp"))]
impl Synapse {
fn normalized_weight(&self) -> i16 {
let abs_max = self.max_weight.unsigned_abs();
if abs_max > 0 {
(i32::from(self.weight) * 100 / i32::from(abs_max)) as i16
} else {
0
}
}
}
#[cfg(feature = "unstable-stdp")]
fn bounds_by_sign(weight: i16) -> (i16, i16) {
if weight >= 0 {
(2000, 0) } else {
(0, -2000) }
}
#[cfg(feature = "unstable-stdp")]
#[derive(Debug, Clone)]
pub struct STDPRule {
pub tau_plus_us: u32,
pub tau_minus_us: u32,
pub a_plus: i16,
pub a_minus: i16,
pub learning_rate: u16,
}
#[cfg(feature = "unstable-stdp")]
impl STDPRule {
#[must_use]
pub fn new() -> Self {
Self {
tau_plus_us: 20_000,
tau_minus_us: 20_000,
a_plus: 50,
a_minus: -53, learning_rate: 100,
}
}
#[must_use]
pub fn calculate_weight_change(&self, dt_us: i32) -> i16 {
if dt_us > 0 {
let decay = (i64::from(dt_us).abs() * i64::from(SCALE)) / i64::from(self.tau_minus_us);
if decay < 10_000 {
let factor = (i64::from(SCALE) - decay).max(0); ((i64::from(self.a_minus) * factor * i64::from(self.learning_rate))
/ (i64::from(SCALE) * i64::from(SCALE))) as i16
} else {
0
}
} else {
let decay = (i64::from(dt_us).abs() * i64::from(SCALE)) / i64::from(self.tau_plus_us);
if decay < 10_000 {
let factor = (i64::from(SCALE) - decay).max(0); ((i64::from(self.a_plus) * factor * i64::from(self.learning_rate))
/ (i64::from(SCALE) * i64::from(SCALE))) as i16
} else {
0
}
}
}
}
#[cfg(feature = "unstable-stdp")]
impl Default for STDPRule {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
#![allow(clippy::shadow_unrelated)]
use super::*;
use proptest::prelude::*;
#[test]
fn new_excitatory_synapse_has_default_params() {
let s = Synapse::new(3, 7, 150).expect("valid ids");
assert_eq!(s.pre(), 3);
assert_eq!(s.post(), 7);
assert_eq!(s.weight(), 150);
#[cfg(feature = "unstable-stdp")]
{
assert_eq!(s.max_weight(), 2000); assert_eq!(s.min_weight(), 0);
assert_eq!((s.raw_stdp_delta(), s.absorbed_delta()), (0, 0));
}
}
#[test]
fn negative_weight_makes_inhibitory() {
let s = Synapse::new(3, 7, -150).expect("valid ids");
assert_eq!((s.pre(), s.post(), s.weight()), (3, 7, -150));
#[cfg(feature = "unstable-stdp")]
{
assert_eq!(s.max_weight(), 0); assert_eq!(s.min_weight(), -2000);
}
}
#[cfg(feature = "unstable-stdp")]
#[test]
fn the_bounds_follow_the_sign() {
for (weight, bounds) in [
(i16::MAX, (0, 2000)),
(1, (0, 2000)),
(0, (0, 2000)),
(-1, (-2000, 0)),
(i16::MIN, (-2000, 0)),
] {
let s = Synapse::new(3, 7, weight).expect("valid ids");
assert_eq!((s.min_weight(), s.max_weight()), bounds, "weight {weight}");
assert_eq!(s.weight(), weight, "kept as given");
}
}
#[test]
fn self_connection_rejected() {
let err = Synapse::new(5, 5, 100).unwrap_err();
assert_eq!(err, Error::SelfConnection);
}
#[cfg(feature = "unstable-stdp")]
#[test]
fn normalized_weight_is_percentage_of_max() {
let mut s = Synapse::new(1, 2, 100).expect("valid ids");
assert_eq!(s.max_weight(), 2000);
assert_eq!(s.normalized_weight(), 5);
s.weight = s.max_weight;
assert_eq!(s.normalized_weight(), 100);
s.weight = -s.max_weight;
assert_eq!(s.normalized_weight(), -100);
s.max_weight = 0;
assert_eq!(s.normalized_weight(), 0, "zero max must not divide by zero");
}
#[cfg(feature = "unstable-stdp")]
#[test]
fn weight_clamped_at_bounds() {
let mut s = Synapse::new(1, 2, 100).expect("valid ids");
s.update_weight(10_000); assert_eq!(s.weight(), s.max_weight());
assert_eq!((s.raw_stdp_delta(), s.absorbed_delta()), (10_000, 8_100));
s.update_weight(-10_000); assert_eq!(s.weight(), s.min_weight());
assert_eq!((s.raw_stdp_delta(), s.absorbed_delta()), (0, 100));
}
#[cfg(feature = "unstable-stdp")]
#[test]
fn stdp_ltp_when_pre_before_post() {
let rule = STDPRule::new();
let dt_us: i32 = -5_000; let delta = rule.calculate_weight_change(dt_us);
assert!(
delta >= 0,
"pre-before-post must produce LTP (>=0), got {delta}"
);
}
#[cfg(feature = "unstable-stdp")]
#[test]
fn stdp_ltd_when_post_before_pre() {
let rule = STDPRule::new();
let dt_us: i32 = 5_000;
let delta = rule.calculate_weight_change(dt_us);
assert!(
delta <= 0,
"post-before-pre must produce LTD (<=0), got {delta}"
);
}
#[cfg(feature = "unstable-stdp")]
#[test]
fn stdp_zero_outside_window() {
let rule = STDPRule::new();
let far_dt: i32 = -200_000;
assert_eq!(rule.calculate_weight_change(far_dt), 0);
let far_dt_pos: i32 = 200_000;
assert_eq!(rule.calculate_weight_change(far_dt_pos), 0);
}
#[cfg(feature = "unstable-stdp")]
#[test]
fn stdp_zero_at_zero_dt() {
let rule = STDPRule::new();
let delta = rule.calculate_weight_change(0);
let expected =
(i32::from(rule.a_plus) * SCALE * i32::from(rule.learning_rate)) / (SCALE * SCALE);
assert_eq!(delta, expected as i16);
}
#[cfg(feature = "unstable-stdp")]
#[test]
fn stdp_decay_monotonic_with_abs_dt() {
let rule = STDPRule::new();
let small = rule.calculate_weight_change(-1_000).abs();
let large = rule.calculate_weight_change(-10_000).abs();
assert!(
large <= small,
"|delta| must decay with |dt|: small={small}, large={large}"
);
}
#[cfg(feature = "unstable-stdp")]
#[test]
fn stdp_zero_just_past_the_old_overflow_boundary() {
let rule = STDPRule::new();
assert_eq!(rule.calculate_weight_change(2_200_000), 0, "LTD branch");
assert_eq!(rule.calculate_weight_change(-2_200_000), 0, "LTP branch");
assert_eq!(rule.calculate_weight_change(i32::MAX), 0);
assert_eq!(rule.calculate_weight_change(i32::MIN), 0);
}
#[cfg(feature = "unstable-stdp")]
#[test]
fn stdp_extreme_learning_rate_does_not_overflow_the_product() {
let mut rule = STDPRule::new();
rule.learning_rate = u16::MAX;
let delta = rule.calculate_weight_change(0);
let expected = (i64::from(rule.a_plus) * i64::from(SCALE) * i64::from(u16::MAX))
/ (i64::from(SCALE) * i64::from(SCALE));
assert_eq!(
i64::from(delta),
expected,
"no wrap at lr = u16::MAX, dt = 0"
);
}
proptest! {
#[test]
fn prop_self_connection_always_rejected(id in 0u16..=1000, weight in -3000i16..=3000) {
let result = Synapse::new(id, id, weight);
prop_assert_eq!(result.err(), Some(Error::SelfConnection));
}
#[cfg(feature = "unstable-stdp")]
#[test]
fn prop_weight_clamped(weight in any::<i16>(), delta in any::<i16>()) {
let mut s = Synapse::new(1, 2, weight).expect("valid ids");
prop_assert!(s.min_weight() <= s.max_weight());
s.update_weight(delta);
prop_assert!(s.weight() >= s.min_weight());
prop_assert!(s.weight() <= s.max_weight());
}
#[cfg(feature = "unstable-stdp")]
#[test]
fn prop_stdp_sign_convention(dt_us in -200_000i32..=200_000) {
let rule = STDPRule::new();
let delta = rule.calculate_weight_change(dt_us);
if dt_us > 0 {
prop_assert!(delta <= 0, "post-before-pre must produce LTD");
} else if dt_us < 0 {
prop_assert!(delta >= 0, "pre-before-post must produce LTP");
}
}
#[cfg(feature = "unstable-stdp")]
#[test]
fn prop_stdp_zero_outside_window(multiplier in 11u32..=100) {
let rule = STDPRule::new();
let far_dt_pos = (rule.tau_minus_us * multiplier) as i32;
let far_dt_neg = -((rule.tau_plus_us * multiplier) as i32);
prop_assert_eq!(rule.calculate_weight_change(far_dt_pos), 0);
prop_assert_eq!(rule.calculate_weight_change(far_dt_neg), 0);
}
#[cfg(feature = "unstable-stdp")]
#[test]
fn prop_stdp_dt_full_i32_range(dt_us in i32::MIN..=i32::MAX) {
let rule = STDPRule::new();
let delta = rule.calculate_weight_change(dt_us);
let outside =
i64::from(dt_us).abs() >= 10 * i64::from(rule.tau_plus_us.max(rule.tau_minus_us));
if outside {
prop_assert_eq!(delta, 0, "outside the window at dt={}", dt_us);
} else if dt_us > 0 {
prop_assert!(delta <= 0, "in-window post-before-pre must be LTD at dt={}", dt_us);
} else {
prop_assert!(delta >= 0, "in-window pre-before-post must be LTP at dt={}", dt_us);
}
}
}
#[cfg(feature = "unstable-stdp")]
#[test]
fn the_default_rule_is_the_one_its_doc_names() {
let r = STDPRule::new();
assert_eq!(
(
r.tau_plus_us,
r.tau_minus_us,
r.a_plus,
r.a_minus,
r.learning_rate
),
(20_000, 20_000, 50, -53, 100)
);
}
}