ontoenv module

class ontoenv.OntoEnv(path=None, recreate=False, create_or_use_cached=False, read_only=False, search_directories=None, require_ontology_names=False, strict=False, offline=False, use_cached_ontologies=False, resolution_policy=Ellipsis, root=Ellipsis, includes=None, excludes=None, include_ontologies=None, exclude_ontologies=None, temporary=False, remote_cache_ttl_secs=None, graph_store=None, init_from_store=False)

Bases: object

add(location, overwrite=False, fetch_imports=True, force=False)

Add a new ontology to the OntoEnv

add_no_imports(location, overwrite=False, force=False)

Add a new ontology to the OntoEnv without exploring owl:imports.

close()
dump(includes=None)

Print the contents of the OntoEnv

flush()
get_closure(uri, destination_graph=None, rewrite_sh_prefixes=True, remove_owl_imports=True, recursion_depth=Ellipsis)

Merge the imports closure of uri into a single graph and return it alongside the closure list.

The first element of the returned tuple is either the provided destination_graph (after mutation) or a brand-new rdflib.Graph. The second element is an ordered list of ontology IRIs in the resolved closure starting with uri. Set rewrite_sh_prefixes or remove_owl_imports to control post-processing of the merged triples.

get_dependencies(graph, graph_name=None, recursion_depth=Ellipsis, fetch_missing=False)

Get the dependency closure of a given graph and return it as a new graph.

This method will look for owl:imports statements in the provided graph, then find those ontologies within the OntoEnv and compute the full dependency closure. The triples of all ontologies in the closure are returned as a new graph. The original graph is never modified.

Parameters:
  • graph (rdflib.Graph) – The graph to find dependencies for.

  • graph_name (Optional[str]) – If provided, all owl:Ontology declarations from the closure are replaced with a single one for this URI and sh:prefixes are rewritten to point at it. If None (default), each ontology in the closure retains its own owl:Ontology declaration (a proper union of the closure graphs); sh:prefixes are left distributed and no root is imposed.

  • recursion_depth (int) – The maximum depth for recursive import resolution. A negative value (default) means no limit.

  • fetch_missing (bool) – If True, will fetch ontologies that are not in the environment.

Returns:

A tuple containing the populated dependency graph and the sorted list of imported ontology IRIs.

Return type:

tuple[rdflib.Graph, list[str]]

get_graph(uri)

Get the graph with the given URI as an rdflib.Graph

get_importers(uri)

Get the names of all ontologies that import the given ontology

get_namespaces(ontology=None, include_closure=False)

Get namespace prefix mappings.

Prefixes are extracted from both parser-level declarations (@prefix in Turtle, PREFIX in SPARQL-style syntaxes, XML namespace declarations) and SHACL sh:declare entries. SHACL entries take precedence when the same prefix appears in both sources.

Parameters:
  • ontology – The IRI of the ontology to query. If None, returns merged namespaces from every ontology in the environment.

  • include_closure – When True, namespaces from the full transitive owl:imports closure of the ontology are included. Ignored when ontology is None.

Returns:

A dict[str, str] mapping prefix names (e.g. "owl") to namespace IRIs (e.g. "http://www.w3.org/2002/07/owl#").

get_ontology(uri)

Get the ontology metadata with the given URI

get_ontology_names()

Get the names of all ontologies in the OntoEnv

import_dependencies(graph, recursion_depth=Ellipsis, fetch_missing=False)

Import the dependencies referenced by owl:imports triples in graph.

When fetch_missing is true, the environment attempts to download unresolved imports before computing the closure. After merging the closure triples into graph, all owl:imports statements are removed. The returned list contains the deduplicated ontology IRIs that were successfully imported.

import_graph(destination_graph, uri, recursion_depth=Ellipsis)
is_offline()
is_strict()
list_closure(uri, recursion_depth=Ellipsis)

List the ontologies in the imports closure of the given ontology.

uri may be either:

  • a string IRI of an ontology already in the environment, or

  • an rdflib.Graph that has not yet been added to the environment. In that case the closure is computed from the graph’s owl:imports declarations without modifying the environment.

missing_imports(uri=None)

Return IRIs of imports that cannot be resolved in the environment.

uri may be:

  • None — scans every ontology in the environment and returns the union of all unresolvable imports (de-duplicated).

  • a string IRI of an ontology already in the environment — walks its full transitive closure and returns every unresolvable import IRI.

  • an rdflib.Graph not yet in the environment — extracts its direct owl:imports, then for each import that is in the environment walks that import’s closure. Imports absent from the environment are themselves reported as missing.

refresh_from_store()

Re-reads all graphs from the attached graph store and rebuilds the environment’s ontology metadata and import dependency graph. Call this whenever the graph store has been mutated externally and you need OntoEnv’s view to catch up.

requires_ontology_names()
resolution_policy()
set_offline(offline)
set_require_ontology_names(require)
set_resolution_policy(policy)
set_strict(strict)
snapshot_as_dataset(backend='auto', store=None)

Return a point-in-time rdflib.Dataset view of the environment.

The Dataset is read-only and reflects the state of the env at the time of the call. Call again (or refresh_dataset_from_env) after env.flush() to pick up subsequent changes.

