Skip to content

ontocast.tool.triple_manager.util

Shared helpers for triple store backends: the catalog read, strictly.

Attributes

LIST_NAMED_GRAPHS_QUERY = '\nSELECT DISTINCT ?g WHERE {\n GRAPH ?g { ?s ?p ?o }\n}\n' module-attribute

LineageT = TypeVar('LineageT', bound=OntologyPropertiesWithLineage) module-attribute

ONTOLOGY_HEADER_QUERY = '\nPREFIX owl: <http://www.w3.org/2002/07/owl#>\nPREFIX dcterms: <http://purl.org/dc/terms/>\nPREFIX vann: <http://purl.org/vocab/vann/>\nPREFIX oc: <https://growgraph.dev/ontocast#>\nSELECT DISTINCT ?g ?onto ?versionIri ?version ?prior ?prefix ?namespace ?title ?description\n ?created ?modified ?removed\nWHERE {\n GRAPH ?g {\n ?onto a owl:Ontology .\n OPTIONAL { ?onto owl:versionIRI ?versionIri }\n OPTIONAL { ?onto owl:versionInfo ?version }\n OPTIONAL { ?onto owl:priorVersion ?prior }\n OPTIONAL { ?onto vann:preferredNamespacePrefix ?prefix }\n OPTIONAL { ?onto vann:preferredNamespaceUri ?namespace }\n OPTIONAL { ?onto dcterms:title ?title }\n OPTIONAL { ?onto dcterms:description ?description }\n OPTIONAL { ?onto dcterms:created ?created }\n OPTIONAL { ?onto dcterms:modified ?modified }\n OPTIONAL { ?g a oc:RemovedVersion . BIND(true AS ?removed) }\n }\n}\n' module-attribute

__all__ = ['CatalogContractError', 'LIST_NAMED_GRAPHS_QUERY', 'LineageT', 'ONTOLOGY_HEADER_QUERY', 'deterministic_turtle_serialization', 'head_headers', 'headers_from_select_rows', 'ontology_from_named_graph'] module-attribute

logger = logging.getLogger(__name__) module-attribute

Classes

CatalogContractError

Bases: ValueError

A stored graph does not carry the version header this library writes.

Source code in ontocast/onto/ontology_header.py
class CatalogContractError(ValueError):
    """A stored graph does not carry the version header this library writes."""

    def __init__(self, graph_uri: str, missing: Sequence[str]) -> None:
        self.graph_uri = graph_uri
        self.missing = list(missing)
        super().__init__(
            f"graph {graph_uri} is not a version of an ontology: "
            f"missing {', '.join(self.missing)}"
        )

Attributes

graph_uri = graph_uri instance-attribute
missing = list(missing) instance-attribute

Methods:

__init__(graph_uri, missing)
Source code in ontocast/onto/ontology_header.py
def __init__(self, graph_uri: str, missing: Sequence[str]) -> None:
    self.graph_uri = graph_uri
    self.missing = list(missing)
    super().__init__(
        f"graph {graph_uri} is not a version of an ontology: "
        f"missing {', '.join(self.missing)}"
    )

Functions:

deterministic_turtle_serialization(graph)

Create a deterministic Turtle serialization of an RDF graph.

Source code in ontocast/tool/triple_manager/util.py
def deterministic_turtle_serialization(graph: Graph) -> str:
    """Create a deterministic Turtle serialization of an RDF graph."""
    prefix_lines = [
        f"@prefix {p}: <{ns}> ."
        for p, ns in sorted(graph.namespace_manager.namespaces())
    ]
    triples_sorted = sorted(graph, key=lambda t: (str(t[0]), str(t[1]), str(t[2])))
    triple_lines = [
        f"{s.n3(graph.namespace_manager)} {p.n3(graph.namespace_manager)} {o.n3(graph.namespace_manager)} ."
        for s, p, o in triples_sorted
    ]
    return "\n".join(prefix_lines + [""] + triple_lines)

head_headers(headers)

One head per ontology; diverged ontologies are logged and left out.

A diverged ontology (several heads) is listed by the catalog and its versions can be read, but nothing extracts against it or extends it until a merge makes one head.

Source code in ontocast/tool/triple_manager/util.py
def head_headers(headers: Sequence[OntologyHeader]) -> list[OntologyHeader]:
    """One head per ontology; diverged ontologies are logged and left out.

    A diverged ontology (several heads) is listed by the catalog and its
    versions can be read, but nothing extracts against it or extends it
    until a merge makes one head.
    """
    single, diverged = catalog_heads(headers)
    for iri, heads in diverged.items():
        logger.error(
            "Ontology %s has %d heads (%s); it is excluded from extraction "
            "until merged",
            iri,
            len(heads),
            ", ".join(h.version_iri or h.graph_uri for h in heads),
        )
    return single

headers_from_select_rows(rows)

Fold :data:ONTOLOGY_HEADER_QUERY rows into one header per named graph.

?prior is multi-valued, so the query returns a small cross product; rows sharing a graph describe one version and are merged.

Raises:

Type Description
CatalogContractError

a graph's header is incomplete.

Source code in ontocast/tool/triple_manager/util.py
def headers_from_select_rows(rows: Iterable[dict[str, str]]) -> list[OntologyHeader]:
    """Fold :data:`ONTOLOGY_HEADER_QUERY` rows into one header per named graph.

    ``?prior`` is multi-valued, so the query returns a small cross product; rows
    sharing a graph describe one version and are merged.

    Raises:
        CatalogContractError: a graph's header is incomplete.
    """
    fields: dict[str, dict[str, list[str]]] = defaultdict(lambda: defaultdict(list))
    for row in rows:
        graph_uri = row.get("g")
        if not graph_uri:
            continue
        for name, value in row.items():
            if name == "g" or not value:
                continue
            bucket = fields[graph_uri][name]
            if value not in bucket:
                bucket.append(value)
    return [
        header_from_fields(graph_uri, fields[graph_uri]) for graph_uri in sorted(fields)
    ]

ontology_from_named_graph(graph_uri, graph)

Build the :class:Ontology stored as the version graph graph_uri.

Raises:

Type Description
CatalogContractError

the graph is not a version of an ontology. A foreign graph in an ontologies dataset is a fault, never a silent gap in the catalog.

Source code in ontocast/tool/triple_manager/util.py
def ontology_from_named_graph(graph_uri: str, graph: Graph) -> Ontology:
    """Build the :class:`Ontology` stored as the version graph ``graph_uri``.

    Raises:
        CatalogContractError: the graph is not a version of an ontology. A
            foreign graph in an ontologies dataset is a fault, never a silent
            gap in the catalog.
    """
    deterministic_graph = RDFGraph()
    deterministic_graph.parse(
        data=deterministic_turtle_serialization(graph), format="turtle"
    )
    for prefix, namespace in graph.namespaces():
        if prefix:
            deterministic_graph.bind(prefix, namespace)
    ontology = ontology_from_version_graph(graph_uri, deterministic_graph)
    logger.debug(
        "Loaded ontology %s version %s from graph %s",
        ontology.iri,
        ontology.version,
        graph_uri,
    )
    return ontology