From 72c2073f0a466d86e4cd40307dc53e3f9e31489f Mon Sep 17 00:00:00 2001 From: Nayib Gloria <55710092+nayib-jose-gloria@users.noreply.github.com> Date: Fri, 15 Mar 2024 15:00:44 -0400 Subject: [PATCH] feat: add is_valid_term_id method to OntologyParser (#115) --- .../cellxgene_ontology_guide/ontology_parser.py | 16 ++++++++++++++++ api/python/tests/test_ontology_parser.py | 7 +++++++ 2 files changed, 23 insertions(+) diff --git a/api/python/src/cellxgene_ontology_guide/ontology_parser.py b/api/python/src/cellxgene_ontology_guide/ontology_parser.py index 82e0c23f..554522e7 100644 --- a/api/python/src/cellxgene_ontology_guide/ontology_parser.py +++ b/api/python/src/cellxgene_ontology_guide/ontology_parser.py @@ -39,6 +39,22 @@ def _parse_ontology_name(self, term_id: str) -> str: return ontology_name + def is_valid_term_id(self, term_id: str) -> bool: + """ + Check if an ontology term ID is valid and defined in a supported ontology. If deprecated but defined + in the ontology, it is considered valid. + + :param term_id: str ontology term to check + :return: boolean flag indicating whether the term is supported + """ + try: + ontology_name = self._parse_ontology_name(term_id) + if term_id in self.cxg_schema.ontology(ontology_name): + return True + except ValueError: + return False + return False + def get_term_ancestors(self, term_id: str, include_self: bool = False) -> List[str]: """ Get the ancestor ontology terms for a given term. If include_self is True, the term itself will be included as diff --git a/api/python/tests/test_ontology_parser.py b/api/python/tests/test_ontology_parser.py index f368b19e..3e8d4e4d 100644 --- a/api/python/tests/test_ontology_parser.py +++ b/api/python/tests/test_ontology_parser.py @@ -73,6 +73,13 @@ def test_parse_ontology_name__not_supported(ontology_parser): ontology_parser._parse_ontology_name("GO:0000001") +@pytest.mark.parametrize( + "term_id,expected", [("CL:0000001", True), ("CL:0000003", True), ("CL:0000009", False), ("GO:0000001", False)] +) +def test_is_valid_term_id(ontology_parser, term_id, expected): + assert ontology_parser.is_valid_term_id(term_id) == expected + + def test_get_term_ancestors(ontology_parser): assert ontology_parser.get_term_ancestors("CL:0000004") == ["CL:0000000", "CL:0000001", "CL:0000002"] assert ontology_parser.get_term_ancestors("CL:0000004", include_self=True) == [