Skip to content

ontocast.tool.facts_validation.unit_findings

Deterministic per-unit findings on a rendered facts graph.

Only unresolved, machine-verified issues go back to the LLM, as MANDATORY fix instructions that must be resolved by rewriting — never by deleting the statement.

Attributes

CoverageMode = TypingLiteral['off', 'measurements', 'all'] module-attribute

logger = logging.getLogger(__name__) module-attribute

Classes

Functions:

collect_unit_findings(*, graph, ontology_graph, quarantined, extraction_text, fact_namespaces, coverage_limit=30, coverage_mandatory='off', policy=None, is_citation_metadata=False, is_non_content=False, subject_contract=None, full_catalog_terms=None)

Assemble all deterministic findings for one rendered unit graph.

Mandatory: quarantined literals (with closed-range individual suggestions), forbidden-namespace terms (example.org), doc-namespace predicates, unresolved catalog near-misses, predicates asserted on a subject whose type contradicts their rdfs:domain, statements and values that name no subject (subject_contract), instances with no concrete type, and value nodes whose only numeric content sits in a label. Advisory by default: numeric mentions of the source text absent from the graph, as two findings -- measurements (a number with its unit, in text order with context) and bare numbers -- whose mandatory flag coverage_mandatory sets (off | measurements | all; the booleans are off/all).

The policy's exempt terms (the sanctioned fallback vocabulary the facts prompt itself names, plus code predicates) never raise UNKNOWN_TERM: flagging the vocabulary the prompt recommends produced mandatory findings that repair renders obeyed by deleting correct data.

A citation-metadata unit is rendered with the bibliographic vocabulary and told to keep away from the domain ontology, so its catalog share is zero by instruction; DOMAIN_ADHERENCE is not judged there, nor on a non-content unit (front matter, author notes, identifiers), which has no domain facts for the catalog to describe.

full_catalog_terms is the whole catalog's inventory, as opposed to the unit's retrieved snapshot in ontology_graph. A term the snapshot did not retrieve is still a term, so it is never reported as unknown -- and, for a term that is genuinely unknown, replacement candidates are offered only under token containment, never on similarity alone.

