mod authors;
mod derivative;
mod text;
use serde::{Deserialize, Serialize};
use crate::id::WorkId;
use crate::publication::{self, first_page, journal_in, same_journal};
use crate::record::SourceRecord;
use authors::{author_overlap, family_name};
use derivative::claim_mentions_derivative;
pub use derivative::is_derivative;
use text::Normalised;
pub use text::{normalise, search_terms, shared_title, title_similarity, unmarked};
const W_TITLE: f64 = 0.5;
const W_AUTHORS: f64 = 0.25;
const W_YEAR: f64 = 0.25;
const YEAR_MISMATCH_PENALTY: f64 = 0.5;
const TITLE_MISMATCH_PENALTY: f64 = 0.5;
const AUTHORS_MISMATCH_PENALTY: f64 = 0.5;
const SINGLE_FIELD_CAP: f64 = 0.7;
const UNCORROBORATED_CAP: f64 = 0.8;
const CORROBORATING_AUTHORS: f64 = 0.75;
const DERIVATIVE_PENALTY: f64 = 0.5;
const LOCATION_MISMATCH_CAP: f64 = 0.8;
const JOURNAL_MISMATCH_PENALTY: f64 = 0.9;
pub const VERIFIED: f64 = 0.85;
pub const PLAUSIBLE: f64 = 0.6;
const AUTHORS_COMPARED: usize = 3;
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Claim {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub text: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub ids: Vec<WorkId>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub title: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub authors: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub year: Option<i16>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub container: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub volume: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub page: Option<String>,
}
impl Claim {
pub fn from_text(text: impl Into<String>) -> Self {
let text = text.into();
Claim {
ids: find_ids(&text),
text: Some(text),
..Claim::default()
}
}
pub fn from_input(input: &str) -> Self {
let input = input.trim();
match input.parse::<WorkId>() {
Ok(id) => Claim {
ids: vec![id],
..Claim::default()
},
Err(_) => Claim::from_text(input),
}
}
pub fn is_empty(&self) -> bool {
self.text.is_none()
&& self.ids.is_empty()
&& self.title.is_none()
&& self.authors.is_empty()
}
pub fn reference(&self) -> Option<String> {
if let Some(text) = &self.text {
return Some(text.clone());
}
let location = match (&self.volume, &self.page) {
(Some(v), Some(p)) => Some(format!("{v}:{p}")),
(Some(v), None) => Some(v.clone()),
(None, p) => p.clone(),
};
let when = [self.year.map(|y| y.to_string()), location]
.into_iter()
.flatten()
.collect::<Vec<_>>()
.join(";");
let parts: Vec<String> = [
(!self.authors.is_empty()).then(|| self.authors.join(", ")),
self.title.clone(),
self.container.clone(),
(!when.is_empty()).then_some(when),
]
.into_iter()
.flatten()
.collect();
(!parts.is_empty()).then(|| parts.join(". "))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Agreement {
Match,
Partial,
Mismatch,
Unknown,
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct FieldCheck {
pub agreement: Agreement,
#[serde(skip_serializing_if = "Option::is_none")]
pub score: Option<f64>,
}
impl FieldCheck {
const UNKNOWN: FieldCheck = FieldCheck {
agreement: Agreement::Unknown,
score: None,
};
fn exact(agrees: bool) -> Self {
FieldCheck::scored(if agrees { 1.0 } else { 0.0 })
}
fn scored(score: f64) -> Self {
let agreement = match score {
s if s >= 0.9 => Agreement::Match,
s if s >= 0.5 => Agreement::Partial,
_ => Agreement::Mismatch,
};
FieldCheck {
agreement,
score: Some(score),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Assessment {
pub confidence: f64,
pub title: FieldCheck,
pub authors: FieldCheck,
pub year: FieldCheck,
pub container: FieldCheck,
pub volume: FieldCheck,
pub page: FieldCheck,
pub ids: Agreement,
}
pub fn assess(claim: &Claim, record: &SourceRecord) -> Assessment {
let work = &record.work;
let text = claim.text.as_deref().map(Normalised::new);
let title = match (&claim.title, &work.title, &text) {
(Some(claimed), Some(actual), _) => FieldCheck::scored(title_similarity(claimed, actual)),
(None, Some(actual), Some(text)) => FieldCheck::scored(text.title_coverage(actual)),
_ => FieldCheck::UNKNOWN,
};
let families: Vec<String> = work.authors.iter().filter_map(family_name).collect();
let authors = if families.is_empty() {
FieldCheck::UNKNOWN
} else if !claim.authors.is_empty() {
FieldCheck::scored(author_overlap(&claim.authors, &families))
} else if let Some(text) = &text {
FieldCheck::scored(text.author_coverage(&families))
} else {
FieldCheck::UNKNOWN
};
let actual_years: Vec<i16> = work
.issued
.map(|d| d.year())
.into_iter()
.chain(work.other_years.iter().copied())
.collect();
let claimed_years: Vec<i16> = match (claim.year, &text) {
(Some(y), _) => vec![y],
(None, Some(text)) => text.years(),
_ => Vec::new(),
};
let year = match actual_years.is_empty() || claimed_years.is_empty() {
false => {
let delta = claimed_years
.iter()
.flat_map(|c| actual_years.iter().map(move |a| (c - a).unsigned_abs()))
.min()
.unwrap_or(u16::MAX);
FieldCheck::scored(0.5f64.powi(i32::from(delta.min(30))))
}
true => FieldCheck::UNKNOWN,
};
let container = match (&claim.container, &work.container_title, &text) {
(Some(claimed), Some(actual), _) => FieldCheck::exact(same_journal(claimed, actual)),
(None, Some(actual), Some(text)) if journal_in(&text.words, actual) => {
FieldCheck::exact(true)
}
_ => FieldCheck::UNKNOWN,
};
let located = match &claim.text {
Some(text) if claim.volume.is_none() && claim.page.is_none() => publication::locator(text),
_ => publication::Locator {
volume: claim.volume.clone(),
page: claim.page.as_deref().map(|p| first_page(p).to_owned()),
},
};
let same = |claimed: Option<&str>, actual: Option<&str>| match (claimed, actual) {
(Some(c), Some(a)) if !c.is_empty() && !a.is_empty() => {
FieldCheck::exact(c.trim().eq_ignore_ascii_case(a.trim()))
}
_ => FieldCheck::UNKNOWN,
};
let volume = same(located.volume.as_deref(), work.volume.as_deref());
let page = same(
located.page.as_deref(),
work.page.as_deref().map(first_page),
);
let located = volume.agreement == Agreement::Match && page.agreement == Agreement::Match;
let placed = container.agreement == Agreement::Match && volume.agreement == Agreement::Match;
let title = match placed {
true if claim.title.is_none() && title.agreement == Agreement::Mismatch => {
FieldCheck::UNKNOWN
}
_ => title,
};
let ids = id_agreement(&claim.ids, &record.ids);
let id_only = [title, authors, year].iter().all(|c| c.score.is_none());
let mut confidence = if id_only && ids == Agreement::Match {
1.0
} else {
combine(title, authors, year)
};
let corroborated = authors.score.is_some_and(|s| s >= CORROBORATING_AUTHORS)
|| ids == Agreement::Match
|| located;
if !id_only && !corroborated {
confidence = confidence.min(UNCORROBORATED_CAP);
}
if [volume, page]
.iter()
.any(|c| c.agreement == Agreement::Mismatch)
{
confidence = confidence.min(LOCATION_MISMATCH_CAP);
}
if container.agreement == Agreement::Mismatch {
confidence *= JOURNAL_MISMATCH_PENALTY;
}
if let Some(actual) = &work.title
&& is_derivative(actual)
&& !claim_mentions_derivative(claim)
{
confidence *= DERIVATIVE_PENALTY;
}
Assessment {
confidence,
title,
authors,
year,
container,
volume,
page,
ids,
}
}
fn combine(title: FieldCheck, authors: FieldCheck, year: FieldCheck) -> f64 {
let parts = [(title, W_TITLE), (authors, W_AUTHORS), (year, W_YEAR)];
let known: Vec<(f64, f64)> = parts
.iter()
.filter_map(|(check, w)| check.score.map(|s| (s, *w)))
.collect();
let weight: f64 = known.iter().map(|(_, w)| w).sum();
if weight == 0.0 {
return 0.0;
}
let mut confidence = known.iter().map(|(s, w)| s * w).sum::<f64>() / weight;
if year.agreement == Agreement::Mismatch {
confidence *= YEAR_MISMATCH_PENALTY;
}
if title.agreement == Agreement::Mismatch {
confidence *= TITLE_MISMATCH_PENALTY;
}
if authors.agreement == Agreement::Mismatch {
confidence *= AUTHORS_MISMATCH_PENALTY;
}
if known.len() < 2 {
confidence = confidence.min(SINGLE_FIELD_CAP);
}
confidence
}
pub fn id_agreement(claimed: &[WorkId], actual: &[WorkId]) -> Agreement {
if claimed.is_empty() {
return Agreement::Unknown;
}
if claimed
.iter()
.any(|c| actual.iter().any(|a| same_work_id(c, a)))
{
return Agreement::Match;
}
let shares_kind = claimed
.iter()
.any(|c| actual.iter().any(|a| a.kind() == c.kind()));
if shares_kind {
Agreement::Mismatch
} else {
Agreement::Unknown
}
}
pub fn same_work_id(a: &WorkId, b: &WorkId) -> bool {
match (a, b) {
(WorkId::Arxiv(x), WorkId::Arxiv(y)) => x.unversioned() == y.unversioned(),
_ => a == b,
}
}
pub fn find_ids(text: &str) -> Vec<WorkId> {
let mut found: Vec<WorkId> = Vec::new();
for mention in crate::id::scan(text) {
if !found.iter().any(|f| same_work_id(f, &mention.id)) {
found.push(mention.id);
}
}
found
}
#[cfg(test)]
mod tests;