File size: 11,847 Bytes
7ba3101
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Build a frozen, reproducible knowledge snapshot for HypoAgent-Bio.

Sources
-------
1. PubMed E-utilities: literature abstracts for GBM / temozolomide resistance.
2. UniProt REST: structured protein cards for candidate molecules.

The script writes:
  data/kb/documents.jsonl   one PubMed abstract per line
  data/kb/entities.json     structured protein / lncRNA cards
  data/kb/manifest.json     queries, counts, timestamps, source URLs

The snapshot is committed to the repository so that retrieval, experiments and
the paper can be reproduced without network access.
"""
from __future__ import annotations

import json
import re
import sys
import time
import urllib.parse
import urllib.request
import xml.etree.ElementTree as ET
from datetime import datetime, timezone
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
KB_DIR = ROOT / "data" / "kb"
EUTILS = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils"
UNIPROT = "https://rest.uniprot.org/uniprotkb"

# Each theme has 2 complementary queries; retmax is kept small on purpose so
# that the frozen corpus stays reviewable (roughly 100 abstracts).
QUERIES: dict[str, list[str]] = {
    "mgmt": [
        "glioblastoma temozolomide resistance MGMT promoter methylation",
        "MGMT DNA repair temozolomide glioblastoma therapy response",
    ],
    "dna_damage": [
        "glioblastoma temozolomide DNA damage response apoptosis",
        "temozolomide resistance DNA mismatch repair base excision repair glioma",
    ],
    "tme": [
        "glioblastoma tumor microenvironment immunosuppression temozolomide resistance",
        "glioblastoma associated macrophage microglia temozolomide treatment",
    ],
    "singlecell": [
        "glioblastoma single-cell RNA sequencing heterogeneity temozolomide resistance",
        "glioma stem cell drug tolerance single cell transcriptomics",
    ],
    "candidate": [
        "ELFN2 glioma glioblastoma",
        "LRRC4 glioma glioblastoma",
        "TMBIM6 glioma glioblastoma",
        "SRRM1 glioma glioblastoma",
        "LINC00470 glioma glioblastoma",
        "PPP1CA glioma glioblastoma protein phosphatase 1",
    ],
    "combination": [
        "glioblastoma temozolomide combination therapy synthetic lethality",
        "glioblastoma temozolomide sensitizer blood-brain barrier",
    ],
    "biomarker": [
        "glioblastoma temozolomide resistance biomarker prediction",
        "glioblastoma molecular subtype temozolomide response",
    ],
    "plm": [
        "protein language model drug target discovery cancer",
        "deep learning protein function prediction glioma",
    ],
}

ENTITY_GENES = ["ELFN2", "PPP1CA", "SRRM1", "TMBIM6", "LRRC4"]
ENTITY_ALIASES = {
    "ELFN2": ["ELFN2", "protein phosphatase 1 regulatory subunit 29"],
    "PPP1CA": ["PPP1CA", "PP1", "PP1-alpha", "protein phosphatase 1"],
    "SRRM1": ["SRRM1", "SRm160", "serine/arginine repetitive matrix protein 1"],
    "TMBIM6": ["TMBIM6", "BI-1", "Bax inhibitor 1"],
    "LRRC4": ["LRRC4", "LRRC4A", "leucine-rich repeat-containing protein 4"],
    "LINC00470": ["LINC00470", "long intergenic non-protein coding RNA 470"],
}

HEADERS = {"User-Agent": "HypoAgent-Bio/1.0 (academic reproducibility snapshot)"}


def http_get(url: str, tries: int = 4, timeout: int = 45) -> bytes:
    last = None
    for attempt in range(tries):
        try:
            req = urllib.request.Request(url, headers=HEADERS)
            with urllib.request.urlopen(req, timeout=timeout) as fh:
                return fh.read()
        except Exception as exc:  # noqa: BLE001 - retry any transport error
            last = exc
            time.sleep(1.5 * (attempt + 1))
    raise RuntimeError(f"GET failed after {tries} tries: {url}") from last


def esearch(term: str, retmax: int = 12) -> list[str]:
    qs = urllib.parse.urlencode(
        {"db": "pubmed", "term": term, "retmax": retmax, "retmode": "json", "sort": "relevance"}
    )
    payload = json.loads(http_get(f"{EUTILS}/esearch.fcgi?{qs}"))
    return payload.get("esearchresult", {}).get("idlist", [])


def efetch(pmids: list[str]) -> list[dict]:
    if not pmids:
        return []
    qs = urllib.parse.urlencode({"db": "pubmed", "id": ",".join(pmids), "retmode": "xml"})
    xml_bytes = http_get(f"{EUTILS}/efetch.fcgi?{qs}")
    root = ET.fromstring(xml_bytes)
    docs = []
    for art in root.findall(".//PubmedArticle"):
        pmid = art.findtext(".//PMID") or ""
        title = "".join(art.find(".//ArticleTitle").itertext()) if art.find(".//ArticleTitle") is not None else ""
        abstract_parts = []
        for node in art.findall(".//Abstract/AbstractText"):
            label = node.attrib.get("Label")
            text = "".join(node.itertext()).strip()
            if text:
                abstract_parts.append(f"{label}: {text}" if label else text)
        abstract = " ".join(abstract_parts).strip()
        journal = art.findtext(".//Journal/Title") or ""
        year = art.findtext(".//JournalIssue/PubDate/Year") or ""
        if not year:
            medline = art.findtext(".//JournalIssue/PubDate/MedlineDate") or ""
            year = medline[:4] if medline else ""
        authors = []
        for a in art.findall(".//AuthorList/Author"):
            last = a.findtext("LastName") or ""
            initials = a.findtext("Initials") or ""
            if last:
                authors.append(f"{last} {initials}".strip())
        doi = ""
        for aid in art.findall(".//ArticleId"):
            if aid.attrib.get("IdType") == "doi":
                doi = (aid.text or "").strip()
                break
        if len(abstract) >= 180 and title:
            docs.append(
                {
                    "doc_id": f"PMID:{pmid}",
                    "source": "PubMed",
                    "pmid": pmid,
                    "doi": doi,
                    "title": title.strip(),
                    "abstract": abstract,
                    "journal": journal,
                    "year": year,
                    "authors": authors[:8],
                    "url": f"https://pubmed.ncbi.nlm.nih.gov/{pmid}/",
                }
            )
    return docs


def fetch_uniprot(gene: str) -> dict | None:
    q = urllib.parse.quote(f"gene_exact:{gene} AND organism_id:9606 AND reviewed:true")
    fields = "accession,protein_name,gene_names,cc_function,cc_subcellular_location,cc_disease"
    url = f"{UNIPROT}/search?query={q}&fields={fields}&format=json&size=5"
    data = json.loads(http_get(url))
    results = data.get("results", [])
    if not results:
        return None
    rec = results[0]
    functions = []
    locations = []
    diseases = []
    for comment in rec.get("comments", []):
        ctype = comment.get("commentType")
        texts = [t.get("value", "") for t in comment.get("texts", []) if t.get("value")]
        if ctype == "FUNCTION":
            functions.extend(texts)
        elif ctype == "SUBCELLULAR LOCATION":
            locations.extend(texts)
        elif ctype == "DISEASE":
            diseases.extend(texts)
    return {
        "uniprot": rec.get("primaryAccession", ""),
        "protein_name": (
            rec.get("proteinDescription", {}).get("recommendedName", {}).get("fullName", {}).get("value", "")
        ),
        "function": " ".join(functions)[:1200],
        "location": " ".join(locations)[:400],
        "disease": " ".join(diseases)[:400],
    }


def build_entities(documents: list[dict]) -> list[dict]:
    entities = []
    for gene in ENTITY_GENES:
        card = fetch_uniprot(gene)
        time.sleep(0.35)
        if not card:
            continue
        aliases = ENTITY_ALIASES.get(gene, [gene])
        evidence_ids = []
        for doc in documents:
            haystack = f"{doc['title']} {doc['abstract']}".lower()
            if any(alias.lower() in haystack for alias in aliases):
                evidence_ids.append(doc["doc_id"])
        entities.append(
            {
                "entity_id": f"GENE:{gene}",
                "gene": gene,
                "name": card["protein_name"],
                "type": "protein",
                "aliases": aliases,
                "uniprot": card["uniprot"],
                "function": card["function"],
                "location": card["location"],
                "disease": card["disease"],
                "evidence_ids": evidence_ids,
                "source_url": f"https://www.uniprot.org/uniprotkb/{card['uniprot']}/entry",
            }
        )
    # LINC00470 is a lncRNA and has no UniProt protein entry; keep a literature-only card.
    aliases = ENTITY_ALIASES["LINC00470"]
    evidence_ids = [
        d["doc_id"]
        for d in documents
        if any(a.lower() in f"{d['title']} {d['abstract']}".lower() for a in aliases)
    ]
    entities.append(
        {
            "entity_id": "GENE:LINC00470",
            "gene": "LINC00470",
            "name": "long intergenic non-protein coding RNA 470",
            "type": "lncRNA",
            "aliases": aliases,
            "uniprot": "",
            "function": "Long non-coding RNA; no UniProt protein entry. Function must be grounded in the retrieved literature evidence.",
            "location": "nucleus / cytoplasm (context dependent, see evidence)",
            "disease": "glioma / glioblastoma (see evidence)",
            "evidence_ids": evidence_ids,
            "source_url": "https://www.ncbi.nlm.nih.gov/gene/?term=LINC00470",
        }
    )
    return entities


def main() -> None:
    KB_DIR.mkdir(parents=True, exist_ok=True)
    all_docs: dict[str, dict] = {}
    manifest_queries = []
    for theme, queries in QUERIES.items():
        for query in queries:
            pmids = esearch(query)
            docs = efetch(pmids)
            added = 0
            for doc in docs:
                if doc["doc_id"] in all_docs:
                    themes = set(all_docs[doc["doc_id"]].get("themes", []))
                    themes.add(theme)
                    all_docs[doc["doc_id"]]["themes"] = sorted(themes)
                else:
                    doc["themes"] = [theme]
                    all_docs[doc["doc_id"]] = doc
                    added += 1
            manifest_queries.append(
                {"theme": theme, "query": query, "pmids": pmids, "new_documents": added}
            )
            print(f"[{theme}] {query[:60]}... -> {len(pmids)} hits, {added} new", flush=True)
            time.sleep(0.4)

    documents = sorted(all_docs.values(), key=lambda d: (d["year"], d["doc_id"]), reverse=True)
    with (KB_DIR / "documents.jsonl").open("w", encoding="utf-8") as fh:
        for doc in documents:
            fh.write(json.dumps(doc, ensure_ascii=False) + "\n")

    print(f"Fetching {len(ENTITY_GENES)} UniProt cards + LINC00470 ...", flush=True)
    entities = build_entities(documents)
    (KB_DIR / "entities.json").write_text(
        json.dumps(entities, ensure_ascii=False, indent=2), encoding="utf-8"
    )

    manifest = {
        "created_at_utc": datetime.now(timezone.utc).isoformat(),
        "n_documents": len(documents),
        "n_entities": len(entities),
        "themes": {t: sum(1 for d in documents if t in d["themes"]) for t in QUERIES},
        "queries": manifest_queries,
        "sources": {
            "literature": "NCBI PubMed E-utilities",
            "proteins": "UniProtKB REST",
        },
        "license_note": "PubMed abstracts are used for non-commercial research; cite original PMIDs.",
    }
    (KB_DIR / "manifest.json").write_text(
        json.dumps(manifest, ensure_ascii=False, indent=2), encoding="utf-8"
    )
    print(f"Done: {len(documents)} documents, {len(entities)} entity cards -> {KB_DIR}")


if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        sys.exit(130)