Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ensure that saving with squash removes all but current ontology #707

Merged
merged 2 commits into from
Jan 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 11 additions & 7 deletions ontopy/ontology.py
Original file line number Diff line number Diff line change
Expand Up @@ -992,20 +992,24 @@ def save(

if squash:
URIRef, RDF, OWL = rdflib.URIRef, rdflib.RDF, rdflib.OWL
iri = self.iri if self.iri else self.base_iri
graph = self.world.as_rdflib_graph()
graph.namespace_manager.bind("", rdflib.Namespace(self.base_iri))
graph.namespace_manager.bind("", rdflib.Namespace(iri))

# Remove all ontology-declarations in the graph that are
# not the current ontology.
for s, _, _ in graph.triples((None, RDF.type, OWL.Ontology)):
if str(s).rstrip("/#") != self.base_iri.rstrip("/#"):
for _, p, o in graph.triples((s, None, None)):
graph.remove((s, p, o))
graph.remove((s, OWL.imports, None))

if self.iri:
base_iri = URIRef(self.base_iri)
for s, p, o in graph.triples((base_iri, None, None)):
graph.remove((s, p, o))
graph.add((URIRef(self.iri), p, o))

# Remove anonymous namespace and imports
graph.remove((URIRef("http://anonymous"), RDF.type, OWL.Ontology))
imports = list(graph.triples((None, OWL.imports, None)))
for triple in imports:
graph.remove(triple)

graph.serialize(destination=filename, format=format)
elif format in OWLREADY2_FORMATS:
super().save(file=filename, format=fmt)
Expand Down
23 changes: 23 additions & 0 deletions tests/test_ontology_squash.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
"""Test the Ontology.save(squash=True, ...)"""


def test_ontology_squash():
import re
from pathlib import Path
from ontopy import get_ontology

repo_dir = Path(__file__).resolve().parent.parent
onto_dir = repo_dir / "tests" / "testonto"
out_dir = repo_dir / "tests" / "output"

testonto = get_ontology(onto_dir / "testonto.ttl").load()

testonto.save(out_dir / "testonto_squash.ttl", squash=True)

with open(out_dir / "testonto_squash.ttl", "r") as f:
txt = f.read()

s = re.findall(r".* a owl:Ontology", txt)
assert len(s) == 1
assert s[0].startswith("<http://emmo.info/testonto>")
assert len(re.findall(r"owl:imports", txt)) == 0