feagi-evolutionary 0.0.63

Evolution and Genome Management - Genotype operations for FEAGI
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
// Copyright 2025 Neuraville Inc.
// SPDX-License-Identifier: Apache-2.0

//! Genome modulator instances.
//!
//! An instance is a named copy of a built-in [`ModulatorKind`] plus the cortical
//! id of the driver area that turns it on. The driver is either a 1x1x1 area the
//! instance owns, or an existing area it adopts. Areas and mapping rules subscribe
//! by instance id.

use feagi_structures::genomic::cortical_area::CorticalID;
use feagi_structures::genomic::{
    validate_instance_fields, ModulatorKind, ModulatorValidationError,
};
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::collections::HashMap;

use crate::types::{EvoError, EvoResult};

/// One user-defined modulator and the driver area that owns it.
#[derive(Debug, Clone, PartialEq)]
pub struct ModulatorInstance {
    pub kind: ModulatorKind,
    pub magnitude_percent: f32,
    pub effect_duration_bursts: u16,
    pub rest_bursts: u16,
    pub graded: bool,
    pub full_scale_potential: Option<f32>,
    pub driver_cortical_id: CorticalID,
}

impl ModulatorInstance {
    /// True when the driver is an existing area, not one created for this instance.
    /// An adopted driver keeps its own timing and is not deleted with the instance.
    pub fn adopts_driver(&self) -> bool {
        !self.driver_cortical_id.is_modulator_driver()
    }

    /// Reject fields that cannot produce a defined signal.
    pub fn validate(&self) -> Result<(), ModulatorValidationError> {
        validate_instance_fields(
            self.magnitude_percent,
            self.effect_duration_bursts,
            self.graded,
            self.full_scale_potential,
        )?;
        if self.kind == ModulatorKind::MemoryFreeze && self.magnitude_percent <= 0.0 {
            return Err(ModulatorValidationError(
                "memory.freeze requires magnitude_percent > 0".to_string(),
            ));
        }
        if self.kind == ModulatorKind::MemoryCapture
            && !(1.0..=100.0).contains(&self.magnitude_percent)
        {
            return Err(ModulatorValidationError(format!(
                "memory.capture requires magnitude_percent between 1 and 100 (got {})",
                self.magnitude_percent
            )));
        }
        Ok(())
    }

    /// Hierarchical genome object for this instance.
    pub fn to_json(&self) -> Value {
        let mut object = serde_json::Map::new();
        object.insert("type".to_string(), json!(self.kind.as_str()));
        object.insert(
            "magnitude_percent".to_string(),
            json!(self.magnitude_percent),
        );
        object.insert(
            "effect_duration_bursts".to_string(),
            json!(self.effect_duration_bursts),
        );
        object.insert("rest_bursts".to_string(), json!(self.rest_bursts));
        object.insert("graded".to_string(), json!(self.graded));
        if let Some(scale) = self.full_scale_potential {
            object.insert("full_scale_potential".to_string(), json!(scale));
        }
        object.insert(
            "driver_cortical_id".to_string(),
            json!(self.driver_cortical_id.as_base_64()),
        );
        Value::Object(object)
    }
}

/// All modulator instances in a genome, keyed by instance id.
#[derive(Debug, Clone, Default)]
pub struct ModulatorRegistry {
    modulators: HashMap<String, ModulatorInstance>,
}

impl ModulatorRegistry {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn insert(&mut self, id: String, instance: ModulatorInstance) {
        self.modulators.insert(id, instance);
    }

    pub fn get(&self, id: &str) -> Option<&ModulatorInstance> {
        self.modulators.get(id)
    }

    pub fn get_mut(&mut self, id: &str) -> Option<&mut ModulatorInstance> {
        self.modulators.get_mut(id)
    }

    pub fn contains(&self, id: &str) -> bool {
        self.modulators.contains_key(id)
    }

    pub fn remove(&mut self, id: &str) -> Option<ModulatorInstance> {
        self.modulators.remove(id)
    }

    pub fn rename(&mut self, old_id: &str, new_id: String) -> bool {
        if let Some(instance) = self.modulators.remove(old_id) {
            self.modulators.insert(new_id, instance);
            true
        } else {
            false
        }
    }

    pub fn len(&self) -> usize {
        self.modulators.len()
    }

    pub fn is_empty(&self) -> bool {
        self.modulators.is_empty()
    }

    pub fn ids(&self) -> Vec<String> {
        let mut ids: Vec<String> = self.modulators.keys().cloned().collect();
        ids.sort();
        ids
    }

    pub fn iter(&self) -> impl Iterator<Item = (&String, &ModulatorInstance)> {
        self.modulators.iter()
    }

    /// Hierarchical `modulators` object.
    pub fn to_json(&self) -> Value {
        let mut object = serde_json::Map::new();
        let mut ids: Vec<&String> = self.modulators.keys().collect();
        ids.sort();
        for id in ids {
            if let Some(instance) = self.modulators.get(id) {
                object.insert(id.clone(), instance.to_json());
            }
        }
        Value::Object(object)
    }
}

