1use feagi_structures::genomic::classifiers::Classifier;
15use feagi_structures::genomic::cortical_area::CorticalArea;
16use feagi_structures::genomic::cortical_area::CorticalID;
17use feagi_structures::genomic::BrainRegion;
18use serde::{Deserialize, Serialize};
19use std::collections::HashMap;
20
21#[derive(Debug, Clone)]
23pub struct RuntimeGenome {
24 pub metadata: GenomeMetadata,
26
27 pub cortical_areas: HashMap<CorticalID, CorticalArea>,
29
30 pub brain_regions: HashMap<String, BrainRegion>,
32
33 pub classifiers: HashMap<String, Classifier>,
36
37 pub morphologies: MorphologyRegistry,
39
40 pub modulators: crate::modulators::ModulatorRegistry,
42
43 pub physiology: PhysiologyConfig,
45
46 pub signatures: GenomeSignatures,
48
49 pub stats: GenomeStats,
51
52 pub change_history: Vec<serde_json::Value>,
57}
58
59impl RuntimeGenome {
60 pub fn apply_classifier_required_mappings(&mut self) -> usize {
66 let mut added = 0usize;
67 for classifier in self.classifiers.values() {
68 let Some(associative_window) =
69 CorticalID::try_from_base_64(&classifier.sample_memory_id)
70 .ok()
71 .and_then(|id| self.cortical_areas.get(&id))
72 .and_then(|area| crate::extract_memory_properties(&area.properties))
73 .map(|props| props.temporal_depth)
74 else {
75 continue;
76 };
77 for mapping in classifier.required_mappings() {
78 let Ok(dst_id) = CorticalID::try_from_base_64(&mapping.dst_area_id) else {
79 continue;
80 };
81 if !self.cortical_areas.contains_key(&dst_id) {
82 continue;
83 }
84 let Ok(src_id) = CorticalID::try_from_base_64(&mapping.src_area_id) else {
85 continue;
86 };
87 let Some(src_area) = self.cortical_areas.get_mut(&src_id) else {
88 continue;
89 };
90 let Some(mapping_dst) = src_area
91 .properties
92 .entry("cortical_mapping_dst".to_string())
93 .or_insert_with(|| serde_json::json!({}))
94 .as_object_mut()
95 else {
96 continue;
97 };
98 let Some(rules) = mapping_dst
99 .entry(mapping.dst_area_id.clone())
100 .or_insert_with(|| serde_json::json!([]))
101 .as_array_mut()
102 else {
103 continue;
104 };
105 let present = rules.iter().any(|rule| {
106 rule.get("morphology_id").and_then(|v| v.as_str())
107 == Some(mapping.morphology_id.as_str())
108 });
109 if present {
110 continue;
111 }
112 rules.push(
113 feagi_structures::genomic::classifiers::classifier_mapping_rule(
114 &mapping.morphology_id,
115 associative_window,
116 ),
117 );
118 added += 1;
119 }
120 }
121 added
122 }
123}
124
125#[derive(Debug, Clone, Serialize, Deserialize)]
127pub struct GenomeMetadata {
128 pub genome_id: String,
129 pub genome_title: String,
130 pub genome_description: String,
131 pub version: String,
132 pub timestamp: f64, #[serde(skip_serializing_if = "Option::is_none")]
137 pub brain_regions_root: Option<String>,
138}
139
140#[derive(Debug, Clone, Default)]
142pub struct MorphologyRegistry {
143 morphologies: HashMap<String, Morphology>,
145}
146
147impl MorphologyRegistry {
148 pub fn new() -> Self {
150 Self::default()
151 }
152
153 pub fn add_morphology(&mut self, id: String, morphology: Morphology) {
155 self.morphologies.insert(id, morphology);
156 }
157
158 pub fn get(&self, id: &str) -> Option<&Morphology> {
160 self.morphologies.get(id)
161 }
162
163 pub fn contains(&self, id: &str) -> bool {
165 self.morphologies.contains_key(id)
166 }
167
168 pub fn morphology_ids(&self) -> Vec<String> {
170 self.morphologies.keys().cloned().collect()
171 }
172
173 pub fn remove_morphology(&mut self, id: &str) -> bool {
177 self.morphologies.remove(id).is_some()
178 }
179
180 pub fn count(&self) -> usize {
182 self.morphologies.len()
183 }
184
185 pub fn iter(&self) -> impl Iterator<Item = (&String, &Morphology)> {
187 self.morphologies.iter()
188 }
189}
190
191#[derive(Debug, Clone, Serialize, Deserialize)]
193pub struct Morphology {
194 pub morphology_type: MorphologyType,
196
197 pub parameters: MorphologyParameters,
199
200 pub class: String,
202}
203
204#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
206#[serde(rename_all = "lowercase")]
207pub enum MorphologyType {
208 Vectors,
210
211 Patterns,
213
214 Functions,
216
217 Composite,
219}
220
221#[derive(Debug, Clone, Serialize, Deserialize)]
223#[serde(untagged)]
224pub enum MorphologyParameters {
225 Vectors { vectors: Vec<[i32; 3]> },
227
228 Patterns {
230 patterns: Vec<[Vec<PatternElement>; 2]>,
231 },
232
233 Functions {},
235
236 Composite {
238 src_seed: [u32; 3],
239 src_pattern: Vec<[i32; 2]>,
240 mapper_morphology: String,
241 },
242}
243
244#[derive(Debug, Clone, PartialEq, Eq)]
246pub enum PatternElement {
247 Value(i32),
249 Wildcard, Skip, Exclude, DirectionPositive, DirectionNegative, DirectionPositiveInclusive, DirectionNegativeInclusive, Offset(i32), Range(i32, i32), AbsoluteRange(i32, i32), }
270
271impl Serialize for PatternElement {
273 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
274 where
275 S: serde::Serializer,
276 {
277 match self {
278 PatternElement::Value(v) => serializer.serialize_i32(*v),
279 PatternElement::Wildcard => serializer.serialize_str("*"),
280 PatternElement::Skip => serializer.serialize_str("?"),
281 PatternElement::Exclude => serializer.serialize_str("!"),
282 PatternElement::DirectionPositive => serializer.serialize_str("?+"),
283 PatternElement::DirectionNegative => serializer.serialize_str("?-"),
284 PatternElement::DirectionPositiveInclusive => serializer.serialize_str("?+="),
285 PatternElement::DirectionNegativeInclusive => serializer.serialize_str("?-="),
286 PatternElement::Offset(off) => {
287 if *off >= 0 {
288 serializer.serialize_str(&format!("?+{}", off))
289 } else {
290 serializer.serialize_str(&format!("?{}", off))
291 }
292 }
293 PatternElement::Range(lo, hi) => {
294 let lo_str = if *lo >= 0 {
295 format!("?+{}", lo)
296 } else {
297 format!("?{}", lo)
298 };
299 let hi_str = if *hi >= 0 {
300 format!("?+{}", hi)
301 } else {
302 format!("?{}", hi)
303 };
304 serializer.serialize_str(&format!("{}:{}", lo_str, hi_str))
305 }
306 PatternElement::AbsoluteRange(lo, hi) => {
307 serializer.serialize_str(&format!("{}..{}", lo, hi))
308 }
309 }
310 }
311}
312
313impl<'de> Deserialize<'de> for PatternElement {
315 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
316 where
317 D: serde::Deserializer<'de>,
318 {
319 let value = serde_json::Value::deserialize(deserializer)?;
320 match value {
321 serde_json::Value::Number(n) => {
322 if let Some(i) = n.as_i64() {
323 Ok(PatternElement::Value(i as i32))
324 } else {
325 Err(serde::de::Error::custom(
326 "Pattern element must be an integer",
327 ))
328 }
329 }
330 serde_json::Value::String(s) => Self::parse_string(&s)
331 .ok_or_else(|| serde::de::Error::custom(format!("Unknown pattern element: {}", s))),
332 _ => Err(serde::de::Error::custom(
333 "Pattern element must be number or string",
334 )),
335 }
336 }
337}
338
339impl PatternElement {
340 pub fn parse_string(s: &str) -> Option<Self> {
342 match s {
343 "*" => Some(PatternElement::Wildcard),
344 "?" => Some(PatternElement::Skip),
345 "!" => Some(PatternElement::Exclude),
346 "?+" => Some(PatternElement::DirectionPositive),
347 "?-" => Some(PatternElement::DirectionNegative),
348 "?+=" => Some(PatternElement::DirectionPositiveInclusive),
349 "?-=" => Some(PatternElement::DirectionNegativeInclusive),
350 _ => {
351 if let Some(range) = Self::try_parse_range(s) {
352 return Some(range);
353 }
354 if let Some(abs_range) = Self::try_parse_absolute_range(s) {
355 return Some(abs_range);
356 }
357 if let Some(offset) = Self::try_parse_offset(s) {
358 return Some(offset);
359 }
360 None
361 }
362 }
363 }
364
365 fn try_parse_range(s: &str) -> Option<Self> {
366 let parts: Vec<&str> = s.split(':').collect();
367 if parts.len() != 2 {
368 return None;
369 }
370 let lo = Self::extract_relative_offset(parts[0])?;
371 let hi = Self::extract_relative_offset(parts[1])?;
372 Some(PatternElement::Range(lo, hi))
373 }
374
375 fn try_parse_absolute_range(s: &str) -> Option<Self> {
376 let idx = s.find("..")?;
377 if s[idx + 2..].contains("..") {
378 return None;
379 }
380 let lo = s[..idx].parse::<i32>().ok()?;
381 let hi = s[idx + 2..].parse::<i32>().ok()?;
382 Some(PatternElement::AbsoluteRange(lo, hi))
383 }
384
385 fn try_parse_offset(s: &str) -> Option<Self> {
386 let offset = Self::extract_relative_offset(s)?;
387 Some(PatternElement::Offset(offset))
388 }
389
390 fn extract_relative_offset(s: &str) -> Option<i32> {
391 if !s.starts_with('?') {
392 return None;
393 }
394 let rest = &s[1..];
395 if rest.is_empty() || rest == "+" || rest == "-" || rest == "+=" || rest == "-=" {
396 return None;
397 }
398 rest.parse::<i32>().ok()
399 }
400}
401
402#[derive(Debug, Clone, Serialize, Deserialize)]
404pub struct PhysiologyConfig {
405 pub simulation_timestep: f64,
407
408 pub max_age: u64,
410
411 pub evolution_burst_count: u64,
413
414 pub ipu_idle_threshold: u64,
416
417 pub plasticity_queue_depth: usize,
419
420 pub lifespan_mgmt_interval: u64,
422
423 #[serde(default = "default_quantization_precision")]
426 pub quantization_precision: String,
427}
428
429pub fn default_quantization_precision() -> String {
430 "int8".to_string() }
432
433impl Default for PhysiologyConfig {
434 fn default() -> Self {
435 Self {
436 simulation_timestep: 0.025,
437 max_age: 10_000_000,
438 evolution_burst_count: 50,
439 ipu_idle_threshold: 1000,
440 plasticity_queue_depth: 3,
441 lifespan_mgmt_interval: 10,
442 quantization_precision: default_quantization_precision(),
443 }
444 }
445}
446
447#[derive(Debug, Clone, Serialize, Deserialize)]
449pub struct GenomeSignatures {
450 pub genome: String,
452
453 pub blueprint: String,
455
456 pub physiology: String,
458
459 #[serde(skip_serializing_if = "Option::is_none")]
461 pub morphologies: Option<String>,
462}
463
464#[derive(Debug, Clone, Serialize, Deserialize, Default)]
466pub struct GenomeStats {
467 pub innate_cortical_area_count: usize,
469
470 pub innate_neuron_count: usize,
472
473 pub innate_synapse_count: usize,
475}
476
477impl GenomeStats {
478 pub fn from_genome(genome: &RuntimeGenome, synapse_count: usize) -> Self {
487 let innate_neuron_count = genome
488 .cortical_areas
489 .values()
490 .map(|area| {
491 let per_voxel = area
492 .properties
493 .get("neurons_per_voxel")
494 .and_then(|v| v.as_u64())
495 .unwrap_or(1) as usize;
496 area.dimensions.width as usize
497 * area.dimensions.height as usize
498 * area.dimensions.depth as usize
499 * per_voxel
500 })
501 .sum();
502 Self {
503 innate_cortical_area_count: genome.cortical_areas.len(),
504 innate_neuron_count,
505 innate_synapse_count: synapse_count,
506 }
507 }
508}
509
510#[cfg(test)]
511mod tests {
512 use super::*;
513
514 #[test]
515 fn test_morphology_registry_creation() {
516 let registry = MorphologyRegistry::new();
517 assert_eq!(registry.count(), 0);
518 }
519
520 #[test]
521 fn test_morphology_registry_add_and_get() {
522 let mut registry = MorphologyRegistry::new();
523
524 let morphology = Morphology {
525 morphology_type: MorphologyType::Vectors,
526 parameters: MorphologyParameters::Vectors {
527 vectors: vec![[1, 0, 0], [0, 1, 0]],
528 },
529 class: "test".to_string(),
530 };
531
532 registry.add_morphology("test_morph".to_string(), morphology);
533
534 assert_eq!(registry.count(), 1);
535 assert!(registry.contains("test_morph"));
536 assert!(registry.get("test_morph").is_some());
537 }
538
539 fn classifier_genome(sample_to_memory_rules: Vec<serde_json::Value>) -> RuntimeGenome {
540 use feagi_structures::genomic::classifiers::Classifier;
541 use feagi_structures::genomic::cortical_area::{
542 CorticalAreaDimensions, CorticalAreaType, CustomCorticalType, MemoryCorticalType,
543 };
544
545 let area = |id: &str, is_memory: bool| {
546 let kind = if is_memory {
547 CorticalAreaType::Memory(MemoryCorticalType::Memory)
548 } else {
549 CorticalAreaType::Custom(CustomCorticalType::LeakyIntegrateFire)
550 };
551 let mut area = CorticalArea::new(
552 CorticalID::try_from_base_64(id).expect("id"),
553 0,
554 id.to_string(),
555 CorticalAreaDimensions::new(1, 1, 1).expect("dims"),
556 (0, 0, 0).into(),
557 kind,
558 )
559 .expect("area");
560 if is_memory {
561 area.properties
562 .insert("is_mem_type".to_string(), serde_json::json!(true));
563 area.properties
564 .insert("temporal_depth".to_string(), serde_json::json!(2));
565 }
566 area
567 };
568 let mut sample = area("Y01OSVNUX9w=", false);
569 sample.properties.insert(
570 "cortical_mapping_dst".to_string(),
571 serde_json::json!({ "bU1OSVNUXx8=": sample_to_memory_rules }),
572 );
573 let mut cortical_areas = HashMap::new();
574 for a in [
575 sample,
576 area("Y01OSVNUX+E=", false),
577 area("Y01OSVNUX8Y=", false),
578 area("bU1OSVNUXx8=", true),
579 area("bU1OSVNUXyA=", true),
580 ] {
581 cortical_areas.insert(a.cortical_id, a);
582 }
583 let classifier = Classifier {
584 classifier_id: "clf".to_string(),
585 name: "clf".to_string(),
586 parent_region_id: "region".to_string(),
587 coordinates_3d: [0, 0, 0],
588 sample_area_ids: vec!["Y01OSVNUX9w=".to_string()],
589 class_bindings: vec![
590 feagi_structures::genomic::classifiers::ClassifierClassBinding {
591 class_area_id: "Y01OSVNUX+E=".to_string(),
592 class_output_area_id: "Y01OSVNUX8Y=".to_string(),
593 },
594 ],
595 sample_memory_id: "bU1OSVNUXx8=".to_string(),
596 class_memory_id: "bU1OSVNUXyA=".to_string(),
597 error_area_id: "err".to_string(),
598 reward_training: false,
599 answer_feedback_area_id: None,
600 correct_area_id: String::new(),
601 reward_modulator_ids: Vec::new(),
602 answer_latency_bursts: 0,
603 learn_area_id: None,
604 confidence_area_id: None,
605 properties: HashMap::new(),
606 };
607 RuntimeGenome {
608 metadata: GenomeMetadata {
609 genome_id: "t".to_string(),
610 genome_title: "t".to_string(),
611 genome_description: String::new(),
612 version: "3.0".to_string(),
613 timestamp: 0.0,
614 brain_regions_root: None,
615 },
616 cortical_areas,
617 brain_regions: HashMap::new(),
618 classifiers: HashMap::from([("clf".to_string(), classifier)]),
619 morphologies: MorphologyRegistry::new(),
620 modulators: crate::modulators::ModulatorRegistry::new(),
621 physiology: PhysiologyConfig::default(),
622 signatures: GenomeSignatures {
623 genome: "0".to_string(),
624 blueprint: "0".to_string(),
625 physiology: "0".to_string(),
626 morphologies: None,
627 },
628 stats: GenomeStats::default(),
629 change_history: Vec::new(),
630 }
631 }
632
633 fn morphologies(genome: &RuntimeGenome, src: &str, dst: &str) -> Vec<String> {
634 genome.cortical_areas[&CorticalID::try_from_base_64(src).unwrap()]
635 .properties
636 .get("cortical_mapping_dst")
637 .and_then(|m| m.get(dst))
638 .and_then(|r| r.as_array())
639 .map(|rules| {
640 rules
641 .iter()
642 .filter_map(|r| r["morphology_id"].as_str().map(str::to_string))
643 .collect()
644 })
645 .unwrap_or_default()
646 }
647
648 #[test]
649 fn missing_classifier_edges_are_restored() {
650 use feagi_structures::genomic::classifiers::classifier_mapping_rule;
651 let mut genome = classifier_genome(vec![classifier_mapping_rule("classifier_sample", 2)]);
652
653 let added = genome.apply_classifier_required_mappings();
654
655 assert_eq!(
656 morphologies(&genome, "Y01OSVNUX9w=", "bU1OSVNUXx8="),
657 vec!["classifier_sample".to_string()]
658 );
659 assert_eq!(
660 morphologies(&genome, "Y01OSVNUX+E=", "bU1OSVNUXyA="),
661 vec!["classifier_class".to_string()]
662 );
663 let assoc = morphologies(&genome, "bU1OSVNUXx8=", "bU1OSVNUXyA=");
664 assert_eq!(assoc, vec!["associative_memory".to_string()]);
665 let assoc_rule = &genome.cortical_areas
666 [&CorticalID::try_from_base_64("bU1OSVNUXx8=").unwrap()]
667 .properties["cortical_mapping_dst"]["bU1OSVNUXyA="][0];
668 assert_eq!(assoc_rule["plasticity_window"], serde_json::json!(2));
669 assert_eq!(added, 2);
670 }
671
672 #[test]
673 fn complete_classifier_edges_are_left_unchanged() {
674 use feagi_structures::genomic::classifiers::classifier_mapping_rule;
675 let mut genome = classifier_genome(vec![classifier_mapping_rule("classifier_sample", 2)]);
676 genome.apply_classifier_required_mappings();
677 let before = genome.cortical_areas.clone();
678
679 assert_eq!(genome.apply_classifier_required_mappings(), 0);
680 for (id, area) in &before {
681 assert_eq!(
682 area.properties.get("cortical_mapping_dst"),
683 genome.cortical_areas[id]
684 .properties
685 .get("cortical_mapping_dst")
686 );
687 }
688 }
689
690 #[test]
691 fn test_physiology_config_default() {
692 let config = PhysiologyConfig::default();
693 assert_eq!(config.simulation_timestep, 0.025);
694 assert_eq!(config.max_age, 10_000_000);
695 }
696}