Skip to content

ontocast.tool.facts_validation.terms

Catalog term inventory, namespace closure rules, and alias candidates.

What the catalog declares versus merely references decides which namespaces the term checks may treat as closed; ValidationPolicy carries the deployment-level exemptions every check honours.

Attributes

logger = logging.getLogger(__name__) module-attribute

Classes

CatalogRoles

What the whole catalog says each term is, read once per catalog state.

A unit sees a retrieved snapshot; the role of a term (property or class) and a class's place in the hierarchy are read from every held ontology, so a term the snapshot omits is still known for what it is.

Attributes:

Name Type Description
properties

Terms the catalog states are properties.

classes

Terms the catalog states are classes.

hierarchy

The catalog's subclass statements, for closures.

axioms

The catalog's domains, ranges, listed classes and the types of its terms, with the hierarchy.

datatype_ranges

Each property's declared rdfs:range IRIs in the XSD namespace, across every graph; more than one means the catalog contradicts itself.

Source code in ontocast/tool/facts_validation/terms.py
class CatalogRoles:
    """What the whole catalog says each term is, read once per catalog state.

    A unit sees a retrieved snapshot; the role of a term (property or class)
    and a class's place in the hierarchy are read from every held ontology, so
    a term the snapshot omits is still known for what it is.

    Attributes:
        properties: Terms the catalog states are properties.
        classes: Terms the catalog states are classes.
        hierarchy: The catalog's subclass statements, for closures.
        axioms: The catalog's domains, ranges, listed classes and the types
            of its terms, with the hierarchy.
        datatype_ranges: Each property's declared ``rdfs:range`` IRIs in the
            XSD namespace, across every graph; more than one means the catalog
            contradicts itself.
    """

    def __init__(
        self,
        properties: frozenset[str] = frozenset(),
        classes: frozenset[str] = frozenset(),
        hierarchy: RDFGraph | None = None,
        datatype_ranges: dict[str, frozenset[str]] | None = None,
        axioms: RDFGraph | None = None,
    ) -> None:
        self.properties = properties
        self.classes = classes
        self.hierarchy = hierarchy if hierarchy is not None else RDFGraph()
        self.axioms = axioms if axioms is not None else RDFGraph()
        self.datatype_ranges = datatype_ranges or {}
        self._declared_ranges: dict[str, frozenset[str]] | None = None
        self._subject_links: tuple[frozenset[str], frozenset[str]] | None = None
        self._classes_under: dict[frozenset[str], frozenset[str]] = {}

    @classmethod
    def of(cls, graphs: typing.Iterable[RDFGraph]) -> "CatalogRoles":
        """The roles and hierarchy stated across ``graphs``."""
        properties: set[str] = set()
        classes: set[str] = set()
        hierarchy = RDFGraph()
        axioms = RDFGraph()
        ranges: dict[str, set[str]] = {}
        for graph in graphs:
            for predicate in _AXIOM_PREDICATES:
                for triple in graph.triples((None, predicate, None)):
                    axioms.add(triple)
            # Every catalog term's own type: what is a class, a datatype, a
            # symmetric property, and which IRIs are the catalog's individuals,
            # which entailment must never type.
            for triple in graph.triples((None, RDF.type, None)):
                if isinstance(triple[0], URIRef):
                    axioms.add(triple)
            known_properties, known_classes = _catalog_term_roles(graph)
            properties |= known_properties
            classes |= known_classes
            for predicate in (
                *_HIERARCHY_PREDICATES,
                RDFS.subPropertyOf,
                OWL.inverseOf,
            ):
                for triple in graph.triples((None, predicate, None)):
                    hierarchy.add(triple)
            for subject, range_iri in graph.subject_objects(RDFS.range):
                if isinstance(subject, URIRef) and str(range_iri).startswith(str(XSD)):
                    ranges.setdefault(str(subject), set()).add(str(range_iri))
        # A term typed both ways across files is contradictory; trust neither.
        ambiguous = properties & classes
        return cls(
            frozenset(properties - ambiguous),
            frozenset(classes - ambiguous),
            hierarchy,
            {iri: frozenset(found) for iri, found in ranges.items()},
            axioms + hierarchy,
        )

    def with_axioms(self, graph: RDFGraph) -> RDFGraph:
        """``graph`` together with the catalog's axioms, as a new graph.

        A unit's snapshot may keep a property's domain and drop its range, or a
        class without its place in the hierarchy; domain and range repairs read
        this union so the answer does not depend on what retrieval kept.
        """
        if not len(self.axioms):
            return graph
        return graph + self.axioms

    def declared_ranges(self) -> dict[str, frozenset[str]]:
        """Each property's declared XSD ranges: the catalog's and the well-known.

        Read once per catalog state; a unit adds only its snapshot's.
        """
        if self._declared_ranges is None:
            merged: dict[str, set[str]] = {}
            for prop, datatype in well_known_datatype_ranges().items():
                merged.setdefault(prop, set()).add(datatype)
            for prop, datatypes in self.datatype_ranges.items():
                merged.setdefault(prop, set()).update(datatypes)
            self._declared_ranges = {
                prop: frozenset(found) for prop, found in merged.items()
            }
        return self._declared_ranges

    def subject_links(self) -> tuple[frozenset[str], frozenset[str]]:
        """The properties linking a statement and its subject, each direction.

        The well-known ones, every catalog sub-property of one, and every
        catalog inverse of one in the other direction.

        Returns:
            ``(forward, inverse)``: statement -> subject, subject -> statement.
        """
        if self._subject_links is None:
            forward, inverse = (set(found) for found in well_known_subject_links())
            changed = True
            while changed:
                before = len(forward) + len(inverse)
                for side, other in ((forward, inverse), (inverse, forward)):
                    for prop in list(side):
                        node = URIRef(prop)
                        side |= {
                            str(s)
                            for s in self.hierarchy.subjects(RDFS.subPropertyOf, node)
                            if isinstance(s, URIRef)
                        }
                        other |= {
                            str(term)
                            for term in (
                                *self.hierarchy.subjects(OWL.inverseOf, node),
                                *self.hierarchy.objects(node, OWL.inverseOf),
                            )
                            if isinstance(term, URIRef)
                        }
                changed = len(forward) + len(inverse) != before
            self._subject_links = (frozenset(forward), frozenset(inverse))
        return self._subject_links

    def subject_contract(self, value_base: frozenset[str]) -> SubjectContract:
        """The :class:`SubjectContract` of this catalog.

        Args:
            value_base: The value classes to anchor on (:func:`value_class_base`).
        """
        forward, inverse = self.subject_links()
        return SubjectContract(
            statement_classes=self.classes_under(well_known_statement_classes()),
            value_classes=self.classes_under(value_base),
            forward=forward,
            inverse=inverse,
        )

    def classes_under(self, base: frozenset[str]) -> frozenset[str]:
        """``base`` and every catalog class whose supertypes meet it.

        Args:
            base: Anchor classes, such as the classes of structured values
                (:func:`value_class_base`) or of statements.
        """
        found = self._classes_under.get(base)
        if found is None:
            candidates = self.classes | {
                str(s) for s in self.hierarchy.subjects(RDFS.subClassOf, None)
            }
            found = frozenset(base) | {
                iri
                for iri in candidates
                if {str(c) for c in superclass_closure(URIRef(iri), self.hierarchy)}
                & base
            }
            self._classes_under[base] = found
        return found

