Skip to content

ontocast.tool.facts_validation.literal_repair

LLM-free parse-time repairs on rendered facts graphs.

Every rewrite here either retypes a literal the schema grounds, resolves an unambiguous near-miss or code, or collapses a degenerate encoding — no repair invents a value.

Attributes

logger = logging.getLogger(__name__) module-attribute

Classes

Functions:

dedupe_literal_variants(graph, fact_namespaces=None)

Collapse duplicate literals differing only in language tag or datatype.

The renderer emits the same value inconsistently across chunks — "X"@en in one unit, "X"^^xsd:string in another, a plain "X" in a third — and after aggregation one (subject, predicate) carries all three as distinct RDF terms. One survives per lexical form: the language-tagged form (each distinct language kept — those are distinct assertions), else the plain form, else the xsd:string form. Reified provenance follows the survivor.

Parameters:

Name Type Description Default
graph RDFGraph

Aggregated facts graph, mutated in place.

required
fact_namespaces Sequence[str] | None

When set, only subjects under these namespaces are touched.

None

Returns:

Name Type Description
One list[GraphRepairRecord]
Source code in ontocast/tool/facts_validation/literal_repair.py
def dedupe_literal_variants(
    graph: RDFGraph,
    fact_namespaces: Sequence[str] | None = None,
) -> list[GraphRepairRecord]:
    """Collapse duplicate literals differing only in language tag or datatype.

    The renderer emits the same value inconsistently across chunks —
    ``"X"@en`` in one unit, ``"X"^^xsd:string`` in another, a plain ``"X"``
    in a third — and after aggregation one ``(subject, predicate)`` carries
    all three as distinct RDF terms. One survives per lexical form: the
    language-tagged form (each distinct language kept — those are distinct
    assertions), else the plain form, else the ``xsd:string`` form. Reified
    provenance follows the survivor.

    Args:
        graph: Aggregated facts graph, mutated in place.
        fact_namespaces: When set, only subjects under these namespaces are
            touched.

    Returns:
        One :class:`GraphRepairRecord` per removed literal variant.
    """
    from ontocast.onto.rdfgraph import retarget_reifiers
    from ontocast.tool.facts_validation.terms import _in_fact_scope

    namespaces = [ns for ns in (fact_namespaces or []) if ns]
    groups: dict[tuple[URIRef, URIRef, str], list[Literal]] = {}
    for subject, predicate, obj in graph:
        if not isinstance(subject, URIRef) or not isinstance(predicate, URIRef):
            continue
        if not isinstance(obj, Literal):
            continue
        if namespaces and not _in_fact_scope(subject, namespaces):
            continue
        groups.setdefault((subject, predicate, str(obj)), []).append(obj)

    records: list[GraphRepairRecord] = []
    replacements: dict[tuple[Node, Node, Node], tuple[Node, Node, Node]] = {}
    for (subject, predicate, _lexical), literals in sorted(
        groups.items(), key=lambda item: (str(item[0][0]), str(item[0][1]), item[0][2])
    ):
        if len(literals) < 2:
            continue
        tagged = sorted(
            (lit for lit in literals if lit.language is not None),
            key=lambda lit: str(lit.language),
        )
        plain = [
            lit for lit in literals if lit.language is None and lit.datatype is None
        ]
        typed = [
            lit
            for lit in literals
            if lit.language is None and lit.datatype == XSD.string
        ]
        if tagged:
            keep = tagged[0]
            drop = plain + typed
        elif plain:
            keep = plain[0]
            drop = typed
        else:
            # Distinct datatypes beyond xsd:string are not variants of one
            # value; leave them to the datatype-aware repairs.
            continue
        for variant in drop:
            graph.remove((subject, predicate, variant))
            replacements[(subject, predicate, variant)] = (subject, predicate, keep)
            records.append(
                GraphRepairRecord(
                    kind=FactsGateRepairKind.LITERAL_VARIANT_PRUNED,
                    source=f"{subject} {predicate} {variant.n3()}",
                    target=keep.n3(),
                )
            )
    if replacements:
        retarget_reifiers(graph, replacements)
        logger.info(
            "Collapsed %d literal variant(s) differing only in language tag "
            "or datatype",
            len(records),
        )
    return records

literal_ranges(ontology_graph, catalog_roles=None)

Each predicate with one declared retypable datatype range, with it.

Read from the unit's ontology_graph, the whole catalog (catalog_roles, memoised there with the well-known vocabularies' ranges) and the well-known vocabularies, so a property the unit's snapshot did not retrieve is still known. A predicate declared with two different datatypes anywhere is left out: no single value fits both. Ranges inherited through rdfs:subPropertyOf are not followed.

Source code in ontocast/tool/facts_validation/literal_repair.py
def literal_ranges(
    ontology_graph: RDFGraph | None, catalog_roles: CatalogRoles | None = None
) -> dict[URIRef, URIRef]:
    """Each predicate with one declared retypable datatype range, with it.

    Read from the unit's ``ontology_graph``, the whole catalog
    (``catalog_roles``, memoised there with the well-known vocabularies'
    ranges) and the well-known vocabularies, so a property the unit's snapshot
    did not retrieve is still known. A predicate declared with two different
    datatypes anywhere is left out: no single value fits both. Ranges
    inherited through ``rdfs:subPropertyOf`` are not followed.
    """
    roles = catalog_roles if catalog_roles is not None else CatalogRoles()
    declared = {prop: set(found) for prop, found in roles.declared_ranges().items()}
    if ontology_graph is not None:
        for predicate, range_iri in ontology_graph.subject_objects(RDFS.range):
            if (
                isinstance(predicate, URIRef)
                and isinstance(range_iri, URIRef)
                and str(range_iri).startswith(str(XSD))
            ):
                declared.setdefault(str(predicate), set()).add(str(range_iri))
    return {
        URIRef(predicate): URIRef(next(iter(datatypes)))
        for predicate, datatypes in declared.items()
        if len(datatypes) == 1
        and URIRef(next(iter(datatypes))) in _RETYPABLE_RANGE_DATATYPES
    }

materialize_entailed_types(graph, ontology_graph)

Assert the types the ontology context entails on the graph's nodes.

For every triple x p y: when the context declares p rdfs:domain D with D a named class, x a D is added; when it declares p rdfs:range R with R a named class and y an IRI, y a R is added. owl:Thing and the other vacuous classes are never asserted, nor is a type on a node the context itself types (a catalog individual).

A type is added only where it is consistent with what the node already asserts: when the node has no type, or when the entailed class specialises one of its asserted types. Nothing is added when the entailed class is already in the asserted types' superclass closure (redundant), or when every asserted type is unrelated to it -- that contradiction is the DOMAIN_VIOLATION finding's to report, and materialising the domain there would hide it.

An IRI still untyped after that takes the class a link lists through schema:domainIncludes / schema:rangeIncludes, when the property lists exactly one class and declares no rdfs counterpart, and all of the node's links agree on it. A listed class never joins an asserted type and never types a blank node.

Parameters:

Name Type Description Default
graph RDFGraph

