indra
indra copied to clipboard
Add PyOBO Client
As an alternative to the OWL client and OBO client, which both load ontologies by their source files, the following code could be used to directly reuse any arbitrary ontology that's available through PyOBO. Alternatively, it would be possible to use PyOBO to convert the resources to an ontology file that could then be loaded with one of the pre-existing loaders. This code was originally written in #1339, but that PR was closed since this wasn't really necessary for anything.
class PyOboClient(OntologyClient):
"""A base client for data that's been grabbed via PyOBO."""
@classmethod
def update_by_prefix(
cls,
prefix: str,
include_relations: bool = False,
predicate: Optional[Callable[["pyobo.Term"], bool]] = None,
):
"""Update the JSON data by looking up the ontology through PyOBO."""
import pyobo
terms = iter(pyobo.get_ontology(prefix))
if predicate:
terms = filter(predicate, terms)
terms = sorted(terms, key=attrgetter("identifier"))
entries = [
{
'id': term.identifier,
'name': term.name,
'synonyms': [synonym.name for synonym in term.synonyms],
'xrefs': [
dict(namespace=xref.prefix, id=xref.identifier)
for xref in term.xrefs
],
'alt_ids': [
alt_id.identifier
for alt_id in term.alt_ids
],
'relations': _get_pyobo_rels(term) if include_relations else {},
}
for term in terms
]
entries = prune_standard(entries)
resource_path = get_resource_path(f'{prefix}.json')
with open(resource_path, 'w') as file:
json.dump(entries, fp=file, indent=1, sort_keys=True)
def _get_pyobo_rels(term: "pyobo.Term"):
rv = defaultdict(list)
for parent in term.parents:
rv["is_a"].append(parent.curie)
for type_def, references in term.relationships.items():
for reference in references:
rv[type_def.curie].append(reference.curie)
return dict(rv)
def prune_standard(entries):
return prune_empty_entries(
entries,
{'synonyms', 'xrefs', 'alt_ids', 'relations'},
)