Skip to main content

qualia_cooperative_core/
contextual_evidence.rs

1//! Evidence detail for contextual assertions about subjects such as taxa, specimens and parts.
2//!
3//! A [`ContextualAssertion`](crate::contextual_assertion::ContextualAssertion) records who asserted
4//! what, from which root source, with what lifecycle and verification status. [`EvidenceDetail`]
5//! holds the content of a measured or described fact: property, value and unit, uncertainty,
6//! method, observation/validity time, biological scope, the record or media region it came from,
7//! and the basis on which it is held (measured, described, derived, model assumption, artistic
8//! choice or unknown). [`EvidencedAssertion`] pairs the two without changing the existing
9//! assertion type. Competing values for one property coexist as separate assertions.
10
11use serde::{Deserialize, Serialize};
12
13use crate::record::{q_hash_str, NQuin};
14
15/// Basis on which an assertion's value is held. Keeps model assumptions and artistic choices
16/// distinguishable from source evidence.
17#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
18#[serde(rename_all = "snake_case")]
19pub enum ClaimBasis {
20    /// Measured by a stated method.
21    Measured,
22    /// Descriptive statement from a source (treatment, flora, description).
23    Described,
24    /// Derived by inference or calculation from other assertions.
25    Derived,
26    /// Model or simulation assumption, not evidence about the subject.
27    ModelAssumption,
28    /// Authored artistic or illustrative choice.
29    ArtisticChoice,
30    /// The value is unknown; the assertion records the gap.
31    Unknown,
32}
33
34impl ClaimBasis {
35    pub const fn as_str(&self) -> &'static str {
36        match self {
37            Self::Measured => "measured",
38            Self::Described => "described",
39            Self::Derived => "derived",
40            Self::ModelAssumption => "model_assumption",
41            Self::ArtisticChoice => "artistic_choice",
42            Self::Unknown => "unknown",
43        }
44    }
45}
46
47impl Default for ClaimBasis {
48    fn default() -> Self {
49        Self::Unknown
50    }
51}
52
53/// Seven-tier epistemic provenance lattice (`epistemic:hasEpistemicStatus`).
54///
55/// Distinguishes direct physical readouts from subject-specific inferences, documentary
56/// extractions, longitudinal projections, population priors, phylogenetic brackets, and
57/// authorial intent.
58#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
59#[serde(rename_all = "snake_case")]
60pub enum EpistemicTier {
61    /// 1:1 physical readout of the asserted quantity (CT/MRI/DEXA/XROMM/tape/caliper).
62    DirectlyObserved,
63    /// Computed deterministically from `DirectlyObserved` or `ExtractedFromRecord` inputs of
64    /// the same subject via a named transfer formula.
65    InferredFromObservation,
66    /// Parsed or transcribed from a clinical record, report, or literature table.
67    ExtractedFromRecord,
68    /// Projected forward or backward in time from an earlier observation of the same subject.
69    LongitudinallyProjected,
70    /// Completed or regularised using population SSM/SDM or allometric scaling priors.
71    StatisticallyCalibrated,
72    /// Reconstructed across evolutionary homologs via Witmer's Extant Phylogenetic Bracket.
73    PhylogeneticallyBracketed,
74    /// Deliberately posed, sculpted, or hypothetically modified (e.g. clinical test or creative).
75    AuthorialIntent,
76}
77
78impl EpistemicTier {
79    pub const fn as_str(&self) -> &'static str {
80        match self {
81            Self::DirectlyObserved => "directly_observed",
82            Self::InferredFromObservation => "inferred_from_observation",
83            Self::ExtractedFromRecord => "extracted_from_record",
84            Self::LongitudinallyProjected => "longitudinally_projected",
85            Self::StatisticallyCalibrated => "statistically_calibrated",
86            Self::PhylogeneticallyBracketed => "phylogenetically_bracketed",
87            Self::AuthorialIntent => "authorial_intent",
88        }
89    }
90
91    pub const fn as_iri(&self) -> &'static str {
92        match self {
93            Self::DirectlyObserved => "https://ns.webizen.org/epistemic#DirectlyObserved",
94            Self::InferredFromObservation => "https://ns.webizen.org/epistemic#InferredFromObservation",
95            Self::ExtractedFromRecord => "https://ns.webizen.org/epistemic#ExtractedFromRecord",
96            Self::LongitudinallyProjected => "https://ns.webizen.org/epistemic#LongitudinallyProjected",
97            Self::StatisticallyCalibrated => "https://ns.webizen.org/epistemic#StatisticallyCalibrated",
98            Self::PhylogeneticallyBracketed => "https://ns.webizen.org/epistemic#PhylogeneticallyBracketed",
99            Self::AuthorialIntent => "https://ns.webizen.org/epistemic#AuthorialIntent",
100        }
101    }
102
103    /// Ordinal rank in the 7-tier lattice (0 = most direct empirical observation).
104    pub const fn rank(&self) -> u8 {
105        match self {
106            Self::DirectlyObserved => 0,
107            Self::InferredFromObservation => 1,
108            Self::ExtractedFromRecord => 2,
109            Self::LongitudinallyProjected => 3,
110            Self::StatisticallyCalibrated => 4,
111            Self::PhylogeneticallyBracketed => 5,
112            Self::AuthorialIntent => 6,
113        }
114    }
115}
116
117/// Normative `q42m:*` observation method taxonomy covering physical anthropometry,
118/// volumetric/planar/densitometric imaging, biomechanical telemetry, and documentary records.
119#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
120#[serde(rename_all = "snake_case")]
121pub enum ObservationMethod {
122    // 1. Direct Physical Anthropometry
123    FlexibleTapeCircumference,
124    LinearAnthropometryStadiometer,
125    InfantLengthBoard,
126    OsteometricBoard,
127    SlidingCaliper,
128    SpreadingCaliper,
129    SkinfoldCaliper,
130    GravimetricScale,
131    BioelectricalImpedanceBia,
132    ClinicalGoniometer,
133    DigitalInclinometer,
134    // 2. Volumetric, Planar & Densitometric Imaging
135    DexaArealDensitometry,
136    ClinicalCtQuantitativeQct,
137    ClinicalCtStandard,
138    HrPqctMicroarchitecture,
139    MicroCtSynchrotron,
140    ClinicalMriStructural,
141    ClinicalMriDixonPdff,
142    ClinicalMriDti,
143    DiagnosticUltrasound2D,
144    DiagnosticUltrasound3D,
145    ShearWaveElastography,
146    QuantitativeUltrasoundCalcaneal,
147    PlanarRadiographXRay,
148    EosSlotScanningBiplanar,
149    BiplanarFluoroscopyXromm,
150    Optical3DSurfaceScan,
151    MultiViewPhotogrammetry,
152    TerrestrialLidarTls,
153    // 3. Kinematic, Kinetic & Wearable Telemetry
154    OpticalMarkerMoCap,
155    MarkerlessMultiViewPose,
156    InertialImuArray,
157    ForcePlateGrf,
158    InShoePressureInsole,
159    GaitMatPressureWalkway,
160    IsokineticDynamometry,
161    HandgripDynamometry,
162    SurfaceEmg,
163    FineWireEmg,
164    Spirometry,
165    WearablePpgSmartwatch,
166    ElectrocardiographyEcg,
167    // 4. Clinical Records, Lab Assays & Documentary Sources
168    ElectronicHealthRecordFhir,
169    Hl7v2ClinicalFeed,
170    DicomStructuredReport,
171    ClinicalLaboratoryAssay,
172    IcdCodedDiagnosis,
173    PathologyReport,
174    ClinicalNarrativeDocument,
175    PublishedScientificLiterature,
176    MuseumSpecimenRegister,
177    SubjectSelfReportQuestionnaire,
178}
179
180impl ObservationMethod {
181    pub const fn as_curie(&self) -> &'static str {
182        match self {
183            Self::FlexibleTapeCircumference => "q42m:FlexibleTapeCircumference",
184            Self::LinearAnthropometryStadiometer => "q42m:LinearAnthropometry_Stadiometer",
185            Self::InfantLengthBoard => "q42m:InfantLengthBoard",
186            Self::OsteometricBoard => "q42m:OsteometricBoard",
187            Self::SlidingCaliper => "q42m:SlidingCaliper",
188            Self::SpreadingCaliper => "q42m:SpreadingCaliper",
189            Self::SkinfoldCaliper => "q42m:SkinfoldCaliper",
190            Self::GravimetricScale => "q42m:GravimetricScale",
191            Self::BioelectricalImpedanceBia => "q42m:BioelectricalImpedance_BIA",
192            Self::ClinicalGoniometer => "q42m:ClinicalGoniometer",
193            Self::DigitalInclinometer => "q42m:DigitalInclinometer",
194            Self::DexaArealDensitometry => "q42m:DEXA_ArealDensitometry",
195            Self::ClinicalCtQuantitativeQct => "q42m:ClinicalCT_Quantitative_QCT",
196            Self::ClinicalCtStandard => "q42m:ClinicalCT_Standard",
197            Self::HrPqctMicroarchitecture => "q42m:HR_pQCT_Microarchitecture",
198            Self::MicroCtSynchrotron => "q42m:MicroCT_Synchrotron",
199            Self::ClinicalMriStructural => "q42m:ClinicalMRI_Structural",
200            Self::ClinicalMriDixonPdff => "q42m:ClinicalMRI_DixonPDFF",
201            Self::ClinicalMriDti => "q42m:ClinicalMRI_DTI",
202            Self::DiagnosticUltrasound2D => "q42m:DiagnosticUltrasound_2D",
203            Self::DiagnosticUltrasound3D => "q42m:DiagnosticUltrasound_3D",
204            Self::ShearWaveElastography => "q42m:ShearWaveElastography",
205            Self::QuantitativeUltrasoundCalcaneal => "q42m:QuantitativeUltrasound_Calcaneal",
206            Self::PlanarRadiographXRay => "q42m:PlanarRadiograph_XRay",
207            Self::EosSlotScanningBiplanar => "q42m:EOS_SlotScanningBiplanar",
208            Self::BiplanarFluoroscopyXromm => "q42m:BiplanarFluoroscopy_XROMM",
209            Self::Optical3DSurfaceScan => "q42m:Optical3DSurfaceScan",
210            Self::MultiViewPhotogrammetry => "q42m:MultiViewPhotogrammetry",
211            Self::TerrestrialLidarTls => "q42m:TerrestrialLiDAR_TLS",
212            Self::OpticalMarkerMoCap => "q42m:OpticalMarkerMoCap",
213            Self::MarkerlessMultiViewPose => "q42m:MarkerlessMultiViewPose",
214            Self::InertialImuArray => "q42m:InertialIMU_Array",
215            Self::ForcePlateGrf => "q42m:ForcePlate_GRF",
216            Self::InShoePressureInsole => "q42m:InShoePressureInsole",
217            Self::GaitMatPressureWalkway => "q42m:GaitMat_PressureWalkway",
218            Self::IsokineticDynamometry => "q42m:IsokineticDynamometry",
219            Self::HandgripDynamometry => "q42m:HandgripDynamometry",
220            Self::SurfaceEmg => "q42m:SurfaceEMG_sEMG",
221            Self::FineWireEmg => "q42m:FineWireEMG",
222            Self::Spirometry => "q42m:Spirometry",
223            Self::WearablePpgSmartwatch => "q42m:WearablePPG_Smartwatch",
224            Self::ElectrocardiographyEcg => "q42m:Electrocardiography_ECG",
225            Self::ElectronicHealthRecordFhir => "q42m:ElectronicHealthRecord_FHIR",
226            Self::Hl7v2ClinicalFeed => "q42m:HL7v2_ClinicalFeed",
227            Self::DicomStructuredReport => "q42m:DICOM_StructuredReport",
228            Self::ClinicalLaboratoryAssay => "q42m:ClinicalLaboratoryAssay",
229            Self::IcdCodedDiagnosis => "q42m:ICD_CodedDiagnosis",
230            Self::PathologyReport => "q42m:PathologyReport",
231            Self::ClinicalNarrativeDocument => "q42m:ClinicalNarrativeDocument",
232            Self::PublishedScientificLiterature => "q42m:PublishedScientificLiterature",
233            Self::MuseumSpecimenRegister => "q42m:MuseumSpecimenRegister",
234            Self::SubjectSelfReportQuestionnaire => "q42m:SubjectSelfReport_Questionnaire",
235        }
236    }
237
238    pub fn as_iri(&self) -> String {
239        let local = self.as_curie().strip_prefix("q42m:").unwrap_or(self.as_curie());
240        format!("https://ns.webizen.org/epistemic/method#{local}")
241    }
242
243    /// 1 = PhysicalAnthropometry, 2 = VolumetricAndPlanarImaging, 3 = BiomechanicalTelemetry,
244    /// 4 = DocumentaryAndRecordExtraction.
245    pub const fn category_code(&self) -> u8 {
246        match self {
247            Self::FlexibleTapeCircumference
248            | Self::LinearAnthropometryStadiometer
249            | Self::InfantLengthBoard
250            | Self::OsteometricBoard
251            | Self::SlidingCaliper
252            | Self::SpreadingCaliper
253            | Self::SkinfoldCaliper
254            | Self::GravimetricScale
255            | Self::BioelectricalImpedanceBia
256            | Self::ClinicalGoniometer
257            | Self::DigitalInclinometer => 1,
258            Self::DexaArealDensitometry
259            | Self::ClinicalCtQuantitativeQct
260            | Self::ClinicalCtStandard
261            | Self::HrPqctMicroarchitecture
262            | Self::MicroCtSynchrotron
263            | Self::ClinicalMriStructural
264            | Self::ClinicalMriDixonPdff
265            | Self::ClinicalMriDti
266            | Self::DiagnosticUltrasound2D
267            | Self::DiagnosticUltrasound3D
268            | Self::ShearWaveElastography
269            | Self::QuantitativeUltrasoundCalcaneal
270            | Self::PlanarRadiographXRay
271            | Self::EosSlotScanningBiplanar
272            | Self::BiplanarFluoroscopyXromm
273            | Self::Optical3DSurfaceScan
274            | Self::MultiViewPhotogrammetry
275            | Self::TerrestrialLidarTls => 2,
276            Self::OpticalMarkerMoCap
277            | Self::MarkerlessMultiViewPose
278            | Self::InertialImuArray
279            | Self::ForcePlateGrf
280            | Self::InShoePressureInsole
281            | Self::GaitMatPressureWalkway
282            | Self::IsokineticDynamometry
283            | Self::HandgripDynamometry
284            | Self::SurfaceEmg
285            | Self::FineWireEmg
286            | Self::Spirometry
287            | Self::WearablePpgSmartwatch
288            | Self::ElectrocardiographyEcg => 3,
289            Self::ElectronicHealthRecordFhir
290            | Self::Hl7v2ClinicalFeed
291            | Self::DicomStructuredReport
292            | Self::ClinicalLaboratoryAssay
293            | Self::IcdCodedDiagnosis
294            | Self::PathologyReport
295            | Self::ClinicalNarrativeDocument
296            | Self::PublishedScientificLiterature
297            | Self::MuseumSpecimenRegister
298            | Self::SubjectSelfReportQuestionnaire => 4,
299        }
300    }
301}
302
303/// Role of the observer who acquired or extracted the evidence (`q42:ObserverRole`).
304#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
305#[serde(rename_all = "snake_case")]
306pub enum ObserverRole {
307    SelfMeasured,
308    PeerMeasured,
309    ClinicianMeasured,
310    IsakCertified,
311    AutomatedSensor,
312    CuratorExtracted,
313}
314
315impl ObserverRole {
316    pub const fn as_str(&self) -> &'static str {
317        match self {
318            Self::SelfMeasured => "self_measured",
319            Self::PeerMeasured => "peer_measured",
320            Self::ClinicianMeasured => "clinician_measured",
321            Self::IsakCertified => "isak_certified",
322            Self::AutomatedSensor => "automated_sensor",
323            Self::CuratorExtracted => "curator_extracted",
324        }
325    }
326
327    pub const fn as_iri(&self) -> &'static str {
328        match self {
329            Self::SelfMeasured => "https://ns.webizen.org/epistemic#SelfMeasured",
330            Self::PeerMeasured => "https://ns.webizen.org/epistemic#PeerMeasured",
331            Self::ClinicianMeasured => "https://ns.webizen.org/epistemic#ClinicianMeasured",
332            Self::IsakCertified => "https://ns.webizen.org/epistemic#ISAKCertified",
333            Self::AutomatedSensor => "https://ns.webizen.org/epistemic#AutomatedSensor",
334            Self::CuratorExtracted => "https://ns.webizen.org/epistemic#CuratorExtracted",
335        }
336    }
337}
338
339/// Biological freshness stability class governing half-life decay ($t_{1/2}$).
340#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
341#[serde(rename_all = "snake_case")]
342pub enum TemporalStabilityClass {
343    /// $t_{1/2} \sim 10^1\text{–}10^3\text{ s}$ (heart rate, EMG, acute posture).
344    AcutePhysiological,
345    /// $t_{1/2} \sim 10^5\text{–}10^6\text{ s}$ (girths, body weight, gestation, fracture callus).
346    SubacuteMetabolicGravidAndHealing,
347    /// $t_{1/2} \sim 10^7\text{–}10^8\text{ s}$ (aBMD/vBMD, muscle PCSA/HU, pediatric growth).
348    OntogeneticAndSkeletalRemodeling,
349    /// $t_{1/2} > 10^9\text{ s}$ (adult diaphyseal length, fossil geometry).
350    SkeletallyMatureInvariant,
351}
352
353impl TemporalStabilityClass {
354    /// Default biological half-life in days (`None` = invariant / non-decaying).
355    pub const fn default_half_life_days(&self) -> Option<f64> {
356        match self {
357            Self::AcutePhysiological => Some(0.005), // ~432 s
358            Self::SubacuteMetabolicGravidAndHealing => Some(7.0),
359            Self::OntogeneticAndSkeletalRemodeling => Some(365.0),
360            Self::SkeletallyMatureInvariant => None,
361        }
362    }
363}
364
365/// Four-axis temporal provenance & exponential freshness decay model.
366#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, Default)]
367pub struct TemporalObservationAxis {
368    /// When the physical state existed in the organism (Unix epoch ms).
369    pub phenomenon_time_ms: i64,
370    /// When the sensor, imaging study, or clinician captured the measurement (Unix epoch ms).
371    #[serde(default, skip_serializing_if = "Option::is_none")]
372    pub acquisition_time_ms: Option<i64>,
373    /// When the datum was parsed or transcribed from a document/record (Unix epoch ms).
374    #[serde(default, skip_serializing_if = "Option::is_none")]
375    pub extraction_time_ms: Option<i64>,
376    /// When the assertion was compiled into the `.q42`/`.10d`/`.m64` model (Unix epoch ms).
377    #[serde(default, skip_serializing_if = "Option::is_none")]
378    pub calibration_time_ms: Option<i64>,
379    /// Biological half-life in days (`None` = invariant / no temporal decay).
380    #[serde(default, skip_serializing_if = "Option::is_none")]
381    pub half_life_days: Option<f64>,
382}
383
384impl TemporalObservationAxis {
385    pub const fn with_stability_class(
386        phenomenon_time_ms: i64,
387        class: TemporalStabilityClass,
388    ) -> Self {
389        Self {
390            phenomenon_time_ms,
391            acquisition_time_ms: None,
392            extraction_time_ms: None,
393            calibration_time_ms: None,
394            half_life_days: class.default_half_life_days(),
395        }
396    }
397
398    /// Exponential freshness decay: $2^{-\max(0, t_{\text{eval}} - t_{\text{phenomenon}}) / t_{1/2}}$.
399    pub fn compute_decayed_confidence(&self, eval_time_ms: i64) -> f64 {
400        let dt_ms = eval_time_ms.saturating_sub(self.phenomenon_time_ms).max(0) as f64;
401        if dt_ms == 0.0 {
402            return 1.0;
403        }
404        match self.half_life_days {
405            None => 1.0,
406            Some(h) if !h.is_finite() || h <= 0.0 => 0.0,
407            Some(h) => 2.0_f64.powf(-dt_ms / (h * 86_400_000.0)),
408        }
409    }
410
411    /// Scales `base_confidence` (clamped to `0.0..=1.0`) by the exponential decay factor.
412    pub fn compute_decayed_confidence_from_base(
413        &self,
414        base_confidence: f64,
415        eval_time_ms: i64,
416    ) -> f64 {
417        base_confidence.clamp(0.0, 1.0) * self.compute_decayed_confidence(eval_time_ms)
418    }
419}
420
421/// Asserted value. Numeric values carry a unit IRI (for example a QUDT unit).
422#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
423#[serde(rename_all = "snake_case", tag = "kind")]
424pub enum EvidenceValue {
425    Quantity { value: f64, unit_iri: String },
426    Range { min: f64, max: f64, unit_iri: String },
427    Text { text: String, language: Option<String> },
428    Iri { iri: String },
429}
430
431/// Statistical uncertainty or sample description for a value.
432#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
433pub struct Uncertainty {
434    #[serde(default, skip_serializing_if = "Option::is_none")]
435    pub standard_deviation: Option<f64>,
436    #[serde(default, skip_serializing_if = "Option::is_none")]
437    pub interval: Option<(f64, f64)>,
438    #[serde(default, skip_serializing_if = "Option::is_none")]
439    pub interval_confidence: Option<f64>,
440    #[serde(default, skip_serializing_if = "Option::is_none")]
441    pub sample_size: Option<u32>,
442}
443
444/// What the assertion is about biologically. Type-level facts leave `individual_iri` empty;
445/// observations of particular organisms set it.
446#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
447pub struct BiologicalScope {
448    #[serde(default, skip_serializing_if = "Option::is_none")]
449    pub taxon_concept_iri: Option<String>,
450    #[serde(default, skip_serializing_if = "Option::is_none")]
451    pub part_iri: Option<String>,
452    #[serde(default, skip_serializing_if = "Option::is_none")]
453    pub life_stage_iri: Option<String>,
454    #[serde(default, skip_serializing_if = "Option::is_none")]
455    pub sex_iri: Option<String>,
456    #[serde(default, skip_serializing_if = "Option::is_none")]
457    pub population_iri: Option<String>,
458    #[serde(default, skip_serializing_if = "Option::is_none")]
459    pub individual_iri: Option<String>,
460}
461
462/// Content of a measured or described fact.
463#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
464pub struct EvidenceDetail {
465    pub property_iri: String,
466    pub basis: ClaimBasis,
467    #[serde(default, skip_serializing_if = "Option::is_none")]
468    pub value: Option<EvidenceValue>,
469    #[serde(default, skip_serializing_if = "Option::is_none")]
470    pub uncertainty: Option<Uncertainty>,
471    #[serde(default, skip_serializing_if = "Option::is_none")]
472    pub method_iri: Option<String>,
473    /// ISO 8601 instant or interval of observation.
474    #[serde(default, skip_serializing_if = "Option::is_none")]
475    pub observed_at: Option<String>,
476    /// ISO 8601 interval during which the assertion is held valid.
477    #[serde(default, skip_serializing_if = "Option::is_none")]
478    pub valid_during: Option<String>,
479    /// ISO 8601 start of validity interval (`q42:validFrom`).
480    #[serde(default, skip_serializing_if = "Option::is_none")]
481    pub valid_from: Option<String>,
482    /// ISO 8601 end of validity interval (`q42:validUntil`).
483    #[serde(default, skip_serializing_if = "Option::is_none")]
484    pub valid_until: Option<String>,
485    #[serde(default)]
486    pub scope: BiologicalScope,
487    /// Identifier of the record within the root source (for example a trait observation id).
488    #[serde(default, skip_serializing_if = "Option::is_none")]
489    pub source_record_id: Option<String>,
490    /// Region of a media item supporting the assertion (for example an Audiovisual Core ROI).
491    #[serde(default, skip_serializing_if = "Option::is_none")]
492    pub media_region: Option<String>,
493    /// Seven-tier epistemic provenance state (`q42:epistemicTier`).
494    #[serde(default, skip_serializing_if = "Option::is_none")]
495    pub epistemic_tier: Option<EpistemicTier>,
496    /// Normative `q42m:*` observation method (`q42:observationMethod`).
497    #[serde(default, skip_serializing_if = "Option::is_none")]
498    pub observation_method: Option<ObservationMethod>,
499    /// Role of the observer (`q42:observerRole`).
500    #[serde(default, skip_serializing_if = "Option::is_none")]
501    pub observer_role: Option<ObserverRole>,
502    /// Four-axis temporal provenance and half-life decay parameters.
503    #[serde(default, skip_serializing_if = "Option::is_none")]
504    pub temporal_axis: Option<TemporalObservationAxis>,
505    /// Biological freshness stability class.
506    #[serde(default, skip_serializing_if = "Option::is_none")]
507    pub stability_class: Option<TemporalStabilityClass>,
508    /// Canonical IRI/hash of the transfer formula for `InferredFromObservation`.
509    #[serde(default, skip_serializing_if = "Option::is_none")]
510    pub inference_formula_iri: Option<String>,
511    /// Upstream observation assertion IDs for `InferredFromObservation`.
512    #[serde(default, skip_serializing_if = "Vec::is_empty")]
513    pub derived_from_observation_ids: Vec<String>,
514}
515
516const INLINE_TAG_DECIMAL: u64 = 0b010 << 60;
517const PAYLOAD_60: u64 = 0x0FFF_FFFF_FFFF_FFFF;
518
519pub const P_PROPERTY: &str = "https://ns.webizen.org/evidence#property";
520pub const P_BASIS: &str = "https://ns.webizen.org/evidence#basis";
521pub const P_VALUE: &str = "https://ns.webizen.org/evidence#value";
522pub const P_VALUE_MIN: &str = "https://ns.webizen.org/evidence#valueMin";
523pub const P_VALUE_MAX: &str = "https://ns.webizen.org/evidence#valueMax";
524pub const P_UNIT: &str = "https://ns.webizen.org/evidence#unit";
525pub const P_METHOD: &str = "https://ns.webizen.org/evidence#method";
526pub const P_TAXON: &str = "https://ns.webizen.org/evidence#taxonConcept";
527pub const P_PART: &str = "https://ns.webizen.org/evidence#part";
528pub const P_LIFE_STAGE: &str = "https://ns.webizen.org/evidence#lifeStage";
529pub const P_SEX: &str = "https://ns.webizen.org/evidence#sex";
530pub const P_POPULATION: &str = "https://ns.webizen.org/evidence#population";
531pub const P_INDIVIDUAL: &str = "https://ns.webizen.org/evidence#individual";
532pub const P_SOURCE_RECORD: &str = "https://ns.webizen.org/evidence#sourceRecord";
533
534pub const P_OBSERVED_AT: &str = "q42:observedAt";
535pub const P_VALID_FROM: &str = "q42:validFrom";
536pub const P_VALID_UNTIL: &str = "q42:validUntil";
537pub const P_VALID_DURING: &str = "q42:validDuring";
538pub const P_OBSERVATION_METHOD: &str = "q42:observationMethod";
539pub const P_EPISTEMIC_TIER: &str = "q42:epistemicTier";
540pub const P_OBSERVER_ROLE: &str = "q42:observerRole";
541pub const P_UNCERTAINTY_VALUE: &str = "q42:uncertaintyValue";
542pub const P_UNCERTAINTY_UNIT: &str = "q42:uncertaintyUnit";
543pub const P_UNCERTAINTY_CONFIDENCE: &str = "q42:uncertaintyConfidence";
544pub const P_MEDIA_REGION: &str = "q42:mediaRegion";
545pub const P_PHENOMENON_TIME_MS: &str = "q42:phenomenonTimeMs";
546pub const P_ACQUISITION_TIME_MS: &str = "q42:acquisitionTimeMs";
547pub const P_EXTRACTION_TIME_MS: &str = "q42:extractionTimeMs";
548pub const P_CALIBRATION_TIME_MS: &str = "q42:calibrationTimeMs";
549pub const P_INFERENCE_FORMULA: &str = "q42:inferenceFormula";
550
551/// Encodes a number as an inline `xsd:decimal` object (value x 10^6) when it is finite,
552/// non-negative and fits 60 bits; otherwise hashes its canonical lexical form.
553pub fn encode_decimal_object(v: f64) -> u64 {
554    let scaled = v * 1_000_000.0;
555    if v.is_finite() && v >= 0.0 && scaled <= PAYLOAD_60 as f64 {
556        INLINE_TAG_DECIMAL | (scaled.round() as u64 & PAYLOAD_60)
557    } else {
558        q_hash_str(&format!("{v:?}^^xsd:decimal"))
559    }
560}
561
562impl EvidenceDetail {
563    /// Validates internal consistency. Numeric values must be finite, ranges ordered, and a
564    /// `Measured` assertion must name its method.
565    pub fn validate(&self) -> Result<(), String> {
566        if self.property_iri.trim().is_empty() {
567            return Err("evidence property_iri is empty".into());
568        }
569        match &self.value {
570            Some(EvidenceValue::Quantity { value, unit_iri }) => {
571                if !value.is_finite() {
572                    return Err("evidence quantity is not finite".into());
573                }
574                if unit_iri.trim().is_empty() {
575                    return Err("evidence quantity requires unit_iri".into());
576                }
577            }
578            Some(EvidenceValue::Range { min, max, unit_iri }) => {
579                if !min.is_finite() || !max.is_finite() || min > max {
580                    return Err("evidence range must be finite with min <= max".into());
581                }
582                if unit_iri.trim().is_empty() {
583                    return Err("evidence range requires unit_iri".into());
584                }
585            }
586            Some(EvidenceValue::Text { text, .. }) if text.trim().is_empty() => {
587                return Err("evidence text is empty".into());
588            }
589            Some(EvidenceValue::Iri { iri }) if iri.trim().is_empty() => {
590                return Err("evidence iri is empty".into());
591            }
592            _ => {}
593        }
594        if self.basis == ClaimBasis::Unknown && self.value.is_some() {
595            return Err("an unknown-basis assertion must not carry a value".into());
596        }
597        if self.basis == ClaimBasis::Measured
598            && self.method_iri.is_none()
599            && self.observation_method.is_none()
600        {
601            return Err("a measured assertion requires method_iri or observation_method".into());
602        }
603        if let Some(u) = &self.uncertainty {
604            if let Some(sd) = u.standard_deviation {
605                if !sd.is_finite() || sd < 0.0 {
606                    return Err("uncertainty standard_deviation must be finite and >= 0".into());
607                }
608            }
609            if let Some((lo, hi)) = u.interval {
610                if !lo.is_finite() || !hi.is_finite() || lo > hi {
611                    return Err("uncertainty interval must be finite with lo <= hi".into());
612                }
613            }
614            if let Some(c) = u.interval_confidence {
615                if !(0.0..=1.0).contains(&c) {
616                    return Err("interval_confidence must be in 0.0..=1.0".into());
617                }
618            }
619        }
620        if let Some(axis) = &self.temporal_axis {
621            if let Some(h) = axis.half_life_days {
622                if !h.is_finite() || h <= 0.0 {
623                    return Err("temporal_axis half_life_days must be finite and > 0".into());
624                }
625            }
626        }
627        Ok(())
628    }
629
630    /// Appends evidence quins for subject hash `s` into `out[start..]`; returns the new length.
631    pub fn compile_to_quins(&self, s: u64, ctx: u64, meta: u64, out: &mut [NQuin], start: usize) -> usize {
632        let mut n = start;
633        let mut push = |p: &str, o: u64, n: &mut usize| {
634            if *n < out.len() {
635                out[*n] = NQuin::new(s, q_hash_str(p), o, ctx, meta);
636                *n += 1;
637            }
638        };
639        push(P_PROPERTY, q_hash_str(&self.property_iri), &mut n);
640        push(P_BASIS, q_hash_str(self.basis.as_str()), &mut n);
641        let value_unit_iri = match &self.value {
642            Some(EvidenceValue::Quantity { value, unit_iri }) => {
643                push(P_VALUE, encode_decimal_object(*value), &mut n);
644                push(P_UNIT, q_hash_str(unit_iri), &mut n);
645                Some(unit_iri.as_str())
646            }
647            Some(EvidenceValue::Range { min, max, unit_iri }) => {
648                push(P_VALUE_MIN, encode_decimal_object(*min), &mut n);
649                push(P_VALUE_MAX, encode_decimal_object(*max), &mut n);
650                push(P_UNIT, q_hash_str(unit_iri), &mut n);
651                Some(unit_iri.as_str())
652            }
653            Some(EvidenceValue::Text { text, .. }) => {
654                push(P_VALUE, q_hash_str(text), &mut n);
655                None
656            }
657            Some(EvidenceValue::Iri { iri }) => {
658                push(P_VALUE, q_hash_str(iri), &mut n);
659                None
660            }
661            None => None,
662        };
663        let optional = [
664            (P_METHOD, &self.method_iri),
665            (P_TAXON, &self.scope.taxon_concept_iri),
666            (P_PART, &self.scope.part_iri),
667            (P_LIFE_STAGE, &self.scope.life_stage_iri),
668            (P_SEX, &self.scope.sex_iri),
669            (P_POPULATION, &self.scope.population_iri),
670            (P_INDIVIDUAL, &self.scope.individual_iri),
671            (P_SOURCE_RECORD, &self.source_record_id),
672            (P_OBSERVED_AT, &self.observed_at),
673            (P_VALID_FROM, &self.valid_from),
674            (P_VALID_UNTIL, &self.valid_until),
675            (P_VALID_DURING, &self.valid_during),
676            (P_MEDIA_REGION, &self.media_region),
677            (P_INFERENCE_FORMULA, &self.inference_formula_iri),
678        ];
679        for (p, v) in optional {
680            if let Some(v) = v {
681                push(p, q_hash_str(v), &mut n);
682            }
683        }
684        if let Some(tier) = self.epistemic_tier {
685            push(P_EPISTEMIC_TIER, q_hash_str(tier.as_iri()), &mut n);
686        }
687        if let Some(method) = self.observation_method {
688            push(P_OBSERVATION_METHOD, q_hash_str(method.as_curie()), &mut n);
689        }
690        if let Some(role) = self.observer_role {
691            push(P_OBSERVER_ROLE, q_hash_str(role.as_iri()), &mut n);
692        }
693        if let Some(u) = &self.uncertainty {
694            if let Some(sd) = u.standard_deviation {
695                push(P_UNCERTAINTY_VALUE, encode_decimal_object(sd), &mut n);
696                if let Some(unit_iri) = value_unit_iri {
697                    push(P_UNCERTAINTY_UNIT, q_hash_str(unit_iri), &mut n);
698                }
699            }
700            if let Some(c) = u.interval_confidence {
701                push(P_UNCERTAINTY_CONFIDENCE, encode_decimal_object(c), &mut n);
702            }
703        }
704        if let Some(axis) = &self.temporal_axis {
705            push(P_PHENOMENON_TIME_MS, q_hash_str(&axis.phenomenon_time_ms.to_string()), &mut n);
706            if let Some(t) = axis.acquisition_time_ms {
707                push(P_ACQUISITION_TIME_MS, q_hash_str(&t.to_string()), &mut n);
708            }
709            if let Some(t) = axis.extraction_time_ms {
710                push(P_EXTRACTION_TIME_MS, q_hash_str(&t.to_string()), &mut n);
711            }
712            if let Some(t) = axis.calibration_time_ms {
713                push(P_CALIBRATION_TIME_MS, q_hash_str(&t.to_string()), &mut n);
714            }
715        }
716        n
717    }
718}
719
720/// A contextual assertion together with the content of the fact it asserts.
721#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
722pub struct EvidencedAssertion {
723    pub assertion: crate::contextual_assertion::ContextualAssertion,
724    pub evidence: EvidenceDetail,
725}
726
727impl EvidencedAssertion {
728    /// Validates the evidence and its consistency with the assertion's statement type.
729    pub fn validate(&self) -> Result<(), String> {
730        use crate::contextual_assertion::StatementType;
731        let a = &self.assertion;
732        if a.id.trim().is_empty() || a.subject_uri.trim().is_empty() {
733            return Err("assertion id and subject_uri are required".into());
734        }
735        self.evidence.validate()?;
736        match self.evidence.basis {
737            ClaimBasis::Measured | ClaimBasis::Described if a.root_source_id.trim().is_empty() => {
738                Err("measured or described evidence requires root_source_id".into())
739            }
740            ClaimBasis::ModelAssumption | ClaimBasis::ArtisticChoice
741                if matches!(
742                    a.statement_type,
743                    StatementType::Observation | StatementType::AdjudicatedFinding
744                ) =>
745            {
746                Err("a model assumption or artistic choice cannot be an observation or finding".into())
747            }
748            ClaimBasis::Derived
749                if a.statement_type != StatementType::Inference
750                    && a.derived_from_assertion_ids.is_empty() =>
751            {
752                Err("derived evidence must be an inference or name derived_from_assertion_ids".into())
753            }
754            _ => Ok(()),
755        }
756    }
757
758    /// Writes the assertion quins followed by the evidence quins; returns the count written.
759    pub fn compile_to_quins(&self, out: &mut [NQuin]) -> usize {
760        let a = &self.assertion;
761        let n = a.compile_to_quins(out);
762        let s = q_hash_str(&a.id);
763        let ctx = q_hash_str(&a.scope_domain);
764        let meta = a.sensitivity.to_metadata_mask() | (a.asserted_at_unix as u64);
765        self.evidence.compile_to_quins(s, ctx, meta, out, n)
766    }
767}
768
769#[cfg(test)]
770mod tests {
771    use super::*;
772    use crate::contextual_assertion::{
773        AssertionStatus, ContextualAssertion, StatementType, VerificationStatus,
774    };
775    use crate::record::SensitivityClass;
776
777    fn assertion(st: StatementType, root: &str) -> ContextualAssertion {
778        ContextualAssertion {
779            id: "ea-1".into(),
780            subject_uri: "https://biodiversity.org.au/afd/taxa/Wallabia_bicolor".into(),
781            statement_type: st,
782            assertion_status: AssertionStatus::Active,
783            verification_status: VerificationStatus::Proposed,
784            claim_summary: "head-body length".into(),
785            author_did: "did:example:curator".into(),
786            root_source_id: root.into(),
787            derived_from_assertion_ids: Vec::new(),
788            scope_domain: "species:wallabia-bicolor".into(),
789            sensitivity: SensitivityClass::Public,
790            asserted_at_unix: 1_700_000_000,
791            expires_at_unix: None,
792            superseded_by_id: None,
793            adjudicated_by_human_did: None,
794        }
795    }
796
797    fn measured() -> EvidenceDetail {
798        EvidenceDetail {
799            property_iri: "http://purl.obolibrary.org/obo/VT_0002257".into(),
800            basis: ClaimBasis::Measured,
801            value: Some(EvidenceValue::Range {
802                min: 0.665,
803                max: 0.847,
804                unit_iri: "http://qudt.org/vocab/unit/M".into(),
805            }),
806            uncertainty: None,
807            method_iri: Some("urn:example:method:caliper".into()),
808            observed_at: None,
809            valid_during: None,
810            scope: BiologicalScope {
811                life_stage_iri: Some("http://purl.obolibrary.org/obo/UBERON_0000113".into()),
812                ..Default::default()
813            },
814            source_record_id: Some("record-42".into()),
815            media_region: None,
816            ..Default::default()
817        }
818    }
819
820    #[test]
821    fn measured_evidence_validates_and_compiles() {
822        let ea = EvidencedAssertion {
823            assertion: assertion(StatementType::Observation, "src:example-dataset"),
824            evidence: measured(),
825        };
826        ea.validate().unwrap();
827        let mut out = [NQuin::default(); 32];
828        let n = ea.compile_to_quins(&mut out);
829        // 5 assertion + property, basis, min, max, unit, method, life stage, source record.
830        assert_eq!(n, 13);
831        let min = out[7];
832        assert_eq!(min.predicate, q_hash_str(P_VALUE_MIN));
833        assert_eq!(min.object, INLINE_TAG_DECIMAL | 665_000);
834        assert!(out[..n].iter().all(|q| q.parity == q.subject ^ q.predicate ^ q.object ^ q.context));
835    }
836
837    #[test]
838    fn evidence_validation_fails_closed() {
839        let mut e = measured();
840        e.method_iri = None;
841        assert!(e.validate().unwrap_err().contains("method"));
842
843        let mut e = measured();
844        e.basis = ClaimBasis::Unknown;
845        e.method_iri = None;
846        assert!(e.validate().unwrap_err().contains("unknown"));
847
848        let mut e = measured();
849        e.value = Some(EvidenceValue::Range { min: 2.0, max: 1.0, unit_iri: "u".into() });
850        assert!(e.validate().is_err());
851
852        let mut e = measured();
853        e.value = Some(EvidenceValue::Quantity { value: 1.0, unit_iri: String::new() });
854        assert!(e.validate().unwrap_err().contains("unit"));
855    }
856
857    #[test]
858    fn assertion_consistency_is_enforced() {
859        let no_source = EvidencedAssertion {
860            assertion: assertion(StatementType::Observation, ""),
861            evidence: measured(),
862        };
863        assert!(no_source.validate().unwrap_err().contains("root_source_id"));
864
865        let mut assumption = measured();
866        assumption.basis = ClaimBasis::ModelAssumption;
867        let bad = EvidencedAssertion {
868            assertion: assertion(StatementType::Observation, "src"),
869            evidence: assumption.clone(),
870        };
871        assert!(bad.validate().unwrap_err().contains("model assumption"));
872        let ok = EvidencedAssertion {
873            assertion: assertion(StatementType::Attestation, "src"),
874            evidence: assumption,
875        };
876        ok.validate().unwrap();
877
878        let mut derived = measured();
879        derived.basis = ClaimBasis::Derived;
880        let bad = EvidencedAssertion {
881            assertion: assertion(StatementType::Observation, "src"),
882            evidence: derived,
883        };
884        assert!(bad.validate().unwrap_err().contains("derived"));
885    }
886
887    #[test]
888    fn negative_values_fall_back_to_lexical_hash() {
889        let o = encode_decimal_object(-0.2);
890        assert_eq!(o, q_hash_str("-0.2^^xsd:decimal"));
891        assert_eq!(encode_decimal_object(0.95), INLINE_TAG_DECIMAL | 950_000);
892    }
893
894    #[test]
895    fn epistemic_tiers_and_observer_roles_cover_all_seven_levels() {
896        let tiers = [
897            EpistemicTier::DirectlyObserved,
898            EpistemicTier::InferredFromObservation,
899            EpistemicTier::ExtractedFromRecord,
900            EpistemicTier::LongitudinallyProjected,
901            EpistemicTier::StatisticallyCalibrated,
902            EpistemicTier::PhylogeneticallyBracketed,
903            EpistemicTier::AuthorialIntent,
904        ];
905        for (idx, tier) in tiers.iter().enumerate() {
906            assert_eq!(tier.rank() as usize, idx);
907            assert!(tier.as_iri().starts_with("https://ns.webizen.org/epistemic#"));
908            assert!(!tier.as_str().is_empty());
909        }
910        assert!(EpistemicTier::DirectlyObserved < EpistemicTier::AuthorialIntent);
911
912        let roles = [
913            ObserverRole::SelfMeasured,
914            ObserverRole::PeerMeasured,
915            ObserverRole::ClinicianMeasured,
916            ObserverRole::IsakCertified,
917            ObserverRole::AutomatedSensor,
918            ObserverRole::CuratorExtracted,
919        ];
920        for role in roles {
921            assert!(role.as_iri().starts_with("https://ns.webizen.org/epistemic#"));
922            assert!(!role.as_str().is_empty());
923        }
924    }
925
926    #[test]
927    fn observation_methods_cover_all_q42m_taxonomies() {
928        let samples = [
929            (ObservationMethod::FlexibleTapeCircumference, "q42m:FlexibleTapeCircumference", 1),
930            (ObservationMethod::DexaArealDensitometry, "q42m:DEXA_ArealDensitometry", 2),
931            (ObservationMethod::ClinicalCtQuantitativeQct, "q42m:ClinicalCT_Quantitative_QCT", 2),
932            (ObservationMethod::ClinicalMriDixonPdff, "q42m:ClinicalMRI_DixonPDFF", 2),
933            (ObservationMethod::DiagnosticUltrasound3D, "q42m:DiagnosticUltrasound_3D", 2),
934            (ObservationMethod::BiplanarFluoroscopyXromm, "q42m:BiplanarFluoroscopy_XROMM", 2),
935            (ObservationMethod::TerrestrialLidarTls, "q42m:TerrestrialLiDAR_TLS", 2),
936            (ObservationMethod::InertialImuArray, "q42m:InertialIMU_Array", 3),
937            (ObservationMethod::IsokineticDynamometry, "q42m:IsokineticDynamometry", 3),
938            (ObservationMethod::GaitMatPressureWalkway, "q42m:GaitMat_PressureWalkway", 3),
939            (ObservationMethod::ElectronicHealthRecordFhir, "q42m:ElectronicHealthRecord_FHIR", 4),
940            (ObservationMethod::IcdCodedDiagnosis, "q42m:ICD_CodedDiagnosis", 4),
941            (ObservationMethod::PathologyReport, "q42m:PathologyReport", 4),
942            (ObservationMethod::SubjectSelfReportQuestionnaire, "q42m:SubjectSelfReport_Questionnaire", 4),
943        ];
944        for (method, expected_curie, expected_cat) in samples {
945            assert_eq!(method.as_curie(), expected_curie);
946            assert_eq!(method.category_code(), expected_cat);
947            assert!(method.as_iri().starts_with("https://ns.webizen.org/epistemic/method#"));
948        }
949    }
950
951    #[test]
952    fn temporal_observation_axis_exponential_decay() {
953        let day_ms: i64 = 86_400_000;
954        let t0: i64 = 1_700_000_000_000;
955        let axis = TemporalObservationAxis {
956            phenomenon_time_ms: t0,
957            acquisition_time_ms: Some(t0 + 5_000),
958            extraction_time_ms: Some(t0 + 60_000),
959            calibration_time_ms: Some(t0 + 120_000),
960            half_life_days: Some(7.0),
961        };
962        assert!((axis.compute_decayed_confidence(t0) - 1.0).abs() < 1e-12);
963        assert!((axis.compute_decayed_confidence(t0 - day_ms) - 1.0).abs() < 1e-12);
964        assert!((axis.compute_decayed_confidence(t0 + 7 * day_ms) - 0.5).abs() < 1e-12);
965        assert!((axis.compute_decayed_confidence(t0 + 14 * day_ms) - 0.25).abs() < 1e-12);
966        assert!((axis.compute_decayed_confidence_from_base(0.8, t0 + 7 * day_ms) - 0.4).abs() < 1e-12);
967
968        let invariant = TemporalObservationAxis::with_stability_class(
969            t0,
970            TemporalStabilityClass::SkeletallyMatureInvariant,
971        );
972        assert!((invariant.compute_decayed_confidence(t0 + 3650 * day_ms) - 1.0).abs() < 1e-12);
973    }
974
975    #[test]
976    fn compile_to_quins_emits_all_epistemic_and_temporal_provenance() {
977        let t0: i64 = 1_700_000_000_000;
978        let detail = EvidenceDetail {
979            property_iri: "https://ns.webizen.org/dens#arealBMD".into(),
980            basis: ClaimBasis::Measured,
981            value: Some(EvidenceValue::Quantity {
982                value: 1.045,
983                unit_iri: "http://qudt.org/vocab/unit/GM-PER-CentiM2".into(),
984            }),
985            uncertainty: Some(Uncertainty {
986                standard_deviation: Some(0.012),
987                interval: Some((1.021, 1.069)),
988                interval_confidence: Some(0.95),
989                sample_size: Some(1),
990            }),
991            method_iri: None,
992            observed_at: Some("2026-11-15T10:00:00Z".into()),
993            valid_during: Some("2026-11-15T10:00:00Z/2027-11-15T10:00:00Z".into()),
994            valid_from: Some("2026-11-15T10:00:00Z".into()),
995            valid_until: Some("2027-11-15T10:00:00Z".into()),
996            scope: BiologicalScope::default(),
997            source_record_id: Some("dexa-l1-l4-01".into()),
998            media_region: Some("xywh=120,240,80,160".into()),
999            epistemic_tier: Some(EpistemicTier::DirectlyObserved),
1000            observation_method: Some(ObservationMethod::DexaArealDensitometry),
1001            observer_role: Some(ObserverRole::ClinicianMeasured),
1002            temporal_axis: Some(TemporalObservationAxis {
1003                phenomenon_time_ms: t0,
1004                acquisition_time_ms: Some(t0 + 1_000),
1005                extraction_time_ms: Some(t0 + 2_000),
1006                calibration_time_ms: Some(t0 + 3_000),
1007                half_life_days: Some(365.0),
1008            }),
1009            stability_class: Some(TemporalStabilityClass::OntogeneticAndSkeletalRemodeling),
1010            inference_formula_iri: None,
1011            derived_from_observation_ids: Vec::new(),
1012        };
1013        detail.validate().unwrap();
1014
1015        let mut out = [NQuin::default(); 32];
1016        let s = q_hash_str("ea-dexa-1");
1017        let ctx = q_hash_str("subject:human-1");
1018        let n = detail.compile_to_quins(s, ctx, 0, &mut out, 0);
1019        let preds: Vec<u64> = out[..n].iter().map(|q| q.predicate).collect();
1020
1021        for required in [
1022            P_OBSERVED_AT,
1023            P_VALID_FROM,
1024            P_VALID_UNTIL,
1025            P_OBSERVATION_METHOD,
1026            P_EPISTEMIC_TIER,
1027            P_OBSERVER_ROLE,
1028            P_UNCERTAINTY_VALUE,
1029            P_UNCERTAINTY_UNIT,
1030            P_UNCERTAINTY_CONFIDENCE,
1031            P_MEDIA_REGION,
1032            P_PHENOMENON_TIME_MS,
1033            P_ACQUISITION_TIME_MS,
1034            P_EXTRACTION_TIME_MS,
1035            P_CALIBRATION_TIME_MS,
1036        ] {
1037            assert!(
1038                preds.contains(&q_hash_str(required)),
1039                "missing predicate {required}"
1040            );
1041        }
1042        assert!(out[..n].iter().all(|q| q.parity == q.subject ^ q.predicate ^ q.object ^ q.context));
1043    }
1044}