Attributes

axioms = axioms if axioms is not None else RDFGraph() instance-attribute
classes = classes instance-attribute
datatype_ranges = datatype_ranges or {} instance-attribute
hierarchy = hierarchy if hierarchy is not None else RDFGraph() instance-attribute
properties = properties instance-attribute

Methods:

__init__(properties=frozenset(), classes=frozenset(), hierarchy=None, datatype_ranges=None, axioms=None)
Source code in ontocast/tool/facts_validation/terms.py
def __init__(
    self,
    properties: frozenset[str] = frozenset(),
    classes: frozenset[str] = frozenset(),
    hierarchy: RDFGraph | None = None,
    datatype_ranges: dict[str, frozenset[str]] | None = None,
    axioms: RDFGraph | None = None,
) -> None:
    self.properties = properties
    self.classes = classes
    self.hierarchy = hierarchy if hierarchy is not None else RDFGraph()
    self.axioms = axioms if axioms is not None else RDFGraph()
    self.datatype_ranges = datatype_ranges or {}
    self._declared_ranges: dict[str, frozenset[str]] | None = None
    self._subject_links: tuple[frozenset[str], frozenset[str]] | None = None
    self._classes_under: dict[frozenset[str], frozenset[str]] = {}
classes_under(base)

base and every catalog class whose supertypes meet it.

Parameters:

Name Type Description Default
base frozenset[str]

Anchor classes, such as the classes of structured values (:func:value_class_base) or of statements.

required
Source code in ontocast/tool/facts_validation/terms.py
def classes_under(self, base: frozenset[str]) -> frozenset[str]:
    """``base`` and every catalog class whose supertypes meet it.

    Args:
        base: Anchor classes, such as the classes of structured values
            (:func:`value_class_base`) or of statements.
    """
    found = self._classes_under.get(base)
    if found is None:
        candidates = self.classes | {
            str(s) for s in self.hierarchy.subjects(RDFS.subClassOf, None)
        }
        found = frozenset(base) | {
            iri
            for iri in candidates
            if {str(c) for c in superclass_closure(URIRef(iri), self.hierarchy)}
            & base
        }
        self._classes_under[base] = found
    return found
declared_ranges()

Each property's declared XSD ranges: the catalog's and the well-known.

Read once per catalog state; a unit adds only its snapshot's.

Source code in ontocast/tool/facts_validation/terms.py
def declared_ranges(self) -> dict[str, frozenset[str]]:
    """Each property's declared XSD ranges: the catalog's and the well-known.

    Read once per catalog state; a unit adds only its snapshot's.
    """
    if self._declared_ranges is None:
        merged: dict[str, set[str]] = {}
        for prop, datatype in well_known_datatype_ranges().items():
            merged.setdefault(prop, set()).add(datatype)
        for prop, datatypes in self.datatype_ranges.items():
            merged.setdefault(prop, set()).update(datatypes)
        self._declared_ranges = {
            prop: frozenset(found) for prop, found in merged.items()
        }
    return self._declared_ranges
of(graphs) classmethod

The roles and hierarchy stated across graphs.

Source code in ontocast/tool/facts_validation/terms.py
@classmethod
def of(cls, graphs: typing.Iterable[RDFGraph]) -> "CatalogRoles":
    """The roles and hierarchy stated across ``graphs``."""
    properties: set[str] = set()
    classes: set[str] = set()
    hierarchy = RDFGraph()
    axioms = RDFGraph()
    ranges: dict[str, set[str]] = {}
    for graph in graphs:
        for predicate in _AXIOM_PREDICATES:
            for triple in graph.triples((None, predicate, None)):
                axioms.add(triple)
        # Every catalog term's own type: what is a class, a datatype, a
        # symmetric property, and which IRIs are the catalog's individuals,
        # which entailment must never type.
        for triple in graph.triples((None, RDF.type, None)):
            if isinstance(triple[0], URIRef):
                axioms.add(triple)
        known_properties, known_classes = _catalog_term_roles(graph)
        properties |= known_properties
        classes |= known_classes
        for predicate in (
            *_HIERARCHY_PREDICATES,
            RDFS.subPropertyOf,
            OWL.inverseOf,
        ):
            for triple in graph.triples((None, predicate, None)):
                hierarchy.add(triple)
        for subject, range_iri in graph.subject_objects(RDFS.range):
            if isinstance(subject, URIRef) and str(range_iri).startswith(str(XSD)):
                ranges.setdefault(str(subject), set()).add(str(range_iri))
    # A term typed both ways across files is contradictory; trust neither.
    ambiguous = properties & classes
    return cls(
        frozenset(properties - ambiguous),
        frozenset(classes - ambiguous),
        hierarchy,
        {iri: frozenset(found) for iri, found in ranges.items()},
        axioms + hierarchy,
    )