Source code in ontocast/tool/facts_validation/unit_findings.py
def collect_unit_findings(
    *,
    graph: RDFGraph,
    ontology_graph: RDFGraph | None,
    quarantined: list[RejectedLiteralTriple],
    extraction_text: str,
    fact_namespaces: list[str],
    coverage_limit: int = 30,
    coverage_mandatory: str | bool = "off",
    policy: ValidationPolicy | None = None,
    is_citation_metadata: bool = False,
    is_non_content: bool = False,
    subject_contract: SubjectContract | None = None,
    full_catalog_terms: set[str] | None = None,
) -> list[FactsUnitFinding]:
    """Assemble all deterministic findings for one rendered unit graph.

    Mandatory: quarantined literals (with closed-range individual
    suggestions), forbidden-namespace terms (``example.org``), doc-namespace
    predicates, unresolved catalog near-misses, predicates asserted on a
    subject whose type contradicts their ``rdfs:domain``, statements and
    values that name no subject (``subject_contract``), instances with no
    concrete type, and value nodes whose only numeric content sits in a
    label. Advisory by default: numeric
    mentions of the source text absent from the graph, as two findings --
    measurements (a number with its unit, in text order with context) and
    bare numbers -- whose mandatory flag ``coverage_mandatory`` sets
    (``off`` | ``measurements`` | ``all``; the booleans are ``off``/``all``).

    The policy's exempt terms (the sanctioned fallback vocabulary the facts
    prompt itself names, plus code predicates) never raise UNKNOWN_TERM:
    flagging the vocabulary the prompt recommends produced mandatory findings
    that repair renders obeyed by deleting correct data.

    A citation-metadata unit is rendered with the bibliographic vocabulary
    and told to keep away from the domain ontology, so its catalog share is
    zero by instruction; ``DOMAIN_ADHERENCE`` is not judged there, nor on a
    non-content unit (front matter, author notes, identifiers), which has no
    domain facts for the catalog to describe.

    ``full_catalog_terms`` is the whole catalog's inventory, as opposed to
    the unit's retrieved snapshot in ``ontology_graph``. A term the snapshot
    did not retrieve is still a term, so it is never reported as unknown --
    and, for a term that is genuinely unknown, replacement candidates are
    offered only under token containment, never on similarity alone.
    """
    policy = policy or ValidationPolicy()
    known_terms = set(full_catalog_terms or ())
    findings: list[FactsUnitFinding] = []
    standard_namespaces = policy.standard_namespaces()
    # The vocabularies the catalog builds on: a namespace it declares terms
    # in, or borrows a term from (a superclass, a restricted property). A
    # strict vocabulary closes everything outside them; what the catalog
    # borrows it is no authority on, so a borrowed namespace stays open.
    catalog_namespaces = {
        _namespace_of(term)
        for term in (*known_terms, *collect_catalog_terms(ontology_graph))
    }
    fallback_terms = policy.exempt_terms(graph, ontology_graph)
    quantity_fallback_vocabulary = policy.quantity_fallback_vocabulary

    for rejected in quarantined:
        findings.append(
            FactsUnitFinding(
                kind=FactsUnitFindingKind.QUARANTINED_LITERAL,
                message=(
                    f"Triple excluded ({rejected.reason}): the object of "
                    f"<{rejected.predicate}> must be an IRI/valid literal, got "
                    f"'{rejected.object_lexical}'."
                ),
                subject=rejected.subject,
                predicate=rejected.predicate,
                value=rejected.object_lexical,
                suggestions=_closed_range_suggestions(rejected, ontology_graph),
            )
        )

    catalog_terms = collect_catalog_terms(ontology_graph)
    declared_namespaces = collect_declared_namespaces(ontology_graph)
    normalized_fact_namespaces = [ns for ns in fact_namespaces if ns]

    prefix_map = {
        prefix: str(namespace) for prefix, namespace in graph.namespaces() if prefix
    }
    flagged_terms: set[str] = set()
    for subject, predicate, obj in graph:
        if predicate == RDF.type and isinstance(obj, Literal):
            lexical = str(obj).strip()
            if lexical in flagged_terms:
                continue
            flagged_terms.add(lexical)
            resolved = _resolve_type_literal(lexical, prefix_map)
            findings.append(
                FactsUnitFinding(
                    kind=FactsUnitFindingKind.LITERAL_TYPE_OBJECT,
                    message=(
                        f"rdf:type object '{lexical}' is a string literal, not "
                        "an IRI; assert the type as a catalog class IRI "
                        "(`a prefix:Class`), never as a quoted string."
                    ),
                    subject=str(subject),
                    value=lexical,
                    suggestions=[resolved]
                    if resolved and resolved in catalog_terms
                    else [],
                )
            )
            continue
        for position, term in (("predicate", predicate), ("type", obj)):
            if not isinstance(term, URIRef):
                continue
            if position == "type" and predicate != RDF.type:
                continue
            text = str(term)
            if text in flagged_terms:
                continue
            verdict = term_verdict(
                text,
                catalog_terms=catalog_terms,
                known_terms=known_terms,
                fallback_terms=fallback_terms,
                declared_namespaces=declared_namespaces,
                catalog_namespaces=catalog_namespaces,
                standard_namespaces=standard_namespaces,
                vocabulary=policy.vocabulary,
            )
            if (
                verdict is not None
                and verdict.kind is TermVerdictKind.PLACEHOLDER_NAMESPACE
            ):
                flagged_terms.add(text)
                findings.append(
                    FactsUnitFinding(
                        kind=FactsUnitFindingKind.UNKNOWN_TERM,
                        message=(
                            f"<{text}> uses the example.org placeholder namespace; "
                            "replace it with a catalog term or express the "
                            "statement with catalog/standard vocabulary."
                        ),
                        predicate=text,
                        suggestions=_containment_qualified(
                            term,
                            _alias_candidates(
                                term,
                                graph,
                                catalog_terms,
                                ontology_graph=ontology_graph,
                                position=position,
                            ),
                        )
                        if catalog_terms
                        else [],
                    )
                )
                continue
            if any(text.startswith(ns) for ns in normalized_fact_namespaces):
                flagged_terms.add(text)
                role_message = (
                    f"Predicate <{text}> is minted in the facts/document "
                    "namespace; facts namespaces hold instances only — "
                    "use a catalog or standard-vocabulary property."
                    if position == "predicate"
                    else f"rdf:type object <{text}> is a class minted in the "
                    "facts/document namespace; facts namespaces hold instances, "
                    "not classes — type the instance with a catalog or "
                    "standard-vocabulary class."
                )
                findings.append(
                    FactsUnitFinding(
                        kind=FactsUnitFindingKind.UNKNOWN_TERM,
                        message=role_message,
                        predicate=text,
                        suggestions=_containment_qualified(
                            term,
                            _alias_candidates(
                                term,
                                graph,
                                catalog_terms,
                                ontology_graph=ontology_graph,
                                position=position,
                            ),
                        )
                        if catalog_terms
                        else [],
                    )
                )
                continue
            if verdict is None:
                continue
            namespace = _namespace_of(text)
            if verdict.kind is TermVerdictKind.WELL_KNOWN_MISSING:
                # Written from memory: the prompt names the vocabulary, not
                # its terms, so a plausible term it does not have is caught
                # here, with near-misses from the vocabulary itself.
                flagged_terms.add(text)
                findings.append(
                    FactsUnitFinding(
                        kind=FactsUnitFindingKind.UNKNOWN_TERM,
                        message=(
                            f"<{text}> is not a term of {verdict.vocabulary_title}; "
                            "rewrite the statement IN PLACE with a term that "
                            "exists in it (or a suggested candidate), or with a "
                            "term from the ontology chapter, keeping the "
                            "statement and its value."
                        ),
                        predicate=text,
                        suggestions=_containment_qualified(
                            term,
                            _alias_candidates(
                                term,
                                graph,
                                well_known_terms(namespace),
                                position=position,
                            ),
                        ),
                    )
                )
                continue
            if verdict.kind is TermVerdictKind.CLOSED_NAMESPACE_MISSING:
                # A member of a closed namespace: a near-miss of a real term.
                message = (
                    f"<{text}> does not exist in its ontology; rewrite "
                    "the term IN PLACE to the closest correct term from "
                    "the ontology chapter (or a suggested candidate), "
                    "keeping the statement and its value. Do NOT delete "
                    "the statement."
                )
            else:
                # A vocabulary that is neither the catalog's, one it borrows
                # from, nor well-known. The strict vocabulary admits nothing
                # else, so the statement is re-expressed or left out.
                message = (
                    f"<{text}> is not a term of the ontology nor of a "
                    "well-known vocabulary, and the vocabulary is strict: "
                    "rewrite the statement with a term from the ontology "
                    "chapter or a well-known vocabulary, or leave the "
                    "statement out if none can express it."
                )
            flagged_terms.add(text)
            findings.append(
                FactsUnitFinding(
                    kind=FactsUnitFindingKind.UNKNOWN_TERM,
                    message=message,
                    predicate=text,
                    suggestions=_containment_qualified(
                        term,
                        _alias_candidates(
                            term,
                            graph,
                            catalog_terms,
                            ontology_graph=ontology_graph,
                            position=position,
                        ),
                    ),
                )
            )

    findings.extend(
        _unit_outside_context_findings(
            graph, ontology_graph, catalog_terms | known_terms, policy
        )
    )
    findings.extend(
        _scalar_as_bounds_findings(graph, ontology_graph, normalized_fact_namespaces)
    )
    findings.extend(
        _unit_symbol_case_findings(
            graph,
            ontology_graph,
            extraction_text,
            normalized_fact_namespaces,
            policy,
        )
    )
    findings.extend(domain_violation_findings(graph, ontology_graph))
    findings.extend(
        untyped_instance_findings(graph, ontology_graph, normalized_fact_namespaces)
    )
    if not is_citation_metadata and not is_non_content:
        findings.extend(
            statement_without_subject_findings(
                graph, normalized_fact_namespaces, subject_contract
            )
        )
        findings.extend(
            _domain_adherence_findings(
                graph,
                catalog_terms,
                normalized_fact_namespaces,
                policy.domain_adherence_min_share,
                min_terms=policy.domain_adherence_min_terms,
            )
        )
    findings.extend(
        _label_only_number_findings(
            graph,
            unit_properties=expand_vocabulary_terms(
                _vocabulary_role_subset(quantity_fallback_vocabulary, "unit"),
                graph,
                ontology_graph,
            ),
            numeric_value_properties=expand_vocabulary_terms(
                _vocabulary_role_subset(quantity_fallback_vocabulary, "numeric_value"),
                graph,
                ontology_graph,
            ),
            fact_namespaces=normalized_fact_namespaces,
        )
    )

    if coverage_limit > 0:
        findings.extend(
            _numeric_coverage_findings(
                unit_numeric_inventory(
                    graph=graph,
                    ontology_graph=ontology_graph,
                    extraction_text=extraction_text,
                    policy=policy,
                    limit=coverage_limit,
                ),
                coverage_mode(coverage_mandatory),
            )
        )

    return findings

