Skip to main content

fprint_pipeline/
matcher.rs

1// SPDX-FileCopyrightText: 2026 fprintd (pure-Rust) contributors
2//
3// SPDX-License-Identifier: MIT OR Apache-2.0
4
5//! The NBIS-template matcher seam — the back half of the pipeline, onto [`fprint_bozorth3`].
6//!
7//! It converts an [`fprint_core::Template::Nbis`] (host-side minutiae, one inner vector per
8//! enrolled capture) into `fprint_bozorth3::Minutia` and scores a probe against an enrolled
9//! template, taking the **maximum** score over enrolled samples — libfprint/NBIS's verify
10//! semantics.
11//!
12//! The conversion lives here rather than in `fprint-bozorth3` so the matcher stays a self-contained,
13//! dependency-free arithmetic kernel — the `xyt` triple is the only shared fact. A match-on-chip
14//! `Raw` handle is opaque and never host-matched.
15
16use fprint_core::Template;
17
18/// The outcome of scoring one template against another.
19///
20/// [`nbis_match_score`] returns this rather than a bare `u32` so a caller cannot mistake "cannot be
21/// host-matched" for "scored zero". The two are genuinely different: [`Scored(0)`](MatchScore::Scored)
22/// is a real comparison that found nothing in common, while
23/// [`Incomparable`](MatchScore::Incomparable) means there were no host-side minutiae to compare at all
24/// (a match-on-chip handle, or an un-enrolled template).
25#[derive(Clone, Copy, Debug, PartialEq, Eq)]
26#[non_exhaustive]
27pub enum MatchScore {
28    /// Both templates carried host-side NBIS minutiae and were scored by BOZORTH3. The value is the
29    /// raw score; `0` is a valid outcome — a comparison that matched nothing.
30    Scored(u32),
31    /// The pair cannot be host-matched: at least one template is a match-on-chip `Raw` handle or an
32    /// `Undefined` template, so there are no host minutiae for BOZORTH3 to compare.
33    Incomparable,
34}
35
36impl MatchScore {
37    /// The BOZORTH3 score if the pair was comparable, else `None`.
38    #[must_use]
39    pub fn score(self) -> Option<u32> {
40        match self {
41            MatchScore::Scored(score) => Some(score),
42            MatchScore::Incomparable => None,
43        }
44    }
45
46    /// Whether this outcome clears `threshold`: a [`Scored(s)`](MatchScore::Scored) with
47    /// `s >= threshold`. An [`Incomparable`](MatchScore::Incomparable) pair never accepts.
48    #[must_use]
49    pub fn accepts(self, threshold: u32) -> bool {
50        matches!(self, MatchScore::Scored(score) if score >= threshold)
51    }
52}
53
54/// Score a `scanned` probe template against an `enrolled` one.
55///
56/// When **both** are [`Template::Nbis`], returns [`MatchScore::Scored`] with the BOZORTH3 match score
57/// — the maximum over every (enrolled-sample, scanned-sample) pair, since each capture is an
58/// independent minutiae set (libfprint/NBIS verify semantics). When either is a match-on-chip
59/// [`Template::Raw`] handle or [`Template::Undefined`], there are no host minutiae to compare and the
60/// result is [`MatchScore::Incomparable`]. Turn a score into a decision with
61/// [`accepts`](MatchScore::accepts) against a driver threshold (or use [`nbis_verify`]).
62#[must_use]
63pub fn nbis_match_score(enrolled: &Template, scanned: &Template) -> MatchScore {
64    let (Template::Nbis(enrolled_samples), Template::Nbis(scanned_samples)) = (enrolled, scanned)
65    else {
66        return MatchScore::Incomparable;
67    };
68
69    let mut best = 0;
70    for probe in scanned_samples {
71        let probe: Vec<fprint_bozorth3::Minutia> = probe.iter().map(to_bz).collect();
72        for gallery in enrolled_samples {
73            let gallery: Vec<fprint_bozorth3::Minutia> = gallery.iter().map(to_bz).collect();
74            best = best.max(fprint_bozorth3::match_score(&probe, &gallery));
75        }
76    }
77    MatchScore::Scored(best)
78}
79
80/// Verify (1:1): whether `scanned` matches `enrolled` at or above `threshold`.
81///
82/// The one-line decision form of [`nbis_match_score`] for the common verify path, mirroring
83/// [`nbis_identify`]'s 1:N shape. An [`Incomparable`](MatchScore::Incomparable) pair never verifies.
84#[must_use]
85pub fn nbis_verify(enrolled: &Template, scanned: &Template, threshold: u32) -> bool {
86    nbis_match_score(enrolled, scanned).accepts(threshold)
87}
88
89/// Identify (1:N): the `gallery` index whose enrolled template best matches `scanned` and clears
90/// `threshold`, or `None` if none does.
91///
92/// This is the host-image `identify` semantics: score the probe against each enrolled template
93/// ([`nbis_match_score`]) and take the strongest above the driver threshold. Ties resolve to the
94/// **lowest** index (first-best), so the result is deterministic.
95#[must_use]
96pub fn nbis_identify(scanned: &Template, gallery: &[Template], threshold: u32) -> Option<usize> {
97    let mut best: Option<(usize, u32)> = None;
98    for (i, enrolled) in gallery.iter().enumerate() {
99        let Some(score) = nbis_match_score(enrolled, scanned).score() else {
100            continue; // an incomparable pair is never a candidate
101        };
102        if score >= threshold && best.is_none_or(|(_, b)| score > b) {
103            best = Some((i, score));
104        }
105    }
106    best.map(|(i, _)| i)
107}
108
109/// Convert a slice of domain [`fprint_core::Minutia`] into `fprint_bozorth3::Minutia`s ready to score.
110///
111/// One enrolled or scanned capture is one such slice; the result is the input BOZORTH3's
112/// [`match_score`](fprint_bozorth3::match_score) takes. Only the `xyt` triple crosses the boundary —
113/// the same interoperability fact [`nbis_match_score`] applies internally per sample.
114#[must_use]
115pub fn minutiae_to_bozorth(ms: &[fprint_core::Minutia]) -> Vec<fprint_bozorth3::Minutia> {
116    ms.iter().map(to_bz).collect()
117}
118
119/// Convert one domain minutia to the matcher's xyt triple (an interoperability fact, not coupling).
120#[inline]
121fn to_bz(m: &fprint_core::Minutia) -> fprint_bozorth3::Minutia {
122    fprint_bozorth3::Minutia {
123        x: m.x,
124        y: m.y,
125        theta: m.theta,
126    }
127}
128
129#[cfg(test)]
130mod tests {
131    use super::*;
132    use fprint_core::Minutia;
133
134    fn nbis(pts: Vec<Minutia>) -> Template {
135        Template::Nbis(vec![pts])
136    }
137
138    #[test]
139    fn a_raw_or_undefined_template_is_incomparable() {
140        let host = nbis(vec![Minutia {
141            x: 1,
142            y: 2,
143            theta: 3,
144        }]);
145
146        assert_eq!(
147            nbis_match_score(&Template::Undefined, &host),
148            MatchScore::Incomparable
149        );
150        assert_eq!(
151            nbis_match_score(&host, &Template::Undefined),
152            MatchScore::Incomparable
153        );
154        assert_eq!(
155            nbis_match_score(&Template::Raw(vec![0xAB]), &host),
156            MatchScore::Incomparable
157        );
158
159        // Incomparable never yields a score and never verifies, at any threshold.
160        assert_eq!(nbis_match_score(&Template::Undefined, &host).score(), None);
161        assert!(!nbis_verify(&Template::Raw(vec![0xAB]), &host, 0));
162    }
163
164    #[test]
165    fn two_nbis_templates_are_scored_even_when_empty() {
166        // Two empty Nbis templates are comparable: the score is a real `0`, not "incomparable".
167        let empty = Template::Nbis(vec![]);
168        assert_eq!(nbis_match_score(&empty, &empty), MatchScore::Scored(0));
169        assert_eq!(nbis_match_score(&empty, &empty).score(), Some(0));
170    }
171
172    #[test]
173    fn accepts_needs_a_score_at_or_over_threshold() {
174        assert!(MatchScore::Scored(50).accepts(40));
175        assert!(MatchScore::Scored(40).accepts(40));
176        assert!(!MatchScore::Scored(39).accepts(40));
177        assert!(!MatchScore::Incomparable.accepts(0));
178    }
179}