subject_contract(value_base)

The :class:SubjectContract of this catalog.

Parameters:

Name Type Description Default
value_base frozenset[str]

The value classes to anchor on (:func:value_class_base).

required
Source code in ontocast/tool/facts_validation/terms.py
def subject_contract(self, value_base: frozenset[str]) -> SubjectContract:
    """The :class:`SubjectContract` of this catalog.

    Args:
        value_base: The value classes to anchor on (:func:`value_class_base`).
    """
    forward, inverse = self.subject_links()
    return SubjectContract(
        statement_classes=self.classes_under(well_known_statement_classes()),
        value_classes=self.classes_under(value_base),
        forward=forward,
        inverse=inverse,
    )

The properties linking a statement and its subject, each direction.

The well-known ones, every catalog sub-property of one, and every catalog inverse of one in the other direction.

Returns:

Type Description
tuple[frozenset[str], frozenset[str]]

(forward, inverse): statement -> subject, subject -> statement.

Source code in ontocast/tool/facts_validation/terms.py
def subject_links(self) -> tuple[frozenset[str], frozenset[str]]:
    """The properties linking a statement and its subject, each direction.

    The well-known ones, every catalog sub-property of one, and every
    catalog inverse of one in the other direction.

    Returns:
        ``(forward, inverse)``: statement -> subject, subject -> statement.
    """
    if self._subject_links is None:
        forward, inverse = (set(found) for found in well_known_subject_links())
        changed = True
        while changed:
            before = len(forward) + len(inverse)
            for side, other in ((forward, inverse), (inverse, forward)):
                for prop in list(side):
                    node = URIRef(prop)
                    side |= {
                        str(s)
                        for s in self.hierarchy.subjects(RDFS.subPropertyOf, node)
                        if isinstance(s, URIRef)
                    }
                    other |= {
                        str(term)
                        for term in (
                            *self.hierarchy.subjects(OWL.inverseOf, node),
                            *self.hierarchy.objects(node, OWL.inverseOf),
                        )
                        if isinstance(term, URIRef)
                    }
            changed = len(forward) + len(inverse) != before
        self._subject_links = (frozenset(forward), frozenset(inverse))
    return self._subject_links
with_axioms(graph)

graph together with the catalog's axioms, as a new graph.

A unit's snapshot may keep a property's domain and drop its range, or a class without its place in the hierarchy; domain and range repairs read this union so the answer does not depend on what retrieval kept.

Source code in ontocast/tool/facts_validation/terms.py
def with_axioms(self, graph: RDFGraph) -> RDFGraph:
    """``graph`` together with the catalog's axioms, as a new graph.

    A unit's snapshot may keep a property's domain and drop its range, or a
    class without its place in the hierarchy; domain and range repairs read
    this union so the answer does not depend on what retrieval kept.
    """
    if not len(self.axioms):
        return graph
    return graph + self.axioms

SubjectContract

Bases: BaseModel

What makes a statement name its subject, over the whole catalog.

Attributes:

Name Type Description
statement_classes frozenset[str]

Classes whose instances are statements about something else (an observation), with every catalog class under one.

value_classes frozenset[str]

Classes whose instances are values, likewise.

forward frozenset[str]

Properties running from a statement to its subject.

inverse frozenset[str]

Properties running from a subject to a statement.

Source code in ontocast/tool/facts_validation/terms.py
class SubjectContract(BaseModel):
    """What makes a statement name its subject, over the whole catalog.

    Attributes:
        statement_classes: Classes whose instances are statements about
            something else (an observation), with every catalog class under one.
        value_classes: Classes whose instances are values, likewise.
        forward: Properties running from a statement to its subject.
        inverse: Properties running from a subject to a statement.
    """

    model_config = {"frozen": True}

    statement_classes: frozenset[str] = frozenset()
    value_classes: frozenset[str] = frozenset()
    forward: frozenset[str] = frozenset()
    inverse: frozenset[str] = frozenset()

Attributes

forward = frozenset() class-attribute instance-attribute
inverse = frozenset() class-attribute instance-attribute
model_config = {'frozen': True} class-attribute instance-attribute
statement_classes = frozenset() class-attribute instance-attribute
value_classes = frozenset() class-attribute instance-attribute

ValidationPolicy

Bases: BaseModel

Deployment-level exemptions and vocabulary for deterministic validation.

One object instead of a parameter per concern: the namespaces a deployment shares across catalogs, the sanctioned quantity fallback vocabulary, and the code predicates — everything the term checks must never flag, because configuration explicitly blessed it.

