Skip to content

Commit 0a53a91

Browse files
committed
Add a cbd_subject() method
This method determines whether the graph is a Concise Bounded Description and, if it is, for what subject
1 parent defb286 commit 0a53a91

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

rdflib/graph.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1879,6 +1879,23 @@ def add_to_cbd(uri: _SubjectType) -> None:
18791879

18801880
return subgraph
18811881

1882+
def cbd_subject(self) -> Optional[_SubjectType]:
1883+
"""Determine the subject for which the graph is a Concise Bounded Description
1884+
1885+
:return: The subject of the CBD or None
1886+
"""
1887+
roots = set(self.roots())
1888+
if len(roots) != 1:
1889+
# A CBD has exactly one root
1890+
return None
1891+
root = roots.pop()
1892+
1893+
real_cbd = self.cbd(root)
1894+
if not real_cbd.isomorphic(self):
1895+
return None
1896+
1897+
return root
1898+
18821899

18831900
_ContextType = Graph
18841901

test/test_graph/test_graph_cbd.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -159,3 +159,27 @@ def test_cbd_target(rdfs_graph: Graph):
159159

160160
assert result is target
161161
assert expected_result == set(result.triples((None, None, None)))
162+
163+
164+
def test_cbd_subject(get_graph):
165+
g = get_graph
166+
167+
assert g.cbd(EX.R1).cbd_subject() == (
168+
EX.R1
169+
), "cbd_subject() for CBD of EX.R1 should be EX.R1"
170+
assert g.cbd(EX.R2).cbd_subject() == (
171+
EX.R2
172+
), "cbd_subject() for CBD of EX.R2 should be EX.R2"
173+
assert g.cbd(EX.R3).cbd_subject() == (
174+
EX.R3
175+
), "cbd_subject() for CBD of EX.R3 should be EX.R3"
176+
assert g.cbd(EX.R4).cbd_subject() == (
177+
None
178+
), "cbd_subject() for CBD of EX.R4 should be None"
179+
180+
test_g = g.cbd(EX.R1)
181+
test_g.add((EX.R2, EX.propOne, EX.P1))
182+
183+
assert test_g.cbd_subject() is (
184+
None
185+
), "cbd_subject() of graph with an additional subject should be None"

0 commit comments

Comments
 (0)