coverage_mode(value)

Normalise the coverage-mandatory knob, boolean form included.

True is the setting's old spelling of all and False of off; anything unrecognised is off, the advisory default.

Source code in ontocast/tool/facts_validation/unit_findings.py
def coverage_mode(value: str | bool | None) -> CoverageMode:
    """Normalise the coverage-mandatory knob, boolean form included.

    ``True`` is the setting's old spelling of ``all`` and ``False`` of
    ``off``; anything unrecognised is ``off``, the advisory default.
    """
    if isinstance(value, bool):
        return "all" if value else "off"
    if isinstance(value, str):
        lowered = value.strip().lower()
        if lowered == "measurements":
            return "measurements"
        if lowered in ("all", "true", "1", "yes", "on"):
            return "all"
    return "off"

domain_violation_findings(graph, ontology_graph)

Report subjects whose asserted type contradicts a predicate's rdfs:domain.

Only rdfs:domain entails, so only it can be contradicted: classes a schema:domainIncludes lists are expected ones, which later uses may widen. An untyped subject is never a violation -- the parse-time repair types it from the domain, and a subject still untyped is UNTYPED_INSTANCE's to report. It becomes one when the subject carries an asserted type unrelated to every domain class: inference would add the domain class on top of an incompatible one.

Conservative by construction, since a false accusation costs a repair. A subject is reported only when it has at least one asserted type and every asserted type is unrelated to every declared domain class -- neither a subtype nor a supertype of it, following rdfs:subClassOf and owl:equivalentClass intersections in both directions. Typing a subject with a supertype of the domain (sosa:Observation where the domain is ex:Measurement) is consistent and not reported.

