scripts/extract_ring1_corpus.py
Use this file in any AI chat (paste-only or attachment-capable):
Pinned raw file: https://openislet.org/files/gen-eb955f8266035aba/scripts/extract_ring1_corpus.py · SHA-256: eee6ac565ed0fb16…
publication-type metadata plus audited narrative reviews whose PubMed XML
omits the Review publication-type tag supply the classification.
"""
publication_types = dossier.get("publication_types") or []
if not isinstance(publication_types, list):
raise ValueError("Dossier publication_types must be a list")
pmid = str(dossier.get("pmid") or "").strip()
contextual = {"review", "systematic review", "meta-analysis", "editorial", "comment"}
if pmid not in CONFIRMED_NARRATIVE_REVIEW_PMIDS and not contextual.intersection(
str(value).strip().lower() for value in publication_types
):
return
record["study_metadata"]["source_text_type"] = "Review_or_Commentary"
record["screening_decision"].update(
included=False,
is_crispr_or_high_throughput_screen=False,
screen_library_size_genes=None,
exclusion_reason="Review_Editorial_or_Commentary",
)
for field in ("arms", "atomic_effects", "effect_modifier_interactions", "causal_mechanism_edges"):
record[field] = []
record["cross_study_discovery_bridges"] = {key: [] for key in record.get("cross_study_discovery_bridges", {})}
def extract_one_dossier(dossier: dict[str, Any]) -> dict[str, Any]:
pmid = str(dossier.get("pmid"))
title = dossier.get("title") or ""
abstract = dossier.get("abstract") or ""
ft = _get_effective_fulltext_sections(pmid, dossier)
ft_parts = [title, abstract]
for r in ft.get("results_paragraphs", []):
ft_parts.append(r)
for fig in ft.get("figure_legends", []):
ft_parts.append(fig.get("caption", ""))
non_methods_text = "\n".join(ft_parts)
for m in ft.get("methods_paragraphs", []):
ft_parts.append(m)
full_text = "\n".join(ft_parts)
has_ft = bool(
dossier.get("has_parsed_fulltext_xml")
or dossier.get("has_fulltext_xml")
or ft.get("results_paragraphs")
or ft.get("figure_legends")
)
has_geo = bool(dossier.get("linked_geo_datasets"))
norm_ab = re.sub(r"\s+", " ", abstract).strip()
norm_ti = re.sub(r"\s+", " ", title).strip()
if pmid in SUPERSEDED_PREPRINT_MAP:
src_type = "Preprint_Superseded_By_Peer_Reviewed"
elif (dossier.get("abstract_indexed") is False or dossier.get("abstract") is None) and not has_ft:
src_type = "Citation_Only_No_Abstract_Indexed"
elif norm_ti and norm_ab.lower().startswith(norm_ti.lower()[:50]):
src_type = "Project_Summary"
elif has_ft and has_geo:
src_type = "FullText_Plus_Supplement_or_GEO"
elif has_ft:
src_type = "FullText_XML_or_PDF"
else:
src_type = "Abstract_Only"
mesh_list = dossier.get("mesh_terms") or dossier.get("mesh_headings") or []
pillars = map_pillars(dossier.get("matched_pillars", []), full_text)
tier = infer_fidelity_tier(full_text, mesh_list, dossier.get("publication_types", []), non_methods_text=non_methods_text)
cell_source, cell_line, stage = infer_cell_source_and_stage(full_text, mesh_list, title=title, pmid=pmid)
niche = infer_transplant_site_and_niche(full_text)
edits = detect_genetic_edits(title, abstract, full_text)
tl = full_text.lower()
is_screen = any(k in tl for k in ("crispr screen", "genome-wide screen", "pooled screen", "perturb-seq", "brunello", "gecko"))
# Infer challenge conditions
challenges = []
if any(k in tl for k in ("ifn-gamma", "ifnγ", "il-1beta", "il-1β", "tnf-alpha", "tnfα", "ifn-alpha", "ifnα", "cytokine")):
challenges.append({
"challenge_type": "Cytokine_Cocktail_IFNg_IL1b_TNFa_or_IFNa",
"effector_to_target_ratio": None,
"oxygen_pct": None,
"glucose_concentration_mM": None,
"duration_hours_or_days": None,
"specific_autoantigen_or_hla_restriction": None,
})
if any(k in tl for k in ("thapsigargin", "tunicamycin", "er stress", "dtt")):
challenges.append({
"challenge_type": "ER_Stress_Thapsigargin_or_Tunicamycin",
"effector_to_target_ratio": None,
"oxygen_pct": None,
"glucose_concentration_mM": None,
"duration_hours_or_days": None,
"specific_autoantigen_or_hla_restriction": None,
})
if any(k in tl for k in ("nk cell", "natural killer", "missing self", "missing-self")):
challenges.append({
"challenge_type": "Primary_NK_Cell_MissingSelf_Assay",
"effector_to_target_ratio": None,
"oxygen_pct": None,
"glucose_concentration_mM": None,
"duration_hours_or_days": None,
"specific_autoantigen_or_hla_restriction": None,
})
if any(k in tl for k in ("autoreactive t", "t-cell clone", "cd8+ t", "ins-drip", "ppi15-24")):
challenges.append({
"challenge_type": "T1D_Autoreactive_CD8_or_CD4_TCR_Clone",
"effector_to_target_ratio": None,
"oxygen_pct": None,
"glucose_concentration_mM": None,
"duration_hours_or_days": None,
"specific_autoantigen_or_hla_restriction": None,
})
if any(k in tl for k in ("allogeneic", "pbmc", "allograft")):
challenges.append({
"challenge_type": "InVivo_Allogeneic_or_Autoimmune_Graft" if niche["transplant_site"] != "InVitro_Only" else "Allogeneic_PBMC_or_T_Cell_CoCulture",
"effector_to_target_ratio": None,
"oxygen_pct": None,
"glucose_concentration_mM": None,
"duration_hours_or_days": None,
"specific_autoantigen_or_hla_restriction": None,
})
if any(k in tl for k in ("hypoxia", "1% o2", "ischemi")):
challenges.append({
"challenge_type": "Hypoxia_Ischemia_Challenge",
"effector_to_target_ratio": None,
"oxygen_pct": 1.0 if "1%" in tl else None,
"glucose_concentration_mM": None,
"duration_hours_or_days": None,
"specific_autoantigen_or_hla_restriction": None,
})
if not challenges:
challenges.append({
"challenge_type": "Unstressed_Baseline",
"effector_to_target_ratio": None,
"oxygen_pct": None,
"glucose_concentration_mM": None,
"duration_hours_or_days": None,
"specific_autoantigen_or_hla_restriction": None,
})
atomic_effects, modifier_interactions, causal_edges, bridges = extract_atomic_effects_and_modifiers(
pmid=pmid,
dossier=dossier,
study_edits=edits,
cell_source=cell_source,
stage=stage,
transplant_site=niche["transplant_site"],
tier=tier,
)
authors = dossier.get("authors") or []
first_author = dossier.get("first_author") or (authors[0] if authors else "")
senior_author = dossier.get("senior_author") or (authors[-1] if len(authors) > 1 else first_author)
geo_accs = [g["accession"] for g in dossier.get("linked_geo_datasets", []) if g.get("accession")]
pub_year = dossier.get("pub_year") or 2020
arm1_n = atomic_effects[0]["treatment_n"] if atomic_effects else None
arm1_n_unit = atomic_effects[0]["n_unit"] if (atomic_effects and arm1_n is not None) else None
arms_list = [
{
"arm_id": f"pmid{pmid}_arm1_primary",
"arm_label": f"Primary experimental arm in {first_author} ({pub_year})",
"is_reference_control": False,
"sample_size_n": arm1_n,
"sample_size_unit": arm1_n_unit,
"gate1_substrate_and_differentiation": {
"cell_source_class": cell_source,
"cell_line_id": cell_line,
"donor_hla_profile": None,
"protocol_backbone": None,
"canonical_differentiation_stage_evaluated": stage,
"stage_small_molecules_and_factors": [],
"cluster_mean_diameter_um": None,
"pct_nkx6_1_cpeptide_double_pos": None,
"pct_mafa_pos": None,
"pct_alpha_gcg_pos": None,
"pct_delta_sst_pos": None,
"pct_off_target_enterochromaffin_slc18a1": None,
},
"gate2_3_4_genetic_and_epitope_edits": edits,
"gate5_engraftment_niche": niche,
"challenge_conditions": challenges,
"quantitative_readouts": {
"specific_lysis_or_death_pct_mean": None,
"specific_lysis_or_death_pct_sd": None,
"cell_viability_pct_mean": None,
"early_72h_graft_survival_pct": None,
"time_to_vascular_inosculation_hours": None,
"necrotic_core_or_damp_release_pct": None,
"fibrotic_capsule_thickness_um": None,
"in_vivo_graft_survival_days_median": None,
"pct_graft_surviving_at_end_of_followup": None,
"followup_duration_days": None,
"static_gsis_stimulation_index_mean": None,
"static_gsis_stimulation_index_sd": None,
"dynamic_perifusion_first_phase_fold": None,
"proinsulin_to_insulin_ratio": None,
"in_vivo_stimulated_c_peptide_ng_ml": None,
"de_novo_dsa_or_autoantibody_spreading_observed": None,
},
}
]
comp_effs = [e for e in atomic_effects if e.get("comparator_arm_id") == f"pmid{pmid}_arm2_comparator"]
if comp_effs:
ce0 = comp_effs[0]
_, comp_arm_label = _extract_comparator_clause(
ce0.get("verbatim_evidence_quote") or "", edits, cell_source, stage, first_author, pub_year
)
ce0_y = (ce0.get("outcome_variable_Y") or "").lower()
is_viability_y = ce0.get("measurement_unit") == "%" and any(
k in ce0_y for k in ("viability", "survival")
)
comp_niche = copy.deepcopy(niche)
comp_niche["oxygen_bridge_72h_carrier"] = _infer_comparator_oxygen_carrier(
niche.get("oxygen_bridge_72h_carrier"), comp_arm_label
)
arms_list.append({
"arm_id": f"pmid{pmid}_arm2_comparator",
"arm_label": comp_arm_label,
"is_reference_control": True,
"sample_size_n": ce0.get("control_n"),
"sample_size_unit": ce0.get("n_unit") if ce0.get("control_n") is not None else None,
"gate1_substrate_and_differentiation": {
"cell_source_class": cell_source,
"cell_line_id": cell_line,
"donor_hla_profile": None,
"protocol_backbone": f"Isogenic reference control matched to {cell_source} ({stage})",
"canonical_differentiation_stage_evaluated": stage,
"stage_small_molecules_and_factors": [],
"cluster_mean_diameter_um": None,
"pct_nkx6_1_cpeptide_double_pos": None,
"pct_mafa_pos": None,
"pct_alpha_gcg_pos": None,
"pct_delta_sst_pos": None,
"pct_off_target_enterochromaffin_slc18a1": None,
},
"gate2_3_4_genetic_and_epitope_edits": [],
"gate5_engraftment_niche": comp_niche,
"challenge_conditions": challenges,
"quantitative_readouts": {
"specific_lysis_or_death_pct_mean": None,
"specific_lysis_or_death_pct_sd": None,
"cell_viability_pct_mean": ce0.get("control_mean") if is_viability_y else None,
"early_72h_graft_survival_pct": None,
"time_to_vascular_inosculation_hours": None,
"necrotic_core_or_damp_release_pct": None,
"fibrotic_capsule_thickness_um": None,
"in_vivo_graft_survival_days_median": None,
"pct_graft_surviving_at_end_of_followup": None,
"followup_duration_days": None,
"static_gsis_stimulation_index_mean": None,
"static_gsis_stimulation_index_sd": None,