//! Two editions of one book, aligned: chapters, then paragraphs within aligned chapters, then sentences within //! aligned paragraphs. Baseline: Gale–Church (1993) length-based dynamic programming over beads 1:1, 1:0, 0:1, 2:1, //! 1:2, 2:2, plus **anchors** — numbers and capitalised names found on both sides — that pull the path through them, //! so one removed or merged paragraph does not shift everything after it. use crate::token::{Kind, sentences, tokens}; use serde::{Deserialize, Serialize}; use std::collections::BTreeSet; /// One aligned group: segment indices on each side (either side may be empty: an omission). #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct Bead { pub a: Vec, pub b: Vec, } /// Gale–Church variance of the length ratio. const S2: f64 = 6.8; /// Bead shapes and their prior probabilities (Gale & Church 1993, table 5), split evenly between mirror shapes. const SHAPES: [((usize, usize), f64); 6] = [((1, 1), 0.89), ((1, 0), 0.005), ((0, 1), 0.005), ((2, 1), 0.0445), ((1, 2), 0.0445), ((2, 2), 0.011)]; /// What one shared anchor is worth, in the cost's units (nats), up to three per bead. const ANCHOR: f64 = 2.5; /// Two sides that both carry numbers but share none are unlikely to be the same text. const NUMBER_MISMATCH: f64 = 2.0; struct Seg { len: f64, anchors: BTreeSet, numbers: bool, } fn seg(text: &str) -> Seg { let mut anchors = BTreeSet::new(); let mut numbers = false; for t in tokens(text) { match t.kind { Kind::Number if t.text.chars().any(|c| c.is_ascii_digit()) => { numbers = true; anchors.insert(t.text.clone()); } Kind::Word if t.capitalised() && !t.sentence_start && t.text.chars().count() >= 3 => { // Names keep their stem across languages more often than their endings (Caesar / Caesaris). let stem: String = t.text.chars().take(5).flat_map(char::to_lowercase).collect(); anchors.insert(stem); } _ => {} } } Seg { len: text.chars().filter(|c| !c.is_whitespace()).count() as f64, anchors, numbers } } /// The standard normal CDF (Abramowitz & Stegun 7.1.26 through erf). fn phi(x: f64) -> f64 { let z = x.abs() / std::f64::consts::SQRT_2; let t = 1.0 / (1.0 + 0.327_591_1 * z); let y = 1.0 - (((((1.061_405_429 * t - 1.453_152_027) * t) + 1.421_413_741) * t - 0.284_496_736) * t + 0.254_829_592) * t * (-z * z).exp(); if x >= 0.0 { 0.5 * (1.0 + y) } else { 0.5 * (1.0 - y) } } fn length_cost(la: f64, lb: f64, ratio: f64) -> f64 { if la == 0.0 && lb == 0.0 { return 0.0; } let mean = (la + lb / ratio) / 2.0; let delta = (lb - la * ratio) / (mean.max(1.0) * S2).sqrt(); let p = 2.0 * (1.0 - phi(delta.abs())); -(p.max(1e-12)).ln() } /// Aligns two sequences of segments (chapters, paragraphs or sentences) by their lengths and anchors. pub fn align>(a: &[S], b: &[S]) -> Vec { let sa: Vec = a.iter().map(|s| seg(s.as_ref())).collect(); let sb: Vec = b.iter().map(|s| seg(s.as_ref())).collect(); let (n, m) = (sa.len(), sb.len()); if n == 0 || m == 0 { return if n == 0 && m == 0 { Vec::new() } else { vec![Bead { a: (0..n).collect(), b: (0..m).collect() }] }; } let total_a: f64 = sa.iter().map(|s| s.len).sum(); let total_b: f64 = sb.iter().map(|s| s.len).sum(); let ratio = if total_a > 0.0 && total_b > 0.0 { total_b / total_a } else { 1.0 }; // A band around the diagonal keeps a book-length alignment small: wide enough for every omission seen in // practice, the whole table when the sides are short. let width = (n.abs_diff(m) + 64).max(64); let centre = |i: usize| -> usize { i * m / n }; let lo = |i: usize| centre(i).saturating_sub(width); let hi = |i: usize| (centre(i) + width).min(m); let w = 2 * width + 1; let idx = |i: usize, j: usize| -> Option { (j >= lo(i) && j <= hi(i)).then(|| i * w + (j - lo(i))) }; let mut cost = vec![f64::INFINITY; (n + 1) * w]; let mut back = vec![u8::MAX; (n + 1) * w]; cost[idx(0, 0).expect("origin in band")] = 0.0; for i in 0..=n { for j in lo(i)..=hi(i) { if i == 0 && j == 0 { continue; } let here = idx(i, j).expect("in band"); for (k, &((di, dj), prior)) in SHAPES.iter().enumerate() { if di > i || dj > j { continue; } let Some(prev) = idx(i - di, j - dj) else { continue }; let before = cost[prev]; if !before.is_finite() { continue; } let la: f64 = sa[i - di..i].iter().map(|s| s.len).sum(); let lb: f64 = sb[j - dj..j].iter().map(|s| s.len).sum(); // An omission costs its prior only: comparing a paragraph's length with nothing says nothing, and it // would make a badly fitting merge look cheaper than the omission it really is. let mut c = if di == 0 || dj == 0 { -prior.ln() } else { length_cost(la, lb, ratio) - prior.ln() }; if di > 0 && dj > 0 { let left: BTreeSet<&String> = sa[i - di..i].iter().flat_map(|s| &s.anchors).collect(); let right: BTreeSet<&String> = sb[j - dj..j].iter().flat_map(|s| &s.anchors).collect(); let shared = left.intersection(&right).count().min(3); c -= ANCHOR * shared as f64; let nums_a = sa[i - di..i].iter().any(|s| s.numbers); let nums_b = sb[j - dj..j].iter().any(|s| s.numbers); if nums_a && nums_b && shared == 0 { c += NUMBER_MISMATCH; } } if before + c < cost[here] { cost[here] = before + c; back[here] = k as u8; } } } } let mut beads = Vec::new(); let (mut i, mut j) = (n, m); while i > 0 || j > 0 { let Some(at) = idx(i, j) else { break }; let k = back[at]; if k == u8::MAX { // Unreachable inside the band (cannot happen with the band above); keep the rest as one bead. beads.push(Bead { a: (0..i).collect(), b: (0..j).collect() }); break; } let ((di, dj), _) = SHAPES[k as usize]; beads.push(Bead { a: (i - di..i).collect(), b: (j - dj..j).collect() }); i -= di; j -= dj; } beads.reverse(); beads } /// UTF-16 `(start, end)` ranges of sentences on each side of one aligned group. pub type SentencePair = (Vec<(usize, usize)>, Vec<(usize, usize)>); /// Sentences of two aligned paragraphs, aligned: each pair is the UTF-16 ranges of its sentences in `a` and in `b`. pub fn sentence_pairs(a: &str, b: &str) -> Vec { let sa = sentences(a); let sb = sentences(b); let text = |s: &str, r: (usize, usize)| -> String { let units: Vec = s.encode_utf16().collect(); String::from_utf16_lossy(&units[r.0.min(units.len())..r.1.min(units.len())]) }; let ta: Vec = sa.iter().map(|&r| text(a, r)).collect(); let tb: Vec = sb.iter().map(|&r| text(b, r)).collect(); align(&ta, &tb) .into_iter() .map(|bead| (bead.a.iter().map(|&k| sa[k]).collect(), bead.b.iter().map(|&k| sb[k]).collect())) .collect() } /// Precision, recall and F1 of an alignment against a gold one, over the links (every a-index × b-index pair of a /// bead). Omissions (beads with an empty side) count as links to nothing on that side. pub fn score(found: &[Bead], gold: &[Bead]) -> (f64, f64, f64) { let links = |beads: &[Bead]| -> BTreeSet<(Option, Option)> { let mut s = BTreeSet::new(); for bd in beads { if bd.a.is_empty() { s.extend(bd.b.iter().map(|&y| (None, Some(y)))); } else if bd.b.is_empty() { s.extend(bd.a.iter().map(|&x| (Some(x), None))); } else { for &x in &bd.a { for &y in &bd.b { s.insert((Some(x), Some(y))); } } } } s }; let f = links(found); let g = links(gold); let hit = f.intersection(&g).count() as f64; let p = if f.is_empty() { 0.0 } else { hit / f.len() as f64 }; let r = if g.is_empty() { 0.0 } else { hit / g.len() as f64 }; let f1 = if p + r == 0.0 { 0.0 } else { 2.0 * p * r / (p + r) }; (p, r, f1) }