Facts graph, repaired in place.

required
ontology_graph RDFGraph | None

Ontology context declaring domains and ranges.

required

Returns:

Type Description
tuple[int, list[GraphRepairRecord]]

Tuple of (number of added triples, applied-repair records).

Source code in ontocast/tool/facts_validation/literal_repair.py
def materialize_entailed_types(
    graph: RDFGraph, ontology_graph: RDFGraph | None
) -> tuple[int, list[GraphRepairRecord]]:
    """Assert the types the ontology context entails on the graph's nodes.

    For every triple ``x p y``: when the context declares ``p rdfs:domain D``
    with ``D`` a named class, ``x a D`` is added; when it declares
    ``p rdfs:range R`` with ``R`` a named class and ``y`` an IRI, ``y a R``
    is added. ``owl:Thing`` and the other vacuous classes are never asserted,
    nor is a type on a node the context itself types (a catalog individual).

    A type is added only where it is consistent with what the node already
    asserts: when the node has no type, or when the entailed class
    specialises one of its asserted types. Nothing is added when the entailed
    class is already in the asserted types' superclass closure (redundant),
    or when every asserted type is unrelated to it -- that contradiction is
    the ``DOMAIN_VIOLATION`` finding's to report, and materialising the
    domain there would hide it.

    An IRI still untyped after that takes the class a link lists through
    ``schema:domainIncludes`` / ``schema:rangeIncludes``, when the property
    lists exactly one class and declares no ``rdfs`` counterpart, and all of
    the node's links agree on it. A listed class never joins an asserted type
    and never types a blank node.

    Args:
        graph: Facts graph, repaired in place.
        ontology_graph: Ontology context declaring domains and ranges.

    Returns:
        Tuple of (number of added triples, applied-repair records).
    """
    if ontology_graph is None or not len(ontology_graph):
        return 0, []
    # Only an rdfs side entails; a listed side types a node only when it
    # names one class (below).
    domains = _declared_domains(ontology_graph, source="rdfs")
    ranges = declared_class_ranges(ontology_graph, source="rdfs")
    listed_domains = sole_listed_classes(ontology_graph, "domain", domains)
    listed_ranges = sole_listed_classes(ontology_graph, "range", ranges)
    if not (domains or ranges or listed_domains or listed_ranges):
        return 0, []

    closures: dict[URIRef, set[URIRef]] = {}

    def closure(class_iri: URIRef) -> set[URIRef]:
        if class_iri not in closures:
            closures[class_iri] = superclass_closure(class_iri, ontology_graph)
        return closures[class_iri]

    def admissible(node: Node, entailed: URIRef) -> bool:
        if entailed in _VACUOUS_TYPES or not isinstance(node, (URIRef, BNode)):
            return False
        if (node, RDF.type, None) in ontology_graph:
            return False
        asserted = {
            value
            for value in graph.objects(node, RDF.type)
            if isinstance(value, URIRef) and value not in _VACUOUS_TYPES
        }
        if not asserted:
            return True
        if any(entailed in closure(value) for value in asserted):
            return False
        return any(value in closure(entailed) for value in asserted)

    additions: dict[tuple[Node, URIRef], URIRef] = {}
    for subject, predicate, obj in graph:
        if not isinstance(predicate, URIRef) or predicate == RDF.type:
            continue
        for entailed in domains.get(predicate, ()):
            if admissible(subject, entailed):
                additions.setdefault((subject, entailed), predicate)
        if not isinstance(obj, URIRef):
            continue
        for entailed in ranges.get(predicate, ()):
            if admissible(obj, entailed):
                additions.setdefault((obj, entailed), predicate)

    # A node still untyped takes the one class its links list, when they agree.
    listed: dict[URIRef, dict[URIRef, URIRef]] = {}
    entailed_nodes = {node for node, _ in additions}
    for subject, predicate, obj in graph:
        if not isinstance(predicate, URIRef):
            continue
        for node, table in ((subject, listed_domains), (obj, listed_ranges)):
            cls = table.get(predicate)
            if (
                cls is not None
                and isinstance(node, URIRef)
                and node not in entailed_nodes
                and admissible(node, cls)
                and not any(
                    value not in _VACUOUS_TYPES
                    for value in graph.objects(node, RDF.type)
                )
            ):
                classes = listed.setdefault(node, {})
                classes[cls] = min(classes.get(cls, predicate), predicate)
    for node, classes in listed.items():
        if len(classes) == 1:
            ((cls, predicate),) = classes.items()
            additions[(node, cls)] = predicate

    applied: list[GraphRepairRecord] = []
    for (node, entailed), predicate in sorted(
        additions.items(), key=lambda item: (str(item[0][0]), str(item[0][1]))
    ):
        if (node, RDF.type, entailed) in graph:
            continue
        graph.add((node, RDF.type, entailed))
        applied.append(
            GraphRepairRecord(
                kind=FactsUnitFindingKind.ENTAILED_TYPE,
                source=f"{node} {predicate}",
                target=str(entailed),
            )
        )
        logger.info("Materialised entailed type <%s> on <%s>", entailed, node)
    if applied:
        record_active_count("repair/entailed_type", len(applied))
    return len(applied), applied

normalize_literals_against_schema(graph, ontology_graph, catalog_roles=None)

Retype literals whose predicate declares a compatible datatype range.

Applies :func:schema_retypings to graph in place.

Returns:

Type Description
int

Number of retyped literals.

Source code in ontocast/tool/facts_validation/literal_repair.py
def normalize_literals_against_schema(
    graph: RDFGraph,
    ontology_graph: RDFGraph | None,
    catalog_roles: CatalogRoles | None = None,
) -> int:
    """Retype literals whose predicate declares a compatible datatype range.

    Applies :func:`schema_retypings` to ``graph`` in place.

    Returns:
        Number of retyped literals.
    """
    replacements = schema_retypings(graph, ontology_graph, catalog_roles)
    for old, new in replacements:
        graph.remove(old)
        graph.add(new)
    return len(replacements)

partition_literals_outside_temporal_ranges(graph, ontology_graph, catalog_roles=None)

Split off :func:temporal_range_mismatches, quarantined for the critic.

Returns:

Type Description
tuple[RDFGraph, list[RejectedLiteralTriple]]

Tuple of (clean graph, quarantined triples).

Source code in ontocast/tool/facts_validation/literal_repair.py
def partition_literals_outside_temporal_ranges(
    graph: RDFGraph,
    ontology_graph: RDFGraph | None,
    catalog_roles: CatalogRoles | None = None,
) -> tuple[RDFGraph, list[RejectedLiteralTriple]]:
    """Split off :func:`temporal_range_mismatches`, quarantined for the critic.

    Returns:
        Tuple of (clean graph, quarantined triples).
    """
    found = temporal_range_mismatches(graph, ontology_graph, catalog_roles)
    if not found:
        return graph, []
    set_aside = {triple for triple, _ in found}
    clean = RDFGraph()
    for prefix, namespace_uri in graph.namespaces():
        if prefix:
            clean.bind(prefix, namespace_uri)
    for triple in graph:
        if triple not in set_aside:
            clean.add(triple)
    return clean, [record for _, record in found]

