Skip to main content

qualia_core_db/sensing/
mod.rs

1//! Caller-bounded contracts for preserving physical measurement meaning when
2//! projecting selected coordinates into QualiaDB's semantic Tensor10D space.
3//!
4//! This module does not acquire devices, convert units, infer coordinates,
5//! establish calibration, verify provenance, or claim scientific truth. A
6//! partial projection remains partial until a caller supplies every required
7//! axis and a declared profile/domain/convention.
8
9use core::num::NonZeroU64;
10
11pub mod acquisition;
12pub mod association;
13pub mod association_table;
14pub mod authority;
15pub mod authorization;
16pub mod container;
17pub mod discovery;
18pub mod fusion;
19mod fusion_time;
20pub mod grounding;
21#[cfg(not(target_arch = "wasm32"))]
22pub mod local_custody;
23pub mod nfc_evidence;
24pub mod projection_map;
25pub mod quin_index;
26pub mod radio_evidence;
27pub mod radio_receipt;
28pub mod record;
29pub mod revocation;
30pub mod sidecar_attestation;
31pub mod signed_evidence;
32pub mod signed_scope;
33pub mod uncertainty;
34
35use crate::container_10d::{
36    field_section::{FieldDescriptor, FieldRepresentationKind, FieldSupportKind, FieldTypeKind},
37    manifold_identity_v2::TypedFieldRecord,
38};
39use crate::tensor::Tensor10D;
40
41/// Tensor10D's existing semantic axis order.
42pub const PROJECTION_AXIS_ORDER: [&str; 10] = crate::container_10d::axis_role::AXIS_ORDER;
43
44/// An opaque registry value, with missing/unknown represented explicitly.
45#[derive(Clone, Copy, Debug, PartialEq, Eq)]
46pub enum SemanticId {
47    Unknown,
48    Known(NonZeroU64),
49}
50
51impl SemanticId {
52    pub const fn new(value: u64) -> Result<Self, ProjectionError> {
53        match NonZeroU64::new(value) {
54            Some(value) => Ok(Self::Known(value)),
55            None => Err(ProjectionError::InvalidIdentifier),
56        }
57    }
58
59    pub const fn from_optional(value: u64) -> Self {
60        match NonZeroU64::new(value) {
61            Some(value) => Self::Known(value),
62            None => Self::Unknown,
63        }
64    }
65
66    pub const fn value(self) -> Option<u64> {
67        match self {
68            Self::Unknown => None,
69            Self::Known(value) => Some(value.get()),
70        }
71    }
72}
73
74/// Broad measurement modality. A registry-defined modality must use a
75/// nonzero identifier; `Unknown` stays unknown and is never guessed.
76#[derive(Clone, Copy, Debug, PartialEq, Eq)]
77pub enum MeasurementModality {
78    Unknown,
79    Electromagnetic,
80    Optical,
81    Acoustic,
82    Inertial,
83    Thermal,
84    Pressure,
85    Registered(NonZeroU64),
86}
87
88impl MeasurementModality {
89    pub const fn registered(id: u64) -> Result<Self, ProjectionError> {
90        match NonZeroU64::new(id) {
91            Some(id) => Ok(Self::Registered(id)),
92            None => Err(ProjectionError::InvalidIdentifier),
93        }
94    }
95}
96
97/// Physical-field metadata paired by the caller's checked container resolver.
98/// FIEL `unit_hash` and MID2 `unit_id` are both preserved independently; this
99/// type does not infer a conversion or claim that those registries agree.
100#[derive(Clone, Copy, Debug, PartialEq, Eq)]
101pub struct PhysicalFieldSemantics {
102    field_id: u64,
103    typed_field_kind: u16,
104    field_name_hash: u64,
105    legacy_unit_hash: u64,
106    typed_unit_id: SemanticId,
107    field_type: FieldTypeKind,
108    support: FieldSupportKind,
109    representation: FieldRepresentationKind,
110    modality: MeasurementModality,
111    physical_quantity: SemanticId,
112}
113
114impl PhysicalFieldSemantics {
115    /// Validate known FIEL descriptor tags while retaining the MID2 kind and
116    /// unit identifier verbatim. `field` and `typed` must refer to the same
117    /// selected field as established by the caller's envelope resolver.
118    pub fn from_existing(
119        field: &FieldDescriptor,
120        typed: &TypedFieldRecord,
121        modality: MeasurementModality,
122        physical_quantity: SemanticId,
123    ) -> Result<Self, ProjectionError> {
124        if field.name_hash == 0
125            || typed.field_id == 0
126            || field.reserved != 0
127            || field.reserved2 != 0
128        {
129            return Err(ProjectionError::InvalidFieldDescriptor);
130        }
131        if typed.flags != 0 {
132            return Err(ProjectionError::InvalidTypedFieldRecord);
133        }
134        let field_type = FieldTypeKind::from_u8(field.type_kind)
135            .ok_or(ProjectionError::UnsupportedFieldDescriptor)?;
136        let support = FieldSupportKind::from_u8(field.support)
137            .ok_or(ProjectionError::UnsupportedFieldDescriptor)?;
138        let representation = FieldRepresentationKind::from_u8(field.representation)
139            .ok_or(ProjectionError::UnsupportedFieldDescriptor)?;
140
141        Ok(Self {
142            field_id: typed.field_id,
143            typed_field_kind: typed.kind,
144            field_name_hash: field.name_hash,
145            legacy_unit_hash: field.unit_hash,
146            typed_unit_id: SemanticId::from_optional(typed.unit_id),
147            field_type,
148            support,
149            representation,
150            modality,
151            physical_quantity,
152        })
153    }
154
155    pub const fn field_id(self) -> u64 {
156        self.field_id
157    }
158
159    /// MID2 kind is retained raw. Consumers must interpret it through the
160    /// versioned typed-field registry rather than infer physical meaning here.
161    pub const fn typed_field_kind(self) -> u16 {
162        self.typed_field_kind
163    }
164
165    pub const fn field_name_hash(self) -> u64 {
166        self.field_name_hash
167    }
168
169    pub const fn legacy_unit_hash(self) -> u64 {
170        self.legacy_unit_hash
171    }
172
173    pub const fn typed_unit_id(self) -> SemanticId {
174        self.typed_unit_id
175    }
176
177    pub const fn field_type(self) -> FieldTypeKind {
178        self.field_type
179    }
180
181    pub const fn support(self) -> FieldSupportKind {
182        self.support
183    }
184
185    pub const fn representation(self) -> FieldRepresentationKind {
186        self.representation
187    }
188
189    pub const fn modality(self) -> MeasurementModality {
190        self.modality
191    }
192
193    pub const fn physical_quantity(self) -> SemanticId {
194        self.physical_quantity
195    }
196}
197
198/// One explicit coordinate claim. `Unknown` carries no numeric default.
199#[derive(Clone, Copy, Debug, PartialEq)]
200pub enum AxisClaim {
201    Unknown,
202    Known(f32),
203}
204
205impl AxisClaim {
206    pub fn known(value: f32) -> Result<Self, ProjectionError> {
207        if !value.is_finite() {
208            return Err(ProjectionError::InvalidCoordinate);
209        }
210        Ok(Self::Known(value))
211    }
212}
213
214/// An interpretation declaration attached to a projection. IDs may remain
215/// unknown; materialization requires them all to be known.
216#[derive(Clone, Copy, Debug, PartialEq)]
217pub struct SemanticProjection {
218    physical: PhysicalFieldSemantics,
219    profile_id: SemanticId,
220    domain_id: SemanticId,
221    coordinate_convention_id: SemanticId,
222    axes: [AxisClaim; 10],
223}
224
225impl SemanticProjection {
226    pub fn new(
227        physical: PhysicalFieldSemantics,
228        profile_id: SemanticId,
229        domain_id: SemanticId,
230        coordinate_convention_id: SemanticId,
231        axes: [AxisClaim; 10],
232    ) -> Result<Self, ProjectionError> {
233        for axis in axes {
234            if let AxisClaim::Known(value) = axis {
235                if !value.is_finite() {
236                    return Err(ProjectionError::InvalidCoordinate);
237                }
238            }
239        }
240        Ok(Self {
241            physical,
242            profile_id,
243            domain_id,
244            coordinate_convention_id,
245            axes,
246        })
247    }
248
249    pub const fn physical(&self) -> &PhysicalFieldSemantics {
250        &self.physical
251    }
252
253    pub const fn profile_id(&self) -> SemanticId {
254        self.profile_id
255    }
256
257    pub const fn domain_id(&self) -> SemanticId {
258        self.domain_id
259    }
260
261    pub const fn coordinate_convention_id(&self) -> SemanticId {
262        self.coordinate_convention_id
263    }
264
265    pub const fn axes(&self) -> &[AxisClaim; 10] {
266        &self.axes
267    }
268
269    /// Materialize a Tensor10D only when every axis and interpretation ID is
270    /// explicitly supplied. No q=0, alpha=1, hash-to-coordinate, or other
271    /// defaults are applied.
272    pub fn materialize(&self) -> Result<ProjectedTensor10D, ProjectionError> {
273        require_known(self.profile_id, ProjectionError::UnknownProfile)?;
274        require_known(self.domain_id, ProjectionError::UnknownDomain)?;
275        require_known(
276            self.coordinate_convention_id,
277            ProjectionError::UnknownCoordinateConvention,
278        )?;
279        let mut values = [0.0f32; 10];
280        for (index, axis) in self.axes.iter().enumerate() {
281            values[index] = match axis {
282                AxisClaim::Known(value) if value.is_finite() => *value,
283                AxisClaim::Known(_) => return Err(ProjectionError::InvalidCoordinate),
284                AxisClaim::Unknown => return Err(ProjectionError::UnknownAxis { index }),
285            };
286        }
287        Ok(ProjectedTensor10D {
288            tensor: Tensor10D::new(
289                values[0], values[1], values[2], values[3], values[4], values[5], values[6],
290                values[7], values[8], values[9],
291            ),
292            physical: self.physical,
293            profile_id: self.profile_id,
294            domain_id: self.domain_id,
295            coordinate_convention_id: self.coordinate_convention_id,
296        })
297    }
298}
299
300/// A fully declared Tensor10D projection together with its physical meaning
301/// and interpretation registry IDs. Tensor coordinates alone are not a
302/// physical observation or evidence of measurement accuracy.
303#[derive(Clone, Copy, Debug, PartialEq)]
304pub struct ProjectedTensor10D {
305    tensor: Tensor10D,
306    physical: PhysicalFieldSemantics,
307    profile_id: SemanticId,
308    domain_id: SemanticId,
309    coordinate_convention_id: SemanticId,
310}
311
312impl ProjectedTensor10D {
313    pub const fn tensor(&self) -> &Tensor10D {
314        &self.tensor
315    }
316
317    pub const fn physical(&self) -> &PhysicalFieldSemantics {
318        &self.physical
319    }
320
321    pub const fn profile_id(&self) -> SemanticId {
322        self.profile_id
323    }
324
325    pub const fn domain_id(&self) -> SemanticId {
326        self.domain_id
327    }
328
329    pub const fn coordinate_convention_id(&self) -> SemanticId {
330        self.coordinate_convention_id
331    }
332}
333
334fn require_known(id: SemanticId, unknown_error: ProjectionError) -> Result<u64, ProjectionError> {
335    match id.value() {
336        Some(value) => Ok(value),
337        None => Err(unknown_error),
338    }
339}
340
341#[derive(Clone, Copy, Debug, PartialEq, Eq)]
342pub enum ProjectionError {
343    InvalidIdentifier,
344    InvalidFieldDescriptor,
345    InvalidTypedFieldRecord,
346    UnsupportedFieldDescriptor,
347    InvalidCoordinate,
348    UnknownAxis { index: usize },
349    UnknownProfile,
350    UnknownDomain,
351    UnknownCoordinateConvention,
352}
353
354#[cfg(test)]
355#[path = "tests.rs"]
356mod tests;