Skip to content

Commit

Permalink
NXOntology.root property
Browse files Browse the repository at this point in the history
  • Loading branch information
dhimmel committed Mar 11, 2022
1 parent 6b6829c commit 3a0cd3a
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 1 deletion.
14 changes: 14 additions & 0 deletions nxontology/ontology.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,20 @@ def roots(self) -> Set[Node]:
roots.add(node)
return roots

@property
def root(self) -> Node:
"""
Sole root of this directed acyclic graph.
If this ontology has multiple roots, raise ValueError.
This function is intended as a convenience function for ontologies that are weakly connected,
meaning all nodes derive from a single root.
"""
roots = self.roots
if len(roots) == 1:
(root,) = roots
return root
raise ValueError("Ontology has multiple roots.")

@property # type: ignore [misc]
@cache_on_frozen
def leaves(self) -> Set[Node]:
Expand Down
8 changes: 7 additions & 1 deletion nxontology/tests/conftest.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import pytest

from nxontology import NXOntology
from nxontology.examples import create_metal_nxo
from nxontology.examples import create_disconnected_nxo, create_metal_nxo


@pytest.fixture
Expand All @@ -20,3 +20,9 @@ def metal_nxo_frozen() -> NXOntology[str]:
metal_nxo = create_metal_nxo()
metal_nxo.freeze()
return metal_nxo


@pytest.fixture
def disconnected_nxo() -> NXOntology[str]:
"""Returns a newly created disconnected ontology for each test."""
return create_disconnected_nxo()
8 changes: 8 additions & 0 deletions nxontology/tests/ontology_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ def test_nxontology_check_is_dag(metal_nxo: NXOntology[str]) -> None:
def test_nxontology_roots(metal_nxo_frozen: NXOntology[str]) -> None:
roots = metal_nxo_frozen.roots
assert roots == {"metal"}
assert metal_nxo_frozen.root == "metal"


def test_nxontology_leaves(metal_nxo_frozen: NXOntology[str]) -> None:
Expand All @@ -89,6 +90,13 @@ def test_nxontology_isolates() -> None:
assert {"a", "b"} == nxo.isolates


def test_nxontology_disconnected(disconnected_nxo: NXOntology[str]) -> None:
assert disconnected_nxo.roots == {"metal", "tree", "water"}
assert not networkx.is_weakly_connected(disconnected_nxo.graph)
with pytest.raises(ValueError, match="has multiple roots"):
disconnected_nxo.root


def test_set_graph_attributes(metal_nxo: NXOntology[str]) -> None:
assert metal_nxo.name == "Metals"
metal_nxo.graph.nodes["gold"]["metal_label"] = "test_label"
Expand Down

0 comments on commit 3a0cd3a

Please sign in to comment.