promote_degenerate_bounds(graph, *, numeric_value_property, lower_bound_property, upper_bound_property, inclusive_flag_properties=())

Rewrite equal lower/upper bounds into a single scalar value, in place.

A node whose lower and upper bounds carry the same canonical numeric value encodes an exact scalar as a fake range. The rewrite fires only when the encoding is unambiguous: exactly one literal per bound property, equal canonical values, no existing scalar on the node, and no exclusive-bound flag (an exclusive equal bound denotes an empty interval — malformed, and left for findings). Property IRIs are injected by the caller from configuration; nothing is hardcoded.

Returns:

Type Description
int

Number of nodes rewritten.

Source code in ontocast/tool/facts_validation/literal_repair.py
def promote_degenerate_bounds(
    graph: RDFGraph,
    *,
    numeric_value_property: str,
    lower_bound_property: str,
    upper_bound_property: str,
    inclusive_flag_properties: Sequence[str] = (),
) -> int:
    """Rewrite equal lower/upper bounds into a single scalar value, in place.

    A node whose lower and upper bounds carry the same canonical numeric value
    encodes an exact scalar as a fake range. The rewrite fires only when the
    encoding is unambiguous: exactly one literal per bound property, equal
    canonical values, no existing scalar on the node, and no exclusive-bound
    flag (an exclusive equal bound denotes an empty interval — malformed, and
    left for findings). Property IRIs are injected by the caller from
    configuration; nothing is hardcoded.

    Returns:
        Number of nodes rewritten.
    """
    lower_ref = URIRef(lower_bound_property)
    upper_ref = URIRef(upper_bound_property)
    value_ref = URIRef(numeric_value_property)
    flag_refs = [URIRef(term) for term in inclusive_flag_properties]
    promoted = 0
    for subject in sorted(set(graph.subjects(lower_ref, None)), key=str):
        lowers = [obj for obj in graph.objects(subject, lower_ref)]
        uppers = [obj for obj in graph.objects(subject, upper_ref)]
        if len(lowers) != 1 or len(uppers) != 1:
            continue
        if not isinstance(lowers[0], Literal) or not isinstance(uppers[0], Literal):
            continue
        if (subject, value_ref, None) in graph:
            continue
        low = canonical_number(str(lowers[0]).strip())
        high = canonical_number(str(uppers[0]).strip())
        if low is None or low != high:
            continue
        if any(
            str(flag_value).strip().lower() == "false"
            for flag_ref in flag_refs
            for flag_value in graph.objects(subject, flag_ref)
        ):
            continue
        graph.remove((subject, lower_ref, lowers[0]))
        graph.remove((subject, upper_ref, uppers[0]))
        for flag_ref in flag_refs:
            for flag_value in list(graph.objects(subject, flag_ref)):
                graph.remove((subject, flag_ref, flag_value))
        graph.add((subject, value_ref, Literal(low, datatype=XSD.decimal)))
        promoted += 1
    if promoted:
        logger.info(
            "Promoted %d degenerate bound pair(s) to <%s>",
            promoted,
            numeric_value_property,
        )
    return promoted

promote_degenerate_bounds_from_vocabulary(graph, ontology_graph, vocabulary)

Run :func:promote_degenerate_bounds with properties from configuration.

Active only when the quantity vocabulary names all three roles — numeric_value, lower_bound, upper_bound (roles containing inclusive supply the optional bound flags). The default vocabulary carries no bound roles, so this is off unless a deployment configures its range encoding.

Source code in ontocast/tool/facts_validation/literal_repair.py
def promote_degenerate_bounds_from_vocabulary(
    graph: RDFGraph,
    ontology_graph: RDFGraph | None,
    vocabulary: dict[str, str] | None,
) -> int:
    """Run :func:`promote_degenerate_bounds` with properties from configuration.

    Active only when the quantity vocabulary names all three roles —
    ``numeric_value``, ``lower_bound``, ``upper_bound`` (roles containing
    ``inclusive`` supply the optional bound flags). The default vocabulary
    carries no bound roles, so this is off unless a deployment configures its
    range encoding.
    """
    vocabulary = vocabulary or {}
    numeric_terms = expand_vocabulary_terms(
        {"numeric_value": vocabulary.get("numeric_value", "")}, graph, ontology_graph
    )
    lower_terms = expand_vocabulary_terms(
        {"lower_bound": vocabulary.get("lower_bound", "")}, graph, ontology_graph
    )
    upper_terms = expand_vocabulary_terms(
        {"upper_bound": vocabulary.get("upper_bound", "")}, graph, ontology_graph
    )
    inclusive_terms = expand_vocabulary_terms(
        _vocabulary_role_subset(vocabulary, "inclusive"), graph, ontology_graph
    )
    if len(numeric_terms) != 1 or len(lower_terms) != 1 or len(upper_terms) != 1:
        return 0
    return promote_degenerate_bounds(
        graph,
        numeric_value_property=next(iter(numeric_terms)),
        lower_bound_property=next(iter(lower_terms)),
        upper_bound_property=next(iter(upper_terms)),
        inclusive_flag_properties=sorted(inclusive_terms),
    )

repair_compact_iri_literals(graph, ontology_context_graph, known_terms)

Coerce plain-string compact IRIs on IRI-valued positions into IRIs.

A JSON-LD bare string ("qudt:unit": "unit:NanoM") parses as a literal, so the node loses its link and reads as missing the property. A literal is rewritten only when every condition holds: it is plain (no language tag, no datatype or xsd:string); the predicate is not rdf:type (that is :func:repair_literal_type_objects); the lexical form is a compact IRI whose prefix the graph or the known-prefix context binds; and either the schema says the predicate takes an IRI or the expanded IRI is a known term. Prose such as "time: 10 minutes" never matches the compact-IRI form.

Parameters:

Name Type Description Default
graph RDFGraph

Facts graph, repaired in place.

required
ontology_context_graph RDFGraph

Schema that says which predicates take IRIs.

required
known_terms set[str]

IRIs the catalog and fallback vocabulary declare; covers predicates whose range the vendored vocabulary leaves undeclared.

required

Returns:

Type Description
tuple[int, list[GraphRepairRecord]]

Tuple of (number of rewritten triples, applied-repair records).