Source code in ontocast/tool/facts_validation/terms.py
class ValidationPolicy(BaseModel):
    """Deployment-level exemptions and vocabulary for deterministic validation.

    One object instead of a parameter per concern: the namespaces a deployment
    shares across catalogs, the sanctioned quantity fallback vocabulary, and
    the code predicates — everything the term checks must never flag, because
    configuration explicitly blessed it.
    """

    additional_standard_namespaces: tuple[str, ...] = ()
    #: ``strict`` closes the vocabulary to the catalog, the vocabularies it
    #: borrows from, the well-known vocabularies and the terms named here:
    #: any other class or property is UNKNOWN_TERM. ``open`` lets any other
    #: vocabulary pass, so only a member of a closed namespace is unknown.
    vocabulary: typing.Literal["strict", "open"] = "strict"
    quantity_fallback_vocabulary: dict[str, str] | None = None
    code_predicates: tuple[str, ...] = ()
    #: IRIs the shapes-derived conformance chapter instructs the renderer to
    #: emit. Same class of exemption as the fallback vocabulary: the prompt
    #: recommends these terms, so flagging them UNKNOWN_TERM would have the
    #: repair lane delete exactly what the prompt required. Threaded per unit
    #: from the tenancy's shapes catalog.
    contract_exempt_terms: tuple[str, ...] = ()
    #: Keep identifier digit groups out of the numeric-coverage inventory.
    #: Same class as the exemptions above -- something configuration says the
    #: deterministic checks must not put in front of the renderer.
    numeric_identifier_guard: bool = False
    #: Floor on the share of schema terms a render must take from the
    #: catalog before DOMAIN_ADHERENCE fires. 0 disables the check.
    domain_adherence_min_share: float = 0.15
    #: Fewest distinct schema terms a render must use before its catalog
    #: share is judged at all. A share over a handful of terms is noise: a
    #: front-matter unit typing an identifier and an author with generic
    #: vocabulary is not a render that abandoned the catalog.
    domain_adherence_min_terms: int = 4

    def standard_namespaces(self) -> tuple[str, ...]:
        """Namespaces no catalog owns: the meta-vocabularies, the well-known
        vocabularies (:mod:`ontocast.onto.well_known`) and the configured
        ones. A term of a well-known vocabulary must still exist in it."""
        return (
            *_STANDARD_NAMESPACES,
            *well_known_namespaces(),
            *self.additional_standard_namespaces,
        )

    def exempt_terms(self, *graphs: RDFGraph | None) -> set[str]:
        """Exact IRIs configuration blessed: fallback vocabulary, code
        predicates, and the shapes-contract terms."""
        terms = expand_vocabulary_terms(self.quantity_fallback_vocabulary, *graphs)
        terms.update(self.code_predicates)
        terms.update(self.contract_exempt_terms)
        return terms

Attributes

additional_standard_namespaces = () class-attribute instance-attribute
code_predicates = () class-attribute instance-attribute
contract_exempt_terms = () class-attribute instance-attribute
domain_adherence_min_share = 0.15 class-attribute instance-attribute
domain_adherence_min_terms = 4 class-attribute instance-attribute
numeric_identifier_guard = False class-attribute instance-attribute
quantity_fallback_vocabulary = None class-attribute instance-attribute
vocabulary = 'strict' class-attribute instance-attribute

Methods:

exempt_terms(*graphs)

Exact IRIs configuration blessed: fallback vocabulary, code predicates, and the shapes-contract terms.

Source code in ontocast/tool/facts_validation/terms.py
def exempt_terms(self, *graphs: RDFGraph | None) -> set[str]:
    """Exact IRIs configuration blessed: fallback vocabulary, code
    predicates, and the shapes-contract terms."""
    terms = expand_vocabulary_terms(self.quantity_fallback_vocabulary, *graphs)
    terms.update(self.code_predicates)
    terms.update(self.contract_exempt_terms)
    return terms
standard_namespaces()

Namespaces no catalog owns: the meta-vocabularies, the well-known vocabularies (:mod:ontocast.onto.well_known) and the configured ones. A term of a well-known vocabulary must still exist in it.

Source code in ontocast/tool/facts_validation/terms.py
def standard_namespaces(self) -> tuple[str, ...]:
    """Namespaces no catalog owns: the meta-vocabularies, the well-known
    vocabularies (:mod:`ontocast.onto.well_known`) and the configured
    ones. A term of a well-known vocabulary must still exist in it."""
    return (
        *_STANDARD_NAMESPACES,
        *well_known_namespaces(),
        *self.additional_standard_namespaces,
    )

Functions:

build_surface_index(ontology_graph, code_predicates=())

Map exact catalog surface forms to the IRIs declaring them.

Case-sensitive and exact: these are codes and names a model may have transcribed verbatim ("d", "meV", "CsPbBr3"), not free text to be fuzzy-matched. A form claimed by more than one IRI stays in the index and is rejected at lookup time — an ambiguous code is not a repairable one.

Parameters:

Name Type Description Default
ontology_graph RDFGraph | None

Merged ontology context to index.

required
code_predicates Sequence[str]

Extra code-bearing predicates (UCUM codes, symbols, notations) on top of the standard name predicates.

()

Returns:

Type Description
dict[str, set[str]]

Surface form -> set of IRIs declaring it.

Source code in ontocast/tool/facts_validation/terms.py
def build_surface_index(
    ontology_graph: RDFGraph | None,
    code_predicates: Sequence[str] = (),
) -> dict[str, set[str]]:
    """Map exact catalog surface forms to the IRIs declaring them.

    Case-sensitive and exact: these are codes and names a model may have
    transcribed verbatim (``"d"``, ``"meV"``, ``"CsPbBr3"``), not free text to
    be fuzzy-matched. A form claimed by more than one IRI stays in the index and
    is rejected at lookup time — an ambiguous code is not a repairable one.

    Args:
        ontology_graph: Merged ontology context to index.
        code_predicates: Extra code-bearing predicates (UCUM codes, symbols,
            notations) on top of the standard name predicates.

    Returns:
        Surface form -> set of IRIs declaring it.
    """
    index: dict[str, set[str]] = {}
    if ontology_graph is None:
        return index
    predicates: list[URIRef] = [RDFS.label, SKOS.prefLabel, SKOS.notation]
    predicates.extend(URIRef(predicate) for predicate in code_predicates)
    for predicate in predicates:
        for subject, value in ontology_graph.subject_objects(predicate):
            if not isinstance(subject, URIRef) or not isinstance(value, Literal):
                continue
            text = str(value).strip()
            if text:
                index.setdefault(text, set()).add(str(subject))
    return index

catalog_term_evidence(ontology_graph)

Catalog terms with property evidence and with class evidence.

