gresil 0.1.0-alpha.9

Spiking neural networks in no_std Rust, i16 fixed point, for microcontrollers
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
// SPDX-FileCopyrightText: 2026 philo-the-dendron
// SPDX-License-Identifier: AGPL-3.0-or-later
//! A network of fixed size: `N` neurons and `S` synapses in arrays, no
//! heap, no plasticity, the std step's order verbatim.
//!
//! [`FixedNetwork::step`] is `SpikingNeuralNetwork::step` without the
//! plasticity passes and the stats, in the same order:
//! the adaptation decay of every neuron; integrate-and-fire, which reads
//! the pulses the previous step delivered; the clear; then the pulses of
//! this step's spikes, in the synapse array's order. The step has no
//! `Result`, no index and no division of its own; the neuron it calls
//! divides only by a constant or a `NonZero`. An id past the arrays is no
//! spike and no target.
//!
//! On the host, `FixedNetwork::try_from(&net)` converts a plasticity-off
//! `SpikingNeuralNetwork` of the same size, and the two step alike, bit
//! for bit: the tests below pin it
//! on the network of `chain-3` (`tests/traces/cases.rs`), and
//! `tests/traces.rs` on every plasticity-off trace.
//!
//! A frozen network's rows go through [`trace::row`](crate::trace::row),
//! the one writer of a `neuralos-trace v1` row: the trace tests on the
//! host, the ESP32-C3 firmware and the QEMU replay. `freeze` (`std`,
//! behind `unstable-freeze`) writes the arrays themselves as Rust source.
//!
//! # `no_std`
//!
//! No allocator, no dependency. `FixedSynapse::from_network`, the
//! conversion and `freeze` read a `SpikingNeuralNetwork` or write a
//! `String`, so they are `std`.

use crate::lif_neuron::LIFNeuron;
#[cfg(feature = "std")]
use crate::network::SpikingNeuralNetwork;
#[cfg(feature = "std")]
use crate::{Error, Result};

#[cfg(all(feature = "std", feature = "unstable-freeze"))]
pub mod freeze;

/// One synapse of a [`FixedNetwork`]: a spike of `pre` adds `pulse_pa` to
/// the synaptic current of `post`, which `post`'s next step integrates.
///
/// Six bytes, `Copy`. The pulse is the std network's per-spike
/// `weight / synaptic_input_divisor`, computed once, when the synapse is
/// made (`from_network`).
///
/// The three fields are public on purpose: every value is legal (a `pre`
/// or `post` past the arrays delivers nothing), so no field guards a rule.
/// Not exhaustive: a field may come in a minor release, so outside this
/// crate a synapse is built by [`new`](Self::new).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct FixedSynapse {
    /// Presynaptic neuron id: its spike sends the pulse.
    pub pre: u16,
    /// Postsynaptic neuron id: its synaptic current takes the pulse.
    pub post: u16,
    /// The pulse, pA.
    pub pulse_pa: i16,
}

#[cfg(feature = "std")]
impl FixedSynapse {
    /// The synapses of `net` by `pre`, ascending, and within one `pre` in
    /// the order they were added: a stable sort of
    /// [`SpikingNeuralNetwork::synapses`] by `pre`, the order `net`'s own
    /// step delivers them in, from the CSR it sorts first when a synapse
    /// came in since the last sort ([`SpikingNeuralNetwork::step`]).
    ///
    /// Each pulse is the std step's own expression, `weight / divisor as
    /// i16`, exact for every divisor the setter takes, 1 to 32,767.
    #[must_use]
    // `divisor as i16` is the std step's expression, verbatim (doc above).
    #[allow(clippy::cast_possible_wrap)]
    pub fn from_network(net: &SpikingNeuralNetwork) -> Vec<Self> {
        let divisor = net.synaptic_input_divisor() as i16;
        let mut synapses: Vec<Self> = net
            .synapses()
            .iter()
            .map(|s| Self {
                pre: s.pre_neuron_id,
                post: s.post_neuron_id,
                pulse_pa: s.weight / divisor,
            })
            .collect();
        // Stable: synapses of one `pre` keep the order they were added in.
        synapses.sort_by_key(|s| s.pre);
        synapses
    }
}