Source code in ontocast/tool/facts_validation/literal_repair.py
def repair_compact_iri_literals(
    graph: RDFGraph,
    ontology_context_graph: RDFGraph,
    known_terms: set[str],
) -> tuple[int, list[GraphRepairRecord]]:
    """Coerce plain-string compact IRIs on IRI-valued positions into IRIs.

    A JSON-LD bare string (``"qudt:unit": "unit:NanoM"``) parses as a literal,
    so the node loses its link and reads as missing the property. A literal is
    rewritten only when every condition holds: it is plain (no language tag,
    no datatype or ``xsd:string``); the predicate is not ``rdf:type`` (that is
    :func:`repair_literal_type_objects`); the lexical form is a compact IRI
    whose prefix the graph or the known-prefix context binds; and either the
    schema says the predicate takes an IRI or the expanded IRI is a known term.
    Prose such as ``"time: 10 minutes"`` never matches the compact-IRI form.

    Args:
        graph: Facts graph, repaired in place.
        ontology_context_graph: Schema that says which predicates take IRIs.
        known_terms: IRIs the catalog and fallback vocabulary declare; covers
            predicates whose range the vendored vocabulary leaves undeclared.

    Returns:
        Tuple of (number of rewritten triples, applied-repair records).
    """
    prefix_map = dict(RDFGraph.get_known_prefixes() or {})
    prefix_map.update(
        {prefix: str(namespace) for prefix, namespace in graph.namespaces() if prefix}
    )
    replacements: list[tuple[tuple[Node, Node, Node], URIRef, str]] = []
    expects_iri: dict[URIRef, bool] = {}
    for subject, predicate, obj in graph:
        if predicate == RDF.type or not isinstance(obj, Literal):
            continue
        if obj.language or obj.datatype not in (None, XSD.string):
            continue
        lexical = str(obj).strip()
        match = _COMPACT_IRI.match(lexical)
        if match is None:
            continue
        namespace = prefix_map.get(match.group(1))
        if not namespace:
            continue
        expanded = f"{namespace}{match.group(2)}"
        if expanded not in known_terms:
            if not isinstance(predicate, URIRef):
                continue
            if predicate not in expects_iri:
                expects_iri[predicate] = _predicate_expects_iri_object(
                    predicate, ontology_context_graph
                )[0]
            if not expects_iri[predicate]:
                continue
        replacements.append(((subject, predicate, obj), URIRef(expanded), lexical))

    applied: list[GraphRepairRecord] = []
    for (subject, predicate, obj), iri, lexical in replacements:
        graph.remove((subject, predicate, obj))
        graph.add((subject, predicate, iri))
        applied.append(
            GraphRepairRecord(
                kind=FactsUnitFindingKind.COMPACT_IRI_LITERAL,
                source=lexical,
                target=str(iri),
            )
        )
        logger.info("Repaired compact-IRI literal %r -> <%s>", lexical, iri)
    if applied:
        record_active_count("repair/compact_iri_literal", len(applied))
    return len(applied), applied

repair_literal_type_objects(graph)

Coerce literal rdf:type objects into IRIs.

The renderer sometimes emits a "prefix:Class"^^xsd:string instead of a prefix:Class (JSON-LD bare-string type values parse the same way). A literal-typed node is invisible to SPARQL class queries, reasoning, and the aggregator's URI minting/entity matching, all of which guard on isinstance(obj, URIRef). Absolute IRIs and compact IRIs bound in the graph are rewritten deterministically; unresolvable forms become MANDATORY findings.

Returns:

Type Description
int

Tuple of (number of rewritten triples, unresolved findings,

list[FactsUnitFinding]

applied-repair records).

Source code in ontocast/tool/facts_validation/literal_repair.py
def repair_literal_type_objects(
    graph: RDFGraph,
) -> tuple[int, list[FactsUnitFinding], list[GraphRepairRecord]]:
    """Coerce literal ``rdf:type`` objects into IRIs.

    The renderer sometimes emits ``a "prefix:Class"^^xsd:string`` instead of
    ``a prefix:Class`` (JSON-LD bare-string type values parse the same way).
    A literal-typed node is invisible to SPARQL class queries, reasoning, and
    the aggregator's URI minting/entity matching, all of which guard on
    ``isinstance(obj, URIRef)``. Absolute IRIs and compact IRIs bound in the
    graph are rewritten deterministically; unresolvable forms become MANDATORY
    findings.

    Returns:
        Tuple of (number of rewritten triples, unresolved findings,
        applied-repair records).
    """
    prefix_map = {
        prefix: str(namespace) for prefix, namespace in graph.namespaces() if prefix
    }
    rewritten = 0
    findings: list[FactsUnitFinding] = []
    applied: list[GraphRepairRecord] = []
    for subject, predicate, obj in list(graph.triples((None, RDF.type, None))):
        if not isinstance(obj, Literal):
            continue
        lexical = str(obj).strip()
        resolved = _resolve_type_literal(lexical, prefix_map)
        if resolved is not None:
            graph.remove((subject, predicate, obj))
            graph.add((subject, RDF.type, URIRef(resolved)))
            rewritten += 1
            applied.append(
                GraphRepairRecord(
                    kind=FactsUnitFindingKind.LITERAL_TYPE_OBJECT,
                    source=lexical,
                    target=resolved,
                )
            )
            logger.info(
                "Repaired literal rdf:type object %r -> <%s>", lexical, resolved
            )
            continue
        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,
            )
        )
    return rewritten, findings, applied

repair_paired_object_properties(graph)

Move a node off a datatype property onto the object property paired with it.

A well-known vocabulary can state one relation twice, once for a literal and once for a node (sosa:hasSimpleResult / sosa:hasResult, :func:~ontocast.onto.well_known.well_known_object_pairs). A node written on the datatype one is rewritten to the object one. A reifier follows its statement.

Returns:

Type Description
tuple[int, list[GraphRepairRecord]]

Tuple of (number of triples moved, applied-repair records).

Source code in ontocast/tool/facts_validation/literal_repair.py
def repair_paired_object_properties(
    graph: RDFGraph,
) -> tuple[int, list[GraphRepairRecord]]:
    """Move a node off a datatype property onto the object property paired with it.

    A well-known vocabulary can state one relation twice, once for a literal
    and once for a node (``sosa:hasSimpleResult`` / ``sosa:hasResult``,
    :func:`~ontocast.onto.well_known.well_known_object_pairs`). A node written
    on the datatype one is rewritten to the object one. A reifier follows its
    statement.

    Returns:
        Tuple of (number of triples moved, applied-repair records).
    """
    pairs = well_known_object_pairs()
    moved: dict[Triple, Triple] = {}
    for subject, predicate, obj in graph:
        paired = pairs.get(str(predicate))
        if paired is not None and isinstance(obj, (URIRef, BNode)):
            moved[(subject, predicate, obj)] = (subject, URIRef(paired), obj)
    applied: list[GraphRepairRecord] = []
    for written in sorted(moved, key=lambda t: tuple(str(term) for term in t)):
        graph.remove(written)
        graph.add(moved[written])
        applied.append(
            GraphRepairRecord(
                kind=FactsUnitFindingKind.PAIRED_OBJECT_PROPERTY,
                source=f"{written[0]} {written[1]}",
                target=str(moved[written][1]),
            )
        )
    if applied:
        if graph.has_reifications:
            graph.reifications.retarget(moved)
        record_active_count("repair/paired_object_property", len(applied))
    return len(applied), applied

repair_property_aliases(graph, ontology_graph, *, min_ratio=0.95, exempt_terms=None, full_catalog_terms=None, catalog_roles=None)

Rewrite near-miss predicates in catalog namespaces; report ambiguity.