Parameters:

Name Type Description Default
graph RDFGraph

Rendered facts graph for one unit.

required
ontology_graph RDFGraph | None

Ontology context the renderer was given.

required

Returns:

Name Type Description
list list[FactsUnitFinding]

One mandatory finding per offending (subject, predicate) pair,

list[FactsUnitFinding]

ordered by subject then predicate.

Source code in ontocast/tool/facts_validation/unit_findings.py
def domain_violation_findings(
    graph: RDFGraph,
    ontology_graph: RDFGraph | None,
) -> list[FactsUnitFinding]:
    """Report subjects whose asserted type contradicts a predicate's ``rdfs:domain``.

    Only ``rdfs:domain`` entails, so only it can be contradicted: classes a
    ``schema:domainIncludes`` lists are expected ones, which later uses may
    widen. An untyped subject is never a violation -- the parse-time repair
    types it from the domain, and a subject still untyped is
    ``UNTYPED_INSTANCE``'s to report. It becomes one when the subject carries
    an asserted type unrelated to every domain class: inference would add the
    domain class on top of an incompatible one.

    Conservative by construction, since a false accusation costs a repair.
    A subject is reported only when it has at least one asserted type and every
    asserted type is *unrelated* to every declared domain class -- neither a
    subtype nor a supertype of it, following ``rdfs:subClassOf`` and
    ``owl:equivalentClass`` intersections in both directions. Typing a subject
    with a supertype of the domain (``sosa:Observation`` where the domain is
    ``ex:Measurement``) is consistent and not reported.

    Args:
        graph: Rendered facts graph for one unit.
        ontology_graph: Ontology context the renderer was given.

    Returns:
        list: One mandatory finding per offending (subject, predicate) pair,
        ordered by subject then predicate.
    """
    if ontology_graph is None or not len(ontology_graph):
        return []
    domains = _declared_domains(ontology_graph, source="rdfs")
    if not domains:
        return []
    described = _described_classes(ontology_graph)

    closures: dict[URIRef, set[URIRef]] = {}
    findings: list[FactsUnitFinding] = []
    reported: set[tuple[str, str]] = set()

    for subject, predicate, _ in sorted(graph, key=lambda t: (str(t[0]), str(t[1]))):
        declared = domains.get(predicate)
        if declared is None or not isinstance(subject, URIRef):
            continue
        asserted = {
            value
            for value in graph.objects(subject, RDF.type)
            if isinstance(value, URIRef)
        }
        # Only types and domains the context places in a hierarchy can be
        # argued about: an undecidable pair is not reported.
        fits = types_compatible(
            asserted, declared, ontology_graph, described=described, closures=closures
        )
        if fits is not False:
            continue
        declared = {value for value in declared if value in described}
        key = (str(subject), str(predicate))
        if key in reported:
            continue
        reported.add(key)
        expected = ", ".join(f"<{value}>" for value in sorted(declared, key=str))
        actual = ", ".join(f"<{value}>" for value in sorted(asserted, key=str))
        findings.append(
            FactsUnitFinding(
                kind=FactsUnitFindingKind.DOMAIN_VIOLATION,
                message=(
                    f"<{subject}> is typed {actual} but carries <{predicate}>, "
                    f"whose rdfs:domain is {expected}. Either type the subject "
                    "as a class of the domain, or use the property that fits "
                    "the type it has."
                ),
                subject=str(subject),
                predicate=str(predicate),
                suggestions=sorted(str(value) for value in declared),
            )
        )
    return findings