/// `N` neurons and `S` synapses in arrays: a network with no heap and no
/// plasticity (module doc).
///
/// Built by [`new`](Self::new) from any arrays, or on the host by
/// `FixedNetwork::try_from(&net)` from a plasticity-off
/// `SpikingNeuralNetwork` of the same size: what that conversion refuses
/// is its § Errors.
#[derive(Debug, Clone)]
pub struct FixedNetwork<const N: usize, const S: usize> {
    neurons: [LIFNeuron; N],
    synapses: [FixedSynapse; S],
    dt_us: u32,
    time_us: u64,
}

impl<const N: usize, const S: usize> FixedNetwork<N, S> {
    /// A network of these neurons and synapses, stepping `dt_us`, at time
    /// 0.
    ///
    /// Total: any arrays are a network. A synapse whose `pre` or `post` is
    /// not below `N` delivers nothing, and the array order is the delivery
    /// order ([`synapses`](Self::synapses)).
    #[must_use]
    pub const fn new(neurons: [LIFNeuron; N], synapses: [FixedSynapse; S], dt_us: u32) -> Self {
        Self {
            neurons,
            synapses,
            dt_us,
            time_us: 0,
        }
    }

    /// Advance by one `dt_us`, in the std step's order without plasticity:
    /// decay every neuron's adaptation current; integrate each with
    /// `input[i]` at this step's time, writing `fired[i]`; clear every
    /// synaptic current; deliver each synapse whose `pre` fired, in array
    /// order; advance the time by `dt_us`. The clock is a `u64`, saturating at
    /// `u64::MAX` (about 585,000 years of model time: no run reaches it); the
    /// neurons are handed its low 32 bits, which wrap at 2^32 μs (71.6 min)
    /// without changing a spike (`the_clock_runs_past_the_u32_ceiling`).
    ///
    /// A pulse is read by the next step's integration: the one-step
    /// synaptic delay of the std network. A spike at step t reaches `post`
    /// at step t + 1. A `post` that is refractory at step t + 1 integrates
    /// nothing, and the clear drops the pulse: it is lost, not deferred.
    ///
    /// ```
    /// use gresil::{FixedNetwork, FixedSynapse, LIFNeuron, NeuronType, VoltageResolution};
    ///
    /// let quiet = |id| LIFNeuron::new(id, NeuronType::Excitatory, VoltageResolution::Millivolt);
    /// let synapse = [FixedSynapse::new(0, 1, 400)];
    /// let mut fired = [false; 2];
    ///
    /// // `pre` fires at step 0 (3,000 pA: +15 mV, onto the threshold).
    /// let mut net = FixedNetwork::new([quiet(0), quiet(1)], synapse, 1_000);
    /// net.step(&[3_000, 0], &mut fired);
    /// assert_eq!(fired, [true, false]);
    /// assert_eq!(net.neurons()[1].membrane_potential(), -70); // not yet
    /// net.step(&[0, 0], &mut fired);
    /// assert_eq!(net.neurons()[1].membrane_potential(), -68); // one step later
    ///
    /// // The same, `post` firing at step 0 too: refractory through step 2.
    /// let mut net = FixedNetwork::new([quiet(0), quiet(1)], synapse, 1_000);
    /// net.step(&[3_000, 3_000], &mut fired);
    /// assert_eq!(fired, [true, true]);
    /// assert_eq!(net.neurons()[1].synaptic_current_pa(), 400); // delivered
    /// net.step(&[0, 0], &mut fired); // not read, then cleared
    /// assert_eq!(net.neurons()[1].synaptic_current_pa(), 0);
    /// net.step(&[0, 0], &mut fired); // the period's last silent step
    /// assert_eq!(net.neurons()[1].refractory_remaining_us(), 0);
    /// net.step(&[0, 0], &mut fired); // integrates, and nothing is left:
    /// assert_eq!(net.neurons()[1].membrane_potential(), -80); // read, -78
    /// ```
    pub fn step(&mut self, input: &[i16; N], fired: &mut [bool; N]) {
        for n in &mut self.neurons {
            n.decay_adaptation_current();
        }
        // The neurons keep the low 32 bits of the clock
        // (`LIFNeuron::integrate_and_fire` § Semantics item 1).
        #[allow(clippy::cast_possible_truncation)]
        let now_us = self.time_us as u32;
        for ((n, &current_pa), spiked) in self.neurons.iter_mut().zip(input).zip(fired.iter_mut()) {
            *spiked = n.integrate_and_fire(current_pa, self.dt_us, now_us);
        }
        for n in &mut self.neurons {
            n.clear_synaptic_current();
        }
        for s in &self.synapses {
            if fired.get(usize::from(s.pre)) == Some(&true) {
                if let Some(post) = self.neurons.get_mut(usize::from(s.post)) {
                    post.add_synaptic_current(s.pulse_pa);
                }
            }
        }
        self.time_us = self.time_us.saturating_add(u64::from(self.dt_us));
    }