A predicate that is not a catalog term and not a real term of a well-known vocabulary (:func:~ontocast.onto.well_known.is_well_known_term) exists nowhere. When exactly one catalog property (catalog_roles, the whole catalog, else the snapshot) in another namespace has its very local name, the prefix slipped and that property is the target; this holds for a predicate in a catalog namespace or a well-known one. A predicate in a namespace the catalog declares terms in is otherwise a near-miss (ex:lowerBound for ex:hasLowerBound), and the rewrite fires only when exactly one candidate qualifies: its name tokens contain the alias's, the alias's contain its, or the two spell the same once case and separators are folded. Several qualifying candidates are a tie that the SequenceMatcher ratio may break -- the best-scoring one wins when it clears min_ratio and nothing ties it. Similarity alone never licenses a rewrite: a high ratio also joins names that differ by exactly one token, and rewriting across that gap substitutes one property for another. Anything else becomes a mandatory finding carrying the top suggestions.

A class written as an rdf:type object follows the same exact-name rule: one that exists nowhere is rewritten to the catalog class, in another namespace, with exactly its local name -- the only one, or among several the one that is a subclass of every other (class_alias).

Only namespaces the catalog declares terms in are eligible for the near-miss rewrite (see :func:collect_declared_namespaces); exempt_terms (expanded fallback vocabulary) are never treated as near-misses, and neither is a predicate in full_catalog_terms: a term the whole catalog declares is real even when this unit's snapshot did not retrieve it, and the snapshot's look-alike is then a different property, not the intended one. Such a predicate is left untouched here; whether it is reported is the term checks' business.

Returns:

Type Description
int

Tuple of (number of rewritten triples, unresolved findings,

list[FactsUnitFinding]

applied-repair records).

Source code in ontocast/tool/facts_validation/literal_repair.py
def repair_property_aliases(
    graph: RDFGraph,
    ontology_graph: RDFGraph | None,
    *,
    min_ratio: float = 0.95,
    exempt_terms: set[str] | None = None,
    full_catalog_terms: set[str] | None = None,
    catalog_roles: CatalogRoles | None = None,
) -> tuple[int, list[FactsUnitFinding], list[GraphRepairRecord]]:
    """Rewrite near-miss predicates in catalog namespaces; report ambiguity.

    A predicate that is not a catalog term and not a real term of a
    well-known vocabulary (:func:`~ontocast.onto.well_known.is_well_known_term`)
    exists nowhere. When exactly one catalog property (``catalog_roles``, the
    whole catalog, else the snapshot) in another namespace has its very local
    name, the prefix slipped and that property is the target; this holds for
    a predicate in a catalog namespace or a well-known one. A predicate in a
    namespace the catalog declares terms in is otherwise a near-miss
    (``ex:lowerBound`` for ``ex:hasLowerBound``), and the rewrite fires only when
    exactly one candidate *qualifies*: its name tokens contain the alias's,
    the alias's contain its, or the two spell the same once case and
    separators are folded. Several qualifying candidates are a tie that the
    ``SequenceMatcher`` ratio may break -- the best-scoring one wins when it
    clears ``min_ratio`` and nothing ties it. Similarity alone never licenses
    a rewrite: a high ratio also joins names that differ by exactly one token,
    and rewriting across that gap substitutes one property for another.
    Anything else becomes a mandatory finding carrying the top suggestions.

    A class written as an ``rdf:type`` object follows the same exact-name
    rule: one that exists nowhere is rewritten to the catalog class, in
    another namespace, with exactly its local name -- the only one, or among
    several the one that is a subclass of every other (``class_alias``).

    Only namespaces the catalog *declares* terms in are eligible for the
    near-miss rewrite (see :func:`collect_declared_namespaces`); ``exempt_terms`` (expanded fallback
    vocabulary) are never treated as near-misses, and neither is a predicate
    in ``full_catalog_terms``: a term the whole catalog declares is real even
    when this unit's snapshot did not retrieve it, and the snapshot's
    look-alike is then a different property, not the intended one. Such a
    predicate is left untouched here; whether it is reported is the term
    checks' business.

    Returns:
        Tuple of (number of rewritten triples, unresolved findings,
        applied-repair records).
    """
    catalog_terms = collect_catalog_terms(ontology_graph)
    if not catalog_terms:
        return 0, [], []
    declared_namespaces = collect_declared_namespaces(ontology_graph)
    exempt = exempt_terms or set()
    known_elsewhere = full_catalog_terms or set()

    findings: list[FactsUnitFinding] = []
    applied: list[GraphRepairRecord] = []
    rewritten = 0
    nowhere = {
        predicate
        for predicate in graph.predicates()
        if isinstance(predicate, URIRef)
        and str(predicate) not in catalog_terms
        and str(predicate) not in exempt
        and str(predicate) not in known_elsewhere
        and is_well_known_term(str(predicate)) is not True
    }
    snapshot_properties, snapshot_classes = _catalog_term_roles(ontology_graph)
    # A well-known property the catalog only references is a property too.
    properties = (
        set(snapshot_properties)
        | (set(catalog_roles.properties) if catalog_roles is not None else set())
        | {
            term
            for term in catalog_terms | known_elsewhere
            if well_known_role(term) == "property"
        }
    )
    for alias in sorted(nowhere, key=str):
        near_miss = _namespace_of(str(alias)) in declared_namespaces
        if not near_miss and is_well_known_term(str(alias)) is None:
            continue
        candidates = (
            _alias_candidates(
                alias, graph, catalog_terms, ontology_graph=ontology_graph
            )
            if near_miss
            else []
        )
        target = _same_name_elsewhere(alias, properties) or (
            _select_alias_target(str(alias), candidates, min_ratio)
            if near_miss
            else None
        )
        if target is not None:
            replacement = URIRef(target)
            alias_triples = 0
            for subject, predicate, obj in list(graph.triples((None, alias, None))):
                graph.remove((subject, predicate, obj))
                graph.add((subject, replacement, obj))
                rewritten += 1
                alias_triples += 1
            applied.append(
                GraphRepairRecord(
                    kind=FactsUnitFindingKind.PROPERTY_ALIAS,
                    source=str(alias),
                    target=str(replacement),
                    triple_count=alias_triples,
                )
            )
            logger.info("Repaired property alias %s -> %s", alias, replacement)
            continue
        if not near_miss:
            continue
        findings.append(
            FactsUnitFinding(
                kind=FactsUnitFindingKind.PROPERTY_ALIAS,
                message=(
                    f"Predicate <{alias}> is not defined in its ontology; "
                    "replace it with the correct catalog property."
                ),
                predicate=str(alias),
                suggestions=candidates,
            )
        )

    # A class named under the wrong prefix: the same exact-name rule, on types.
    classes = set(snapshot_classes) | (
        set(catalog_roles.classes) if catalog_roles is not None else set()
    )
    unknown_types = {
        cls
        for cls in graph.objects(None, RDF.type)
        if isinstance(cls, URIRef)
        and str(cls) not in catalog_terms
        and str(cls) not in exempt
        and str(cls) not in known_elsewhere
        and is_well_known_term(str(cls)) is not True
    }
    context = ontology_graph if ontology_graph is not None else RDFGraph()
    hierarchy = (
        catalog_roles.with_axioms(context) if catalog_roles is not None else context
    )
    for alias in sorted(unknown_types, key=str):
        if (
            _namespace_of(str(alias)) not in declared_namespaces
            and is_well_known_term(str(alias)) is None
        ):
            continue
        target = _most_specific_same_name(alias, classes, hierarchy)
        if target is None:
            continue
        typed = list(graph.subjects(RDF.type, alias))
        for subject in typed:
            graph.remove((subject, RDF.type, alias))
            graph.add((subject, RDF.type, URIRef(target)))
        rewritten += len(typed)
        applied.append(
            GraphRepairRecord(
                kind=FactsUnitFindingKind.CLASS_ALIAS,
                source=str(alias),
                target=target,
                triple_count=len(typed),
            )
        )
        logger.info("Repaired class alias %s -> %s", alias, target)
    return rewritten, findings, applied

