Skip to main content

feagi_brain_development/models/
cortical_area.rs

1// Copyright 2025 Neuraville Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4/*!
5CorticalArea business logic and extension methods.
6
7The core CorticalArea data structure is defined in feagi_data_structures.
8This module provides business logic methods for coordinate transformations
9and builder patterns.
10*/
11
12use std::collections::HashMap;
13
14use crate::types::{BduError, BduResult, Position};
15
16// Import core types from feagi_data_structures
17pub use feagi_structures::genomic::cortical_area::{
18    CoreCorticalType, CorticalArea, CorticalAreaDimensions, CorticalID,
19};
20
21/// Extension trait providing business logic methods for CorticalArea
22pub trait CorticalAreaExt {
23    /// Create a cortical area with custom properties
24    fn with_properties(self, properties: HashMap<String, serde_json::Value>) -> Self;
25
26    /// Add a single property (builder pattern)
27    fn add_property(self, key: String, value: serde_json::Value) -> Self;
28
29    /// Add a single property in-place
30    fn add_property_mut(&mut self, key: String, value: serde_json::Value);
31
32    /// Check if a 3D position is within this area's bounds
33    fn contains_position(&self, pos: (i32, i32, i32)) -> bool;
34
35    /// Convert absolute brain position to relative position within this area
36    fn to_relative_position(&self, pos: (i32, i32, i32)) -> BduResult<Position>;
37
38    /// Convert relative position within area to absolute brain position
39    fn to_absolute_position(&self, rel_pos: Position) -> BduResult<(i32, i32, i32)>;
40
41    /// Get neurons_per_voxel from properties (defaults to 1)
42    fn neurons_per_voxel(&self) -> u32;
43
44    /// Get refractory_period from properties (defaults to 0)
45    fn refractory_period(&self) -> u16;
46
47    /// Get snooze_period from properties (defaults to 0)
48    fn snooze_period(&self) -> u16;
49
50    /// Get leak_coefficient from properties (defaults to 0.0).
51    ///
52    /// Per-burst fraction of membrane potential lost, `g` in `V_t = V_{t-1} * (1 - g) + I_t`.
53    /// The NPU applies it lazily: at the next input, `V = V * (1 - g)^(t - t_last)` before adding `I`.
54    fn leak_coefficient(&self) -> f32;
55
56    /// Get firing_threshold from properties (defaults to 1.0)
57    fn firing_threshold(&self) -> f32;
58
59    /// Get firing_threshold_limit from properties (defaults to 0.0 = no limit)
60    fn firing_threshold_limit(&self) -> f32;
61
62    /// Get property as u32 with default
63    fn get_u32_property(&self, key: &str, default: u32) -> u32;
64
65    /// Get property as u16 with default
66    fn get_u16_property(&self, key: &str, default: u16) -> u16;
67
68    /// Get property as f32 with default.
69    /// NOTE: Incurs precision loss. Use `get_f64_property` when building API responses.
70    fn get_f32_property(&self, key: &str, default: f32) -> f32;
71
72    /// Get property as f64 with default, preserving full precision from the stored JSON value.
73    /// Prefer this over `get_f32_property() as f64` when building DTOs / API responses.
74    fn get_f64_property(&self, key: &str, default: f64) -> f64;
75
76    /// Get property as bool with default
77    fn get_bool_property(&self, key: &str, default: bool) -> bool;
78
79    /// Check if this is an input area
80    fn is_input_area(&self) -> bool;
81
82    /// Check if this is an output area
83    fn is_output_area(&self) -> bool;
84
85    /// Get cortical group classification
86    fn get_cortical_group(&self) -> Option<String>;
87
88    /// Get visible flag from properties (defaults to true)
89    fn visible(&self) -> bool;
90
91    /// Get sub_group from properties
92    fn sub_group(&self) -> Option<String>;
93
94    /// Get plasticity_constant from properties
95    fn plasticity_constant(&self) -> f32;
96
97    /// Get postsynaptic_current from properties
98    fn postsynaptic_current(&self) -> f32;
99
100    /// Get psp_uniform_distribution from properties (defaults to true for Power and memory
101    /// cortical areas, false for other types when the key is absent)
102    fn psp_uniform_distribution(&self) -> bool;
103
104    /// Get degeneration from properties
105    fn degeneration(&self) -> f32;
106
107    /// Get burst_engine_active from properties
108    fn burst_engine_active(&self) -> bool;
109
110    /// Get firing_threshold_increment from properties
111    fn firing_threshold_increment(&self) -> f32;
112
113    /// Get firing_threshold_increment_x from properties
114    fn firing_threshold_increment_x(&self) -> f32;
115
116    /// Get firing_threshold_increment_y from properties
117    fn firing_threshold_increment_y(&self) -> f32;
118
119    /// Get firing_threshold_increment_z from properties
120    fn firing_threshold_increment_z(&self) -> f32;
121
122    /// Get consecutive_fire_count from properties
123    fn consecutive_fire_count(&self) -> u32;
124
125    /// Get leak_variability from properties
126    fn leak_variability(&self) -> f32;
127
128    /// Get neuron_excitability from properties
129    fn neuron_excitability(&self) -> f32;
130
131    /// Get postsynaptic_current_max from properties
132    fn postsynaptic_current_max(&self) -> f32;
133
134    /// Get mp_charge_accumulation from properties
135    fn mp_charge_accumulation(&self) -> bool;
136
137    /// Get mp_driven_psp from properties
138    fn mp_driven_psp(&self) -> bool;
139
140    /// Get init_lifespan from properties (memory parameter)
141    fn init_lifespan(&self) -> u32;
142
143    /// Get lifespan_growth_rate from properties (memory parameter)
144    fn lifespan_growth_rate(&self) -> f32;
145
146    /// Get longterm_mem_threshold from properties (memory parameter)
147    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                // Derive from cortical_type if not in properties
302                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        self.get_f32_property("neuron_excitability", 100.0)
382    }
383
384    fn postsynaptic_current_max(&self) -> f32 {
385        self.get_f32_property("postsynaptic_current_max", 0.0)
386    }
387
388    fn mp_charge_accumulation(&self) -> bool {
389        self.get_bool_property("mp_charge_accumulation", false)
390    }
391
392    fn mp_driven_psp(&self) -> bool {
393        self.get_bool_property("mp_driven_psp", false)
394    }
395
396    fn init_lifespan(&self) -> u32 {
397        self.get_u32_property("init_lifespan", 0)
398    }
399
400    fn lifespan_growth_rate(&self) -> f32 {
401        self.get_f32_property("lifespan_growth_rate", 0.0)
402    }
403
404    fn longterm_mem_threshold(&self) -> u32 {
405        self.get_u32_property("longterm_mem_threshold", 0)
406    }
407}
408
409#[cfg(test)]
410mod tests {
411    use super::*;
412
413    #[test]
414    fn test_contains_position() {
415        let cortical_id = CoreCorticalType::Power.to_cortical_id();
416        let cortical_type = cortical_id
417            .as_cortical_type()
418            .expect("Failed to get cortical type");
419        let dims = CorticalAreaDimensions::new(10, 10, 10).unwrap();
420        let area = CorticalArea::new(
421            cortical_id,
422            0,
423            "Test Area".to_string(),
424            dims,
425            (5, 5, 5).into(),
426            cortical_type,
427        )
428        .unwrap();
429
430        assert!(area.contains_position((5, 5, 5))); // Min corner
431        assert!(area.contains_position((14, 14, 14))); // Max corner
432        assert!(!area.contains_position((4, 5, 5))); // Outside (x too small)
433        assert!(!area.contains_position((15, 5, 5))); // Outside (x too large)
434    }
435
436    #[test]
437    fn test_position_conversion() {
438        let cortical_id = CoreCorticalType::Power.to_cortical_id();
439        let cortical_type = cortical_id
440            .as_cortical_type()
441            .expect("Failed to get cortical type");
442        let dims = CorticalAreaDimensions::new(10, 10, 10).unwrap();
443        let area = CorticalArea::new(
444            cortical_id,
445            0,
446            "Test Area".to_string(),
447            dims,
448            (100, 200, 300).into(),
449            cortical_type,
450        )
451        .unwrap();
452
453        // Area spans from (100,200,300) to (109,209,309)
454        // Absolute (105, 207, 308) should map to relative (5, 7, 8)
455        let rel_pos = area.to_relative_position((105, 207, 308)).unwrap();
456        assert_eq!(rel_pos, (5, 7, 8));
457
458        // Convert back
459        let abs_pos = area.to_absolute_position(rel_pos).unwrap();
460        assert_eq!(abs_pos, (105, 207, 308));
461
462        // Test out of bounds
463        let result = area.to_relative_position((99, 200, 300));
464        assert!(result.is_err());
465    }
466
467    #[test]
468    fn test_properties() {
469        let cortical_id = CoreCorticalType::Power.to_cortical_id();
470        let cortical_type = cortical_id
471            .as_cortical_type()
472            .expect("Failed to get cortical type");
473        let dims = CorticalAreaDimensions::new(10, 10, 10).unwrap();
474        let area = CorticalArea::new(
475            cortical_id,
476            0,
477            "Test".to_string(),
478            dims,
479            (0, 0, 0).into(),
480            cortical_type,
481        )
482        .unwrap()
483        .add_property("resolution".to_string(), serde_json::json!(128))
484        .add_property("modality".to_string(), serde_json::json!("visual"));
485
486        assert_eq!(
487            area.get_property("resolution"),
488            Some(&serde_json::json!(128))
489        );
490        assert_eq!(
491            area.get_property("modality"),
492            Some(&serde_json::json!("visual"))
493        );
494        assert_eq!(area.get_property("nonexistent"), None);
495    }
496
497    #[test]
498    fn test_power_defaults_zero_degeneration_and_psp_uniform() {
499        let cortical_id = CoreCorticalType::Power.to_cortical_id();
500        let cortical_type = cortical_id
501            .as_cortical_type()
502            .expect("Failed to get cortical type");
503        let dims = CorticalAreaDimensions::new(1, 1, 1).unwrap();
504        let area = CorticalArea::new(
505            cortical_id,
506            1,
507            "Brain_Power".to_string(),
508            dims,
509            (0, 0, -20).into(),
510            cortical_type,
511        )
512        .unwrap();
513
514        assert_eq!(area.degeneration(), 0.0);
515        assert!(
516            area.psp_uniform_distribution(),
517            "Power must default to PSP uniformity when the genome omits the flag"
518        );
519    }
520}