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
// SPDX-FileCopyrightText: 2026 philo-the-dendron
// SPDX-License-Identifier: AGPL-3.0-or-later
//! The freezer: a network as the Rust source of the arrays a
//! [`FixedNetwork`](super::FixedNetwork) steps. `std`: it writes
//! `String`s.
//!
//! A frozen file has three parts, one function each: the [`preamble`],
//! one [`module`] per network, and the [`tail`], the `for_each_frozen!`
//! macro over the modules. The library's trace tests write
//! `tests/traces/frozen.rs` with all three (`cases::freeze`), and
//! `gresil-nir2json --freeze` writes one module for a stranger's graph.
//! A module needs only `core` and this crate, so firmware can include it.
//!
//! Behind the `unstable-freeze` feature, outside the semver promise:
//! anything here may change or go in a minor release.

// The text is built line by line, `format!` then `push_str`, as
// `cases::freeze` built it before the move: each line reads as the
// source it writes.
#![allow(clippy::format_push_string)]

use super::FixedSynapse;
use crate::lif_neuron::LIFNeuron;
use crate::network::SpikingNeuralNetwork;
use crate::trace::{self, Kind, Rows};

/// The head of the library's frozen file (module doc).
const PREAMBLE: &str = "\
// Generated by `cargo run -p gresil --example trace --features unstable-stdp,unstable-freeze -- write` from
// tests/traces/cases.rs (`cases::freeze`); do not edit it by hand.
// tests/traces.rs regenerates it and compares line for line.
//
// Every plasticity-off case of tests/traces/ as the arrays a FixedNetwork
// steps: N neurons and S synapses, the time step, the run, whether the
// trace keeps spiking steps only, the trace's header line verbatim, the
// neurons as built, each one a constructor call and one setter per
// parameter (every parameter written, default or not), the synapses in
// the CSR order, and the drive as runs of equal steps, (count,
// currents). plasticity-on is not here: a FixedNetwork has no
// plasticity.
//
// Included by #[path] with #[rustfmt::skip] on the `mod frozen;` line, so
// rustfmt leaves it as written: by tests/traces.rs, and by firmware, since
// it needs only core and gresil. One allow, builtin: dead_code, since
// an includer reads only the constants it needs.
#![allow(dead_code)]
";

/// The head of the library's frozen file, `tests/traces/frozen.rs`: what
/// it is, how it is made and kept, and its one allow (`dead_code`: an
/// includer reads only the constants it needs). The allow is an inner
/// attribute, so that file is included as a module (`#[path]`), not by
/// `include!`.
#[must_use]
pub fn preamble() -> &'static str {
    PREAMBLE
}

