Skip to content

ontocast.tool.facts_validation.grounding

Whether a value says what its text says.

A value (an instance of a value class, blank or named) states numbers and names individuals (:func:~ontocast.tool.facts_validation.statements.value_components). Two checks read it against the content unit's text:

  • each number is grounded: the text writes it in digits (:func:~ontocast.util.numeric_inventory.stated_numbers), or in number words within a label of the value that the text writes verbatim, up to case and spacing (:func:~ontocast.util.numeric_inventory.worded_numbers), as written or rescaled by a power of ten (:func:~ontocast.util.numeric_inventory.grounds). A label the text does not write grounds nothing, since the model wrote it. A fraction, a converted value, or a conventional value for a vague phrase is not stated;
  • each individual whose property's range is a closed class agrees with the catalog's cues written next to the value's numbers -- in the value's label when it writes the number, the value's own mention, else in the text: the skos:altLabel, notation and symbol literals of that class's individuals (:func:~ontocast.util.numeric_inventory.cue_index). A cue of another individual, and none of its own, contradicts it, when the individual has cues of its own in the catalog.

Both act only on value nodes: a graph without values gets no finding, and a catalog without cues gives no contradiction.

Attributes

__all__ = ['node_key', 'node_name', 'node_of', 'value_grounding_findings', 'value_nodes'] module-attribute

Classes

Functions:

node_key(node)

How a finding names node: its IRI, or _: and a blank node's id.

Source code in ontocast/tool/facts_validation/grounding.py
def node_key(node: Node) -> str:
    """How a finding names ``node``: its IRI, or ``_:`` and a blank node's id."""
    return f"_:{node}" if isinstance(node, BNode) else str(node)

node_name(graph, node)

How a message names node: its IRI, or a blank value by its carrier.

A blank node's id differs from run to run, so a value is named by the first carrier and property that point at it, in IRI order, up to the first named carrier.

Source code in ontocast/tool/facts_validation/grounding.py
def node_name(graph: Graph, node: Node) -> str:
    """How a message names ``node``: its IRI, or a blank value by its carrier.

    A blank node's id differs from run to run, so a value is named by the
    first carrier and property that point at it, in IRI order, up to the
    first named carrier.
    """
    path: list[str] = []
    seen: set[Node] = set()
    while isinstance(node, BNode) and node not in seen:
        seen.add(node)
        carriers = sorted(
            (
                (carrier, predicate)
                for carrier, predicate in graph.subject_predicates(node)
                if carrier not in seen
            ),
            key=lambda pair: (isinstance(pair[0], BNode), str(pair[0]), str(pair[1])),
        )
        if not carriers:
            return "a blank value node" + "".join(reversed(path))
        node, predicate = carriers[0]
        path.append(f" on <{predicate}>")
    if isinstance(node, BNode):
        return "a blank value node" + "".join(reversed(path))
    if not path:
        return f"<{node}>"
    return f"the value of <{node}>" + "".join(reversed(path))

node_of(key)

The node :func:node_key named.

Source code in ontocast/tool/facts_validation/grounding.py
def node_of(key: str) -> Node:
    """The node :func:`node_key` named."""
    return BNode(key[2:]) if key.startswith("_:") else URIRef(key)

value_grounding_findings(scope, contract, text, ontology_graph)

Ungrounded numbers and contradicted individuals of the values in scope.

ungrounded_number: a number of a value that text writes neither in digits nor in the number words of a label of the value that text writes verbatim ("five constituencies"), as written or rescaled by a power of ten (1e3 is grounded by "1000", 0.05 by "5%"). Its subject is the value (:func:node_key), predicate and value the number's property and lexical form.

contradicted_individual: an individual of a value, on a property whose range is a closed class, when a cue of another individual of that class, and none of its own, is written next to one of the value's numbers: in the value's label when the label writes the number, else in the text, and the individual has cues of its own. Its value is the individual, its suggestions the individuals the cue names. No individual is ever proposed for a value that names none.

Needs the unit's text: with none, nothing is judged.

Parameters:

Name Type Description Default
scope FactScope

The unit's fact scope.

required
contract StatementContract

The catalog's statement contract (value classes, closed ranges).

required
text str

The content unit's text.

required
ontology_graph Graph | None

The unit's ontology context, where cues are read.

required

Returns:

Type Description
list[FactsUnitFinding]

Mandatory findings, ordered by value then property.

