Skip to main content

feagi_structures/genomic/brain_regions/
port_encoding.rs

1// Copyright 2025 Neuraville Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4/*!
5Brain-region `port_encoding` property: what each designated port carries.
6
7Sibling of `designated_inputs` / `designated_outputs`. Stored on the region as
8`{ "<designated area id, base64>": { "kind", "signed", "frame", "positioning", "source" } }`.
9
10* `kind`, `frame` and `positioning` are the vocabulary of the block datasheet
11  (`KINDS`, `FRAMES`, `POSITIONINGS` in Composer's `block_datasheet.py`); `signed` is a boolean.
12  Any of the four may be `null` (unknown).
13* `source` is `"wiring"` when feagi derived the entry from the IPU/OPU areas wired to the port, and
14  `"author"` when a person set it. Wiring derivation never overwrites an `"author"` entry.
15
16Flag decoding is [`IOCorticalAreaConfigurationFlag::port_encoding_fields`]; the shared table
17`tests/io-flag-fixture.json` keeps it identical to Composer and feagi-mcp.
18*/
19
20use std::collections::BTreeMap;
21
22use serde_json::{json, Map, Value};
23
24use crate::genomic::brain_regions::BrainRegion;
25use crate::genomic::cortical_area::io_cortical_area_configuration_flag::PortEncodingFields;
26use crate::genomic::cortical_area::CorticalID;
27use crate::FeagiDataError;
28
29/// Region property key holding the port encoding map.
30pub const PORT_ENCODING_KEY: &str = "port_encoding";
31
32/// Allowed `kind` values (same order as the IO configuration flag variants).
33pub const PORT_KINDS: [&str; 12] = [
34    "Boolean",
35    "Percentage",
36    "Percentage2D",
37    "Percentage3D",
38    "Percentage4D",
39    "SignedPercentage",
40    "SignedPercentage2D",
41    "SignedPercentage3D",
42    "SignedPercentage4D",
43    "CartesianPlane",
44    "Misc",
45    "PoseEstimation",
46];
47/// Allowed `frame` values.
48pub const PORT_FRAMES: [&str; 2] = ["Absolute", "Incremental"];
49/// Allowed `positioning` values.
50pub const PORT_POSITIONINGS: [&str; 2] = ["Linear", "Fractional"];
51
52const KIND_FIELD: &str = "kind";
53const SIGNED_FIELD: &str = "signed";
54const FRAME_FIELD: &str = "frame";
55const POSITIONING_FIELD: &str = "positioning";
56const SOURCE_FIELD: &str = "source";
57const SOURCE_WIRING: &str = "wiring";
58const SOURCE_AUTHOR: &str = "author";
59
60/// Where a port encoding entry came from.
61#[derive(Debug, Clone, Copy, PartialEq, Eq)]
62pub enum PortEncodingSource {
63    /// Derived from the IPU/OPU areas wired to the port (or the port's own IO flags).
64    Wiring,
65    /// Set by a person through the region API.
66    Author,
67}
68
69impl PortEncodingSource {
70    /// Wire text of the source.
71    pub const fn as_str(self) -> &'static str {
72        match self {
73            Self::Wiring => SOURCE_WIRING,
74            Self::Author => SOURCE_AUTHOR,
75        }
76    }
77
78    fn parse(text: &str) -> Result<Self, FeagiDataError> {
79        match text {
80            SOURCE_WIRING => Ok(Self::Wiring),
81            SOURCE_AUTHOR => Ok(Self::Author),
82            other => Err(bad(format!(
83                "port_encoding source '{other}' is not one of: {SOURCE_WIRING}, {SOURCE_AUTHOR}"
84            ))),
85        }
86    }
87}
88
89/// One designated port's encoding. A `None` field is unknown (`null` on the wire).
90#[derive(Debug, Clone, PartialEq, Eq)]
91pub struct PortEncoding {
92    pub kind: Option<String>,
93    pub signed: Option<bool>,
94    pub frame: Option<String>,
95    pub positioning: Option<String>,
96    pub source: PortEncodingSource,
97}
98
99fn bad(message: String) -> FeagiDataError {
100    FeagiDataError::BadParameters(message)
101}
102
103/// Read a nullable vocabulary field: absent or `null` is `None`, otherwise one of `allowed`.
104fn vocabulary_field(
105    object: &Map<String, Value>,
106    field: &str,
107    allowed: &[&str],
108) -> Result<Option<String>, FeagiDataError> {
109    match object.get(field) {
110        None | Some(Value::Null) => Ok(None),
111        Some(Value::String(text)) if allowed.contains(&text.as_str()) => Ok(Some(text.clone())),
112        Some(other) => Err(bad(format!(
113            "port_encoding {field} {other} is not one of: {}",
114            allowed.join(", ")
115        ))),
116    }
117}
118
119/// Reject object keys that are not one of `known`.
120fn reject_unknown_keys(object: &Map<String, Value>, known: &[&str]) -> Result<(), FeagiDataError> {
121    for key in object.keys() {
122        if !known.contains(&key.as_str()) {
123            return Err(bad(format!(
124                "port_encoding entry has unknown field '{key}' (allowed: {})",
125                known.join(", ")
126            )));
127        }
128    }
129    Ok(())
130}
131
132impl PortEncoding {
133    fn from_object(
134        value: &Value,
135        source: PortEncodingSource,
136        known: &[&str],
137    ) -> Result<Self, FeagiDataError> {
138        let object = value
139            .as_object()
140            .ok_or_else(|| bad("a port_encoding entry must be a JSON object".to_string()))?;
141        reject_unknown_keys(object, known)?;
142        let signed = match object.get(SIGNED_FIELD) {
143            None | Some(Value::Null) => None,
144            Some(Value::Bool(flag)) => Some(*flag),
145            Some(other) => {
146                return Err(bad(format!(
147                    "port_encoding signed {other} must be true, false or null"
148                )))
149            }
150        };
151        Ok(Self {
152            kind: vocabulary_field(object, KIND_FIELD, &PORT_KINDS)?,
153            signed,
154            frame: vocabulary_field(object, FRAME_FIELD, &PORT_FRAMES)?,
155            positioning: vocabulary_field(object, POSITIONING_FIELD, &PORT_POSITIONINGS)?,
156            source,
157        })
158    }
159
160    /// Parse a stored entry; `source` is required and must be `"wiring"` or `"author"`.
161    pub fn from_stored_value(value: &Value) -> Result<Self, FeagiDataError> {
162        let source = value
163            .get(SOURCE_FIELD)
164            .and_then(Value::as_str)
165            .ok_or_else(|| bad("a stored port_encoding entry needs a string source".to_string()))
166            .and_then(PortEncodingSource::parse)?;
167        Self::from_object(
168            value,
169            source,
170            &[
171                KIND_FIELD,
172                SIGNED_FIELD,
173                FRAME_FIELD,
174                POSITIONING_FIELD,
175                SOURCE_FIELD,
176            ],
177        )
178    }
179
180    /// Parse an entry an author sends through the API. The server assigns `source = "author"`,
181    /// so a `source` key in the input is rejected.
182    pub fn from_author_value(value: &Value) -> Result<Self, FeagiDataError> {
183        Self::from_object(
184            value,
185            PortEncodingSource::Author,
186            &[KIND_FIELD, SIGNED_FIELD, FRAME_FIELD, POSITIONING_FIELD],
187        )
188    }
189
190    /// Wire form: all five keys, unknown fields as `null`.
191    pub fn to_value(&self) -> Value {
192        json!({
193            KIND_FIELD: self.kind,
194            SIGNED_FIELD: self.signed,
195            FRAME_FIELD: self.frame,
196            POSITIONING_FIELD: self.positioning,
197            SOURCE_FIELD: self.source.as_str(),
198        })
199    }
200
201    /// Wiring entry holding exactly what one IO flag defines.
202    pub fn from_flag_fields(fields: &PortEncodingFields) -> Self {
203        Self {
204            kind: Some(fields.kind.to_string()),
205            signed: fields.signed,
206            frame: fields.frame.map(|frame| frame.label().to_string()),
207            positioning: fields.positioning.map(|p| p.label().to_string()),
208            source: PortEncodingSource::Wiring,
209        }
210    }
211
212    /// Wiring entry for several IO peers: a field the peers disagree on is `None`, an agreed
213    /// field is kept. `None` when there are no peers.
214    pub fn from_peer_fields(peers: &[PortEncodingFields]) -> Option<Self> {
215        let (first, rest) = peers.split_first()?;
216        let mut merged = Self::from_flag_fields(first);
217        for peer in rest {
218            let other = Self::from_flag_fields(peer);
219            if merged.kind != other.kind {
220                merged.kind = None;
221            }
222            if merged.signed != other.signed {
223                merged.signed = None;
224            }
225            if merged.frame != other.frame {
226                merged.frame = None;
227            }
228            if merged.positioning != other.positioning {
229                merged.positioning = None;
230            }
231        }
232        Some(merged)
233    }
234}
235
236/// Which side of a region an IO area id belongs to.
237#[derive(Debug, Clone, Copy, PartialEq, Eq)]
238pub enum IoPortSide {
239    /// IPU id (leading byte `i`).
240    Input,
241    /// OPU id (leading byte `o`).
242    Output,
243}
244
245/// Result of decoding a cortical id as an IO area.
246#[derive(Debug, Clone, Copy, PartialEq, Eq)]
247pub enum IoAreaDecode {
248    /// Not an IPU or OPU id.
249    NotIo,
250    /// An IPU/OPU id whose flag the flag decoder refuses.
251    Refused(IoPortSide),
252    /// An IPU/OPU id and the fields its flag defines.
253    Fields(IoPortSide, PortEncodingFields),
254}
255
256/// Decode an area id the same way Composer's `io_flag_decode.area_fields` and Studio's
257/// `region_port_hints` do.
258pub fn decode_io_area(id: &CorticalID) -> IoAreaDecode {
259    let side = match id.as_bytes()[0] {
260        b'i' => IoPortSide::Input,
261        b'o' => IoPortSide::Output,
262        _ => return IoAreaDecode::NotIo,
263    };
264    match id.extract_io_data_flag() {
265        Ok(flag) => IoAreaDecode::Fields(side, flag.port_encoding_fields()),
266        Err(_) => IoAreaDecode::Refused(side),
267    }
268}
269
270/// Parse the `port_encoding` property value into entries keyed by base64 area id.
271pub fn parse_port_encoding(
272    value: &Value,
273) -> Result<BTreeMap<String, PortEncoding>, FeagiDataError> {
274    let object = value
275        .as_object()
276        .ok_or_else(|| bad("port_encoding must be a JSON object keyed by area id".to_string()))?;
277    let mut entries = BTreeMap::new();
278    for (area_id, entry) in object {
279        CorticalID::try_from_base_64(area_id).map_err(|err| {
280            bad(format!(
281                "port_encoding key '{area_id}' is not a base64 cortical id: {err}"
282            ))
283        })?;
284        entries.insert(area_id.clone(), PortEncoding::from_stored_value(entry)?);
285    }
286    Ok(entries)
287}
288
289/// Serialize entries to the `port_encoding` property value.
290pub fn port_encoding_to_value(entries: &BTreeMap<String, PortEncoding>) -> Value {
291    Value::Object(
292        entries
293            .iter()
294            .map(|(area_id, entry)| (area_id.clone(), entry.to_value()))
295            .collect(),
296    )
297}
298
299/// The region's stored port encoding (empty when the property is absent).
300pub fn region_port_encoding(
301    region: &BrainRegion,
302) -> Result<BTreeMap<String, PortEncoding>, FeagiDataError> {
303    match region.properties.get(PORT_ENCODING_KEY) {
304        Some(value) => parse_port_encoding(value),
305        None => Ok(BTreeMap::new()),
306    }
307}
308
309/// Write entries to the region; an empty map removes the property.
310pub fn set_region_port_encoding(
311    region: &mut BrainRegion,
312    entries: &BTreeMap<String, PortEncoding>,
313) {
314    if entries.is_empty() {
315        region.properties.remove(PORT_ENCODING_KEY);
316    } else {
317        region.properties.insert(
318            PORT_ENCODING_KEY.to_string(),
319            port_encoding_to_value(entries),
320        );
321    }
322}
323
324#[cfg(test)]
325mod tests {
326    use super::*;
327    use crate::genomic::cortical_area::descriptors::{CorticalSubUnitIndex, CorticalUnitIndex};
328    use crate::genomic::cortical_area::io_cortical_area_configuration_flag::{
329        FrameChangeHandling, IOCorticalAreaConfigurationFlag as Flag, PercentageNeuronPositioning,
330    };
331
332    fn io_id(flag: Flag, is_input: bool) -> CorticalID {
333        flag.as_io_cortical_id(
334            is_input,
335            *b"tst",
336            CorticalUnitIndex::from(0u16),
337            CorticalSubUnitIndex::from(0u8),
338        )
339    }
340
341    const ABS_LINEAR: Flag = Flag::Percentage(
342        FrameChangeHandling::Absolute,
343        PercentageNeuronPositioning::Linear,
344    );
345
346    #[test]
347    fn vocabulary_matches_the_flag_decoder_kinds() {
348        // Every kind the flag decoder can emit is in the allowed vocabulary.
349        for variant in 0u16..12 {
350            let id = CorticalID::try_from_bytes(&[b'i', b't', b's', b't', variant as u8, 0, 0, 0])
351                .unwrap();
352            let IoAreaDecode::Fields(_, fields) = decode_io_area(&id) else {
353                panic!("variant {variant} must decode");
354            };
355            assert!(PORT_KINDS.contains(&fields.kind), "{}", fields.kind);
356        }
357    }
358
359    #[test]
360    fn decode_gives_all_four_fields_for_percentage() {
361        let id = io_id(ABS_LINEAR, true);
362        let IoAreaDecode::Fields(side, fields) = decode_io_area(&id) else {
363            panic!("must decode");
364        };
365        assert_eq!(side, IoPortSide::Input);
366        let entry = PortEncoding::from_flag_fields(&fields);
367        assert_eq!(entry.kind.as_deref(), Some("Percentage"));
368        assert_eq!(entry.signed, Some(false));
369        assert_eq!(entry.frame.as_deref(), Some("Absolute"));
370        assert_eq!(entry.positioning.as_deref(), Some("Linear"));
371        assert_eq!(entry.source, PortEncodingSource::Wiring);
372    }
373
374    #[test]
375    fn decode_frame_only_kind_leaves_signed_and_positioning_null() {
376        let id = io_id(Flag::Misc(FrameChangeHandling::Incremental), false);
377        let IoAreaDecode::Fields(side, fields) = decode_io_area(&id) else {
378            panic!("must decode");
379        };
380        assert_eq!(side, IoPortSide::Output);
381        let entry = PortEncoding::from_flag_fields(&fields);
382        assert_eq!(entry.kind.as_deref(), Some("Misc"));
383        assert_eq!(entry.signed, None);
384        assert_eq!(entry.frame.as_deref(), Some("Incremental"));
385        assert_eq!(entry.positioning, None);
386    }
387
388    #[test]
389    fn decode_refuses_positioning_bit_on_a_frame_only_kind_and_skips_non_io() {
390        // variant 10 (Misc) with the positioning bit set: the flag decoder refuses it.
391        let refused =
392            CorticalID::try_from_bytes(&[b'i', b't', b's', b't', 0x0A, 0x02, 0, 0]).unwrap();
393        assert_eq!(
394            decode_io_area(&refused),
395            IoAreaDecode::Refused(IoPortSide::Input)
396        );
397        let custom = CorticalID::try_from_bytes(b"cst_port").unwrap();
398        assert_eq!(decode_io_area(&custom), IoAreaDecode::NotIo);
399    }
400
401    #[test]
402    fn peers_disagreeing_on_one_field_null_only_that_field() {
403        let absolute = ABS_LINEAR.port_encoding_fields();
404        let incremental = Flag::Percentage(
405            FrameChangeHandling::Incremental,
406            PercentageNeuronPositioning::Linear,
407        )
408        .port_encoding_fields();
409        let merged = PortEncoding::from_peer_fields(&[absolute, incremental]).unwrap();
410        assert_eq!(merged.kind.as_deref(), Some("Percentage"));
411        assert_eq!(merged.signed, Some(false));
412        assert_eq!(merged.frame, None);
413        assert_eq!(merged.positioning.as_deref(), Some("Linear"));
414        assert!(PortEncoding::from_peer_fields(&[]).is_none());
415    }
416
417    #[test]
418    fn stored_entry_round_trips_and_requires_a_source() {
419        let entry = PortEncoding::from_flag_fields(&ABS_LINEAR.port_encoding_fields());
420        let value = entry.to_value();
421        assert_eq!(PortEncoding::from_stored_value(&value).unwrap(), entry);
422        let mut without_source = value.clone();
423        without_source.as_object_mut().unwrap().remove("source");
424        assert!(PortEncoding::from_stored_value(&without_source).is_err());
425    }
426
427    #[test]
428    fn vocabulary_violations_are_rejected() {
429        for bad_value in [
430            json!({"kind": "Nonsense", "source": "wiring"}),
431            json!({"signed": "yes", "source": "wiring"}),
432            json!({"frame": "Sideways", "source": "wiring"}),
433            json!({"positioning": 3, "source": "wiring"}),
434            json!({"kind": "Boolean", "source": "robot"}),
435            json!({"kind": "Boolean", "source": "wiring", "extra": 1}),
436            json!("Boolean"),
437        ] {
438            assert!(
439                PortEncoding::from_stored_value(&bad_value).is_err(),
440                "{bad_value}"
441            );
442        }
443    }
444
445    #[test]
446    fn author_entry_rejects_a_source_key_and_treats_absent_as_null() {
447        assert!(PortEncoding::from_author_value(&json!({"source": "wiring"})).is_err());
448        let entry = PortEncoding::from_author_value(&json!({"kind": "Boolean"})).unwrap();
449        assert_eq!(entry.kind.as_deref(), Some("Boolean"));
450        assert_eq!(entry.signed, None);
451        assert_eq!(entry.source, PortEncodingSource::Author);
452    }
453
454    #[test]
455    fn map_parse_requires_base64_cortical_id_keys() {
456        let id = CorticalID::try_from_bytes(b"cst_port").unwrap();
457        let entry = PortEncoding::from_flag_fields(&ABS_LINEAR.port_encoding_fields());
458        let good = json!({ id.as_base_64(): entry.to_value() });
459        let parsed = parse_port_encoding(&good).unwrap();
460        assert_eq!(parsed[&id.as_base_64()], entry);
461        assert!(parse_port_encoding(&json!({"not base64!": entry.to_value()})).is_err());
462        assert!(parse_port_encoding(&json!([])).is_err());
463    }
464}