/// One `pub mod` for the trace `case`, its last newline included: `N`,
/// `S`, `DT_US`, `STEPS`, `SPIKES_ONLY`, `HEADER` (the trace's header
/// line, [`trace::header`]'s), `NEURONS` (one constructor call and one
/// setter per parameter each, every parameter written, at rest),
/// `SYNAPSES` (the delivery order, which [`FixedSynapse::from_network`]
/// gives as the CSR's) and `DRIVE`, runs of equal steps, `(count,
/// currents)`. The module is named after the case, `-` made `_`.
///
/// Everything but the run is read from `net`: its neurons, its synapses,
/// its time step and the header's fields. `case`, `kind`, `steps` and
/// `rows` name the trace, and `drive` is its run.
///
/// No state is emitted: a frozen neuron is its parameters, at rest. The
/// eight setters are written default or not, so a frozen file does not
/// move when a default does — the per-type table and the per-grid
/// scaling are what an old file would otherwise be silently rebound to.
///
/// # Panics
///
/// On what a frozen file cannot hold, each message naming the case:
/// plasticity on, since a `FixedNetwork` has none; a clock that is not
/// at 0, since the file starts at 0 and writes no state; neurons on two
/// grids, which no public constructor builds (`from_neurons` refuses
/// them), and a `case` that is empty or holds anything but lowercase
/// ASCII letters, digits and `-`, both of which the header line
/// refuses; a run of `drive` that does not hold one current per neuron;
/// a neuron that is not at rest (the assert in `neuron_chain` carries
/// the reasons it cannot fire on the stranger path); and a neuron whose
/// `id` is not its position, since the id is what a `FixedNetwork`
/// indexes it by and what seeds its noise; `from_neurons` refuses both,
/// so only a network the crate's own tests write reaches them. And when
/// the chain written for a neuron does not rebuild it, which is this
/// module's own defect and not the caller's.
#[must_use]
pub fn module(
    net: &SpikingNeuralNetwork,
    case: &str,
    kind: Kind,
    steps: u32,
    rows: Rows,
    drive: &[(u32, Vec<i16>)],
) -> String {
    assert!(
        !net.plasticity_enabled(),
        "{case}: plasticity is on, and a FixedNetwork has none"
    );
    assert_eq!(
        net.time_us(),
        0,
        "{case}: the network has stepped, and a frozen file starts at 0"
    );
    assert!(
        trace::one_grid(net).is_some(),
        "{case}: the neurons store their potentials on two grids, and a trace names one"
    );
    assert!(
        trace::is_case_name(case),
        "{case:?}: a case name is lowercase ASCII letters, digits and -"
    );
    let header = trace::header(net, case, kind, steps, rows)
        .expect("one grid and a case name by the rule, both checked above");
    let neurons = net.neurons();
    let synapses = FixedSynapse::from_network(net);
    let dt_us = net.dt_us();
    let spikes_only = matches!(rows, Rows::Spikes);
    let name = case.replace('-', "_");
    assert!(
        drive
            .iter()
            .all(|(_, currents)| currents.len() == neurons.len()),
        "{case}: one current per neuron in every run of the drive"
    );
    let mut out = format!("pub mod {name} {{\n");
    out.push_str("    use gresil::{FixedSynapse, LIFNeuron, NeuronType, VoltageResolution};\n\n");
    out.push_str(&format!("    pub const N: usize = {};\n", neurons.len()));
    out.push_str(&format!("    pub const S: usize = {};\n", synapses.len()));
    out.push_str(&format!("    pub const DT_US: u32 = {dt_us};\n"));
    out.push_str(&format!("    pub const STEPS: u32 = {steps};\n"));
    out.push_str(&format!(
        "    pub const SPIKES_ONLY: bool = {spikes_only};\n"
    ));
    out.push_str(&format!("    pub const HEADER: &str = {header:?};\n"));
    out.push_str("    pub const NEURONS: [LIFNeuron; N] = [\n");
    for (i, neuron) in neurons.iter().enumerate() {
        let (chain, rebuilt) = neuron_chain(case, i, neuron);
        // THE GUARD IS A CORPUS TEST, NOT A TRIPWIRE. It fires when a
        // frozen neuron carries a value the chain does not write, which
        // is what "the emitted list of setters is complete" means here.
        // It is not the tripwire a field added to `LIFNeuron` trips:
        // that one is `neuron_chain`'s destructure, and behind it
        // `the_neuron_has_seventeen_fields`, whose neuron is a literal.
        // WHAT IT ALONE COVERS, since the test lines in `tests/traces.rs`
        // catch a missing setter in-tree too: the stranger path, where
        // no test line exists, and an earlier error, at regeneration.
        //
        // Three limits, since a reader will want to lean on it. (1) It
        // proves the chain's LIST is complete, not that a setter is
        // right: where the source neuron was itself built by the chain
        // (`nir::substrate_neuron`), the rebuild shares its setters and
        // cannot see an error inside one — what sees that is the at-rest
        // assert below and the trace. (2) A neuron whose
        // `voltage_resolution` was assigned alone rebuilds equal to
        // itself and is frozen as it is: this is a completeness check on
        // the chain, never a validity check on the neuron. (3) It reads
        // the DERIVED `Debug` of `LIFNeuron`, `NeuronType` and
        // `VoltageResolution` (the crate's own habit for a field-by-field
        // compare, `nir::chain_equivalence_both_builders_bit_exact`); a
        // hand-written `Debug` on any of the three would blind it, and
        // one on `LIFNeuron` the field count too — but not that test's
        // literal, which is the compiler's own check and reads no `Debug`
        // at all.
        assert_eq!(
            format!("{rebuilt:?}"),
            format!("{neuron:?}"),
            "{case}, neuron {i}: the emitted chain does not rebuild the neuron"
        );
        assert!(
            usize::from(neuron.id) == i,
            "{case}, neuron {i}: a neuron's id is its position in the array, \
             which is what indexes it and what seeds its noise"
        );
        out.push_str(&format!("        {chain},\n"));
    }
    out.push_str("    ];\n");
    if synapses.is_empty() {
        out.push_str("    pub const SYNAPSES: [FixedSynapse; S] = [];\n");
    } else {
        out.push_str("    pub const SYNAPSES: [FixedSynapse; S] = [\n");
        for s in &synapses {
            out.push_str(&format!(
                "        FixedSynapse::new({}, {}, {}),\n",
                s.pre, s.post, s.pulse_pa
            ));
        }
        out.push_str("    ];\n");
    }
    out.push_str("    pub const DRIVE: &[(u32, [i16; N])] = &[\n");
    for (count, currents) in drive {
        let currents: Vec<String> = currents.iter().map(i16::to_string).collect();
        out.push_str(&format!("        ({count}, [{}]),\n", currents.join(", ")));
    }
    out.push_str("    ];\n}\n");
    out
}

