|
| 1 | +"""Extract ChEBI ontology data using fastobo and build a networkx graph.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +from pathlib import Path |
| 6 | + |
| 7 | +import fastobo |
| 8 | +import networkx as nx |
| 9 | + |
| 10 | + |
| 11 | +def _chebi_id_to_str(chebi_id: str) -> str: |
| 12 | + """Convert 'CHEBI:123' to '123' (string).""" |
| 13 | + return chebi_id.split(":")[1] |
| 14 | + |
| 15 | + |
| 16 | +def _term_data(doc: "fastobo.term.TermFrame") -> dict | None: |
| 17 | + """Extract data from a single fastobo TermFrame. |
| 18 | +
|
| 19 | + Returns |
| 20 | + ------- |
| 21 | + dict or None |
| 22 | + Parsed term data, or ``None`` if the term is marked as obsolete. |
| 23 | + """ |
| 24 | + parents: list[str] = [] |
| 25 | + has_part: set[str] = set() |
| 26 | + name: str | None = None |
| 27 | + smiles: str | None = None |
| 28 | + subset: str | None = None |
| 29 | + |
| 30 | + for clause in doc: |
| 31 | + if isinstance(clause, fastobo.term.IsObsoleteClause): |
| 32 | + if clause.obsolete: |
| 33 | + return None |
| 34 | + elif isinstance(clause, fastobo.term.PropertyValueClause): |
| 35 | + pv = clause.property_value |
| 36 | + if str(pv.relation) in ( |
| 37 | + "chemrof:smiles_string", |
| 38 | + "http://purl.obolibrary.org/obo/chebi/smiles", |
| 39 | + ): |
| 40 | + smiles = pv.value |
| 41 | + elif isinstance(clause, fastobo.term.SynonymClause): |
| 42 | + if "SMILES" in clause.raw_value() and smiles is None: |
| 43 | + smiles = clause.raw_value().split('"')[1] |
| 44 | + elif isinstance(clause, fastobo.term.RelationshipClause): |
| 45 | + if str(clause.typedef) == "has_part": |
| 46 | + has_part.add(_chebi_id_to_str(str(clause.term))) |
| 47 | + elif isinstance(clause, fastobo.term.IsAClause): |
| 48 | + parents.append(_chebi_id_to_str(str(clause.term))) |
| 49 | + elif isinstance(clause, fastobo.term.NameClause): |
| 50 | + name = str(clause.name) |
| 51 | + elif isinstance(clause, fastobo.term.SubsetClause): |
| 52 | + subset = str(clause.subset) |
| 53 | + |
| 54 | + return { |
| 55 | + "id": _chebi_id_to_str(str(doc.id)), |
| 56 | + "parents": parents, |
| 57 | + "has_part": has_part, |
| 58 | + "name": name, |
| 59 | + "smiles": smiles, |
| 60 | + "subset": subset, |
| 61 | + } |
| 62 | + |
| 63 | + |
| 64 | +def build_chebi_graph(filepath: str | Path) -> nx.DiGraph: |
| 65 | + """Parse a ChEBI OBO file and build a directed graph of ontology terms. |
| 66 | +
|
| 67 | + ``xref:`` lines are stripped before parsing as they can cause fastobo |
| 68 | + errors on some ChEBI releases. Only non-obsolete CHEBI-prefixed terms |
| 69 | + are included. |
| 70 | +
|
| 71 | + **Nodes** are string CHEBI IDs (e.g. ``"1"`` for ``CHEBI:1``) with |
| 72 | + attributes ``name``, ``smiles``, and ``subset``. |
| 73 | +
|
| 74 | + **Edges** carry a ``relation`` attribute and represent: |
| 75 | +
|
| 76 | + - ``is_a`` — directed from child to parent |
| 77 | + - ``has_part`` — directed from whole to part |
| 78 | +
|
| 79 | + Parameters |
| 80 | + ---------- |
| 81 | + filepath : str or Path |
| 82 | + Path to the ChEBI OBO file. |
| 83 | +
|
| 84 | + Returns |
| 85 | + ------- |
| 86 | + nx.DiGraph |
| 87 | + Directed graph of ChEBI ontology terms and their relationships. |
| 88 | + """ |
| 89 | + with open(filepath, encoding="utf-8") as f: |
| 90 | + content = "\n".join(line for line in f if not line.startswith("xref:")) |
| 91 | + |
| 92 | + graph: nx.DiGraph = nx.DiGraph() |
| 93 | + |
| 94 | + for frame in fastobo.loads(content): |
| 95 | + if not ( |
| 96 | + frame and isinstance(frame.id, fastobo.id.PrefixedIdent) and frame.id.prefix == "CHEBI" |
| 97 | + ): |
| 98 | + continue |
| 99 | + |
| 100 | + term = _term_data(frame) |
| 101 | + if term is None: |
| 102 | + continue |
| 103 | + |
| 104 | + node_id = term["id"] |
| 105 | + graph.add_node(node_id, name=term["name"], smiles=term["smiles"], subset=term["subset"]) |
| 106 | + |
| 107 | + for parent_id in term["parents"]: |
| 108 | + graph.add_edge(node_id, parent_id, relation="is_a") |
| 109 | + |
| 110 | + for part_id in term["has_part"]: |
| 111 | + graph.add_edge(node_id, part_id, relation="has_part") |
| 112 | + |
| 113 | + return graph |
0 commit comments