/// Parse the top-level `modulators` object. An absent object is an empty registry.
pub fn parse_modulator_registry(value: Option<&Value>) -> EvoResult<ModulatorRegistry> {
    let Some(value) = value else {
        return Ok(ModulatorRegistry::new());
    };
    let Some(object) = value.as_object() else {
        return Err(EvoError::InvalidGenome(
            "modulators must be an object".to_string(),
        ));
    };
    let mut registry = ModulatorRegistry::new();
    for (id, body) in object {
        registry.insert(id.clone(), parse_modulator_instance(id, body)?);
    }
    Ok(registry)
}

fn parse_modulator_instance(id: &str, body: &Value) -> EvoResult<ModulatorInstance> {
    let object = body
        .as_object()
        .ok_or_else(|| EvoError::InvalidGenome(format!("modulator '{id}' must be an object")))?;
    let type_name = object
        .get("type")
        .and_then(|v| v.as_str())
        .ok_or_else(|| EvoError::InvalidGenome(format!("modulator '{id}' is missing type")))?;
    let kind = ModulatorKind::parse(type_name)
        .map_err(|err| EvoError::InvalidGenome(format!("modulator '{id}': {err}")))?;
    let magnitude_percent = object
        .get("magnitude_percent")
        .and_then(|v| v.as_f64())
        .ok_or_else(|| {
            EvoError::InvalidGenome(format!("modulator '{id}' is missing magnitude_percent"))
        })? as f32;
    let effect_duration_bursts = object
        .get("effect_duration_bursts")
        .and_then(|v| v.as_u64())
        .ok_or_else(|| {
            EvoError::InvalidGenome(format!(
                "modulator '{id}' is missing effect_duration_bursts"
            ))
        })?;
    if effect_duration_bursts > u16::MAX as u64 {
        return Err(EvoError::InvalidGenome(format!(
            "modulator '{id}' effect_duration_bursts exceeds u16"
        )));
    }
    let rest_bursts = object
        .get("rest_bursts")
        .and_then(|v| v.as_u64())
        .unwrap_or(0);
    if rest_bursts > u16::MAX as u64 {
        return Err(EvoError::InvalidGenome(format!(
            "modulator '{id}' rest_bursts exceeds u16"
        )));
    }
    let graded = object
        .get("graded")
        .and_then(|v| v.as_bool())
        .unwrap_or(false);
    let full_scale_potential = object
        .get("full_scale_potential")
        .and_then(|v| v.as_f64())
        .map(|v| v as f32);
    let driver = object
        .get("driver_cortical_id")
        .and_then(|v| v.as_str())
        .ok_or_else(|| {
            EvoError::InvalidGenome(format!("modulator '{id}' is missing driver_cortical_id"))
        })?;
    let driver_cortical_id = CorticalID::try_from_base_64(driver)
        .map_err(|err| EvoError::InvalidGenome(format!("modulator '{id}' driver id: {err}")))?;
    let instance = ModulatorInstance {
        kind,
        magnitude_percent,
        effect_duration_bursts: effect_duration_bursts as u16,
        rest_bursts: rest_bursts as u16,
        graded,
        full_scale_potential,
        driver_cortical_id,
    };
    instance
        .validate()
        .map_err(|err| EvoError::InvalidGenome(format!("modulator '{id}': {err}")))?;
    Ok(instance)
}

/// Locked neuron properties the instance writes onto its driver area.
pub fn driver_locked_properties(instance: &ModulatorInstance) -> HashMap<String, Value> {
    let mut properties = HashMap::new();
    properties.insert("refractory_period".to_string(), json!(0));
    properties.insert("spike_train".to_string(), json!(true));
    properties.insert(
        "consecutive_fire_cnt_max".to_string(),
        json!(instance.effect_duration_bursts),
    );
    properties.insert(
        "consecutive_fire_limit".to_string(),
        json!(instance.effect_duration_bursts),
    );
    properties.insert("snooze_length".to_string(), json!(instance.rest_bursts));
    properties.insert("snooze_period".to_string(), json!(instance.rest_bursts));
    properties.insert("mp_driven_psp".to_string(), json!(instance.graded));
    properties.insert("cortical_group".to_string(), json!("MODULATOR"));
    if let Some(scale) = instance.full_scale_potential {
        properties.insert("full_scale_potential".to_string(), json!(scale));
    }
    properties
}

/// Property names the API and Brain Visualizer must leave read-only on a driver.
pub fn driver_locked_property_names() -> &'static [&'static str] {
    &[
        "refractory_period",
        "spike_train",
        "consecutive_fire_cnt_max",
        "consecutive_fire_limit",
        "neuron_consecutive_fire_count",
        "consecutive_fire_count",
        "snooze_length",
        "snooze_period",
        "mp_driven_psp",
    ]
}

