Skip to main content

feagi_evolutionary/
modulators.rs

1// Copyright 2025 Neuraville Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Genome modulator instances.
5//!
6//! An instance is a named copy of a built-in [`ModulatorKind`] plus the cortical
7//! id of the driver area that turns it on. The driver is either a 1x1x1 area the
8//! instance owns, or an existing area it adopts. Areas and mapping rules subscribe
9//! by instance id.
10
11use feagi_structures::genomic::cortical_area::CorticalID;
12use feagi_structures::genomic::{
13    validate_instance_fields, ModulatorKind, ModulatorValidationError,
14};
15use serde::{Deserialize, Serialize};
16use serde_json::{json, Value};
17use std::collections::HashMap;
18
19use crate::types::{EvoError, EvoResult};
20
21/// One user-defined modulator and the driver area that owns it.
22#[derive(Debug, Clone, PartialEq)]
23pub struct ModulatorInstance {
24    pub kind: ModulatorKind,
25    pub magnitude_percent: f32,
26    pub effect_duration_bursts: u16,
27    pub rest_bursts: u16,
28    pub graded: bool,
29    pub full_scale_potential: Option<f32>,
30    pub driver_cortical_id: CorticalID,
31}
32
33impl ModulatorInstance {
34    /// True when the driver is an existing area, not one created for this instance.
35    /// An adopted driver keeps its own timing and is not deleted with the instance.
36    pub fn adopts_driver(&self) -> bool {
37        !self.driver_cortical_id.is_modulator_driver()
38    }
39
40    /// Reject fields that cannot produce a defined signal.
41    pub fn validate(&self) -> Result<(), ModulatorValidationError> {
42        validate_instance_fields(
43            self.magnitude_percent,
44            self.effect_duration_bursts,
45            self.graded,
46            self.full_scale_potential,
47        )?;
48        if self.kind == ModulatorKind::MemoryFreeze && self.magnitude_percent <= 0.0 {
49            return Err(ModulatorValidationError(
50                "memory.freeze requires magnitude_percent > 0".to_string(),
51            ));
52        }
53        if self.kind == ModulatorKind::MemoryCapture
54            && !(1.0..=100.0).contains(&self.magnitude_percent)
55        {
56            return Err(ModulatorValidationError(format!(
57                "memory.capture requires magnitude_percent between 1 and 100 (got {})",
58                self.magnitude_percent
59            )));
60        }
61        Ok(())
62    }
63
64    /// Hierarchical genome object for this instance.
65    pub fn to_json(&self) -> Value {
66        let mut object = serde_json::Map::new();
67        object.insert("type".to_string(), json!(self.kind.as_str()));
68        object.insert(
69            "magnitude_percent".to_string(),
70            json!(self.magnitude_percent),
71        );
72        object.insert(
73            "effect_duration_bursts".to_string(),
74            json!(self.effect_duration_bursts),
75        );
76        object.insert("rest_bursts".to_string(), json!(self.rest_bursts));
77        object.insert("graded".to_string(), json!(self.graded));
78        if let Some(scale) = self.full_scale_potential {
79            object.insert("full_scale_potential".to_string(), json!(scale));
80        }
81        object.insert(
82            "driver_cortical_id".to_string(),
83            json!(self.driver_cortical_id.as_base_64()),
84        );
85        Value::Object(object)
86    }
87}
88
89/// All modulator instances in a genome, keyed by instance id.
90#[derive(Debug, Clone, Default)]
91pub struct ModulatorRegistry {
92    modulators: HashMap<String, ModulatorInstance>,
93}
94
95impl ModulatorRegistry {
96    pub fn new() -> Self {
97        Self::default()
98    }
99
100    pub fn insert(&mut self, id: String, instance: ModulatorInstance) {
101        self.modulators.insert(id, instance);
102    }
103
104    pub fn get(&self, id: &str) -> Option<&ModulatorInstance> {
105        self.modulators.get(id)
106    }
107
108    pub fn get_mut(&mut self, id: &str) -> Option<&mut ModulatorInstance> {
109        self.modulators.get_mut(id)
110    }
111
112    pub fn contains(&self, id: &str) -> bool {
113        self.modulators.contains_key(id)
114    }
115
116    pub fn remove(&mut self, id: &str) -> Option<ModulatorInstance> {
117        self.modulators.remove(id)
118    }
119
120    pub fn rename(&mut self, old_id: &str, new_id: String) -> bool {
121        if let Some(instance) = self.modulators.remove(old_id) {
122            self.modulators.insert(new_id, instance);
123            true
124        } else {
125            false
126        }
127    }
128
129    pub fn len(&self) -> usize {
130        self.modulators.len()
131    }
132
133    pub fn is_empty(&self) -> bool {
134        self.modulators.is_empty()
135    }
136
137    pub fn ids(&self) -> Vec<String> {
138        let mut ids: Vec<String> = self.modulators.keys().cloned().collect();
139        ids.sort();
140        ids
141    }
142
143    pub fn iter(&self) -> impl Iterator<Item = (&String, &ModulatorInstance)> {
144        self.modulators.iter()
145    }
146
147    /// Hierarchical `modulators` object.
148    pub fn to_json(&self) -> Value {
149        let mut object = serde_json::Map::new();
150        let mut ids: Vec<&String> = self.modulators.keys().collect();
151        ids.sort();
152        for id in ids {
153            if let Some(instance) = self.modulators.get(id) {
154                object.insert(id.clone(), instance.to_json());
155            }
156        }
157        Value::Object(object)
158    }
159}
160
161/// Parse the top-level `modulators` object. An absent object is an empty registry.
162pub fn parse_modulator_registry(value: Option<&Value>) -> EvoResult<ModulatorRegistry> {
163    let Some(value) = value else {
164        return Ok(ModulatorRegistry::new());
165    };
166    let Some(object) = value.as_object() else {
167        return Err(EvoError::InvalidGenome(
168            "modulators must be an object".to_string(),
169        ));
170    };
171    let mut registry = ModulatorRegistry::new();
172    for (id, body) in object {
173        registry.insert(id.clone(), parse_modulator_instance(id, body)?);
174    }
175    Ok(registry)
176}
177
178fn parse_modulator_instance(id: &str, body: &Value) -> EvoResult<ModulatorInstance> {
179    let object = body
180        .as_object()
181        .ok_or_else(|| EvoError::InvalidGenome(format!("modulator '{id}' must be an object")))?;
182    let type_name = object
183        .get("type")
184        .and_then(|v| v.as_str())
185        .ok_or_else(|| EvoError::InvalidGenome(format!("modulator '{id}' is missing type")))?;
186    let kind = ModulatorKind::parse(type_name)
187        .map_err(|err| EvoError::InvalidGenome(format!("modulator '{id}': {err}")))?;
188    let magnitude_percent = object
189        .get("magnitude_percent")
190        .and_then(|v| v.as_f64())
191        .ok_or_else(|| {
192            EvoError::InvalidGenome(format!("modulator '{id}' is missing magnitude_percent"))
193        })? as f32;
194    let effect_duration_bursts = object
195        .get("effect_duration_bursts")
196        .and_then(|v| v.as_u64())
197        .ok_or_else(|| {
198            EvoError::InvalidGenome(format!(
199                "modulator '{id}' is missing effect_duration_bursts"
200            ))
201        })?;
202    if effect_duration_bursts > u16::MAX as u64 {
203        return Err(EvoError::InvalidGenome(format!(
204            "modulator '{id}' effect_duration_bursts exceeds u16"
205        )));
206    }
207    let rest_bursts = object
208        .get("rest_bursts")
209        .and_then(|v| v.as_u64())
210        .unwrap_or(0);
211    if rest_bursts > u16::MAX as u64 {
212        return Err(EvoError::InvalidGenome(format!(
213            "modulator '{id}' rest_bursts exceeds u16"
214        )));
215    }
216    let graded = object
217        .get("graded")
218        .and_then(|v| v.as_bool())
219        .unwrap_or(false);
220    let full_scale_potential = object
221        .get("full_scale_potential")
222        .and_then(|v| v.as_f64())
223        .map(|v| v as f32);
224    let driver = object
225        .get("driver_cortical_id")
226        .and_then(|v| v.as_str())
227        .ok_or_else(|| {
228            EvoError::InvalidGenome(format!("modulator '{id}' is missing driver_cortical_id"))
229        })?;
230    let driver_cortical_id = CorticalID::try_from_base_64(driver)
231        .map_err(|err| EvoError::InvalidGenome(format!("modulator '{id}' driver id: {err}")))?;
232    let instance = ModulatorInstance {
233        kind,
234        magnitude_percent,
235        effect_duration_bursts: effect_duration_bursts as u16,
236        rest_bursts: rest_bursts as u16,
237        graded,
238        full_scale_potential,
239        driver_cortical_id,
240    };
241    instance
242        .validate()
243        .map_err(|err| EvoError::InvalidGenome(format!("modulator '{id}': {err}")))?;
244    Ok(instance)
245}
246
247/// Locked neuron properties the instance writes onto its driver area.
248pub fn driver_locked_properties(instance: &ModulatorInstance) -> HashMap<String, Value> {
249    let mut properties = HashMap::new();
250    properties.insert("refractory_period".to_string(), json!(0));
251    properties.insert("spike_train".to_string(), json!(true));
252    properties.insert(
253        "consecutive_fire_cnt_max".to_string(),
254        json!(instance.effect_duration_bursts),
255    );
256    properties.insert(
257        "consecutive_fire_limit".to_string(),
258        json!(instance.effect_duration_bursts),
259    );
260    properties.insert("snooze_length".to_string(), json!(instance.rest_bursts));
261    properties.insert("snooze_period".to_string(), json!(instance.rest_bursts));
262    properties.insert("mp_driven_psp".to_string(), json!(instance.graded));
263    properties.insert("cortical_group".to_string(), json!("MODULATOR"));
264    if let Some(scale) = instance.full_scale_potential {
265        properties.insert("full_scale_potential".to_string(), json!(scale));
266    }
267    properties
268}
269
270/// Property names the API and Brain Visualizer must leave read-only on a driver.
271pub fn driver_locked_property_names() -> &'static [&'static str] {
272    &[
273        "refractory_period",
274        "spike_train",
275        "consecutive_fire_cnt_max",
276        "consecutive_fire_limit",
277        "neuron_consecutive_fire_count",
278        "consecutive_fire_count",
279        "snooze_length",
280        "snooze_period",
281        "mp_driven_psp",
282    ]
283}
284
285/// Request body shape shared by create and update. Serde is used by the API layer.
286#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
287pub struct ModulatorWrite {
288    #[serde(rename = "type")]
289    pub kind: String,
290    pub magnitude_percent: f32,
291    pub effect_duration_bursts: u16,
292    pub rest_bursts: u16,
293    #[serde(default)]
294    pub graded: bool,
295    #[serde(default)]
296    pub full_scale_potential: Option<f32>,
297    /// Existing area to adopt as the driver. Absent creates a new driver area.
298    #[serde(default, skip_serializing_if = "Option::is_none")]
299    pub driver_cortical_id: Option<String>,
300}
301
302impl ModulatorWrite {
303    /// An adopted driver fires on its own schedule, so the instance cannot add duration or rest.
304    pub fn validate_adopted_timing(&self) -> EvoResult<()> {
305        if self.effect_duration_bursts != 1 || self.rest_bursts != 0 {
306            return Err(EvoError::InvalidGenome(
307                "a modulator on an existing area takes its timing from that area: \
308                 effect_duration_bursts must be 1 and rest_bursts 0"
309                    .to_string(),
310            ));
311        }
312        Ok(())
313    }
314
315    pub fn into_instance(self, driver_cortical_id: CorticalID) -> EvoResult<ModulatorInstance> {
316        let kind = ModulatorKind::parse(&self.kind).map_err(EvoError::InvalidGenome)?;
317        let instance = ModulatorInstance {
318            kind,
319            magnitude_percent: self.magnitude_percent,
320            effect_duration_bursts: self.effect_duration_bursts,
321            rest_bursts: self.rest_bursts,
322            graded: self.graded,
323            full_scale_potential: self.full_scale_potential,
324            driver_cortical_id,
325        };
326        instance
327            .validate()
328            .map_err(|err| EvoError::InvalidGenome(err.0))?;
329        Ok(instance)
330    }
331}
332
333#[cfg(test)]
334mod memory_formation_tests {
335    use super::*;
336
337    #[test]
338    fn memory_formation_instance_round_trips_through_genome_json() {
339        let mut registry = ModulatorRegistry::new();
340        registry.insert(
341            "no_new_memory".to_string(),
342            ModulatorInstance {
343                kind: ModulatorKind::MemoryFormation,
344                magnitude_percent: -100.0,
345                effect_duration_bursts: 1,
346                rest_bursts: 0,
347                graded: false,
348                full_scale_potential: None,
349                driver_cortical_id: CorticalID::modulator_driver(0),
350            },
351        );
352        let json = registry.to_json();
353        assert_eq!(json["no_new_memory"]["type"], "memory.formation");
354        let parsed = parse_modulator_registry(Some(&json)).expect("parse");
355        let instance = parsed.get("no_new_memory").expect("instance");
356        assert_eq!(instance.kind, ModulatorKind::MemoryFormation);
357        assert_eq!(instance.magnitude_percent, -100.0);
358        assert_eq!(parsed.to_json(), json);
359    }
360}
361
362#[cfg(test)]
363mod memory_freeze_tests {
364    use super::*;
365
366    fn freeze_instance(magnitude_percent: f32) -> ModulatorInstance {
367        ModulatorInstance {
368            kind: ModulatorKind::MemoryFreeze,
369            magnitude_percent,
370            effect_duration_bursts: 1,
371            rest_bursts: 0,
372            graded: false,
373            full_scale_potential: None,
374            driver_cortical_id: CorticalID::modulator_driver(1),
375        }
376    }
377
378    #[test]
379    fn memory_freeze_rejects_non_positive_magnitude() {
380        assert!(freeze_instance(0.0).validate().is_err());
381        assert!(freeze_instance(-50.0).validate().is_err());
382        assert!(freeze_instance(100.0).validate().is_ok());
383    }
384
385    #[test]
386    fn memory_freeze_round_trips_through_genome_json() {
387        let mut registry = ModulatorRegistry::new();
388        registry.insert("hold".to_string(), freeze_instance(100.0));
389        let parsed = parse_modulator_registry(Some(&registry.to_json())).unwrap();
390        assert_eq!(
391            parsed.get("hold").unwrap().kind,
392            ModulatorKind::MemoryFreeze
393        );
394    }
395}
396
397#[cfg(test)]
398mod memory_capture_tests {
399    use super::*;
400
401    fn capture_instance(magnitude_percent: f32) -> ModulatorInstance {
402        ModulatorInstance {
403            kind: ModulatorKind::MemoryCapture,
404            magnitude_percent,
405            effect_duration_bursts: 1,
406            rest_bursts: 0,
407            graded: false,
408            full_scale_potential: None,
409            driver_cortical_id: CorticalID::modulator_driver(1),
410        }
411    }
412
413    #[test]
414    fn memory_capture_magnitude_must_be_one_to_one_hundred() {
415        assert!(capture_instance(0.0).validate().is_err());
416        assert!(capture_instance(-1.0).validate().is_err());
417        assert!(capture_instance(101.0).validate().is_err());
418        assert!(capture_instance(1.0).validate().is_ok());
419        assert!(capture_instance(100.0).validate().is_ok());
420        let message = capture_instance(0.0).validate().unwrap_err().to_string();
421        assert!(message.contains("between 1 and 100"), "{message}");
422    }
423
424    #[test]
425    fn memory_capture_round_trips_through_genome_json() {
426        let mut registry = ModulatorRegistry::new();
427        registry.insert("rec".to_string(), capture_instance(50.0));
428        let parsed = parse_modulator_registry(Some(&registry.to_json())).unwrap();
429        assert_eq!(
430            parsed.get("rec").unwrap().kind,
431            ModulatorKind::MemoryCapture
432        );
433    }
434}