Skip to main content

feagi_structures/genomic/
sensory_cortical_unit.rs

1use crate::genomic::cortical_area::descriptors::CorticalSubUnitIndex;
2use crate::genomic::cortical_area::descriptors::CorticalUnitIndex;
3use crate::genomic::cortical_area::io_cortical_area_configuration_flag::{
4    FrameChangeHandling, PercentageNeuronPositioning,
5};
6use crate::genomic::cortical_area::{
7    CorticalAreaType, CorticalID, IOCorticalAreaConfigurationFlag,
8};
9use crate::sensor_cortical_units;
10use paste;
11use serde_json::{Map, Value};
12use std::collections::HashMap;
13use std::fmt::{Display, Formatter};
14
15#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] // TODO move me!
16pub struct UnitTopology {
17    pub relative_position: [i32; 3],
18    pub channel_dimensions_default: [u32; 3],
19    pub channel_dimensions_min: [u32; 3],
20    pub channel_dimensions_max: [u32; 3],
21}
22
23macro_rules! default_firing_threshold_impl {
24    () => {
25        None
26    };
27    ($value:expr) => {
28        Some($value)
29    };
30}
31
32macro_rules! default_mp_charge_accumulation_impl {
33    () => {
34        None
35    };
36    ($value:expr) => {
37        Some($value)
38    };
39}
40
41macro_rules! default_firing_threshold_increment_impl {
42    () => {
43        None
44    };
45    ([$x:expr, $y:expr, $z:expr]) => {
46        Some([$x, $y, $z])
47    };
48}
49
50macro_rules! define_sensory_cortical_units_enum {
51    (
52        SensoryCorticalUnit {
53            $(
54                $(#[doc = $doc:expr])?
55                $variant_name:ident => {
56                    friendly_name: $friendly_name:expr,
57                    accepted_wrapped_io_data_type: $accepted_wrapped_io_data_type:expr,
58                    cortical_id_unit_reference: $cortical_id_unit_reference:expr,
59                    number_cortical_areas: $number_cortical_areas:expr,
60                    $(default_firing_threshold: $default_firing_threshold:expr,)?
61                    $(default_firing_threshold_increment: [$default_firing_threshold_increment_x:expr, $default_firing_threshold_increment_y:expr, $default_firing_threshold_increment_z:expr],)?
62                    $(default_mp_charge_accumulation: $default_mp_charge_accumulation:expr,)?
63                    cortical_type_parameters: {
64                        $($param_name:ident: $param_type:ty),* $(,)?
65                    },
66                    $(allowed_frame_change_handling: [$($allowed_frame:ident),* $(,)?],)? // TODO delete this!
67                    cortical_area_properties: {
68                        $($cortical_sub_unit_index:tt => ($io_cortical_area_configuration_flag_expr:expr, relative_position: [$rel_x:expr, $rel_y:expr, $rel_z:expr], channel_dimensions_default: [$dim_default_x:expr, $dim_default_y:expr, $dim_default_z:expr], channel_dimensions_min: [$dim_min_x:expr, $dim_min_y:expr, $dim_min_z:expr], channel_dimensions_max: [$dim_max_x:expr, $dim_max_y:expr, $dim_max_z:expr])),* $(,)?
69                    }
70                }
71            ),* $(,)?
72        }
73    ) => {
74        #[derive(Debug, Hash, PartialEq, Eq, Clone, Copy, serde::Serialize, serde::Deserialize)]
75        pub enum SensoryCorticalUnit {
76            $(
77                $(#[doc = $doc])?
78                $variant_name,
79            )*
80        }
81
82        impl SensoryCorticalUnit {
83            $(
84                paste::paste! {
85                    #[doc = "Get cortical area types array for " $friendly_name " using individual parameters."]
86                    pub const fn [<get_cortical_area_types_array_for_ $variant_name:snake _with_parameters >](
87                        $($param_name: $param_type),*) -> [CorticalAreaType; $number_cortical_areas] {
88                        [
89                            $(CorticalAreaType::BrainInput($io_cortical_area_configuration_flag_expr)),*
90                        ]
91                    }
92
93                    #[doc = "Get cortical IDs array for " $friendly_name " using individual parameters."]
94                    pub const fn [<get_cortical_ids_array_for_ $variant_name:snake _with_parameters >](
95                        $($param_name: $param_type,)* cortical_unit_index: CorticalUnitIndex) -> [CorticalID; $number_cortical_areas] {
96                        let cortical_unit_identifier: [u8; 3] = $cortical_id_unit_reference;
97                        [
98                            $(
99                                $io_cortical_area_configuration_flag_expr .as_io_cortical_id(true, cortical_unit_identifier, cortical_unit_index, CorticalSubUnitIndex::from($cortical_sub_unit_index))
100                            ),*
101                        ]
102                    }
103                }
104            )*
105
106            pub const fn get_snake_case_name(&self) -> &'static str {
107                match self {
108                    $(
109                        SensoryCorticalUnit::$variant_name => paste::paste!{ stringify!([<$variant_name:snake>]) },
110                    )*
111                }
112            }
113
114            /// Parse a sensory cortical unit from its snake_case name
115            ///
116            /// # Arguments
117            /// * `name` - The snake_case name (e.g., "simple_vision", "raw_i_m_u")
118            ///
119            /// # Returns
120            /// * `Some(SensoryCorticalUnit)` - If name matches a known type
121            /// * `None` - If name is not recognized
122            pub fn from_snake_case_name(name: &str) -> Option<SensoryCorticalUnit> {
123                match name {
124                    $(
125                        paste::paste!{ stringify!([<$variant_name:snake>]) } => Some(SensoryCorticalUnit::$variant_name),
126                    )*
127                    _ => None,
128                }
129            }
130
131            /// Returns all available sensory cortical unit types.
132            /// This is useful for enumerating all possible sensor types in the system.
133            pub const fn list_all() -> &'static [SensoryCorticalUnit] {
134                &[
135                    $(
136                        SensoryCorticalUnit::$variant_name,
137                    )*
138                ]
139            }
140
141            /// Returns the friendly (human-readable) name for this sensory cortical unit type.
142            pub const fn get_friendly_name(&self) -> &'static str {
143                match self {
144                    $(
145                        SensoryCorticalUnit::$variant_name => $friendly_name,
146                    )*
147                }
148            }
149
150            /// Returns the 3-byte cortical ID unit reference for this type. // TODO delete me!
151            pub const fn get_cortical_id_unit_reference(&self) -> [u8; 3] {
152                match self {
153                    $(
154                        SensoryCorticalUnit::$variant_name => $cortical_id_unit_reference,
155                    )*
156                }
157            }
158
159            /// Returns the number of cortical areas this type creates.
160            pub const fn get_number_cortical_areas(&self) -> usize {
161                match self {
162                    $(
163                        SensoryCorticalUnit::$variant_name => $number_cortical_areas,
164                    )*
165                }
166            }
167
168            /// Returns the template-defined default firing threshold for auto-created areas.
169            /// `None` means no template override is defined.
170            pub const fn get_default_firing_threshold(&self) -> Option<f64> {
171                match self {
172                    $(
173                        SensoryCorticalUnit::$variant_name => {
174                            default_firing_threshold_impl!($($default_firing_threshold)?)
175                        }
176                    )*
177                }
178            }
179
180            /// Returns template-defined default per-axis firing threshold increment [x, y, z].
181            /// `None` means no template override is defined.
182            pub const fn get_default_firing_threshold_increment(&self) -> Option<[f64; 3]> {
183                match self {
184                    $(
185                        SensoryCorticalUnit::$variant_name => {
186                            default_firing_threshold_increment_impl!(
187                                $([$default_firing_threshold_increment_x, $default_firing_threshold_increment_y, $default_firing_threshold_increment_z])?
188                            )
189                        }
190                    )*
191                }
192            }
193
194            /// Returns the template-defined default mp_charge_accumulation for auto-created areas.
195            /// `None` means no template override is defined.
196            pub const fn get_default_mp_charge_accumulation(&self) -> Option<bool> {
197                match self {
198                    $(
199                        SensoryCorticalUnit::$variant_name => {
200                            default_mp_charge_accumulation_impl!($($default_mp_charge_accumulation)?)
201                        }
202                    )*
203                }
204            }
205
206            /// Returns the accepted wrapped IO data type name for this sensory unit type.
207            pub const fn get_accepted_wrapped_io_data_type(&self) -> &'static str { // TODO delete me!
208                match self {
209                    $(
210                        SensoryCorticalUnit::$variant_name => stringify!($accepted_wrapped_io_data_type),
211                    )*
212                }
213            }
214
215            /// Returns the default topology for all units of this cortical type.
216            pub fn get_unit_default_topology(&self) -> HashMap<CorticalSubUnitIndex, UnitTopology> {
217                match self {
218                    $(
219                        SensoryCorticalUnit::$variant_name => {
220                            let mut topology = HashMap::new();
221                            $(
222                                topology.insert(
223                                    CorticalSubUnitIndex::from($cortical_sub_unit_index),
224                                    UnitTopology {
225                                        relative_position: [$rel_x, $rel_y, $rel_z],
226                                        channel_dimensions_default: [$dim_default_x, $dim_default_y, $dim_default_z],
227                                        channel_dimensions_min: [$dim_min_x, $dim_min_y, $dim_min_z],
228                                        channel_dimensions_max: [$dim_max_x, $dim_max_y, $dim_max_z],
229                                    }
230                                );
231                            )*
232                            topology
233                        }
234                    )*
235                }
236            }
237
238
239            /// Returns the allowed frame change handling modes from the template, if restricted.
240            /// If None is returned, all frame change handling modes are allowed.
241            /// If Some is returned, only the specified modes are valid.
242            pub fn get_allowed_frame_change_handling(&self) -> Option<&'static [FrameChangeHandling]> { // TODO delete me!
243                match self {
244                    $(
245                        SensoryCorticalUnit::$variant_name => {
246                            $crate::get_allowed_frame_change_handling_impl!($($($allowed_frame),*)?)
247                        }
248                    )*
249                }
250            }
251
252            pub fn get_cortical_id_vector_from_index_and_serde_io_configuration_flags(&self, cortical_unit_index: CorticalUnitIndex, map: Map<String, Value>) -> Result<Vec<CorticalID>, crate::FeagiDataError> {
253                match self {
254                    $(
255                        SensoryCorticalUnit::$variant_name => {
256                            paste::paste! {
257                                let array = SensoryCorticalUnit::[<get_cortical_ids_array_for_ $variant_name:snake _with_parameters >](
258                                    $($param_type::try_from_serde_map(&map)?,)*
259                                    cortical_unit_index);
260                                return Ok(array.to_vec());
261                            }
262                        }
263                    )*
264                }
265            }
266
267
268
269        }
270
271        impl Display for SensoryCorticalUnit {
272            fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
273                match self {
274                    $(
275                        SensoryCorticalUnit::$variant_name => write!(f, $friendly_name),
276                    )*
277                }
278    }
279        }
280    };
281
282}
283// Generate the SensoryCorticalUnit enum and all helper methods from the template
284sensor_cortical_units!(define_sensory_cortical_units_enum);
285
286impl SensoryCorticalUnit {
287    /// Check if a legacy 3-char subtype matches a supported IPU type and return its default CorticalID.
288    /// Used by genome migrator to avoid converting unsupported legacy IPU areas to MiscData.
289    pub fn try_from_legacy_subtype(subtype: &str) -> Option<CorticalID> {
290        let subtype_bytes = subtype.as_bytes();
291        if subtype_bytes.len() != 3 {
292            return None;
293        }
294        let subtype_arr = [subtype_bytes[0], subtype_bytes[1], subtype_bytes[2]];
295        for unit in Self::list_all() {
296            if unit.get_cortical_id_unit_reference() == subtype_arr {
297                return Some(unit.get_default_cortical_id_for_group(CorticalUnitIndex::from(0u8)));
298            }
299        }
300        None
301    }
302
303    /// Get the default CorticalID for this unit with group index 0 (Absolute frame handling, Linear positioning).
304    pub fn get_default_cortical_id_for_group(&self, group_index: CorticalUnitIndex) -> CorticalID {
305        use crate::genomic::cortical_area::io_cortical_area_configuration_flag::{
306            FrameChangeHandling, PercentageNeuronPositioning,
307        };
308        let fh = FrameChangeHandling::Absolute;
309        let pos = PercentageNeuronPositioning::Linear;
310        match self {
311            SensoryCorticalUnit::Infrared => {
312                Self::get_cortical_ids_array_for_infrared_with_parameters(fh, pos, group_index)[0]
313            }
314            SensoryCorticalUnit::Proximity => {
315                Self::get_cortical_ids_array_for_proximity_with_parameters(fh, pos, group_index)[0]
316            }
317            SensoryCorticalUnit::Shock => {
318                Self::get_cortical_ids_array_for_shock_with_parameters(fh, pos, group_index)[0]
319            }
320            SensoryCorticalUnit::Battery => {
321                Self::get_cortical_ids_array_for_battery_with_parameters(fh, pos, group_index)[0]
322            }
323            SensoryCorticalUnit::Servo => {
324                Self::get_cortical_ids_array_for_servo_with_parameters(fh, pos, group_index)[0]
325            }
326            SensoryCorticalUnit::AnalogGPIO => {
327                Self::get_cortical_ids_array_for_analog_g_p_i_o_with_parameters(
328                    fh,
329                    pos,
330                    group_index,
331                )[0]
332            }
333            SensoryCorticalUnit::DigitalGPIO => {
334                Self::get_cortical_ids_array_for_digital_g_p_i_o_with_parameters(group_index)[0]
335            }
336            SensoryCorticalUnit::MiscData => {
337                Self::get_cortical_ids_array_for_misc_data_with_parameters(fh, group_index)[0]
338            }
339            SensoryCorticalUnit::TextEnglishInput => {
340                Self::get_cortical_ids_array_for_text_english_input_with_parameters(fh, group_index)
341                    [0]
342            }
343            SensoryCorticalUnit::CountInput => {
344                Self::get_cortical_ids_array_for_count_input_with_parameters(fh, pos, group_index)
345                    [0]
346            }
347            SensoryCorticalUnit::Vision => {
348                Self::get_cortical_ids_array_for_vision_with_parameters(fh, group_index)[0]
349            }
350            SensoryCorticalUnit::DepthMap => {
351                Self::get_cortical_ids_array_for_depth_map_with_parameters(fh, group_index)[0]
352            }
353            SensoryCorticalUnit::SegmentedVision => {
354                Self::get_cortical_ids_array_for_segmented_vision_with_parameters(fh, group_index)
355                    [0]
356            }
357            SensoryCorticalUnit::RawIMU => {
358                // Default group index returns the accelerometer (sub-area 0) as
359                // the canonical "primary" cortical id of a Raw IMU unit.
360                Self::get_cortical_ids_array_for_raw_i_m_u_with_parameters(fh, pos, group_index)[0]
361            }
362            SensoryCorticalUnit::SmartIMU => {
363                Self::get_cortical_ids_array_for_smart_i_m_u_with_parameters(fh, pos, group_index)
364                    [0]
365            }
366        }
367    }
368}