domain_vocabulary_share(graph, catalog_terms, fact_namespaces)

Count distinct schema terms drawn from the catalog, and the total.

Schema position only -- predicates and rdf:type objects. Instances in the fact namespaces are excluded (they are supposed to be minted, not looked up), and so are the RDF/RDFS/OWL/XSD/SKOS/DC/PROV plumbing namespaces, which every graph uses regardless of which catalog it was given and would otherwise float the ratio for free. Generic content vocabularies such as schema.org deliberately stay in the denominator: reaching for them instead of the catalog is exactly what this measures.

Parameters:

Name Type Description Default
graph RDFGraph

The rendered unit graph.

required
catalog_terms set[str]

Terms declared by the unit's ontology context.

required
fact_namespaces Sequence[str]

Namespaces holding minted instances.

required

Returns:

Type Description
tuple[int, int]

tuple[int, int]: (from_catalog, total) over distinct terms.

Source code in ontocast/tool/facts_validation/unit_findings.py
def domain_vocabulary_share(
    graph: RDFGraph,
    catalog_terms: set[str],
    fact_namespaces: Sequence[str],
) -> tuple[int, int]:
    """Count distinct schema terms drawn from the catalog, and the total.

    Schema position only -- predicates and ``rdf:type`` objects. Instances in
    the fact namespaces are excluded (they are supposed to be minted, not
    looked up), and so are the RDF/RDFS/OWL/XSD/SKOS/DC/PROV plumbing
    namespaces, which every graph uses regardless of which catalog it was
    given and would otherwise float the ratio for free. Generic *content*
    vocabularies such as schema.org deliberately stay in the denominator:
    reaching for them instead of the catalog is exactly what this measures.

    Args:
        graph: The rendered unit graph.
        catalog_terms: Terms declared by the unit's ontology context.
        fact_namespaces: Namespaces holding minted instances.

    Returns:
        tuple[int, int]: ``(from_catalog, total)`` over distinct terms.
    """
    used: set[str] = set()
    from_catalog: set[str] = set()
    for _, predicate, obj in graph:
        candidates = [predicate]
        if predicate == RDF.type:
            candidates.append(obj)
        for term in candidates:
            if not isinstance(term, URIRef):
                continue
            text = str(term)
            if any(text.startswith(ns) for ns in fact_namespaces):
                continue
            if text.startswith(_STANDARD_NAMESPACES):
                continue
            used.add(text)
            if text in catalog_terms:
                from_catalog.add(text)
    return len(from_catalog), len(used)

statement_without_subject_findings(graph, fact_namespaces, contract, *, max_candidates=12)

Report every statement or value in the unit that names no subject.

An instance of a statement class (an observation) that states a value (:func:~ontocast.tool.facts_validation.connectivity.states_a_value) names its subject only through a subject property: a forward one from it, or an inverse one to it. A link to its observed property or its procedure is not that. An instance of a value class names its subject by being linked to any other instance, in either direction. An instance of another class stating its own values is a fact about itself and is not reported.

Parameters:

Name Type Description Default
graph RDFGraph

Rendered facts graph for one unit.

required
fact_namespaces Sequence[str]

Namespaces holding minted instances.

required
contract SubjectContract | None

The catalog's statement and value classes and subject properties; None reports nothing.

required
max_candidates int

Most candidate subjects suggested per finding.

12

Returns:

