OpenIslet

scripts/summarize_omics_baseline.py

Compiles the live OpenTargets T1D genetic associations (MONDO_0005147) and gnomAD

script Release v0.8.0 gen-eb955f8266035aba 30 KB · 2 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/summarize_omics_baseline.py · SHA-256: 55f707d4e38353e9…

        "rationale": "ZnT8 autoantigen (pLI=1.9e-7). Human LoF protects against T2D (PMID:24584071) and boosts SC-islet GSIS/hypoxia survival (PMID:31676859, PMID:42078397), but complete biallelic KO abolishes insulin dense-core zinc crystallization and alters hepatic insulin clearance. Excluded from lean Chassis A core.",
    },
    "STAT1": {
        "opentargets_t1d_score": 0.0707,
        "gate": "Gate4_Intrinsic_IFN_JAK_STAT_Block",
        "failure_mode_defended": "FM6_Interferon_Signaling_vs_Epistatic_Promoter_Trap",
        "recommended_edit": "Avoid_Clonal_KO_When_Using_GAS_ISRE_Inducible_Shields",
        "hpa_islet_expression_status": "Ubiquitous_IFN_Signal_Transducer_Descriptive_Context_Only",
        "rationale": "Strongly constrained in gnomAD (pLI=1.000, LOEUF=0.302, oe_lof=0.215, oe_mis=0.385). Clonal STAT1-/- blocks IFN-gamma apoptosis (Maestas 2026 PMID:41886504) but creates an epistatic deadlock if paired with GAS/ISRE-inducible PD-L1/SERPINB9 promoters without an NF-kB bypass.",
    },
    "TGM2": {
        "opentargets_t1d_score": None,
        "gate": "Gate2_Autoantigen_Stealth_TCR_or_AutoAb",
        "failure_mode_defended": "FM4_PostTranslational_Neoantigens_HIPs_DRiPs_Deamidation",
        "recommended_edit": "Biallelic_KO",
        "hpa_islet_expression_status": "Expressed_in_Endothelial_and_Stressed_Islet_Cells_Descriptive_Context_Only",
        "rationale": "Tissue transglutaminase 2; deamidates glutamine residues on islet proteins under ER calcium stress to generate high-affinity HLA-DQ2/DQ8 neoantigens. Completely LoF tolerant (pLI=7.0e-13, oe_lof=0.701).",
    },
    "THBD": {
        "opentargets_t1d_score": 0.065,
        "gate": None,
        "failure_mode_defended": None,
        "recommended_edit": "Optional_Surface_CoDisplay_for_Intravascular_IBMIR_Sites",
        "hpa_islet_expression_status": "Endothelial_Enriched_Intronless_Gene_Descriptive_Context_Only",
        "rationale": "Thrombomodulin (CD141); intronless gene (gnomAD LoF metrics null; oe_mis=1.041) that converts thrombin into an activator of anticoagulant Protein C (PMID:38709159).",
    },
    "TNFAIP3": {
        "opentargets_t1d_score": 0.354,
        "gate": "Gate4_Intrinsic_IFN_JAK_STAT_Block",
        "failure_mode_defended": "FM6_Interferon_MHC_I_Hyperexpression_and_Apoptosis",
        "recommended_edit": "Gain_of_Function_Inducible_OE_NEVER_KO",
        "hpa_islet_expression_status": "NFkB_Inducible_Islet_Survival_Brake_Descriptive_Context_Only",
        "rationale": "A20 ubiquitin-editing NF-kB/JNK brake; extreme LoF intolerance (pLI=1.000, LOEUF=0.217); must never be knocked out.",
    },
    "TXNIP": {
        "opentargets_t1d_score": 0.195,
        "gate": "Gate4_Intrinsic_Hypoxia_Metabolic_Shield",
        "failure_mode_defended": "FM11_72h_Ischemic_Hypoxia_and_Necrotic_DAMP_Alarm",
        "recommended_edit": "Biallelic_KO_or_Verapamil_Preconditioning",
        "hpa_islet_expression_status": "Glucose_and_ER_Stress_Inducible_Beta_Cell_ProApoptotic_Factor_Descriptive_Context_Only",
        "rationale": "Mediates glucotoxic and ER-stress mitochondrial apoptosis (Chen et al. 2008 PMID:18552236; Shalev 2014 PMID:24911120); LoF tolerant (pLI=0.0009).",
    },
    "TYK2": {
        "opentargets_t1d_score": 0.583522184815907,
        "gate": "Gate4_Intrinsic_IFN_JAK_STAT_Block",
        "failure_mode_defended": "FM6_Interferon_MHC_I_Hyperexpression_and_Apoptosis",
        "recommended_edit": "Biallelic_KO_or_Selective_Kinase_Domain_BaseEdit",
        "hpa_islet_expression_status": "Ubiquitous_Type_I_IFN_Kinase_Stage3_5_Developmental_Role_Descriptive_Context_Only",
        "rationale": "Blocks IFN-alpha/beta/IL-12/23 signaling and MHC-I hyper-expression (human LoF protects against T1D; OpenTargets #9, pLI=2.8e-7), but complete Stage-0 hPSC knockout reduces Stage 4-5 endocrine precursor yield by ~30-50% (Chandra et al. 2022 PMID:36289205).",
    },
}