/// Request body shape shared by create and update. Serde is used by the API layer.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ModulatorWrite {
    #[serde(rename = "type")]
    pub kind: String,
    pub magnitude_percent: f32,
    pub effect_duration_bursts: u16,
    pub rest_bursts: u16,
    #[serde(default)]
    pub graded: bool,
    #[serde(default)]
    pub full_scale_potential: Option<f32>,
    /// Existing area to adopt as the driver. Absent creates a new driver area.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub driver_cortical_id: Option<String>,
}

impl ModulatorWrite {
    /// An adopted driver fires on its own schedule, so the instance cannot add duration or rest.
    pub fn validate_adopted_timing(&self) -> EvoResult<()> {
        if self.effect_duration_bursts != 1 || self.rest_bursts != 0 {
            return Err(EvoError::InvalidGenome(
                "a modulator on an existing area takes its timing from that area: \
                 effect_duration_bursts must be 1 and rest_bursts 0"
                    .to_string(),
            ));
        }
        Ok(())
    }

    pub fn into_instance(self, driver_cortical_id: CorticalID) -> EvoResult<ModulatorInstance> {
        let kind = ModulatorKind::parse(&self.kind).map_err(EvoError::InvalidGenome)?;
        let instance = ModulatorInstance {
            kind,
            magnitude_percent: self.magnitude_percent,
            effect_duration_bursts: self.effect_duration_bursts,
            rest_bursts: self.rest_bursts,
            graded: self.graded,
            full_scale_potential: self.full_scale_potential,
            driver_cortical_id,
        };
        instance
            .validate()
            .map_err(|err| EvoError::InvalidGenome(err.0))?;
        Ok(instance)
    }
}

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

    #[test]
    fn memory_formation_instance_round_trips_through_genome_json() {
        let mut registry = ModulatorRegistry::new();
        registry.insert(
            "no_new_memory".to_string(),
            ModulatorInstance {
                kind: ModulatorKind::MemoryFormation,
                magnitude_percent: -100.0,
                effect_duration_bursts: 1,
                rest_bursts: 0,
                graded: false,
                full_scale_potential: None,
                driver_cortical_id: CorticalID::modulator_driver(0),
            },
        );
        let json = registry.to_json();
        assert_eq!(json["no_new_memory"]["type"], "memory.formation");
        let parsed = parse_modulator_registry(Some(&json)).expect("parse");
        let instance = parsed.get("no_new_memory").expect("instance");
        assert_eq!(instance.kind, ModulatorKind::MemoryFormation);
        assert_eq!(instance.magnitude_percent, -100.0);
        assert_eq!(parsed.to_json(), json);
    }
}

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

    fn freeze_instance(magnitude_percent: f32) -> ModulatorInstance {
        ModulatorInstance {
            kind: ModulatorKind::MemoryFreeze,
            magnitude_percent,
            effect_duration_bursts: 1,
            rest_bursts: 0,
            graded: false,
            full_scale_potential: None,
            driver_cortical_id: CorticalID::modulator_driver(1),
        }
    }

    #[test]
    fn memory_freeze_rejects_non_positive_magnitude() {
        assert!(freeze_instance(0.0).validate().is_err());
        assert!(freeze_instance(-50.0).validate().is_err());
        assert!(freeze_instance(100.0).validate().is_ok());
    }

    #[test]
    fn memory_freeze_round_trips_through_genome_json() {
        let mut registry = ModulatorRegistry::new();
        registry.insert("hold".to_string(), freeze_instance(100.0));
        let parsed = parse_modulator_registry(Some(&registry.to_json())).unwrap();
        assert_eq!(
            parsed.get("hold").unwrap().kind,
            ModulatorKind::MemoryFreeze
        );
    }
}

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

    fn capture_instance(magnitude_percent: f32) -> ModulatorInstance {
        ModulatorInstance {
            kind: ModulatorKind::MemoryCapture,
            magnitude_percent,
            effect_duration_bursts: 1,
            rest_bursts: 0,
            graded: false,
            full_scale_potential: None,
            driver_cortical_id: CorticalID::modulator_driver(1),
        }
    }

    #[test]
    fn memory_capture_magnitude_must_be_one_to_one_hundred() {
        assert!(capture_instance(0.0).validate().is_err());
        assert!(capture_instance(-1.0).validate().is_err());
        assert!(capture_instance(101.0).validate().is_err());
        assert!(capture_instance(1.0).validate().is_ok());
        assert!(capture_instance(100.0).validate().is_ok());
        let message = capture_instance(0.0).validate().unwrap_err().to_string();
        assert!(message.contains("between 1 and 100"), "{message}");
    }

    #[test]
    fn memory_capture_round_trips_through_genome_json() {
        let mut registry = ModulatorRegistry::new();
        registry.insert("rec".to_string(), capture_instance(50.0));
        let parsed = parse_modulator_registry(Some(&registry.to_json())).unwrap();
        assert_eq!(
            parsed.get("rec").unwrap().kind,
            ModulatorKind::MemoryCapture
        );
    }
}