repair_reversed_triples(graph, ontology_graph)

Turn around a triple the context shows was written backwards.

x p y becomes y p x when p has a domain and a class range, both ends are typed IRIs, x is outside the domain and y outside the range as written, and swapped both fit. One end fitting, or a type the context cannot place, leaves the triple as it is: the subject may be mistyped, or the property wrong, and neither is a direction. The sides are read from rdfs and from listed (schema:*Includes) classes alike: a listed class contradicts nothing on its own, but evidence at all four positions is a direction. A symmetric property is never turned. A reifier follows its statement.

Parameters:

Name Type Description Default
graph RDFGraph

Facts graph, repaired in place.

required
ontology_graph RDFGraph | None

Ontology context declaring domains and ranges.

required

Returns:

Type Description
tuple[int, list[GraphRepairRecord]]

Tuple of (number of triples turned, applied-repair records).

Source code in ontocast/tool/facts_validation/literal_repair.py
def repair_reversed_triples(
    graph: RDFGraph, ontology_graph: RDFGraph | None
) -> tuple[int, list[GraphRepairRecord]]:
    """Turn around a triple the context shows was written backwards.

    ``x p y`` becomes ``y p x`` when ``p`` has a domain and a class range,
    both ends are typed IRIs, ``x`` is outside the domain and ``y`` outside the
    range as written, and swapped both fit. One end fitting, or a type the
    context cannot place, leaves the triple as it is: the subject may be
    mistyped, or the property wrong, and neither is a direction. The sides are
    read from ``rdfs`` and from listed (``schema:*Includes``) classes alike:
    a listed class contradicts nothing on its own, but evidence at all four
    positions is a direction. A symmetric property is never turned. A reifier
    follows its statement.

    Args:
        graph: Facts graph, repaired in place.
        ontology_graph: Ontology context declaring domains and ranges.

    Returns:
        Tuple of (number of triples turned, applied-repair records).
    """
    if ontology_graph is None or not len(ontology_graph):
        return 0, []
    domains = _declared_domains(ontology_graph)
    ranges = declared_class_ranges(ontology_graph)
    directed = {
        predicate
        for predicate in domains.keys() & ranges.keys()
        if (predicate, RDF.type, OWL.SymmetricProperty) not in ontology_graph
    }
    if not directed:
        return 0, []
    described = _described_classes(ontology_graph)
    closures: dict[URIRef, set[URIRef]] = {}

    def fits(node: URIRef, declared: set[URIRef]) -> bool | None:
        asserted = {
            value
            for value in graph.objects(node, RDF.type)
            if isinstance(value, URIRef) and value not in _VACUOUS_TYPES
        }
        return types_compatible(
            asserted, declared, ontology_graph, described=described, closures=closures
        )

    reversed_: dict[Triple, Triple] = {}
    for subject, predicate, obj in graph:
        if not isinstance(predicate, URIRef) or predicate not in directed:
            continue
        if not isinstance(subject, URIRef) or not isinstance(obj, URIRef):
            continue
        domain, range_ = domains[predicate], ranges[predicate]
        if (
            fits(subject, domain) is False
            and fits(obj, range_) is False
            and fits(obj, domain) is True
            and fits(subject, range_) is True
        ):
            reversed_[(subject, predicate, obj)] = (obj, predicate, subject)

    applied: list[GraphRepairRecord] = []
    for written in sorted(reversed_, key=lambda t: tuple(str(term) for term in t)):
        turned = reversed_[written]
        graph.remove(written)
        graph.add(turned)
        applied.append(
            GraphRepairRecord(
                kind=FactsUnitFindingKind.TRIPLE_REVERSED,
                source=f"{written[0]} {written[1]}",
                target=str(written[2]),
            )
        )
        logger.info("Turned around <%s> <%s> <%s>", *written)
    if applied:
        if graph.has_reifications:
            graph.reifications.retarget(reversed_)
        record_active_count("repair/triple_reversed", len(applied))
    return len(applied), applied

resolve_code_literals(graph, ontology_graph, code_predicates=())

Link nodes to the catalog individual whose code they already carry.

A renderer that reads 4-15 days often annotates the value node with the code it saw — qudt:ucumCode "d" — instead of the object property that points at the individual — qudt:unit unit:DAY. The graph is well-formed, so no range check fires, but every query reading the object property gets an unbound result. The code came from the text and the individual is in the catalog, so the link is recoverable without asking the model again.

Fully schema-driven, no vocabulary compiled in: the connecting property is whichever object property the ontology context declares with a range the resolved individual is typed as, and a domain the subject satisfies. If the schema offers several such properties, or none, nothing is added.

Parameters:

Name Type Description Default
graph RDFGraph

Rendered facts graph, repaired in place.

required
ontology_graph RDFGraph | None

Merged ontology context, read-only.

required
code_predicates Sequence[str]

Predicates carrying machine-resolvable codes.

()

Returns:

Type Description
tuple[int, list[GraphRepairRecord]]

Tuple of (number of added triples, applied-repair records).

