} url = "https://www.ebi.ac.uk/europepmc/webservices/rest/search?" + urllib.parse.urlencode(params) with urllib.request.urlopen(url, timeout=30) as resp: data = json.loads(resp.read().decode("utf-8")) results, total, fetched, next_cursor = _validated_europepmc_page(data, total, fetched, seen_cursors, seen_records) for r in results: pub_type = str(r.get("pubType", "")).lower() if "review" in pub_type: continue pmid = r.get("pmid") if pmid: pmids.add(str(pmid)) elif r.get("source") == "PPR": preprints.append({ "id": r.get("id"), "doi": r.get("doi"), "title": r.get("title"), "pub_year": r.get("pubYear"), "authorString": r.get("authorString"), "journal": r.get("bookOrReportDetails", {}).get("publisher", "Preprint"), }) if next_cursor is None: break cursor = next_cursor time.sleep(0.35) else: raise ValueError("Europe PMC page budget exhausted before retrieval completion; partition the query or increase the explicit budget") return pmids, preprints def elink_citation_snowball(seed_pmids: list[str]) -> tuple[set[str], set[str]]: """Uses NCBI ELink to retrieve all primary PubMed articles that cite OR are cited by the 42 Golden Seeds.""" params = { "dbfrom": "pubmed", "db": "pubmed", "id": ",".join(seed_pmids), "linkname": "pubmed_pubmed_citedin,pubmed_pubmed_refs", "retmode": "json", } api_key = os.environ.get("NCBI_API_KEY") if api_key: params["api_key"] = api_key url = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/elink.fcgi?" + urllib.parse.urlencode(params) with urllib.request.urlopen(url, timeout=45) as resp: data = json.loads(resp.read().decode("utf-8")) cited_by: set[str] = set() refs: set[str] = set() for lset in data.get("linksets", []): for db in lset.get("linksetdbs", []): lname = db.get("linkname", "") links = [str(x) for x in db.get("links", [])] if lname == "pubmed_pubmed_citedin": cited_by.update(links) elif lname == "pubmed_pubmed_refs": refs.update(links) time.sleep(0.35) return cited_by, refs def europepmc_search_patents(query: str, max_pages: int = 5) -> list[dict]: """Queries Europe PMC REST API for patent records (SRC:PAT).""" if type(max_pages) is not int or max_pages <= 0: raise ValueError("Europe PMC page budget must be a positive integer") patents_by_id: dict[str, dict] = {} cursor = "*" total, fetched, seen_cursors = None, 0, {cursor} seen_records: set[tuple[str, str]] = set() for _ in range(max_pages): params = { "query": query, "format": "json", "pageSize": "1000", "resultType": "lite", "cursorMark": cursor, } url = "https://www.ebi.ac.uk/europepmc/webservices/rest/search?" + urllib.parse.urlencode(params) with urllib.request.urlopen(url, timeout=30) as resp: data = json.loads(resp.read().decode("utf-8")) results, total, fetched, next_cursor = _validated_europepmc_page(data, total, fetched, seen_cursors, seen_records) for r in results: if r.get("source") == "PAT": pat_id = str(r.get("id", "")) if pat_id and pat_id not in patents_by_id: patents_by_id[pat_id] = { "id": pat_id, "title": r.get("title"), "pub_year": r.get("pubYear"), "authorString": r.get("authorString"), "patent_source": r.get("source"), } if next_cursor is None: break cursor = next_cursor time.sleep(0.35) else: raise ValueError("Europe PMC page budget exhausted before retrieval completion; partition the query or increase the explicit budget") return list(patents_by_id.values()) def geo_gds_search_datasets(queries: dict[str, str]) -> tuple[list[dict], set[str]]: """Queries NCBI GEO DataSets (db=gds) for GSE series, filters out amyloid-beta/TGF-beta false positives, and extracts linked PubMed IDs.""" gds_id_to_categories: dict[str, list[str]] = {} api_key = os.environ.get("NCBI_API_KEY") for q_name, q_str in queries.items(): params = { "db": "gds", "term": q_str, "retmode": "json", "retmax": "2000", } if api_key: params["api_key"] = api_key url = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?" + urllib.parse.urlencode(params) with urllib.request.urlopen(url, timeout=30) as resp: data = json.loads(resp.read().decode("utf-8")) result = data.get("esearchresult", {}) id_list = result.get("idlist", []) count = result.get("count") if (not isinstance(count, str) or not count.isascii() or not count.isdigit() or not isinstance(id_list, list) or any(not isinstance(uid, str) or not uid.isascii() or not uid.isdigit() or int(uid) <= 0 for uid in id_list) or len(set(id_list)) != len(id_list)): raise ValueError("GEO search response has invalid count or identifiers") if len(id_list) != int(count): raise ValueError("GEO search retrieval is incomplete; partition the query before claiming complete discovery") print(f"[GEO GDS] {q_name}: {len(id_list)} raw GSE series") for gid in id_list: gds_id_to_categories.setdefault(str(gid), []).append(q_name) time.sleep(0.35) all_gds_ids = sorted(gds_id_to_categories.keys(), reverse=True) datasets: list[dict] = [] linked_pmids: set[str] = set() batch_size = 200 islet_terms = ( "islet", "pancrea", "sc-beta", "sc-islet", "beta-cell", "beta cell", "β-cell", "β cell", "beta-like", "β-like", "endoc-betah", "endoc-βh", "min6", "nit-1", "ins-1", "hpap", "npod", "insulin-producing", "insulin-secreting", "endocrine progenitor", ) for i in range(0, len(all_gds_ids), batch_size): chunk = all_gds_ids[i : i + batch_size] params = { "db": "gds", "id": ",".join(chunk), "retmode": "json", } if api_key: params["api_key"] = api_key url = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi" data_bytes = urllib.parse.urlencode(params).encode("utf-8") req = urllib.request.Request(url, data=data_bytes, method="POST") with urllib.request.urlopen(req, timeout=45) as resp: sdata = json.loads(resp.read().decode("utf-8")) res_map = sdata.get("result", {}) for gid in chunk: item = res_map.get(gid) if not isinstance(item, dict) or item.get("error"): raise ValueError(f"GEO metadata response is missing or rejected requested identifier {gid}") title_str = item.get("title", "") or "" summary_str = item.get("summary", "") or "" combined_lower = (title_str + " " + summary_str).lower() # Exclude NCBI GDS hyphen-split false positives (e.g. amyloid-beta, TGF-beta in brain/liver) if not any(term in combined_lower for term in islet_terms): continue acc = item.get("accession", "") pmids_for_gse = [str(p) for p in item.get("pubmedids", []) if p] linked_pmids.update(pmids_for_gse) datasets.append({ "gds_uid": gid, "accession": acc, "title": title_str, "summary": summary_str[:400], "taxon": item.get("taxon", ""), "gds_type": item.get("gdstype", ""), "n_samples": item.get("n_samples", 0), "pub_date": item.get("pdat", ""), "pubmed_ids": pmids_for_gse, "matched_geo_queries": gds_id_to_categories.get(gid, []), }) time.sleep(0.35) return datasets, linked_pmids def compute_overlap_breakdown(pillar_map: dict[str, list[str]]) -> dict: """Computes multi-pillar and multi-gate overlap statistics across all discovered PMIDs.""" subpillar_count_hist: dict[int, int] = {} major_pillar_count_hist: dict[int, int] = {} major_pairwise: dict[str, int] = {} def get_major_pillars(tags: list[str]) -> set[str]: maj: set[str] = set() for t in tags: if t.startswith("Pillar1"): maj.add("P1_Differentiation_Cytoarchitecture") elif t.startswith("Pillar2"): maj.add("P2_Allo_Auto_Cloaking") elif t.startswith("Pillar3"): maj.add("P3_Intrinsic_Stress_Amyloid_Viral_HPAP") elif t.startswith("Pillar4"): maj.add("P4_Engraftment_Vascularization") return maj sc_islet_multi_gate = { "P1A_SC_Islet_total": 0, "P1A_and_P2_Cloaking": 0, "P1A_and_P3_Intrinsic_Targets": 0, "P1A_and_P4_Engraftment_Vascular": 0, "P1A_and_2plus_other_Major_Pillars": 0, "All_4_Major_Pillars_Simultaneously": 0, } high_density_pmids_3plus_subpillars: list[str] = [] major_labels = [ "P1_Differentiation_Cytoarchitecture", "P2_Allo_Auto_Cloaking", "P3_Intrinsic_Stress_Amyloid_Viral_HPAP", "P4_Engraftment_Vascularization", ] for pmid, tags in pillar_map.items(): core_tags = [t for t in tags if t.startswith("Pillar1") or t.startswith("Pillar2") or t.startswith("Pillar3") or t.startswith("Pillar4")] n_sub = len(core_tags) subpillar_count_hist[n_sub] = subpillar_count_hist.get(n_sub, 0) + 1 if n_sub >= 3: high_density_pmids_3plus_subpillars.append(pmid) maj = get_major_pillars(tags) n_maj = len(maj) major_pillar_count_hist[n_maj] = major_pillar_count_hist.get(n_maj, 0) + 1 if n_maj == 4: sc_islet_multi_gate["All_4_Major_Pillars_Simultaneously"] += 1 for i in range(len(major_labels)): for j in range(i + 1, len(major_labels)): if major_labels[i] in maj and major_labels[j] in maj: pair_key = f"{major_labels[i]}__x__{major_labels[j]}" major_pairwise[pair_key] = major_pairwise.get(pair_key, 0) + 1 if "Pillar1A_SC_Islet_Differentiation_Maturation" in tags: sc_islet_multi_gate["P1A_SC_Islet_total"] += 1 if "P2_Allo_Auto_Cloaking" in maj: sc_islet_multi_gate["P1A_and_P2_Cloaking"] += 1 if "P3_Intrinsic_Stress_Amyloid_Viral_HPAP" in maj: sc_islet_multi_gate["P1A_and_P3_Intrinsic_Targets"] += 1 if "P4_Engraftment_Vascularization" in maj: sc_islet_multi_gate["P1A_and_P4_Engraftment_Vascular"] += 1 if len(maj - {"P1_Differentiation_Cytoarchitecture"}) >= 2: sc_islet_multi_gate["P1A_and_2plus_other_Major_Pillars"] += 1