Source code in ontocast/tool/facts_validation/grounding.py
def value_grounding_findings(
    scope: FactScope,
    contract: StatementContract,
    text: str,
    ontology_graph: Graph | None,
) -> list[FactsUnitFinding]:
    """Ungrounded numbers and contradicted individuals of the values in ``scope``.

    ``ungrounded_number``: a number of a value that ``text`` writes neither in
    digits nor in the number words of a label of the value that ``text``
    writes verbatim ("five constituencies"), as written or rescaled by a power
    of ten (``1e3`` is grounded by "1000", ``0.05`` by "5%"). Its
    ``subject`` is the value (:func:`node_key`), ``predicate`` and ``value``
    the number's property and lexical form.

    ``contradicted_individual``: an individual of a value, on a property whose
    range is a closed class, when a cue of another individual of that class,
    and none of its own, is written next to one of the value's numbers: in
    the value's label when the label writes the number, else in the text,
    and the individual has cues of its own. Its ``value`` is the individual,
    its suggestions the individuals the cue names. No individual is ever
    proposed for a value that names none.

    Needs the unit's ``text``: with none, nothing is judged.

    Args:
        scope: The unit's fact scope.
        contract: The catalog's statement contract (value classes, closed
            ranges).
        text: The content unit's text.
        ontology_graph: The unit's ontology context, where cues are read.

    Returns:
        Mandatory findings, ordered by value then property.
    """
    if not text.strip():
        return []
    graph = scope.graph
    text_spans = stated_number_spans(text)
    text_numbers = {value for value, _, _ in text_spans}
    findings: list[FactsUnitFinding] = []
    for node in value_nodes(scope, contract):
        components = value_components(graph, node, contract)
        if not components.numbers:
            continue
        label = _label_text(graph, node)
        label_spans = stated_number_spans(label)
        stated = text_numbers.union(
            *(worded_numbers(mention) for mention in _mentions(graph, node, text))
        )
        name = node_name(graph, node)
        magnitudes: set[str] = set()
        for number in components.numbers:
            magnitude = (number.number or "").lstrip("-")
            magnitudes.add(magnitude)
            if magnitude in stated or grounds(magnitude, stated):
                continue
            findings.append(
                FactsUnitFinding(
                    kind=FactsUnitFindingKind.UNGROUNDED_NUMBER,
                    message=(
                        f"{name} records {number.value} on <{number.predicate}>, "
                        "a number the text does not state. Record only a number "
                        "the text writes in digits, or in words that the value's "
                        "label quotes exactly as the text writes them."
                    ),
                    subject=node_key(node),
                    predicate=number.predicate,
                    value=str(number.value),
                )
            )
        for individual in components.individuals:
            if not individual.closed_range:
                continue
            cues = cue_index(ontology_graph, individual.closed_range)
            if not cues:
                continue
            # The label is the value's own mention when it writes the number;
            # elsewhere in the text the same number may belong to another one.
            in_label = [(s, e) for value, s, e in label_spans if value in magnitudes]
            adjacent = (
                _adjacent_cues(label, in_label, tuple(cues))
                if in_label
                else _adjacent_cues(
                    text,
                    [(s, e) for value, s, e in text_spans if value in magnitudes],
                    tuple(cues),
                )
            )
            carried = str(individual.value)
            if not adjacent or any(carried in cues[cue] for cue in adjacent):
                continue
            # An individual the catalog gives no cue can be named by none.
            if not any(carried in iris for iris in cues.values()):
                continue
            named = sorted({iri for cue in adjacent for iri in cues[cue]})
            written = ", ".join(f"'{cue}'" for cue in sorted(adjacent))
            findings.append(
                FactsUnitFinding(
                    kind=FactsUnitFindingKind.CONTRADICTED_INDIVIDUAL,
                    message=(
                        f"{name} names <{carried}> on <{individual.predicate}>, "
                        f"but the text writes {written} next to its number, "
                        "which the catalog declares for "
                        + ", ".join(f"<{iri}>" for iri in named)
                        + ". Name the individual the text's cue declares, or "
                        "none."
                    ),
                    subject=node_key(node),
                    predicate=individual.predicate,
                    value=carried,
                    suggestions=named,
                )
            )
    return findings

value_nodes(scope, contract)

The fact nodes typed with a value class, blank or named, in a stable order.

Source code in ontocast/tool/facts_validation/grounding.py
def value_nodes(scope: FactScope, contract: StatementContract) -> list[Node]:
    """The fact nodes typed with a value class, blank or named, in a stable order."""
    if not contract.value_classes:
        return []
    found = {
        node
        for node, cls in scope.graph.subject_objects(RDF.type)
        if str(cls) in contract.value_classes and scope.holds(node)
    }
    return sorted(found, key=lambda node: (isinstance(node, BNode), str(node)))