From 8b5dbe52fac04a0405364c51d0c2272759a7001c Mon Sep 17 00:00:00 2001 From: Jesper Friis Date: Wed, 24 Jan 2024 16:56:29 +0100 Subject: [PATCH] Ensure that saving with squash removes all but current ontology --- ontopy/ontology.py | 18 +++++++++++------- tests/test_ontology_squash.py | 23 +++++++++++++++++++++++ 2 files changed, 34 insertions(+), 7 deletions(-) create mode 100644 tests/test_ontology_squash.py diff --git a/ontopy/ontology.py b/ontopy/ontology.py index 908b2851c..7820ebee3 100644 --- a/ontopy/ontology.py +++ b/ontopy/ontology.py @@ -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) diff --git a/tests/test_ontology_squash.py b/tests/test_ontology_squash.py new file mode 100644 index 000000000..9809c72ce --- /dev/null +++ b/tests/test_ontology_squash.py @@ -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("") + assert len(re.findall(r"owl:imports", txt)) == 0