scirs2-neural 0.4.2

Neural network building blocks module for SciRS2 (scirs2-neural) - Minimal Version
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
//! Population Coding and Spike Encoding
//!
//! Converts continuous-valued signals into spike trains using biologically
//! motivated encoding schemes:
//! - Rate coding (Poisson process)
//! - Temporal coding (time-to-first-spike)
//! - Population coding (Gaussian tuning curves)

use crate::error::{NeuralError, Result};

// ---------------------------------------------------------------------------
// Encoding Schemes
// ---------------------------------------------------------------------------

/// Spike encoding strategy.
#[derive(Debug, Clone)]
pub enum SpikeEncoding {
    /// Poisson rate coding: fires at rate proportional to input value.
    /// `period` is the reference period (ms) corresponding to rate = 1.
    RateCoding { period: f32 },
    /// Time-to-first-spike temporal coding.
    /// Stronger inputs produce earlier spikes within a `window` (ms).
    TemporalCoding { window: f32 },
    /// Population coding with Gaussian tuning curves.
    PopulationCoding {
        /// Number of neurons in the population
        n_neurons: usize,
        /// Width (σ) of each Gaussian tuning curve
        tuning_width: f32,
        /// Minimum preferred stimulus value
        x_min: f32,
        /// Maximum preferred stimulus value
        x_max: f32,
    },
}

// ---------------------------------------------------------------------------
// SpikeEncoder
// ---------------------------------------------------------------------------

/// Encodes continuous-valued inputs as spike trains.
#[derive(Debug, Clone)]
pub struct SpikeEncoder {
    /// Encoding scheme in use
    pub encoding: SpikeEncoding,
    /// Internal phase accumulators for rate coding (one per input dimension)
    phase: Vec<f32>,
}

impl SpikeEncoder {
    /// Create a new encoder with the given encoding scheme.
    pub fn new(encoding: SpikeEncoding) -> Self {
        Self {
            encoding,
            phase: Vec::new(),
        }
    }

    /// Initialize phase accumulators for a given input dimensionality.
    pub fn init(&mut self, n_inputs: usize) {
        self.phase = vec![0.0; n_inputs];
    }

    /// Encode a scalar input value as a single spike (true/false) for one time step.
    ///
    /// For `RateCoding` the phase accumulates at each step; a spike is emitted
    /// when `phase >= 1.0`.  Uses a deterministic integrate-and-fire approach
    /// rather than random sampling (preserves reproducibility).
    ///
    /// # Arguments
    /// * `value` — normalised input in [0, 1]
    /// * `dt`    — time step (ms)
    /// * `idx`   — encoder channel index (for phase tracking)
    ///
    /// # Errors
    /// Returns an error if `idx` is out of bounds.
    pub fn encode_scalar(&mut self, value: f32, dt: f32, idx: usize) -> Result<bool> {
        match &self.encoding {
            SpikeEncoding::RateCoding { period } => {
                if idx >= self.phase.len() {
                    return Err(NeuralError::InvalidArgument(format!(
                        "encoder index {idx} out of bounds ({})",
                        self.phase.len()
                    )));
                }
                let rate = value.clamp(0.0, 1.0) / period;
                self.phase[idx] += rate * dt;
                if self.phase[idx] >= 1.0 {
                    self.phase[idx] -= 1.0;
                    return Ok(true);
                }
                Ok(false)
            }
            SpikeEncoding::TemporalCoding { window: _ } => {
                // Temporal coding: single spike at time t = window * (1 - value)
                // At step 0 we emit iff value is above threshold for this dt slice.
                // Simplified: treat as rate encoding with inverse rate.
                if idx >= self.phase.len() {
                    return Err(NeuralError::InvalidArgument(format!(
                        "encoder index {idx} out of bounds"
                    )));
                }
                // Emit at most once; track via phase saturation
                if self.phase[idx] < 0.0 {
                    return Ok(false); // already fired
                }
                let threshold = 1.0 - value.clamp(0.0, 1.0);
                self.phase[idx] += dt;
                if self.phase[idx] >= threshold * 100.0 {
                    self.phase[idx] = -1.0; // mark as fired
                    return Ok(true);
                }
                Ok(false)
            }
            SpikeEncoding::PopulationCoding { .. } => Err(NeuralError::InvalidArgument(
                "Use encode_population() for PopulationCoding".into(),
            )),
        }
    }

