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
699
// SPDX-FileCopyrightText: 2026 philo-the-dendron
// SPDX-License-Identifier: AGPL-3.0-or-later
//! The constructors' rules, case by case: each case is run here against
//! the rule the docs state, written in this file apart from the library.
//! A case a rule refuses is refused under that rule's name; every other
//! case builds, and a topology case's network runs 25 steps; no case
//! panics. When a case breaks two rules either name will do: the library
//! promises no order between them.
//!
//! Part of the test gate (`cargo test --workspace`); alone,
//! `cargo test -p gresil --test constructors`.

use gresil::trace::{self, Kind, Rows};
use gresil::{
    Error, FixedNetwork, FixedSynapse, LIFNeuron, NetworkTopology, NeuronType,
    SpikingNeuralNetwork, VoltageResolution,
};
use std::panic::{catch_unwind, AssertUnwindSafe};

/// What the rules say of a case.
#[derive(Debug)]
enum Rule {
    Builds,
    /// Refused under one of these names, two when a case breaks two rules.
    Refused(&'static [Error]),
}

/// The cases run, and the ones whose outcome is not their rule's.
#[derive(Default)]
struct Cases {
    run: usize,
    wrong: Vec<String>,
}

impl Cases {
    fn check(&mut self, id: &str, rule: Rule, case: impl FnOnce() -> Result<(), Error>) {
        self.run += 1;
        let got = catch_unwind(AssertUnwindSafe(case));
        let kept = match (&rule, &got) {
            (Rule::Builds, Ok(Ok(()))) => true,
            (Rule::Refused(names), Ok(Err(e))) => names.contains(e),
            _ => false,
        };
        if !kept {
            let got = match got {
                Ok(Ok(())) => "built".to_string(),
                Ok(Err(e)) => format!("refused {e:?}"),
                Err(_) => "panicked".to_string(),
            };
            self.wrong
                .push(format!("{id}: the rule says {rule:?}, got {got}"));
        }
    }

    fn assert_kept(self, cases: usize) {
        assert!(
            self.wrong.is_empty(),
            "{} of {} cases break their rule:\n{}",
            self.wrong.len(),
            self.run,
            self.wrong.join("\n")
        );
        assert_eq!(self.run, cases, "the cases run");
    }
}

/// 25 steps, a quarter of the neurons driven at 3,000 pA each step, chosen
/// by a fixed generator.
fn drive(net: &mut SpikingNeuralNetwork) -> Result<(), Error> {
    let mut lcg: u32 = 12_345;
    let mut input = vec![0i16; usize::from(net.neuron_count())];
    for _ in 0..25 {
        for current in &mut input {
            lcg = lcg.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
            *current = if (lcg >> 24).is_multiple_of(4) {
                3000
            } else {
                0
            };
        }
        net.step(&input)?;
    }
    Ok(())
}

fn topology_case(n: u16, dt: u32, topology: NetworkTopology) -> Result<(), Error> {
    let mut net = SpikingNeuralNetwork::new(n, dt, topology)?;
    net.build_topology()?;
    drive(&mut net)
}

/// `new`'s rules, then the topology's own (`build_topology`).
fn topology_rule(n: u16, dt: u32, topology: NetworkTopology) -> Rule {
    if n == 0 && dt == 0 {
        return Rule::Refused(&[Error::NeuronCountOutOfRange, Error::ZeroTimeStep]);
    }
    if n == 0 {
        return Rule::Refused(&[Error::NeuronCountOutOfRange]);
    }
    // A step of zero freezes every membrane too: either name will do.
    if dt == 0 {
        return Rule::Refused(&[Error::ZeroTimeStep, Error::FrozenMembrane]);
    }
    // `new`'s neurons: the count times the ratio, truncated, excitatory
    // (Ï„ = 20 ms), the rest inhibitory (10 ms); the ratio is the
    // `Balanced` one, the 80/20 split's for the other topologies. A
    // membrane moves when the step is at least τ / 1,000: 20 μs, and 10 μs.
    let ratio = match topology {
        NetworkTopology::Balanced { excitatory_ratio } => excitatory_ratio,
        NetworkTopology::Random { .. }
        | NetworkTopology::SmallWorld { .. }
        | NetworkTopology::Feedforward { .. } => 0.8,
        other => panic!("no rule written here for {other:?}"),
    };
    let excitatory = (f64::from(n) * ratio).trunc();
    let has_excitatory = excitatory >= 1.0;
    let has_inhibitory = excitatory.is_nan() || excitatory < f64::from(n);
    if (has_excitatory && dt < 20) || (has_inhibitory && dt < 10) {
        return Rule::Refused(&[Error::FrozenMembrane]);
    }
    match topology {
        // A probability from 0 to 1, NaN refused, at any neuron count.
        NetworkTopology::Random { connectivity: p }
        | NetworkTopology::SmallWorld {
            rewiring_prob: p, ..
        } => {
            if (0.0..=1.0).contains(&p) {
                Rule::Builds
            } else {
                Rule::Refused(&[Error::ProbabilityOutOfRange])
            }
        }
        // Every layer has a neuron, and the sizes sum to the count.
        NetworkTopology::Feedforward { layers } => {
            let sum: usize = layers.iter().map(|&size| usize::from(size)).sum();
            if layers.contains(&0) || sum != usize::from(n) {
                Rule::Refused(&[Error::BadLayerSizes])
            } else {
                Rule::Builds
            }
        }
        // The count times the ratio, truncated, is the excitatory count,
        // and a network needs a neuron of each type.
        NetworkTopology::Balanced { excitatory_ratio } => {
            let excitatory = (f64::from(n) * excitatory_ratio).trunc();
            if excitatory >= 1.0 && excitatory <= f64::from(n) - 1.0 {
                Rule::Builds
            } else {
                Rule::Refused(&[Error::MissingNeuronType])
            }
        }
        other => panic!("no rule written here for {other:?}"),
    }
}

fn topology(cases: &mut Cases, id: &str, n: u16, dt: u32, topology: NetworkTopology) {
    cases.check(id, topology_rule(n, dt, topology), || {
        topology_case(n, dt, topology)
    });
}

/// `layers` for a `Feedforward` case, kept for the test's run.
fn leak(layers: &[u16]) -> &'static [u16] {
    Box::leak(layers.to_vec().into_boxed_slice())
}