def finite_optional_metric(value, label: str, upper: float | None = None, *, required: bool = False):
    if value is None and not required:
        return None
    if isinstance(value, bool) or not isinstance(value, (int, float)):
        raise ValueError(f"{label} must be a finite real number")
    try:
        finite = math.isfinite(value)
    except OverflowError:
        finite = False
    if not finite or value < 0 or (upper is not None and value > upper):
        raise ValueError(f"{label} is outside its finite nonnegative domain")
    return value


def main() -> None:
    ot_file = OMICS_DIR / "t1d_associated_targets_top100.json"
    ot_scores = {}
    if ot_file.exists():
        with open(ot_file, encoding="utf-8") as f:
            ot_data = json.load(f)
        if ot_data.get("disease", {}).get("id") != "MONDO_0005147":
            raise ValueError("OpenTargets source must identify MONDO_0005147")
        for row in ot_data.get("disease", {}).get("associatedTargets", {}).get("rows", []):
            sym = row.get("target", {}).get("approvedSymbol")
            if not isinstance(sym, str) or not sym.strip() or sym in ot_scores:
                raise ValueError("OpenTargets symbols must be nonempty and unique")
            ot_scores[sym] = finite_optional_metric(row.get("score"), f"OpenTargets {sym} score", 1.0, required=True)

    records = []
    skipped_gnomad_files = []
    direct_graphql_targets = []
    curated_fallback_targets = []
    null_targets = []
    for p in sorted(glob.glob(str(OMICS_DIR / "gnomad_*.json"))):
        with open(p, encoding="utf-8") as f:
            raw = json.load(f)
        if raw.get("data") is not None and not isinstance(raw["data"], dict):
            raise ValueError("gnomAD data must be an object or null")
        gene = (raw.get("data") or {}).get("gene")
        if gene is not None and not isinstance(gene, dict):
            raise ValueError("gnomAD gene must be an object or null")
        if not gene or not gene.get("symbol"):
            err_msgs = [e.get("message", "") for e in (raw.get("errors") or []) if isinstance(e, dict)]
            skipped_gnomad_files.append({
                "file": Path(p).name,
                "status": "Upstream_GraphQL_Error_Skipped_Non_Stack_Target",
                "error_messages": err_msgs,
                "note": raw.get("openislet_audit_note", "Gene object null in raw gnomAD response; excluded from 27-gene stack prior table."),
            })
            continue
        sym = gene.get("symbol")
        if not isinstance(sym, str) or Path(p).name != f"gnomad_{sym}.json":
            raise ValueError("gnomAD filename and gene symbol must match")
        gid = gene.get("gene_id")
        if not isinstance(gid, str) or re.fullmatch(r"ENSG[0-9]{11}(?:\.[0-9]+)?", gid) is None:
            raise ValueError("gnomAD source must identify a canonical human Ensembl gene")
        c = gene.get("gnomad_constraint")
        if c is not None and not isinstance(c, dict):
            raise ValueError("gnomAD constraints must be an object or null")
        c = c or {}
        for key in ("pLI", "pli", "oe_lof", "oe_lof_lower", "oe_lof_upper", "oe_mis", "oe_mis_lower", "oe_mis_upper"):
            if key in c:
                finite_optional_metric(c[key], f"{sym} {key}", 1.0 if key in {"pLI", "pli"} else None)
        for prefix in ("oe_lof", "oe_mis"):
            lower, upper = c.get(prefix + "_lower"), c.get(prefix + "_upper")
            if lower is not None and upper is not None and lower > upper:
                raise ValueError(f"{sym} {prefix} interval is reversed")
        ann = ENGINEERING_ANNOTATIONS.get(sym, {})
        finite_optional_metric(ann.get("opentargets_t1d_score"), f"{sym} curated prior", 1.0)
        pli_val = c.get("pLI") if c.get("pLI") is not None else c.get("pli")
        if sym in ot_scores:
            ot_val = ot_scores[sym]
            curated_val = ot_scores[sym]
            ot_prov = "OpenTargets_MONDO_0005147_Direct_GraphQL_Top25"
            direct_graphql_targets.append(sym)
        elif ann.get("opentargets_t1d_score") is not None:
            ot_val = None
            curated_val = ann.get("opentargets_t1d_score")
            ot_prov = "Curated_Literature_Prior_Fallback_Not_In_Top25_GraphQL"
            curated_fallback_targets.append(sym)
        else:
            ot_val = None
            curated_val = None
            ot_prov = "Not_Indexed_Null"
            null_targets.append(sym)
        records.append({
            "gene_symbol": sym,
            "ensembl_gene_id": gid,
            "opentargets_t1d_score": ot_val,
            "curated_literature_prior_t1d_score": curated_val,
            "opentargets_score_source": ot_prov,
            "opentargets_score_provenance": ot_prov,
            "gnomad_pli": pli_val,
            "gnomad_oe_lof": c.get("oe_lof"),
            "gnomad_loeuf_upper": c.get("oe_lof_upper"),
            "gnomad_oe_mis": c.get("oe_mis"),
            "hpa_islet_expression_status": ann.get("hpa_islet_expression_status"),
            "functional_gate": ann.get("gate"),
            "failure_mode_defended": ann.get("failure_mode_defended"),
            "recommended_edit": ann.get("recommended_edit"),
            "engineering_rationale": ann.get("rationale"),
        })

    out_path = OMICS_DIR / "target_prior_table.json"
    prior_payload = {
        "generated_at": "2026-10-24",
        "schema_version": "0.8.1",
        "omics_integration_note": (
            "Quantitative evaluator incorporates gnomAD v2.1.1/v4 loss-of-function constraint "
            "(gnomad_pli, gnomad_loeuf_upper) and OpenTargets/literature T1D genetic association priors. "
            "opentargets_t1d_score is populated ONLY for the 3 direct hits in the top-25 MONDO_0005147 "
            "GraphQL snapshot (INS, PTPN2, TYK2; non-top-25 genes have opentargets_t1d_score=null), while "
            "curated literature T1D association priors are stored separately in "
            "curated_literature_prior_t1d_score with explicit opentargets_score_source / "
            "opentargets_score_provenance tags (AUDIT-REF). Human Protein Atlas / GTEx islet "
            "expression fields (hpa_islet_expression_status) are retained as qualitative biological context "
            "metadata only."
        ),
        "opentargets_provenance_summary": {
            "opentargets_release": "26.09",
            "source_file": "data/omics/t1d_associated_targets_top100.json",
            "source_file_rows_returned": len(ot_scores),
            "direct_graphql_top25_count": len(direct_graphql_targets),
            "direct_graphql_top25_targets": direct_graphql_targets,
            "curated_literature_prior_fallback_count": len(curated_fallback_targets),
            "curated_literature_prior_fallback_targets": curated_fallback_targets,
            "not_indexed_null_count": len(null_targets),
            "not_indexed_null_targets": null_targets,
        },
        "skipped_gnomad_files_audit": skipped_gnomad_files,
        "targets": records,
    }

    extracted_summary_path = BASE_DIR / "data" / "extracted" / "omics_baseline_summary.json"
    summary_payload = {
        "generated_at": "2026-10-24",
        "schema_version": "0.8.1",
        "raw_opentargets_file": "data/omics/t1d_associated_targets_top100.json",
        "raw_opentargets_rows_returned": len(ot_scores),
        "raw_opentargets_symbols": sorted(ot_scores.keys()),
        "direct_graphql_top25_targets_in_prior_table": direct_graphql_targets,
        "curated_literature_prior_fallback_targets": curated_fallback_targets,
        "not_indexed_null_targets": null_targets,
        "skipped_gnomad_files_audit": skipped_gnomad_files,
        "target_count": len(records),
        "targets": records,
    }
    publish_byte_artifacts({
        out_path: (json.dumps(prior_payload, indent=2, allow_nan=False) + "\n").encode("utf-8"),
        extracted_summary_path: (json.dumps(summary_payload, indent=2, allow_nan=False) + "\n").encode("utf-8"),
    }, lock_path=BASE_DIR / "data" / ".omics-publication.lock")
    print(f"Wrote {len(records)} target priors to {out_path} and {extracted_summary_path} (direct GraphQL: {len(direct_graphql_targets)}, curated fallback: {len(curated_fallback_targets)}, null: {len(null_targets)})")


if __name__ == "__main__":
    main()