1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
use crate::genomic::cortical_area::descriptors::CorticalSubUnitIndex;
use crate::genomic::cortical_area::descriptors::CorticalUnitIndex;
use crate::genomic::cortical_area::io_cortical_area_configuration_flag::{
FrameChangeHandling, PercentageNeuronPositioning, PoseSchema,
};
use crate::genomic::cortical_area::{
CorticalAreaType, CorticalID, IOCorticalAreaConfigurationFlag,
};
use crate::genomic::sensory_cortical_unit::{format_sub_unit_area_name, UnitTopology};
use crate::motor_cortical_units;
use paste;
use serde_json::{Map, Value};
use std::collections::HashMap;
use std::fmt::{Display, Formatter};
// Helper macro to handle optional allowed_frame_change_handling
#[macro_export]
macro_rules! get_allowed_frame_change_handling_impl { // TODO delete this!
() => {
None
};
($($allowed:ident),+) => {
Some(&[$(FrameChangeHandling::$allowed),+] as &'static [FrameChangeHandling])
};
}
macro_rules! define_motor_cortical_units_enum {
(
MotorCorticalUnit {
$(
$(#[doc = $doc:expr])?
$variant_name:ident => {
friendly_name: $friendly_name:expr,
accepted_wrapped_io_data_type: $accepted_wrapped_io_data_type:expr,
cortical_id_unit_reference: $cortical_id_unit_reference:expr,
number_cortical_areas: $number_cortical_areas:expr,
cortical_type_parameters: {
$($param_name:ident: $param_type:ty),* $(,)?
},
$(allowed_frame_change_handling: [$($allowed_frame:ident),* $(,)?],)? // TODO delete this!
cortical_area_properties: {
$($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])),* $(,)?
}
}
),* $(,)?
}
) => {
#[derive(Debug, Hash, PartialEq, Eq, Clone, Copy, serde::Deserialize, serde::Serialize)]
pub enum MotorCorticalUnit {
$(
$(#[doc = $doc])?
$variant_name,
)*
}
impl MotorCorticalUnit {
$(
paste::paste! {
#[doc = "Get cortical area types array for " $friendly_name "."]
pub const fn [<get_cortical_area_types_array_for_ $variant_name:snake _with_parameters >](
$($param_name: $param_type),*) -> [CorticalAreaType; $number_cortical_areas] {
// Keep parameterized API stable even for unit templates that don't consume every parameter.
$(let _ = &$param_name;)*
[
$(CorticalAreaType::BrainOutput($io_cortical_area_configuration_flag_expr)),*
]
}
#[doc = "Get cortical IDs array for " $friendly_name "."]
pub const fn [<get_cortical_ids_array_for_ $variant_name:snake _with_parameters >](
$($param_name: $param_type,)* cortical_unit_index: CorticalUnitIndex) -> [CorticalID; $number_cortical_areas] {
// Keep parameterized API stable even for unit templates that don't consume every parameter.
$(let _ = &$param_name;)*
let cortical_unit_identifier: [u8; 3] = $cortical_id_unit_reference;
[
$(
$io_cortical_area_configuration_flag_expr .as_io_cortical_id(false, cortical_unit_identifier, cortical_unit_index, CorticalSubUnitIndex::from($cortical_sub_unit_index))
),*
]
}
}
)*
pub const fn get_snake_case_name(&self) -> &'static str {
match self {
$(
MotorCorticalUnit::$variant_name => paste::paste!{ stringify!([<$variant_name:snake>]) },
)*
}
}
/// Get the accepted wrapped IO data type for this motor cortical unit.
/// Returns the string name of the data type (e.g., "MiscData", "SignedPercentageData").
pub const fn get_accepted_wrapped_io_data_type(&self) -> &'static str {
match self {
$(
MotorCorticalUnit::$variant_name => stringify!($variant_name:snake),
)*
}
}
/// Parse a motor cortical unit from its snake_case name
///
/// # Arguments
/// * `name` - The snake_case name (e.g., "positional_servo", "led_matrix")
///
/// # Returns
/// * `Some(MotorCorticalUnit)` - If name matches a known type
/// * `None` - If name is not recognized
pub fn from_snake_case_name(name: &str) -> Option<MotorCorticalUnit> {
match name {
$(
paste::paste!{ stringify!([<$variant_name:snake>]) } => Some(MotorCorticalUnit::$variant_name),
)*
_ => None,
}
}
// TODO from_snake_case_name_const
/// Returns all available motor cortical unit types.
/// This is useful for enumerating all possible motor types in the system.
pub const fn list_all() -> &'static [MotorCorticalUnit] {
&[
$(
MotorCorticalUnit::$variant_name,
)*
]
}
/// Returns the friendly (human-readable) name for this motor cortical unit type.
pub const fn get_friendly_name(&self) -> &'static str {
match self {
$(
MotorCorticalUnit::$variant_name => $friendly_name,
)*
}
}
/// Returns the 3-byte cortical ID unit reference for this type.
pub const fn get_cortical_id_unit_reference(&self) -> [u8; 3] {
match self {
$(
MotorCorticalUnit::$variant_name => $cortical_id_unit_reference,
)*
}
}
/// Returns the number of cortical areas this type creates.
pub const fn get_number_cortical_areas(&self) -> usize {
match self {
$(
MotorCorticalUnit::$variant_name => $number_cortical_areas,
)*
}
}
/// Returns the default topology for all units of this cortical type.
pub fn get_unit_default_topology(&self) -> HashMap<CorticalSubUnitIndex, UnitTopology> {
match self {
$(
MotorCorticalUnit::$variant_name => {
let mut topology = HashMap::new();
$(
topology.insert(
CorticalSubUnitIndex::from($cortical_sub_unit_index),
UnitTopology {
relative_position: [$rel_x, $rel_y, $rel_z],
channel_dimensions_default: [$dim_default_x, $dim_default_y, $dim_default_z],
channel_dimensions_min: [$dim_min_x, $dim_min_y, $dim_min_z],
channel_dimensions_max: [$dim_max_x, $dim_max_y, $dim_max_z],
}
);
)*
topology
}
)*
}
}
/// Returns the allowed FrameChangeHandling values for this motor cortical unit.
/// If None, all FrameChangeHandling values are allowed.
/// If Some, only the specified values are allowed.
pub fn get_allowed_frame_change_handling(&self) -> Option<&'static [FrameChangeHandling]> {
match self {
$(
MotorCorticalUnit::$variant_name => {
$crate::get_allowed_frame_change_handling_impl!($($($allowed_frame),*)?)
}
)*
}
}
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> {
match self {
$(
MotorCorticalUnit::$variant_name => {
paste::paste! {
let array = MotorCorticalUnit::[<get_cortical_ids_array_for_ $variant_name:snake _with_parameters >](
$($param_type::try_from_serde_map(&map)?,)*
cortical_unit_index);
return Ok(array.to_vec());
}
}
)*
}
}
}
impl Display for MotorCorticalUnit {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
$(
MotorCorticalUnit::$variant_name => write!(f, $friendly_name),
)*
}
}
}
};
}
// Generate the MotorCorticalUnit enum and all helper methods from the template
motor_cortical_units!(define_motor_cortical_units_enum);
impl MotorCorticalUnit {
/// Display names of the areas of a unit whose areas have distinct roles, in
/// sub-unit order. `None` for units that do not name their areas.
pub const fn get_sub_unit_display_names(&self) -> Option<&'static [&'static str]> {
match self {
MotorCorticalUnit::MidiOutput => Some(&["Notes", "Expression"]),
_ => None,
}
}
/// Title for one area of a unit whose areas have distinct roles (see
/// [`Self::get_sub_unit_display_names`]). `None` for units without area display names,
/// whose naming is unchanged.
///
/// With a unit label the title is `"<label> (<area display name>)"`; without one it is
/// `"<type display name> (<area display name>) Unit <unit_index>"`. The label is used
/// as given (not trimmed, escaped or length-limited here).
pub fn build_sub_unit_area_name(
&self,
unit_label: Option<&str>,
sub_unit_index: usize,
unit_index: u16,
) -> Option<String> {
let area_name = self.get_sub_unit_display_names()?.get(sub_unit_index)?;
Some(format_sub_unit_area_name(
self.get_friendly_name(),
area_name,
unit_label,
unit_index,
))
}
/// Check if a legacy 3-char subtype matches a supported OPU type and return its default CorticalID.
/// Used by genome migrator to avoid converting unsupported legacy OPU areas to MiscData.
pub fn try_from_legacy_subtype(subtype: &str) -> Option<CorticalID> {
let subtype_bytes = subtype.as_bytes();
if subtype_bytes.len() != 3 {
return None;
}
let subtype_arr = [subtype_bytes[0], subtype_bytes[1], subtype_bytes[2]];
for unit in Self::list_all() {
if unit.get_cortical_id_unit_reference() == subtype_arr {
return Some(unit.get_default_cortical_id_for_group(CorticalUnitIndex::from(0u16)));
}
}
None
}
/// Get the default CorticalID for this unit with group index 0 (Absolute frame handling, Linear positioning).
pub fn get_default_cortical_id_for_group(&self, group_index: CorticalUnitIndex) -> CorticalID {
use crate::genomic::cortical_area::io_cortical_area_configuration_flag::{
FrameChangeHandling, PercentageNeuronPositioning,
};
let fh = FrameChangeHandling::Absolute;
let pos = PercentageNeuronPositioning::Linear;
match self {
MotorCorticalUnit::RotaryMotor => {
Self::get_cortical_ids_array_for_rotary_motor_with_parameters(fh, pos, group_index)
[0]
}
MotorCorticalUnit::PositionalServo => {
Self::get_cortical_ids_array_for_positional_servo_with_parameters(
FrameChangeHandling::Absolute,
pos,
group_index,
)[0]
}
MotorCorticalUnit::Gaze => {
Self::get_cortical_ids_array_for_gaze_with_parameters(fh, pos, group_index)[0]
}
MotorCorticalUnit::MiscData => {
Self::get_cortical_ids_array_for_misc_data_with_parameters(fh, group_index)[0]
}
MotorCorticalUnit::TextEnglishOutput => {
Self::get_cortical_ids_array_for_text_english_output_with_parameters(
fh,
group_index,
)[0]
}
MotorCorticalUnit::CountOutput => {
Self::get_cortical_ids_array_for_count_output_with_parameters(fh, pos, group_index)
[0]
}
MotorCorticalUnit::ObjectSegmentation => {
Self::get_cortical_ids_array_for_object_segmentation_with_parameters(
fh,
group_index,
)[0]
}
MotorCorticalUnit::SimpleVisionOutput => {
Self::get_cortical_ids_array_for_simple_vision_output_with_parameters(
fh,
group_index,
)[0]
}
MotorCorticalUnit::PoseEstimation => {
Self::get_cortical_ids_array_for_pose_estimation_with_parameters(
fh,
PoseSchema::HumanBody,
group_index,
)[0]
}
MotorCorticalUnit::DynamicImageProcessing => {
Self::get_cortical_ids_array_for_dynamic_image_processing_with_parameters(
fh,
pos,
group_index,
)[0]
}
MotorCorticalUnit::SpatialPointer => {
Self::get_cortical_ids_array_for_spatial_pointer_with_parameters(
fh,
pos,
group_index,
)[0]
}
MotorCorticalUnit::AngularPointer => {
Self::get_cortical_ids_array_for_angular_pointer_with_parameters(
fh,
pos,
group_index,
)[0]
}
MotorCorticalUnit::AudioOutput => {
Self::get_cortical_ids_array_for_audio_output_with_parameters(fh, group_index)[0]
}
MotorCorticalUnit::MidiOutput => {
Self::get_cortical_ids_array_for_midi_output_with_parameters(fh, pos, group_index)
[0]
}
}
}
}