Skip to main content

feagi_structures/genomic/
modulator.rs

1// Copyright 2025 Neuraville Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Built-in modulator kinds and the burst signal model.
5//!
6//! Modulator *types* are fixed by FEAGI. Users create instances of these types.
7//! The signal formulas here are the single definition used by the genome
8//! validator and the burst engine.
9
10use serde::{Deserialize, Serialize};
11use std::fmt;
12
13/// Built-in modulator type. The set is not user-editable.
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
15pub enum ModulatorKind {
16    /// Neuron firing threshold. `threshold * (1 + signal)`.
17    FiringThreshold,
18    /// Neuron leak coefficient, clamped to `[0, 1]`.
19    Leak,
20    /// Probabilistic firing excitability, clamped to `[0, 1]`.
21    FiringProbability,
22    /// PSP of the subscribed mapping's synapses. `psp * (1 + signal)`.
23    TransmissionGain,
24    /// Adds `signal` into the mapping's R-STDP reward `R(t)`.
25    Reward,
26    /// STDP / R-STDP eta of the mapping. `eta * (1 + signal)`.
27    LearningRate,
28    /// Open/closed switch on the subscribed mapping. Transmission is 0 unless a
29    /// gate instance in the group has an active driver; then the factor is the signal.
30    Gate,
31    /// Memory formation switch on a subscribed memory area. Factor is
32    /// `clamp(1 + signal, 0, 1)`; at 0 the area forms no new memory neurons.
33    MemoryFormation,
34    /// Memory freeze switch on a subscribed memory area. While the combined signal is
35    /// above 0 the area is a full snapshot: no creation, ageing, lifespan growth,
36    /// long-term conversion or reward consolidation. Existing memory neurons still fire.
37    /// Magnitude must be above 0.
38    MemoryFreeze,
39    /// Memory capture switch on a subscribed memory area. While the combined signal is
40    /// above 0 the area is recording. Magnitude must be 1..=100.
41    MemoryCapture,
42}
43
44impl ModulatorKind {
45    /// Stable genome and API identifier.
46    pub fn as_str(self) -> &'static str {
47        match self {
48            Self::FiringThreshold => "neuro.firing_threshold",
49            Self::Leak => "neuro.leak",
50            Self::FiringProbability => "neuro.firing_probability",
51            Self::TransmissionGain => "synaptic.transmission_gain",
52            Self::Reward => "synaptic.reward",
53            Self::LearningRate => "synaptic.learning_rate",
54            Self::Gate => "synaptic.gate",
55            Self::MemoryFormation => "memory.formation",
56            Self::MemoryFreeze => "memory.freeze",
57            Self::MemoryCapture => "memory.capture",
58        }
59    }
60
61    /// Parse a genome or API type string.
62    pub fn parse(value: &str) -> Result<Self, String> {
63        match value {
64            "neuro.firing_threshold" => Ok(Self::FiringThreshold),
65            "neuro.leak" => Ok(Self::Leak),
66            "neuro.firing_probability" => Ok(Self::FiringProbability),
67            "synaptic.transmission_gain" => Ok(Self::TransmissionGain),
68            "synaptic.reward" => Ok(Self::Reward),
69            "synaptic.learning_rate" => Ok(Self::LearningRate),
70            "synaptic.gate" => Ok(Self::Gate),
71            "memory.formation" => Ok(Self::MemoryFormation),
72            "memory.freeze" => Ok(Self::MemoryFreeze),
73            "memory.capture" => Ok(Self::MemoryCapture),
74            other => Err(format!("unknown modulator type '{other}'")),
75        }
76    }
77
78    /// Every built-in type, in stable order.
79    pub fn all() -> &'static [Self] {
80        &[
81            Self::FiringThreshold,
82            Self::Leak,
83            Self::FiringProbability,
84            Self::TransmissionGain,
85            Self::Reward,
86            Self::LearningRate,
87            Self::Gate,
88            Self::MemoryFormation,
89            Self::MemoryFreeze,
90            Self::MemoryCapture,
91        ]
92    }
93
94    /// Neuromodulators subscribe on cortical areas.
95    pub fn is_neuromodulator(self) -> bool {
96        matches!(
97            self,
98            Self::FiringThreshold | Self::Leak | Self::FiringProbability
99        )
100    }
101
102    /// Kinds that subscribe on cortical areas: `neuro.*`, `memory.formation`, `memory.freeze`,
103    /// `memory.capture`.
104    pub fn is_area_level(self) -> bool {
105        self.is_neuromodulator()
106            || matches!(
107                self,
108                Self::MemoryFormation | Self::MemoryFreeze | Self::MemoryCapture
109            )
110    }
111
112    /// Synaptic modulators subscribe on mapping rules.
113    pub fn is_synaptic(self) -> bool {
114        !self.is_area_level()
115    }
116
117    /// Reward combines by addition. Every other kind combines by multiplication.
118    pub fn combines_by_addition(self) -> bool {
119        matches!(self, Self::Reward)
120    }
121}
122
123impl fmt::Display for ModulatorKind {
124    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
125        f.write_str(self.as_str())
126    }
127}
128
129/// Why an instance definition was rejected.
130#[derive(Debug, Clone, PartialEq, Eq)]
131pub struct ModulatorValidationError(pub String);
132
133impl fmt::Display for ModulatorValidationError {
134    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
135        f.write_str(&self.0)
136    }
137}
138
139/// Check instance fields that do not depend on the rest of the genome.
140///
141/// `magnitude_percent` must be finite and `>= -100` so every multiplicative
142/// factor stays non-negative. `effect_duration_bursts` must be at least 1.
143/// Graded instances require `full_scale_potential > 0`.
144pub fn validate_instance_fields(
145    magnitude_percent: f32,
146    effect_duration_bursts: u16,
147    graded: bool,
148    full_scale_potential: Option<f32>,
149) -> Result<(), ModulatorValidationError> {
150    if !magnitude_percent.is_finite() || magnitude_percent < -100.0 {
151        return Err(ModulatorValidationError(
152            "magnitude_percent must be finite and >= -100".to_string(),
153        ));
154    }
155    if effect_duration_bursts < 1 {
156        return Err(ModulatorValidationError(
157            "effect_duration_bursts must be >= 1".to_string(),
158        ));
159    }
160    if graded {
161        match full_scale_potential {
162            Some(scale) if scale.is_finite() && scale > 0.0 => {}
163            _ => {
164                return Err(ModulatorValidationError(
165                    "graded modulators require full_scale_potential > 0".to_string(),
166                ));
167            }
168        }
169    }
170    Ok(())
171}
172
173/// `spike_train` with `consecutive_fire_limit == 0` would never end.
174pub fn validate_spike_train(
175    enabled: bool,
176    consecutive_fire_limit: u16,
177) -> Result<(), ModulatorValidationError> {
178    if enabled && consecutive_fire_limit < 1 {
179        return Err(ModulatorValidationError(
180            "spike_train requires consecutive_fire_limit >= 1".to_string(),
181        ));
182    }
183    Ok(())
184}
185
186/// Signal of one instance at one burst.
187///
188/// `fired` includes spike-train firings. When `graded` is false, a firing has
189/// strength 1. When graded, strength is `min(membrane_potential / full_scale, 1)`.
190/// A silent driver contributes 0.
191pub fn modulator_signal(
192    magnitude_percent: f32,
193    fired: bool,
194    graded: bool,
195    membrane_potential: f32,
196    full_scale_potential: f32,
197) -> f32 {
198    if !fired {
199        return 0.0;
200    }
201    let strength = if graded {
202        (membrane_potential / full_scale_potential).min(1.0)
203    } else {
204        1.0
205    };
206    (magnitude_percent / 100.0) * strength
207}
208
209/// Product of `(1 + signal)` across instances that share a parameter.
210pub fn multiplicative_factor(signals: &[f32]) -> f32 {
211    signals
212        .iter()
213        .fold(1.0_f32, |acc, signal| acc * (1.0 + signal))
214}
215
216/// Transmission factor of a group's gate instances: the largest signal (open if
217/// any gate is open), never below 0. A silent driver has signal 0, so the gate is closed.
218pub fn gate_factor(signals: &[f32]) -> f32 {
219    signals.iter().copied().fold(0.0_f32, f32::max)
220}
221
222/// Memory formation factor: product of `(1 + signal)` clamped to `[0, 1]`.
223/// 0 means the area forms no new memory neurons.
224pub fn memory_formation_factor(signals: &[f32]) -> f32 {
225    multiplicative_factor(signals).clamp(0.0, 1.0)
226}
227
228/// Memory freeze: the area is frozen while the summed signal is above 0.
229pub fn memory_freeze_active(signals: &[f32]) -> bool {
230    signals.iter().sum::<f32>() > 0.0
231}
232
233/// Memory capture: the area is recording while the summed signal is above 0.
234pub fn memory_capture_active(signals: &[f32]) -> bool {
235    signals.iter().sum::<f32>() > 0.0
236}
237
238/// Sum of reward signals. Reward does not use the multiplicative factor.
239pub fn summed_reward(signals: &[f32]) -> f32 {
240    signals.iter().sum()
241}
242
243/// Scale a stored baseline and clamp to the parameter's valid range.
244///
245/// Leak and excitability are clamped to `[0, 1]`. Threshold, transmission
246/// gain, and learning rate stay non-negative. Reward is not a scaled parameter.
247pub fn scale_baseline(kind: ModulatorKind, baseline: f32, factor: f32) -> f32 {
248    let value = baseline * factor;
249    match kind {
250        ModulatorKind::Leak | ModulatorKind::FiringProbability => value.clamp(0.0, 1.0),
251        ModulatorKind::FiringThreshold
252        | ModulatorKind::TransmissionGain
253        | ModulatorKind::LearningRate
254        | ModulatorKind::Gate
255        | ModulatorKind::MemoryFormation
256        | ModulatorKind::MemoryFreeze
257        | ModulatorKind::MemoryCapture => value.max(0.0),
258        ModulatorKind::Reward => value,
259    }
260}
261
262#[cfg(test)]
263mod tests {
264    use super::*;
265
266    #[test]
267    fn silent_driver_contributes_nothing() {
268        assert_eq!(modulator_signal(30.0, false, false, 10.0, 10.0), 0.0);
269    }
270
271    #[test]
272    fn ungraded_firing_uses_full_magnitude() {
273        assert!((modulator_signal(30.0, true, false, 1.0, 10.0) - 0.3).abs() < 1e-6);
274        assert!((modulator_signal(-80.0, true, false, 1.0, 10.0) + 0.8).abs() < 1e-6);
275    }
276
277    #[test]
278    fn graded_firing_scales_with_membrane_potential_and_caps_at_one() {
279        let half = modulator_signal(30.0, true, true, 5.0, 10.0);
280        assert!((half - 0.15).abs() < 1e-6);
281        let capped = modulator_signal(30.0, true, true, 40.0, 10.0);
282        assert!((capped - 0.3).abs() < 1e-6);
283    }
284
285    #[test]
286    fn factors_multiply_and_reward_adds() {
287        let factor = multiplicative_factor(&[0.3, -0.5]);
288        assert!((factor - (1.3 * 0.5)).abs() < 1e-6);
289        assert!((summed_reward(&[0.3, -0.5]) + 0.2).abs() < 1e-6);
290    }
291
292    #[test]
293    fn leak_and_excitability_clamp_to_unit_interval() {
294        assert!((scale_baseline(ModulatorKind::Leak, 0.8, 2.0) - 1.0).abs() < 1e-6);
295        assert!((scale_baseline(ModulatorKind::FiringProbability, 0.2, 0.0) - 0.0).abs() < 1e-6);
296        assert!(scale_baseline(ModulatorKind::FiringThreshold, 2.0, 3.0) > 0.0);
297    }
298
299    #[test]
300    fn magnitude_below_minus_100_is_rejected() {
301        assert!(validate_instance_fields(-100.1, 1, false, None).is_err());
302        assert!(validate_instance_fields(-100.0, 1, false, None).is_ok());
303    }
304
305    #[test]
306    fn graded_requires_positive_full_scale() {
307        assert!(validate_instance_fields(10.0, 1, true, None).is_err());
308        assert!(validate_instance_fields(10.0, 1, true, Some(0.0)).is_err());
309        assert!(validate_instance_fields(10.0, 1, true, Some(4.0)).is_ok());
310    }
311
312    #[test]
313    fn spike_train_rejects_unlimited_consecutive_fire() {
314        assert!(validate_spike_train(true, 0).is_err());
315        assert!(validate_spike_train(true, 1).is_ok());
316        assert!(validate_spike_train(false, 0).is_ok());
317    }
318
319    #[test]
320    fn memory_freeze_is_area_level_and_active_above_zero() {
321        assert_eq!(
322            ModulatorKind::parse("memory.freeze").unwrap(),
323            ModulatorKind::MemoryFreeze
324        );
325        assert!(ModulatorKind::MemoryFreeze.is_area_level());
326        assert!(!ModulatorKind::MemoryFreeze.is_synaptic());
327        assert!(!memory_freeze_active(&[]));
328        assert!(!memory_freeze_active(&[0.0]));
329        assert!(memory_freeze_active(&[0.5]));
330    }
331
332    #[test]
333    fn memory_capture_is_area_level_and_active_above_zero() {
334        assert_eq!(
335            ModulatorKind::parse("memory.capture").unwrap(),
336            ModulatorKind::MemoryCapture
337        );
338        assert_eq!(ModulatorKind::MemoryCapture.as_str(), "memory.capture");
339        assert!(ModulatorKind::all().contains(&ModulatorKind::MemoryCapture));
340        assert!(ModulatorKind::MemoryCapture.is_area_level());
341        assert!(!ModulatorKind::MemoryCapture.is_synaptic());
342        assert!(!memory_capture_active(&[]));
343        assert!(!memory_capture_active(&[0.0]));
344        assert!(memory_capture_active(&[0.5]));
345    }
346
347    #[test]
348    fn type_strings_round_trip() {
349        for kind in ModulatorKind::all() {
350            assert_eq!(ModulatorKind::parse(kind.as_str()).unwrap(), *kind);
351        }
352    }
353
354    #[test]
355    fn gate_kind_is_synaptic_and_parses() {
356        assert_eq!(
357            ModulatorKind::parse("synaptic.gate").unwrap(),
358            ModulatorKind::Gate
359        );
360        assert_eq!(ModulatorKind::Gate.as_str(), "synaptic.gate");
361        assert!(ModulatorKind::Gate.is_synaptic());
362        assert!(!ModulatorKind::Gate.combines_by_addition());
363    }
364
365    #[test]
366    fn gate_factor_is_closed_when_silent_and_open_if_any_open() {
367        assert_eq!(gate_factor(&[0.0]), 0.0);
368        assert_eq!(gate_factor(&[0.0, 1.0]), 1.0);
369        assert!((gate_factor(&[0.5, 0.25]) - 0.5).abs() < 1e-6);
370    }
371
372    #[test]
373    fn memory_formation_is_area_level_and_clamped() {
374        assert_eq!(
375            ModulatorKind::parse("memory.formation").unwrap(),
376            ModulatorKind::MemoryFormation
377        );
378        assert!(ModulatorKind::MemoryFormation.is_area_level());
379        assert!(!ModulatorKind::MemoryFormation.is_synaptic());
380        assert!(!ModulatorKind::MemoryFormation.is_neuromodulator());
381        assert_eq!(memory_formation_factor(&[-1.0]), 0.0);
382        assert_eq!(memory_formation_factor(&[0.0]), 1.0);
383        assert_eq!(memory_formation_factor(&[0.5]), 1.0);
384        assert!((memory_formation_factor(&[-0.25]) - 0.75).abs() < 1e-6);
385        assert_eq!(memory_formation_factor(&[]), 1.0);
386    }
387}