Skip to main content

qualia_core_db/container_10d/
corpus_envelope.rs

1//! Species-trait envelopes read from a species corpus.
2//!
3//! The hard-coded envelopes in [`super::metric_trait_gate`] are reference examples. A bound
4//! with an evidenced assertion uses that assertion and cites its id. A bound with only a model
5//! assumption cites that assumption. A bound with no assertion falls back to the reference
6//! example and is labelled [`BoundBasis::ModelAssumption`].
7
8use qualia_cooperative_core::contextual_evidence::{ClaimBasis, EvidenceValue};
9
10use super::metric_trait_gate::MetricTraitEnvelope;
11use crate::q42::species_corpus::SpeciesCorpus;
12
13pub const P_BODY_LENGTH: &str = "https://ns.webizen.org/eco/traits#bodyLength";
14pub const P_BODY_WIDTH: &str = "https://ns.webizen.org/eco/traits#bodyWidth";
15pub const P_BODY_HEIGHT: &str = "https://ns.webizen.org/eco/traits#bodyHeight";
16pub const P_BODY_MASS: &str = "https://ns.webizen.org/eco/traits#bodyMass";
17
18pub const UNIT_METRE: &str = "http://qudt.org/vocab/unit/M";
19pub const UNIT_KILOGRAM: &str = "http://qudt.org/vocab/unit/KiloGM";
20
21/// Why a bound is held.
22#[derive(Clone, Debug, PartialEq, Eq)]
23pub enum BoundBasis {
24    /// Measured, described or derived assertions agree.
25    Evidence,
26    /// A recorded model assumption, or the reference example when the corpus is silent.
27    ModelAssumption,
28}
29
30/// One envelope axis and the assertions it cites.
31#[derive(Clone, Debug, PartialEq)]
32pub struct BoundCitation {
33    pub min: f32,
34    pub max: f32,
35    pub basis: BoundBasis,
36    pub assertion_ids: Vec<String>,
37}
38
39/// A dimensional admission envelope whose axes cite corpus assertions.
40#[derive(Clone, Debug, PartialEq)]
41pub struct CitedMetricEnvelope {
42    pub envelope: MetricTraitEnvelope,
43    pub length: BoundCitation,
44    pub width: BoundCitation,
45    pub height: BoundCitation,
46    pub mass: BoundCitation,
47}
48
49/// Reference example for a known species id (`macropus-giganteus`, spaces and underscores accepted).
50pub fn reference_envelope_for_species(species_id: &str) -> Option<&'static MetricTraitEnvelope> {
51    use super::metric_trait_gate::*;
52    let key: String = species_id
53        .chars()
54        .map(|c| {
55            if c == ' ' || c == '_' {
56                '-'
57            } else {
58                c.to_ascii_lowercase()
59            }
60        })
61        .collect();
62    Some(match key.as_str() {
63        "macropus-giganteus" | "eastern-grey-kangaroo" => &ENVELOPE_MACROPUS_GIGANTEUS,
64        "vombatus-ursinus" | "common-wombat" => &ENVELOPE_VOMBATUS_URSINUS,
65        "ornithorhynchus-anatinus" | "platypus" => &ENVELOPE_ORNITHORHYNCHUS_ANATINUS,
66        "aquila-audax" | "wedge-tailed-eagle" => &ENVELOPE_AQUILA_AUDAX,
67        "corymbia-aparrerinja" | "ghost-gum" => &ENVELOPE_CORYMBIA_APARRERINJA,
68        "field-utility-4wd" => &ENVELOPE_FIELD_UTILITY_4WD,
69        _ => return None,
70    })
71}
72
73/// Builds an envelope from `corpus`, using `reference` wherever the corpus has no range.
74///
75/// Disagreeing evidence is an error. The reference values are not mixed into an evidenced span.
76pub fn cited_envelope_from_corpus(
77    corpus: &SpeciesCorpus,
78    reference: &MetricTraitEnvelope,
79) -> Result<CitedMetricEnvelope, String> {
80    let length = cite_bound(corpus, P_BODY_LENGTH, UNIT_METRE, reference.min_length_m, reference.max_length_m)?;
81    let width = cite_bound(corpus, P_BODY_WIDTH, UNIT_METRE, reference.min_width_m, reference.max_width_m)?;
82    let height = cite_bound(corpus, P_BODY_HEIGHT, UNIT_METRE, reference.min_height_m, reference.max_height_m)?;
83    let mass = cite_bound(corpus, P_BODY_MASS, UNIT_KILOGRAM, reference.min_mass_kg, reference.max_mass_kg)?;
84    Ok(CitedMetricEnvelope {
85        envelope: MetricTraitEnvelope {
86            entity_class_id: reference.entity_class_id,
87            min_length_m: length.min,
88            max_length_m: length.max,
89            min_width_m: width.min,
90            max_width_m: width.max,
91            min_height_m: height.min,
92            max_height_m: height.max,
93            min_mass_kg: mass.min,
94            max_mass_kg: mass.max,
95        },
96        length,
97        width,
98        height,
99        mass,
100    })
101}
102
103fn cite_bound(
104    corpus: &SpeciesCorpus,
105    property: &str,
106    unit: &str,
107    ref_min: f32,
108    ref_max: f32,
109) -> Result<BoundCitation, String> {
110    if corpus.conflicts().iter().any(|c| c.property_iri == property) {
111        return Err(format!("species corpus conflicts on '{property}'"));
112    }
113    let mut evidence: Vec<(f64, f64, String)> = Vec::new();
114    let mut assumptions: Vec<(f64, f64, String)> = Vec::new();
115    for a in corpus.assertions_for(property, None) {
116        let Some((min, max, u)) = range_of(&a.evidence.value) else {
117            continue;
118        };
119        if u != unit {
120            return Err(format!(
121                "assertion '{}' uses unit '{u}', expected '{unit}'",
122                a.assertion.id
123            ));
124        }
125        let slot = match a.evidence.basis {
126            ClaimBasis::Measured | ClaimBasis::Described | ClaimBasis::Derived => &mut evidence,
127            ClaimBasis::ModelAssumption => &mut assumptions,
128            ClaimBasis::ArtisticChoice | ClaimBasis::Unknown => continue,
129        };
130        slot.push((min, max, a.assertion.id.clone()));
131    }
132    let chosen = if !evidence.is_empty() {
133        Some((BoundBasis::Evidence, evidence))
134    } else if !assumptions.is_empty() {
135        Some((BoundBasis::ModelAssumption, assumptions))
136    } else {
137        None
138    };
139    let Some((basis, spans)) = chosen else {
140        return Ok(BoundCitation {
141            min: ref_min,
142            max: ref_max,
143            basis: BoundBasis::ModelAssumption,
144            assertion_ids: Vec::new(),
145        });
146    };
147    let (min, max) = union_overlapping(&spans, property)?;
148    Ok(BoundCitation {
149        min: min as f32,
150        max: max as f32,
151        basis,
152        assertion_ids: spans.into_iter().map(|(_, _, id)| id).collect(),
153    })
154}
155
156fn range_of(value: &Option<EvidenceValue>) -> Option<(f64, f64, &str)> {
157    match value {
158        Some(EvidenceValue::Range { min, max, unit_iri }) => Some((*min, *max, unit_iri.as_str())),
159        Some(EvidenceValue::Quantity { value, unit_iri }) => Some((*value, *value, unit_iri.as_str())),
160        _ => None,
161    }
162}
163
164fn union_overlapping(spans: &[(f64, f64, String)], property: &str) -> Result<(f64, f64), String> {
165    let (mut lo, mut hi, _) = spans[0];
166    for (a0, a1, _) in spans {
167        if *a0 > hi || lo > *a1 {
168            return Err(format!("inconsistent ranges for '{property}' within one source"));
169        }
170        lo = lo.min(*a0);
171        hi = hi.max(*a1);
172    }
173    if !lo.is_finite() || !hi.is_finite() || lo > hi {
174        return Err(format!("range for '{property}' is not finite"));
175    }
176    Ok((lo, hi))
177}
178
179#[cfg(test)]
180mod tests {
181    use super::*;
182    use crate::q42::species_corpus::{KnowledgeGroup, SpeciesCorpusBuilder};
183    use crate::q42_volume::{IngestAccessPolicy, IngestProvenanceRecord};
184    use qualia_cooperative_core::contextual_assertion::{
185        AssertionStatus, ContextualAssertion, StatementType, VerificationStatus,
186    };
187    use qualia_cooperative_core::contextual_evidence::{
188        BiologicalScope, ClaimBasis, EvidenceDetail, EvidenceValue, EvidencedAssertion,
189    };
190    use qualia_cooperative_core::record::SensitivityClass;
191
192    fn measured(id: &str, property: &str, min: f64, max: f64, unit: &str) -> EvidencedAssertion {
193        EvidencedAssertion {
194            assertion: ContextualAssertion {
195                id: id.into(),
196                subject_uri: "urn:taxon:macropus".into(),
197                statement_type: StatementType::Observation,
198                assertion_status: AssertionStatus::Active,
199                verification_status: VerificationStatus::Proposed,
200                claim_summary: id.into(),
201                author_did: "did:example:curator".into(),
202                root_source_id: "src-1".into(),
203                derived_from_assertion_ids: Vec::new(),
204                scope_domain: "species:macropus-giganteus".into(),
205                sensitivity: SensitivityClass::Public,
206                asserted_at_unix: 1,
207                expires_at_unix: None,
208                superseded_by_id: None,
209                adjudicated_by_human_did: None,
210            },
211            evidence: EvidenceDetail {
212                property_iri: property.into(),
213                basis: ClaimBasis::Measured,
214                value: Some(EvidenceValue::Range {
215                    min,
216                    max,
217                    unit_iri: unit.into(),
218                }),
219                uncertainty: None,
220                method_iri: Some("urn:example:method".into()),
221                observed_at: None,
222                valid_during: None,
223                scope: BiologicalScope::default(),
224                source_record_id: None,
225                media_region: None,
226                ..Default::default()
227            },
228        }
229    }
230
231    #[test]
232    fn evidenced_length_is_cited_and_missing_axes_stay_reference_assumptions() {
233        let ingest = IngestProvenanceRecord::new(
234            IngestAccessPolicy::PublicNotForRedistribution,
235            "ab".repeat(32),
236            "1",
237            "c".repeat(64),
238            "b".repeat(64),
239        );
240        let corpus = SpeciesCorpusBuilder::new(
241            "urn:corpus:macropus",
242            "urn:taxon:macropus",
243            "macropus-giganteus",
244            "r1",
245        )
246        .source_from_ingest("src-1", "guide", &ingest)
247        .assertion(measured("ea-len", P_BODY_LENGTH, 1.0, 1.6, UNIT_METRE))
248        .gap_if_missing(
249            "gap-mass",
250            KnowledgeGroup::MorphologyAnatomy,
251            P_BODY_MASS,
252            None,
253            "no mass assertion",
254        )
255        .build()
256        .unwrap();
257        let reference = reference_envelope_for_species("Macropus giganteus").unwrap();
258        let cited = cited_envelope_from_corpus(&corpus, reference).unwrap();
259        assert_eq!(cited.length.basis, BoundBasis::Evidence);
260        assert_eq!(cited.length.assertion_ids, ["ea-len"]);
261        assert!((cited.envelope.min_length_m - 1.0).abs() < 1e-5);
262        assert_eq!(cited.mass.basis, BoundBasis::ModelAssumption);
263        assert!(cited.mass.assertion_ids.is_empty());
264        assert_eq!(cited.envelope.min_mass_kg, reference.min_mass_kg);
265    }
266}