Skip to main content

feagi_structures/genomic/brain_regions/
mod.rs

1// Copyright 2025 Neuraville Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4/*!
5BrainRegion data model.
6
7Represents a hierarchical grouping of cortical areas with functional significance.
8Moved from feagi-core/crates/feagi-bdu/src/models/brain_region.rs
9*/
10
11mod port_encoding;
12mod region_id;
13pub use port_encoding::{
14    decode_io_area, parse_port_encoding, port_encoding_to_value, region_port_encoding,
15    set_region_port_encoding, IoAreaDecode, IoPortSide, PortEncoding, PortEncodingSource,
16    PORT_ENCODING_KEY, PORT_FRAMES, PORT_KINDS, PORT_POSITIONINGS,
17};
18pub use region_id::RegionID;
19
20/// Canonical display name of the genome tree root. Brain Visualizer and
21/// neuroembryogenesis treat a region with this exact name as the unique root.
22pub const ROOT_BRAIN_REGION_NAME: &str = "Root Brain Region";
23
24use crate::genomic::cortical_area::CorticalID;
25use crate::FeagiDataError;
26use serde::{Deserialize, Serialize};
27use std::collections::{HashMap, HashSet};
28
29/// Type of brain region (placeholder for future functional/anatomical classification)
30///
31/// Currently, no specific region types are defined. This enum serves as a placeholder
32/// for future extensions when functional or anatomical classification is implemented.
33#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
34#[serde(rename_all = "lowercase")]
35#[derive(Default)]
36pub enum RegionType {
37    /// Generic/undefined region type (placeholder)
38    #[default]
39    Undefined,
40}
41
42impl std::fmt::Display for RegionType {
43    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
44        write!(f, "undefined")
45    }
46}
47
48/// Brain region metadata (genome representation)
49///
50/// A brain region is a hierarchical grouping of cortical areas that share
51/// functional or anatomical characteristics. Regions form a tree structure
52/// where each region can contain multiple cortical areas and sub-regions.
53///
54/// # Design Notes
55///
56/// - Regions are organizational constructs (not physical entities)
57/// - Used for genome editing, visualization, and bulk operations
58/// - Serializable for genome persistence
59/// - Properties stored as HashMap for maximum flexibility
60///
61#[derive(Debug, Clone, Serialize, Deserialize)]
62pub struct BrainRegion {
63    /// Unique identifier for this region
64    pub region_id: RegionID,
65
66    /// Human-readable name (mapped to "title" in genome JSON)
67    pub name: String,
68
69    /// Functional/anatomical type
70    pub region_type: RegionType,
71
72    /// Set of cortical area IDs contained in this region
73    #[serde(default)]
74    pub cortical_areas: HashSet<CorticalID>,
75
76    /// Additional user-defined properties
77    /// Commonly used keys: description, coordinate_2d, coordinate_3d, inputs, outputs, signature
78    #[serde(default)]
79    pub properties: HashMap<String, serde_json::Value>,
80}
81
82impl BrainRegion {
83    /// Create a new brain region
84    ///
85    /// # Arguments
86    ///
87    /// * `region_id` - Unique identifier (validated RegionID)
88    /// * `name` - Human-readable name
89    /// * `region_type` - Functional type
90    ///
91    /// # Errors
92    ///
93    /// Returns error if name is empty
94    ///
95    pub fn new(
96        region_id: RegionID,
97        name: String,
98        region_type: RegionType,
99    ) -> Result<Self, FeagiDataError> {
100        if name.trim().is_empty() {
101            return Err(FeagiDataError::BadParameters(
102                "name cannot be empty".to_string(),
103            ));
104        }
105
106        Ok(Self {
107            region_id,
108            name,
109            region_type,
110            cortical_areas: HashSet::new(),
111            properties: HashMap::new(),
112        })
113    }
114
115    /// Create a region with initial cortical areas
116    pub fn with_areas(mut self, areas: impl IntoIterator<Item = CorticalID>) -> Self {
117        self.cortical_areas.extend(areas);
118        self
119    }
120
121    /// Create a region with custom properties
122    pub fn with_properties(mut self, properties: HashMap<String, serde_json::Value>) -> Self {
123        self.properties = properties;
124        self
125    }
126
127    /// Add a cortical area to this region
128    ///
129    /// Returns `true` if the area was newly added, `false` if it was already present
130    ///
131    pub fn add_area(&mut self, area_id: CorticalID) -> bool {
132        self.cortical_areas.insert(area_id)
133    }
134
135    /// Remove a cortical area from this region
136    ///
137    /// Returns `true` if the area was present and removed, `false` if it wasn't present
138    ///
139    pub fn remove_area(&mut self, area_id: &CorticalID) -> bool {
140        self.cortical_areas.remove(area_id)
141    }
142
143    /// Check if this region contains a specific cortical area
144    pub fn contains_area(&self, area_id: &CorticalID) -> bool {
145        self.cortical_areas.contains(area_id)
146    }
147
148    /// Get all cortical area IDs in this region
149    pub fn get_all_areas(&self) -> Vec<&CorticalID> {
150        self.cortical_areas.iter().collect()
151    }
152
153    /// Get the number of cortical areas in this region
154    pub fn area_count(&self) -> usize {
155        self.cortical_areas.len()
156    }
157
158    /// Clear all cortical areas from this region
159    pub fn clear_areas(&mut self) {
160        self.cortical_areas.clear();
161    }
162
163    /// Get a property value by key
164    pub fn get_property(&self, key: &str) -> Option<&serde_json::Value> {
165        self.properties.get(key)
166    }
167
168    /// Add a property to the region
169    pub fn add_property(&mut self, key: String, value: serde_json::Value) {
170        self.properties.insert(key, value);
171    }
172
173    /// Convert to dictionary representation (for serialization)
174    pub fn to_dict(&self) -> serde_json::Value {
175        // Convert CorticalIDs to their base64 string representation for JSON
176        let area_ids: Vec<String> = self
177            .cortical_areas
178            .iter()
179            .map(|id| id.as_base_64())
180            .collect();
181
182        let mut dict = serde_json::json!({
183            "id": self.region_id.to_string(),
184            "name": self.name,
185            "region_type": self.region_type.to_string(),
186            "cortical_areas": area_ids,
187        });
188
189        // Add all properties from the HashMap
190        for (key, value) in &self.properties {
191            dict[key] = value.clone();
192        }
193
194        dict
195    }
196}