File size: 3,979 Bytes
50dd82b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
"""Parse InterPro flat files into a queryable cache.

Downloads from:
- https://ftp.ebi.ac.uk/pub/databases/interpro/current_release/entry.list
- https://ftp.ebi.ac.uk/pub/databases/interpro/current_release/ParentChildTreeFile.txt

Produces:
- tmp/mcq_build/interpro_cache.json
    {
      "entries": {"IPR000169": {"type": "Active_site",
                                "name": "Cysteine peptidase, active site"}},
      "parent": {"IPR037302": "IPR000008", ...},   # child -> parent
      "children": {"IPR000008": ["IPR014705", ...]},  # parent -> children
      "roots": ["IPR000008", ...],   # entries with no parent (hierarchy roots)
    }

Parent-child tree file format:
    IPR000008::C2 domain::
    --IPR014705::Synaptotagmin-17, C2B domain::
    ----IPR037302::deeper nesting::

Indentation level = 2 * depth (each "--" pair adds one level).
"""

from __future__ import annotations

import json
import re
from pathlib import Path

HERE = Path(__file__).parent
ENTRY_LIST = HERE / "entry.list"
TREE_FILE = HERE / "ParentChildTreeFile.txt"
OUTPUT = HERE / "interpro_cache.json"

IPR_LINE_RE = re.compile(r"^(-*)(IPR\d{6})::([^:]*)::")


def parse_entries() -> dict[str, dict[str, str]]:
    """Parse entry.list → {IPR: {type, name}}."""
    entries: dict[str, dict[str, str]] = {}
    with open(ENTRY_LIST) as f:
        header = f.readline()
        assert header.startswith("ENTRY_AC"), f"unexpected header: {header!r}"
        for line in f:
            parts = line.rstrip("\n").split("\t")
            if len(parts) < 3:
                continue
            ac, etype, name = parts[0], parts[1], parts[2]
            if not ac.startswith("IPR"):
                continue
            entries[ac] = {"type": etype, "name": name}
    return entries


def parse_tree() -> tuple[dict[str, str], dict[str, list[str]], list[str]]:
    """Parse ParentChildTreeFile.txt → (parent_map, children_map, roots).

    Returns:
        parent: dict mapping child IPR → immediate parent IPR
        children: dict mapping parent IPR → list of immediate child IPRs
        roots: list of IPRs that appear as top-level entries (depth 0)
    """
    parent: dict[str, str] = {}
    children: dict[str, list[str]] = {}
    roots: list[str] = []
    # Stack of (depth, IPR) for current lineage
    stack: list[tuple[int, str]] = []

    with open(TREE_FILE) as f:
        for raw in f:
            line = raw.rstrip("\n")
            if not line:
                continue
            m = IPR_LINE_RE.match(line)
            if not m:
                continue
            dashes, ac, _name = m.group(1), m.group(2), m.group(3)
            depth = len(dashes) // 2

            # Pop stack until we find the parent depth
            while stack and stack[-1][0] >= depth:
                stack.pop()

            if stack:
                par = stack[-1][1]
                parent[ac] = par
                children.setdefault(par, []).append(ac)
            else:
                roots.append(ac)
                children.setdefault(ac, [])

            stack.append((depth, ac))
    return parent, children, roots


def main() -> int:
    entries = parse_entries()
    parent, children, roots = parse_tree()

    cache = {
        "entries": entries,
        "parent": parent,
        "children": children,
        "roots": roots,
        "stats": {
            "n_entries": len(entries),
            "n_in_hierarchy": len(parent) + len(roots),
            "n_with_children": sum(1 for v in children.values() if v),
            "n_roots": len(roots),
        },
    }

    with open(OUTPUT, "w") as f:
        json.dump(cache, f)
    print(f"Saved {OUTPUT}")
    print(f"  entries: {cache['stats']['n_entries']}")
    print(f"  hierarchy nodes: {cache['stats']['n_in_hierarchy']}")
    print(f"  roots: {cache['stats']['n_roots']}")
    print(f"  entries with children: {cache['stats']['n_with_children']}")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())