Skip to main content

graphrt_core/grounding/
figures.rs

1//! The numbers check of a report: every number a text states must be one of the facts, as
2//! rounded for the text.
3//!
4//! Unlike [`super::check`], which reads a chat reply sentence by sentence, this check looks at
5//! numbers only and leaves the words to the writer: a report may say anything about the figures,
6//! as long as each figure is one of the facts. It reports the numbers that are not, and changes
7//! nothing.
8//!
9//! - **Rounding**: a number matches a fact that rounds to it at the precision it is written with.
10//!   `13.2%` matches `13.19`, `13%` matches `12.6`, `1.2 million` matches `1,234,567`, but
11//!   `13.21` does not match `13.2` (a figure more precise than the facts is made up).
12//!   [`Tolerance::Exact`] asks for the value itself.
13//! - **Shares**: with `ratios_as_percent`, `13.19%` matches the ratio `0.1319` and `0.13`
14//!   matches `13%`.
15//! - **Notation**: `1.234.567` and `1,234,567` are the same number, and so are `13,19` and
16//!   `13.19`. A number that can be read both ways (`1.234`) matches either reading. Multipliers
17//!   (`15k`, `15 rb`, `2 jt`, `1.5 million`, `3 miliar`) are applied. Signs are ignored:
18//!   "down 5%" states the figure `-5%` as `5%`.
19//! - **Words**: `0`, `1` and `2` written alone are words ("2 stores"), not figures. A digit glued
20//!   to letters before it (`Q3`, `H1`, `v2`) is a name, not a figure.
21//!
22//! Facts are texts, read the same way, or JSON values, whose numbers are taken as they are (a
23//! JSON `1.234` is one and a quarter, never a thousand).
24
25/// How close a number must be to a fact.
26#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
27#[non_exhaustive]
28pub enum Tolerance {
29    /// The fact rounds to the number at the precision it is written with.
30    #[default]
31    Rounding,
32    /// The number is the fact.
33    Exact,
34}
35
36/// How numbers are compared.
37#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
38pub struct NumberRules {
39    pub tolerance: Tolerance,
40    /// A percentage matches the ratio it is (`13.19%` and `0.1319`), both ways.
41    pub ratios_as_percent: bool,
42}
43
44/// A number the facts do not hold, with the sentence it stands in.
45#[derive(Clone, Debug, PartialEq, Eq)]
46pub struct UnsupportedNumber {
47    /// The number as the text writes it (`13.2%`, `1,2 juta`).
48    pub number: String,
49    pub sentence: String,
50}
51
52/// The numbers some facts hold.
53#[derive(Clone, Debug, Default)]
54pub struct Figures {
55    /// Each value, and whether it was written as a percentage.
56    values: Vec<(f64, bool)>,
57}
58
59/// Multipliers a number may be written with, in the word right after it.
60const MULTIPLIERS: &[(&str, f64)] = &[
61    ("k", 1e3),
62    ("rb", 1e3),
63    ("ribu", 1e3),
64    ("thousand", 1e3),
65    ("jt", 1e6),
66    ("juta", 1e6),
67    ("mn", 1e6),
68    ("million", 1e6),
69    ("millions", 1e6),
70    ("miliar", 1e9),
71    ("milyar", 1e9),
72    ("billion", 1e9),
73    ("bn", 1e9),
74    ("triliun", 1e12),
75    ("trillion", 1e12),
76];
77
78/// Currency codes and signs written right before a number (`Rp15.000`, `US$5`, `IDR 2jt`):
79/// the letters do not make the number part of a name.
80const CURRENCY_PREFIXES: &[&str] = &[
81    "rp", "idr", "us", "usd", "eur", "sgd", "s", "myr", "rm", "gbp", "jpy", "aud", "a", "inr", "rs", "php", "thb",
82    "vnd", "cny", "rmb", "hkd", "hk", "cad", "c", "nzd", "nz", "chf", "brl", "r", "zar", "krw", "kes", "ksh", "ngn",
83];
84
85/// One number in a text: the readings it may have.
86#[derive(Clone, Debug)]
87pub(super) struct Written {
88    pub(super) text: String,
89    readings: Vec<Reading>,
90    percent: bool,
91    /// Written with digits alone: no separator, multiplier or percent sign (`7`, `2024`).
92    pub(super) plain: bool,
93    /// Byte offset in the text, for its sentence.
94    pub(super) at: usize,
95    /// Byte offset right after the number as written (its multiplier and `%` included).
96    pub(super) end: usize,
97}
98
99impl Written {
100    /// The value of a plain number (`Self::plain`), `None` for any other.
101    pub(super) fn plain_value(&self) -> Option<f64> {
102        match self.readings.as_slice() {
103            [reading] if self.plain => Some(reading.value),
104            _ => None,
105        }
106    }
107}
108
109/// One reading of a number: its value and the half unit of its last written digit.
110#[derive(Clone, Copy, Debug)]
111struct Reading {
112    value: f64,
113    half_unit: f64,
114}
115
116impl Figures {
117    pub fn new() -> Self {
118        Self::default()
119    }
120
121    /// Adds the numbers a text states.
122    pub fn add_text(&mut self, text: &str) {
123        for number in scan(text) {
124            for reading in &number.readings {
125                self.values.push((reading.value, number.percent));
126            }
127        }
128    }
129
130    /// Adds the numbers of a JSON value: its numbers as they are, its strings as texts.
131    pub fn add_json(&mut self, value: &serde_json::Value) {
132        match value {
133            serde_json::Value::Number(number) => {
134                if let Some(value) = number.as_f64() {
135                    self.values.push((value.abs(), false));
136                }
137            }
138            serde_json::Value::String(text) => self.add_text(text),
139            serde_json::Value::Array(items) => items.iter().for_each(|item| self.add_json(item)),
140            serde_json::Value::Object(fields) => fields.values().for_each(|item| self.add_json(item)),
141            serde_json::Value::Null | serde_json::Value::Bool(_) => {}
142        }
143    }
144
145    /// Whether the facts hold no number.
146    pub fn is_empty(&self) -> bool {
147        self.values.is_empty()
148    }
149
150    /// The numbers of `text` the facts do not hold, in order.
151    pub fn unsupported(&self, text: &str, rules: NumberRules) -> Vec<UnsupportedNumber> {
152        scan(text)
153            .into_iter()
154            .filter(|number| !self.holds(number, rules))
155            .map(|number| UnsupportedNumber { sentence: sentence_at(text, number.at), number: number.text })
156            .collect()
157    }
158
159    pub(super) fn holds(&self, number: &Written, rules: NumberRules) -> bool {
160        number.readings.iter().any(|reading| {
161            self.values.iter().any(|(fact, fact_percent)| {
162                let mut candidates = vec![(*fact, 1.0)];
163                if rules.ratios_as_percent {
164                    // A ratio fact read as a percentage, a percentage fact as a ratio.
165                    if number.percent && !fact_percent {
166                        candidates.push((fact * 100.0, 1.0));
167                    }
168                    if !number.percent && *fact_percent {
169                        candidates.push((fact / 100.0, 1.0));
170                    }
171                }
172                candidates.iter().any(|(fact, _)| close(*fact, *reading, rules.tolerance))
173            })
174        })
175    }
176}
177
178/// How far apart two written numbers are when they match, `None` when they do not: a number
179/// matches another when either rounds to the other at the precision it is written with (or,
180/// with [`Tolerance::Exact`], when they are the same value). With `ratios_as_percent` a
181/// percentage matches the ratio it is, both ways.
182#[cfg(feature = "compare-numbers")]
183pub(super) fn distance(left: &Written, right: &Written, rules: NumberRules) -> Option<f64> {
184    let mut best: Option<f64> = None;
185    for a in &left.readings {
186        for b in &right.readings {
187            let mut values = vec![b.value];
188            let mut units = vec![b.half_unit];
189            if rules.ratios_as_percent && left.percent != right.percent {
190                // The right number read as the left one is written: a ratio as a percentage,
191                // a percentage as a ratio.
192                let by = if left.percent { 100.0 } else { 0.01 };
193                values.push(b.value * by);
194                units.push(b.half_unit * by);
195            }
196            for (value, half_unit) in values.into_iter().zip(units) {
197                let room = match rules.tolerance {
198                    Tolerance::Rounding => a.half_unit.max(half_unit),
199                    Tolerance::Exact => 0.0,
200                };
201                let slack = 1e-9 * a.value.abs().max(value.abs()).max(1.0);
202                let gap = (a.value - value).abs();
203                if gap <= room + slack && best.is_none_or(|best| gap < best) {
204                    best = Some(gap);
205                }
206            }
207        }
208    }
209    best
210}
211
212fn close(fact: f64, reading: Reading, tolerance: Tolerance) -> bool {
213    let room = match tolerance {
214        Tolerance::Rounding => reading.half_unit,
215        Tolerance::Exact => 0.0,
216    };
217    // A little more, for values that binary floating point cannot write exactly.
218    let slack = 1e-9 * reading.value.abs().max(1.0);
219    (fact.abs() - reading.value).abs() <= room + slack
220}
221
222/// The numbers of `text`.
223pub(super) fn scan(text: &str) -> Vec<Written> {
224    let chars: Vec<(usize, char)> = text.char_indices().collect();
225    let mut found = Vec::new();
226    let mut index = 0;
227    while let Some(&(at, c)) = chars.get(index) {
228        if !c.is_ascii_digit() {
229            index += 1;
230            continue;
231        }
232        // A digit glued to letters (`Q3`, `H1`, `v2`, `gpt5`) is part of a name, unless the
233        // letters are a currency (`Rp15.000`).
234        let in_a_name =
235            letters_before(&chars, index).is_some_and(|letters| !CURRENCY_PREFIXES.contains(&letters.as_str()));
236        let start = index;
237        while let Some(&(_, c)) = chars.get(index) {
238            let separator_between_digits = matches!(c, '.' | ',')
239                && chars.get(index + 1).is_some_and(|(_, next)| next.is_ascii_digit())
240                && index > start;
241            if c.is_ascii_digit() || separator_between_digits {
242                index += 1;
243            } else {
244                break;
245            }
246        }
247        let token: String = chars.get(start..index).unwrap_or_default().iter().map(|(_, c)| c).collect();
248        // Letters right after the digits (`15k`, `2jt`) or a word after a space (`15 ribu`).
249        let (word, word_end) = word_after(&chars, index);
250        if in_a_name {
251            index = index.max(word_end);
252            continue;
253        }
254        let multiplier =
255            word.as_deref().and_then(|word| MULTIPLIERS.iter().find(|(name, _)| *name == word).map(|(_, by)| *by));
256        let glued_letters = chars.get(index).is_some_and(|(_, c)| c.is_alphabetic());
257        // Letters glued to the digits that are not a multiplier (`3rd`, `2x`): still a number.
258        let percent = percent_after(&chars, index, word.as_deref());
259        let mut written = token.clone();
260        let mut end = index;
261        if let Some(word) = word.as_deref().filter(|_| multiplier.is_some()) {
262            written = if glued_letters { format!("{token}{word}") } else { format!("{token} {word}") };
263            end = word_end;
264        }
265        if percent {
266            written.push('%');
267        }
268        let readings: Vec<Reading> = readings_of(&token)
269            .into_iter()
270            .map(|reading| match multiplier {
271                Some(by) => Reading { value: reading.value * by, half_unit: reading.half_unit * by },
272                None => reading,
273            })
274            .collect();
275        let plain = !percent && multiplier.is_none() && !token.contains(['.', ',']);
276        let a_word = plain && readings.iter().all(|reading| reading.value <= 2.0);
277        if !readings.is_empty() && !a_word {
278            let end_at = match word.as_deref() {
279                _ if !percent => end,
280                Some("percent" | "persen" | "pct") => word_end,
281                _ => percent_end(&chars, end),
282            };
283            let end_byte = chars.get(end_at).map_or(text.len(), |(byte, _)| *byte);
284            found.push(Written { text: written, readings, percent, plain, at, end: end_byte });
285        }
286        index = end.max(index);
287    }
288    found
289}
290
291/// The letters glued before position `at` (`$` signs skipped), lowercase, if any.
292fn letters_before(chars: &[(usize, char)], at: usize) -> Option<String> {
293    let mut start = at;
294    while start > 0 && chars.get(start - 1).is_some_and(|(_, c)| *c == '$') {
295        start -= 1;
296    }
297    let end = start;
298    while start > 0 && chars.get(start - 1).is_some_and(|(_, c)| c.is_alphabetic()) {
299        start -= 1;
300    }
301    (start < end)
302        .then(|| chars.get(start..end).unwrap_or_default().iter().flat_map(|(_, c)| c.to_lowercase()).collect())
303}
304
305/// The word right after a number (glued or after spaces), lowercase, and where it ends.
306fn word_after(chars: &[(usize, char)], from: usize) -> (Option<String>, usize) {
307    let mut index = from;
308    while chars.get(index).is_some_and(|(_, c)| *c == ' ' || *c == '\u{a0}') {
309        index += 1;
310    }
311    let start = index;
312    while chars.get(index).is_some_and(|(_, c)| c.is_alphabetic()) {
313        index += 1;
314    }
315    if index == start {
316        return (None, from);
317    }
318    let word: String = chars.get(start..index).unwrap_or_default().iter().flat_map(|(_, c)| c.to_lowercase()).collect();
319    (Some(word), index)
320}
321
322/// Where the `%` after the number ends (the index after it), or `from` when the percent is a
323/// word that `from` already passed.
324fn percent_end(chars: &[(usize, char)], from: usize) -> usize {
325    let mut index = from;
326    while chars.get(index).is_some_and(|(_, c)| *c == ' ' || *c == '\u{a0}') {
327        index += 1;
328    }
329    if chars.get(index).is_some_and(|(_, c)| *c == '%') { index + 1 } else { from }
330}
331
332/// Whether a `%` or the word percent follows the number.
333fn percent_after(chars: &[(usize, char)], from: usize, word: Option<&str>) -> bool {
334    let mut index = from;
335    while chars.get(index).is_some_and(|(_, c)| *c == ' ' || *c == '\u{a0}') {
336        index += 1;
337    }
338    chars.get(index).is_some_and(|(_, c)| *c == '%') || matches!(word, Some("percent" | "persen" | "pct"))
339}
340
341/// The values `token` (digits with `.` and `,`) may mean.
342fn readings_of(token: &str) -> Vec<Reading> {
343    let separators: Vec<char> = token.chars().filter(|c| matches!(c, '.' | ',')).collect();
344    let groups: Vec<&str> = token.split(['.', ',']).collect();
345    let integer = |digits: &str| digits.parse::<f64>().ok();
346    let decimal = |whole: &str, fraction: &str| {
347        let value = format!("{whole}.{fraction}").parse::<f64>().ok()?;
348        let places = i32::try_from(fraction.len()).ok()?;
349        Some(Reading { value, half_unit: 0.5 * 10f64.powi(-places) })
350    };
351    let whole = |digits: String| integer(&digits).map(|value| Reading { value, half_unit: 0.5 });
352    let mut readings = Vec::new();
353    match separators.as_slice() {
354        [] => readings.extend(whole(token.to_owned())),
355        [_] => {
356            let (Some(left), Some(right)) = (groups.first(), groups.get(1)) else { return readings };
357            // `1.234` or `1,234`: a thousand and more, or one and a little.
358            if right.len() == 3 {
359                readings.extend(whole(format!("{left}{right}")));
360            }
361            readings.extend(decimal(left, right));
362        }
363        [first, rest @ ..] => {
364            let last = rest.last().copied().unwrap_or(*first);
365            let all_same = rest.iter().all(|separator| separator == first);
366            let inner_are_thousands = groups.iter().skip(1).take(groups.len().saturating_sub(2)).all(|g| g.len() == 3);
367            if all_same && groups.iter().skip(1).all(|group| group.len() == 3) {
368                // `1.234.567`
369                readings.extend(whole(groups.concat()));
370            } else if !all_same
371                && last != *first
372                && inner_are_thousands
373                && rest.iter().rev().skip(1).all(|s| s == first)
374            {
375                // `1.234,56` and `1,234.56`: the last separator is the decimal one.
376                let (Some(fraction), Some(head)) = (groups.last(), groups.get(..groups.len() - 1)) else {
377                    return readings;
378                };
379                readings.extend(decimal(&head.concat(), fraction));
380            }
381        }
382    }
383    readings
384}
385
386/// The sentence of `text` around byte offset `at`, trimmed.
387pub(super) fn sentence_at(text: &str, at: usize) -> String {
388    let (start, end) = sentence_span(text, at);
389    text.get(start..end).unwrap_or_default().trim().to_owned()
390}
391
392/// The byte span of the sentence of `text` around byte offset `at`: from the end of the
393/// sentence before it to the end of its own. A `.` between digits ends nothing.
394pub(super) fn sentence_span(text: &str, at: usize) -> (usize, usize) {
395    let ends_a_sentence = |index: usize, c: char| {
396        matches!(c, '.' | '!' | '?' | '\n')
397            && text
398                .get(index + c.len_utf8()..)
399                .is_none_or(|rest| rest.is_empty() || rest.starts_with(char::is_whitespace))
400    };
401    let start = text
402        .char_indices()
403        .rfind(|(index, c)| *index < at && ends_a_sentence(*index, *c))
404        .map_or(0, |(index, c)| index + c.len_utf8());
405    let end = text
406        .char_indices()
407        .find(|(index, c)| *index >= at && ends_a_sentence(*index, *c))
408        .map_or(text.len(), |(index, c)| index + c.len_utf8());
409    (start, end)
410}
411
412#[cfg(test)]
413#[allow(clippy::unwrap_used, clippy::indexing_slicing)]
414mod tests {
415    use super::*;
416
417    fn rules() -> NumberRules {
418        NumberRules { tolerance: Tolerance::Rounding, ratios_as_percent: true }
419    }
420
421    fn unsupported(facts: &[&str], text: &str, rules: NumberRules) -> Vec<String> {
422        let mut known = Figures::new();
423        facts.iter().for_each(|fact| known.add_text(fact));
424        known.unsupported(text, rules).into_iter().map(|u| u.number).collect()
425    }
426
427    #[test]
428    fn a_rounded_number_matches_its_fact() {
429        let facts = ["revenue 1234567, growth 13.19, margin 12.6"];
430        assert!(unsupported(&facts, "Revenue was 1.2 million, up 13.2, margin 13.", rules()).is_empty());
431        assert!(unsupported(&facts, "Revenue reached 1,234,567 (13,19 growth).", rules()).is_empty());
432        // More precise than the facts, or another figure.
433        assert_eq!(unsupported(&facts, "Growth was 13.21 and 14.", rules()), ["13.21", "14"]);
434        let exact = NumberRules { tolerance: Tolerance::Exact, ratios_as_percent: false };
435        assert_eq!(unsupported(&facts, "Growth was 13.2, margin 12.6.", exact), ["13.2"]);
436    }
437
438    #[test]
439    fn percentages_match_ratios() {
440        let mut known = Figures::new();
441        known.add_json(&serde_json::json!({"conversion": 0.1319, "share": "45%", "orders": 1520}));
442        let rules = rules();
443        let found = |text: &str| known.unsupported(text, rules).into_iter().map(|u| u.number).collect::<Vec<_>>();
444        assert!(found("Conversion rose to 13.2% on 1,520 orders.").is_empty());
445        assert!(found("Konversi 13,19 persen, pangsa 0,45.").is_empty());
446        assert_eq!(found("Conversion was 14%."), ["14%"]);
447        let plain = NumberRules { tolerance: Tolerance::Rounding, ratios_as_percent: false };
448        assert_eq!(known.unsupported("Conversion was 13.2%.", plain).len(), 1);
449        // A JSON fact is the number it is: 1.234 is not a thousand.
450        let mut json = Figures::new();
451        json.add_json(&serde_json::json!(1.234));
452        assert_eq!(json.unsupported("It was 1234.", rules).len(), 1);
453        assert!(json.unsupported("It was 1,23.", rules).is_empty());
454    }
455
456    #[test]
457    fn multipliers_and_notations() {
458        let facts = ["sales 15000, budget 2500000, total 3100000000"];
459        assert!(
460            unsupported(&facts, "Sales were 15k (Rp15 ribu), budget 2,5 jt, total 3,1 miliar.", rules()).is_empty()
461        );
462        assert!(unsupported(&facts, "Budget: 2.5 million. Sales: 15.000 (US$15k).", rules()).is_empty());
463        // `m` is a metre as often as a million: a word, not a multiplier.
464        assert_eq!(unsupported(&facts, "The shelf is 4 m.", rules()), ["4"]);
465        assert_eq!(unsupported(&facts, "Sales were 16k.", rules()), ["16k"]);
466    }
467
468    #[test]
469    fn words_names_and_signs_are_not_figures() {
470        let facts = ["down 5.4"];
471        assert!(unsupported(&facts, "In Q3 the 2 stores of H1 fell 5.4%.", NumberRules::default()).is_empty());
472        assert!(unsupported(&facts, "It fell -5.4.", rules()).is_empty());
473        assert_eq!(unsupported(&facts, "3 stores fell.", rules()), ["3"]);
474    }
475
476    #[test]
477    fn the_sentence_of_each_number_is_reported() {
478        let mut known = Figures::new();
479        known.add_text("10");
480        let found = known.unsupported("Orders grew 12.5% to 10. That beat the plan of 9.", rules());
481        assert_eq!(found.len(), 2);
482        assert_eq!(found[0].number, "12.5%");
483        assert_eq!(found[0].sentence, "Orders grew 12.5% to 10.");
484        assert_eq!(found[1].sentence, "That beat the plan of 9.");
485    }
486}