Skip to content

Commit

Permalink
Merge pull request #116 from tcmitchell/114-document-graph
Browse files Browse the repository at this point in the history
Add Document.graph()
  • Loading branch information
tcmitchell authored Oct 21, 2020
2 parents c4de873 + 2356972 commit 9962005
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 5 deletions.
19 changes: 14 additions & 5 deletions sbol3/document.py
Original file line number Diff line number Diff line change
Expand Up @@ -230,11 +230,7 @@ def write(self, fpath: str, file_format: str = None) -> None:
file_format = self._guess_format(fpath)
if file_format is None:
raise ValueError('Unable to determine file format')
graph = rdflib.Graph()
for prefix, uri in self._namespaces.items():
graph.bind(prefix, uri)
for obj in self.objects:
obj.serialize(graph)
graph = self.graph()
if file_format == SORTED_NTRIPLES:
# have RDFlib give us the ntriples as a string
nt_text = graph.serialize(format='nt')
Expand All @@ -253,6 +249,19 @@ def write(self, fpath: str, file_format: str = None) -> None:
else:
graph.serialize(fpath, format=file_format)

def graph(self) -> rdflib.Graph:
"""Convert document to an RDF Graph.
The returned graph is a snapshot of the document and will
not be updated by subsequent changes to the document.
"""
graph = rdflib.Graph()
for prefix, uri in self._namespaces.items():
graph.bind(prefix, uri)
for obj in self.objects:
obj.serialize(graph)
return graph

def bind(self, prefix: str, uri: str) -> None:
"""Bind a prefix to an RDF namespace in the written RDF document.
Expand Down
28 changes: 28 additions & 0 deletions test/test_document.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
import tempfile
import unittest

import rdflib

import sbol3

MODULE_LOCATION = os.path.dirname(os.path.abspath(__file__))
Expand Down Expand Up @@ -119,6 +121,32 @@ def test_guess_format(self):
with self.assertRaises(ValueError):
doc.write('test.foo')

def test_empty_graph(self):
# Ensure that an empty document generates an empty RDF graph
doc = sbol3.Document()
g = doc.graph()
self.assertEqual(0, len(g))

def test_graph(self):
doc = sbol3.Document()
doc.add(sbol3.Component('foo', sbol3.SBO_DNA))
graph = doc.graph()
self.assertEqual(3, len(graph))
subjects = set()
predicates = set()
for s, p, _ in graph:
subjects.add(s)
predicates.add(p)
# Expecting 1 subject, the component
self.assertEqual(1, len(subjects))
# Expecting 3 predicates
self.assertEqual(3, len(predicates))
self.assertIn(rdflib.RDF.type, predicates)
# Convert predicates to strings for the remaining assertions
predicates = [str(p) for p in predicates]
self.assertIn(sbol3.SBOL_DISPLAY_ID, predicates)
self.assertIn(sbol3.SBOL_TYPE, predicates)


if __name__ == '__main__':
unittest.main()

0 comments on commit 9962005

Please sign in to comment.