OpenIslet

scripts/harvest_corpus.py

OpenIslet.org (Project Islet-1) — Multi-Source Corpus Finder & Harvester (v0.3)

script Release v0.8.0 gen-eb955f8266035aba 60 KB · 5 sections

Use this file in any AI chat (paste-only or attachment-capable):

Download as text (.txt) Download section (.txt)

Pinned raw file: https://openislet.org/files/gen-eb955f8266035aba/scripts/harvest_corpus.py · SHA-256: c61503b386f1f486…

    return {
        "subpillar_hit_distribution": {str(k): subpillar_count_hist[k] for k in sorted(subpillar_count_hist.keys())},
        "major_pillar_hit_distribution": {str(k): major_pillar_count_hist[k] for k in sorted(major_pillar_count_hist.keys())},
        "major_pillar_pairwise_intersections": major_pairwise,
        "sc_islet_multi_gate_intersections": sc_islet_multi_gate,
        "high_density_3plus_subpillars_count": len(high_density_pmids_3plus_subpillars),
        "high_density_3plus_subpillars_sample_pmids": sorted(high_density_pmids_3plus_subpillars, reverse=True)[:50],
    }


def efetch_metadata(pmids: list[str], pillar_map: dict[str, list[str]], out_path: Path) -> int:
    if not isinstance(pmids, list) or any(not isinstance(pid, str) or not pid.isdigit() or int(pid) <= 0 for pid in pmids) or len(set(pmids)) != len(pmids):
        raise ValueError("Requested corpus PMIDs must be unique positive numeric strings")
    requested_pmids = set(pmids)
    existing_pmids: set[str] = set()
    if out_path.exists():
        with open(out_path, "r", encoding="utf-8") as fin:
            for line_number, line in enumerate(fin, 1):
                if not line.strip():
                    continue
                try:
                    record = json.loads(line)
                    pmid = record.get("pmid") if isinstance(record, dict) else None
                    if not isinstance(pmid, str) or not pmid.isdigit() or int(pmid) <= 0 or pmid in existing_pmids:
                        raise ValueError("invalid or duplicate PMID")
                    existing_pmids.add(pmid)
                except (ValueError, TypeError) as exc:
                    raise ValueError(f"Cannot resume malformed corpus {out_path.name} line {line_number}: {exc}") from exc
    if not existing_pmids <= requested_pmids:
        raise ValueError("Cannot resume a corpus containing PMIDs outside the requested query snapshot")
    remaining_pmids = [p for p in pmids if p not in existing_pmids]
    if existing_pmids:
        print(f"[RESUME] {len(existing_pmids)} PMIDs already in {out_path.name}; fetching {len(remaining_pmids)} remaining...", flush=True)
    batch_size = 200
    written = len(existing_pmids)
    needs_record_separator = out_path.exists() and out_path.stat().st_size > 0 and not out_path.read_bytes().endswith(b"\n")
    with open(out_path, "a", encoding="utf-8") as fout:
        for i in range(0, len(remaining_pmids), batch_size):
            chunk = remaining_pmids[i : i + batch_size]
            params = {
                "db": "pubmed",
                "id": ",".join(chunk),
                "retmode": "xml",
            }
            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/efetch.fcgi"
            data_bytes = urllib.parse.urlencode(params).encode("utf-8")
            xml_bytes = b""
            for attempt in range(4):
                try:
                    req = urllib.request.Request(url, data=data_bytes, method="POST")
                    with urllib.request.urlopen(req, timeout=60) as resp:
                        xml_bytes = resp.read()
                    break
                except Exception as exc:
                    if attempt == 3:
                        raise
                    print(f"  [WARN] efetch retry {attempt + 1}/3 after {exc}...", flush=True)
                    time.sleep(1.5 * (attempt + 1))
            root = ET.fromstring(xml_bytes)
            batch_records = []
            for article in root.findall(".//PubmedArticle"):
                pmid_el = article.find(".//MedlineCitation/PMID")
                pmid = pmid_el.text if pmid_el is not None else ""
                title_el = article.find(".//Article/ArticleTitle")
                title = "".join(title_el.itertext()).strip() if title_el is not None else ""
                abs_texts = [
                    "".join(el.itertext()).strip()
                    for el in article.findall(".//Article/Abstract/AbstractText")
                ]
                abstract = "\n".join(t for t in abs_texts if t)
                yr_el = article.find(".//Article/Journal/JournalIssue/PubDate/Year")
                if yr_el is None:
                    yr_el = article.find(".//Article/Journal/JournalIssue/PubDate/MedlineDate")
                pub_year = yr_el.text[:4] if (yr_el is not None and yr_el.text) else None
                jour_el = article.find(".//Article/Journal/Title")
                journal = jour_el.text if jour_el is not None else ""
                doi = None
                pmcid = None
                for aid in article.findall(".//PubmedData/ArticleIdList/ArticleId"):
                    id_type = aid.attrib.get("IdType", "")
                    if id_type == "doi":
                        doi = aid.text
                    elif id_type == "pmc":
                        pmcid = aid.text
                mesh_terms = [
                    el.text
                    for el in article.findall(".//MedlineCitation/MeshHeadingList/MeshHeading/DescriptorName")
                    if el.text
                ]
                keywords = [
                    el.text
                    for el in article.findall(".//MedlineCitation/KeywordList/Keyword")
                    if el.text
                ]
                pub_types = [
                    el.text
                    for el in article.findall(".//Article/PublicationTypeList/PublicationType")
                    if el.text
                ]
                authors = article.findall(".//Article/AuthorList/Author")
                first_author = None
                senior_author = None
                if authors:
                    fa_last = authors[0].findtext("LastName") or authors[0].findtext("CollectiveName") or ""
                    fa_init = authors[0].findtext("Initials") or ""
                    first_author = f"{fa_last} {fa_init}".strip()
                    la_last = authors[-1].findtext("LastName") or authors[-1].findtext("CollectiveName") or ""
                    la_init = authors[-1].findtext("Initials") or ""
                    senior_author = f"{la_last} {la_init}".strip()
                rec = {
                    "pmid": pmid,
                    "pmcid": pmcid,
                    "doi": doi,
                    "pub_year": int(pub_year) if (pub_year and pub_year.isdigit()) else None,
                    "journal": journal,
                    "first_author": first_author,
                    "senior_author": senior_author,
                    "title": title,
                    "abstract": abstract,
                    "mesh_terms": mesh_terms,
                    "keywords": keywords,
                    "publication_types": pub_types,
                    "matched_pillars": pillar_map.get(pmid, []),
                    "has_open_pmc_fulltext": pmcid is not None,
                }
                batch_records.append(rec)
            returned_pmids = [rec["pmid"] for rec in batch_records]
            if len(returned_pmids) != len(set(returned_pmids)) or set(returned_pmids) != set(chunk):
                raise ValueError("PubMed efetch batch must contain exactly the requested unique PMIDs; checkpoint not advanced")
            if needs_record_separator:
                fout.write("\n")
                needs_record_separator = False
            for rec in batch_records:
                fout.write(json.dumps(rec, ensure_ascii=False) + "\n")
                written += 1
            fout.flush()
            print(f"Fetched {written}/{len(pmids)} records...", flush=True)
            time.sleep(0.34)
    return written