Source code in ontocast/tool/facts_validation/literal_repair.py
def resolve_code_literals(
    graph: RDFGraph,
    ontology_graph: RDFGraph | None,
    code_predicates: Sequence[str] = (),
) -> tuple[int, list[GraphRepairRecord]]:
    """Link nodes to the catalog individual whose code they already carry.

    A renderer that reads ``4-15 days`` often annotates the value node with the
    code it saw — ``qudt:ucumCode "d"`` — instead of the object property that
    points at the individual — ``qudt:unit unit:DAY``. The graph is well-formed,
    so no range check fires, but every query reading the object property gets
    an unbound result. The code came from the text and the individual is in the
    catalog, so the link is recoverable without asking the model again.

    Fully schema-driven, no vocabulary compiled in: the connecting property is
    whichever object property the ontology context declares with a range the
    resolved individual is typed as, and a domain the subject satisfies. If the
    schema offers several such properties, or none, nothing is added.

    Args:
        graph: Rendered facts graph, repaired in place.
        ontology_graph: Merged ontology context, read-only.
        code_predicates: Predicates carrying machine-resolvable codes.

    Returns:
        Tuple of (number of added triples, applied-repair records).
    """
    if ontology_graph is None or not code_predicates:
        return 0, []
    code_terms = [URIRef(predicate) for predicate in code_predicates]
    # Only the code predicates themselves resolve here: a label match is a
    # different, much weaker signal and belongs to the shapes-driven pass.
    code_index: dict[str, set[str]] = {}
    for predicate in code_terms:
        for subject, value in ontology_graph.subject_objects(predicate):
            if isinstance(subject, URIRef) and isinstance(value, Literal):
                text = str(value).strip()
                if text:
                    code_index.setdefault(text, set()).add(str(subject))
    if not code_index:
        return 0, []

    domains = _declared_domains(ontology_graph)
    ranges = sides_by_property(ontology_graph, "range")

    # Superclass closures repeat heavily across literals; memoise per call.
    closures: dict[URIRef, set[URIRef]] = {}

    def closure(class_iri: URIRef) -> set[URIRef]:
        if class_iri not in closures:
            closures[class_iri] = superclass_closure(class_iri, ontology_graph)
        return closures[class_iri]

    # The usage-evidence scan is a full graph walk; build it lazily, once,
    # only if some literal actually needs the no-declared-range fallback.
    linking_evidence: list[tuple[set[URIRef], set[URIRef], URIRef]] | None = None

    added = 0
    records: list[GraphRepairRecord] = []
    for code_predicate in code_terms:
        for subject, value in list(graph.subject_objects(code_predicate)):
            if not isinstance(subject, URIRef) or not isinstance(value, Literal):
                continue
            resolved = resolve_unique_surface(code_index, str(value))
            if resolved is None:
                continue
            resolved_types: set[URIRef] = set()
            for type_iri in ontology_graph.objects(resolved, RDF.type):
                if isinstance(type_iri, URIRef):
                    resolved_types |= closure(type_iri)
            if not resolved_types:
                continue
            subject_types: set[URIRef] = set()
            for type_iri in graph.objects(subject, RDF.type):
                if isinstance(type_iri, URIRef):
                    subject_types |= closure(type_iri)

            candidates = [
                predicate
                for predicate, range_set in ranges.items()
                if range_set & resolved_types
                and (
                    predicate not in domains
                    or not domains[predicate]
                    or domains[predicate] & subject_types
                )
            ]
            if not candidates:
                # Vendored vocabulary projections often declare individuals and
                # their codes but no rdfs:range (the shipped QUDT unit subset is
                # one). Fall back to how the graph already links this kind of
                # subject to this kind of individual -- the same
                # induce-from-usage move the functional-predicate harvest makes.
                if linking_evidence is None:
                    linking_evidence = _collect_linking_evidence(
                        graph, ontology_graph, closure
                    )
                candidates = _observed_linking_predicates(
                    linking_evidence, subject_types, resolved_types
                )
            # Already linked, ambiguous, or unsupported by the schema.
            candidates = [
                predicate
                for predicate in candidates
                if (subject, predicate, None) not in graph
            ]
            if len(candidates) != 1:
                continue
            predicate = candidates[0]
            graph.add((subject, predicate, resolved))
            added += 1
            records.append(
                GraphRepairRecord(
                    kind=FactsGateRepairKind.CODE_RESOLVED,
                    source=f"{code_predicate} {value.n3()}",
                    target=f"{predicate} {resolved}",
                )
            )
            logger.info(
                "Resolved code %s on <%s> to <%s %s>",
                value.n3(),
                subject,
                predicate,
                resolved,
            )
    return added, records

schema_retypings(graph, ontology_graph, catalog_roles=None)

Literals whose predicate declares a compatible datatype range, retyped.

Fixes the qudt:numericValue 230 vs "230"^^xsd:decimal drift at parse time, and the same drift for the date, time and duration datatypes: when the range (:func:literal_ranges) is in :data:_RETYPABLE_RANGE_DATATYPES and the lexical form is a value of it, the literal is rewritten with it. A calendar text that names exactly one value of the range ("29 June 2021" on an xsd:date range) is rewritten to that value.

A literal is only retyped from an untyped, xsd:string, or numeric source -- a string range must never be able to clobber a correctly typed value -- and language-tagged literals are left alone, since they are rdf:langString and retyping would discard the tag.

Reads graph only.

Returns:

Type Description
list[tuple[Triple, Triple]]

Each retyped triple with its replacement.

Source code in ontocast/tool/facts_validation/literal_repair.py
def schema_retypings(
    graph: RDFGraph,
    ontology_graph: RDFGraph | None,
    catalog_roles: CatalogRoles | None = None,
) -> list[tuple[Triple, Triple]]:
    """Literals whose predicate declares a compatible datatype range, retyped.

    Fixes the ``qudt:numericValue 230`` vs ``"230"^^xsd:decimal`` drift at parse
    time, and the same drift for the date, time and duration datatypes: when
    the range (:func:`literal_ranges`) is in :data:`_RETYPABLE_RANGE_DATATYPES`
    and the lexical form is a value of it, the literal is rewritten with it. A
    calendar text that names exactly one value of the range (``"29 June
    2021"`` on an ``xsd:date`` range) is rewritten to that value.

    A literal is only retyped from an untyped, ``xsd:string``, or numeric source
    -- a string range must never be able to clobber a correctly typed value --
    and language-tagged literals are left alone, since they are
    ``rdf:langString`` and retyping would discard the tag.

    Reads ``graph`` only.

    Returns:
        Each retyped triple with its replacement.
    """
    declared_ranges = literal_ranges(ontology_graph, catalog_roles)
    if not declared_ranges:
        return []

    replacements: list[tuple[Triple, Triple]] = []
    for subject, predicate, obj in graph:
        if not isinstance(obj, Literal) or not isinstance(predicate, URIRef):
            continue
        target_datatype = declared_ranges.get(predicate)
        if target_datatype is None or obj.datatype == target_datatype:
            continue
        if obj.language is not None:
            continue
        numeric_target = target_datatype in _NUMERIC_RANGE_DATATYPES
        source_admissible = obj.datatype is None or obj.datatype == XSD.string
        if numeric_target:
            # Keep the pre-existing numeric->numeric promotion (integer to
            # decimal, say), which a source-side "untyped or string" rule alone
            # would silently drop.
            source_admissible = (
                source_admissible or obj.datatype in _NUMERIC_RANGE_DATATYPES
            )
        if not source_admissible:
            continue
        value = _typed_value(str(obj).strip(), target_datatype)
        if value is None:
            continue
        replacements.append(((subject, predicate, obj), (subject, predicate, value)))
    return replacements

temporal_range_mismatches(graph, ontology_graph, catalog_roles=None)

Text on a date, time or duration range that is not a value of it.

Run after :func:normalize_literals_against_schema, so a text that is such a value has already been retyped: what is left untyped, xsd:string or language-tagged on a predicate whose range (:func:literal_ranges) is a temporal datatype is not one -- a recurrence or a phrase where a date belongs. Numeric ranges are left to the numeric checks.

