Skip to main content

qualia_core_db/sensing/acquisition/
tensor.rs

1use super::*;
2#[derive(Clone, Copy, Debug, PartialEq, Eq)]
3pub enum ByteOrder {
4    Little,
5    Big,
6}
7#[derive(Clone, Copy, Debug, PartialEq, Eq)]
8pub enum Encoding {
9    /// Existing scalar semantics, extended without allocating new wire IDs.
10    Shared(Scalar),
11    U16,
12    U32,
13    U64,
14    ComplexI16,
15    ComplexF64,
16    /// Unknown registered encoding remains byte-readable; numeric access is unsupported.
17    Opaque {
18        profile: crate::sensing::SemanticId,
19        element_bytes: u32,
20    },
21}
22impl Encoding {
23    pub fn bytes(self) -> usize {
24        match self {
25            Self::Shared(s) => s.bytes() as usize,
26            Self::U16 => 2,
27            Self::U32 => 4,
28            Self::U64 => 8,
29            Self::Opaque { element_bytes, .. } => element_bytes as usize,
30            Self::ComplexI16 => 4,
31            Self::ComplexF64 => 16,
32        }
33    }
34    pub fn complex(self) -> bool {
35        matches!(
36            self,
37            Self::Shared(Scalar::ComplexF32) | Self::ComplexI16 | Self::ComplexF64
38        )
39    }
40}
41#[derive(Clone, Copy, Debug, PartialEq, Eq)]
42pub enum ComponentOrder {
43    Scalar,
44    RealImag,
45    ImagReal,
46}
47/// Axis meanings are explicit. No implicit image row/column interpretation.
48#[derive(Clone, Copy, Debug, PartialEq, Eq)]
49pub enum Axis {
50    Sample,
51    Channel,
52    Sensor,
53    Lag,
54    LeftChannel,
55    RightChannel,
56    Registered(crate::sensing::SemanticId),
57}
58#[derive(Clone, Copy, Debug)]
59pub struct Layout {
60    pub rank: u8,
61    pub extents: [u32; 4],
62    pub strides: [usize; 4],
63    pub axes: [Axis; 4],
64    pub encoding: Encoding,
65    pub byte_order: ByteOrder,
66    pub components: ComponentOrder,
67}
68impl Layout {
69    pub fn span(self) -> Result<usize, Error> {
70        let rank = usize::from(self.rank);
71        if let Encoding::Opaque {
72            profile,
73            element_bytes,
74        } = self.encoding
75        {
76            profile.value().ok_or(Error::Identity)?;
77            if element_bytes == 0 {
78                return Err(Error::Encoding);
79            }
80        }
81        if !(1..=4).contains(&rank)
82            || self.extents[..rank].contains(&0)
83            || self.extents[rank..].iter().any(|&x| x != 0)
84            || self.strides[rank..].iter().any(|&x| x != 0)
85            || (self.encoding.complex() == (self.components == ComponentOrder::Scalar))
86        {
87            return Err(Error::Shape);
88        }
89        for i in 0..rank {
90            if let Axis::Registered(id) = self.axes[i] {
91                id.value().ok_or(Error::Identity)?;
92            }
93            if self.axes[..i].contains(&self.axes[i]) {
94                return Err(Error::Shape);
95            }
96        }
97        let mut span = self.encoding.bytes();
98        let mut axes = [(0usize, 0u32); 4];
99        let mut n = 0;
100        for i in 0..rank {
101            if self.extents[i] > 1 {
102                axes[n] = (self.strides[i], self.extents[i]);
103                n += 1;
104            }
105        }
106        axes[..n].sort_unstable_by_key(|x| x.0);
107        for &(stride, extent) in &axes[..n] {
108            if stride < span {
109                return Err(Error::Shape);
110            }
111            span = span
112                .checked_add(
113                    stride
114                        .checked_mul((extent - 1) as usize)
115                        .ok_or(Error::Overflow)?,
116                )
117                .ok_or(Error::Overflow)?;
118        }
119        Ok(span)
120    }
121}
122/// All bytes including NaN payloads remain available; scientific access rejects nonfinite lanes.
123#[derive(Clone, Copy, Debug)]
124pub struct TensorView<'a> {
125    region: Region<'a>,
126    layout: Layout,
127    context: Context,
128    clock: Option<Clock>,
129    axes: SignalAxes,
130}
131impl<'a> TensorView<'a> {
132    pub fn admit(
133        region: Region<'a>,
134        layout: Layout,
135        context: Context,
136        clock: Option<Clock>,
137        axes: SignalAxes,
138    ) -> Result<Self, Error> {
139        if layout.span()? != region.bytes().len() {
140            return Err(Error::Bounds);
141        }
142        context.validate()?;
143        axes.validate()?;
144        if !layout.encoding.complex()
145            && (axes.complex_convention.is_some() || axes.phase_origin.is_some())
146        {
147            return Err(Error::Semantics);
148        }
149        if let Some(clock) = clock {
150            let i = layout.axes[..usize::from(layout.rank)]
151                .iter()
152                .position(|x| *x == Axis::Sample)
153                .ok_or(Error::Clock)?;
154            clock.time_at(u64::from(layout.extents[i] - 1))?;
155        }
156        Ok(Self {
157            region,
158            layout,
159            context,
160            clock,
161            axes,
162        })
163    }
164    pub fn region(self) -> Region<'a> {
165        self.region
166    }
167    pub fn layout(self) -> Layout {
168        self.layout
169    }
170    pub fn context(self) -> Context {
171        self.context
172    }
173    pub fn clock(self) -> Option<Clock> {
174        self.clock
175    }
176    pub fn signal_axes(self) -> SignalAxes {
177        self.axes
178    }
179    pub fn element(self, index: [u32; 4]) -> Result<&'a [u8], Error> {
180        let mut offset = 0usize;
181        for (i, &value) in index.iter().enumerate() {
182            if i >= usize::from(self.layout.rank) {
183                if value != 0 {
184                    return Err(Error::Bounds);
185                }
186                continue;
187            }
188            if value >= self.layout.extents[i] {
189                return Err(Error::Bounds);
190            }
191            offset = offset
192                .checked_add(
193                    (value as usize)
194                        .checked_mul(self.layout.strides[i])
195                        .ok_or(Error::Overflow)?,
196                )
197                .ok_or(Error::Overflow)?;
198        }
199        self.region
200            .bytes()
201            .get(
202                offset
203                    ..offset
204                        .checked_add(self.layout.encoding.bytes())
205                        .ok_or(Error::Overflow)?,
206            )
207            .ok_or(Error::Bounds)
208    }
209    /// No calibration is applied. Known quantity/unit and finite lanes are required.
210    pub fn numeric(self, index: [u32; 4]) -> Result<[f64; 2], Error> {
211        self.context.quantity.require_known()?;
212        let b = self.element(index)?;
213        let big = self.layout.byte_order == ByteOrder::Big;
214        let u16v = |b: &[u8]| {
215            if big {
216                u16::from_be_bytes(b.try_into().unwrap())
217            } else {
218                u16::from_le_bytes(b.try_into().unwrap())
219            }
220        };
221        let u32v = |b: &[u8]| {
222            if big {
223                u32::from_be_bytes(b.try_into().unwrap())
224            } else {
225                u32::from_le_bytes(b.try_into().unwrap())
226            }
227        };
228        let u64v = |b: &[u8]| {
229            if big {
230                u64::from_be_bytes(b.try_into().unwrap())
231            } else {
232                u64::from_le_bytes(b.try_into().unwrap())
233            }
234        };
235        let mut value = match self.layout.encoding {
236            Encoding::U16 => [u16v(b) as f64, 0.0],
237            Encoding::Opaque { .. } => return Err(Error::Unsupported),
238            Encoding::U32 => [u32v(b) as f64, 0.0],
239            Encoding::U64 => {
240                let n = u64v(b);
241                if n > 9_007_199_254_740_992 {
242                    return Err(Error::Unsupported);
243                }
244                [n as f64, 0.0]
245            }
246            Encoding::ComplexI16 => [u16v(&b[..2]) as i16 as f64, u16v(&b[2..]) as i16 as f64],
247            Encoding::ComplexF64 => [f64::from_bits(u64v(&b[..8])), f64::from_bits(u64v(&b[8..]))],
248            Encoding::Shared(s) => match s {
249                Scalar::U8 => [b[0] as f64, 0.0],
250                Scalar::I16 => [u16v(b) as i16 as f64, 0.0],
251                Scalar::I32 => [u32v(b) as i32 as f64, 0.0],
252                Scalar::I24 => {
253                    let n = if big {
254                        ((b[0] as i32) << 16) | ((b[1] as i32) << 8) | b[2] as i32
255                    } else {
256                        ((b[2] as i32) << 16) | ((b[1] as i32) << 8) | b[0] as i32
257                    };
258                    [(n << 8 >> 8) as f64, 0.0]
259                }
260                Scalar::F32 => [f32::from_bits(u32v(b)) as f64, 0.0],
261                Scalar::F64 => [f64::from_bits(u64v(b)), 0.0],
262                Scalar::ComplexF32 => [
263                    f32::from_bits(u32v(&b[..4])) as f64,
264                    f32::from_bits(u32v(&b[4..])) as f64,
265                ],
266            },
267        };
268        if self.layout.components == ComponentOrder::ImagReal {
269            value.swap(0, 1);
270        }
271        if value.iter().any(|x| !x.is_finite()) {
272            return Err(Error::Nonfinite);
273        }
274        Ok(value)
275    }
276}