OpenIslet

scripts/run_layer2_perturbation_and_regulatory_plane.py

Layer 2: Single-Cell Perturbation & Regulatory Sequence Plane (v0.8.0)

script Release v0.8.0 gen-eb955f8266035aba 1.13 MB · 71 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/run_layer2_perturbation_and_regulatory_plane.py · SHA-256: 3220e68f97203dbc…

        elif hlae_resting_mols > 0 or hlae_mols > 0:
            hour0_protection_status = (
                f"HLAE_BELOW_ASSUMED_THRESHOLD ({hlae_resting_mols} resting / {hlae_mols} IFN-gamma-stimulated molecules/cell < 15,000 threshold; "
                f"CD47 prior = {cd47_mols} molecules/cell; AUDIT-REF)"
            )
        else:
            hour0_protection_status = (
                f"HLAE_ABSENT ({hlae_resting_mols} molecules/cell; CD47 prior {cd47_mols} molecules/cell does not establish missing-self protection)"
            )
        cxcl10_pg = 0.0 if spec["cxcl10_ko"] else max(0.0, round(70.0 * cxcl10_inducible_fold, 1))
        serpinb9_uM = max(0.0, round(0.215 * cxcl10_inducible_fold, 2)) if spec["locus3_ki"] else 0.08
        pdl1_pre_skip_prior = max(0.0, 6400.0 * cxcl10_inducible_fold) if spec["locus3_ki"] else None
        pdl1_mols = max(0, int(round(pdl1_pre_skip_prior * eta_2a_skipping))) if spec["locus3_ki"] else 8500

        if is_hpsc:
            s4_draws = sorted(min(0.95, max(0.05, rng.gauss(spec["stage4_mean"], spec["stage4_sd"]))) for _ in range(1000))
            s6_draws = sorted(min(0.95, max(0.05, rng.gauss(spec["stage6_mean"], spec["stage6_sd"]))) for _ in range(1000))
            s7_draws = sorted(min(0.90, max(0.05, rng.gauss(spec["beta_yield_mean"], spec["beta_yield_sd"]))) for _ in range(1000))
            s4_ci: Any = summarize_prior_draws(s4_draws)
            s6_ci: Any = summarize_prior_draws(s6_draws)
            s7_ci: Any = summarize_prior_draws(s7_draws)
        else:
            s4_ci = "not_applicable_primary_cadaveric_islets"
            s6_ci = "not_applicable_primary_cadaveric_islets"
            s7_ci = "not_applicable_primary_cadaveric_islets"

        prof: Dict[str, Any] = {
            "genotype_id": spec["genotype_id"],
            "genotype_aliases": spec.get("genotype_aliases", []),
            "evidence_class": "literature_anchored_stage_specific_prior_with_independent_monte_carlo_bands_not_direct_wetlab_observation",
            "hip_core_factor_vector_X1_to_X6": spec["hip_core_factor_vector_X1_to_X6"],
            "description": spec["description"],
            "is_hpsc_stage0_to_stage7_product": is_hpsc,
            "stage4_pp2_nkx61_fraction": spec["stage4_mean"] if is_hpsc else None,
            "stage4_pp2_nkx61_prior_scenario_interval_p10_p90": s4_ci,
            "stage6_neurog3_ep_fraction": spec["stage6_mean"] if is_hpsc else None,
            "stage6_neurog3_ep_prior_scenario_interval_p10_p90": s6_ci,
            "stage7_sc_beta_yield_fraction": spec["beta_yield_mean"] if is_hpsc else None,
            "stage7_sc_beta_yield_prior_scenario_interval_p10_p90": s7_ci,
            "stage7_sc_alpha_yield_fraction": 0.30 if is_hpsc else None,
            "stage7_sc_delta_yield_fraction": 0.10 if is_hpsc else None,
            "gsis_stimulation_index_20mM_vs_2p8mM": spec["gsis_mean"],
            "gsis_prior_scenario_interval_p10_p90": mc_interval(spec["gsis_mean"], spec["gsis_sd"], 1.0, 8.0),
            "iec_cord_branching_index_relative": spec["iec_branch_mean"],
            "iec_cord_branching_prior_scenario_interval_p10_p90": mc_interval(spec["iec_branch_mean"], spec["iec_branch_sd"], 0.1, 1.5),
            "hour0_basal_cd47_molecules_per_cell": cd47_mols,
            "hour0_basal_hlae_molecules_per_cell": hlae_resting_mols,
            "hour0_resting_unstimulated_hlae_molecules_per_cell": hlae_resting_mols,
            "ifng_24h_induced_hlae_molecules_per_cell": hlae_mols,
            "hour0_resting_hlae_vulnerability_gap_molecules_per_cell": hlae_hour0_gap_mols,
            "hour0_resting_hlae_below_15k_nkg2a_threshold": resting_hlae_below_15k,
            "hour0_resting_hlae_meets_25k_release_gate": bool(hlae_resting_mols >= 25000),
            "ifng24h_hlae_meets_25k_release_gate": bool(hlae_mols >= 25000),
            "hour0_hlae_and_cd47_protection_status": hour0_protection_status,
            "ifng_24h_cxcl10_secretion_pg_ml": cxcl10_pg,
            "hour0_basal_serpinb9_cytosolic_uM": 0.09 if spec["locus3_ki"] else 0.08,
            "hour0_basal_pdl1_molecules_per_cell": 9100 if spec["locus3_ki"] else 8500,
            "serpinb9_induction_half_time_hours": 6.0 if spec["locus3_ki"] else None,
            "hour0_single_hit_gzmb_bolus_coverage_ratio_at_0p20uM_si_1p5": round((0.09 if spec["locus3_ki"] else 0.08) / (1.5 * 0.20), 4),
            "hour0_kinetic_race_status": (
                "UNSTIMULATED_HOUR0_SERPINB9_BELOW_0P30UM_BOLUS_FLOOR_REQUIRES_GATE_0C_KINETIC_OR_L3_BFB_BASAL_FLOOR"
                if spec["locus3_ki"]
                else "NO_LOCUS3_TRANSGENE"
            ),
            "ifng_24h_serpinb9_cytosolic_uM": serpinb9_uM,
            "ifng_24h_pdl1_molecules_per_cell": pdl1_mols,
            "ifng_24h_pdl1_before_2a_skip_prior_molecules_per_cell": pdl1_pre_skip_prior,
            "pdl1_downstream_2a_skip_factor_prior": eta_2a_skipping if spec["locus3_ki"] else None,
            "surface_density_endpoint_evidence_class": "UNVALIDATED_PRIOR_REQUIRES_TIMEPOINT_AND_LINEAGE_MATCHED_FLOW_CYTOMETRY",
            "primary_nk_specific_lysis_pct_cd94_nkg2a_pos": spec["nkg2a_lysis_mean"],
            "primary_nk_specific_lysis_pct_kir_pos_nkg2a_neg": spec["kir_lysis_mean"],
            "alloreactive_cd8_ctl_lysis_pct": spec["allo_ctl_mean"],
            "autoreactive_ppi_cd8_ctl_lysis_pct": spec["auto_ctl_mean"],
            "empirical_literature_anchors": spec["empirical_literature_anchors"],
        }
        prof["uncertainty_semantics"] = "independent prior scenario draws; no posterior fitting or held-out validation"
        if spec["genotype_id"].startswith("SCENARIO_B"):
            product_id = "ISLET1_B1_6LOCUS_TYK2_KO_INS" if spec["genotype_id"].startswith("SCENARIO_B1_") else "ISLET1_B2_5LOCUS_TYK2_PE"
            contract = get_product_definition(product_id, root=REPO_ROOT, require_staged_fastas=False)
            prof.update(product_definition_id=product_id, product_definition=contract,
                        exact_product_defined=False, source_construct=None,
                        prediction_status="PROVISIONAL_P2A_COMPARATOR_NOT_EXACT_SCENARIO_B_PRODUCT",
                        no_scenario_b_product_benefit_claim=True)
            prof["description"] = ("Provisional P2A experimental comparator; no exact Scenario-B product prediction. "
                "The named family contract proposes a 2A-free cassette whose donor ledger is not materialized. " + spec["description"])
        elif spec["genotype_id"] == "SCENARIO_A_ARM_1A_BICISTRONIC_P2A_COMPARATOR":
            prof["product_definition_id"] = "ISLET1_A4_ARM1A"
        else:
            prof["product_definition_id"] = "ISLET1_A4_ARM1B" if spec["genotype_id"] == "SCENARIO_A_ARM_1B_UNIVERSAL_LEAN_4LOCUS" else "REFERENCE_PRIOR_COMPARATOR"
        if prof["product_definition_id"].startswith("ISLET1_A4_"):
            prof["product_definition"] = get_product_definition(
                prof["product_definition_id"], root=REPO_ROOT, require_staged_fastas=False
            )
            prof["source_construct"] = ("LOCUS1_ARM1A_TPT2A_BICISTRONIC" if prof["product_definition_id"].endswith("ARM1A") else "LOCUS1_ARM1B_2AFREE_BIDIRECTIONAL_R01")
            prof["exact_product_defined"] = True
            prof["physical_qualification_status"] = "PREREGISTERED_PENDING"
        elif prof["product_definition_id"] == "REFERENCE_PRIOR_COMPARATOR":
            prof.update(exact_product_defined=False, source_construct=None,
                        prediction_status="REFERENCE_PRIOR_HYPOTHESIS_NOT_AN_EXACT_PRODUCT", product_definition=None)
        if prof.get("product_definition") is not None:
            prof["declared_dsb_locus_count_K"] = prof["product_definition"]["K"]
            prof["declared_base_or_prime_edit_locus_count_B"] = prof["product_definition"]["B"]
        # Compatibility aliases are explicitly prior draws, never posterior credible bands.
        aliases = {}
        for key, value in list(prof.items()):
            if "_prior_scenario_interval_p10_p90" in key:
                old = key.replace("_prior_scenario_interval_p10_p90", "_credible_interval_p10_p90")
                prof[old] = value
                aliases[old] = {"deprecated_alias_of": key, "semantics": "independent prior scenario draws, no posterior fitting or held-out validation"}
        prof["deprecated_uncertainty_aliases"] = aliases
        perturbation_profiles.append(prof)

    by_id = {p["genotype_id"]: p for p in perturbation_profiles}
    wt_profile = by_id["WT_UNEDITED_CONTROL"]
    arm1b_profile = by_id["SCENARIO_A_ARM_1B_UNIVERSAL_LEAN_4LOCUS"]
    tyk2_profile = by_id["HIP_CORE_X4_TYK2_KO_PERTURBATION"]

    l3_bfb_profile_projection = {
        "product_definition_id": "ISLET1_A4_L3_BFB_BASALFLOOR",
        "source_construct": "Locus3_BasalFloor_ScarFree_SERPINB9_PDL1_challenger_muse_r3",
        "donor_length_bp": 4078,
        "donor_sha256": "0a5f714d536cfb427039e50966fbc88cc6f7dbec8252f26bf43f32a359017c7e",
        "hour0_basal_serpinb9_cytosolic_uM": 0.30,
        "ifng_24h_serpinb9_cytosolic_uM": 0.89,
        "sp1_basal_to_ifng24h_ratio": round(0.30 / 0.89, 4),
        "suicide_inhibitor_stoichiometry_si": 1.0,
        "hour0_single_hit_gzmb_bolus_coverage_ratio_at_0p20uM_si_1p0": round(0.30 / (1.0 * 0.20), 4),
        "hour0_single_hit_gzmb_bolus_coverage_ratio_at_0p15uM_standard_bolus_si_1p0": round(0.30 / (1.0 * 0.15), 4),
        "hour0_post_pulse_1_2_3_serpinb9_at_0p15uM_every_2h_uM": [
            round(0.30 - 0.15, 6),
            round(0.30 + (0.15 - 0.30) * (2.0 ** (-1.0 / 3.0)) - 0.15, 6),
            0.0,
        ],
        "pdl1_downstream_2a_skip_factor_prior": None,
        "ifng_24h_pdl1_molecules_per_cell": int(round(6400.0 * cxcl10_inducible_fold)),
        "hour0_kinetic_race_status": "L3_BFB_BASAL_FLOOR_TARGET_0P30UM_CLEARS_SINGLE_AND_2PULSE_0P15UM_BOLUS_EXHAUSTS_AT_PULSE_3_REQUIRES_1P52UM_FOR_12PULSE_HYPOXIA_GATE_0C_KINETIC",
    }
    arm1b_profile["l3_bfb_basalfloor_profile_projection_sonnet55_r4"] = l3_bfb_profile_projection

    tyk2_ifna_orphan_hc_branches = {
        "beta_cell_ipsc_80_to_90pct_ifna_attenuation_branch_pmid_36289205": [0.10, 0.20],
        "human_leukocyte_wt_like_0_to_20pct_ifna_attenuation_branch_pmid_30578352_42268925": [0.80, 1.00],
        "ifng_jak1_jak2_unattenuated_orphan_hc_flux_multiplier_vs_b2m_ko": [0.85, 1.00],
    }
    tyk2_ifna_isre_induction_branches = {
        "beta_cell_ipsc_knockdown_branch_pmid_36289205": [0.15, 0.35],
        "human_leukocyte_wt_like_high_dose_ifna_branch_pmid_30578352_42268925": [0.80, 1.00],
    }
    for prof in perturbation_profiles:
        gid = prof["genotype_id"]
        if "TYK2" in gid:
            is_ko = "KO" in gid
            prof["ifna_dominant_early_flare_branch_predictions_astra6_r4"] = {
                "tyk2_allele_class": "TYK2_KO_BIALLELIC" if is_ko else "TYK2_P1104A_HOMOZYGOUS_PRIME_EDIT",
                "ifng_24h_ctl_synapse_baseline": {
                    "hlae_molecules_per_cell": prof["ifng_24h_induced_hlae_molecules_per_cell"],
                    "serpinb9_cytosolic_uM": prof["ifng_24h_serpinb9_cytosolic_uM"],
                    "pdl1_molecules_per_cell": prof["ifng_24h_pdl1_molecules_per_cell"],
                    "cxcl10_secretion_pg_ml": prof["ifng_24h_cxcl10_secretion_pg_ml"],
                },
                "ifna_early_flare_isre_induction_multiplier_branches": (
                    {"tyk2_ko_abrogated_typeI_ifn_branch_pmid_36289205": [0.05, 0.15]}
                    if is_ko
                    else tyk2_ifna_isre_induction_branches
                ),
                "ifna_early_flare_orphan_hc_flux_multiplier_branches": (
                    {"tyk2_ko_abrogated_typeI_ifn_branch_pmid_36289205": [0.05, 0.15]}
                    if is_ko
                    else tyk2_ifna_orphan_hc_branches
                ),
                "ifna_early_flare_serpinb9_uM_by_branch": (
                    {
                        "tyk2_ko_abrogated_typeI_ifn_branch_pmid_36289205": [
                            round(0.09 + (arm1b_profile["ifng_24h_serpinb9_cytosolic_uM"] - 0.09) * m, 3)
                            for m in [0.05, 0.15]
                        ]
                    }
                    if is_ko
                    else {
                        b_name: [
                            round(0.09 + (arm1b_profile["ifng_24h_serpinb9_cytosolic_uM"] - 0.09) * m, 3)
                            for m in mults
                        ]
                        for b_name, mults in tyk2_ifna_isre_induction_branches.items()
                    }
                ),
                "ifna_early_flare_pdl1_molecules_per_cell_by_branch": (
                    {
                        "tyk2_ko_abrogated_typeI_ifn_branch_pmid_36289205": [
                            int(round(9100 + (arm1b_profile["ifng_24h_pdl1_molecules_per_cell"] - 9100) * m))
                            for m in [0.05, 0.15]
                        ]
                    }
                    if is_ko
                    else {
                        b_name: [
                            int(round(9100 + (arm1b_profile["ifng_24h_pdl1_molecules_per_cell"] - 9100) * m))
                            for m in mults
                        ]
                        for b_name, mults in tyk2_ifna_isre_induction_branches.items()
                    }
                ),
            }
    stages = [
        {"stage_id": "Stage_0_hPSC", "markers": "OCT4+/SOX2+/NANOG+", "day": 0},
        {"stage_id": "Stage_1_Definitive_Endoderm", "markers": "SOX17+/FOXA2+", "day": 3},
        {"stage_id": "Stage_4_Pancreatic_Progenitor_PP2", "markers": "PDX1+/NKX6.1+/SOX9+", "day": 11},
        {"stage_id": "Stage_6_Endocrine_Progenitor_EP", "markers": "NEUROG3+/NKX2.2+/FEV+", "day": 18},
        {"stage_id": "Stage_7_Mature_SC_Beta", "markers": "INS+/NKX6.1+/MAFA+/UCN3+/ENTPD3+", "day": 28},
        {"stage_id": "Stage_7_Mature_SC_Alpha", "markers": "GCG+/ARX+/IRX2+", "day": 28},
        {"stage_id": "Stage_7_Mature_SC_Delta", "markers": "SST+/HHEX+", "day": 28},
        {"stage_id": "Isogenic_iEC_Microvessel", "markers": "CD31+/CD144(VE-Cadherin)+/vWF+", "day": 14},
    ]

    return {
        "model_type": "Literature-Anchored Stage-Specific Prior Lookup with Independent Per-Stage Monte Carlo Uncertainty Bands (N=1,000 draws per stage/endpoint; not a fitted ODE/GRN dynamical model)",
        "construct_grammar_verification": grammar_audit,
        "effects_corpus_validation_status": effects_corpus_status,
        "evidence_eligibility": {
            "policy": "Exclude project summaries, reviews/commentaries and superseded preprints before any directional study weighting; retain only source-typed active records",
            "excluded_effect_records": len(excluded_effect_ids),
            "excluded_study_pmids": sorted(excluded_study_pmids),
            "eligible_effect_records": len(unique_effect_ids - excluded_effect_ids),
            "duplicate_exact_effect_records_skipped": duplicate_exact_effect_records_skipped,
        },
        "input_provenance": {
            "ring1_atomic_effects": {"path": effects_input_path, "sha256": effects_sha256,
                                      "bytes": len(effects_bytes), "unique_effect_records": len(unique_effect_ids)},
            "raw_reference_object_sha256": sha256_str(json.dumps(ref,sort_keys=True,separators=(",",":"))),
            "construct_verification_object_sha256": sha256_str(json.dumps(construct_verification,sort_keys=True,separators=(",",":"))),
            "motif_scan_object_sha256": sha256_str(json.dumps(motif_scans,sort_keys=True,separators=(",",":"))),
            "scope": "Hashes bind the actual consumed bytes/objects, not an authenticated biological prediction."},
        "calibration_inputs_consumed": {
            "gtex_cd47_pancreas_median_tpm": cd47_pancreas_tpm,
            "gtex_b2m_pancreas_median_tpm": b2m_pancreas_tpm,
            "basal_wt_hlae_molecules_per_cell": int(round(basal_hlae_wt)),
            "encode_screen_cxcl10_max_biosample_tpm": cxcl10_encode_biosample_max_tpm,
            "jaspar_cxcl10_stat1_stat2_log2_odds": cxcl10_isre_top_score,
            "jaspar_cxcl10_bounded_motif_activation": round(cxcl10_motif_activation, 6),
            "jaspar_b2m_irf1_log2_odds": b2m_isre_top_score,
            "jaspar_b2m_bounded_motif_activation": round(b2m_motif_activation, 6),
            "eta_2a_ribosomal_skipping_downstream_factor": eta_2a_skipping,
            "ring1_unique_records_deduplicated_count": len(unique_effect_ids),
            "ring1_directional_study_gene_links_count": directional_study_total,
            "ring1_continuous_evidence_weight": ring1_evidence_weight,
            "ring1_gene_effect_evidence_counts": gene_effect_counts,
            "ring1_canonical_gene_effect_evidence_counts": canonical_gene_effect_counts,
            "ring1_canonical_gene_study_pmids": {
                g: {label: sorted(pmids, key=int) for label, pmids in groups.items()}
                for g, groups in gene_study_sets.items()