1use feagi_structures::genomic::cortical_area::CorticalArea;
15use feagi_structures::genomic::cortical_area::CorticalID;
16use feagi_structures::genomic::BrainRegion;
17use serde::{Deserialize, Serialize};
18use std::collections::HashMap;
19
20#[derive(Debug, Clone)]
22pub struct RuntimeGenome {
23 pub metadata: GenomeMetadata,
25
26 pub cortical_areas: HashMap<CorticalID, CorticalArea>,
28
29 pub brain_regions: HashMap<String, BrainRegion>,
31
32 pub morphologies: MorphologyRegistry,
34
35 pub physiology: PhysiologyConfig,
37
38 pub signatures: GenomeSignatures,
40
41 pub stats: GenomeStats,
43}
44
45#[derive(Debug, Clone, Serialize, Deserialize)]
47pub struct GenomeMetadata {
48 pub genome_id: String,
49 pub genome_title: String,
50 pub genome_description: String,
51 pub version: String,
52 pub timestamp: f64, #[serde(skip_serializing_if = "Option::is_none")]
57 pub brain_regions_root: Option<String>,
58}
59
60#[derive(Debug, Clone, Default)]
62pub struct MorphologyRegistry {
63 morphologies: HashMap<String, Morphology>,
65}
66
67impl MorphologyRegistry {
68 pub fn new() -> Self {
70 Self::default()
71 }
72
73 pub fn add_morphology(&mut self, id: String, morphology: Morphology) {
75 self.morphologies.insert(id, morphology);
76 }
77
78 pub fn get(&self, id: &str) -> Option<&Morphology> {
80 self.morphologies.get(id)
81 }
82
83 pub fn contains(&self, id: &str) -> bool {
85 self.morphologies.contains_key(id)
86 }
87
88 pub fn morphology_ids(&self) -> Vec<String> {
90 self.morphologies.keys().cloned().collect()
91 }
92
93 pub fn remove_morphology(&mut self, id: &str) -> bool {
97 self.morphologies.remove(id).is_some()
98 }
99
100 pub fn count(&self) -> usize {
102 self.morphologies.len()
103 }
104
105 pub fn iter(&self) -> impl Iterator<Item = (&String, &Morphology)> {
107 self.morphologies.iter()
108 }
109}
110
111#[derive(Debug, Clone, Serialize, Deserialize)]
113pub struct Morphology {
114 pub morphology_type: MorphologyType,
116
117 pub parameters: MorphologyParameters,
119
120 pub class: String,
122}
123
124#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
126#[serde(rename_all = "lowercase")]
127pub enum MorphologyType {
128 Vectors,
130
131 Patterns,
133
134 Functions,
136
137 Composite,
139}
140
141#[derive(Debug, Clone, Serialize, Deserialize)]
143#[serde(untagged)]
144pub enum MorphologyParameters {
145 Vectors { vectors: Vec<[i32; 3]> },
147
148 Patterns {
150 patterns: Vec<[Vec<PatternElement>; 2]>,
151 },
152
153 Functions {},
155
156 Composite {
158 src_seed: [u32; 3],
159 src_pattern: Vec<[i32; 2]>,
160 mapper_morphology: String,
161 },
162}
163
164#[derive(Debug, Clone, PartialEq, Eq)]
166pub enum PatternElement {
167 Value(i32),
169 Wildcard, Skip, Exclude, DirectionPositive, DirectionNegative, DirectionPositiveInclusive, DirectionNegativeInclusive, Offset(i32), Range(i32, i32), }
188
189impl Serialize for PatternElement {
191 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
192 where
193 S: serde::Serializer,
194 {
195 match self {
196 PatternElement::Value(v) => serializer.serialize_i32(*v),
197 PatternElement::Wildcard => serializer.serialize_str("*"),
198 PatternElement::Skip => serializer.serialize_str("?"),
199 PatternElement::Exclude => serializer.serialize_str("!"),
200 PatternElement::DirectionPositive => serializer.serialize_str("?+"),
201 PatternElement::DirectionNegative => serializer.serialize_str("?-"),
202 PatternElement::DirectionPositiveInclusive => serializer.serialize_str("?+="),
203 PatternElement::DirectionNegativeInclusive => serializer.serialize_str("?-="),
204 PatternElement::Offset(off) => {
205 if *off >= 0 {
206 serializer.serialize_str(&format!("?+{}", off))
207 } else {
208 serializer.serialize_str(&format!("?{}", off))
209 }
210 }
211 PatternElement::Range(lo, hi) => {
212 let lo_str = if *lo >= 0 {
213 format!("?+{}", lo)
214 } else {
215 format!("?{}", lo)
216 };
217 let hi_str = if *hi >= 0 {
218 format!("?+{}", hi)
219 } else {
220 format!("?{}", hi)
221 };
222 serializer.serialize_str(&format!("{}:{}", lo_str, hi_str))
223 }
224 }
225 }
226}
227
228impl<'de> Deserialize<'de> for PatternElement {
230 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
231 where
232 D: serde::Deserializer<'de>,
233 {
234 let value = serde_json::Value::deserialize(deserializer)?;
235 match value {
236 serde_json::Value::Number(n) => {
237 if let Some(i) = n.as_i64() {
238 Ok(PatternElement::Value(i as i32))
239 } else {
240 Err(serde::de::Error::custom(
241 "Pattern element must be an integer",
242 ))
243 }
244 }
245 serde_json::Value::String(s) => Self::parse_string(&s)
246 .ok_or_else(|| serde::de::Error::custom(format!("Unknown pattern element: {}", s))),
247 _ => Err(serde::de::Error::custom(
248 "Pattern element must be number or string",
249 )),
250 }
251 }
252}
253
254impl PatternElement {
255 pub fn parse_string(s: &str) -> Option<Self> {
257 match s {
258 "*" => Some(PatternElement::Wildcard),
259 "?" => Some(PatternElement::Skip),
260 "!" => Some(PatternElement::Exclude),
261 "?+" => Some(PatternElement::DirectionPositive),
262 "?-" => Some(PatternElement::DirectionNegative),
263 "?+=" => Some(PatternElement::DirectionPositiveInclusive),
264 "?-=" => Some(PatternElement::DirectionNegativeInclusive),
265 _ => {
266 if let Some(range) = Self::try_parse_range(s) {
267 return Some(range);
268 }
269 if let Some(offset) = Self::try_parse_offset(s) {
270 return Some(offset);
271 }
272 None
273 }
274 }
275 }
276
277 fn try_parse_range(s: &str) -> Option<Self> {
278 let parts: Vec<&str> = s.split(':').collect();
279 if parts.len() != 2 {
280 return None;
281 }
282 let lo = Self::extract_relative_offset(parts[0])?;
283 let hi = Self::extract_relative_offset(parts[1])?;
284 Some(PatternElement::Range(lo, hi))
285 }
286
287 fn try_parse_offset(s: &str) -> Option<Self> {
288 let offset = Self::extract_relative_offset(s)?;
289 Some(PatternElement::Offset(offset))
290 }
291
292 fn extract_relative_offset(s: &str) -> Option<i32> {
293 if !s.starts_with('?') {
294 return None;
295 }
296 let rest = &s[1..];
297 if rest.is_empty() || rest == "+" || rest == "-" || rest == "+=" || rest == "-=" {
298 return None;
299 }
300 rest.parse::<i32>().ok()
301 }
302}
303
304#[derive(Debug, Clone, Serialize, Deserialize)]
306pub struct PhysiologyConfig {
307 pub simulation_timestep: f64,
309
310 pub max_age: u64,
312
313 pub evolution_burst_count: u64,
315
316 pub ipu_idle_threshold: u64,
318
319 pub plasticity_queue_depth: usize,
321
322 pub lifespan_mgmt_interval: u64,
324
325 #[serde(default = "default_quantization_precision")]
328 pub quantization_precision: String,
329}
330
331pub fn default_quantization_precision() -> String {
332 "int8".to_string() }
334
335impl Default for PhysiologyConfig {
336 fn default() -> Self {
337 Self {
338 simulation_timestep: 0.025,
339 max_age: 10_000_000,
340 evolution_burst_count: 50,
341 ipu_idle_threshold: 1000,
342 plasticity_queue_depth: 3,
343 lifespan_mgmt_interval: 10,
344 quantization_precision: default_quantization_precision(),
345 }
346 }
347}
348
349#[derive(Debug, Clone, Serialize, Deserialize)]
351pub struct GenomeSignatures {
352 pub genome: String,
354
355 pub blueprint: String,
357
358 pub physiology: String,
360
361 #[serde(skip_serializing_if = "Option::is_none")]
363 pub morphologies: Option<String>,
364}
365
366#[derive(Debug, Clone, Serialize, Deserialize, Default)]
368pub struct GenomeStats {
369 pub innate_cortical_area_count: usize,
371
372 pub innate_neuron_count: usize,
374
375 pub innate_synapse_count: usize,
377}
378
379#[cfg(test)]
380mod tests {
381 use super::*;
382
383 #[test]
384 fn test_morphology_registry_creation() {
385 let registry = MorphologyRegistry::new();
386 assert_eq!(registry.count(), 0);
387 }
388
389 #[test]
390 fn test_morphology_registry_add_and_get() {
391 let mut registry = MorphologyRegistry::new();
392
393 let morphology = Morphology {
394 morphology_type: MorphologyType::Vectors,
395 parameters: MorphologyParameters::Vectors {
396 vectors: vec![[1, 0, 0], [0, 1, 0]],
397 },
398 class: "test".to_string(),
399 };
400
401 registry.add_morphology("test_morph".to_string(), morphology);
402
403 assert_eq!(registry.count(), 1);
404 assert!(registry.contains("test_morph"));
405 assert!(registry.get("test_morph").is_some());
406 }
407
408 #[test]
409 fn test_physiology_config_default() {
410 let config = PhysiologyConfig::default();
411 assert_eq!(config.simulation_timestep, 0.025);
412 assert_eq!(config.max_age, 10_000_000);
413 }
414}