graphrt-core 0.10.0

Executor-agnostic graph runtime for agentic AI workflows: graph model, variable pool, scheduler, events, snapshots and built-in control nodes.
Documentation
//! The numbers of a text compared with the numbers of a reference text, such as a written
//! report section against the section it should match.
//!
//! Numbers are read and matched as the numbers check of a report reads them
//! ([`super::figures`]): notations (`1.234.567` = `1,234,567`, `13,19` = `13.19`), multipliers
//! (`15k`, `2 jt`, `1.5 million`), percentages, and `0`, `1` and `2` written alone as words.
//! Rounding works both ways here: two numbers match when either rounds to the other at the
//! precision it is written with, so `13.2%` matches `13.19%` and `13.19%` matches `13.2%`.
//! [`Tolerance::Exact`](super::figures::Tolerance::Exact) asks for the same value.
//!
//! Each number of the reference is matched at most once: a text that writes `120` twice
//! against a reference that writes it once has one `120` in both and one in the text only.

use super::figures::{NumberRules, distance, scan};

/// What [`compare_numbers`] found, each number as written and in the order it is written.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct NumberComparison {
    /// The numbers of the text that match a number of the reference, as the text writes them.
    pub both: Vec<String>,
    /// The numbers of the text the reference does not hold.
    pub text_only: Vec<String>,
    /// The numbers of the reference the text does not state, as the reference writes them.
    pub reference_only: Vec<String>,
}

impl NumberComparison {
    pub fn both_count(&self) -> usize {
        self.both.len()
    }

    pub fn text_only_count(&self) -> usize {
        self.text_only.len()
    }

    pub fn reference_only_count(&self) -> usize {
        self.reference_only.len()
    }

    /// How many numbers the reference writes.
    pub fn reference_count(&self) -> usize {
        self.both.len() + self.reference_only.len()
    }
}

/// Compares the numbers `text` writes with the numbers `reference` writes (see the module docs).
///
/// Each number of the text, in order, takes the closest number of the reference not taken yet
/// that it matches (the first of equally close ones).
pub fn compare_numbers(text: &str, reference: &str, rules: NumberRules) -> NumberComparison {
    let reference_numbers = scan(reference);
    let mut taken = vec![false; reference_numbers.len()];
    let mut comparison = NumberComparison::default();
    for number in scan(text) {
        let mut closest: Option<(usize, f64)> = None;
        for (index, candidate) in reference_numbers.iter().enumerate() {
            if taken.get(index).copied().unwrap_or(true) {
                continue;
            }
            if let Some(gap) = distance(&number, candidate, rules)
                && closest.is_none_or(|(_, best)| gap < best)
            {
                closest = Some((index, gap));
            }
        }
        match closest {
            Some((index, _)) => {
                if let Some(slot) = taken.get_mut(index) {
                    *slot = true;
                }
                comparison.both.push(number.text);
            }
            None => comparison.text_only.push(number.text),
        }
    }
    comparison.reference_only =
        reference_numbers.into_iter().zip(taken).filter(|(_, taken)| !taken).map(|(number, _)| number.text).collect();
    comparison
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::grounding::figures::Tolerance;

    fn compare(text: &str, reference: &str) -> NumberComparison {
        compare_numbers(text, reference, NumberRules::default())
    }

    fn strings(items: &[&str]) -> Vec<String> {
        items.iter().map(|item| (*item).to_owned()).collect()
    }

    #[test]
    fn rounding_matches_both_ways() {
        // The text rounds the reference, and the reference rounds the text.
        let rounded = compare("Revenue grew 13.2% to 1.2 million.", "Revenue grew 13.19% to 1,234,567.");
        assert_eq!(rounded.both, strings(&["13.2%", "1.2 million"]));
        assert!(rounded.text_only.is_empty() && rounded.reference_only.is_empty(), "{rounded:?}");
        let precise = compare("Revenue grew 13.19% to 1,234,567.", "Revenue grew 13.2% to 1.2 million.");
        assert_eq!(precise.both, strings(&["13.19%", "1,234,567"]));
        assert_eq!(precise.reference_only_count(), 0);
        // Too far apart at either precision.
        let off = compare("Margin was 13.4%.", "Margin was 13.2%.");
        assert_eq!(off.text_only, strings(&["13.4%"]));
        assert_eq!(off.reference_only, strings(&["13.2%"]));
        // Exact asks for the same value.
        let exact = compare_numbers(
            "Margin was 13.2%.",
            "Margin was 13.19%.",
            NumberRules { tolerance: Tolerance::Exact, ratios_as_percent: false },
        );
        assert_eq!((exact.both_count(), exact.text_only_count(), exact.reference_only_count()), (0, 1, 1));
    }

    #[test]
    fn percentages_and_ratios() {
        let plain = compare("Conversion was 13.2%.", "Conversion was 0.1319.");
        assert_eq!(plain.both_count(), 0);
        let rules = NumberRules { tolerance: Tolerance::Rounding, ratios_as_percent: true };
        let as_ratio = compare_numbers("Conversion was 13.2%.", "Conversion was 0.1319.", rules);
        assert_eq!(as_ratio.both, strings(&["13.2%"]));
        let as_percent = compare_numbers("Conversion was 0.13.", "Conversion was 13.19%.", rules);
        assert_eq!(as_percent.both, strings(&["0.13"]));
        let words = compare("Share 45 percent.", "Share 45%.");
        assert_eq!(words.both, strings(&["45%"]));
    }

    #[test]
    fn notations_and_multipliers() {
        let found = compare(
            "North sold 1.234.567 (Rp15 ribu per order), South 2,5 jt, margin 13,19.",
            "North 1,234,567, order value 15000, South 2500000, margin 13.19.",
        );
        assert_eq!(found.both, strings(&["1.234.567", "15 ribu", "2,5 jt", "13,19"]));
        assert!(found.text_only.is_empty() && found.reference_only.is_empty(), "{found:?}");
        // Small numbers written alone and names are not figures.
        let words = compare("In Q3 the 2 stores sold 120 orders.", "120 orders in 3 stores.");
        assert_eq!(words.both, strings(&["120"]));
        assert_eq!(words.reference_only, strings(&["3"]));
        assert!(words.text_only.is_empty());
    }

    #[test]
    fn each_reference_number_is_used_once() {
        let repeated = compare("North had 120 orders, South 120 and East 120.", "North 120, South 120.");
        assert_eq!(repeated.both, strings(&["120", "120"]));
        assert_eq!(repeated.text_only, strings(&["120"]));
        assert!(repeated.reference_only.is_empty());
        let missing = compare("North 120.", "North 120, South 120, East 95.");
        assert_eq!(missing.reference_only, strings(&["120", "95"]));
        assert_eq!(missing.reference_count(), 3);
        // The closest number is taken, so a rounded one does not take an exact one's match.
        let closest = compare("Revenue 13 and margin 12.6.", "Margin 12.6, revenue 13.");
        assert_eq!(closest.both, strings(&["13", "12.6"]));
        assert!(closest.reference_only.is_empty(), "{closest:?}");
    }

    #[test]
    fn empty_texts_have_no_numbers() {
        assert_eq!(compare("", ""), NumberComparison::default());
        let only_reference = compare("No figures here.", "Revenue 1,520.");
        assert_eq!(only_reference.reference_only, strings(&["1,520"]));
    }
}