Skip to main content

aspero_engine/
verdict.rs

1//! Turning scored candidates into a verdict, why ([`Reason`]), and a
2//! one-sentence reason in English.
3
4use aspero_core::matching::{self, PLAUSIBLE, VERIFIED};
5use aspero_core::publication::first_page;
6use aspero_core::{Agreement, Claim, Update, UpdateKind};
7
8use crate::resolve::{Candidate, ClaimExt, ResolveReport};
9
10#[derive(Debug, Clone, Copy, PartialEq, Eq)]
11#[non_exhaustive]
12pub enum Verdict {
13    /// A work matching the claim exists (and so do its claimed identifiers).
14    Verified,
15    /// A work partly matching the claim exists; check the details.
16    Plausible,
17    /// The claimed identifier is wrong: it doesn't exist, or it belongs to
18    /// a work that doesn't match the rest of the claim.
19    Mismatch,
20    /// No matching work was found.
21    NotFound,
22    /// Providers failed, so nothing conclusive can be said.
23    Unverifiable,
24}
25
26impl Verdict {
27    pub fn as_str(self) -> &'static str {
28        match self {
29            Verdict::Verified => "verified",
30            Verdict::Plausible => "plausible",
31            Verdict::Mismatch => "mismatch",
32            Verdict::NotFound => "not_found",
33            Verdict::Unverifiable => "unverifiable",
34        }
35    }
36}
37
38#[derive(Debug, Clone)]
39#[non_exhaustive]
40pub struct Verification {
41    pub verdict: Verdict,
42    /// One sentence, for people and agents: [`why`](Self::why) and
43    /// [`notes`](Self::notes) in English.
44    pub reason: String,
45    /// Why, as data, for front ends that word it themselves.
46    pub why: Reason,
47    /// What to know about the work the verdict is about, whatever the
48    /// verdict: its retraction or withdrawal, and its newer version.
49    pub notes: Vec<Update>,
50    /// The candidate the verdict is about, as an index into
51    /// `report.candidates`: the matching work, or the best guess at what was
52    /// meant.
53    pub best: Option<usize>,
54    pub report: ResolveReport,
55}
56
57/// Why a verdict was reached. "The work" is the verdict's candidate
58/// ([`Verification::best`]); "the identifiers" are those the claim gave.
59#[derive(Debug, Clone, PartialEq, Eq)]
60#[non_exhaustive]
61pub enum Reason {
62    /// The citation matches the work. (Verified)
63    Matches,
64    /// The citation partly matches the work. (Plausible) `differs` is
65    /// never empty.
66    PartlyMatches { differs: Vec<Difference> },
67    /// The citation agrees with the work as far as it goes, but gives too
68    /// little to confirm it: nothing differs, and no authors, identifier
69    /// or journal and place corroborate it. (Plausible)
70    Unconfirmed,
71    /// The closest work shares the title, but other details differ.
72    /// (Mismatch) `differs` is never empty.
73    Closest { differs: Vec<Difference> },
74    /// No matching work. (NotFound)
75    NoMatch,
76    /// The identifiers exist; the claim gives nothing else to compare.
77    /// (Verified)
78    IdExists,
79    /// The identifiers exist and the citation agrees. (Verified)
80    IdAgrees,
81    /// The identifiers exist and the citation partly matches, or shares
82    /// the title with an error such as a wrong year. (Plausible) `differs`
83    /// is never empty.
84    IdPartlyMatches { differs: Vec<Difference> },
85    /// The identifiers are another work (candidate `cited`); the citation
86    /// matches the work. (Mismatch)
87    IdElsewhere { cited: usize },
88    /// The identifiers' work (the work) doesn't match the citation, and no
89    /// other does. (Mismatch)
90    IdDisagrees,
91    /// The identifiers don't exist; the citation matches the work.
92    /// (Mismatch)
93    IdMissingElsewhere,
94    /// The identifiers don't exist, and no matching work was found.
95    /// (NotFound)
96    IdMissing,
97    /// Providers failed, so nothing conclusive can be said. (Unverifiable)
98    ProvidersFailed,
99}
100
101impl Reason {
102    /// A short machine-friendly name.
103    pub fn as_str(&self) -> &'static str {
104        match self {
105            Reason::Matches => "matches",
106            Reason::PartlyMatches { .. } => "partly_matches",
107            Reason::Unconfirmed => "unconfirmed",
108            Reason::Closest { .. } => "closest",
109            Reason::NoMatch => "no_match",
110            Reason::IdExists => "id_exists",
111            Reason::IdAgrees => "id_agrees",
112            Reason::IdPartlyMatches { .. } => "id_partly_matches",
113            Reason::IdElsewhere { .. } => "id_elsewhere",
114            Reason::IdDisagrees => "id_disagrees",
115            Reason::IdMissingElsewhere => "id_missing_elsewhere",
116            Reason::IdMissing => "id_missing",
117            Reason::ProvidersFailed => "providers_failed",
118        }
119    }
120
121    /// The fields that differ, where the reason has them.
122    pub fn differs(&self) -> &[Difference] {
123        match self {
124            Reason::PartlyMatches { differs }
125            | Reason::Closest { differs }
126            | Reason::IdPartlyMatches { differs } => differs,
127            _ => &[],
128        }
129    }
130}
131
132/// A cited field the work disagrees with, and the work's value if it's
133/// worth showing.
134#[derive(Debug, Clone, PartialEq, Eq)]
135#[non_exhaustive]
136pub struct Difference {
137    pub field: CitedField,
138    pub actual: Option<String>,
139}
140
141#[derive(Debug, Clone, Copy, PartialEq, Eq)]
142#[non_exhaustive]
143pub enum CitedField {
144    Title,
145    Authors,
146    Year,
147    Journal,
148    Volume,
149    FirstPage,
150    /// What kind of work it is: the work is a reply, correction or
151    /// commentary on the one cited (`actual`: "correction", "reply", …).
152    Kind,
153}
154
155impl CitedField {
156    pub fn as_str(self) -> &'static str {
157        match self {
158            CitedField::Title => "title",
159            CitedField::Authors => "authors",
160            CitedField::Year => "year",
161            CitedField::Journal => "journal",
162            CitedField::Volume => "volume",
163            CitedField::FirstPage => "first_page",
164            CitedField::Kind => "kind",
165        }
166    }
167}
168
169impl std::fmt::Display for Difference {
170    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
171        f.write_str(&self.field.as_str().replace('_', " "))?;
172        match (&self.actual, self.field) {
173            (Some(v), CitedField::Journal) => write!(f, " (\"{v}\")"),
174            (Some(v), _) => write!(f, " ({v})"),
175            (None, _) => Ok(()),
176        }
177    }
178}
179
180/// The same title plus matching authors *or* year, with the other wrong: a
181/// real work cited with an error (wrong year, misattributed authors), not a
182/// missing one. The title alone proves little: short titles like "Protein
183/// Folding" occur inside many longer ones.
184fn near_miss(c: &Candidate) -> bool {
185    let a = &c.assessment;
186    a.title.agreement == Agreement::Match
187        && (a.authors.agreement == Agreement::Match || a.year.agreement == Agreement::Match)
188}
189
190/// The fields that don't fully agree. With `known_only`, only fields both
191/// sides gave and that disagree; otherwise also those the citation doesn't
192/// confirm.
193fn differences(claim: &Claim, c: &Candidate, known_only: bool) -> Vec<Difference> {
194    let a = &c.assessment;
195    let w = &c.record.work;
196    let off = |check: &matching::FieldCheck| match known_only {
197        true => matches!(check.agreement, Agreement::Mismatch | Agreement::Partial),
198        false => check.agreement != Agreement::Match,
199    };
200    let diff = |field, actual: Option<String>| Difference { field, actual };
201    [
202        off(&a.title).then(|| diff(CitedField::Title, None)),
203        off(&a.authors).then(|| diff(CitedField::Authors, None)),
204        matches!(a.year.agreement, Agreement::Mismatch | Agreement::Partial)
205            .then(|| diff(CitedField::Year, w.issued.map(|d| d.year().to_string()))),
206        (a.container.agreement == Agreement::Mismatch)
207            .then(|| diff(CitedField::Journal, w.container_title.clone())),
208        (a.volume.agreement == Agreement::Mismatch)
209            .then(|| diff(CitedField::Volume, w.volume.clone())),
210        (a.page.agreement == Agreement::Mismatch).then(|| {
211            let first = w.page.as_deref().map(|p| first_page(p).to_owned());
212            diff(CitedField::FirstPage, first)
213        }),
214        w.title
215            .as_deref()
216            .and_then(matching::derivative_kind)
217            .filter(|_| !matching::claim_mentions_derivative(claim))
218            .map(|kind| diff(CitedField::Kind, Some(kind.to_owned()))),
219    ]
220    .into_iter()
221    .flatten()
222    .collect()
223}
224
225/// The differences as a clause: "its year (2017) differs", "its authors and
226/// year (2017) differ".
227fn clause(differs: &[Difference]) -> Option<String> {
228    let fields: Vec<String> = differs.iter().map(ToString::to_string).collect();
229    match fields.len() {
230        0 => None,
231        1 => Some(format!("its {} differs", fields[0])),
232        _ => Some(format!("its {} differ", fields.join(" and "))),
233    }
234}
235
236fn describe(c: &Candidate) -> String {
237    let w = &c.record.work;
238    let title = w.title.as_deref().unwrap_or("(untitled)");
239    let year = w
240        .issued
241        .map(|d| format!(" ({})", d.year()))
242        .unwrap_or_default();
243    let id = c.ids.first().map(|i| format!(", {i}")).unwrap_or_default();
244    format!("\"{title}\"{year}{id}")
245}
246
247/// Turns gathered candidates into a verdict.
248pub(crate) fn judge(claim: &Claim, report: ResolveReport) -> Verification {
249    let (verdict, why, best) = decide(claim, &report);
250    // Existing is not the same as citable or current: say so whatever the
251    // verdict.
252    let notes: Vec<Update> = best
253        .map(|i| &report.candidates[i])
254        .into_iter()
255        .flat_map(|c| {
256            [
257                c.retraction(),
258                c.updates.iter().find(|u| u.kind == UpdateKind::NewVersion),
259            ]
260        })
261        .flatten()
262        .cloned()
263        .collect();
264    let mut reason = explain(claim, &report, &why, best);
265    if !notes.is_empty() {
266        let notes: Vec<String> = notes.iter().map(describe_update).collect();
267        reason = format!("{reason}; note: {}", notes.join("; "));
268    }
269    Verification {
270        verdict,
271        reason,
272        why,
273        notes,
274        best,
275        report,
276    }
277}
278
279/// [`weigh`], settled: a reason that lists differences always lists
280/// one. Agreeing without them is [`Reason::Unconfirmed`]; a closest work
281/// that differs in nothing named isn't a mismatch to report.
282fn decide(claim: &Claim, report: &ResolveReport) -> (Verdict, Reason, Option<usize>) {
283    match weigh(claim, report) {
284        (
285            verdict,
286            Reason::PartlyMatches { differs } | Reason::IdPartlyMatches { differs },
287            best,
288        ) if differs.is_empty() => (verdict, Reason::Unconfirmed, best),
289        (_, Reason::Closest { differs }, _) if differs.is_empty() => {
290            (Verdict::NotFound, Reason::NoMatch, None)
291        }
292        settled => settled,
293    }
294}
295
296fn weigh(claim: &Claim, report: &ResolveReport) -> (Verdict, Reason, Option<usize>) {
297    let best = report.candidates.first();
298    let best_conf = best.map_or(0.0, |c| c.assessment.confidence);
299    let failed = !report.errors.is_empty()
300        || report
301            .lookups
302            .iter()
303            .any(|l| l.record.is_none() && !l.is_not_found());
304
305    if claim.ids.is_empty() {
306        return match best {
307            Some(_) if best_conf >= VERIFIED => (Verdict::Verified, Reason::Matches, Some(0)),
308            Some(c) if best_conf >= PLAUSIBLE => (
309                Verdict::Plausible,
310                Reason::PartlyMatches {
311                    differs: differences(claim, c, true),
312                },
313                Some(0),
314            ),
315            Some(c) if near_miss(c) => (
316                Verdict::Mismatch,
317                Reason::Closest {
318                    differs: differences(claim, c, false),
319                },
320                Some(0),
321            ),
322            _ if failed => (Verdict::Unverifiable, Reason::ProvidersFailed, None),
323            _ => (Verdict::NotFound, Reason::NoMatch, None),
324        };
325    }
326    let by_id = report
327        .candidates
328        .iter()
329        .position(|c| c.assessment.ids == Agreement::Match);
330    let elsewhere = |skip: Option<usize>| {
331        report
332            .candidates
333            .iter()
334            .enumerate()
335            .position(|(i, c)| Some(i) != skip && c.assessment.confidence >= PLAUSIBLE)
336    };
337    match by_id.map(|i| (i, &report.candidates[i])) {
338        Some((i, _)) if !claim.is_descriptive() => (Verdict::Verified, Reason::IdExists, Some(i)),
339        Some((i, c)) if c.assessment.confidence >= VERIFIED => {
340            (Verdict::Verified, Reason::IdAgrees, Some(i))
341        }
342        Some((i, c)) if c.assessment.confidence >= PLAUSIBLE => (
343            Verdict::Plausible,
344            Reason::IdPartlyMatches {
345                differs: differences(claim, c, true),
346            },
347            Some(i),
348        ),
349        Some((i, c)) => match elsewhere(Some(i)) {
350            Some(j) => (Verdict::Mismatch, Reason::IdElsewhere { cited: i }, Some(j)),
351            // The identifiers' work, cited with an error (a wrong year):
352            // the same title, and matching authors or year.
353            None if near_miss(c) => (
354                Verdict::Plausible,
355                Reason::IdPartlyMatches {
356                    differs: differences(claim, c, true),
357                },
358                Some(i),
359            ),
360            None => (Verdict::Mismatch, Reason::IdDisagrees, Some(i)),
361        },
362        None if failed => (Verdict::Unverifiable, Reason::ProvidersFailed, None),
363        None => match elsewhere(None) {
364            Some(j) => (Verdict::Mismatch, Reason::IdMissingElsewhere, Some(j)),
365            None => (Verdict::NotFound, Reason::IdMissing, None),
366        },
367    }
368}
369
370/// The reason in English, without notes.
371fn explain(claim: &Claim, report: &ResolveReport, why: &Reason, best: Option<usize>) -> String {
372    let claimed = claim
373        .ids
374        .iter()
375        .map(ToString::to_string)
376        .collect::<Vec<_>>()
377        .join(", ");
378    let work = || {
379        best.map(|i| describe(&report.candidates[i]))
380            .unwrap_or_default()
381    };
382    let details = || clause(why.differs());
383    match why {
384        Reason::Matches => format!("matches {}", work()),
385        Reason::PartlyMatches { .. } => format!(
386            "partly matches {}; {}",
387            work(),
388            details().unwrap_or_else(|| "check the details".into())
389        ),
390        Reason::Unconfirmed => format!(
391            "agrees with {} as far as it goes, but gives too little to confirm it",
392            work()
393        ),
394        Reason::Closest { .. } => format!(
395            "closest work is {}, but {}",
396            work(),
397            details().unwrap_or_else(|| "its details differ".into())
398        ),
399        Reason::NoMatch => "no matching work found".into(),
400        Reason::IdExists => format!("{claimed} exists: {}", work()),
401        Reason::IdAgrees => format!("{claimed} and the citation agree: {}", work()),
402        Reason::IdPartlyMatches { .. } => format!(
403            "{claimed} exists and partly matches the citation: {}{}",
404            work(),
405            details().map(|d| format!("; {d}")).unwrap_or_default()
406        ),
407        Reason::IdElsewhere { cited } => format!(
408            "{claimed} is {}, but the citation matches {}",
409            describe(&report.candidates[*cited]),
410            work()
411        ),
412        Reason::IdDisagrees => {
413            format!("{claimed} is {}, which does not match the citation", work())
414        }
415        Reason::IdMissingElsewhere => {
416            format!("{claimed} does not exist; the citation matches {}", work())
417        }
418        Reason::IdMissing => format!("{claimed} does not exist and no matching work was found"),
419        Reason::ProvidersFailed if claim.ids.is_empty() => {
420            "providers failed; nothing conclusive".into()
421        }
422        Reason::ProvidersFailed => format!("could not look up {claimed}: providers failed"),
423    }
424}
425
426/// "RETRACTED (2010-02-06, notice doi:…, via retraction-watch)".
427pub fn describe_update(u: &Update) -> String {
428    // The notice of a new version is the newer work itself.
429    if u.kind == UpdateKind::NewVersion {
430        let by = u
431            .notice
432            .as_ref()
433            .map(|n| format!(" by {n}"))
434            .unwrap_or_default();
435        let date = u.date.map(|d| format!(" ({d})")).unwrap_or_default();
436        return format!("superseded{by}{date}");
437    }
438    let what = match &u.kind {
439        UpdateKind::Retraction => "RETRACTED".to_owned(),
440        UpdateKind::Withdrawal => "WITHDRAWN".to_owned(),
441        UpdateKind::ExpressionOfConcern => "expression of concern".to_owned(),
442        UpdateKind::Correction => "corrected".to_owned(),
443        other => other.as_str().replace('_', " "),
444    };
445    let details: Vec<String> = [
446        u.date.map(|d| d.to_string()),
447        u.notice.as_ref().map(|n| format!("notice {n}")),
448        u.source.as_ref().map(|s| format!("via {s}")),
449    ]
450    .into_iter()
451    .flatten()
452    .collect();
453    if details.is_empty() {
454        what
455    } else {
456        format!("{what} ({})", details.join(", "))
457    }
458}