Name Type Description
list list[FactsUnitFinding]

One mandatory finding per such instance, ordered by IRI; its

list[FactsUnitFinding]

suggestions are the unit's instances that could be the subject.

Source code in ontocast/tool/facts_validation/unit_findings.py
def statement_without_subject_findings(
    graph: RDFGraph,
    fact_namespaces: Sequence[str],
    contract: SubjectContract | None,
    *,
    max_candidates: int = 12,
) -> list[FactsUnitFinding]:
    """Report every statement or value in the unit that names no subject.

    An instance of a statement class (an observation) that states a value
    (:func:`~ontocast.tool.facts_validation.connectivity.states_a_value`)
    names its subject only through a subject property: a ``forward`` one from
    it, or an ``inverse`` one to it. A link to its observed property or its
    procedure is not that. An instance of a value class names its subject by
    being linked to any other instance, in either direction. An instance of
    another class stating its own values is a fact about itself and is not
    reported.

    Args:
        graph: Rendered facts graph for one unit.
        fact_namespaces: Namespaces holding minted instances.
        contract: The catalog's statement and value classes and subject
            properties; ``None`` reports nothing.
        max_candidates: Most candidate subjects suggested per finding.

    Returns:
        list: One mandatory finding per such instance, ordered by IRI; its
        suggestions are the unit's instances that could be the subject.
    """
    if contract is None:
        return []
    statements = {URIRef(iri) for iri in contract.statement_classes}
    values = {URIRef(iri) for iri in contract.value_classes}
    forward = [URIRef(iri) for iri in contract.forward]
    inverse = [URIRef(iri) for iri in contract.inverse]
    scaffolding = scaffolding_nodes(graph)
    isolated = isolated_instances(graph, fact_namespaces)
    instances = sorted(
        (
            node
            for node in fact_instances(graph, fact_namespaces)
            if isinstance(node, URIRef)
        ),
        key=str,
    )

    def names_subject(node: URIRef) -> bool:
        return any((node, prop, None) in graph for prop in forward) or any(
            (None, prop, node) in graph for prop in inverse
        )

    lapsed: list[URIRef] = []
    for node in instances:
        types = set(graph.objects(node, RDF.type))
        if not types & (statements | values):
            continue
        if not states_a_value(graph, node, scaffolding):
            continue
        if types & statements:
            if not names_subject(node):
                lapsed.append(node)
        elif node in isolated:
            lapsed.append(node)
    if not lapsed:
        return []
    candidates = [
        str(node)
        for node in instances
        if not set(graph.objects(node, RDF.type)) & (statements | values)
    ][:max_candidates]
    return [
        FactsUnitFinding(
            kind=FactsUnitFindingKind.STATEMENT_WITHOUT_SUBJECT,
            message=(
                f"<{node}> states a value but names nothing it is about. Link "
                "it to the instance the text says was measured or described "
                "(its feature of interest, or the property the ontology gives "
                "for it), in the direction the property runs; mint that "
                "instance if the text names it and it is missing."
            ),
            subject=str(node),
            suggestions=candidates,
        )
        for node in lapsed
    ]

unit_numeric_inventory(*, graph, ontology_graph, extraction_text, policy=None, limit=30)

Numbers of the unit text absent from its graph, measurements first.

The unit surfaces come from the unit individuals of the ontology context (found through the configured unit-role property), so a catalog-specific unit counts as a measurement once the catalog declares it. Measurements are judged against structured (number, unit) pairs in the graph — a bare numeric literal does not clear a unit-adjacent mention. Shared by the coverage findings and the completion pass, which must agree on what is missing.

Source code in ontocast/tool/facts_validation/unit_findings.py
def unit_numeric_inventory(
    *,
    graph: RDFGraph,
    ontology_graph: RDFGraph | None,
    extraction_text: str,
    policy: ValidationPolicy | None = None,
    limit: int = 30,
) -> NumericInventory:
    """Numbers of the unit text absent from its graph, measurements first.

    The unit surfaces come from the unit individuals of the ontology context
    (found through the configured unit-role property), so a catalog-specific
    unit counts as a measurement once the catalog declares it. Measurements
    are judged against structured ``(number, unit)`` pairs in the graph —
    a bare numeric literal does not clear a unit-adjacent mention. Shared by
    the coverage findings and the completion pass, which must agree on what
    is missing.
    """
    policy = policy or ValidationPolicy()
    unit_properties = expand_vocabulary_terms(
        _vocabulary_role_subset(policy.quantity_fallback_vocabulary, "unit"),
        graph,
        ontology_graph,
    )
    return missing_numeric_inventory(
        extraction_text,
        graph,
        unit_surfaces=unit_surfaces_in_ontology(ontology_graph, unit_properties),
        ontology_graph=ontology_graph,
        unit_properties=unit_properties,
        ignore_identifier_fragments=policy.numeric_identifier_guard,
        limit=limit,
    )

