scripts/identify_and_stratify_corpus.py
Use this file in any AI chat (paste-only or attachment-capable):
Pinned raw file: https://openislet.org/files/gen-eb955f8266035aba/scripts/identify_and_stratify_corpus.py · SHA-256: b8d9431dd82a9f3f…
#!/usr/bin/env python3
"""
Step 2: Deterministic Data Identification, Signal Tagging & Concentric Ring Stratification
Scans all 7,703 PubMed records (6,857 initial harvest + 846 targeted blind-spot and
counter-evidence additions) in data/raw/corpus_manifest_all_sources.jsonl +
70 Preprints + 196 GEO GSE series + 114 Clinical Trials to identify:
1. Physical Data Accessibility (Open Full-Text PMC XML vs. GEO GSE Matrix vs. Abstract-Only)
2. Target Gene / Protein Mentions across our 38 prioritized Islet-1 engineering targets
3. Biological Fidelity Tier (Tier 1 Human Clinical -> Tier 2 NHP/Humanized/Human Co-Culture -> Tier 3 Human Abiotic/NSG -> Tier 4 Rodent-Only)
4. Quantitative & Effect-Modifier Signal Density
5. Concentric Extraction Priority Ring (Ring 1 Platinum Multi-Gate Core -> Ring 2 -> Ring 3 -> Ring 4)
"""
import argparse
import json
import re
from collections import Counter
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent.parent
RAW_DIR = BASE_DIR / "data" / "raw"
GOLDEN_SEED_PMIDS = {
"25303535", "27163171", "32094658", "35241836", "32846125", "37188763",
"38684699", "30412052", "24658304", "28325479", "16461897", "30853558",
"30778232", "37156915", "37043559", "38335966", "39758817", "34407395",
"32814902", "36599351", "36055241", "29844327", "30269996", "28263308",
"42690930", "26912858", "32719542", "39988068", "36289205", "32444635",
"31900242", "24584071", "31676859", "32432213", "20699420", "18753660",
"23086037", "19641142", "30074059", "23737756", "19336676", "22442301",
"33135383", "34480863", "35559682",
}
CURATED_FRONTIER_AND_COUNTEREVIDENCE_RING1_PMIDS = [
"42671571", "26276263", "41445610", "39626097", "41758964", "40757665",
"40251154", "39824805", "40112799", "40782792", "41851084", "42856627",
"41993274", "41093834", "41617975", "41951603", "36030035", "41607298",
"38754432", "41218919", "32569842", "34954144", "27626039", "35795779",
"27183617", "39529170", "37264229", "28504668", "37820008", "38508139",
"40668892",
]
CURATED_FRONTIER_SET = set(CURATED_FRONTIER_AND_COUNTEREVIDENCE_RING1_PMIDS)
CURATED_ORDER_INDEX = {
pmid: idx for idx, pmid in enumerate(CURATED_FRONTIER_AND_COUNTEREVIDENCE_RING1_PMIDS)
}
SUPERSEDED_PREPRINT_PMIDS = {
"40832357", "37502937", "38496417", "38766166", "39149298",
"39211206", "39763971", "40236391", "40777266", "41542419",
"39211191", "37886586", "41509220", "37905040",
}
PROJECT_SUMMARY_PMIDS: set[str] = set()
CITATION_ONLY_NO_ABSTRACT_PMIDS = {"42430558"}
REVIEW_PMIDS = {"35482056", "38099391", "42613697", "16435302", "41574859"}
CLINICAL_TRIAL_REPORT_PMIDS = {"40251154"}
TARGET_PATTERNS: dict[str, re.Pattern] = {
"B2M": re.compile(r"\b(b2m|beta-?2-?microglobulin|β2m)\b", re.I),
"CIITA": re.compile(r"\b(ciita)\b", re.I),
"NLRC5": re.compile(r"\b(nlrc5|cita)\b", re.I),
"HLA-C": re.compile(r"\b(hla-c|hla-c1|hla-c2)\b", re.I),
"HLA-E": re.compile(r"\b(hla-e)\b", re.I),
"HLA-G": re.compile(r"\b(hla-g)\b", re.I),
"CD47": re.compile(r"\b(cd47|sirp-?alpha|sirpα)\b", re.I),
"CD274_PDL1": re.compile(r"\b(pd-?l1|cd274)\b", re.I),
"FAS_FASL": re.compile(r"\b(fasl|fas ligand|cd95l)\b", re.I),
"CD55_CD59_CD39": re.compile(r"\b(cd55|cd59|cd39|entpd1)\b", re.I),
"FCGR1A_CD64": re.compile(r"\b(cd64|fcgr1a)\b", re.I),
"TYK2": re.compile(r"\b(tyk2)\b", re.I),
"RNLS": re.compile(r"\b(rnls|renalase)\b", re.I),
"IFIH1": re.compile(r"\b(ifih1|mda5)\b", re.I),
"SLC30A8": re.compile(r"\b(slc30a8|znt8|znt8a)\b", re.I),
"G6PC2": re.compile(r"\b(g6pc2|igrp)\b", re.I),
"GAD2": re.compile(r"\b(gad2|gad65|gada)\b", re.I),
"PTPRN": re.compile(r"\b(ptprn|ia-?2|ia-?2a|phogrin)\b", re.I),
"INS_Leader_DRiP": re.compile(r"\b(preproinsulin|signal peptide|ins-drip\w*|hybrid insulin peptide\w*)\b", re.I),
"IAPP": re.compile(r"\b(iapp|islet amyloid|amylin|pramlintide)\b", re.I),
"CXADR": re.compile(r"\b(cxadr|car-siv|coxsackie\w*)\b", re.I),
"CHGA": re.compile(r"\b(chga|chromogranin|we14)\b", re.I),
"TGM2": re.compile(r"\b(tgm2|transglutaminase 2)\b", re.I),
"SERPINB9": re.compile(r"\b(serpinb9|pi-9|proteinase inhibitor 9|granzyme b)\b", re.I),
"TNFAIP3": re.compile(r"\b(tnfaip3|\ba20\b)\b", re.I),
"PTPN2": re.compile(r"\b(ptpn2)\b", re.I),
"GLIS3": re.compile(r"\b(glis3)\b", re.I),
"TXNIP": re.compile(r"\b(txnip|verapamil)\b", re.I),
"MANF": re.compile(r"\b(manf)\b", re.I),
"TET2": re.compile(r"\b(tet2)\b", re.I),
"RIPK1": re.compile(r"\b(ripk1)\b", re.I),
"CXCL10": re.compile(r"\b(cxcl10|ip-10|cxcr3)\b", re.I),
"F3_THBD_IBMIR": re.compile(r"\b(tissue factor|ibmir|thrombomodulin|thbd)\b", re.I),
"ICASP9_SafetySwitch": re.compile(r"\b(icasp9|inducible caspase|suicide gene|hsv-tk)\b", re.I),
"PDX1_NKX61_MAFA": re.compile(r"\b(nkx6-?1|nkx6\.1|mafa|pdx1)\b", re.I),
"WNT4_Latrunculin": re.compile(r"\b(wnt4|latrunculin|enterochromaffin|slc18a1)\b", re.I),
"GJD2_Cx36": re.compile(r"\b(connexin-?36|cx36|gjd2)\b", re.I),
}
QUANT_REGEX = re.compile(
r"(\b\d+(\.\d+)?\s*%|\bp\s*[<=>]\s*0\.\d+|\b\d+(\.\d+)?-fold\b|\b\d+(\.\d+)?\s*(mm|μm|um|ng/ml|iu/ml|ieq|days|hours|weeks|months)\b|\bn\s*=\s*\d+)",
re.I,
)
MODIFIER_REGEX = re.compile(
r"\b(dose-dependent|time-dependent|stage\s*[1-7]|hypoxi\w+|normoxi\w+|cytokine\w*|ifn-?[αaγg]|tnf-?[αa]|il-?1[βb]|high glucose|16\.7\s*mm|20\s*mm|2\.8\s*mm|diameter|microvessel\w*|pre-?vascular\w*|knockout|overexpress\w*|crispr|base edit\w*|prime edit\w*|heterozygous|homozygous|b2m|hla-c|kir|nkg2a)\b",
re.I,
)
def classify_fidelity_tier(rec: dict) -> str:
text = f"{rec.get('title', '')} {rec.get('abstract', '')}".lower()
mesh = " ".join(rec.get("mesh_terms", [])).lower()
pub_types = " ".join(rec.get("publication_types", [])).lower()
if "clinical trial" in pub_types or any(
k in text for k in ("clinical trial", "phase 1", "phase 2", "phase i/ii", "vx-880", "zimislecel", "up421", "patient with type 1 diabetes", "intraportal islet transplantation in patients")
):
if "human" in mesh or "human" in text or "patient" in text:
return "Tier_1_Human_InVivo"
has_human_cells = (
"humans" in mesh
or any(
k in text
for k in (
"human", "sc-islet", "sc-beta", "sc-β", "hpsc", "hesc", "ipsc",
"endoc-betah", "endoc-βh", "patient-derived", "pluripotent stem cell",
)
)
)
if has_human_cells:
if any(
k in text or k in mesh
for k in (
"nonhuman primate", "non-human primate", "macaque", "rhesus",
"cynomolgus", "baboon", "macaca", "humanized mice", "humanized mouse",
"pbmc-nsg", "hu-pbmc",
)
):
return "Tier_2A_Human_Cells_InVivo_NHP_or_HumanizedMouse"
if any(
k in text
for k in (
"pbmc", "t-cell clone", "t cell clone", "autoreactive t", "ctl",
"nk cell", "natural killer", "macrophage", "phagocytosis",
"whole blood", "ibmir", "autoantibod", "allogeneic t", "mixed lymphocyte",
)
):
return "Tier_2B_Human_Cells_InVitro_HumanImmune_or_AutoAb_CoCulture"
return "Tier_3_Human_Cells_AbioticStress_or_ImmunodeficientMouse"
return "Tier_4_Rodent_or_Xenogeneic_Only"
def main(allow_title_only_fallback: bool = False) -> None:
manifest_file = RAW_DIR / "corpus_manifest_all_sources.jsonl"
geo_file = RAW_DIR / "functional_genomics_geo_datasets.json"
ppr_file = RAW_DIR / "preprints_sc_islets_hypoimmune.jsonl"
dossier_dir = BASE_DIR / "data" / "dossiers"
pmid_to_gse: dict[str, list[str]] = {}
if geo_file.exists():
with open(geo_file, "r", encoding="utf-8") as f:
gdata = json.load(f)
for ds in gdata.get("datasets", []):
acc = ds.get("accession", "")
for pid in ds.get("pubmed_ids", []):
pmid_to_gse.setdefault(str(pid), []).append(acc)
records = []
with open(manifest_file, "r", encoding="utf-8") as f:
for line in f:
if line.strip():
records.append(json.loads(line))
manifest_abstract_count = sum(1 for r in records if (r.get("abstract") or "").strip())
dossier_abstract_count = sum(
1 for r in records if (dossier_dir / f"{r.get('pmid', '')}.json").exists()
)
if manifest_abstract_count == 0 and not allow_title_only_fallback:
raise RuntimeError(
"corpus_manifest_all_sources.jsonl contains 0 inline abstracts and allow_title_only_fallback=False; "
"pass allow_title_only_fallback=True to stratify using title+MeSH+keyword+subpillar triage with "
"cached Ring-1 dossier abstracts."
)
data_access_counts = Counter()
fidelity_counts = Counter()
ring_counts = Counter()
target_gene_counts = Counter()
stratified_records = []
ring1_queue = []
for rec in records:
pmid = str(rec.get("pmid", ""))
pmcid = rec.get("pmcid")
gse_list = pmid_to_gse.get(pmid, [])
pillars = rec.get("matched_pillars", [])
core_subpillars = [
p for p in pillars
if p.startswith("Pillar1") or p.startswith("Pillar2") or p.startswith("Pillar3") or p.startswith("Pillar4")
]
# 1. Data accessibility
if pmcid and gse_list:
access_class = "Open_FullText_PMC_XML_Plus_GEO_GSE"
elif pmcid:
access_class = "Open_FullText_PMC_XML"
elif gse_list:
access_class = "Abstract_Plus_GEO_GSE"
else:
access_class = "Abstract_Only"
data_access_counts[access_class] += 1
# 2. Target gene detection
full_str = f"{rec.get('title', '')} {rec.get('abstract', '')} {' '.join(rec.get('keywords', []))}"
matched_targets = []
for tname, pat in TARGET_PATTERNS.items():
if pat.search(full_str):
matched_targets.append(tname)
target_gene_counts[tname] += 1
# 3. Biological fidelity tier
fidelity_tier = classify_fidelity_tier(rec)
fidelity_counts[fidelity_tier] += 1
# 4. Quantitative & Effect-Modifier signal density
quant_hits = len(QUANT_REGEX.findall(full_str))
modifier_hits = len(set(m.lower() for m in MODIFIER_REGEX.findall(full_str)))
# 5. Concentric Ring Stratification
is_seed = pmid in GOLDEN_SEED_PMIDS
is_curated_frontier = pmid in CURATED_FRONTIER_SET
is_multi_subpillar = len(core_subpillars) >= 2
has_geo = len(gse_list) > 0
is_human_multi_target = (
fidelity_tier != "Tier_4_Rodent_or_Xenogeneic_Only"
and len(matched_targets) >= 3
and "Pillar1A_SC_Islet_Differentiation_Maturation" in core_subpillars
)
if is_seed or is_curated_frontier or is_multi_subpillar or has_geo or is_human_multi_target:
ring = "Ring_1_Platinum_MultiGate_Core"
elif (
"Pillar1A_SC_Islet_Differentiation_Maturation" in core_subpillars
or (fidelity_tier != "Tier_4_Rodent_or_Xenogeneic_Only" and len(matched_targets) >= 1)
):
ring = "Ring_2_Human_SC_Islet_and_TargetGene_Core"
elif fidelity_tier != "Tier_4_Rodent_or_Xenogeneic_Only":
ring = "Ring_3_Human_Islet_Paracrine_HPAP_and_Engraftment_Core"
else: