ingraph/primitives/detect/detection.rs
1//! [`Detection`]: a label and a confidence, which is the whole of what a classification with no
2//! geometry IS.
3
4use core::fmt;
5
6use crate::{
7 ColumnKind, ColumnName, ColumnShape, CompositeFilterMarker, CompositeMarker, ConfidenceFilter,
8 DefaultMarker, DefaultVecMarker, FieldName, QuantifiedMarker, Score, TextFilter,
9 column::column_eq,
10};
11
12use super::{Label, LabelWire};
13
14#[cfg(test)]
15mod tests;
16
17/// **A CLASSIFICATION** — what something was decided to be, and how sure the decider was.
18///
19/// The pair is deliberate, for the reason every DETECTION type's is. A classifier emits several
20/// candidates per subject, each with its own confidence, so a row that recorded only the label would
21/// lose the one number that says whether to believe it — and a query narrowing on label and on
22/// confidence separately would let a frame where `cat` scored `0.2` answer a question about cats
23/// above `0.8`, on the strength of some other label scoring `0.9`.
24///
25/// That is [`DetectedLanguage`](crate::primitives::lang::DetectedLanguage)'s own sentence one house
26/// over, and it holds here for the same reason rather than because the two types are one: a language
27/// is a STANDARD's identity and a label is a model's word, so the two carriers are different types
28/// carrying the same shape.
29///
30/// # IT HAS NO GEOMETRY, and that is the type rather than a field left out
31///
32/// A whole-frame classification has no box. `avanalyze`'s contract states it plainly — *a labelled,
33/// scored classification with no geometry of its own, used both for whole-frame image
34/// classification and as the label half of a subject detection* — so this is the honest shape for
35/// the first of those two, and [`LocatedDetection<T>`](super::LocatedDetection) is the honest shape
36/// for the second.
37///
38/// **There is no `Option<BoundingBox<T>>` anywhere in this house**, and the absence is the ruling.
39/// One type with an optional box would make *a classification that has a box* and *a located
40/// detection whose box went missing* the same value, so every consumer reading a location would
41/// carry a branch the type could have refused to represent. Two types make the branch unnecessary
42/// and the invalid state unrepresentable.
43///
44/// # The confidence is a [`Score`] and the type is NOT carrier-generic
45///
46/// `Score` is [`Confidence<f32>`](crate::Confidence) — the width every classifier this framework has
47/// met measures in — and this type names it rather than taking a width parameter of its own. The
48/// precedent is exact and it is in this same house:
49/// [`DetectedLanguage`](crate::primitives::lang::DetectedLanguage) holds a `Score`, not a
50/// `Confidence<S>`, and it is the sibling shape.
51///
52/// It is worth saying what the alternative would have cost, because it is not obviously worse. A
53/// `Detection<S>` would be open at the width the way [`BoundingBox<T>`](crate::BoundingBox) is open
54/// at its component — but the two parameters are not the same question. A geometry component is a
55/// UNIT the caller owns and the crate could not guess; a confidence width is a REPRESENTATION of one
56/// invariant this crate already wrote four carriers for, and the bare name a caller wants is the one
57/// the type is called. `Confidence<S>` could put that bare name into [`Score`]; `Detection<S>`
58/// cannot, `Detection` being the name already. The door is open — a second parameter is an additive
59/// change to an unpublished crate — and it opens when a caller measuring in something else arrives.
60///
61/// # Equality is the PAIR
62///
63/// The same label detected twice at different confidences is two detections, so the confidence is
64/// part of the identity rather than a payload hanging off it. That is every detection type's rule.
65///
66/// # Examples
67///
68/// ```
69/// use ingraph::{Detection, Label, Score};
70///
71/// let seen = Detection::new(
72/// Label::new("golden retriever").unwrap(),
73/// Score::new(0.87).unwrap(),
74/// );
75///
76/// assert_eq!(seen.label().as_str(), "golden retriever");
77/// assert_eq!(seen.confidence().get(), 0.87);
78/// ```
79#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
80pub struct Detection {
81 pub(super) label: Label,
82 pub(super) confidence: Score,
83}
84
85impl Detection {
86 /// A classification at a confidence.
87 ///
88 /// INFALLIBLE, because both halves have already been validated: a [`Label`] cannot be empty and a
89 /// [`Score`] cannot exist outside `[0.0, 1.0]`. There is nothing left for this constructor to
90 /// check, which is what building out of validated parts buys.
91 #[inline]
92 #[must_use]
93 pub const fn new(label: Label, confidence: Score) -> Self {
94 Self { label, confidence }
95 }
96
97 /// The word that was put on the subject.
98 #[inline]
99 #[must_use]
100 pub const fn label(&self) -> &Label {
101 &self.label
102 }
103
104 /// How confident the classifier was, in `[0.0, 1.0]`.
105 #[inline]
106 #[must_use]
107 pub const fn confidence(&self) -> Score {
108 self.confidence
109 }
110}
111
112/// The label and the confidence, which is the whole of what a detection is.
113impl fmt::Debug for Detection {
114 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
115 f.debug_struct("Detection")
116 .field("label", &self.label.as_str())
117 .field("confidence", &self.confidence.get())
118 .finish()
119 }
120}
121
122/// The word, then the confidence in brackets — `golden retriever (0.87)`.
123///
124/// A rendering rather than a round trip, and it is worth saying which: nothing parses this back. A
125/// label may hold a bracket, a digit or a space, so no grammar over this text could tell a label
126/// ending in `(0.5)` from a detection.
127impl fmt::Display for Detection {
128 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
129 write!(f, "{} ({})", self.label, self.confidence.get())
130 }
131}
132
133/// The label column's segment.
134pub(crate) const LABEL: &FieldName = FieldName::new("label");
135
136/// The confidence column's segment.
137///
138/// `confidence` rather than `score`, and the choice is deliberate rather than inherited.
139/// [`DetectedLanguage`](crate::primitives::lang::DetectedLanguage)'s own storage note records the
140/// open question — *a classifier's is a SCORE, a detector's is a CONFIDENCE*, two words for one type
141/// — and asks that it be settled deliberately rather than quietly. This house settles it the same
142/// way that one did, on the type's own name: what this pair holds is a DETECTION, so its degree
143/// column is a confidence, and a schema carrying both houses carries one word between them.
144pub(crate) const CONFIDENCE: &FieldName = FieldName::new("confidence");
145
146/// **The TWO columns a detection spans.**
147///
148/// Both are `Plain`: each half is a leaf, so the whole of a detection is two named columns and there
149/// is nothing to nest. A detection at `top` reaches `top_label` and `top_confidence`.
150pub(super) const SEGMENTS: &[ColumnShape] = &[
151 ColumnShape::Plain(ColumnName::of(LABEL)),
152 ColumnShape::Plain(ColumnName::of(CONFIDENCE)),
153];
154
155/// **The STORAGE half of the width** — two columns, each its own leaf's.
156impl ColumnKind for Detection {
157 const SEGMENTS: &'static [ColumnShape] = SEGMENTS;
158}
159
160/// **One leaf, and it is the value.** A detection means its two columns as declared, so no term over one expands.
161impl crate::DeclaredLeaves for Detection {}
162
163// A detection is one column value when the word and the confidence both are — the same pairing
164// this type's own `PartialEq` already reads.
165column_eq! { Detection }
166
167/// **The DECLARED half — TWO words**, each read off the half that owns it.
168///
169/// The arity is FIXED because both halves are, which is what lets this row exist at all: a
170/// `StoredAs` row is an array whose length is written into the impl, and the boundary
171/// [`TimeRanged<T>`](crate::TimeRanged) records — a generic payload whose word count no length
172/// position can name — is a boundary this type never approaches.
173impl<Db> crate::StoredAs<Db> for Detection
174where
175 Label: crate::StoredAs<Db>,
176 Score: crate::StoredAs<Db>,
177{
178 const WORDS: &'static [&'static str] = &[
179 <Label as crate::StoredAs<Db>>::WORDS[0],
180 <Score as crate::StoredAs<Db>>::WORDS[0],
181 ];
182}
183
184/// **THE ADMISSION** — a detection is one element of a collection, and this is the row a TOP-K field
185/// needs.
186///
187/// A classifier emits *k* candidates per subject, so `Vec<Detection>` is what a row actually holds.
188/// [`CollectionElement`](crate::CollectionElement) states the one fact a width cannot — whether this
189/// type is itself MANY — and a detection is a word and a number, so it is not.
190impl crate::CollectionElement for Detection {}
191
192/// **TWO BINDS OUT**, in segment order, with the one comma between them.
193#[cfg(feature = "sqlx")]
194impl<Db> crate::Carrier<Db> for Detection
195where
196 Db: sqlx::Database,
197 Label: crate::Carrier<Db>,
198 Score: crate::Carrier<Db>,
199{
200 fn push_bind(&self, qb: &mut sqlx::QueryBuilder<Db>) {
201 <Label as crate::Carrier<Db>>::push_bind(&self.label, qb);
202 qb.push(", ");
203 <Score as crate::Carrier<Db>>::push_bind(&self.confidence, qb);
204 }
205}
206
207/// **AND THE TWO BACK IN**, by name.
208///
209/// It states no invariant of its own, and that is the layering rather than an omission: whatever
210/// each half refuses at its own column it refuses here — an empty stored label is
211/// [`EmptyLabel`](super::EmptyLabel), named by the column that held it, and a stored `1.5` in the
212/// confidence column is refused by [`Confidence`](crate::Confidence)'s row. A detection has no rule
213/// ACROSS its two columns, so there is nothing left for this level to re-prove.
214#[cfg(feature = "sqlx")]
215impl<'a, R> crate::Assemble<'a, R> for Detection
216where
217 R: sqlx::Row,
218 Label: crate::Assemble<'a, R>,
219 Score: crate::Assemble<'a, R>,
220{
221 fn assemble(row: &'a R, under: Option<&crate::Path<'_>>) -> sqlx::Result<Self> {
222 let label: Label = crate::assembled(row, LABEL, under)?;
223 let confidence: Score = crate::assembled(row, CONFIDENCE, under)?;
224
225 Ok(Self::new(label, confidence))
226 }
227}
228
229/// **THE KEYSET POSITION** — the two halves in segment order, each behind its own four-byte length.
230///
231/// # The FRAMING is this holder's, and it is the framework's own spelling of it
232///
233/// [`write_member`](crate::cursor::write_member) and
234/// [`read_member`](crate::cursor::read_member) are the crate's one authority for *several values in
235/// one buffer* — the pair a generated composite frames its columns with and the varying list rows
236/// frame their elements with — and this row reaches it rather than inventing a delimiter.
237///
238/// The alternative was to divide the payload by known widths, which is what
239/// [`BoundingBox<T>`](crate::BoundingBox) and [`TimeRanged<T>`](crate::TimeRanged) do. **Neither
240/// division is available here**: a label is VARIABLE-WIDTH and it is FIRST in segment order, so
241/// there is no constant split point from either end — a fixed tail would work only while the
242/// confidence's width could not change, and the label's own bytes could contain anything. Four bytes
243/// a member is what buys a read that REFUSES instead of one that returns a plausible value for bytes
244/// this type never wrote.
245///
246/// The ORDER the bytes encode is the COLUMNS' rather than a claim about detections: this type
247/// publishes no [`Ord`], and a page's need for *an* order is not a claim about *the* order. That is
248/// [`TimeRanged<T>`](crate::TimeRanged)'s own sentence at its own cursor.
249impl crate::CursorValue for Detection {
250 fn write_cursor(&self, out: &mut Vec<u8>) {
251 crate::cursor::write_member(&self.label, out);
252 crate::cursor::write_member(&self.confidence, out);
253 }
254
255 fn read_cursor(bytes: &[u8]) -> Option<Self> {
256 let mut rest = bytes;
257 let label = crate::cursor::read_member::<Label>(&mut rest)?;
258 let confidence = crate::cursor::read_member::<Score>(&mut rest)?;
259
260 // Both members have been read, so anything left is bytes no member owns — a frame this type did
261 // not write.
262 rest.is_empty().then(|| Self::new(label, confidence))
263 }
264}
265
266/// **THE DOCUMENT'S FORM: TWO KEYS AT ONE LEVEL** — the label, then the confidence.
267///
268/// ```text
269/// { "label": "golden retriever", "confidence": 0.87 }
270/// ```
271///
272/// The confidence is a `Double` through the width's own row: BSON's only binary float is 64 bits and
273/// an `f32` widens into it exactly. The `[0.0, 1.0]` invariant is the DOMAIN's rather than the
274/// column's, so nothing about it is encoded — which is the same sentence the SQL bind makes by
275/// binding the wrapped float.
276///
277/// As with every other row of its kind here, this is the FILTER OPERAND's form and not a serde row.
278#[cfg(feature = "mongo")]
279impl crate::MongoCarrier for Detection {
280 fn to_bson(&self) -> bson::Bson {
281 let mut detection = bson::Document::new();
282
283 detection.insert(LABEL.as_str(), crate::MongoCarrier::to_bson(&self.label));
284 detection.insert(
285 CONFIDENCE.as_str(),
286 crate::MongoCarrier::to_bson(&self.confidence),
287 );
288
289 bson::Bson::Document(detection)
290 }
291}
292
293/// **THE READ: the two keys back through their own doors** —
294/// [`MongoCarrier`](crate::MongoCarrier)'s mirror, key for key.
295#[cfg(feature = "mongo")]
296impl crate::query::mongo::MongoExtract for Detection {
297 const BSON: &'static str = "object";
298
299 fn extract(value: Option<&bson::Bson>) -> Result<Self, crate::query::mongo::MongoTypeError> {
300 let held = match value {
301 Some(bson::Bson::Document(held)) => held,
302 Some(other) => {
303 return Err(crate::query::mongo::MongoTypeError::wrong_type(
304 Self::BSON,
305 crate::query::mongo::alias(other),
306 ));
307 }
308 None => return Err(crate::query::mongo::MongoTypeError::Absent),
309 };
310
311 let label = <Label as crate::query::mongo::MongoExtract>::extract(held.get(LABEL.as_str()))?;
312 let confidence =
313 <Score as crate::query::mongo::MongoExtract>::extract(held.get(CONFIDENCE.as_str()))?;
314
315 Ok(Self::new(label, confidence))
316 }
317}
318
319/// What guards a [`Detection`] column — its own filter at both seats.
320///
321/// A detection stores every field it declares, so the two seats name one predicate.
322impl CompositeFilterMarker for Detection {
323 type Filter = DetectionFilter;
324 type ColumnFilter = DetectionFilter;
325}
326
327/// The interpretation a [`Detection`] field is read under — the COMPOSITE reading, because the value
328/// occupies columns of its own and both can be absent together.
329impl DefaultMarker for Detection {
330 type Marker = CompositeMarker<Detection>;
331}
332
333/// **A COLLECTION of detections is asked through the QUANTIFIERS alone.**
334///
335/// This is [`DetectedLanguage`](crate::primitives::lang::DetectedLanguage)'s ruling read over a
336/// second detection type, and every clause of its argument transfers unchanged, because what makes
337/// the argument is the FLOAT rather than the language. Each of the seven operators a
338/// [`ListFilter`](crate::ListFilter) would publish takes a whole detection as its operand, and a
339/// whole detection carries a confidence:
340///
341/// * `hasElement` is exact float equality against a number a client typed, so it answers *no rows*
342/// to the question the caller believed they had asked — *was this label seen at about this
343/// confidence*.
344/// * `eq` and `ne` are that same falseness per element, multiplied by the collection's length.
345/// * `gt`, `gte`, `lt` and `lte` compare two whole collections lexicographically, under an order
346/// composed of a label's bytewise one and a float's.
347///
348/// What is left is `any` and `count`, and `any` loses nothing: it carries the whole
349/// [`DetectionFilter`], so `any: { label: { eq: "cat" }, confidence: { gte: 0.8 } }` is *a cat was
350/// seen, and confidently* — which is the question `hasElement` was pretending to be able to ask.
351///
352/// **This is where TOP-K lives.** A ranked list of candidates is a collection, `count` asks how many
353/// there were, and `any` asks about each — so nothing about ranking belongs in the element type.
354impl DefaultVecMarker for Detection {
355 type Marker = QuantifiedMarker<Vec<Detection>>;
356}
357
358/// The filter that guards a [`Detection`] column: the WORD's own filter, and the CONFIDENCE beside
359/// it.
360///
361/// ```text
362/// input DetectionFilter {
363/// label: LabelFilter
364/// confidence: ConfidenceFilter
365/// }
366/// ```
367///
368/// # `label` takes the TEXT family's twenty words
369///
370/// [`TextFilter`] — `eq`, `ne`, the four orderings, `in`/`notIn`, and the three affix families with
371/// a `nocase` and a negation apiece. Every one of them is a question somebody asks of a label:
372/// `eq: "cat"` is the exact word, `contains: "retriever"` is the breed family, and
373/// `startsWithNocase` is where the case this crate refuses to fold gets asked about instead. See
374/// [`Label`], where the division with the engine is argued.
375///
376/// # `confidence` takes the framework's SIX confidence words
377///
378/// [`ConfidenceFilter`] — `eq`, `ne`, `gt`, `gte`, `lt`, `lte` — and every one is well-defined,
379/// because [`Score`]'s constructor refuses `NaN` and the resulting order is total. `eq` and `ne`
380/// earn their place: `eq: 1.0` is a saturated classifier and `ne: 0.0` is *was it a candidate at
381/// all*, both exactly representable and both genuinely asked.
382///
383/// `in` and `notIn` are ABSENT FROM THE KIND rather than declined here — a membership list over a
384/// continuous measurement resolves each member at a width the client cannot see. See
385/// [`ConfidenceFilter`], where the framework argues it.
386///
387/// # NO WHOLE-DETECTION OPERATOR, and the leaf-tuple equality is still askable
388///
389/// There is no `eq` slot holding a whole detection, no `ne`, no `in`, and no ordering. The leaf
390/// tuple IS the conjunction of the two facets — `{ label: { eq: "cat" }, confidence: { eq: 0.9 } }`
391/// lowers to `label = ? AND confidence = ?`, which is what whole-value equality over a composite
392/// means and the only operator that decomposes conjunctively — so a separate slot would be a second
393/// spelling of one question and a conflict to adjudicate when a client wrote both.
394///
395/// A whole-value `ne` over a composite is a DISJUNCTION, which does not decompose into the
396/// conjunction a filter's slots are joined by; a whole-value `in` spelled per-column is the CARTESIAN
397/// PRODUCT. Ordering is refused for the reason the [`DefaultVecMarker`] row above gives: an order
398/// composed of a word's and a float's is an order over the storage that would read like a ranking.
399/// That is [`BoundingBoxFilter`](crate::BoundingBoxFilter)'s posture one house over, reached by the
400/// same road.
401#[derive(Default)]
402pub struct DetectionFilter {
403 pub(super) label: Option<TextFilter<Label, LabelWire>>,
404 pub(super) confidence: Option<ConfidenceFilter>,
405}
406
407impl DetectionFilter {
408 /// The empty filter — no facet set, so a column guarded by it is unconstrained.
409 #[inline]
410 #[must_use]
411 pub const fn new() -> Self {
412 Self {
413 label: None,
414 confidence: None,
415 }
416 }
417
418 /// True while NO operator slot is set on EITHER facet.
419 pub fn is_empty(&self) -> bool {
420 self
421 .label
422 .as_ref()
423 .is_none_or(crate::GraphqlFilter::is_empty)
424 && self
425 .confidence
426 .as_ref()
427 .is_none_or(ConfidenceFilter::is_empty)
428 }
429
430 crate::graphql::filter::opt_accessor!(
431 label: TextFilter<Label, LabelWire> => with_label, set_label, maybe_label, update_label
432 );
433 crate::graphql::filter::opt_accessor!(
434 confidence: ConfidenceFilter => with_confidence, set_confidence, maybe_confidence, update_confidence
435 );
436}
437
438impl crate::GraphqlFilter for DetectionFilter {
439 #[inline]
440 fn is_empty(&self) -> bool {
441 Self::is_empty(self)
442 }
443}
444
445impl fmt::Debug for DetectionFilter {
446 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
447 f.debug_struct("DetectionFilter")
448 .field("label", &self.label)
449 .field("confidence", &self.confidence)
450 .finish()
451 }
452}
453
454impl Clone for DetectionFilter {
455 fn clone(&self) -> Self {
456 Self {
457 label: self.label.clone(),
458 confidence: self.confidence.clone(),
459 }
460 }
461}
462
463impl PartialEq for DetectionFilter {
464 fn eq(&self, other: &Self) -> bool {
465 self.label == other.label && self.confidence == other.confidence
466 }
467}