Skip to main content

gresil/
synapse.rs

1// SPDX-FileCopyrightText: 2026 philo-the-dendron
2// SPDX-License-Identifier: AGPL-3.0-or-later
3//! Synapse model — clean port from v0.1 `libneuralos/src/core/spiking_neural_network/synapse.rs`.
4//!
5//! # Audit context
6//!
7//! The audit flagged this as **Gem #3** — *"the better-engineered STDP rule impl"*
8//! (vs `stdp_plasticity.rs` which had the LTP timing filter bug). Port this version.
9//!
10//! # Invariants (testable)
11//!
12//! - `Synapse::new(id, id, _)` always refuses, with
13//!   [`Error::SelfConnection`] (no self-connections).
14//!
15//! With the `unstable-stdp` feature (`update_weight`, `STDPRule`, a
16//! synapse's bounds and its two counters exist in no other build, and may
17//! change or go in a minor release):
18//!
19//! - `Synapse::new` sets the bounds from the weight's sign: `[0, 2000]`
20//!   for a weight of 0 or more, `[-2000, 0]` below 0. The fields are the
21//!   crate's, so no caller writes the bounds.
22//! - Weight stays within `[min_weight, max_weight]` after every `update_weight` call.
23//! - `STDPRule::calculate_weight_change(dt)` returns 0 for `|dt| ≥ tau`, where the
24//!   linear factor reaches 0.
25//! - LTP (pre before post, dt < 0) returns a non-negative delta.
26//! - LTD (post before pre, dt > 0) returns a non-positive delta.
27//!
28//! # Fixed-point conventions
29//!
30//! - Weight: `i16`, fixed-point 1000 = 1.0 (range ~[-2000, 2000] typically).
31//! - Time: `u32` microseconds.
32//!
33//! # `no_std`
34//!
35//! Uses `crate::Error` (no `String`, no alloc) for self-connection rejection.
36//! Fully `no_std`-compatible — pairs with `lif_neuron`.
37
38#![allow(clippy::module_name_repetitions)]
39// Fixed-point design: narrow types (i16 weight, u32 μs) with
40// physics-bounded values. Casts between them are intentional and bounded.
41#![allow(
42    clippy::cast_possible_truncation,
43    clippy::cast_possible_wrap,
44    clippy::cast_sign_loss
45)]
46
47use crate::Error;
48
49/// Fixed-point scale: 1000 = 1.0.
50///
51/// Public since Stage 3: with `unstable-bridge`,
52/// `bridge::wire_gamma_to_substrate` maps imported wire-format scales into
53/// the substrate through exactly this constant — the coupling has one home
54/// and a pinning test, not a magic 1000.
55pub const SCALE: i32 = 1000;
56
57/// A synapse: its two ends and its fixed-point weight, and with
58/// `unstable-stdp` the bounds STDP clamps the weight to and two
59/// instrumentation counters.
60///
61/// Its fields are the crate's. [`new`](Self::new) builds it, the bounds
62/// from the weight's sign; `update_weight`, behind `unstable-stdp`, is
63/// its one method that changes it, and a network writes its own
64/// synapses' weights, never their bounds, in its STDP and ternary passes;
65/// its `reset` sets their two counters to 0.
66/// A getter reads each value. A network's synapses reach a caller as a
67/// slice (`SpikingNeuralNetwork::synapses`). Pairs with
68/// [`LIFNeuron`](crate::LIFNeuron) for full integrate-and-fire + STDP.
69#[derive(Debug, Clone)]
70pub struct Synapse {
71    /// Presynaptic (source) neuron ID.
72    pub(crate) pre_neuron_id: u16,
73    /// Postsynaptic (target) neuron ID.
74    pub(crate) post_neuron_id: u16,
75    /// Synaptic weight (fixed-point, 1000 = 1.0). Negative = inhibitory.
76    pub(crate) weight: i16,
77    /// Maximum weight (plasticity clamp).
78    #[cfg(feature = "unstable-stdp")]
79    pub(crate) max_weight: i16,
80    /// Minimum weight (plasticity clamp).
81    #[cfg(feature = "unstable-stdp")]
82    pub(crate) min_weight: i16,
83    /// Cumulative raw STDP delta (session G instrumentation): see
84    /// [`raw_stdp_delta`](Self::raw_stdp_delta).
85    #[cfg(feature = "unstable-stdp")]
86    pub(crate) raw_stdp_delta: i64,
87    /// Cumulative delta the clamp absorbed: see
88    /// [`absorbed_delta`](Self::absorbed_delta).
89    #[cfg(feature = "unstable-stdp")]
90    pub(crate) absorbed_delta: i64,
91}
92
93impl Synapse {
94    /// New synapse between `pre_id` and `post_id` with initial `weight`.
95    ///
96    /// With `unstable-stdp`, the bounds come from the weight's sign:
97    /// `[0, 2000]` for a weight of 0 or more (excitatory, AMPA),
98    /// `[-2000, 0]` below 0 (inhibitory, GABA), and the counters start at
99    /// 0. The weight is kept as given, inside its bounds or not.
100    ///
101    /// ```
102    /// use gresil::Synapse;
103    ///
104    /// let s = Synapse::new(3, 7, -150)?;
105    /// assert_eq!((s.pre(), s.post(), s.weight()), (3, 7, -150));
106    /// #[cfg(feature = "unstable-stdp")]
107    /// assert_eq!((s.min_weight(), s.max_weight()), (-2000, 0));
108    /// #[cfg(feature = "unstable-stdp")]
109    /// assert_eq!((s.raw_stdp_delta(), s.absorbed_delta()), (0, 0));
110    /// assert_eq!(Synapse::new(3, 7, 2_500)?.weight(), 2_500, "kept as given");
111    /// # Ok::<(), gresil::Error>(())
112    /// ```
113    ///
114    /// # Errors
115    ///
116    /// [`Error::SelfConnection`] when `pre_id == post_id`.
117    pub fn new(pre_id: u16, post_id: u16, weight: i16) -> Result<Self, Error> {
118        if pre_id == post_id {
119            return Err(Error::SelfConnection);
120        }
121        #[cfg(feature = "unstable-stdp")]
122        let (max_weight, min_weight) = bounds_by_sign(weight);
123        Ok(Self {
124            pre_neuron_id: pre_id,
125            post_neuron_id: post_id,
126            weight,
127            #[cfg(feature = "unstable-stdp")]
128            max_weight,
129            #[cfg(feature = "unstable-stdp")]
130            min_weight,
131            #[cfg(feature = "unstable-stdp")]
132            raw_stdp_delta: 0,
133            #[cfg(feature = "unstable-stdp")]
134            absorbed_delta: 0,
135        })
136    }
137
138    /// The presynaptic neuron's id: its spike sends the pulse.
139    #[must_use]
140    pub fn pre(&self) -> u16 {
141        self.pre_neuron_id
142    }
143
144    /// The postsynaptic neuron's id: its synaptic current takes the pulse.
145    #[must_use]
146    pub fn post(&self) -> u16 {
147        self.post_neuron_id
148    }
149
150    /// The weight (fixed-point, 1000 = 1.0); negative is inhibitory.
151    #[must_use]
152    pub fn weight(&self) -> i16 {
153        self.weight
154    }
155
156    /// Unstable: behind `unstable-stdp`.
157    /// The largest weight `update_weight` leaves: 2000 for an excitatory
158    /// synapse, 0 for an inhibitory one.
159    #[cfg(feature = "unstable-stdp")]
160    #[must_use]
161    pub fn max_weight(&self) -> i16 {
162        self.max_weight
163    }
164
165    /// Unstable: behind `unstable-stdp`.
166    /// The smallest weight `update_weight` leaves: 0 for an excitatory
167    /// synapse, -2000 for an inhibitory one.
168    #[cfg(feature = "unstable-stdp")]
169    #[must_use]
170    pub fn min_weight(&self) -> i16 {
171        self.min_weight
172    }
173
174    /// Unstable: behind `unstable-stdp`.
175    /// The signed sum of every delta `update_weight` was given since the
176    /// synapse was built or its network's last `reset`, before the clamp
177    /// (session G instrumentation, the mechanism-label evidence). Read
178    /// it per class (intra vs inter assemblies) to decide whether a bucket's
179    /// movement was pairing-driven or clamp/flip-machinery-driven.
180    #[cfg(feature = "unstable-stdp")]
181    #[must_use]
182    pub fn raw_stdp_delta(&self) -> i64 {
183        self.raw_stdp_delta
184    }
185
186    /// Unstable: behind `unstable-stdp`.
187    /// The part of those deltas the `[min_weight, max_weight]` clamp
188    /// absorbed: `Σ(delta − applied)`. When it is large beside
189    /// [`raw_stdp_delta`](Self::raw_stdp_delta), the bounds' asymmetry, not
190    /// the pairing, shaped the trajectory.
191    #[cfg(feature = "unstable-stdp")]
192    #[must_use]
193    pub fn absorbed_delta(&self) -> i64 {
194        self.absorbed_delta
195    }
196
197    /// Unstable: behind `unstable-stdp`.
198    /// Apply a plastic weight delta. Clamps to `[min_weight, max_weight]`.
199    /// Tracks the raw delta and the clamp-absorbed remainder (session G).
200    #[cfg(feature = "unstable-stdp")]
201    pub fn update_weight(&mut self, delta_weight: i16) {
202        let target = self
203            .weight
204            .saturating_add(delta_weight)
205            .clamp(self.min_weight, self.max_weight);
206        let applied = target - self.weight;
207        self.raw_stdp_delta += i64::from(delta_weight);
208        self.absorbed_delta += i64::from(delta_weight) - i64::from(applied);
209        self.weight = target;
210    }
211}
212
213/// Test-only visualization helper (was pub; zero callers anywhere —
214/// the R8 census deferral, ruled in the 2026-08-22 consolidation:
215/// relocated under cfg(test) and pinned, not kept as dead pub
216/// surface). It reads `max_weight`, which exists with `unstable-stdp`.
217#[cfg(all(test, feature = "unstable-stdp"))]
218impl Synapse {
219    /// Weight as a percentage of `max_weight`.
220    fn normalized_weight(&self) -> i16 {
221        let abs_max = self.max_weight.unsigned_abs();
222        if abs_max > 0 {
223            (i32::from(self.weight) * 100 / i32::from(abs_max)) as i16
224        } else {
225            0
226        }
227    }
228}
229
230/// The bounds (`max_weight`, `min_weight`) a weight's sign gives a
231/// synapse: excitatory from 0 up, inhibitory below.
232#[cfg(feature = "unstable-stdp")]
233fn bounds_by_sign(weight: i16) -> (i16, i16) {
234    if weight >= 0 {
235        (2000, 0) // AMPA
236    } else {
237        (0, -2000) // GABA
238    }
239}
240
241/// Unstable: behind `unstable-stdp`.
242/// Spike-Timing-Dependent Plasticity rule.
243///
244/// The audit flagged this as **the better STDP implementation** (vs `stdp_plasticity.rs`):
245/// a linear stand-in for the exponential decay, in fixed point (the factor is
246/// `1000 − |dt|·1000/tau`, clamped at 0), sign-correct (positive dt → LTD,
247/// negative dt → LTP).
248#[cfg(feature = "unstable-stdp")]
249#[derive(Debug, Clone)]
250pub struct STDPRule {
251    /// LTP time constant (μs) — pre-before-post window.
252    pub tau_plus_us: u32,
253    /// LTD time constant (μs) — post-before-pre window.
254    pub tau_minus_us: u32,
255    /// LTP amplitude (fixed-point, 1000 = 1.0).
256    pub a_plus: i16,
257    /// LTD amplitude (negative).
258    pub a_minus: i16,
259    /// Overall learning rate (fixed-point, 1000 = 1.0).
260    pub learning_rate: u16,
261}
262
263#[cfg(feature = "unstable-stdp")]
264impl STDPRule {
265    /// Default biological STDP: 20ms/20ms tau, asymmetric amplitudes (LTD slightly larger).
266    #[must_use]
267    pub fn new() -> Self {
268        Self {
269            tau_plus_us: 20_000,
270            tau_minus_us: 20_000,
271            a_plus: 50,
272            a_minus: -53, // Slightly larger |LTD| than LTP — asymmetry is biological
273            learning_rate: 100,
274        }
275    }
276
277    /// Compute the weight delta for a given spike-time difference.
278    ///
279    /// # Parameters
280    ///
281    /// - `dt_us = pre_spike_time - post_spike_time` (positive = post fired first → LTD).
282    ///
283    /// # Returns
284    ///
285    /// Weight delta (signed): non-negative for LTP, non-positive for LTD, zero outside the window.
286    ///
287    /// # Invariants
288    ///
289    /// - `dt > 0` → returns ≤ 0 (LTD)
290    /// - `dt < 0` → returns ≥ 0 (LTP)
291    /// - `|dt| ≥ tau` → returns 0 (the linear factor reaches 0)
292    ///
293    /// # Bug fix vs v0.1
294    ///
295    /// v0.1 used `factor = SCALE - decay` without clamping. When `|dt| > tau`,
296    /// `decay > SCALE` and `factor` goes negative, breaking the sign convention
297    /// (LTP returns negative, LTD returns positive). The property test
298    /// `prop_stdp_sign_convention` catches this at `dt = -24000`. Fix: clamp
299    /// `factor` to `≥ 0` — the linear exp approximation naturally floors at zero.
300    ///
301    /// # Bug fix (R18 rider, 2026-08-22)
302    ///
303    /// `dt_us.abs() * SCALE` overflowed i32 at `|dt|` > ~2.15 s (release:
304    /// silent wrap → spurious deltas far outside the window, e.g. −560 at
305    /// dt = ±2 200 000 μs where 0 is required; debug: panic) — and
306    /// `dt_us.abs()` itself is UB-adjacent at `i32::MIN`. The whole
307    /// expression now runs in i64, cast BEFORE the abs (total at
308    /// `i32::MIN`), which also covers the tail product
309    /// `a · factor · learning_rate` overflowing i32 at extreme
310    /// `learning_rate` (u16 max). Observable values identical everywhere
311    /// the old code didn't overflow.
312    #[must_use]
313    pub fn calculate_weight_change(&self, dt_us: i32) -> i16 {
314        if dt_us > 0 {
315            // Post fired before pre → LTD (depress the synapse).
316            let decay = (i64::from(dt_us).abs() * i64::from(SCALE)) / i64::from(self.tau_minus_us);
317            if decay < 10_000 {
318                let factor = (i64::from(SCALE) - decay).max(0); // Clamp to ≥ 0
319                ((i64::from(self.a_minus) * factor * i64::from(self.learning_rate))
320                    / (i64::from(SCALE) * i64::from(SCALE))) as i16
321            } else {
322                0
323            }
324        } else {
325            // Pre fired before post (or simultaneous) → LTP (potentiate).
326            let decay = (i64::from(dt_us).abs() * i64::from(SCALE)) / i64::from(self.tau_plus_us);
327            if decay < 10_000 {
328                let factor = (i64::from(SCALE) - decay).max(0); // Clamp to ≥ 0
329                ((i64::from(self.a_plus) * factor * i64::from(self.learning_rate))
330                    / (i64::from(SCALE) * i64::from(SCALE))) as i16
331            } else {
332                0
333            }
334        }
335    }
336}
337
338#[cfg(feature = "unstable-stdp")]
339impl Default for STDPRule {
340    fn default() -> Self {
341        Self::new()
342    }
343}
344
345#[cfg(test)]
346mod tests {
347    #![allow(clippy::shadow_unrelated)]
348    use super::*;
349    use proptest::prelude::*;
350
351    // ----- Unit tests -----
352
353    #[test]
354    fn new_excitatory_synapse_has_default_params() {
355        let s = Synapse::new(3, 7, 150).expect("valid ids");
356        assert_eq!(s.pre(), 3);
357        assert_eq!(s.post(), 7);
358        assert_eq!(s.weight(), 150);
359        #[cfg(feature = "unstable-stdp")]
360        {
361            assert_eq!(s.max_weight(), 2000); // AMPA
362            assert_eq!(s.min_weight(), 0);
363            assert_eq!((s.raw_stdp_delta(), s.absorbed_delta()), (0, 0));
364        }
365    }
366
367    #[test]
368    fn negative_weight_makes_inhibitory() {
369        let s = Synapse::new(3, 7, -150).expect("valid ids");
370        assert_eq!((s.pre(), s.post(), s.weight()), (3, 7, -150));
371        #[cfg(feature = "unstable-stdp")]
372        {
373            assert_eq!(s.max_weight(), 0); // GABA
374            assert_eq!(s.min_weight(), -2000);
375        }
376    }
377
378    /// The bounds follow the weight's sign alone, 0 counting as
379    /// excitatory, at both ends of `i16` and on each side of 0.
380    #[cfg(feature = "unstable-stdp")]
381    #[test]
382    fn the_bounds_follow_the_sign() {
383        for (weight, bounds) in [
384            (i16::MAX, (0, 2000)),
385            (1, (0, 2000)),
386            (0, (0, 2000)),
387            (-1, (-2000, 0)),
388            (i16::MIN, (-2000, 0)),
389        ] {
390            let s = Synapse::new(3, 7, weight).expect("valid ids");
391            assert_eq!((s.min_weight(), s.max_weight()), bounds, "weight {weight}");
392            assert_eq!(s.weight(), weight, "kept as given");
393        }
394    }
395
396    #[test]
397    fn self_connection_rejected() {
398        let err = Synapse::new(5, 5, 100).unwrap_err();
399        assert_eq!(err, Error::SelfConnection);
400    }
401
402    #[cfg(feature = "unstable-stdp")]
403    #[test]
404    fn normalized_weight_is_percentage_of_max() {
405        let mut s = Synapse::new(1, 2, 100).expect("valid ids");
406        assert_eq!(s.max_weight(), 2000);
407        // 100/2000 = 5%
408        assert_eq!(s.normalized_weight(), 5);
409        s.weight = s.max_weight;
410        assert_eq!(s.normalized_weight(), 100);
411        s.weight = -s.max_weight;
412        assert_eq!(s.normalized_weight(), -100);
413        s.max_weight = 0;
414        assert_eq!(s.normalized_weight(), 0, "zero max must not divide by zero");
415    }
416
417    #[cfg(feature = "unstable-stdp")]
418    #[test]
419    fn weight_clamped_at_bounds() {
420        let mut s = Synapse::new(1, 2, 100).expect("valid ids");
421        s.update_weight(10_000); // Way over max
422        assert_eq!(s.weight(), s.max_weight());
423        // 10,000 given, 1,900 applied: the clamp absorbed 8,100
424        assert_eq!((s.raw_stdp_delta(), s.absorbed_delta()), (10_000, 8_100));
425        s.update_weight(-10_000); // Way under min
426        assert_eq!(s.weight(), s.min_weight());
427        // -10,000 given, -2,000 applied: -8,000 more absorbed
428        assert_eq!((s.raw_stdp_delta(), s.absorbed_delta()), (0, 100));
429    }
430
431    // ----- STDP rule tests -----
432
433    #[cfg(feature = "unstable-stdp")]
434    #[test]
435    fn stdp_ltp_when_pre_before_post() {
436        // dt < 0 means pre fired before post → LTP (positive delta).
437        let rule = STDPRule::new();
438        let dt_us: i32 = -5_000; // Pre 5ms before post
439        let delta = rule.calculate_weight_change(dt_us);
440        assert!(
441            delta >= 0,
442            "pre-before-post must produce LTP (>=0), got {delta}"
443        );
444    }
445
446    #[cfg(feature = "unstable-stdp")]
447    #[test]
448    fn stdp_ltd_when_post_before_pre() {
449        // dt > 0 means post fired before pre → LTD (negative delta).
450        let rule = STDPRule::new();
451        let dt_us: i32 = 5_000;
452        let delta = rule.calculate_weight_change(dt_us);
453        assert!(
454            delta <= 0,
455            "post-before-pre must produce LTD (<=0), got {delta}"
456        );
457    }
458
459    #[cfg(feature = "unstable-stdp")]
460    #[test]
461    fn stdp_zero_outside_window() {
462        let rule = STDPRule::new();
463        // 10× tau_plus = 200_000 μs → outside window
464        let far_dt: i32 = -200_000;
465        assert_eq!(rule.calculate_weight_change(far_dt), 0);
466        let far_dt_pos: i32 = 200_000;
467        assert_eq!(rule.calculate_weight_change(far_dt_pos), 0);
468    }
469
470    #[cfg(feature = "unstable-stdp")]
471    #[test]
472    fn stdp_zero_at_zero_dt() {
473        // dt = 0 → simultaneous; LTP branch with decay = 0 → factor = SCALE → a_plus · lr.
474        let rule = STDPRule::new();
475        let delta = rule.calculate_weight_change(0);
476        let expected =
477            (i32::from(rule.a_plus) * SCALE * i32::from(rule.learning_rate)) / (SCALE * SCALE);
478        assert_eq!(delta, expected as i16);
479    }
480
481    #[cfg(feature = "unstable-stdp")]
482    #[test]
483    fn stdp_decay_monotonic_with_abs_dt() {
484        // Larger |dt| → smaller |delta| (within window).
485        let rule = STDPRule::new();
486        let small = rule.calculate_weight_change(-1_000).abs();
487        let large = rule.calculate_weight_change(-10_000).abs();
488        assert!(
489            large <= small,
490            "|delta| must decay with |dt|: small={small}, large={large}"
491        );
492    }
493
494    // ----- R18 rider: the i32 dt-overflow fix, pinned -----
495
496    #[cfg(feature = "unstable-stdp")]
497    #[test]
498    fn stdp_zero_just_past_the_old_overflow_boundary() {
499        // dt = ±2_200_000 μs: past 10·tau (200 ms) AND past the old
500        // i32 product boundary (~2.147 s), where the wrapped decay
501        // produced −560 instead of 0. Exact pins, both branches.
502        let rule = STDPRule::new();
503        assert_eq!(rule.calculate_weight_change(2_200_000), 0, "LTD branch");
504        assert_eq!(rule.calculate_weight_change(-2_200_000), 0, "LTP branch");
505        // The extremes: cast-before-abs must be total at i32::MIN
506        // (`.abs()` on i32::MIN panics in debug, wraps in release).
507        assert_eq!(rule.calculate_weight_change(i32::MAX), 0);
508        assert_eq!(rule.calculate_weight_change(i32::MIN), 0);
509    }
510
511    #[cfg(feature = "unstable-stdp")]
512    #[test]
513    fn stdp_extreme_learning_rate_does_not_overflow_the_product() {
514        // The subsumed tail edge: a · factor · learning_rate in i32
515        // overflows at learning_rate = u16::MAX (53 · 1000 · 65535 ≈
516        // 3.5e9 > i32::MAX). The i64 expression must carry it.
517        let mut rule = STDPRule::new();
518        rule.learning_rate = u16::MAX;
519        // dt = 0 → factor = SCALE exactly (the maximal product).
520        let delta = rule.calculate_weight_change(0);
521        let expected = (i64::from(rule.a_plus) * i64::from(SCALE) * i64::from(u16::MAX))
522            / (i64::from(SCALE) * i64::from(SCALE));
523        assert_eq!(
524            i64::from(delta),
525            expected,
526            "no wrap at lr = u16::MAX, dt = 0"
527        );
528    }
529
530    // ----- Property tests (Cardano-grade rigor) -----
531
532    proptest! {
533        /// Self-connection always rejected, regardless of weight.
534        #[test]
535        fn prop_self_connection_always_rejected(id in 0u16..=1000, weight in -3000i16..=3000) {
536            let result = Synapse::new(id, id, weight);
537            prop_assert_eq!(result.err(), Some(Error::SelfConnection));
538        }
539
540        /// Weight stays within `[min_weight, max_weight]` after any update,
541        /// for every synapse `new` builds: a caller cannot write the
542        /// bounds, so the clamp never meets a minimum above the maximum.
543        #[cfg(feature = "unstable-stdp")]
544        #[test]
545        fn prop_weight_clamped(weight in any::<i16>(), delta in any::<i16>()) {
546            let mut s = Synapse::new(1, 2, weight).expect("valid ids");
547            prop_assert!(s.min_weight() <= s.max_weight());
548            s.update_weight(delta);
549            prop_assert!(s.weight() >= s.min_weight());
550            prop_assert!(s.weight() <= s.max_weight());
551        }
552
553        /// STDP sign convention holds across random dt.
554        #[cfg(feature = "unstable-stdp")]
555        #[test]
556        fn prop_stdp_sign_convention(dt_us in -200_000i32..=200_000) {
557            let rule = STDPRule::new();
558            let delta = rule.calculate_weight_change(dt_us);
559            if dt_us > 0 {
560                prop_assert!(delta <= 0, "post-before-pre must produce LTD");
561            } else if dt_us < 0 {
562                prop_assert!(delta >= 0, "pre-before-post must produce LTP");
563            }
564            // dt == 0 → LTP branch (>= 0), tested separately.
565        }
566
567        /// STDP decays to zero outside 10× tau window.
568        #[cfg(feature = "unstable-stdp")]
569        #[test]
570        fn prop_stdp_zero_outside_window(multiplier in 11u32..=100) {
571            let rule = STDPRule::new();
572            let far_dt_pos = (rule.tau_minus_us * multiplier) as i32;
573            let far_dt_neg = -((rule.tau_plus_us * multiplier) as i32);
574            prop_assert_eq!(rule.calculate_weight_change(far_dt_pos), 0);
575            prop_assert_eq!(rule.calculate_weight_change(far_dt_neg), 0);
576        }
577
578        /// R18 rider: across the FULL i32 dt range — beyond the 10·tau
579        /// window the delta is exactly 0 (no wrap artifacts at any
580        /// magnitude, either sign), and inside the window the sign
581        /// convention holds. The old i32 product wrapped at |dt| >
582        /// ~2.15 s, producing spurious in-window-looking deltas.
583        #[cfg(feature = "unstable-stdp")]
584        #[test]
585        fn prop_stdp_dt_full_i32_range(dt_us in i32::MIN..=i32::MAX) {
586            let rule = STDPRule::new();
587            let delta = rule.calculate_weight_change(dt_us);
588            let outside =
589                i64::from(dt_us).abs() >= 10 * i64::from(rule.tau_plus_us.max(rule.tau_minus_us));
590            if outside {
591                prop_assert_eq!(delta, 0, "outside the window at dt={}", dt_us);
592            } else if dt_us > 0 {
593                prop_assert!(delta <= 0, "in-window post-before-pre must be LTD at dt={}", dt_us);
594            } else {
595                prop_assert!(delta >= 0, "in-window pre-before-post must be LTP at dt={}", dt_us);
596            }
597        }
598    }
599
600    // ----- ISA round 70: a test for the synapse sentence no test held at
601    // 645afa8, where a mutation pass left three survivors; run green there
602    // and red under each. -----
603
604    /// `STDPRule::new` is the rule its doc and the crate README name: 20 ms
605    /// and 20 ms, a₊ 50, a₋ −53, learning rate 100. `stdp_zero_at_zero_dt`
606    /// reads `a_plus` from the rule itself, so it cannot see the number.
607    #[cfg(feature = "unstable-stdp")]
608    #[test]
609    fn the_default_rule_is_the_one_its_doc_names() {
610        let r = STDPRule::new();
611        assert_eq!(
612            (
613                r.tau_plus_us,
614                r.tau_minus_us,
615                r.a_plus,
616                r.a_minus,
617                r.learning_rate
618            ),
619            (20_000, 20_000, 50, -53, 100)
620        );
621    }
622}