/// `for_each_frozen!`, which applies a caller's macro to the module of
/// every case named here, in this order, so no list is kept by hand;
/// then its `pub(crate) use`. A case's module is its name, `-` made `_`,
/// as [`module`] names it.
#[must_use]
pub fn tail(cases: &[&str]) -> String {
    let mut out = String::from(
        "/// Applies the caller's macro to every frozen case, in file order.\n\
         macro_rules! for_each_frozen {\n    ($m:ident) => {\n",
    );
    for case in cases {
        out.push_str(&format!("        $m!({});\n", case.replace('-', "_")));
    }
    out.push_str("    };\n}\npub(crate) use for_each_frozen;\n");
    out
}

/// A neuron as the constructor call and the setters that write its
/// parameters, and the neuron those same calls build.
///
/// The pattern lists every field, so a field added to `LIFNeuron` fails
/// to compile here until the freezer BINDS it — and binding it is a
/// decision: emit a setter for the field, or state why its default is
/// right for every frozen file ever written. THIS DESTRUCTURE IS THE
/// FIRST TRIPWIRE, and it is only as strong as its bindings' readers: a
/// binding with no reader can be answered with `..` and the tripwire is
/// gone. Every one of the seventeen has one — the eight parameters and
/// the three constructor arguments below, the six state fields in the
/// at-rest assert. The second tripwire does not come through here at
/// all: it is `the_neuron_has_seventeen_fields`, whose neuron is a
/// `LIFNeuron { … }` literal, so a field added is the compiler's error
/// there whatever this pattern says.
///
/// `case` and `i` are the case's name and the neuron's index, for the
/// assert below: the two asserts in [`module`]'s loop name both, and a
/// caller that trips this one wants them as much.
fn neuron_chain(case: &str, i: usize, n: &LIFNeuron) -> (String, LIFNeuron) {
    let LIFNeuron {
        id,
        neuron_type,
        membrane_potential,
        resting_potential,
        threshold,
        reset_potential,
        voltage_resolution,
        tau_membrane_us,
        refractory_period_us,
        refractory_remaining_us,
        last_update_time_us,
        last_spike_time_us,
        synaptic_current_pa,
        resistance_mohm,
        noise_amplitude_pa,
        adaptation_current_pa,
        adaptation_enabled,
    } = n;
    // A frozen neuron is parameters, at rest: no state is written, so a
    // neuron carrying state would be frozen as another neuron in
    // silence. This cannot fire on the stranger path, for two
    // independent reasons: `gresil-nir2json`'s `freeze` writes the
    // module before its stepping loop, and `nir::substrate_neuron`
    // builds the membrane at the leak.
    //
    // "At rest" means "before the first step", and `module` reads that
    // off the network's clock: a network stepped once at time 0 with
    // nothing moving passes this assert (`integrate_and_fire` writes
    // `last_update_time_us = current_time_us`, 0 at the first step), not
    // the clock's. A neuron handed to `from_neurons` carrying state, which
    // a clock at 0 does not reveal, is refused there since round 65
    // (`Error::NeuronNotAtRest`), so no public path reaches this assert;
    // it reads its own bindings, the destructure's readers, and its test
    // stages the case.
    assert!(
        membrane_potential == resting_potential
            && *refractory_remaining_us == 0
            && *last_update_time_us == 0
            && *last_spike_time_us == 0
            && *synaptic_current_pa == 0
            && *adaptation_current_pa == 0,
        "{case}, neuron {i}: the freezer writes a neuron at rest, before the first step"
    );
    let mut text = format!(
        "LIFNeuron::new({id}, NeuronType::{neuron_type:?}, \
         VoltageResolution::{voltage_resolution:?})"
    );
    let mut rebuilt = LIFNeuron::new(*id, *neuron_type, *voltage_resolution);
    // ONE LIST for the two halves. `stringify!` writes the setter's name
    // into the text and the same name is called on the rebuild, so a
    // renamed setter cannot part from the text it writes, and a setter
    // dropped from the list takes its binding's reader with it (the
    // gate turns that into `error: unused variable`).
    macro_rules! chain {
        ($($setter:ident => $value:expr),+ $(,)?) => {{
            $(
                text.push_str(&format!(".{}({})", stringify!($setter), $value));
                rebuilt = rebuilt.$setter($value);
            )+
        }};
    }
    chain! {
        with_resting_potential => *resting_potential,
        with_threshold => *threshold,
        with_reset_potential => *reset_potential,
        with_tau_membrane_us => *tau_membrane_us,
        with_refractory_period_us => *refractory_period_us,
        with_resistance_mohm => *resistance_mohm,
        with_noise_amplitude_pa => *noise_amplitude_pa,
        with_adaptation_enabled => *adaptation_enabled,
    }
    (text, rebuilt)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::lif_neuron::{NeuronType, VoltageResolution};

    /// A neuron at rest with no noise, on `grid`.
    fn quiet(id: u16, grid: VoltageResolution) -> LIFNeuron {
        let mut n = LIFNeuron::new(id, NeuronType::Excitatory, grid);
        n.noise_amplitude_pa = 0;
        n
    }

    /// Two quiet neurons on the centi-mV grid and a synapse 0 → 1,
    /// finalized, at a 0.5 ms step, which no trace uses: a network the
    /// freezer takes.
    fn two() -> SpikingNeuralNetwork {
        let neurons = vec![
            quiet(0, VoltageResolution::CentiMillivolt),
            quiet(1, VoltageResolution::CentiMillivolt),
        ];
        let mut net = SpikingNeuralNetwork::from_neurons(neurons, 500).expect("neurons given");
        net.add_synapse(0, 1, 5_000).expect("ids in range");
        net.finalize_synapses();
        net
    }

    /// `two`'s run: three silent steps.
    fn silent() -> Vec<(u32, Vec<i16>)> {
        vec![(3, vec![0, 0])]
    }

    /// What the module reads off the network, and the case's name made
    /// the module's.
    #[test]
    fn the_module_is_named_after_its_case_and_reads_the_network() {
        let text = module(
            &two(),
            "two-quiet",
            Kind::Stranger,
            3,
            Rows::Spikes,
            &silent(),
        );
        assert!(text.starts_with("pub mod two_quiet {\n"), "{text}");
        for line in [
            "    pub const N: usize = 2;\n",
            "    pub const S: usize = 1;\n",
            "    pub const DT_US: u32 = 500;\n",
            "    pub const STEPS: u32 = 3;\n",
            "    pub const SPIKES_ONLY: bool = true;\n",
            "    pub const HEADER: &str = \"# neuralos-trace v1 case=two-quiet kind=stranger n=2 \
             dt_us=500 res=cmV plasticity=off divisor=10 steps=3 rows=spikes\";\n",
        ] {
            assert!(text.contains(line), "{line:?} in {text}");
        }
    }

    /// `tail` names each case's module as `module` does.
    #[test]
    fn the_tail_names_each_case_by_its_module() {
        let text = tail(&["chain-3", "two"]);
        assert!(
            text.contains("        $m!(chain_3);\n        $m!(two);\n"),
            "{text}"
        );
    }

    #[test]
    #[cfg(feature = "unstable-stdp")]
    #[should_panic(expected = "two: plasticity is on")]
    fn plasticity_on_is_refused() {
        let mut net = two();
        net.set_plasticity_enabled(true);
        let _ = module(&net, "two", Kind::Regression, 3, Rows::All, &silent());
    }

    /// Edges added out of `pre` order and never sorted, as
    /// `FixedNetwork::try_from`'s own test adds them, freeze as sorted
    /// ones: the module lists the synapses as `FixedSynapse::from_network`
    /// does, the order the network's first step delivers them in. Before
    /// round 64 the freezer refused the network.
    #[test]
    fn edges_out_of_pre_order_freeze_as_sorted() {
        let wired = |sorted: bool| {
            let neurons = (0..3)
                .map(|id| quiet(id, VoltageResolution::CentiMillivolt))
                .collect();
            let mut net =
                SpikingNeuralNetwork::from_neurons(neurons, 1_000).expect("neurons given");
            net.add_synapse(1, 2, 5_000).expect("ids in range");
            net.add_synapse(0, 1, 5_000).expect("ids in range");
            if sorted {
                net.finalize_synapses();
            }
            net
        };
        let frozen = |net: &SpikingNeuralNetwork| {
            module(
                net,
                "out-of-order",
                Kind::Regression,
                1,
                Rows::All,
                &[(1, vec![0, 0, 0])],
            )
        };
        let text = frozen(&wired(false));
        assert_eq!(text, frozen(&wired(true)), "sorted or not, one module");
        assert!(
            text.contains(
                "        FixedSynapse::new(0, 1, 500),\n        FixedSynapse::new(1, 2, 500),\n"
            ),
            "by pre: {text}"
        );
    }

    /// One step at time 0 moves no field the neuron check reads, so the
    /// clock is what refuses it.
    #[test]
    #[should_panic(expected = "two: the network has stepped")]
    fn a_stepped_network_is_refused() {
        let mut net = two();
        net.step(&[0, 0]).expect("two inputs");
        let _ = module(&net, "two", Kind::Regression, 3, Rows::All, &silent());
    }

    /// Two grids, a network only the crate itself builds: `from_neurons`
    /// refuses it, so neuron 1 is put in its slot after.
    #[test]
    #[should_panic(expected = "mixed: the neurons store their potentials on two grids")]
    fn two_grids_are_refused() {
        let neurons = vec![
            quiet(0, VoltageResolution::Millivolt),
            quiet(1, VoltageResolution::Millivolt),
        ];
        let mut net = SpikingNeuralNetwork::from_neurons(neurons, 1_000).expect("one grid");
        net.neurons_mut()[1] = quiet(1, VoltageResolution::CentiMillivolt);
        let _ = module(
            &net,
            "mixed",
            Kind::Regression,
            1,
            Rows::All,
            &[(1, vec![0, 0])],
        );
    }

    #[test]
    #[should_panic(expected = "\"Two\": a case name is lowercase")]
    fn a_case_name_off_the_rule_is_refused() {
        let _ = module(&two(), "Two", Kind::Regression, 3, Rows::All, &silent());
    }

    #[test]
    #[should_panic(expected = "two: one current per neuron in every run of the drive")]
    fn a_drive_short_of_a_current_is_refused() {
        let _ = module(
            &two(),
            "two",
            Kind::Regression,
            3,
            Rows::All,
            &[(3, vec![0])],
        );
    }

    /// `from_neurons` refuses such a neuron, so the case is put in its
    /// slot after.
    #[test]
    #[should_panic(expected = "restless, neuron 0: the freezer writes a neuron at rest")]
    fn a_neuron_carrying_state_is_refused() {
        let neurons = vec![
            quiet(0, VoltageResolution::CentiMillivolt),
            quiet(1, VoltageResolution::CentiMillivolt),
        ];
        let mut net = SpikingNeuralNetwork::from_neurons(neurons, 1_000).expect("at rest");
        net.neurons_mut()[0].membrane_potential += 1;
        let _ = module(
            &net,
            "restless",
            Kind::Regression,
            1,
            Rows::All,
            &[(1, vec![0, 0])],
        );
    }

    /// `from_neurons` refuses such ids, so the two neurons swap places
    /// after.
    #[test]
    #[should_panic(expected = "swapped, neuron 0: a neuron's id is its position")]
    fn an_id_off_its_position_is_refused() {
        let neurons = vec![
            quiet(0, VoltageResolution::CentiMillivolt),
            quiet(1, VoltageResolution::CentiMillivolt),
        ];
        let mut net = SpikingNeuralNetwork::from_neurons(neurons, 1_000).expect("in place");
        net.neurons_mut().swap(0, 1);
        let _ = module(
            &net,
            "swapped",
            Kind::Regression,
            1,
            Rows::All,
            &[(1, vec![0, 0])],
        );
    }
}