Skip to main content

qualia_core_db/sensing/
association_table.rs

1//! Exact, bounded lookup of externally supplied association-model data.
2//!
3//! Validation checks table shape and finite numbers, not training, calibration,
4//! evidence authenticity or physical reality. The association authority must
5//! verify the model/calibration reference against these exact table contents.
6//! Citation equality binds reference IDs; the authority must separately bind
7//! them to immutable resolved content before approving their use.
8//! Priors and joint likelihoods are supplied explicitly; none are inferred from
9//! identifiers, anchor counts, confidence bytes or calibration declarations.
10
11use core::num::NonZeroU64;
12
13use super::{
14    association::{
15        AssociationEvidence, AssociationEvidenceGroup, AssociationHypothesis,
16        AssociationModelReference, AssociationRequest, AssociationValue, BinaryLogLikelihoods,
17        CalibratedAssociationModel, DependenceAssumption, MAX_ASSOCIATION_EVIDENCE,
18        MAX_ASSOCIATION_HYPOTHESES,
19    },
20    uncertainty::UncertaintyEstimate,
21};
22
23pub const MAX_ASSOCIATION_TABLE_LIKELIHOODS: usize =
24    MAX_ASSOCIATION_HYPOTHESES * MAX_ASSOCIATION_EVIDENCE;
25
26#[derive(Clone, Copy, Debug, PartialEq)]
27pub struct AssociationPriorRow {
28    pub hypothesis: AssociationHypothesis,
29    pub probability: f64,
30}
31
32/// A row applies only to the table's exact request, full hypothesis, and exact
33/// ordered group evidence. `None` denotes the entire joint evidence slice.
34#[derive(Clone, Copy, Debug, PartialEq)]
35pub struct AssociationLikelihoodRow {
36    pub hypothesis_id: NonZeroU64,
37    pub group_id: Option<NonZeroU64>,
38    pub likelihoods: BinaryLogLikelihoods,
39}
40
41#[derive(Clone, Copy, Debug, PartialEq, Eq)]
42pub enum AssociationTableError {
43    CapacityExceeded,
44    MissingInputs,
45    InvalidDependence,
46    InvalidEvidence,
47    DuplicateEvidence,
48    InvalidPrior,
49    DuplicatePrior,
50    InvalidLikelihood,
51    DuplicateLikelihood,
52    MissingLikelihood,
53    UnknownHypothesis,
54    UnknownGroup,
55}
56
57/// Zero-allocation borrowed model with complete declared table coverage.
58/// This concrete implementation accepts only finite log likelihoods/densities;
59/// exact impossible events require a different explicitly qualified model.
60pub struct TableAssociationModel<'model, 'data> {
61    reference: AssociationModelReference,
62    request: AssociationRequest,
63    dependence: DependenceAssumption,
64    evidence: &'model [AssociationEvidence<'data>],
65    priors: &'model [AssociationPriorRow],
66    likelihoods: &'model [AssociationLikelihoodRow],
67}
68
69impl<'model, 'data> TableAssociationModel<'model, 'data> {
70    pub fn new(
71        reference: AssociationModelReference,
72        request: AssociationRequest,
73        dependence: DependenceAssumption,
74        evidence: &'model [AssociationEvidence<'data>],
75        priors: &'model [AssociationPriorRow],
76        likelihoods: &'model [AssociationLikelihoodRow],
77    ) -> Result<Self, AssociationTableError> {
78        if evidence.len() > MAX_ASSOCIATION_EVIDENCE
79            || priors.len() > MAX_ASSOCIATION_HYPOTHESES
80            || likelihoods.len() > MAX_ASSOCIATION_TABLE_LIKELIHOODS
81        {
82            return Err(AssociationTableError::CapacityExceeded);
83        }
84        if evidence.is_empty() || priors.is_empty() {
85            return Err(AssociationTableError::MissingInputs);
86        }
87        if dependence == DependenceAssumption::Unknown {
88            return Err(AssociationTableError::InvalidDependence);
89        }
90        for (index, record) in evidence.iter().enumerate() {
91            if evidence[..index]
92                .iter()
93                .any(|other| other.observation_id == record.observation_id)
94            {
95                return Err(AssociationTableError::DuplicateEvidence);
96            }
97            if matches!(record.value, AssociationValue::Scalar { value, .. } if !value.is_finite())
98                || record
99                    .uncertainty
100                    .is_some_and(|uncertainty| record.field != Some(uncertainty.field()))
101            {
102                return Err(AssociationTableError::InvalidEvidence);
103            }
104            if matches!(dependence, DependenceAssumption::IndependentGroups { .. })
105                && record.dependence_group.is_none()
106            {
107                return Err(AssociationTableError::InvalidDependence);
108            }
109        }
110        for (index, row) in priors.iter().enumerate() {
111            if !row.probability.is_finite() || !(0.0..=1.0).contains(&row.probability) {
112                return Err(AssociationTableError::InvalidPrior);
113            }
114            if priors[..index]
115                .iter()
116                .any(|other| other.hypothesis.id == row.hypothesis.id)
117            {
118                return Err(AssociationTableError::DuplicatePrior);
119            }
120        }
121        for (index, row) in likelihoods.iter().enumerate() {
122            if !row.likelihoods.given_association.is_finite()
123                || !row.likelihoods.given_no_association.is_finite()
124            {
125                return Err(AssociationTableError::InvalidLikelihood);
126            }
127            if likelihoods[..index].iter().any(|other| {
128                other.hypothesis_id == row.hypothesis_id && other.group_id == row.group_id
129            }) {
130                return Err(AssociationTableError::DuplicateLikelihood);
131            }
132            if !priors
133                .iter()
134                .any(|prior| prior.hypothesis.id == row.hypothesis_id)
135            {
136                return Err(AssociationTableError::UnknownHypothesis);
137            }
138            if !group_exists(dependence, evidence, row.group_id) {
139                return Err(AssociationTableError::UnknownGroup);
140            }
141        }
142        for prior in priors {
143            if dependence == DependenceAssumption::Joint {
144                require_row(likelihoods, prior.hypothesis.id, None)?;
145            } else {
146                for (index, record) in evidence.iter().enumerate() {
147                    if !evidence[..index]
148                        .iter()
149                        .any(|other| other.dependence_group == record.dependence_group)
150                    {
151                        require_row(likelihoods, prior.hypothesis.id, record.dependence_group)?;
152                    }
153                }
154            }
155        }
156        Ok(Self {
157            reference,
158            request,
159            dependence,
160            evidence,
161            priors,
162            likelihoods,
163        })
164    }
165
166    pub const fn request(&self) -> AssociationRequest {
167        self.request
168    }
169    pub const fn dependence(&self) -> DependenceAssumption {
170        self.dependence
171    }
172    pub const fn evidence(&self) -> &'model [AssociationEvidence<'data>] {
173        self.evidence
174    }
175    pub const fn priors(&self) -> &'model [AssociationPriorRow] {
176        self.priors
177    }
178    pub const fn likelihoods(&self) -> &'model [AssociationLikelihoodRow] {
179        self.likelihoods
180    }
181}
182
183impl CalibratedAssociationModel for TableAssociationModel<'_, '_> {
184    fn reference(&self) -> AssociationModelReference {
185        self.reference
186    }
187
188    fn prior_probability(
189        &self,
190        request: &AssociationRequest,
191        hypothesis: &AssociationHypothesis,
192    ) -> Option<f64> {
193        if *request != self.request {
194            return None;
195        }
196        self.priors
197            .iter()
198            .find(|row| row.hypothesis == *hypothesis)
199            .map(|row| row.probability)
200    }
201
202    fn joint_log_likelihoods(
203        &self,
204        request: &AssociationRequest,
205        hypothesis: &AssociationHypothesis,
206        group: AssociationEvidenceGroup<'_, '_>,
207    ) -> Option<BinaryLogLikelihoods> {
208        if self.prior_probability(request, hypothesis).is_none() {
209            return None;
210        }
211        let group_id = group.group_id();
212        if !group_exists(self.dependence, self.evidence, group_id) {
213            return None;
214        }
215        let mut expected = self
216            .evidence
217            .iter()
218            .filter(|record| group_id.is_none() || record.dependence_group == group_id);
219        let mut actual = group.records();
220        loop {
221            match (expected.next(), actual.next()) {
222                (None, None) => break,
223                (Some(left), Some(right)) if exact_record(left, right) => {}
224                _ => return None,
225            }
226        }
227        self.likelihoods
228            .iter()
229            .find(|row| row.hypothesis_id == hypothesis.id && row.group_id == group_id)
230            .map(|row| row.likelihoods)
231    }
232}
233
234fn group_exists(
235    dependence: DependenceAssumption,
236    evidence: &[AssociationEvidence<'_>],
237    group: Option<NonZeroU64>,
238) -> bool {
239    match dependence {
240        DependenceAssumption::Joint => group.is_none(),
241        DependenceAssumption::IndependentGroups { .. } => {
242            group.is_some()
243                && evidence
244                    .iter()
245                    .any(|record| record.dependence_group == group)
246        }
247        DependenceAssumption::Unknown => false,
248    }
249}
250
251fn require_row(
252    rows: &[AssociationLikelihoodRow],
253    hypothesis: NonZeroU64,
254    group: Option<NonZeroU64>,
255) -> Result<(), AssociationTableError> {
256    if rows
257        .iter()
258        .any(|row| row.hypothesis_id == hypothesis && row.group_id == group)
259    {
260        Ok(())
261    } else {
262        Err(AssociationTableError::MissingLikelihood)
263    }
264}
265
266fn exact_record(left: &AssociationEvidence<'_>, right: &AssociationEvidence<'_>) -> bool {
267    if left != right {
268        return false;
269    }
270    if let (AssociationValue::Scalar { value: a, .. }, AssociationValue::Scalar { value: b, .. }) =
271        (left.value, right.value)
272    {
273        if a.to_bits() != b.to_bits() {
274            return false;
275        }
276    }
277    match (left.uncertainty, right.uncertainty) {
278        (Some(left), Some(right)) => match (left.estimate(), right.estimate()) {
279            (
280                UncertaintyEstimate::AbsoluteBound { value: a, .. },
281                UncertaintyEstimate::AbsoluteBound { value: b, .. },
282            ) => a.to_bits() == b.to_bits(),
283            (
284                UncertaintyEstimate::ConfidenceInterval {
285                    lower: a, upper: b, ..
286                },
287                UncertaintyEstimate::ConfidenceInterval {
288                    lower: c, upper: d, ..
289                },
290            ) => a.to_bits() == c.to_bits() && b.to_bits() == d.to_bits(),
291            _ => true,
292        },
293        _ => true,
294    }
295}
296
297#[cfg(test)]
298#[path = "association_table_tests.rs"]
299mod tests;