OpenIslet

scripts/rank_islet1_stacks.py

Step 5 & 6: Project Islet-1 Sign-Sensitive, Endpoint-Oriented & Locus-Penalized Evaluator (v0.6.9).

script Release v0.8.0 gen-eb955f8266035aba 638 KB · 42 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/rank_islet1_stacks.py · SHA-256: c05d5fe606219e88…

                "5. Keep model predictions subordinate to their calibration: Layer 4 recipe fractions (scripts/run_layer4_tissue_and_metabolic_twin.py:4220-4222,4643-4645) are recorded metadata that do not scale the ODE right-hand side as lineage masses, so modelled exercise nadirs and per-alpha glucagon multipliers (~1.3x to 4x across M1-M4 and paracrine-scaling variants at equal beta mass) remain sensitivity analyses rather than mandatory recipe-advancement gates."
            ],
        },
        "primary_readouts": [
            "Stage 0->7 Absolute Endocrine Yield & Lineage Purity: Absolute monohormonal NKX6-1+/C-peptide+ beta-cell yield per 10^6 starting hPSCs, % GCG+ alpha, % SST+ delta, % SLC18A1+ off-target enterochromaffin cells (<5% release gate after FACS re-aggregation into <=120 um 60:30:10 spheroids), and batch differentiation failure rate across constitutive TYK2-/- vs TYK2+/+ vs Stage 6/7 TYK2i (Chandra et al. 2022 PMID:36289205 ~32% INS+ reduction gate; Gate 1)",
            "Hour-0 and +IFN-gamma QuantiBRITE molecules/cell for HLA-E and CD47 (comparing bicistronic tPT2A vs 2A-free bidirectional vs CD47-IgV-GPI / CD47-dCT / CD47-WT) on Stage 7 CD49a+/NTPDase3+ beta-cells and iECs (Gate 3)",
            "Primary human innate immune evasion across two unconfounded sub-panels (3A Myeloid Phagocytosis Panel: CD14+ monocyte-derived macrophages genotyped for SIRPA V1/V1, V1/V2, and V2/V2 [n >= 3 donors per genotype, pHrodo-Red 4h engulfment < 5.0% confirmatory release gate, <= 8.0% Tier-1 36-run screening gate]; 3B Sorted Primary NK Subset Panel: purified CD3- CD56dim NK subsets stratified into HCMV-/NKG2A-high, NKG2A- KIR2DL1+/C2 & KIR2DL2/3+/C1 licensed, and HCMV+/NKG2C-high [>=25% NKG2C+ of CD56dim] donors [n >= 4 donors per subset for confirmatory release, >= 3 Tier-1 screen minimum; 4h specific lysis <= 8.0% in NKG2A+NKG2C- and <= 10.0% across all subsets, CD107a degranulation <= 10.0% confirmatory / <= 12.0% Tier-1 screen]; AUDIT-REF & AUDIT-REF; Gate 3)",
            "Autoreactive T1D CD8+ TCR (PPI/IGRP/GAD65) and allogeneic PBMC survival + HLA-DQ2/DQ8 DC indirect presentation bystander assay + cytokine-stimulated beta-cell Fas (CD95) incremental apoptosis screen (Delta_TUNEL+ <= +5.0 pp above cytokine-matched SA-THBD-only control AND anti-Fas ZB4 neutralizing mAb rescue <= 5.0 pp) under SA-FasL/SA-THBD microgels (Gate 2A/2B)",
            "Dynamic perifusion GSIS stimulation index, 16.7 -> 2.8 mM glucose 90% shut-off time (<3 min gate), and Seahorse basal/maximal OCR (Gate 1)",
            "Satellite 24h and 72h 10 nM AP1903 suicide-switch eradication depth (Two-Tier Gate: Tier-1 36-run bulk potency screen requiring >= 99.9% 24h kill and >= 4-log 72h kill across all 36 runs; Tier-2 lead/MCB clonogenic escape qualification across N_eff = N_clonogenic,input * eta_detection >= 2.996e8 detectable clonogenic opportunities calibrated with 1-, 10-, and 100-cell AP1903-resistant spike-in recovery controls; AUDIT-REF & 012; Gate 5)",
        ],
        "tier1_screening_16_runs": factorial_runs[:16],
        "tier2_dealiasing_augmentation_20_runs": factorial_runs[16:],
        "runs": factorial_runs,
    }
    protocols_dir = PROJECT_ROOT / "data" / "protocols"
    protocols_dir.mkdir(parents=True, exist_ok=True)

    direct_logit_sensitivity = compute_direct_output_logit_sensitivity_analysis(
        target_profiles, all_combos, studies=studies, omics=omics
    )

    wetlab_calibration_link_status = dict(_WETLAB_CALIBRATION_STATUS)

    raw_edit_rows = [edit for study in studies for arm in study.get("arms", []) for edit in arm.get("gate2_3_4_genetic_and_epitope_edits", [])]
    expanded_edit_genes = [gene for edit in raw_edit_rows for gene in expand_gene_symbol_tokens(edit.get("gene_symbol_hgnc", ""))]
    aux_values = {key: value["parameter_value"] for key,value in COMPLETE_GATE_COEFFICIENT_REGISTRY["auxiliary_evaluator_hyperparameters"].items()}
    reg_entries = {f"{gate}.{key}": value for gate,group in COMPLETE_GATE_COEFFICIENT_REGISTRY.items() if gate.startswith("Gate") for key,value in group.items() if isinstance(value,dict) and "logit_value" in value}
    reference = json.loads((PROJECT_ROOT / "data/raw/layer2_genomic_and_jaspar_reference.json").read_text())
    promoter = reference["ensembl_verified_homology_arms_and_elements"]["EEF1A1_core_promoter_230bp"]["sequence"].upper()
    reverse_promoter = promoter.translate(str.maketrans("ACGT", "TGCA"))[::-1]
    fasta_records = {}
    active_fasta = PROJECT_ROOT / "data/constructs/islet1_scenario_a_constructs_v0.7.0.fasta"
    for chunk in active_fasta.read_text().split(">"):
        if chunk.strip():
            lines = chunk.splitlines()
            fasta_records[lines[0]] = "".join(lines[1:]).strip().upper()
    promoter_occurrences = [{"construct_id": cid, "forward_occurrences": seq.count(promoter),
                             "reverse_complement_occurrences": seq.count(reverse_promoter)}
                            for cid,seq in fasta_records.items() if promoter in seq or reverse_promoter in seq]
    layer1_audit_ledger = {
        "method": "Computed from this evaluation's source studies, graph, registry, exact design and diagnostics; not an audit closure assertion",
        "source_counts": {"studies": len(studies), "arms": sum(len(study.get("arms", [])) for study in studies),
                          "atomic_effects": sum(len(study.get("atomic_effects", [])) for study in studies),
                          "raw_edit_rows": len(raw_edit_rows), "expanded_edit_gene_occurrences": len(expanded_edit_genes)},
        "corpus_eligibility": graph.get("corpus_epistemic_and_fidelity_diagnostics", {}),
        "profile_counts": {"genes": len(target_profiles), "candidate_target_profiles_with_typed_numeric_lrr": sum(profile.get("signed_lrr_weight_total",0)>0 for profile in target_profiles.values()), "independently_adjudicated_direction_effects": 0, "direction_method": "rule_based_heuristic; no independent adjudication dataset supplied"},
        "native_eef1a1_promoter": {"length_bp": len(promoter), "cpg_dinucleotides": promoter.count("CG"),
                                    "gc_fraction": (promoter.count("G")+promoter.count("C"))/len(promoter),
                                    "sha256": hashlib.sha256(promoter.encode()).hexdigest(),
                                    "construct_occurrences": promoter_occurrences,
                                    "total_exact_or_rc_occurrences": sum(row["forward_occurrences"]+row["reverse_complement_occurrences"] for row in promoter_occurrences)},
        "registry": {"source_literal_offset_terms": sum(len(re.findall(r"(?<![\w.])0\.08\s*\*", value.get("expression", ""))) for value in reg_entries.values()),
                     "net_gate_offset_entries": len(reg_entries), "gate_offset_paths": sorted(reg_entries),
                     "auxiliary_groups": len(aux_values), "auxiliary_scalar_leaves": len(_numeric_scalar_paths(aux_values)),
                     "auxiliary_scalar_paths": _numeric_scalar_paths(aux_values), "engineering_priors": len(ENGINEERING_PRIORS_AND_SENSITIVITY_TABLE)},
        "search": {"all_stacks": len(all_combos), "feasible_stacks": sum(c.get("is_feasible_candidate",True) for c in all_combos),
                   "top_tier_stacks": direct_logit_sensitivity["feasible_subset_and_within_top_tier_variance_decomposition_sol_v80_r2_14"]["top_tier_code_defined_n_stacks"]},
        "design": {"run_rows": len(factorial_runs), "unique_genotypes": dalg["n_distinct_genotypes"],
                   "factor_column_sums": col_sums, "factor_plus_one_counts": plus_one_counts},
        "variance_diagnostics": direct_logit_sensitivity["uniform_grid_pooled_pediatric_gate_logit_variance_decomposition"],
    }

    champion_challenger_portfolio = build_champion_challenger_portfolio(ranked_architectures, all_combos, wetlab_calibration_link_status)

    p_esc_ref = 1e-8
    p_20q_ref = 0.0
    p_20q_mosaic_lod_bound = 0.01
    p_meta_ref = 1e-6
    f_ret_ref = 0.99
    # BPR-04 / DEC-133: withhold retrieval credit before retrieval occurs; distinguish conditional (u=0) scenarios from population-wide bounds.
    p_harm_ref_u0_preventable_meta_only = 1.0 - (1.0 - p_esc_ref) * (1.0 - p_20q_ref) * (1.0 - p_meta_ref * (1.0 - f_ret_ref))
    p_harm_ref_true_pre_retrieval_u0 = 1.0 - (1.0 - p_esc_ref) * (1.0 - p_20q_ref) * (1.0 - p_meta_ref)
    bpr04_baseline_pre_and_post = compute_dose_level_tumor_harm_scenarios_bpr04(
        p_esc_per_psc=p_esc_ref,
        n_psc=8.0,
        p_20q=p_20q_ref,
        p_meta=p_meta_ref,
        f_retrieval=f_ret_ref,
        s_already_offsite=0.0,
        u_omitted_untreated_branch=None,
    )
    p_esc_8psc_dose = bpr04_baseline_pre_and_post["p_esc_dose"]
    p_harm_8psc_true_pre_retrieval = bpr04_baseline_pre_and_post["true_pre_retrieval_conditional_harm"]
    p_harm_8psc_legacy_pre_intragraft_post_preventable_meta = 1.0 - (1.0 - p_esc_8psc_dose) * (1.0 - p_20q_ref) * (1.0 - p_meta_ref * (1.0 - f_ret_ref))
    p_harm_8psc_with_99pct_retrieval_assuming_100pct_preventable_meta = bpr04_baseline_pre_and_post["post_retrieval_conditional_harm"]
    p_harm_8psc_with_99pct_retrieval_if_already_offsite = compute_dose_level_tumor_harm_scenarios_bpr04(
        p_esc_per_psc=p_esc_ref,
        n_psc=8.0,
        p_20q=p_20q_ref,
        p_meta=p_meta_ref,
        f_retrieval=f_ret_ref,
        s_already_offsite=1.0,
        u_omitted_untreated_branch=None,
    )["post_retrieval_conditional_harm"]
    # Exact per-residual-PSC escape rate under 1% 20q11.21 trisomic mosaicism (q_esc = 0.01 * 1e-4 + 0.99 * 1e-8 = 1.0099e-6) without double-counting the 1e-8 dual-purge factor already reflected in N_psc_post_purge = 8.0 (AUDIT-REF & MW-R6-S2-01; DEC-052/053):
    q_esc_1pct_mosaic_20q11 = p_20q_mosaic_lod_bound * 1e-4 + (1.0 - p_20q_mosaic_lod_bound) * 1e-8
    p_esc_8psc_if_1pct_mosaic_20q11 = 1.0 - math.exp(-8.0 * q_esc_1pct_mosaic_20q11)
    p_harm_8psc_if_1pct_mosaic_20q11_true_pre_retrieval_no_explant_discount = 1.0 - (1.0 - p_esc_8psc_if_1pct_mosaic_20q11) * (1.0 - p_meta_ref)
    p_harm_8psc_if_1pct_mosaic_20q11_and_1e4_ap1903_resist = 1.0 - (1.0 - p_esc_8psc_if_1pct_mosaic_20q11) * (1.0 - p_meta_ref * (1.0 - f_ret_ref))
    p_esc_only_8psc_if_1pct_mosaic_20q11_with_99pct_retrieval = p_esc_8psc_if_1pct_mosaic_20q11 * (1.0 - f_ret_ref)
    p_harm_8psc_if_1pct_mosaic_20q11_with_99pct_retrieval = 1.0 - (1.0 - p_esc_8psc_if_1pct_mosaic_20q11 * (1.0 - f_ret_ref)) * (1.0 - p_meta_ref * (1.0 - f_ret_ref))
    p_harm_8psc_simple_1pct_residual_of_8p0892e_6 = p_harm_8psc_if_1pct_mosaic_20q11_and_1e4_ap1903_resist * (1.0 - f_ret_ref)
    bpr04_post_retrieval_offsite_share_sensitivity = {
        f"already_offsite_{int(s * 100)}pct": {
            "s_already_offsite": s,
            "baseline_8psc_post_99pct_retrieval": round(
                compute_dose_level_tumor_harm_scenarios_bpr04(
                    p_esc_per_psc=p_esc_ref, n_psc=8.0, p_20q=p_20q_ref, p_meta=p_meta_ref, f_retrieval=f_ret_ref, s_already_offsite=s
                )["post_retrieval_conditional_harm"],
                12,
            ),
            "mosaic_1pct_8psc_post_99pct_retrieval": round(
                compute_dose_level_tumor_harm_scenarios_bpr04(
                    p_esc_per_psc=q_esc_1pct_mosaic_20q11, n_psc=8.0, p_20q=0.0, p_meta=p_meta_ref, f_retrieval=f_ret_ref, s_already_offsite=s
                )["post_retrieval_conditional_harm"],
                12,
            ),
        }
        for s in (0.0, 0.5, 1.0)
    }
    # Whole-product post-purge burden (9.335 PSCs across 9.335e8 total cells at f_PSC,eff = 1e-8) and pre-Tier-A intermediate whole-product burden (93.35 PSCs across 9.335e8 total cells at f_PSC = 1e-7; R9-S1-L1B-01 & AUDIT-REF [DEC-074/075]):
    p_esc_9p335psc_if_1pct_mosaic_20q11 = 1.0 - math.exp(-9.335 * q_esc_1pct_mosaic_20q11)
    p_harm_9p335psc_if_1pct_mosaic_20q11_true_pre_retrieval = 1.0 - (1.0 - p_esc_9p335psc_if_1pct_mosaic_20q11) * (1.0 - p_meta_ref)
    p_harm_9p335psc_if_1pct_mosaic_20q11_with_99pct_retrieval = 1.0 - (1.0 - p_esc_9p335psc_if_1pct_mosaic_20q11 * (1.0 - f_ret_ref)) * (1.0 - p_meta_ref * (1.0 - f_ret_ref))
    q_esc_1pct_mosaic_10x_resist = p_20q_mosaic_lod_bound * 1e-7 + (1.0 - p_20q_mosaic_lod_bound) * 1e-8
    p_esc_93p35psc_10000x_mosaic = 1.0 - math.exp(-93.35 * q_esc_1pct_mosaic_20q11)
    p_harm_93p35psc_10000x_mosaic_pre_retrieval = 1.0 - (1.0 - p_esc_93p35psc_10000x_mosaic) * (1.0 - p_meta_ref)
    p_harm_93p35psc_10000x_mosaic_with_99pct_retrieval = 1.0 - (1.0 - p_esc_93p35psc_10000x_mosaic * (1.0 - f_ret_ref)) * (1.0 - p_meta_ref * (1.0 - f_ret_ref))
    p_esc_93p35psc_10x_mosaic = 1.0 - math.exp(-93.35 * q_esc_1pct_mosaic_10x_resist)
    p_harm_93p35psc_10x_mosaic_pre_retrieval = 1.0 - (1.0 - p_esc_93p35psc_10x_mosaic) * (1.0 - p_meta_ref)
    p_harm_93p35psc_10x_mosaic_with_99pct_retrieval = 1.0 - (1.0 - p_esc_93p35psc_10x_mosaic * (1.0 - f_ret_ref)) * (1.0 - p_meta_ref * (1.0 - f_ret_ref))
    whole_product_safety_model["unconditional_patient_level_tumor_harm_and_two_stage_psc_purge_model_sonnet55_r5"] = {
        "finding_ids": ["AUDIT-REF", "AUDIT-REF", "AUDIT-REF", "AUDIT-REF", "MW-R5-S1-02", "AUDIT-REF", "AUDIT-REF", "AUDIT-REF", "AUDIT-REF", "AUDIT-REF", "MW-R6-S2-01", "MW-R6-S1-02", "R9-S1-L1B-01", "AUDIT-REF", "R9-S3-L1-01", "R9-S3-L1-02"],
        "provenance": "Audit Convergence Round 5 Step 5, Audit Full Round 5 Step 6, AUDIT-REF Round 6 Step 2, Audit Round 6 Step 4, Audit Full Round 6 Step 5, GPT AUDIT-REF Audit Round 9 Step 2 & Audit Round 9 Step 3 (DEC-047/048/049/050/052/053/074/075; Tang 2011 PMID:21841799; Avery 2013 PMID:24286026; Veres 2019 PMID:31068696; Liang 2018 PMID:30429614; Straathof 2005 PMID:15728125)",
        "evidence_class": "STAGE0_GATE_CHECKLIST_AND_CONDITIONAL_SCENARIO_BOUND_NOT_RANKER_SCORE_INPUT",
        "model_conditioning_scope_sol61_r6": "conditional_scenario_bound_with_mosaic_20q11_and_untriggered_intragraft_terms",
        "conditional_scenario_bound_not_unconditional_correlated_selection_disclaimer_muse_r6": (
            "This equation is a conditional scenario bound under parameterized post-gate residual fractions; "
            "because 20q11.21/BCL2L1 amplification, partial pluripotency retention, and iCasp9/AP1903 apoptosis resistance "
            "are mechanistically coupled along the mitochondrial MOMP/XIAP axis (Avery et al. 2013 PMID:24286026), "
            "Stage-0 Gate 0S directly measures the coupled joint survival probability empirically via the post-stress 20q11.21 outgrowth assay "
            "(obs_post_stress_20q11_bcl2l1_outgrowth_fold <= 1.0) and the sorted hazard-state proliferative clonogenic assay "
            "(0/299,573,228 colonies under pulsed human-PK AP1903 monotherapy; MW-R6-S2-01 & MW-R6-S1-02 [DEC-053])."
        ),
        "unconditional_patient_level_harm_equation": (
            "True pre-retrieval conditional component (withholding surgical retrieval credit until retrieval occurs, assuming omitted/untreated branch u = 0): "
            "P_harm_true_pre_retrieval_cond_u0 = 1 - (1 - P_escape_given_AP1903) * (1 - p_20q11_bclxl_resistant_clone) * (1 - p_untriggered_extragraft_metastasis); "
            "Post-retrieval conditional component decomposing p_meta into already-off-site fraction s (invariant to f_ret) and declared future-preventable fraction (1 - s): "
            "P_harm_post_retrieval_cond_u0 = 1 - (1 - P_escape_given_AP1903 * (1 - f_ret)) * (1 - p_20q11_bclxl_resistant_clone) * (1 - p_meta * (s + (1 - s) * (1 - f_ret))); "
            "Extended recipient-wide equation including omitted/untreated branch probability u = P_untriggered_intragraft_teratoma * (1 - P_clinical_detection_and_ablation): "
            "P_harm_population_wide = u + (1 - u) * r (unestimated without a clinical safety upper bound on u < 1)."
        ),
        "population_wide_patient_harm_upper_bound": None,
        "population_wide_patient_harm_upper_bound_status": "UNESTIMATED_PENDING_CLINICAL_SAFETY_BOUND_ON_OMITTED_UNTREATED_BRANCH_U",
        "computed_reference_patient_harm_upper_bound": None,
        "computed_reference_patient_harm_upper_bound_bpr04_note": (
            "Cleared from misleading upper-bound label under BPR-04 / DEC-133: the legacy 2e-8 figure assumed omitted/untreated branch u = 0 AND "
            "applied 99% retrieval credit to p_meta before retrieval. Without a defensible clinical upper bound on u < 1 in u + (1 - u) * r, "
            "population-wide patient harm risk is unestimated."
        ),
        "computed_reference_conditional_component_u0_true_pre_retrieval": round(p_harm_ref_true_pre_retrieval_u0, 12),
        "computed_reference_conditional_component_u0_assuming_100pct_preventable_meta": round(p_harm_ref_u0_preventable_meta_only, 12),
        "computed_dose_level_8psc_patient_harm_pre_retrieval": round(p_harm_8psc_true_pre_retrieval, 12),
        "computed_dose_level_8psc_intragraft_pre_retrieval_with_100pct_preventable_post_retrieval_meta_legacy_9e8": round(p_harm_8psc_legacy_pre_intragraft_post_preventable_meta, 12),
        "computed_dose_level_8psc_patient_harm_with_99pct_en_bloc_retrieval": round(p_harm_8psc_with_99pct_retrieval_assuming_100pct_preventable_meta, 12),
        "computed_dose_level_8psc_patient_harm_with_99pct_en_bloc_retrieval_if_meta_already_offsite": round(p_harm_8psc_with_99pct_retrieval_if_already_offsite, 12),
        "bpr04_post_retrieval_already_offsite_share_sensitivity": bpr04_post_retrieval_offsite_share_sensitivity,
        "computed_dose_level_8psc_escape_if_1pct_mosaic_20q11_pre_retrieval": round(p_esc_8psc_if_1pct_mosaic_20q11, 10),
        "computed_dose_level_8psc_harm_if_1pct_mosaic_20q11_true_pre_retrieval_no_explant_discount": round(p_harm_8psc_if_1pct_mosaic_20q11_true_pre_retrieval_no_explant_discount, 10),
        "computed_dose_level_8psc_harm_with_1pct_mosaic_20q11_pre_retrieval_bound": round(p_harm_8psc_if_1pct_mosaic_20q11_true_pre_retrieval_no_explant_discount, 10),
        "computed_dose_level_8psc_harm_with_1pct_mosaic_20q11_subclone_bound": round(p_harm_8psc_if_1pct_mosaic_20q11_and_1e4_ap1903_resist, 10),
        "computed_dose_level_8psc_escape_only_with_1pct_mosaic_20q11_and_99pct_en_bloc_retrieval": round(p_esc_only_8psc_if_1pct_mosaic_20q11_with_99pct_retrieval, 12),