/// `new` and `build_topology` at 1 to 30 neurons, every topology, the
/// values at and just past each rule's edges, -0.0 and the infinities, the
/// time step at the membrane rule's edges;
/// and every `Feedforward` list of 0 to 4 layers over the sizes 0, 1, 2
/// and 5, the empty list included, so a layer of no neuron sits at every
/// place, on its sum and one off it each way.
fn section_a(cases: &mut Cases) {
    for n in [1, 2, 3, 4, 5, 8, 10, 30] {
        topology(
            cases,
            &format!("A/default/n={n}"),
            n,
            1000,
            NetworkTopology::default(),
        );
        for r in [
            -1.0,
            0.0,
            0.01,
            0.05,
            0.2,
            0.5,
            0.8,
            0.9,
            0.95,
            0.99,
            1.0_f64.next_down(),
            1.0,
            1.5,
            -0.0,
            f64::NAN,
            f64::INFINITY,
            f64::NEG_INFINITY,
        ] {
            let balanced = NetworkTopology::Balanced {
                excitatory_ratio: r,
            };
            topology(cases, &format!("A/bal/n={n}/r={r:?}"), n, 1000, balanced);
        }
        // The lower edge of the ratio: 1/n and the value below it.
        let lower = 1.0 / f64::from(n);
        for r in [lower.next_down(), lower] {
            let balanced = NetworkTopology::Balanced {
                excitatory_ratio: r,
            };
            topology(
                cases,
                &format!("A/bal-edge/n={n}/r={r:?}"),
                n,
                1000,
                balanced,
            );
        }
        // The probability rule at and just past each edge, -0.0, far
        // values and the infinities.
        let (below, above) = (0.0_f64.next_down(), 1.0_f64.next_up());
        for c in [
            -1.0,
            below,
            -0.0,
            0.0,
            0.1,
            0.5,
            1.0,
            above,
            2.0,
            1e30,
            f64::INFINITY,
            f64::NEG_INFINITY,
            f64::NAN,
        ] {
            let random = NetworkTopology::Random { connectivity: c };
            topology(cases, &format!("A/rand/n={n}/c={c:?}"), n, 1000, random);
        }
        for k in [0u8, 1, 2, 3, 4, 10, 255] {
            for p in [
                -1.0,
                below,
                -0.0,
                0.0,
                0.5,
                1.0,
                above,
                5.0,
                f64::INFINITY,
                f64::NEG_INFINITY,
                f64::NAN,
            ] {
                let small_world = NetworkTopology::SmallWorld {
                    local_connections: k,
                    rewiring_prob: p,
                };
                topology(
                    cases,
                    &format!("A/sw/n={n}/k={k}/p={p:?}"),
                    n,
                    1000,
                    small_world,
                );
            }
        }
    }
    for dt in [0, 1, 9, 10, 19, 20, 1000, u32::MAX] {
        topology(
            cases,
            &format!("A/dt={dt}"),
            10,
            dt,
            NetworkTopology::default(),
        );
    }
    // Where the neurons' types decide the membrane rule: one neuron at the
    // default ratio is inhibitory, and a `Balanced` ratio of 0, of 1 and
    // NaN leaves no excitatory, no inhibitory and no excitatory neuron.
    for (n, kind) in [
        (1, NetworkTopology::default()),
        (
            10,
            NetworkTopology::Balanced {
                excitatory_ratio: 0.0,
            },
        ),
        (
            10,
            NetworkTopology::Balanced {
                excitatory_ratio: 1.0,
            },
        ),
        (
            10,
            NetworkTopology::Balanced {
                excitatory_ratio: f64::NAN,
            },
        ),
    ] {
        for dt in [9, 10, 19, 20] {
            topology(cases, &format!("A/dt={dt}/n={n}/{kind:?}"), n, dt, kind);
        }
    }
    topology(cases, "A/n=0", 0, 1000, NetworkTopology::default());
    topology(cases, "A/n=0/dt=0", 0, 0, NetworkTopology::default());
    let sizes = [0u16, 1, 2, 5];
    for len in 0..=4u32 {
        for code in 0..sizes.len().pow(len) {
            let mut c = code;
            let mut list = Vec::new();
            for _ in 0..len {
                list.push(sizes[c % sizes.len()]);
                c /= sizes.len();
            }
            let sum: u16 = list.iter().sum();
            let layers = leak(&list);
            for n in [sum.checked_sub(1), Some(sum), Some(sum + 1)] {
                if let Some(n @ 1..) = n {
                    let feedforward = NetworkTopology::Feedforward { layers };
                    topology(cases, &format!("A/ff/{list:?}/n={n}"), n, 1000, feedforward);
                }
            }
        }
    }
}

