1use std::collections::HashMap;
13
14use crate::types::{BduError, BduResult, Position};
15
16pub use feagi_structures::genomic::cortical_area::{
18 CoreCorticalType, CorticalArea, CorticalAreaDimensions, CorticalID,
19};
20
21pub trait CorticalAreaExt {
23 fn with_properties(self, properties: HashMap<String, serde_json::Value>) -> Self;
25
26 fn add_property(self, key: String, value: serde_json::Value) -> Self;
28
29 fn add_property_mut(&mut self, key: String, value: serde_json::Value);
31
32 fn contains_position(&self, pos: (i32, i32, i32)) -> bool;
34
35 fn to_relative_position(&self, pos: (i32, i32, i32)) -> BduResult<Position>;
37
38 fn to_absolute_position(&self, rel_pos: Position) -> BduResult<(i32, i32, i32)>;
40
41 fn neurons_per_voxel(&self) -> u32;
43
44 fn refractory_period(&self) -> u16;
46
47 fn snooze_period(&self) -> u16;
49
50 fn leak_coefficient(&self) -> f32;
55
56 fn firing_threshold(&self) -> f32;
58
59 fn firing_threshold_limit(&self) -> f32;
61
62 fn get_u32_property(&self, key: &str, default: u32) -> u32;
64
65 fn get_u16_property(&self, key: &str, default: u16) -> u16;
67
68 fn get_f32_property(&self, key: &str, default: f32) -> f32;
71
72 fn get_f64_property(&self, key: &str, default: f64) -> f64;
75
76 fn get_bool_property(&self, key: &str, default: bool) -> bool;
78
79 fn is_input_area(&self) -> bool;
81
82 fn is_output_area(&self) -> bool;
84
85 fn get_cortical_group(&self) -> Option<String>;
87
88 fn visible(&self) -> bool;
90
91 fn sub_group(&self) -> Option<String>;
93
94 fn plasticity_constant(&self) -> f32;
96
97 fn postsynaptic_current(&self) -> f32;
99
100 fn psp_uniform_distribution(&self) -> bool;
103
104 fn degeneration(&self) -> f32;
106
107 fn burst_engine_active(&self) -> bool;
109
110 fn firing_threshold_increment(&self) -> f32;
112
113 fn firing_threshold_increment_x(&self) -> f32;
115
116 fn firing_threshold_increment_y(&self) -> f32;
118
119 fn firing_threshold_increment_z(&self) -> f32;
121
122 fn consecutive_fire_count(&self) -> u32;
124
125 fn leak_variability(&self) -> f32;
127
128 fn neuron_excitability(&self) -> f32;
130
131 fn postsynaptic_current_max(&self) -> f32;
133
134 fn mp_charge_accumulation(&self) -> bool;
136
137 fn mp_driven_psp(&self) -> bool;
139
140 fn init_lifespan(&self) -> u32;
142
143 fn lifespan_growth_rate(&self) -> f32;
145
146 fn longterm_mem_threshold(&self) -> u32;
148}
149
150impl CorticalAreaExt for CorticalArea {
151 fn with_properties(mut self, properties: HashMap<String, serde_json::Value>) -> Self {
152 self.properties = properties;
153 self
154 }
155
156 fn add_property(mut self, key: String, value: serde_json::Value) -> Self {
157 self.properties.insert(key, value);
158 self
159 }
160
161 fn add_property_mut(&mut self, key: String, value: serde_json::Value) {
162 self.properties.insert(key, value);
163 }
164
165 fn contains_position(&self, pos: (i32, i32, i32)) -> bool {
166 let (x, y, z) = pos;
167 let ox = self.position.x;
168 let oy = self.position.y;
169 let oz = self.position.z;
170
171 x >= ox
172 && y >= oy
173 && z >= oz
174 && x < ox + self.dimensions.width as i32
175 && y < oy + self.dimensions.height as i32
176 && z < oz + self.dimensions.depth as i32
177 }
178
179 fn to_relative_position(&self, pos: (i32, i32, i32)) -> BduResult<Position> {
180 if !self.contains_position(pos) {
181 return Err(BduError::OutOfBounds {
182 pos: (pos.0 as u32, pos.1 as u32, pos.2 as u32),
183 dims: (
184 self.dimensions.width as usize,
185 self.dimensions.height as usize,
186 self.dimensions.depth as usize,
187 ),
188 });
189 }
190
191 let ox = self.position.x;
192 let oy = self.position.y;
193 let oz = self.position.z;
194 Ok((
195 (pos.0 - ox) as u32,
196 (pos.1 - oy) as u32,
197 (pos.2 - oz) as u32,
198 ))
199 }
200
201 fn to_absolute_position(&self, rel_pos: Position) -> BduResult<(i32, i32, i32)> {
202 if !self.dimensions.contains(rel_pos) {
203 return Err(BduError::OutOfBounds {
204 pos: rel_pos,
205 dims: (
206 self.dimensions.width as usize,
207 self.dimensions.height as usize,
208 self.dimensions.depth as usize,
209 ),
210 });
211 }
212
213 let ox = self.position.x;
214 let oy = self.position.y;
215 let oz = self.position.z;
216 Ok((
217 ox + rel_pos.0 as i32,
218 oy + rel_pos.1 as i32,
219 oz + rel_pos.2 as i32,
220 ))
221 }
222
223 fn neurons_per_voxel(&self) -> u32 {
224 self.get_u32_property("neurons_per_voxel", 1)
225 }
226
227 fn refractory_period(&self) -> u16 {
228 self.get_u16_property("refractory_period", 0)
229 }
230
231 fn snooze_period(&self) -> u16 {
232 self.get_u16_property("snooze_period", 0)
233 }
234
235 fn leak_coefficient(&self) -> f32 {
236 self.get_f32_property("leak_coefficient", 0.0)
237 }
238
239 fn firing_threshold(&self) -> f32 {
240 self.get_f32_property("firing_threshold", 1.0)
241 }
242
243 fn get_u32_property(&self, key: &str, default: u32) -> u32 {
244 self.properties
245 .get(key)
246 .and_then(|v| v.as_u64())
247 .map(|v| v as u32)
248 .unwrap_or(default)
249 }
250
251 fn get_u16_property(&self, key: &str, default: u16) -> u16 {
252 self.properties
253 .get(key)
254 .and_then(|v| v.as_u64())
255 .map(|v| v as u16)
256 .unwrap_or(default)
257 }
258
259 fn get_f32_property(&self, key: &str, default: f32) -> f32 {
260 self.properties
261 .get(key)
262 .and_then(|v| v.as_f64())
263 .map(|v| v as f32)
264 .unwrap_or(default)
265 }
266
267 fn get_f64_property(&self, key: &str, default: f64) -> f64 {
268 self.properties
269 .get(key)
270 .and_then(|v| v.as_f64())
271 .unwrap_or(default)
272 }
273
274 fn get_bool_property(&self, key: &str, default: bool) -> bool {
275 self.properties
276 .get(key)
277 .and_then(|v| v.as_bool())
278 .unwrap_or(default)
279 }
280
281 fn is_input_area(&self) -> bool {
282 matches!(
283 self.cortical_type,
284 feagi_structures::genomic::cortical_area::CorticalAreaType::BrainInput(_)
285 )
286 }
287
288 fn is_output_area(&self) -> bool {
289 matches!(
290 self.cortical_type,
291 feagi_structures::genomic::cortical_area::CorticalAreaType::BrainOutput(_)
292 )
293 }
294
295 fn get_cortical_group(&self) -> Option<String> {
296 self.properties
297 .get("cortical_group")
298 .and_then(|v| v.as_str())
299 .map(|s| s.to_string())
300 .or_else(|| {
301 use feagi_structures::genomic::cortical_area::CorticalAreaType;
303 match self.cortical_type {
304 CorticalAreaType::BrainInput(_) => Some("IPU".to_string()),
305 CorticalAreaType::BrainOutput(_) => Some("OPU".to_string()),
306 CorticalAreaType::Memory(_) => Some("MEMORY".to_string()),
307 CorticalAreaType::Custom(_) => Some("CUSTOM".to_string()),
308 CorticalAreaType::Core(_) => Some("CORE".to_string()),
309 CorticalAreaType::Modulator => Some("MODULATOR".to_string()),
310 }
311 })
312 }
313
314 fn visible(&self) -> bool {
315 self.get_bool_property("visible", true)
316 }
317
318 fn sub_group(&self) -> Option<String> {
319 self.properties
320 .get("sub_group")
321 .and_then(|v| v.as_str())
322 .map(|s| s.to_string())
323 }
324
325 fn plasticity_constant(&self) -> f32 {
326 self.get_f32_property("plasticity_constant", 0.0)
327 }
328
329 fn postsynaptic_current(&self) -> f32 {
330 self.get_f32_property("postsynaptic_current", 1.0)
331 }
332
333 fn psp_uniform_distribution(&self) -> bool {
334 let default = matches!(
335 self.cortical_type,
336 feagi_structures::genomic::cortical_area::CorticalAreaType::Memory(_)
337 | feagi_structures::genomic::cortical_area::CorticalAreaType::Core(
338 CoreCorticalType::Power
339 )
340 );
341 self.get_bool_property("psp_uniform_distribution", default)
342 }
343
344 fn degeneration(&self) -> f32 {
345 self.get_f32_property("degeneration", 0.0)
346 }
347
348 fn burst_engine_active(&self) -> bool {
349 self.get_bool_property("burst_engine_active", false)
350 }
351
352 fn firing_threshold_increment(&self) -> f32 {
353 self.get_f32_property("firing_threshold_increment", 0.0)
354 }
355
356 fn firing_threshold_increment_x(&self) -> f32 {
357 self.get_f32_property("firing_threshold_increment_x", 0.0)
358 }
359
360 fn firing_threshold_increment_y(&self) -> f32 {
361 self.get_f32_property("firing_threshold_increment_y", 0.0)
362 }
363
364 fn firing_threshold_increment_z(&self) -> f32 {
365 self.get_f32_property("firing_threshold_increment_z", 0.0)
366 }
367
368 fn firing_threshold_limit(&self) -> f32 {
369 self.get_f32_property("firing_threshold_limit", 0.0)
370 }
371
372 fn consecutive_fire_count(&self) -> u32 {
373 self.get_u32_property("consecutive_fire_limit", 0)
374 }
375
376 fn leak_variability(&self) -> f32 {
377 self.get_f32_property("leak_variability", 0.0)
378 }
379
380 fn neuron_excitability(&self) -> f32 {
381 feagi_evolutionary::units::excitability_fraction(f64::from(
383 self.get_f32_property("neuron_excitability", 1.0),
384 )) as f32
385 }
386
387 fn postsynaptic_current_max(&self) -> f32 {
388 self.get_f32_property("postsynaptic_current_max", 0.0)
389 }
390
391 fn mp_charge_accumulation(&self) -> bool {
392 self.get_bool_property("mp_charge_accumulation", false)
393 }
394
395 fn mp_driven_psp(&self) -> bool {
396 self.get_bool_property("mp_driven_psp", false)
397 }
398
399 fn init_lifespan(&self) -> u32 {
400 self.get_u32_property("init_lifespan", 0)
401 }
402
403 fn lifespan_growth_rate(&self) -> f32 {
404 self.get_f32_property("lifespan_growth_rate", 0.0)
405 }
406
407 fn longterm_mem_threshold(&self) -> u32 {
408 self.get_u32_property("longterm_mem_threshold", 0)
409 }
410}
411
412#[cfg(test)]
413mod tests {
414 use super::*;
415
416 #[test]
417 fn test_contains_position() {
418 let cortical_id = CoreCorticalType::Power.to_cortical_id();
419 let cortical_type = cortical_id
420 .as_cortical_type()
421 .expect("Failed to get cortical type");
422 let dims = CorticalAreaDimensions::new(10, 10, 10).unwrap();
423 let area = CorticalArea::new(
424 cortical_id,
425 0,
426 "Test Area".to_string(),
427 dims,
428 (5, 5, 5).into(),
429 cortical_type,
430 )
431 .unwrap();
432
433 assert!(area.contains_position((5, 5, 5))); assert!(area.contains_position((14, 14, 14))); assert!(!area.contains_position((4, 5, 5))); assert!(!area.contains_position((15, 5, 5))); }
438
439 #[test]
440 fn test_position_conversion() {
441 let cortical_id = CoreCorticalType::Power.to_cortical_id();
442 let cortical_type = cortical_id
443 .as_cortical_type()
444 .expect("Failed to get cortical type");
445 let dims = CorticalAreaDimensions::new(10, 10, 10).unwrap();
446 let area = CorticalArea::new(
447 cortical_id,
448 0,
449 "Test Area".to_string(),
450 dims,
451 (100, 200, 300).into(),
452 cortical_type,
453 )
454 .unwrap();
455
456 let rel_pos = area.to_relative_position((105, 207, 308)).unwrap();
459 assert_eq!(rel_pos, (5, 7, 8));
460
461 let abs_pos = area.to_absolute_position(rel_pos).unwrap();
463 assert_eq!(abs_pos, (105, 207, 308));
464
465 let result = area.to_relative_position((99, 200, 300));
467 assert!(result.is_err());
468 }
469
470 #[test]
471 fn test_properties() {
472 let cortical_id = CoreCorticalType::Power.to_cortical_id();
473 let cortical_type = cortical_id
474 .as_cortical_type()
475 .expect("Failed to get cortical type");
476 let dims = CorticalAreaDimensions::new(10, 10, 10).unwrap();
477 let area = CorticalArea::new(
478 cortical_id,
479 0,
480 "Test".to_string(),
481 dims,
482 (0, 0, 0).into(),
483 cortical_type,
484 )
485 .unwrap()
486 .add_property("resolution".to_string(), serde_json::json!(128))
487 .add_property("modality".to_string(), serde_json::json!("visual"));
488
489 assert_eq!(
490 area.get_property("resolution"),
491 Some(&serde_json::json!(128))
492 );
493 assert_eq!(
494 area.get_property("modality"),
495 Some(&serde_json::json!("visual"))
496 );
497 assert_eq!(area.get_property("nonexistent"), None);
498 }
499
500 #[test]
501 fn test_power_defaults_zero_degeneration_and_psp_uniform() {
502 let cortical_id = CoreCorticalType::Power.to_cortical_id();
503 let cortical_type = cortical_id
504 .as_cortical_type()
505 .expect("Failed to get cortical type");
506 let dims = CorticalAreaDimensions::new(1, 1, 1).unwrap();
507 let area = CorticalArea::new(
508 cortical_id,
509 1,
510 "Brain_Power".to_string(),
511 dims,
512 (0, 0, -20).into(),
513 cortical_type,
514 )
515 .unwrap();
516
517 assert_eq!(area.degeneration(), 0.0);
518 assert!(
519 area.psp_uniform_distribution(),
520 "Power must default to PSP uniformity when the genome omits the flag"
521 );
522 }
523}