Only what the catalog states is used: explicit property/class typing, a domain or a range (rdfs or schema:*Includes, property evidence), and rdfs:subClassOf / rdf:type-object position (class evidence). A term may land in both sets; :func:_catalog_term_roles drops those.

Source code in ontocast/tool/facts_validation/terms.py
def catalog_term_evidence(
    ontology_graph: RDFGraph | None,
) -> tuple[set[str], set[str]]:
    """Catalog terms with property evidence and with class evidence.

    Only what the catalog states is used: explicit property/class typing,
    a domain or a range (``rdfs`` or ``schema:*Includes``, property evidence), and
    ``rdfs:subClassOf`` / ``rdf:type``-object position (class evidence). A
    term may land in both sets; :func:`_catalog_term_roles` drops those.
    """
    properties: set[str] = set()
    classes: set[str] = set()
    if ontology_graph is None:
        return properties, classes
    for property_type in _PROPERTY_TYPES:
        for subject in ontology_graph.subjects(RDF.type, property_type):
            if isinstance(subject, URIRef):
                properties.add(str(subject))
    for subject in ontology_graph.subjects(RDF.type, RDF.Property):
        if isinstance(subject, URIRef):
            properties.add(str(subject))
    for predicate in SIDE_PREDICATES:
        for subject in ontology_graph.subjects(predicate, None):
            if isinstance(subject, URIRef):
                properties.add(str(subject))
    for class_type in (OWL.Class, RDFS.Class):
        for subject in ontology_graph.subjects(RDF.type, class_type):
            if isinstance(subject, URIRef):
                classes.add(str(subject))
    for subject, obj in ontology_graph.subject_objects(RDFS.subClassOf):
        for term in (subject, obj):
            if isinstance(term, URIRef):
                classes.add(str(term))
    for obj in ontology_graph.objects(None, RDF.type):
        if isinstance(obj, URIRef):
            classes.add(str(obj))
    return properties, classes

collect_catalog_terms(ontology_graph)

All IRIs appearing anywhere in the ontology context.

Source code in ontocast/tool/facts_validation/terms.py
def collect_catalog_terms(ontology_graph: RDFGraph | None) -> set[str]:
    """All IRIs appearing anywhere in the ontology context."""
    terms: set[str] = set()
    if ontology_graph is None:
        return terms
    for triple in ontology_graph:
        for term in triple:
            if isinstance(term, URIRef):
                terms.add(str(term))
    return terms

collect_declared_namespaces(ontology_graph)

Namespaces the catalog declares terms in (subject-position IRIs).

The UNKNOWN_TERM check treats a namespace as closed — flagging members the catalog does not list — only when the catalog actually declares terms there. A namespace the catalog merely references (qudt:QuantityValue in an rdfs:subClassOf, qudt:unit in an owl:onProperty) is an external vocabulary the catalog borrows from, and the catalog is not an authority on its membership. Treating referenced-only namespaces as closed produced mandatory findings against canonical external properties (qudt:numericValue), which repair renders then obeyed by deleting correct data.

Source code in ontocast/tool/facts_validation/terms.py
def collect_declared_namespaces(ontology_graph: RDFGraph | None) -> set[str]:
    """Namespaces the catalog *declares* terms in (subject-position IRIs).

    The UNKNOWN_TERM check treats a namespace as closed — flagging members the
    catalog does not list — only when the catalog actually declares terms
    there. A namespace the catalog merely *references* (``qudt:QuantityValue``
    in an ``rdfs:subClassOf``, ``qudt:unit`` in an ``owl:onProperty``) is an
    external vocabulary the catalog borrows from, and the catalog is not an
    authority on its membership. Treating referenced-only namespaces as closed
    produced mandatory findings against canonical external properties
    (``qudt:numericValue``), which repair renders then obeyed by deleting
    correct data.
    """
    namespaces: set[str] = set()
    if ontology_graph is None:
        return namespaces
    for subject in ontology_graph.subjects():
        if isinstance(subject, URIRef):
            namespaces.add(_namespace_of(str(subject)))
    return namespaces

concrete_types(graph, node, fact_namespaces)

The asserted rdf:type objects of node that count as a type.

A type counts when it is an IRI outside fact_namespaces (a class minted beside the instances is no class), not a schema metaclass (rdfs:Class, owl:Class, rdf:Property, the OWL property classes, owl:NamedIndividual) and not vacuous (owl:Thing, rdfs:Resource, schema:Thing).

Source code in ontocast/tool/facts_validation/terms.py
def concrete_types(
    graph: RDFGraph, node: Node, fact_namespaces: Sequence[str]
) -> set[URIRef]:
    """The asserted ``rdf:type`` objects of ``node`` that count as a type.

    A type counts when it is an IRI outside ``fact_namespaces`` (a class
    minted beside the instances is no class), not a schema metaclass
    (``rdfs:Class``, ``owl:Class``, ``rdf:Property``, the OWL property
    classes, ``owl:NamedIndividual``) and not vacuous (``owl:Thing``,
    ``rdfs:Resource``, ``schema:Thing``).
    """
    namespaces = [ns for ns in fact_namespaces if ns]
    return {
        value
        for value in graph.objects(node, RDF.type)
        if isinstance(value, URIRef)
        and value not in _VACUOUS_TYPES
        and value not in _SCHEMA_METACLASSES
        and not (namespaces and _in_fact_scope(value, namespaces))
    }

declared_class_ranges(ontology_graph, *, source=None)

Predicate -> the named classes its range names, datatypes left out.

Both rdfs:range and schema:rangeIncludes by default; source="rdfs" keeps the entailing ones. A datatype range (XSD, rdfs:Literal, a declared rdfs:Datatype) types a literal, not a node, and is left out.