    /// The neurons, by id.
    #[must_use]
    pub const fn neurons(&self) -> &[LIFNeuron; N] {
        &self.neurons
    }

    /// The synapses, in delivery order.
    ///
    /// From `FixedSynapse::from_network` this is the CSR order: by `pre`,
    /// ascending, stable within one `pre`. It must stay so for this network
    /// and the std one to agree: the std step visits its firing neurons in
    /// ascending id order, and saturating adds are order-dependent (from 0,
    /// +30,000 twice then −30,000 ends at 2,767; −30,000 first ends at
    /// 30,000). The step itself delivers in whatever order the array holds.
    #[must_use]
    pub const fn synapses(&self) -> &[FixedSynapse; S] {
        &self.synapses
    }

    /// The simulation step, μs.
    #[must_use]
    pub const fn dt_us(&self) -> u32 {
        self.dt_us
    }

    /// The time of the next step, μs, a `u64`: the timestamp its integration
    /// and its spikes carry (the neurons are handed its low 32 bits). Starts
    /// at 0 from [`new`](Self::new), at the network's current time from
    /// `try_from`.
    #[must_use]
    pub const fn time_us(&self) -> u64 {
        self.time_us
    }
}

#[cfg(feature = "std")]
impl<const N: usize, const S: usize> TryFrom<&SpikingNeuralNetwork> for FixedNetwork<N, S> {
    type Error = Error;

    /// `net` as it stands: its neurons cloned into the array, its synapses
    /// by [`FixedSynapse::from_network`], its time step and its current
    /// time.
    ///
    /// # Errors
    ///
    /// [`Error::PlasticityEnabled`] when `net` has plasticity enabled (a
    /// fixed network has none); [`Error::NeuronCountMismatch`] when it has
    /// not exactly `N` neurons, and [`Error::SynapseCountMismatch`] when it
    /// has not exactly `S` synapses.
    ///
    /// A network starts with plasticity off, and only a build with the
    /// `unstable-stdp` feature can turn it on: without the feature the
    /// first refusal is never met.
    fn try_from(net: &SpikingNeuralNetwork) -> Result<Self> {
        if net.plasticity_enabled() {
            return Err(Error::PlasticityEnabled);
        }
        if usize::from(net.neuron_count()) != N {
            return Err(Error::NeuronCountMismatch);
        }
        if usize::try_from(net.synapse_count()) != Ok(S) {
            return Err(Error::SynapseCountMismatch);
        }
        // The two counts again, as the arrays take them. The neurons'
        // cannot differ: a network holds at most 65,535, so `neuron_count`
        // is exact. The synapses' differs only past 2^32, where
        // `synapse_count`'s `u32` wraps.
        let neurons: [LIFNeuron; N] = net
            .neurons()
            .to_vec()
            .try_into()
            .map_err(|_| Error::NeuronCountMismatch)?;
        let synapses: [FixedSynapse; S] = FixedSynapse::from_network(net)
            .try_into()
            .map_err(|_| Error::SynapseCountMismatch)?;
        Ok(Self {
            neurons,
            synapses,
            dt_us: net.dt_us(),
            time_us: net.time_us(),
        })
    }
}