    /// Encode a scalar value using population (Gaussian tuning curve) coding.
    ///
    /// Returns a boolean spike vector of length `n_neurons`.
    ///
    /// Each neuron `i` has preferred stimulus `μ_i = x_min + i*(x_max - x_min)/(n-1)`.
    /// Firing rate ∝ exp(-(x - μ_i)² / (2 σ²)). A spike is emitted if the
    /// accumulated phase for that neuron crosses 1.
    ///
    /// # Arguments
    /// * `value` — stimulus value
    /// * `dt`    — time step (ms)
    ///
    /// # Errors
    /// Returns an error if encoding is not `PopulationCoding`.
    pub fn encode_population(&mut self, value: f32, dt: f32) -> Result<Vec<bool>> {
        let (n_neurons, tuning_width, x_min, x_max) = match &self.encoding {
            SpikeEncoding::PopulationCoding {
                n_neurons,
                tuning_width,
                x_min,
                x_max,
            } => (*n_neurons, *tuning_width, *x_min, *x_max),
            _ => {
                return Err(NeuralError::InvalidArgument(
                    "SpikeEncoder is not configured for PopulationCoding".into(),
                ))
            }
        };

        if self.phase.len() != n_neurons {
            self.phase = vec![0.0; n_neurons];
        }

        let range = (x_max - x_min).max(1e-6);
        let mut spikes = vec![false; n_neurons];

        for i in 0..n_neurons {
            let mu = x_min + i as f32 * range / (n_neurons.saturating_sub(1).max(1)) as f32;
            let diff = (value - mu) / tuning_width;
            let rate = (-0.5 * diff * diff).exp(); // in [0, 1]
            self.phase[i] += rate * dt;
            if self.phase[i] >= 1.0 {
                self.phase[i] -= 1.0;
                spikes[i] = true;
            }
        }
        Ok(spikes)
    }

    /// Encode a full input vector for one time step.
    ///
    /// # Arguments
    /// * `inputs` — slice of normalised values in [0, 1]
    /// * `dt`     — time step (ms)
    ///
    /// # Returns
    /// Spike vector (same length as `inputs` for rate/temporal coding).
    ///
    /// # Errors
    /// Returns an error for `PopulationCoding` — use `encode_population` instead.
    pub fn encode_step(&mut self, inputs: &[f32], dt: f32) -> Result<Vec<bool>> {
        match &self.encoding {
            SpikeEncoding::PopulationCoding { .. } => Err(NeuralError::InvalidArgument(
                "Use encode_population() for PopulationCoding".into(),
            )),
            _ => {
                if self.phase.len() != inputs.len() {
                    self.phase = vec![0.0; inputs.len()];
                }
                let mut spikes = vec![false; inputs.len()];
                for (i, &v) in inputs.iter().enumerate() {
                    spikes[i] = self.encode_scalar(v, dt, i)?;
                }
                Ok(spikes)
            }
        }
    }

    /// Reset all internal phase accumulators.
    pub fn reset(&mut self) {
        for p in self.phase.iter_mut() {
            *p = 0.0;
        }
    }
}

// ---------------------------------------------------------------------------
// Spike Decoder
// ---------------------------------------------------------------------------

/// Decodes spike train statistics back to continuous values.
#[derive(Debug, Clone)]
pub struct SpikeDecoder {
    /// Accumulator for counting spikes
    spike_counts: Vec<u32>,
    /// Total number of time steps accumulated
    total_steps: u32,
}

impl SpikeDecoder {
    /// Create a new decoder for `n` neurons.
    pub fn new(n: usize) -> Self {
        Self {
            spike_counts: vec![0; n],
            total_steps: 0,
        }
    }

    /// Accumulate one time step of spike observations.
    ///
    /// # Errors
    /// Returns an error if `spikes.len() != n`.
    pub fn accumulate(&mut self, spikes: &[bool]) -> Result<()> {
        if spikes.len() != self.spike_counts.len() {
            return Err(NeuralError::DimensionMismatch(format!(
                "expected {} spike channels, got {}",
                self.spike_counts.len(),
                spikes.len()
            )));
        }
        for (cnt, &s) in self.spike_counts.iter_mut().zip(spikes.iter()) {
            if s {
                *cnt += 1;
            }
        }
        self.total_steps += 1;
        Ok(())
    }

    /// Compute the mean firing rate (spikes / step) for each neuron.
    pub fn firing_rates(&self) -> Vec<f32> {
        if self.total_steps == 0 {
            return vec![0.0; self.spike_counts.len()];
        }
        let n = self.total_steps as f32;
        self.spike_counts.iter().map(|&c| c as f32 / n).collect()
    }

    /// Decode population spike counts to a scalar estimate via centre-of-mass.
    ///
    /// Useful for population coding: returns the weighted centroid of preferred
    /// stimuli values across neurons.
    ///
    /// # Arguments
    /// * `x_min` / `x_max` — stimulus range
    ///
    /// # Errors
    /// Returns an error if the decoder has zero neurons.
    pub fn decode_population(&self, x_min: f32, x_max: f32) -> Result<f32> {
        let n = self.spike_counts.len();
        if n == 0 {
            return Err(NeuralError::InvalidArgument(
                "decoder has zero neurons".into(),
            ));
        }
        let range = x_max - x_min;
        let mut num = 0.0_f32;
        let mut denom = 0.0_f32;
        for (i, &c) in self.spike_counts.iter().enumerate() {
            let mu = x_min + i as f32 * range / (n.saturating_sub(1).max(1)) as f32;
            let rate = c as f32;
            num += rate * mu;
            denom += rate;
        }
        if denom < 1e-9 {
            return Ok((x_min + x_max) * 0.5);
        }
        Ok(num / denom)
    }