/// `from_neurons` at 0 to 3 neurons and around 65,535, with and without a
/// time step, then every order of 1 to 3 neurons over the two grids, and a
/// membrane that cannot move at each place of three.
fn section_b(cases: &mut Cases) {
    for n in [0usize, 1, 2, 3, 65_534, 65_535, 65_536, 65_537] {
        for dt in [0u32, 1000] {
            // A step of zero freezes every membrane too: where a neuron is
            // given, that name will do as well.
            let rule = match (n == 0 || n > 65_535, dt == 0) {
                (true, true) if n == 0 => {
                    Rule::Refused(&[Error::NeuronCountOutOfRange, Error::ZeroTimeStep])
                }
                // past 65,536 neurons a `u16` id wraps: off its position too,
                // with a step or without
                (true, true) if n > 65_536 => Rule::Refused(&[
                    Error::NeuronCountOutOfRange,
                    Error::ZeroTimeStep,
                    Error::FrozenMembrane,
                    Error::NeuronIdMismatch,
                ]),
                (true, true) => Rule::Refused(&[
                    Error::NeuronCountOutOfRange,
                    Error::ZeroTimeStep,
                    Error::FrozenMembrane,
                ]),
                (true, false) if n > 65_536 => {
                    Rule::Refused(&[Error::NeuronCountOutOfRange, Error::NeuronIdMismatch])
                }
                (true, false) => Rule::Refused(&[Error::NeuronCountOutOfRange]),
                (false, true) => Rule::Refused(&[Error::ZeroTimeStep, Error::FrozenMembrane]),
                (false, false) => Rule::Builds,
            };
            cases.check(&format!("B/from/n={n}/dt={dt}"), rule, || {
                let neurons = (0..n)
                    .map(|id| {
                        LIFNeuron::new(
                            id as u16,
                            NeuronType::Excitatory,
                            VoltageResolution::Millivolt,
                        )
                    })
                    .collect();
                let mut net = SpikingNeuralNetwork::from_neurons(neurons, dt)?;
                let mut input = vec![0i16; n];
                input[n - 1] = 3000;
                net.step(&input).map(|_| ())
            });
        }
    }
    // A time constant of 0 or above 1,000 steps freezes a membrane; the
    // other two neurons' is one step.
    for dt in [1u32, 1000] {
        let longest = dt * 1000;
        for tau in [0, 1, longest, longest + 1, u32::MAX] {
            for at in 0..3u16 {
                let rule = if tau == 0 || tau > longest {
                    Rule::Refused(&[Error::FrozenMembrane])
                } else {
                    Rule::Builds
                };
                cases.check(&format!("B/tau/dt={dt}/tau={tau}/at={at}"), rule, || {
                    let neurons = (0..3u16)
                        .map(|id| {
                            LIFNeuron::new(id, NeuronType::Excitatory, VoltageResolution::Millivolt)
                                .with_tau_membrane_us(if id == at { tau } else { dt })
                        })
                        .collect();
                    let mut net = SpikingNeuralNetwork::from_neurons(neurons, dt)?;
                    net.step(&[3000; 3]).map(|_| ())
                });
            }
        }
    }
    // A neuron not at rest, by the public API, at each place of three; the
    // same after `reset`, and a neuron the chain rewrote, are at rest.
    // a name, whether the neuron is at rest after, how it is staged
    type Stage = (&'static str, bool, fn(&mut LIFNeuron));
    let stages: [Stage; 6] = [
        ("stepped", false, |n| {
            n.integrate_and_fire(600, 1000, 0);
        }),
        ("clocked", false, |n| {
            n.integrate_and_fire(0, 1000, 5000);
        }),
        ("pulsed", false, |n| n.add_synaptic_current(-100)),
        ("fired", false, |n| {
            *n = n.clone().with_threshold(-100);
            n.integrate_and_fire(0, 1000, 0);
        }),
        ("fired-reset", true, |n| {
            *n = n.clone().with_threshold(-100);
            n.integrate_and_fire(0, 1000, 0);
            n.reset();
        }),
        ("chained", true, |n| {
            *n = n.clone().with_resting_potential(-60)
        }),
    ];
    for (name, at_rest, stage) in stages {
        for at in 0..3usize {
            let rule = if at_rest {
                Rule::Builds
            } else {
                Rule::Refused(&[Error::NeuronNotAtRest])
            };
            cases.check(&format!("B/rest/{name}/at={at}"), rule, || {
                let mut neurons: Vec<LIFNeuron> = (0..3)
                    .map(|id| {
                        LIFNeuron::new(id, NeuronType::Excitatory, VoltageResolution::Millivolt)
                    })
                    .collect();
                stage(&mut neurons[at]);
                let mut net = SpikingNeuralNetwork::from_neurons(neurons, 1000)?;
                net.step(&[3000; 3]).map(|_| ())
            });
        }
    }
    // Ids: every order of three, a gap, a repeat; in place, it builds. A
    // neuron off its position that is also not at rest: either name.
    for ids in [
        [0u16, 1, 2],
        [0, 2, 1],
        [1, 0, 2],
        [1, 2, 0],
        [2, 0, 1],
        [2, 1, 0],
        [0, 1, 3],
        [0, 0, 1],
    ] {
        for stepped in [false, true] {
            let in_place = ids.iter().zip(0u16..).all(|(&id, i)| id == i);
            let rule = match (in_place, stepped) {
                (true, false) => Rule::Builds,
                (true, true) => Rule::Refused(&[Error::NeuronNotAtRest]),
                (false, false) => Rule::Refused(&[Error::NeuronIdMismatch]),
                (false, true) => Rule::Refused(&[Error::NeuronIdMismatch, Error::NeuronNotAtRest]),
            };
            cases.check(&format!("B/id/{ids:?}/stepped={stepped}"), rule, || {
                let mut neurons: Vec<LIFNeuron> = ids
                    .iter()
                    .map(|&id| {
                        LIFNeuron::new(id, NeuronType::Excitatory, VoltageResolution::Millivolt)
                    })
                    .collect();
                if stepped {
                    neurons[2].integrate_and_fire(600, 1000, 0);
                }
                let mut net = SpikingNeuralNetwork::from_neurons(neurons, 1000)?;
                net.step(&[3000; 3]).map(|_| ())
            });
        }
    }
    let grids = [
        VoltageResolution::Millivolt,
        VoltageResolution::CentiMillivolt,
    ];
    for len in 1..=3usize {
        for code in 0..(1usize << len) {
            let order: Vec<VoltageResolution> = (0..len).map(|i| grids[(code >> i) & 1]).collect();
            let rule = if order.iter().all(|&g| g == order[0]) {
                Rule::Builds
            } else {
                Rule::Refused(&[Error::MixedVoltageGrids])
            };
            cases.check(&format!("B/grid/{order:?}"), rule, || {
                let neurons = (0u16..)
                    .zip(&order)
                    .map(|(id, &grid)| LIFNeuron::new(id, NeuronType::Excitatory, grid))
                    .collect();
                let mut net = SpikingNeuralNetwork::from_neurons(neurons, 1000)?;
                net.step(&[]).map(|_| ())
            });
        }
    }
}

/// `set_synaptic_input_divisor` on both sides of each edge, each with six
/// weights: one step sends a pulse, and the fixed path converts the
/// synapse.
fn section_c(cases: &mut Cases) {
    for d in [
        0u16, 1, 2, 3, 10, 100, 1000, 32_766, 32_767, 32_768, 32_769, 40_000, 65_534, 65_535,
    ] {
        for w in [2000i16, -2000, 1, 0, i16::MAX, i16::MIN] {
            let rule = if d == 0 || d > 32_767 {
                Rule::Refused(&[Error::DivisorOutOfRange])
            } else {
                Rule::Builds
            };
            cases.check(&format!("C/div/d={d}/w={w}"), rule, || {
                let neurons = (0..2)
                    .map(|id| {
                        LIFNeuron::new(id, NeuronType::Excitatory, VoltageResolution::Millivolt)
                    })
                    .collect();
                let mut net = SpikingNeuralNetwork::from_neurons(neurons, 1000)?;
                net.set_synaptic_input_divisor(d)?;
                net.add_synapse(0, 1, w)?;
                let _ = FixedSynapse::from_network(&net);
                net.step(&[3000, 0]).map(|_| ())
            });
        }
    }
}

/// Three neurons, wired.
fn net3(edges: &[(u16, u16, i16)]) -> Result<SpikingNeuralNetwork, Error> {
    let neurons = (0..3)
        .map(|id| LIFNeuron::new(id, NeuronType::Excitatory, VoltageResolution::Millivolt))
        .collect();
    let mut net = SpikingNeuralNetwork::from_neurons(neurons, 1000)?;
    for &(pre, post, weight) in edges {
        net.add_synapse(pre, post, weight)?;
    }
    Ok(net)
}

/// `add_synapse` at the ids' edges on three neurons.
fn section_d(cases: &mut Cases) {
    for (pre, post) in [
        (0u16, 0u16),
        (0, 1),
        (0, 2),
        (0, 3),
        (3, 0),
        (2, 2),
        (65_535, 0),
        (0, 65_535),
        (65_535, 65_535),
    ] {
        let rule = match (pre >= 3 || post >= 3, pre == post) {
            (true, true) => Rule::Refused(&[Error::NeuronIdOutOfRange, Error::SelfConnection]),
            (true, false) => Rule::Refused(&[Error::NeuronIdOutOfRange]),
            (false, true) => Rule::Refused(&[Error::SelfConnection]),
            (false, false) => Rule::Builds,
        };
        cases.check(&format!("D/add/{pre}->{post}"), rule, || {
            net3(&[])?.add_synapse(pre, post, 1000)
        });
    }
}

fn fixed<const N: usize, const S: usize>(net: &SpikingNeuralNetwork) -> Result<(), Error> {
    FixedNetwork::<N, S>::try_from(net).map(|_| ())
}

/// `FixedNetwork::try_from`: the right sizes, the wrong ones, edges out of
/// `pre` order, and, with `unstable-stdp`, plasticity on.
fn section_e(cases: &mut Cases) {
    let edges = [(0, 1, 5000), (1, 2, 5000)];
    let net = net3(&edges).expect("three neurons");
    cases.check("E/3-2", Rule::Builds, || fixed::<3, 2>(&net));
    cases.check(
        "E/n=4",
        Rule::Refused(&[Error::NeuronCountMismatch]),
        || fixed::<4, 2>(&net),
    );
    cases.check(
        "E/n=2",
        Rule::Refused(&[Error::NeuronCountMismatch]),
        || fixed::<2, 2>(&net),
    );
    cases.check(
        "E/s=1",
        Rule::Refused(&[Error::SynapseCountMismatch]),
        || fixed::<3, 1>(&net),
    );
    cases.check(
        "E/s=3",
        Rule::Refused(&[Error::SynapseCountMismatch]),
        || fixed::<3, 3>(&net),
    );
    let out_of_order = net3(&[(1, 2, 5000), (0, 1, 5000)]).expect("three neurons");
    cases.check("E/out-of-pre-order", Rule::Builds, || {
        fixed::<3, 2>(&out_of_order)
    });
    #[cfg(feature = "unstable-stdp")]
    {
        let mut on = net3(&edges).expect("three neurons");
        on.set_plasticity_enabled(true);
        cases.check(
            "E/plasticity-on",
            Rule::Refused(&[Error::PlasticityEnabled]),
            || fixed::<3, 2>(&on),
        );
    }
}

/// `trace::header` with twelve case names: one or more of `[a-z0-9-]`.
fn section_f(cases: &mut Cases) {
    let net = net3(&[]).expect("three neurons");
    for name in [
        "", "ok", "ok-1", "a", "Ok", "a_b", "a b", "\u{e9}", "-", "a--b", "0", "A",
    ] {
        let fits = !name.is_empty()
            && name
                .bytes()
                .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-');
        let rule = if fits {
            Rule::Builds
        } else {
            Rule::Refused(&[Error::BadCaseName])
        };
        cases.check(&format!("F/case/{name:?}"), rule, || {
            trace::header(&net, name, Kind::Regression, 10, Rows::All).map(|_| ())
        });
    }
}

/// Layer lists whose sizes sum past 65,535, refused by the layer rule
/// before any synapse.
fn section_g_refused(cases: &mut Cases) {
    for (list, n) in [
        (&[65_535u16, 11][..], 10u16),
        (&[65_535, 2], 1),
        (&[65_534, 4], 2),
        (&[65_535, 1], 65_535),
        (&[32_768, 32_768], 65_535),
    ] {
        let feedforward = NetworkTopology::Feedforward { layers: leak(list) };
        topology(cases, &format!("G/ff/{list:?}/n={n}"), n, 1000, feedforward);
    }
}

#[test]
fn every_constructor_case_follows_its_rule() {
    let mut cases = Cases::default();
    section_a(&mut cases);
    section_b(&mut cases);
    section_c(&mut cases);
    section_d(&mut cases);
    section_e(&mut cases);
    section_f(&mut cases);
    section_g_refused(&mut cases);
    let plasticity = usize::from(cfg!(feature = "unstable-stdp"));
    cases.assert_kept(1909 + 94 + 84 + 9 + 6 + plasticity + 12 + 5);
}

/// The cases at 65,535 neurons that build: two layer lists that sum to
/// it, and `SmallWorld` with no local connection and with two, near the
/// cap. In release an overflow wraps, so this test sees a panic or an
/// abort, never a wrong edge: the ring is
/// `smallworld_near_the_cap_wires_the_ring`'s.
#[test]
fn the_cases_at_65_535_neurons_build() {
    let mut cases = Cases::default();
    for list in [&[65_534u16, 1][..], &[1, 65_534]] {
        let feedforward = NetworkTopology::Feedforward { layers: leak(list) };
        topology(
            &mut cases,
            &format!("G/ff/{list:?}/n=65535"),
            65_535,
            1000,
            feedforward,
        );
    }
    for k in [0, 2] {
        let small_world = NetworkTopology::SmallWorld {
            local_connections: k,
            rewiring_prob: 0.0,
        };
        topology(
            &mut cases,
            &format!("G/sw/n=65535/k={k}/p=0.0"),
            65_535,
            1000,
            small_world,
        );
    }
    cases.assert_kept(4);
}