untyped_instance_findings(graph, ontology_graph, fact_namespaces)

Report every instance of the graph that has no concrete type.

An instance is a fact-namespace IRI in subject or IRI-object position (:func:fact_instances); it is typed when one of its rdf:type objects is a class outside the fact namespaces that is neither a schema metaclass nor vacuous (:func:concrete_types). Suggested classes are the declared domain of every predicate the instance carries and the declared range of every predicate it is the object of (rdfs or schema:*Includes), then catalog classes whose name shares a token with the instance's label or local name.

Parameters:

Name Type Description Default
graph RDFGraph

Rendered facts graph for one unit.

required
ontology_graph RDFGraph | None

Ontology context the renderer was given.

required
fact_namespaces Sequence[str]

Namespaces holding minted instances.

required

Returns:

Name Type Description
list list[FactsUnitFinding]

One mandatory finding per untyped instance, ordered by IRI.

Source code in ontocast/tool/facts_validation/unit_findings.py
def untyped_instance_findings(
    graph: RDFGraph,
    ontology_graph: RDFGraph | None,
    fact_namespaces: Sequence[str],
) -> list[FactsUnitFinding]:
    """Report every instance of the graph that has no concrete type.

    An instance is a fact-namespace IRI in subject or IRI-object position
    (:func:`fact_instances`); it is typed when one of its ``rdf:type`` objects
    is a class outside the fact namespaces that is neither a schema metaclass
    nor vacuous (:func:`concrete_types`). Suggested classes are the declared
    domain of every predicate the instance carries and the declared range of
    every predicate it is the object of (``rdfs`` or ``schema:*Includes``), then catalog
    classes whose name shares a token with the instance's label or local
    name.

    Args:
        graph: Rendered facts graph for one unit.
        ontology_graph: Ontology context the renderer was given.
        fact_namespaces: Namespaces holding minted instances.

    Returns:
        list: One mandatory finding per untyped instance, ordered by IRI.
    """
    untyped = untyped_instances(graph, fact_namespaces)
    if not untyped:
        return []
    domains: dict[URIRef, set[URIRef]] = {}
    ranges: dict[URIRef, set[URIRef]] = {}
    known_classes: set[str] = set()
    if ontology_graph is not None and len(ontology_graph):
        domains = _declared_domains(ontology_graph)
        ranges = sides_by_property(ontology_graph, "range")
        _, known_classes = _catalog_term_roles(ontology_graph)
    findings: list[FactsUnitFinding] = []
    for instance in untyped:
        entailed: set[URIRef] = set()
        for predicate in graph.predicates(instance, None):
            if isinstance(predicate, URIRef):
                entailed |= domains.get(predicate, set())
        for predicate in graph.predicates(None, instance):
            if isinstance(predicate, URIRef):
                entailed |= ranges.get(predicate, set())
        suggestions = sorted(str(value) for value in entailed)
        suggestions.extend(
            candidate
            for candidate in _label_matched_classes(graph, instance, known_classes)
            if candidate not in suggestions
        )
        asserted = sorted(
            f"<{value}>"
            for value in graph.objects(instance, RDF.type)
            if isinstance(value, URIRef)
        )
        situation = (
            f"is typed only {', '.join(asserted)}, which names no concrete class"
            if asserted
            else "has no rdf:type"
        )
        findings.append(
            FactsUnitFinding(
                kind=FactsUnitFindingKind.UNTYPED_INSTANCE,
                message=(
                    f"<{instance}> {situation}. Type it with the class from the "
                    "ONTOLOGY section that fits what the text says it is, or, "
                    "only if none fits, with a specific class from a core "
                    "vocabulary such as schema.org. Not owl:Thing, not a "
                    "metaclass, not a class minted in the facts namespace. "
                    "Keep the instance and its statements."
                ),
                subject=str(instance),
                suggestions=suggestions,
            )
        )
    return findings