Skip to main content

qualia_core_db/sensing/
projection_map.rs

1//! Explicit scalar-observation mapping into declared Tensor10D axes.
2//!
3//! Coefficients, offsets, units, and interpretation IDs are caller supplied.
4//! This module performs no unit conversion, calibration, scientific inference,
5//! or universal mapping from a physical quantity to Tensor10D coordinates.
6//! Propagated uncertainty covers the declared input uncertainty and f32
7//! conversion only; unknown sensor/calibration errors and intermediate f64
8//! rounding are not included, so it is not a complete error bound.
9
10use super::{AxisClaim, PhysicalFieldSemantics, ProjectionError, SemanticId, SemanticProjection};
11
12/// A finite scalar observation and its explicit physical quantity and unit.
13#[derive(Clone, Copy, Debug, PartialEq)]
14pub struct PhysicalObservation {
15    quantity_id: SemanticId,
16    unit_id: SemanticId,
17    value: ObservationValue,
18    absolute_uncertainty: ObservationUncertainty,
19}
20
21#[derive(Clone, Copy, Debug, PartialEq)]
22pub enum ObservationValue {
23    Unknown,
24    Known(f64),
25}
26
27/// Absolute uncertainty in the same unit as the associated observation.
28#[derive(Clone, Copy, Debug, PartialEq)]
29pub enum ObservationUncertainty {
30    Unknown,
31    Known(f64),
32}
33
34impl PhysicalObservation {
35    pub fn new(
36        quantity_id: SemanticId,
37        unit_id: SemanticId,
38        value: ObservationValue,
39        absolute_uncertainty: ObservationUncertainty,
40    ) -> Result<Self, ProjectionMapError> {
41        if quantity_id.value().is_none() || unit_id.value().is_none() {
42            return Err(ProjectionMapError::UnknownPhysicalSemantics);
43        }
44        if let ObservationValue::Known(value) = value {
45            if !value.is_finite() {
46                return Err(ProjectionMapError::InvalidObservation);
47            }
48        }
49        if let ObservationUncertainty::Known(value) = absolute_uncertainty {
50            if !value.is_finite() || value < 0.0 {
51                return Err(ProjectionMapError::InvalidObservation);
52            }
53        }
54        Ok(Self {
55            quantity_id,
56            unit_id,
57            value,
58            absolute_uncertainty,
59        })
60    }
61
62    pub const fn quantity_id(self) -> SemanticId {
63        self.quantity_id
64    }
65    pub const fn unit_id(self) -> SemanticId {
66        self.unit_id
67    }
68    pub const fn value(self) -> ObservationValue {
69        self.value
70    }
71    pub const fn absolute_uncertainty(self) -> ObservationUncertainty {
72        self.absolute_uncertainty
73    }
74}
75
76/// Caller-declared affine mapping: `axis = observation * coefficient + offset`.
77/// The coefficient's implied units and coordinate convention are identified
78/// by the containing `ProjectionMap`; this type does not interpret them.
79#[derive(Clone, Copy, Debug, PartialEq)]
80pub struct AxisMapping {
81    coefficient: f64,
82    offset: f64,
83}
84
85impl AxisMapping {
86    pub fn new(coefficient: f64, offset: f64) -> Result<Self, ProjectionMapError> {
87        if !coefficient.is_finite() || !offset.is_finite() {
88            return Err(ProjectionMapError::InvalidMapping);
89        }
90        Ok(Self {
91            coefficient,
92            offset,
93        })
94    }
95
96    pub const fn coefficient(self) -> f64 {
97        self.coefficient
98    }
99    pub const fn offset(self) -> f64 {
100        self.offset
101    }
102}
103
104/// Mapping declaration for one physical field into one interpretation profile.
105/// `axes[i] == None` means that coordinate is unknown and remains so.
106#[derive(Clone, Copy, Debug, PartialEq)]
107pub struct ProjectionMap {
108    mapping_id: u64,
109    physical: PhysicalFieldSemantics,
110    profile_id: SemanticId,
111    domain_id: SemanticId,
112    coordinate_convention_id: SemanticId,
113    quantity_id: SemanticId,
114    unit_id: SemanticId,
115    axes: [Option<AxisMapping>; 10],
116}
117
118impl ProjectionMap {
119    #[allow(clippy::too_many_arguments)]
120    pub fn new(
121        mapping_id: u64,
122        physical: PhysicalFieldSemantics,
123        profile_id: SemanticId,
124        domain_id: SemanticId,
125        coordinate_convention_id: SemanticId,
126        quantity_id: SemanticId,
127        unit_id: SemanticId,
128        axes: [Option<AxisMapping>; 10],
129    ) -> Result<Self, ProjectionMapError> {
130        if mapping_id == 0 {
131            return Err(ProjectionMapError::InvalidIdentifier);
132        }
133        if profile_id.value().is_none()
134            || domain_id.value().is_none()
135            || coordinate_convention_id.value().is_none()
136            || quantity_id.value().is_none()
137            || unit_id.value().is_none()
138        {
139            return Err(ProjectionMapError::UnknownInterpretation);
140        }
141        if physical.physical_quantity().value() != quantity_id.value() {
142            return Err(ProjectionMapError::QuantityMismatch);
143        }
144        if physical.typed_unit_id().value() != unit_id.value() {
145            return Err(ProjectionMapError::UnitMismatch);
146        }
147        Ok(Self {
148            mapping_id,
149            physical,
150            profile_id,
151            domain_id,
152            coordinate_convention_id,
153            quantity_id,
154            unit_id,
155            axes,
156        })
157    }
158
159    pub const fn mapping_id(self) -> u64 {
160        self.mapping_id
161    }
162
163    /// Apply this exact mapping declaration to one observation. Unknown input
164    /// values and unmapped axes remain `AxisClaim::Unknown`; numeric overflow
165    /// rejects the whole result before a projection is returned.
166    pub fn project(
167        self,
168        observation: PhysicalObservation,
169    ) -> Result<MappedProjection, ProjectionMapError> {
170        if observation.quantity_id != self.quantity_id {
171            return Err(ProjectionMapError::QuantityMismatch);
172        }
173        if observation.unit_id != self.unit_id {
174            return Err(ProjectionMapError::UnitMismatch);
175        }
176
177        let mut axes = [AxisClaim::Unknown; 10];
178        let mut axis_uncertainty = [AxisUncertainty::Unknown; 10];
179        if let ObservationValue::Known(value) = observation.value {
180            let mut i = 0;
181            while i < 10 {
182                if let Some(mapping) = self.axes[i] {
183                    let mapped = value * mapping.coefficient + mapping.offset;
184                    let mapped_f32 = mapped as f32;
185                    if !mapped.is_finite() || !mapped_f32.is_finite() {
186                        return Err(ProjectionMapError::CoordinateOverflow { axis: i });
187                    }
188                    axes[i] =
189                        AxisClaim::known(mapped_f32).map_err(ProjectionMapError::Projection)?;
190                    if let ObservationUncertainty::Known(uncertainty) =
191                        observation.absolute_uncertainty
192                    {
193                        // Include the deterministic f64-to-f32 coordinate
194                        // quantization error in the propagated absolute bound.
195                        let rounding_error = (mapped - mapped_f32 as f64).abs();
196                        let mapped_uncertainty =
197                            uncertainty * mapping.coefficient.abs() + rounding_error;
198                        let uncertainty_f32 = round_up_f64_to_f32(mapped_uncertainty)
199                            .ok_or(ProjectionMapError::UncertaintyOverflow { axis: i })?;
200                        axis_uncertainty[i] = AxisUncertainty::Known(uncertainty_f32);
201                    }
202                }
203                i += 1;
204            }
205        }
206
207        let projection = SemanticProjection::new(
208            self.physical,
209            self.profile_id,
210            self.domain_id,
211            self.coordinate_convention_id,
212            axes,
213        )
214        .map_err(ProjectionMapError::Projection)?;
215        Ok(MappedProjection {
216            mapping_id: self.mapping_id,
217            observation,
218            projection,
219            axis_uncertainty,
220        })
221    }
222}
223
224/// Output keeps physical observation and uncertainty alongside the 10D
225/// projection. The tensor is an interpretation, not a replacement for the
226/// physical value or evidence record.
227#[derive(Clone, Copy, Debug, PartialEq)]
228pub struct MappedProjection {
229    mapping_id: u64,
230    observation: PhysicalObservation,
231    projection: SemanticProjection,
232    axis_uncertainty: [AxisUncertainty; 10],
233}
234
235#[derive(Clone, Copy, Debug, PartialEq)]
236pub enum AxisUncertainty {
237    Unknown,
238    /// Rounded outward to f32. This includes scaled input uncertainty and
239    /// f64-to-f32 coordinate quantization only. It excludes f64 intermediate
240    /// arithmetic error and any sensor, calibration, or model error.
241    Known(f32),
242}
243
244/// Convert a nonnegative finite f64 bound to f32 without rounding inward.
245/// `None` means the value cannot be represented as a finite f32 upper bound.
246fn round_up_f64_to_f32(value: f64) -> Option<f32> {
247    if !value.is_finite() || value < 0.0 || value > f32::MAX as f64 {
248        return None;
249    }
250    let mut rounded = value as f32;
251    if !rounded.is_finite() {
252        return None;
253    }
254    if (rounded as f64) < value {
255        let next_bits = rounded.to_bits().checked_add(1)?;
256        rounded = f32::from_bits(next_bits);
257        if !rounded.is_finite() {
258            return None;
259        }
260    }
261    Some(rounded)
262}
263
264impl MappedProjection {
265    pub const fn mapping_id(self) -> u64 {
266        self.mapping_id
267    }
268    pub const fn observation(self) -> PhysicalObservation {
269        self.observation
270    }
271    pub const fn projection(&self) -> &SemanticProjection {
272        &self.projection
273    }
274    pub const fn axis_uncertainty(&self) -> &[AxisUncertainty; 10] {
275        &self.axis_uncertainty
276    }
277}
278
279#[derive(Clone, Copy, Debug, PartialEq, Eq)]
280pub enum ProjectionMapError {
281    InvalidIdentifier,
282    UnknownPhysicalSemantics,
283    UnknownInterpretation,
284    InvalidObservation,
285    InvalidMapping,
286    QuantityMismatch,
287    UnitMismatch,
288    CoordinateOverflow { axis: usize },
289    UncertaintyOverflow { axis: usize },
290    Projection(ProjectionError),
291}
292
293#[cfg(test)]
294#[path = "projection_map_tests.rs"]
295mod tests;