Source code in ontocast/tool/facts_validation/terms.py
def declared_class_ranges(
    ontology_graph: RDFGraph, *, source: SideSource | None = None
) -> dict[URIRef, set[URIRef]]:
    """Predicate -> the named classes its range names, datatypes left out.

    Both ``rdfs:range`` and ``schema:rangeIncludes`` by default;
    ``source="rdfs"`` keeps the entailing ones. A datatype range (XSD,
    ``rdfs:Literal``, a declared ``rdfs:Datatype``) types a literal, not a
    node, and is left out.
    """
    ranges: dict[URIRef, set[URIRef]] = {}
    for predicate, values in sides_by_property(
        ontology_graph, "range", source=source
    ).items():
        classes = {v for v in values if not is_datatype_value(v, ontology_graph)}
        if classes:
            ranges[predicate] = classes
    return ranges

domain_fits(subject, predicate, graph, ontology_graph)

Whether subject's asserted types contradict no rdfs:domain of predicate.

The test :func:domain_violation_findings applies: only rdfs:domain entails, so only it can be contradicted; a listed class is an expected one.

Source code in ontocast/tool/facts_validation/terms.py
def domain_fits(
    subject: URIRef, predicate: URIRef, graph: RDFGraph, ontology_graph: RDFGraph
) -> bool:
    """Whether ``subject``'s asserted types contradict no ``rdfs:domain`` of ``predicate``.

    The test :func:`domain_violation_findings` applies: only ``rdfs:domain``
    entails, so only it can be contradicted; a listed class is an expected
    one.
    """
    declared = _declared_domains(ontology_graph, source="rdfs").get(predicate)
    if not declared:
        return True
    asserted = {t for t in graph.objects(subject, RDF.type) if isinstance(t, URIRef)}
    return (
        types_compatible(
            asserted,
            declared,
            ontology_graph,
            described=_described_classes(ontology_graph),
            closures={},
        )
        is not False
    )

domain_fitting_properties(subject, obj, graph, ontology_graph, *, replacing, limit=8)

Context properties that may link subject to obj in place of replacing.

A candidate declares a domain (rdfs:domain or schema:domainIncludes) that the subject's asserted types fit, and no range the object's types contradict; a literal object takes only a property with no class range. Ranked by the local-name tokens shared with replacing, then by IRI.

Returns:

Type Description
list[tuple[URIRef, set[URIRef]]]

Up to limit (property, its domain classes) pairs.

Source code in ontocast/tool/facts_validation/terms.py
def domain_fitting_properties(
    subject: URIRef,
    obj: Node,
    graph: RDFGraph,
    ontology_graph: RDFGraph,
    *,
    replacing: URIRef,
    limit: int = 8,
) -> list[tuple[URIRef, set[URIRef]]]:
    """Context properties that may link ``subject`` to ``obj`` in place of ``replacing``.

    A candidate declares a domain (``rdfs:domain`` or ``schema:domainIncludes``)
    that the subject's asserted types fit, and no range the object's types
    contradict; a literal object takes only a property with no class range.
    Ranked by the local-name tokens shared with ``replacing``, then by IRI.

    Returns:
        Up to ``limit`` (property, its domain classes) pairs.
    """
    asserted = {t for t in graph.objects(subject, RDF.type) if isinstance(t, URIRef)}
    if not asserted:
        return []
    described = _described_classes(ontology_graph)
    closures: dict[URIRef, set[URIRef]] = {}
    domains = _declared_domains(ontology_graph)
    ranges = declared_class_ranges(ontology_graph)
    object_types = (
        {t for t in graph.objects(obj, RDF.type) if isinstance(t, URIRef)}
        if isinstance(obj, URIRef)
        else set()
    )
    wanted = _name_tokens(_local_name(str(replacing)))
    scored: list[tuple[int, str, URIRef, set[URIRef]]] = []
    for predicate, declared in domains.items():
        if predicate == replacing:
            continue
        fits = types_compatible(
            asserted, declared, ontology_graph, described=described, closures=closures
        )
        if fits is not True:
            continue
        declared_range = ranges.get(predicate)
        if isinstance(obj, Literal):
            if declared_range:
                continue
        elif declared_range and object_types:
            if (
                types_compatible(
                    object_types,
                    declared_range,
                    ontology_graph,
                    described=described,
                    closures=closures,
                )
                is False
            ):
                continue
        shared = len(wanted & _name_tokens(_local_name(str(predicate))))
        scored.append((-shared, str(predicate), predicate, declared))
    scored.sort(key=lambda item: (item[0], item[1]))
    return [(predicate, declared) for _, _, predicate, declared in scored[:limit]]

expand_vocabulary_terms(vocabulary, *graphs)

Expand configured vocabulary terms (CURIEs or full IRIs) to IRI strings.

CURIEs are expanded against the prefix bindings of every graph given, in order; a CURIE whose prefix no graph binds is dropped rather than guessed.

Source code in ontocast/tool/facts_validation/terms.py
def expand_vocabulary_terms(
    vocabulary: dict[str, str] | None,
    *graphs: RDFGraph | None,
) -> set[str]:
    """Expand configured vocabulary terms (CURIEs or full IRIs) to IRI strings.

    CURIEs are expanded against the prefix bindings of every graph given, in
    order; a CURIE whose prefix no graph binds is dropped rather than guessed.
    """
    terms: set[str] = set()
    if not vocabulary:
        return terms
    bindings: dict[str, str] = {}
    for graph in graphs:
        if graph is None:
            continue
        for prefix, uri in graph.namespaces():
            if prefix:
                bindings.setdefault(prefix, str(uri))
    for term in vocabulary.values():
        if not term:
            continue
        if term.startswith("http://") or term.startswith("https://"):
            terms.add(term)
            continue
        prefix, separator, local = term.partition(":")
        if separator and local and prefix in bindings:
            terms.add(bindings[prefix] + local)
    return terms

fact_instances(graph, fact_namespaces)

The instances a facts graph asserts.

