Skip to content
Closed
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
23 changes: 23 additions & 0 deletions rdflib/graph.py
Original file line number Diff line number Diff line change
Expand Up @@ -951,6 +951,12 @@ def triples_choices(
):
yield s, p, o

def roots(self) -> Generator["_SubjectType", None, None]:
"""A generator of subjects that are roots of the graph"""
for s in self.subjects(unique=True):
if (None, None, s) not in self:
yield s

@overload
def value(
self,
Expand Down Expand Up @@ -1873,6 +1879,23 @@ def add_to_cbd(uri: _SubjectType) -> None:

return subgraph

def cbd_subject(self) -> Optional[_SubjectType]:
"""Determine the subject for which the graph is a Concise Bounded Description

:return: The subject of the CBD or None
"""
roots = set(self.roots())
if len(roots) != 1:
# A CBD has exactly one root
return None
root = roots.pop()

real_cbd = self.cbd(root)
if not real_cbd.isomorphic(self):
return None

return root


_ContextType = Graph

Expand Down
24 changes: 24 additions & 0 deletions test/test_graph/test_graph_cbd.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,3 +159,27 @@ def test_cbd_target(rdfs_graph: Graph):

assert result is target
assert expected_result == set(result.triples((None, None, None)))


def test_cbd_subject(get_graph):
g = get_graph

assert g.cbd(EX.R1).cbd_subject() == (
EX.R1
), "cbd_subject() for CBD of EX.R1 should be EX.R1"
assert g.cbd(EX.R2).cbd_subject() == (
EX.R2
), "cbd_subject() for CBD of EX.R2 should be EX.R2"
assert g.cbd(EX.R3).cbd_subject() == (
EX.R3
), "cbd_subject() for CBD of EX.R3 should be EX.R3"
assert g.cbd(EX.R4).cbd_subject() == (
None
), "cbd_subject() for CBD of EX.R4 should be None"

test_g = g.cbd(EX.R1)
test_g.add((EX.R2, EX.propOne, EX.P1))

assert test_g.cbd_subject() is (
None
), "cbd_subject() of graph with an additional subject should be None"