    /// Reset all counters.
    pub fn reset(&mut self) {
        for c in self.spike_counts.iter_mut() {
            *c = 0;
        }
        self.total_steps = 0;
    }
}

// ---------------------------------------------------------------------------
// Spike Statistics
// ---------------------------------------------------------------------------

/// Compute the inter-spike interval (ISI) sequence from a boolean spike train.
///
/// # Arguments
/// * `train` — boolean spike train
/// * `dt`    — time step (ms)
///
/// # Returns
/// Vector of ISI values (ms). Empty if fewer than 2 spikes.
pub fn inter_spike_intervals(train: &[bool], dt: f32) -> Vec<f32> {
    let spike_times: Vec<f32> = train
        .iter()
        .enumerate()
        .filter(|(_, &s)| s)
        .map(|(i, _)| i as f32 * dt)
        .collect();

    spike_times.windows(2).map(|w| w[1] - w[0]).collect()
}

/// Compute the coefficient of variation (CV) of the ISI distribution.
///
/// CV = σ_ISI / μ_ISI. CV ≈ 1 for Poisson, < 1 for regular, > 1 for bursting.
pub fn isi_cv(train: &[bool], dt: f32) -> Option<f32> {
    let isis = inter_spike_intervals(train, dt);
    if isis.len() < 2 {
        return None;
    }
    let n = isis.len() as f32;
    let mean = isis.iter().sum::<f32>() / n;
    let var = isis.iter().map(|&x| (x - mean).powi(2)).sum::<f32>() / n;
    let std = var.sqrt();
    if mean.abs() < 1e-9 {
        return None;
    }
    Some(std / mean)
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn rate_encoder_fires_at_correct_rate() {
        let mut enc = SpikeEncoder::new(SpikeEncoding::RateCoding { period: 1.0 });
        enc.init(1);
        // With value=0.5 and dt=1.0, rate = 0.5 spikes/ms
        let mut count = 0;
        for _ in 0..1000 {
            if enc.encode_scalar(0.5, 1.0, 0).expect("operation should succeed") {
                count += 1;
            }
        }
        // Expect roughly 500 spikes (±50 tolerance)
        assert!(
            (count as i32 - 500).abs() <= 50,
            "Expected ~500 spikes, got {count}"
        );
    }

    #[test]
    fn rate_encoder_zero_input_no_spike() {
        let mut enc = SpikeEncoder::new(SpikeEncoding::RateCoding { period: 10.0 });
        enc.init(1);
        for _ in 0..1000 {
            assert!(!enc.encode_scalar(0.0, 1.0, 0).expect("operation should succeed"));
        }
    }

    #[test]
    fn population_encoder_fires_near_preferred() {
        let mut enc = SpikeEncoder::new(SpikeEncoding::PopulationCoding {
            n_neurons: 10,
            tuning_width: 0.2,
            x_min: 0.0,
            x_max: 1.0,
        });
        // Run for 1000 steps, stimulus near neuron 5's preferred value (0.5)
        let mut counts = vec![0usize; 10];
        for _ in 0..1000 {
            let spikes = enc.encode_population(0.5, 1.0).expect("operation should succeed");
            for (i, &s) in spikes.iter().enumerate() {
                if s {
                    counts[i] += 1;
                }
            }
        }
        // Neuron index 4 or 5 (preferred ~0.44 or ~0.56) should fire most
        let max_idx = counts.iter().enumerate().max_by_key(|&(_, c)| c).map(|(i, _)| i).expect("operation should succeed");
        assert!(
            (max_idx as i32 - 4).abs() <= 2,
            "Max firing neuron {max_idx} should be near centre"
        );
    }

    #[test]
    fn spike_decoder_firing_rates() {
        let mut dec = SpikeDecoder::new(3);
        // 10 steps: neuron 0 fires all, neuron 1 fires half, neuron 2 never
        for i in 0..10 {
            dec.accumulate(&[true, i % 2 == 0, false]).expect("operation should succeed");
        }
        let rates = dec.firing_rates();
        assert!((rates[0] - 1.0).abs() < 1e-5);
        assert!((rates[1] - 0.5).abs() < 1e-5);
        assert_eq!(rates[2], 0.0);
    }

    #[test]
    fn isi_computation() {
        // Spikes at steps 0, 10, 20 with dt=1.0 → ISI = [10.0, 10.0]
        let mut train = vec![false; 25];
        train[0] = true;
        train[10] = true;
        train[20] = true;
        let isis = inter_spike_intervals(&train, 1.0);
        assert_eq!(isis.len(), 2);
        assert!((isis[0] - 10.0).abs() < 1e-5);
        assert!((isis[1] - 10.0).abs() < 1e-5);
        let cv = isi_cv(&train, 1.0).expect("operation should succeed");
        assert!(cv.abs() < 1e-5, "Regular train should have CV ≈ 0");
    }
}