An instance is a URIRef in one of fact_namespaces that occurs as a subject, or as the IRI object of a triple other than rdf:type, owl:sameAs. Blank nodes are never instances, and neither are the nodes the pipeline mints: chunks, reifiers and the document node (:mod:ontocast.onto.scaffolding). Triples touching a chunk or reifier are skipped, whatever their vocabulary.

Parameters:

Name Type Description Default
graph RDFGraph

Facts graph for one unit or the aggregated document.

required
fact_namespaces Sequence[str]

Namespaces holding minted instances.

required

Returns:

Type Description
set[URIRef]

set[URIRef]: The instances, in no particular order.

Source code in ontocast/tool/facts_validation/terms.py
def fact_instances(graph: RDFGraph, fact_namespaces: Sequence[str]) -> set[URIRef]:
    """The instances a facts graph asserts.

    An instance is a ``URIRef`` in one of ``fact_namespaces`` that occurs as a
    subject, or as the IRI object of a triple other than ``rdf:type``,
    ``owl:sameAs``. Blank nodes are never instances, and neither are the
    nodes the pipeline mints: chunks, reifiers and the document node
    (:mod:`ontocast.onto.scaffolding`). Triples touching a chunk or reifier
    are skipped, whatever their vocabulary.

    Args:
        graph: Facts graph for one unit or the aggregated document.
        fact_namespaces: Namespaces holding minted instances.

    Returns:
        set[URIRef]: The instances, in no particular order.
    """
    namespaces = [ns for ns in fact_namespaces if ns]
    if not namespaces:
        return set()
    scaffolding = scaffolding_nodes(graph)
    minted = scaffolding | document_nodes(graph)
    instances: set[URIRef] = set()
    for subject, predicate, obj in graph:
        if is_scaffolding((subject, predicate, obj), scaffolding):
            continue
        if isinstance(subject, URIRef) and _in_fact_scope(subject, namespaces):
            instances.add(subject)
        if (
            isinstance(obj, URIRef)
            and predicate != RDF.type
            and predicate not in _HANDLE_PREDICATES
            and _in_fact_scope(obj, namespaces)
        ):
            instances.add(obj)
    return instances - minted

is_value_node(graph, node, value_classes)

Whether a type of node is a value class (see :meth:CatalogRoles.value_classes).

Source code in ontocast/tool/facts_validation/terms.py
def is_value_node(graph: RDFGraph, node: Node, value_classes: frozenset[str]) -> bool:
    """Whether a type of ``node`` is a value class (see :meth:`CatalogRoles.value_classes`)."""
    return any(str(t) in value_classes for t in graph.objects(node, RDF.type))

Context object properties that may link node to another instance.

A property qualifies with node as its subject when its declared domain (rdfs:domain or schema:domainIncludes) fits node's asserted types and it has a class range; as its object when its class range fits them. Ordered by IRI, subject direction first.

Returns:

Type Description
list[tuple[URIRef, str]]

Up to limit (property, "from" or "to") pairs: from

list[tuple[URIRef, str]]

when node is the subject.

Source code in ontocast/tool/facts_validation/terms.py
def link_properties(
    node: URIRef,
    graph: RDFGraph,
    ontology_graph: RDFGraph,
    *,
    limit: int = 8,
) -> list[tuple[URIRef, str]]:
    """Context object properties that may link ``node`` to another instance.

    A property qualifies with ``node`` as its subject when its declared domain
    (``rdfs:domain`` or ``schema:domainIncludes``) fits ``node``'s asserted
    types and it has a class range; as its object when its class range fits
    them. Ordered by IRI, subject direction first.

    Returns:
        Up to ``limit`` (property, ``"from"`` or ``"to"``) pairs: ``from``
        when ``node`` is the subject.
    """
    asserted = {t for t in graph.objects(node, RDF.type) if isinstance(t, URIRef)}
    if not asserted:
        return []
    described = _described_classes(ontology_graph)
    closures: dict[URIRef, set[URIRef]] = {}
    domains = _declared_domains(ontology_graph)
    ranges = declared_class_ranges(ontology_graph)

    def fits(declared: set[URIRef] | None) -> bool:
        return bool(declared) and (
            types_compatible(
                asserted,
                declared or set(),
                ontology_graph,
                described=described,
                closures=closures,
            )
            is True
        )

    found: list[tuple[URIRef, str]] = []
    for predicate in sorted(ranges, key=str):
        if fits(domains.get(predicate)):
            found.append((predicate, "from"))
    for predicate in sorted(ranges, key=str):
        if fits(ranges.get(predicate)):
            found.append((predicate, "to"))
    return found[:limit]

resolve_unique_surface(index, text)

The single IRI declaring text as a surface form, if exactly one does.

Source code in ontocast/tool/facts_validation/terms.py
def resolve_unique_surface(index: dict[str, set[str]], text: str) -> URIRef | None:
    """The single IRI declaring ``text`` as a surface form, if exactly one does."""
    candidates = index.get(text.strip(), set())
    if len(candidates) != 1:
        return None
    return URIRef(next(iter(candidates)))

sole_listed_classes(ontology_graph, side, declared)

Predicate -> the one class its schema:<side>Includes lists.

Listed classes are alternatives, so they entail nothing in general; a predicate listing exactly one named class, and declaring no rdfs counterpart, leaves one reading.

Parameters:

Name Type Description Default
ontology_graph RDFGraph

Ontology context.

required
side Side

domain or range.

required
declared Mapping[URIRef, set[URIRef]]

The predicate's rdfs classes of that side; a predicate present here is left out.

required

Returns:

Type Description
dict[URIRef, URIRef]

The sole listed class per predicate; datatypes are never a class.