def main() -> None:
    parser = argparse.ArgumentParser(description="Discover and harvest OpenIslet Evidence Corpus sources (v0.3).")
    parser.add_argument("--mode", choices=["core", "wide", "all_sources"], default="core", help="core (9 sub-pillars), wide (broad sensitivity), or all_sources (All 8 Channels)")
    parser.add_argument("--include-reviews", action="store_true", help="Include Review/Editorial publication types")
    parser.add_argument("--dry-run-counts", action="store_true", help="Print live counts, overlap breakdown, and specialty repo manifests without downloading full PubMed XML")
    parser.add_argument("--from-cached-ids", action="store_true", help="Skip esearch discovery and fetch XML metadata directly for PMIDs in discovered_pmids_{mode}.json")
    args = parser.parse_args()

    RAW_DIR.mkdir(parents=True, exist_ok=True)
    if args.from_cached_ids:
        id_manifest = RAW_DIR / f"discovered_pmids_{args.mode}.json"
        with open(id_manifest, "r", encoding="utf-8") as fid:
            cached = json.load(fid)
        pillar_map = cached["pmid_to_pillars"]
        all_pmids = sorted(pillar_map.keys(), reverse=True)
        out_file = RAW_DIR / f"corpus_manifest_{args.mode}.jsonl"
        print(f"[CACHED IDS] Loaded {len(all_pmids)} PMIDs from {id_manifest}. Fetching PubMed XML metadata...", flush=True)
        n_written = efetch_metadata(all_pmids, pillar_map, out_file)
        print(f"Done. Wrote {n_written} records to {out_file}", flush=True)
        return
    source_queries = WIDE_QUERIES if args.mode == "wide" else CORE_PILLARS
    pillar_map: dict[str, list[str]] = {}

    for name, q in source_queries.items():
        full_q = q if args.include_reviews else (f"({q}){NON_REVIEW_FILTER}")
        ids = esearch_pmids(full_q)
        print(f"[{args.mode.upper()}] {name}: {len(ids)} PMIDs")
        for pid in ids:
            pillar_map.setdefault(pid, []).append(name)

    pubmed_core_pmids = set(pillar_map.keys())
    print(f"\n[{args.mode.upper()}] Deduplicated PubMed Query PMIDs: {len(pubmed_core_pmids)}")

    # Golden Seed Recall Check
    caught_seeds = [s for s in GOLDEN_SEED_PMIDS if s in pubmed_core_pmids]
    missed_seeds = [s for s in GOLDEN_SEED_PMIDS if s not in pubmed_core_pmids]
    print(f"[RECALL CHECK] Golden Benchmark Seed Recall: {len(caught_seeds)}/{len(GOLDEN_SEED_PMIDS)} ({100*len(caught_seeds)/len(GOLDEN_SEED_PMIDS):.1f}%)")
    if missed_seeds:
        for ms in missed_seeds:
            print(f"  -> Missed Seed PMID:{ms} ({GOLDEN_SEED_PMIDS[ms]})")

    preprint_records: list[dict] = []
    patent_records: list[dict] = []
    geo_datasets: list[dict] = []

    if args.mode == "all_sources":
        # Channel 3 & 4: Europe PMC Full-Text Target Mentions + Preprints (bioRxiv/medRxiv)
        seen_ppr_ids: set[str] = set()
        for ep_name, ep_q in EUROPEPMC_SUPPLEMENTARY_QUERIES.items():
            ep_pmids, ep_pprs = europepmc_search_ids(ep_q)
            new_ep = ep_pmids - set(pillar_map.keys())
            print(f"[EUROPEPMC] {ep_name}: {len(ep_pmids)} PMIDs ({len(new_ep)} newly discovered) + {len(ep_pprs)} Preprints")
            for pid in ep_pmids:
                pillar_map.setdefault(pid, []).append(ep_name)
            for ppr in ep_pprs:
                ppr_id = str(ppr.get("id", ""))
                if ppr_id and ppr_id not in seen_ppr_ids:
                    seen_ppr_ids.add(ppr_id)
                    preprint_records.append(ppr)

        # Channel 5: 1-Hop Citation Snowballing (Cited-By + References of the 44 Golden Seeds)
        cited_by, refs = elink_citation_snowball(list(GOLDEN_SEED_PMIDS.keys()))
        snowball_union = cited_by | refs
        wide_union: set[str] = set()
        for w_name, w_q in WIDE_QUERIES.items():
            w_ids = esearch_pmids(f"({w_q}){NON_REVIEW_FILTER}")
            wide_union.update(w_ids)
        domain_filtered_snowball = snowball_union & wide_union
        new_snowball = domain_filtered_snowball - set(pillar_map.keys())
        print(f"[CITATION SNOWBALL] 44 Golden Seeds -> {len(cited_by)} citing + {len(refs)} referenced = {len(snowball_union)} raw PMIDs")
        print(f"[CITATION SNOWBALL] Filtered to primary islet/beta-cell/T1D domain: {len(domain_filtered_snowball)} PMIDs ({len(new_snowball)} newly discovered beyond Core 9 Sub-Pillars)")
        print(f"[WIDE-NET SENSITIVITY POOL] Total Wide-Net Union: {len(wide_union)} primary non-review PMIDs")
        for pid in domain_filtered_snowball:
            pillar_map.setdefault(pid, []).append("Pillar5_Citation_Snowball_of_44_Golden_Seeds")

        # Channel 7: Europe PMC Patent Literature (SRC:PAT)
        for pat_name, pat_q in EUROPEPMC_PATENT_QUERIES.items():
            pats = europepmc_search_patents(pat_q)
            print(f"[PATENTS] {pat_name}: {len(pats)} deduplicated patent records")
            patent_records.extend(pats)
        if patent_records:
            pat_file = RAW_DIR / "patents_sc_islets_hypoimmune.jsonl"
            with open(pat_file, "w", encoding="utf-8") as fpat:
                for pat in patent_records:
                    fpat.write(json.dumps(pat, ensure_ascii=False) + "\n")
            print(f"[PATENTS] Saved {len(patent_records)} patent records to {pat_file}")

        # Channel 8: NCBI GEO (db=gds) Functional Genomics & Single-Cell Datasets + Linked PMIDs
        geo_datasets, geo_linked_pmids = geo_gds_search_datasets(GEO_GDS_QUERIES)
        new_geo_pmids = geo_linked_pmids - set(pillar_map.keys())
        print(f"[GEO GDS] Total islet-verified GSE series: {len(geo_datasets)} | Linked PMIDs: {len(geo_linked_pmids)} ({len(new_geo_pmids)} newly discovered PMIDs)")
        for pid in geo_linked_pmids:
            pillar_map.setdefault(pid, []).append("Channel8_GEO_Functional_Genomics_Linked_PMID")
        if geo_datasets:
            geo_file = RAW_DIR / "functional_genomics_geo_datasets.json"
            with open(geo_file, "w", encoding="utf-8") as fgeo:
                json.dump({
                    "generated_at": "2026-10-20",
                    "total_gse_series": len(geo_datasets),
                    "total_linked_pmids": len(geo_linked_pmids),
                    "newly_discovered_pmids_from_geo": len(new_geo_pmids),
                    "datasets": geo_datasets,
                }, fgeo, indent=2, ensure_ascii=False)
            print(f"[GEO GDS] Saved {len(geo_datasets)} GSE dataset records to {geo_file}")

        # Save preprint manifest