Returns:

Type Description
list[tuple[tuple[Node, Node, Node], RejectedLiteralTriple]]

Each such triple with its quarantine record (expected_datatype

list[tuple[tuple[Node, Node, Node], RejectedLiteralTriple]]

names the range).

Source code in ontocast/tool/facts_validation/literal_repair.py
def temporal_range_mismatches(
    graph: RDFGraph,
    ontology_graph: RDFGraph | None,
    catalog_roles: CatalogRoles | None = None,
) -> list[tuple[tuple[Node, Node, Node], RejectedLiteralTriple]]:
    """Text on a date, time or duration range that is not a value of it.

    Run after :func:`normalize_literals_against_schema`, so a text that is such
    a value has already been retyped: what is left untyped, ``xsd:string`` or
    language-tagged on a predicate whose range (:func:`literal_ranges`) is a
    temporal datatype is not one -- a recurrence or a phrase where a date
    belongs. Numeric ranges are left to the numeric checks.

    Returns:
        Each such triple with its quarantine record (``expected_datatype``
        names the range).
    """
    temporal_ranges = {
        predicate: datatype
        for predicate, datatype in literal_ranges(ontology_graph, catalog_roles).items()
        if datatype in _TEMPORAL_RANGE_DATATYPES
    }
    if not temporal_ranges:
        return []
    found: list[tuple[tuple[Node, Node, Node], RejectedLiteralTriple]] = []
    for subject, predicate, obj in graph:
        if not isinstance(obj, Literal) or obj.datatype not in (None, XSD.string):
            continue
        datatype = temporal_ranges.get(predicate)
        if datatype is None or _fits_range(str(obj).strip(), datatype):
            continue
        standing = tuple(
            sorted(
                str(value)
                for value in graph.objects(subject, predicate)
                if isinstance(value, Literal)
                and value.datatype == datatype
                and RDFGraph._is_valid_typed_literal(value)
            )
        )
        found.append(
            (
                (subject, predicate, obj),
                RejectedLiteralTriple(
                    subject=str(subject),
                    predicate=str(predicate),
                    object_lexical=str(obj),
                    datatype=str(obj.datatype or ""),
                    subject_is_blank=isinstance(subject, BNode),
                    standing_values=standing,
                    reason=(
                        "this text is not a value of the property's datatype; "
                        "write a value of that datatype, or state the text with "
                        "a property that takes text"
                    ),
                    expected_datatype=str(datatype),
                ),
            )
        )
    return found

typed_literal(lexical, datatype)

lexical as a well-formed literal of datatype, or None.

The one constructor the retypes share. A number, date, time or duration is judged by its XSD lexical space (see :func:_typed_value); another datatype by whether rdflib reads a value from the form.

Source code in ontocast/tool/facts_validation/literal_repair.py
def typed_literal(lexical: str, datatype: URIRef) -> Literal | None:
    """``lexical`` as a well-formed literal of ``datatype``, or ``None``.

    The one constructor the retypes share. A number, date, time or duration is
    judged by its XSD lexical space (see :func:`_typed_value`); another
    datatype by whether rdflib reads a value from the form.
    """
    lexical = lexical.strip()
    if datatype in _RETYPABLE_RANGE_DATATYPES:
        return _typed_value(lexical, datatype)
    with _quiet_rdflib_casts():
        value = Literal(lexical, datatype=datatype)
    return value if value.value is not None else None

unresolved_quarantine(graph, items)

The quarantined triples graph has not since made good.

One is resolved when it was written back, when its subject now states its predicate with a new value of the kind it was set aside for lacking (an IRI for an object property, a valid literal of the expected or declared datatype), or when the subject states its text under another predicate.

Source code in ontocast/tool/facts_validation/literal_repair.py
def unresolved_quarantine(
    graph: RDFGraph, items: Sequence[RejectedLiteralTriple]
) -> list[RejectedLiteralTriple]:
    """The quarantined triples ``graph`` has not since made good.

    One is resolved when it was written back, when its subject now states its
    predicate with a new value of the kind it was set aside for lacking (an
    IRI for an object property, a valid literal of the expected or declared
    datatype), or when the subject states its text under another predicate.
    """
    unresolved: list[RejectedLiteralTriple] = []
    for item in items:
        if item.written_back:
            continue
        subject = _quarantined_subject(item)
        if _states_text(graph, subject, item.object_lexical):
            continue
        if any(
            _replaces(obj, item)
            for obj in graph.objects(subject, URIRef(item.predicate))
        ):
            continue
        unresolved.append(item)
    return unresolved

write_back_temporal_quarantine(graph, items)

Put back, as rdfs:comment, date text the unit still holds aside.

A text set aside for not being a value of a date, time or duration datatype -- written plain on such a range, or typed with such a datatype it is not a value of -- and not since resolved (:func:unresolved_quarantine) is kept verbatim on its subject, so nothing is lost and no false date is stated. A subject the graph no longer names, in either position, gets nothing: a comment would make a node of a comment alone. Quarantined strings on object properties and bad numbers are not written back.

Returns:

Type Description
list[GraphRepairRecord]

One quarantine_as_comment record per text written back, and

list[RejectedLiteralTriple]

items with those marked written_back.

Source code in ontocast/tool/facts_validation/literal_repair.py
def write_back_temporal_quarantine(
    graph: RDFGraph, items: Sequence[RejectedLiteralTriple]
) -> tuple[list[GraphRepairRecord], list[RejectedLiteralTriple]]:
    """Put back, as ``rdfs:comment``, date text the unit still holds aside.

    A text set aside for not being a value of a date, time or duration
    datatype -- written plain on such a range, or typed with such a datatype
    it is not a value of -- and not since resolved (:func:`unresolved_quarantine`)
    is kept verbatim on its subject, so nothing is lost and no false date is
    stated. A subject the graph no longer names, in either position, gets
    nothing: a comment would make a node of a comment alone. Quarantined strings on object properties
    and bad numbers are not written back.

    Returns:
        One ``quarantine_as_comment`` record per text written back, and
        ``items`` with those marked ``written_back``.
    """
    pending = set(unresolved_quarantine(graph, items))
    records: list[GraphRepairRecord] = []
    marked: list[RejectedLiteralTriple] = []
    for item in items:
        datatype = item.expected_datatype or item.datatype
        subject = _quarantined_subject(item)
        if (
            item not in pending
            or not datatype
            or URIRef(datatype) not in _TEMPORAL_RANGE_DATATYPES
            or not _in_graph(graph, subject)
        ):
            marked.append(item)
            continue
        graph.add((subject, RDFS.comment, Literal(item.object_lexical)))
        records.append(
            GraphRepairRecord(
                kind=FactsGateRepairKind.QUARANTINE_AS_COMMENT,
                source=f"<{item.predicate}> {item.object_lexical!r}",
                target=item.subject,
            )
        )
        marked.append(item.model_copy(update={"written_back": True}))
    return records, marked