Skip to main content

qualia_core_db/sensing/
uncertainty.rs

1//! Typed, field-bound uncertainty declarations for sensing data.
2//!
3//! The record reuses the selected FIEL descriptor and MID2 typed-field record
4//! represented by `PhysicalFieldSemantics`. It preserves their unit IDs
5//! independently, adds no Quin metadata convention, and makes unknown explicit.
6//! Numeric declarations are caller assertions; this module verifies shape and
7//! finite values, not scientific validity, calibration, probability quality,
8//! source authority, or evidence authenticity.
9
10use core::num::{NonZeroU32, NonZeroU64};
11
12use crate::NQuin;
13
14use super::{
15    projection_map::{AxisUncertainty, MappedProjection},
16    PhysicalFieldSemantics, SemanticId,
17};
18
19/// q_hash-based predicates proposed for a future sensing uncertainty vocabulary.
20/// These names are not asserted to exist in an already registered ontology.
21pub mod proposed_predicates {
22    use crate::q_hash;
23
24    pub const RDF_TYPE: u64 = q_hash("http://www.w3.org/1999/02/22-rdf-syntax-ns#type");
25    pub const UNCERTAINTY_CLASS: u64 = q_hash("urn:qualia:sensing:UncertaintyRecord");
26    pub const HAS_FIELD_ID: u64 = q_hash("urn:qualia:sensing:fieldId");
27    pub const HAS_FIELD_KIND: u64 = q_hash("urn:qualia:sensing:mid2FieldKind");
28    pub const HAS_FIELD_NAME_HASH: u64 = q_hash("urn:qualia:sensing:fielNameHash");
29    pub const HAS_LEGACY_UNIT_HASH: u64 = q_hash("urn:qualia:sensing:fielUnitHash");
30    pub const HAS_TYPED_UNIT_ID: u64 = q_hash("urn:qualia:sensing:mid2UnitId");
31    pub const HAS_ESTIMATE_UNIT_ID: u64 = q_hash("urn:qualia:sensing:estimateUnitId");
32    pub const HAS_AXIS_UNIT_ID: u64 = q_hash("urn:qualia:sensing:projectionAxisUnitId");
33    pub const HAS_QUANTITY_ID: u64 = q_hash("urn:qualia:sensing:physicalQuantityId");
34    pub const HAS_SCOPE_KIND: u64 = q_hash("urn:qualia:sensing:uncertaintyScopeKind");
35    pub const HAS_MAPPING_ID: u64 = q_hash("urn:qualia:sensing:projectionMappingId");
36    pub const HAS_AXIS_INDEX: u64 = q_hash("urn:qualia:sensing:projectionAxisIndex");
37    pub const HAS_PROFILE_ID: u64 = q_hash("urn:qualia:sensing:projectionProfileId");
38    pub const HAS_DOMAIN_ID: u64 = q_hash("urn:qualia:sensing:projectionDomainId");
39    pub const HAS_COORDINATE_CONVENTION_ID: u64 =
40        q_hash("urn:qualia:sensing:coordinateConventionId");
41    pub const HAS_METHOD_ID: u64 = q_hash("urn:qualia:sensing:methodId");
42    pub const HAS_METHOD_VERSION: u64 = q_hash("urn:qualia:sensing:methodVersion");
43    pub const HAS_EVIDENCE_CITATION: u64 = q_hash("urn:qualia:sensing:evidenceCitationId");
44    pub const HAS_ESTIMATE_KIND: u64 = q_hash("urn:qualia:sensing:estimateKind");
45    pub const HAS_ABSOLUTE_BOUND: u64 = q_hash("urn:qualia:sensing:absoluteBound");
46    pub const HAS_RELATIVE_BOUND_MILLIONTHS: u64 =
47        q_hash("urn:qualia:sensing:relativeBoundMillionths");
48    pub const HAS_INTERVAL_LOWER: u64 = q_hash("urn:qualia:sensing:intervalLower");
49    pub const HAS_INTERVAL_UPPER: u64 = q_hash("urn:qualia:sensing:intervalUpper");
50    pub const HAS_COVERAGE_MILLIONTHS: u64 = q_hash("urn:qualia:sensing:coverageMillionths");
51    pub const HAS_METHOD_STATE: u64 = q_hash("urn:qualia:sensing:methodState");
52    pub const HAS_EVIDENCE_STATE: u64 = q_hash("urn:qualia:sensing:evidenceState");
53    pub const HAS_TYPED_UNIT_STATE: u64 = q_hash("urn:qualia:sensing:typedUnitState");
54    pub const HAS_LEGACY_UNIT_STATE: u64 = q_hash("urn:qualia:sensing:legacyUnitState");
55    pub const HAS_QUANTITY_STATE: u64 = q_hash("urn:qualia:sensing:quantityState");
56}
57
58const ID_MASK: u64 = 0x0FFF_FFFF_FFFF_FFFF;
59pub const UNCERTAINTY_SCALE: u32 = 1_000_000;
60pub const MAX_UNCERTAINTY_QUINS: usize = 40;
61
62#[derive(Clone, Copy, Debug, PartialEq, Eq)]
63pub struct MethodVersion {
64    method_id: SemanticId,
65    version: NonZeroU32,
66}
67
68impl MethodVersion {
69    pub fn new(method_id: SemanticId, version: u32) -> Result<Self, UncertaintyError> {
70        require_id(method_id)?;
71        let version = NonZeroU32::new(version).ok_or(UncertaintyError::InvalidMethod)?;
72        Ok(Self { method_id, version })
73    }
74
75    pub const fn method_id(self) -> SemanticId {
76        self.method_id
77    }
78    pub const fn version(self) -> u32 {
79        self.version.get()
80    }
81}
82
83/// A numeric physical error bound, a dimensionless relative bound, or a
84/// confidence interval. Confidence level is a method parameter; it is not a
85/// probability that the measurement or proposition is true.
86#[derive(Clone, Copy, Debug, PartialEq)]
87pub enum UncertaintyEstimate {
88    Unknown,
89    AbsoluteBound {
90        value: f64,
91        unit_id: SemanticId,
92    },
93    /// Dimensionless ratio in millionths; values above one million (100%) are
94    /// valid and are not silently clamped.
95    RelativeBoundMillionths(u32),
96    ConfidenceInterval {
97        lower: f64,
98        upper: f64,
99        coverage_millionths: u32,
100        unit_id: SemanticId,
101    },
102}
103
104#[derive(Clone, Copy, Debug, PartialEq, Eq)]
105pub struct EvidenceReference(NonZeroU64);
106
107impl EvidenceReference {
108    pub const fn new(citation_id: u64) -> Result<Self, UncertaintyError> {
109        if citation_id == 0 || citation_id > ID_MASK {
110            Err(UncertaintyError::InvalidIdentifier)
111        } else {
112            match NonZeroU64::new(citation_id) {
113                Some(id) => Ok(Self(id)),
114                None => Err(UncertaintyError::InvalidIdentifier),
115            }
116        }
117    }
118
119    pub const fn citation_id(self) -> u64 {
120        self.0.get()
121    }
122}
123
124/// Where the uncertainty applies. Projection coordinates remain distinct from
125/// the source field's physical quantity and units.
126#[derive(Clone, Copy, Debug, PartialEq, Eq)]
127pub enum UncertaintyScope {
128    PhysicalField,
129    ProjectionAxis {
130        mapping_id: u64,
131        axis_index: u8,
132        axis_unit_id: SemanticId,
133        profile_id: SemanticId,
134        domain_id: SemanticId,
135        coordinate_convention_id: SemanticId,
136    },
137}
138
139/// Immutable fixed-size declaration bound to one existing FIEL/MID2 field.
140#[derive(Clone, Copy, Debug, PartialEq)]
141pub struct UncertaintyRecord {
142    record_id: u64,
143    field: PhysicalFieldSemantics,
144    scope: UncertaintyScope,
145    estimate: UncertaintyEstimate,
146    method: Option<MethodVersion>,
147    evidence: Option<EvidenceReference>,
148}
149
150impl UncertaintyRecord {
151    pub fn new(
152        record_id: u64,
153        field: PhysicalFieldSemantics,
154        estimate: UncertaintyEstimate,
155        method: Option<MethodVersion>,
156        evidence_citation_id: Option<u64>,
157    ) -> Result<Self, UncertaintyError> {
158        let evidence = match evidence_citation_id {
159            Some(id) => Some(EvidenceReference::new(id)?),
160            None => None,
161        };
162        Self::with_scope(
163            record_id,
164            field,
165            UncertaintyScope::PhysicalField,
166            estimate,
167            method,
168            evidence,
169        )
170    }
171
172    /// Convert an already-propagated projection axis uncertainty. The caller
173    /// must supply the axis unit because Tensor10D profile/domain/convention
174    /// declarations do not define a unit conversion by themselves.
175    pub fn from_projection_axis(
176        record_id: u64,
177        projection: &MappedProjection,
178        axis_index: usize,
179        axis_unit_id: SemanticId,
180        method: Option<MethodVersion>,
181        evidence_citation_id: Option<u64>,
182    ) -> Result<Self, UncertaintyError> {
183        if axis_index >= 10 {
184            return Err(UncertaintyError::InvalidAxis);
185        }
186        require_id(axis_unit_id)?;
187        let estimate = match projection.axis_uncertainty()[axis_index] {
188            AxisUncertainty::Unknown => UncertaintyEstimate::Unknown,
189            AxisUncertainty::Known(value) if value.is_finite() && value >= 0.0 => {
190                UncertaintyEstimate::AbsoluteBound {
191                    value: value as f64,
192                    unit_id: axis_unit_id,
193                }
194            }
195            AxisUncertainty::Known(_) => return Err(UncertaintyError::InvalidEstimate),
196        };
197        let declaration = projection.projection();
198        let scope = UncertaintyScope::ProjectionAxis {
199            mapping_id: projection.mapping_id(),
200            axis_index: axis_index as u8,
201            axis_unit_id,
202            profile_id: declaration.profile_id(),
203            domain_id: declaration.domain_id(),
204            coordinate_convention_id: declaration.coordinate_convention_id(),
205        };
206        let evidence = match evidence_citation_id {
207            Some(id) => Some(EvidenceReference::new(id)?),
208            None => None,
209        };
210        Self::with_scope(
211            record_id,
212            *declaration.physical(),
213            scope,
214            estimate,
215            method,
216            evidence,
217        )
218    }
219
220    fn with_scope(
221        record_id: u64,
222        field: PhysicalFieldSemantics,
223        scope: UncertaintyScope,
224        estimate: UncertaintyEstimate,
225        method: Option<MethodVersion>,
226        evidence: Option<EvidenceReference>,
227    ) -> Result<Self, UncertaintyError> {
228        if record_id == 0 || record_id > ID_MASK || field.field_id() > ID_MASK {
229            return Err(UncertaintyError::InvalidIdentifier);
230        }
231        check_optional_id(field.physical_quantity())?;
232        check_optional_id(field.typed_unit_id())?;
233        if field.field_name_hash() > ID_MASK || field.legacy_unit_hash() > ID_MASK {
234            return Err(UncertaintyError::InvalidIdentifier);
235        }
236        if let Some(method) = method {
237            require_id(method.method_id)?;
238        }
239        if !matches!(estimate, UncertaintyEstimate::Unknown)
240            && field.physical_quantity().value().is_none()
241        {
242            return Err(UncertaintyError::UnknownRequiredSemantics);
243        }
244        validate_scope(scope)?;
245        validate_estimate(field, scope, estimate)?;
246        Ok(Self {
247            record_id,
248            field,
249            scope,
250            estimate,
251            method,
252            evidence,
253        })
254    }
255
256    pub const fn record_id(self) -> u64 {
257        self.record_id
258    }
259    pub const fn field(self) -> PhysicalFieldSemantics {
260        self.field
261    }
262    pub const fn scope(self) -> UncertaintyScope {
263        self.scope
264    }
265    pub const fn estimate(self) -> UncertaintyEstimate {
266        self.estimate
267    }
268    pub const fn method(self) -> Option<MethodVersion> {
269        self.method
270    }
271    pub const fn evidence(self) -> Option<EvidenceReference> {
272        self.evidence
273    }
274
275    /// Export this declaration as a bounded graph of Quins. Every row uses
276    /// metadata=0 and the existing five-field `NQuin::calculate_parity` ABI.
277    /// Predicates are proposed q_hash vocabulary terms, not yet registered
278    /// universal terms. Unknown optional values get explicit state rows.
279    pub fn write_quins(&self, out: &mut [NQuin]) -> Result<usize, UncertaintyError> {
280        let count = self.required_quins();
281        if out.len() < count {
282            return Err(UncertaintyError::Capacity {
283                required: count,
284                available: out.len(),
285            });
286        }
287        let encoded_estimate = self.encode_estimate()?;
288        let mut cursor = 0;
289        use proposed_predicates as p;
290        self.push(out, &mut cursor, p::RDF_TYPE, p::UNCERTAINTY_CLASS);
291        self.push(out, &mut cursor, p::HAS_FIELD_ID, self.field.field_id());
292        self.push_integer(
293            out,
294            &mut cursor,
295            p::HAS_FIELD_KIND,
296            self.field.typed_field_kind() as u64,
297        );
298        self.push(
299            out,
300            &mut cursor,
301            p::HAS_FIELD_NAME_HASH,
302            self.field.field_name_hash(),
303        );
304        self.push_integer(
305            out,
306            &mut cursor,
307            p::HAS_LEGACY_UNIT_STATE,
308            bool_id(self.field.legacy_unit_hash() != 0),
309        );
310        if self.field.legacy_unit_hash() != 0 {
311            self.push(
312                out,
313                &mut cursor,
314                p::HAS_LEGACY_UNIT_HASH,
315                self.field.legacy_unit_hash(),
316            );
317        }
318        self.push_optional_id(
319            out,
320            &mut cursor,
321            p::HAS_QUANTITY_STATE,
322            p::HAS_QUANTITY_ID,
323            self.field.physical_quantity(),
324        );
325        self.push_optional_id(
326            out,
327            &mut cursor,
328            p::HAS_TYPED_UNIT_STATE,
329            p::HAS_TYPED_UNIT_ID,
330            self.field.typed_unit_id(),
331        );
332        match self.scope {
333            UncertaintyScope::PhysicalField => {
334                self.push_integer(out, &mut cursor, p::HAS_SCOPE_KIND, 0)
335            }
336            UncertaintyScope::ProjectionAxis {
337                mapping_id,
338                axis_index,
339                axis_unit_id,
340                profile_id,
341                domain_id,
342                coordinate_convention_id,
343            } => {
344                self.push_integer(out, &mut cursor, p::HAS_SCOPE_KIND, 1);
345                self.push(out, &mut cursor, p::HAS_MAPPING_ID, mapping_id);
346                self.push_integer(out, &mut cursor, p::HAS_AXIS_INDEX, axis_index as u64);
347                self.push(
348                    out,
349                    &mut cursor,
350                    p::HAS_PROFILE_ID,
351                    profile_id.value().unwrap_or(0),
352                );
353                self.push(
354                    out,
355                    &mut cursor,
356                    p::HAS_DOMAIN_ID,
357                    domain_id.value().unwrap_or(0),
358                );
359                self.push(
360                    out,
361                    &mut cursor,
362                    p::HAS_COORDINATE_CONVENTION_ID,
363                    coordinate_convention_id.value().unwrap_or(0),
364                );
365                self.push(
366                    out,
367                    &mut cursor,
368                    p::HAS_AXIS_UNIT_ID,
369                    axis_unit_id.value().unwrap_or(0),
370                );
371            }
372        }
373        self.push_integer(
374            out,
375            &mut cursor,
376            p::HAS_METHOD_STATE,
377            bool_id(self.method.is_some()),
378        );
379        if let Some(method) = self.method {
380            self.push(
381                out,
382                &mut cursor,
383                p::HAS_METHOD_ID,
384                method.method_id.value().unwrap_or(0),
385            );
386            self.push_integer(
387                out,
388                &mut cursor,
389                p::HAS_METHOD_VERSION,
390                method.version() as u64,
391            );
392        }
393        self.push_integer(
394            out,
395            &mut cursor,
396            p::HAS_EVIDENCE_STATE,
397            bool_id(self.evidence.is_some()),
398        );
399        if let Some(evidence) = self.evidence {
400            self.push(
401                out,
402                &mut cursor,
403                p::HAS_EVIDENCE_CITATION,
404                evidence.citation_id(),
405            );
406        }
407        self.write_estimate(out, &mut cursor, encoded_estimate);
408        Ok(cursor)
409    }
410
411    fn required_quins(self) -> usize {
412        let base = 10
413            + count_if(self.field.legacy_unit_hash() != 0)
414            + count_if(self.field.physical_quantity().value().is_some())
415            + count_if(self.field.typed_unit_id().value().is_some())
416            + count_if(self.method.is_some()) * 2
417            + count_if(self.evidence.is_some());
418        let scope = match self.scope {
419            UncertaintyScope::PhysicalField => 0,
420            UncertaintyScope::ProjectionAxis { .. } => 6,
421        };
422        base + scope
423            + match self.estimate {
424                UncertaintyEstimate::Unknown => 1,
425                UncertaintyEstimate::AbsoluteBound { .. } => 3,
426                UncertaintyEstimate::RelativeBoundMillionths(_) => 2,
427                UncertaintyEstimate::ConfidenceInterval { .. } => 5,
428            }
429    }
430
431    fn push(&self, out: &mut [NQuin], cursor: &mut usize, predicate: u64, object: u64) {
432        out[*cursor] = make_quin(self.record_id, predicate, object);
433        *cursor += 1;
434    }
435
436    fn push_integer(&self, out: &mut [NQuin], cursor: &mut usize, predicate: u64, value: u64) {
437        self.push(out, cursor, predicate, integer_object(value));
438    }
439
440    fn push_optional_id(
441        &self,
442        out: &mut [NQuin],
443        cursor: &mut usize,
444        state_predicate: u64,
445        value_predicate: u64,
446        value: SemanticId,
447    ) {
448        if let Some(value) = value.value() {
449            self.push_integer(out, cursor, state_predicate, 1);
450            self.push(out, cursor, value_predicate, value);
451        } else {
452            self.push_integer(out, cursor, state_predicate, 0);
453        }
454    }
455
456    fn encode_estimate(&self) -> Result<EncodedEstimate, UncertaintyError> {
457        Ok(match self.estimate {
458            UncertaintyEstimate::Unknown => EncodedEstimate::Unknown,
459            UncertaintyEstimate::AbsoluteBound { value, unit_id } => EncodedEstimate::Absolute {
460                value: float_object(round_up(value).ok_or(UncertaintyError::NotRepresentable)?),
461                unit_id: require_id(unit_id)?,
462            },
463            UncertaintyEstimate::RelativeBoundMillionths(value) => EncodedEstimate::Relative {
464                millionths: value as u64,
465            },
466            UncertaintyEstimate::ConfidenceInterval {
467                lower,
468                upper,
469                coverage_millionths,
470                unit_id,
471            } => EncodedEstimate::Interval {
472                lower: float_object(round_down(lower).ok_or(UncertaintyError::NotRepresentable)?),
473                upper: float_object(round_up(upper).ok_or(UncertaintyError::NotRepresentable)?),
474                coverage_millionths: coverage_millionths as u64,
475                unit_id: require_id(unit_id)?,
476            },
477        })
478    }
479
480    fn write_estimate(&self, out: &mut [NQuin], cursor: &mut usize, estimate: EncodedEstimate) {
481        use proposed_predicates as p;
482        match estimate {
483            EncodedEstimate::Unknown => self.push_integer(out, cursor, p::HAS_ESTIMATE_KIND, 0),
484            EncodedEstimate::Absolute { value, unit_id } => {
485                self.push_integer(out, cursor, p::HAS_ESTIMATE_KIND, 1);
486                self.push(out, cursor, p::HAS_ABSOLUTE_BOUND, value);
487                self.push(out, cursor, p::HAS_ESTIMATE_UNIT_ID, unit_id);
488            }
489            EncodedEstimate::Relative { millionths } => {
490                self.push_integer(out, cursor, p::HAS_ESTIMATE_KIND, 2);
491                self.push_integer(out, cursor, p::HAS_RELATIVE_BOUND_MILLIONTHS, millionths);
492            }
493            EncodedEstimate::Interval {
494                lower,
495                upper,
496                coverage_millionths,
497                unit_id,
498            } => {
499                self.push_integer(out, cursor, p::HAS_ESTIMATE_KIND, 3);
500                self.push(out, cursor, p::HAS_INTERVAL_LOWER, lower);
501                self.push(out, cursor, p::HAS_INTERVAL_UPPER, upper);
502                self.push_integer(out, cursor, p::HAS_COVERAGE_MILLIONTHS, coverage_millionths);
503                self.push(out, cursor, p::HAS_ESTIMATE_UNIT_ID, unit_id);
504            }
505        }
506    }
507}
508
509#[derive(Clone, Copy)]
510enum EncodedEstimate {
511    Unknown,
512    Absolute {
513        value: u64,
514        unit_id: u64,
515    },
516    Relative {
517        millionths: u64,
518    },
519    Interval {
520        lower: u64,
521        upper: u64,
522        coverage_millionths: u64,
523        unit_id: u64,
524    },
525}
526
527fn validate_estimate(
528    field: PhysicalFieldSemantics,
529    scope: UncertaintyScope,
530    estimate: UncertaintyEstimate,
531) -> Result<(), UncertaintyError> {
532    let unit = match scope {
533        UncertaintyScope::PhysicalField => field.typed_unit_id(),
534        UncertaintyScope::ProjectionAxis { axis_unit_id, .. } => axis_unit_id,
535    };
536    match estimate {
537        UncertaintyEstimate::Unknown => Ok(()),
538        UncertaintyEstimate::AbsoluteBound { value, unit_id } => {
539            if !value.is_finite() || value < 0.0 {
540                return Err(UncertaintyError::InvalidEstimate);
541            }
542            if unit_id != unit || unit_id.value().is_none() {
543                return Err(UncertaintyError::UnitMismatch);
544            }
545            if round_up(value).is_none() {
546                return Err(UncertaintyError::NotRepresentable);
547            }
548            Ok(())
549        }
550        UncertaintyEstimate::RelativeBoundMillionths(_) => Ok(()),
551        UncertaintyEstimate::ConfidenceInterval {
552            lower,
553            upper,
554            coverage_millionths,
555            unit_id,
556        } => {
557            if !lower.is_finite() || !upper.is_finite() || lower > upper {
558                return Err(UncertaintyError::InvalidInterval);
559            }
560            if coverage_millionths == 0 || coverage_millionths > UNCERTAINTY_SCALE {
561                return Err(UncertaintyError::InvalidCoverage);
562            }
563            if unit_id != unit || unit_id.value().is_none() {
564                return Err(UncertaintyError::UnitMismatch);
565            }
566            if round_down(lower).is_none() || round_up(upper).is_none() {
567                return Err(UncertaintyError::NotRepresentable);
568            }
569            Ok(())
570        }
571    }
572}
573
574fn validate_scope(scope: UncertaintyScope) -> Result<(), UncertaintyError> {
575    if let UncertaintyScope::ProjectionAxis {
576        mapping_id,
577        axis_index,
578        axis_unit_id,
579        profile_id,
580        domain_id,
581        coordinate_convention_id,
582    } = scope
583    {
584        if mapping_id == 0 || mapping_id > ID_MASK || axis_index >= 10 {
585            return Err(UncertaintyError::InvalidScope);
586        }
587        require_id(axis_unit_id)?;
588        require_id(profile_id)?;
589        require_id(domain_id)?;
590        require_id(coordinate_convention_id)?;
591    }
592    Ok(())
593}
594
595fn require_id(id: SemanticId) -> Result<u64, UncertaintyError> {
596    match id.value() {
597        Some(value) if value <= ID_MASK => Ok(value),
598        Some(_) => Err(UncertaintyError::InvalidIdentifier),
599        None => Err(UncertaintyError::UnknownRequiredSemantics),
600    }
601}
602
603fn check_optional_id(id: SemanticId) -> Result<(), UncertaintyError> {
604    if let Some(value) = id.value() {
605        if value > ID_MASK {
606            return Err(UncertaintyError::InvalidIdentifier);
607        }
608    }
609    Ok(())
610}
611
612fn bool_id(value: bool) -> u64 {
613    if value {
614        1
615    } else {
616        0
617    }
618}
619
620fn count_if(value: bool) -> usize {
621    if value {
622        1
623    } else {
624        0
625    }
626}
627
628fn make_quin(subject: u64, predicate: u64, object: u64) -> NQuin {
629    let metadata = 0;
630    NQuin {
631        subject,
632        predicate,
633        object,
634        context: 0,
635        metadata,
636        parity: NQuin::calculate_parity(subject, predicate, object, 0, metadata),
637    }
638}
639
640fn float_object(value: f32) -> u64 {
641    crate::frame_layout::pack_float_object(value)
642}
643
644fn integer_object(value: u64) -> u64 {
645    // All call sites are type-bounded (`u16`, `u32`, or small enum/state values).
646    crate::frame_layout::INLINE_TAG_INTEGER | value
647}
648
649fn round_up(value: f64) -> Option<f32> {
650    if !value.is_finite() || value < -(f32::MAX as f64) || value > f32::MAX as f64 {
651        return None;
652    }
653    let mut rounded = value as f32;
654    if (rounded as f64) < value {
655        let bits = rounded.to_bits();
656        let next = if rounded >= 0.0 {
657            bits.checked_add(1)?
658        } else {
659            bits.checked_sub(1)?
660        };
661        rounded = f32::from_bits(next);
662    }
663    if rounded.is_finite() {
664        Some(rounded)
665    } else {
666        None
667    }
668}
669
670fn round_down(value: f64) -> Option<f32> {
671    if !value.is_finite() || value < -(f32::MAX as f64) || value > f32::MAX as f64 {
672        return None;
673    }
674    let mut rounded = value as f32;
675    if (rounded as f64) > value {
676        let bits = rounded.to_bits();
677        let next = if rounded > 0.0 {
678            bits.checked_sub(1)?
679        } else {
680            bits.checked_add(1)?
681        };
682        rounded = f32::from_bits(next);
683    }
684    if rounded.is_finite() {
685        Some(rounded)
686    } else {
687        None
688    }
689}
690
691#[derive(Clone, Copy, Debug, PartialEq, Eq)]
692pub enum UncertaintyError {
693    InvalidIdentifier,
694    UnknownRequiredSemantics,
695    InvalidMethod,
696    InvalidEstimate,
697    InvalidInterval,
698    InvalidCoverage,
699    InvalidAxis,
700    InvalidScope,
701    UnitMismatch,
702    NotRepresentable,
703    Capacity { required: usize, available: usize },
704}
705
706#[cfg(test)]
707#[path = "uncertainty_tests.rs"]
708mod tests;