Source code in ontocast/tool/facts_validation/terms.py
def sole_listed_classes(
    ontology_graph: RDFGraph, side: Side, declared: Mapping[URIRef, set[URIRef]]
) -> dict[URIRef, URIRef]:
    """Predicate -> the one class its ``schema:<side>Includes`` lists.

    Listed classes are alternatives, so they entail nothing in general; a
    predicate listing exactly one named class, and declaring no ``rdfs``
    counterpart, leaves one reading.

    Args:
        ontology_graph: Ontology context.
        side: ``domain`` or ``range``.
        declared: The predicate's ``rdfs`` classes of that side; a predicate
            present here is left out.

    Returns:
        The sole listed class per predicate; datatypes are never a class.
    """
    listed = sides_by_property(ontology_graph, side, source="includes")
    return {
        predicate: next(iter(classes))
        for predicate, classes in listed.items()
        if len(classes) == 1
        and predicate not in declared
        and not is_datatype_value(next(iter(classes)), ontology_graph)
    }

superclass_closure(class_iri, ontology_graph)

Asserted supertypes of class_iri, including itself.

Walks rdfs:subClassOf and steps through owl:equivalentClass intersections, because a class defined only as an intersection (LeadHalidePerovskite ≡ Perovskite ⊓ …) has no asserted subClassOf edge to its genus and would otherwise look unrelated to it.

Source code in ontocast/tool/facts_validation/terms.py
def superclass_closure(class_iri: URIRef, ontology_graph: RDFGraph) -> set[URIRef]:
    """Asserted supertypes of *class_iri*, including itself.

    Walks ``rdfs:subClassOf`` and steps through ``owl:equivalentClass``
    intersections, because a class defined only as an intersection
    (``LeadHalidePerovskite ≡ Perovskite ⊓ …``) has no asserted subClassOf edge
    to its genus and would otherwise look unrelated to it.
    """
    seen: set[URIRef] = set()
    frontier: list[Node] = [class_iri]
    while frontier:
        current = frontier.pop()
        if not isinstance(current, URIRef) or current in seen:
            continue
        seen.add(current)
        frontier.extend(ontology_graph.objects(current, RDFS.subClassOf))
        for equivalent in ontology_graph.objects(current, OWL.equivalentClass):
            for collection in ontology_graph.objects(equivalent, OWL.intersectionOf):
                frontier.extend(ontology_graph.items(collection))
    return seen

types_compatible(asserted, declared, ontology_graph, *, described, closures)

Whether a node typed asserted fits classes declared (a domain or range).

Compatible in either direction: an asserted type specializes a declared class, or a declared class specializes an asserted type. None when the context cannot decide: no declared class it places in a hierarchy (described), or an asserted type it does not describe.

Parameters:

Name Type Description Default
asserted set[URIRef]

The node's asserted types.

required
declared set[URIRef]

The declared domain or range classes.

required
ontology_graph RDFGraph

The ontology context.

required
described set[URIRef]

:func:_described_classes of ontology_graph.

required
closures dict[URIRef, set[URIRef]]

Cache of :func:superclass_closure results, filled in place.

required
Source code in ontocast/tool/facts_validation/terms.py
def types_compatible(
    asserted: set[URIRef],
    declared: set[URIRef],
    ontology_graph: RDFGraph,
    *,
    described: set[URIRef],
    closures: dict[URIRef, set[URIRef]],
) -> bool | None:
    """Whether a node typed ``asserted`` fits classes ``declared`` (a domain or range).

    Compatible in either direction: an asserted type specializes a declared
    class, or a declared class specializes an asserted type. ``None`` when the
    context cannot decide: no declared class it places in a hierarchy
    (``described``), or an asserted type it does not describe.

    Args:
        asserted: The node's asserted types.
        declared: The declared domain or range classes.
        ontology_graph: The ontology context.
        described: :func:`_described_classes` of ``ontology_graph``.
        closures: Cache of :func:`superclass_closure` results, filled in place.
    """
    declared = {value for value in declared if value in described}
    if not declared or not asserted or not asserted <= described:
        return None

    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]

    declared_closure = set().union(*(closure(value) for value in declared))
    return any(
        closure(asserted_type) & declared or asserted_type in declared_closure
        for asserted_type in asserted
    )

untyped_instances(graph, fact_namespaces)

Instances of graph (:func:fact_instances) with no concrete type.

Returns:

Type Description
list[URIRef]

list[URIRef]: The untyped instances, ordered by IRI.

Source code in ontocast/tool/facts_validation/terms.py
def untyped_instances(graph: RDFGraph, fact_namespaces: Sequence[str]) -> list[URIRef]:
    """Instances of ``graph`` (:func:`fact_instances`) with no concrete type.

    Returns:
        list[URIRef]: The untyped instances, ordered by IRI.
    """
    return sorted(
        (
            instance
            for instance in fact_instances(graph, fact_namespaces)
            if not concrete_types(graph, instance, fact_namespaces)
        ),
        key=str,
    )

value_class_base(configured, bindings)

The well-known value classes plus the deployment's configured one.

Parameters:

Name Type Description Default
configured dict[str, str] | None

FACTS_QUANTITY_FALLBACK_VOCABULARY; its value_class role, a CURIE or an IRI, names the deployment's value class.

required
bindings dict[str, str]

Prefix -> namespace, to expand a CURIE.

required
Source code in ontocast/tool/facts_validation/terms.py
def value_class_base(
    configured: dict[str, str] | None, bindings: dict[str, str]
) -> frozenset[str]:
    """The well-known value classes plus the deployment's configured one.

    Args:
        configured: ``FACTS_QUANTITY_FALLBACK_VOCABULARY``; its ``value_class``
            role, a CURIE or an IRI, names the deployment's value class.
        bindings: Prefix -> namespace, to expand a CURIE.
    """
    base = set(well_known_value_classes())
    term = (configured or {}).get("value_class", "")
    if term.startswith(("http://", "https://")):
        base.add(term)
    elif term:
        prefix, _, local = term.partition(":")
        if local and prefix in bindings:
            base.add(bindings[prefix] + local)
    return frozenset(base)