// After the last `impl` of this module, and not before one: a v0 symbol
// carries its `impl` block's index in its module, so a block inserted
// earlier renumbers the blocks after it and relays the firmware's
// `.text` with no code change (measured, ISA round 43).
impl FixedSynapse {
    /// A synapse from its three values: a spike of `pre` adds `pulse_pa`
    /// to the synaptic current of `post`.
    ///
    /// `const`, and not `std`: a frozen network's synapse array is a
    /// `const` of these calls, written by `freeze::module` and
    /// compiled outside this crate — by the firmware, which has no
    /// `std`. The call is positional with the two ids side by side, so
    /// which is which is pinned by a test, not by the types: the frozen
    /// cases' synapse line in `tests/traces.rs`.
    ///
    /// ```
    /// use gresil::FixedSynapse;
    ///
    /// let s = FixedSynapse::new(0, 1, 400);
    /// assert_eq!((s.pre, s.post, s.pulse_pa), (0, 1, 400));
    /// ```
    #[must_use]
    pub const fn new(pre: u16, post: u16, pulse_pa: i16) -> Self {
        Self {
            pre,
            post,
            pulse_pa,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    #[cfg(feature = "std")]
    use crate::csr::SparseSynapseMatrix;
    #[cfg(feature = "std")]
    use crate::lif_neuron::{NeuronType, VoltageResolution};

    /// An excitatory neuron on the mV grid, no noise.
    fn quiet(id: u16) -> LIFNeuron {
        let mut n = LIFNeuron::new(id, NeuronType::Excitatory, VoltageResolution::Millivolt);
        n.noise_amplitude_pa = 0;
        n
    }

    /// Every field a step writes.
    #[cfg(feature = "std")]
    fn state(n: &LIFNeuron) -> (i16, u32, u32, u32, i16, i16) {
        (
            n.membrane_potential,
            n.refractory_remaining_us,
            n.last_update_time_us,
            n.last_spike_time_us,
            n.synaptic_current_pa,
            n.adaptation_current_pa,
        )
    }

    #[test]
    fn a_synapse_is_six_bytes() {
        assert_eq!(core::mem::size_of::<FixedSynapse>(), 6);
    }

    /// The clock runs past 2^32 μs, where it used to saturate, and the
    /// neurons are handed its low 32 bits, all 32 of them.
    #[test]
    fn the_clock_runs_past_the_u32_ceiling() {
        let mut net = FixedNetwork::new([quiet(0)], [], 1_000);
        net.time_us = u64::from(u32::MAX) - 400;
        let mut fired = [false];
        net.step(&[0], &mut fired);
        assert_eq!(net.time_us(), u64::from(u32::MAX) + 600);
        // The first step ran at 2^32 - 401: its stamp keeps bit 31.
        assert_eq!(net.neurons()[0].last_update_time_us, u32::MAX - 400);
        net.step(&[0], &mut fired);
        assert_eq!(net.time_us(), u64::from(u32::MAX) + 1_600);
        // The second step ran at 2^32 + 599: the neuron's stamp is 599.
        assert_eq!(net.neurons()[0].last_update_time_us, 599);
    }

    /// Past 2^32 μs a noisy network does what the same network does 2^32 μs
    /// earlier: the neurons see the clock's low 32 bits and the noise reads
    /// only the seed's low 12, so the wrap is invisible to the spikes. At the
    /// threshold current the noise decides each spike, so the fold would move.
    #[cfg(feature = "std")]
    #[test]
    fn a_clock_past_the_u32_boundary_gives_the_same_noise() {
        let noisy = |id: u16| {
            let mut n = LIFNeuron::new(
                id,
                NeuronType::Excitatory,
                VoltageResolution::CentiMillivolt,
            );
            n.noise_amplitude_pa = 5;
            n
        };
        let run = |start_us: u64| {
            let mut net = FixedNetwork::new([noisy(0), noisy(1), noisy(2), noisy(3)], [], 1_000);
            net.time_us = start_us;
            let mut fired = [false; 4];
            let mut fold = 0u32;
            for step in 0..2_000u32 {
                net.step(&[150; 4], &mut fired);
                for (id, &f) in (0u32..).zip(fired.iter()) {
                    if f {
                        fold = fold
                            .wrapping_mul(31)
                            .wrapping_add(step)
                            .wrapping_mul(31)
                            .wrapping_add(id);
                    }
                }
            }
            fold
        };
        let before = run(1_234_000);
        assert_ne!(before, 0, "the run fires, or the test shows nothing");
        assert_eq!(run(1_234_000 + (1 << 32)), before);
    }

    /// Saturating adds do not commute, so the array order is the delivery
    /// order, sorted or not. Neurons 1 and 2 fire at step 0 on 3,000 pA
    /// (+15 mV, from rest to the −55 mV threshold) and pulse neuron 0,
    /// which is quiet: −30,000, then +30,000 twice, ends at 30,000. By
    /// `pre`, the two +30,000 would come first, saturate at 32,767, and end
    /// at 2,767.
    #[test]
    fn an_unsorted_array_delivers_in_array_order() {
        let mut net = FixedNetwork::new(
            [quiet(0), quiet(1), quiet(2)],
            [
                FixedSynapse {
                    pre: 2,
                    post: 0,
                    pulse_pa: -30_000,
                },
                FixedSynapse {
                    pre: 1,
                    post: 0,
                    pulse_pa: 30_000,
                },
                FixedSynapse {
                    pre: 1,
                    post: 0,
                    pulse_pa: 30_000,
                },
            ],
            1_000,
        );
        let mut fired = [false; 3];
        net.step(&[0, 3_000, 3_000], &mut fired);
        assert_eq!(fired, [false, true, true]);
        assert_eq!(net.neurons()[0].synaptic_current_pa, 30_000);
    }

    /// Total: an id past the arrays is no spike and no target, and the step
    /// goes on.
    #[test]
    fn an_id_past_the_arrays_is_no_spike_and_no_target() {
        let mut net = FixedNetwork::new(
            [quiet(0), quiet(1)],
            [
                FixedSynapse {
                    pre: 0,
                    post: 9,
                    pulse_pa: 500,
                },
                FixedSynapse {
                    pre: 7,
                    post: 1,
                    pulse_pa: 500,
                },
            ],
            1_000,
        );
        let mut fired = [false; 2];
        net.step(&[3_000, 0], &mut fired);
        assert_eq!(fired, [true, false]);
        assert_eq!(net.neurons()[1].synaptic_current_pa, 0);
        assert_eq!(net.time_us(), 1_000);
    }

    /// The network of `chain-3` (`tests/traces/cases.rs`) without its
    /// edges: three excitatory neurons, centi-mV, no noise, divisor 1.
    #[cfg(feature = "std")]
    fn chain_3() -> SpikingNeuralNetwork {
        let neurons = (0..3)
            .map(|id| {
                let mut n = LIFNeuron::new(
                    id,
                    NeuronType::Excitatory,
                    VoltageResolution::CentiMillivolt,
                );
                n.noise_amplitude_pa = 0;
                n
            })
            .collect();
        let mut net =
            SpikingNeuralNetwork::from_neurons(neurons, 1_000).expect("three neurons, 1 ms");
        net.set_synaptic_input_divisor(1).expect("in 1 to 32,767");
        net
    }

    /// The two networks side by side for 100 steps, neuron 0 driven at 600
    /// pA: every spike, every field a step writes, and the time, at each
    /// step. Returns how many times each neuron fired.
    #[cfg(feature = "std")]
    #[must_use]
    fn steps_alike(net: &mut SpikingNeuralNetwork, fixed: &mut FixedNetwork<3, 2>) -> [u32; 3] {
        let mut spiked = [false; 3];
        let mut counts = [0u32; 3];
        for step in 0..100 {
            let want: Vec<u16> = net
                .step(&[600, 0, 0])
                .expect("a built network steps")
                .iter()
                .map(|s| s.neuron_id)
                .collect();
            fixed.step(&[600, 0, 0], &mut spiked);
            let got: Vec<u16> = (0..3u16).filter(|&id| spiked[usize::from(id)]).collect();
            assert_eq!(got, want, "step {step}: the spikes");
            for (f, s) in fixed.neurons().iter().zip(net.neurons()) {
                assert_eq!(state(f), state(s), "step {step}: neuron {}", s.id);
            }
            assert_eq!(fixed.time_us(), net.time_us(), "step {step}: the time");
            for &id in &got {
                counts[usize::from(id)] += 1;
            }
        }
        counts
    }

    /// The fixed step against the std step on the network of `chain-3`
    /// (`tests/traces/cases.rs`): three excitatory neurons in a line,
    /// centi-mV, no noise, 5,000-weight edges at divisor 1, neuron 0 driven
    /// at 600 pA. Every spike and every field a step writes, at each of the
    /// 100 steps, and all three neurons fire.
    #[cfg(feature = "std")]
    #[test]
    fn the_step_is_the_std_step_on_chain_3() {
        let mut net = chain_3();
        net.add_synapse(0, 1, 5_000).expect("ids in range");
        net.add_synapse(1, 2, 5_000).expect("ids in range");
        net.finalize_synapses();
        let mut fixed =
            FixedNetwork::<3, 2>::try_from(&net).expect("plasticity off, 3 neurons, 2 synapses");

        let counts = steps_alike(&mut net, &mut fixed);
        assert!(
            counts.iter().all(|&n| n > 0),
            "all three fire, 1 and 2 through the chain: {counts:?}"
        );
    }

    /// `try_from` converts a network whose edges were added out of `pre`
    /// order and never sorted, and the two step alike: the std network's
    /// first step sorts its CSR into the order `from_network` lists. The
    /// same chain-3, its two edges added `1→2` then `0→1`. Before round 64
    /// that std step read slot 0 for neuron 0, which held the `1→2` edge,
    /// and `try_from` refused the network.
    #[cfg(feature = "std")]
    #[test]
    fn try_from_converts_edges_added_out_of_pre_order() {
        let mut net = chain_3();
        net.add_synapse(1, 2, 5_000).expect("ids in range");
        net.add_synapse(0, 1, 5_000).expect("ids in range");
        let mut fixed =
            FixedNetwork::<3, 2>::try_from(&net).expect("never sorted: 3 neurons, 2 synapses");
        let counts = steps_alike(&mut net, &mut fixed);
        assert!(
            counts.iter().all(|&n| n > 0),
            "all three fire, 1 and 2 through the chain: {counts:?}"
        );
    }

    /// `from_network`'s order is the CSR's. Edges added out of `pre` order,
    /// two sharing pre 2 and two sharing pre 0, pre 0's added out of `post`
    /// order (0→2 before 0→1), and a divisor that truncates (3): a
    /// `SparseSynapseMatrix` built from the same edges and finalized lists,
    /// pre by pre, the same synapses in the same order. Within one `pre`
    /// that is the order they were added, not the `post` order, so a sort
    /// by `(pre, post)` fails here.
    #[cfg(feature = "std")]
    #[test]
    fn from_network_is_the_csr_order() {
        let edges: [(u16, u16, i16); 5] = [
            (2, 0, -125),
            (0, 2, 7),
            (2, 3, -250),
            (1, 3, 40),
            (0, 1, 125),
        ];
        let mut net = SpikingNeuralNetwork::from_neurons(
            (0..4)
                .map(|id| LIFNeuron::new(id, NeuronType::Excitatory, VoltageResolution::Millivolt))
                .collect(),
            1_000,
        )
        .expect("four neurons, 1 ms");
        for &(pre, post, weight) in &edges {
            net.add_synapse(pre, post, weight)
                .expect("ids in range, no self edge");
        }
        net.finalize_synapses();
        net.set_synaptic_input_divisor(3).expect("in 1 to 32,767");
        assert!(
            !net.synapses()
                .windows(2)
                .all(|w| w[0].pre_neuron_id <= w[1].pre_neuron_id),
            "the edges were added out of pre order, or the test proves nothing"
        );

        let mut csr = SparseSynapseMatrix::new(4, edges.len());
        for (i, &(pre, post, weight)) in edges.iter().enumerate() {
            csr.add(pre, post, weight, i);
        }
        csr.finalize();
        let want: Vec<FixedSynapse> = (0..4)
            .flat_map(|pre| {
                csr.connections(pre)
                    .map(move |(post, weight, _)| FixedSynapse {
                        pre,
                        post,
                        pulse_pa: weight / 3,
                    })
            })
            .collect();
        assert_eq!(FixedSynapse::from_network(&net), want);
        let pre_0: Vec<u16> = FixedSynapse::from_network(&net)
            .iter()
            .filter(|s| s.pre == 0)
            .map(|s| s.post)
            .collect();
        assert_eq!(
            pre_0,
            [2, 1],
            "pre 0's synapses in the order added, not by post"
        );
    }

    /// At the largest divisor, 32,767, every weight divides in `i16`:
    /// `i16::MIN` gives −1 and `i16::MAX` 1, where 65,535 overflowed on
    /// `i16::MIN` here, at construction.
    #[cfg(feature = "std")]
    #[test]
    fn from_network_divides_at_the_largest_divisor() {
        let mut net = SpikingNeuralNetwork::from_neurons(
            (0..3)
                .map(|id| LIFNeuron::new(id, NeuronType::Excitatory, VoltageResolution::Millivolt))
                .collect(),
            1_000,
        )
        .expect("three neurons, 1 ms");
        net.add_synapse(0, 1, i16::MIN).expect("ids in range");
        net.add_synapse(1, 2, i16::MAX).expect("ids in range");
        net.finalize_synapses();
        net.set_synaptic_input_divisor(32_767)
            .expect("the largest divisor");
        let pulses: Vec<i16> = FixedSynapse::from_network(&net)
            .iter()
            .map(|s| s.pulse_pa)
            .collect();
        assert_eq!(pulses, [-1, 1]);
    }

    /// `try_from` refuses what a fixed network cannot hold, and carries the
    /// time step and the current time of what it can.
    #[cfg(feature = "std")]
    #[test]
    fn try_from_refuses_plasticity_and_other_sizes() {
        let mut net = SpikingNeuralNetwork::from_neurons(
            (0..3)
                .map(|id| LIFNeuron::new(id, NeuronType::Excitatory, VoltageResolution::Millivolt))
                .collect(),
            1_000,
        )
        .expect("three neurons, 1 ms");
        net.add_synapse(0, 1, 100).expect("ids in range");
        net.add_synapse(1, 2, 100).expect("ids in range");
        net.finalize_synapses();
        #[cfg(feature = "unstable-stdp")]
        {
            net.set_plasticity_enabled(true);
            assert_eq!(
                FixedNetwork::<3, 2>::try_from(&net).err(),
                Some(Error::PlasticityEnabled),
                "plasticity on"
            );
            net.set_plasticity_enabled(false);
        }
        assert_eq!(
            FixedNetwork::<4, 2>::try_from(&net).err(),
            Some(Error::NeuronCountMismatch),
            "four neurons"
        );
        assert_eq!(
            FixedNetwork::<3, 1>::try_from(&net).err(),
            Some(Error::SynapseCountMismatch),
            "one synapse"
        );
        for _ in 0..5 {
            net.step(&[0, 0, 0]).expect("a built network steps");
        }
        let fixed = FixedNetwork::<3, 2>::try_from(&net).expect("plasticity off, 3 and 2");
        assert_eq!((fixed.dt_us(), fixed.time_us()), (1_000, 5_000));
    }

    // ----- ISA round 70: a test for the fixed network's sentence no test
    // held at 645afa8; run green there and red under a mutant that wraps
    // the clock instead of saturating it. -----

    /// The clock saturates at `u64::MAX`, as `step`'s doc says: a step
    /// from 400 μs below it ends there, and the next leaves it there.
    #[test]
    fn the_clock_saturates_at_u64_max() {
        let mut net = FixedNetwork::new([quiet(0)], [], 1_000);
        net.time_us = u64::MAX - 400;
        let mut fired = [false];
        net.step(&[0], &mut fired);
        assert_eq!(net.time_us(), u64::MAX);
        net.step(&[0], &mut fired);
        assert_eq!(net.time_us(), u64::MAX);
    }
}