Parameters:
  • backend"auto" (default) picks "rdf5d" when a persistent .ontoenv/store.r5tu exists and "copy" otherwise. "rdf5d" forces the zero-copy mmap-backed path and raises ValueError for temporary or graph_store=-backed envs. "copy" always materializes the env into an in-memory snapshot.

  • store – Optional existing rdflib.Store to bind the Dataset to.

store_path()
to_rdflib_dataset(mode='auto')

Deprecated alias for snapshot_as_dataset(). Emits DeprecationWarning and delegates with backend=mode.

update(all=False)
class ontoenv.OntoEnvStore(*args, **kwargs)[source]

Bases: Store

A read-only rdflib Store backed by an OntoEnv snapshot.

SPARQL queries are executed by the Rust backend rather than rdflib’s Python query engine. Writes (add, addN, remove) raise ValueError — snapshots are immutable; mutate the underlying ontoenv.OntoEnv and call refresh_dataset_from_env() instead.

Construct via from_env() or, more commonly, via env.snapshot_as_dataset(). Creating an OntoEnvStore() directly yields an empty store, which is mostly useful as the rdflib plugin Graph(store='ontoenv').

Parameters:
  • configuration (str | None)

  • identifier (Identifier | None)

add(triple, context, quoted=False)[source]
Parameters:
Return type:

None

addN(quads)[source]
Parameters:

quads (Iterable[tuple[rdflib.term.Identifier, rdflib.term.Identifier, rdflib.term.Identifier, Any]])

Return type:

None

add_graph(graph)[source]
Parameters:

graph (Any)

Return type:

None

bind(prefix, namespace, override=True)[source]
Parameters:
Return type:

None

close(commit_pending_transaction=False)[source]
Parameters:

commit_pending_transaction (bool)

Return type:

None

commit()[source]
Return type:

None

context_aware: bool = True
contexts(triple=None)[source]
Parameters:

triple (tuple[rdflib.term.Identifier, rdflib.term.Identifier, rdflib.term.Identifier] | None)

Return type:

Generator[Any | None, None, None]

destroy(configuration)[source]
Parameters:

configuration (str)

Return type:

None

formula_aware: bool = False
classmethod from_env(env, mode='auto')[source]

Build a new OntoEnvStore and bind it to a snapshot of env.

Parameters:
  • env (Any)

  • mode (Literal['auto', 'rdf5d', 'copy'])

Return type:

OntoEnvStore

graph_aware: bool = True
namespace(prefix)[source]
Parameters:

prefix (str)

Return type:

URIRef | None

namespaces()[source]
Return type:

Iterable[tuple[str, rdflib.URIRef]]

open(configuration, create=False)[source]
Parameters:
  • configuration (str | None)

  • create (bool)

Return type:

int

prefix(namespace)[source]
Parameters:

namespace (rdflib.URIRef)

Return type:

str | None

query(query, initNs, initBindings, queryGraph, **kwargs)[source]
Parameters:
Return type:

rdflib.query.Result

refresh_from_env(env, mode=None)[source]

Rebind this store to a fresh snapshot of env.

If mode is omitted, the previously chosen backend is reused (or "auto" on first call). Namespace bindings are cleared and re-populated from env.get_namespaces().

Parameters:
  • env (Any)

  • mode (Literal['auto', 'rdf5d', 'copy'] | None)

Return type:

None

remove(triple_pattern, context=None)[source]
Parameters:
  • triple_pattern (tuple[Identifier | None, Identifier | None, Identifier | None])

  • context (Any | None)

Return type:

None

remove_graph(graph)[source]
Parameters:

graph (Any)

Return type:

None

rollback()[source]
Return type:

None

transaction_aware: bool = False
triples(triple_pattern, context=None)[source]
Parameters:
  • triple_pattern (tuple[Identifier | None, Identifier | None, Identifier | None])

  • context (Any | None)

Return type:

Generator[tuple[tuple[Identifier, Identifier, Identifier], Generator[Any | None, None, None]], None, None]

update(update, initNs, initBindings, queryGraph, **kwargs)[source]
Parameters:
Return type:

None

class ontoenv.Ontology

Bases: object

id
imports
last_updated
location
name
namespace_map
version_properties
ontoenv.dataset_from_env(env, store=None, mode='auto')[source]

Return an rdflib.Dataset backed by an OntoEnv snapshot.

Prefer env.snapshot_as_dataset(backend=..., store=...) in user code; this function is the underlying implementation.

Parameters:
  • env (Any) – An ontoenv.OntoEnv instance.

  • store (Store | None) – Optional existing rdflib Store to bind the Dataset to. If None, a fresh OntoEnvStore is created. If an OntoEnvStore is passed, it is refreshed against env using mode. If any other Store is passed, mode='rdf5d' is rejected and the env is copied into the store via rdflib.

  • mode (Mode) – "auto", "rdf5d", or "copy". See the module docstring.

Returns:

A read-only rdflib.Dataset whose named graphs are keyed by ontology IRI, with namespaces bound from the env.

Return type:

Dataset

ontoenv.refresh_dataset_from_env(dataset, env)[source]

Re-snapshot env into an existing OntoEnvStore-backed dataset.

Snapshots are point-in-time; subsequent env.add() / env.flush() calls aren’t reflected in the Dataset until you call this. The originally chosen backend (rdf5d vs copy) is preserved.

Raises:

TypeError – if dataset.store is not an OntoEnvStore.

Parameters:
Return type:

None

ontoenv.run_cli(args)

Run the Rust CLI implementation and return its process-style exit code.