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…

    if niche_k == "NICHE_TRIHORMONAL_120UM_MVF_CAO2":
        logit_g5 += (
            pw * 5.625
            + _pdelta("stage7_trihormonal_120um_mvf_cao2_niche_prior", 0.45, "Gate5_72h_Vascular_Oxygen_and_80yr_Safety", "NICHE_TRIHORMONAL_120UM_MVF_CAO2", 0.45)
            + _rdelta("Gate5_72h_Vascular_Oxygen_and_80yr_Safety", "NICHE_TRIHORMONAL_120UM_MVF_CAO2", 0.45)
        )
    elif niche_k == "NICHE_NAKED_AVASCULAR_TRANSPLANT":
        logit_g5 -= pw * 6.875 - _rdelta("Gate5_72h_Vascular_Oxygen_and_80yr_Safety", "NICHE_NAKED_AVASCULAR_TRANSPLANT", -0.55)
    elif niche_k == "NICHE_UNEDITED_MACRODEVICE_ENCAPSULATION":
        logit_g5 -= pw * 11.875 - _rdelta("Gate5_72h_Vascular_Oxygen_and_80yr_Safety", "NICHE_UNEDITED_MACRODEVICE_ENCAPSULATION", -0.95)

    if saf_k == "SAF_AAVS1_CAG_ICASP9_BIALLELIC":
        logit_g5 += (
            pw * 4.75
            + _rdelta("Gate5_72h_Vascular_Oxygen_and_80yr_Safety", "SAF_AAVS1_CAG_ICASP9_BIALLELIC", 0.38)
            + signed_gene_signal(target_profiles, ["CASP9"], scale=0.25, mode="gof", branch_key="Gate5_SAF_ICASP9")
        )
    elif saf_k == "SAF_G6PC2_ENDOGENOUS_ICASP9":
        logit_g5 += (
            pw * -5.625
            + _rdelta("Gate5_72h_Vascular_Oxygen_and_80yr_Safety", "SAF_G6PC2_ENDOGENOUS_ICASP9", -0.45)
            + signed_gene_signal(target_profiles, ["G6PC2"], scale=0.25, is_knockout=True, branch_key="Gate5_SAF_ICASP9")
            + signed_gene_signal(target_profiles, ["CASP9"], scale=0.25, mode="gof", branch_key="Gate5_SAF_ICASP9")
        )
    elif saf_k == "SAF_NONE":
        logit_g5 -= (
            (pw * 5.625 - _rdelta("Gate5_72h_Vascular_Oxygen_and_80yr_Safety", "SAF_NONE_PEDIATRIC", -0.45))
            if recipient_context == "Pediatric_Early_Onset_T1D"
            else (pw * 3.125 - _rdelta("Gate5_72h_Vascular_Oxygen_and_80yr_Safety", "SAF_NONE_LADA", -0.25))
        )

    _gate_sigmoid = sigmoid_unclipped if sigmoid is _DEFAULT_CLAMPED_SIGMOID else sigmoid
    g1 = _gate_sigmoid(logit_g1)
    g2a = _gate_sigmoid(logit_g2a)
    g2b = _gate_sigmoid(logit_g2b)
    g3 = _gate_sigmoid(logit_g3)
    g4 = _gate_sigmoid(logit_g4)
    g5 = _gate_sigmoid(logit_g5)

    g2_combined = g2a * g2b
    unpenalized_product = g1 * g2_combined * g3 * g4 * g5

    # Multiplex DSB translocation penalty + nickase base-edit penalty wired to ENGINEERING_PRIORS_AND_SENSITIVITY_TABLE
    lambda_k = _finite_real(
        ENGINEERING_PRIORS_AND_SENSITIVITY_TABLE.get("locus_dsb_penalty_rate_lambda_K", {}).get("point_estimate", 0.15), "Locus penalty rate"
    )
    gamma_b = _finite_real(
        ENGINEERING_PRIORS_AND_SENSITIVITY_TABLE.get("base_edit_nickase_penalty_factor_gamma_B", {}).get("point_estimate", 0.965), "Base-edit penalty factor"
    )
    mfg_penalty = engineering_complexity_discount(total_cuts, total_base_edits, lambda_k, gamma_b)
    penalized_index = unpenalized_product * mfg_penalty
    geom_mean = unpenalized_product ** (1.0 / 5.0)
    geom_mean_six_subgates = unpenalized_product ** (1.0 / 6.0)

    gates_unrounded = {
        "Gate1_Maturation_GSIS_and_Paracrine": g1,
        "Gate2A_Allo_Adaptive_T_and_DSA_Stealth": g2a,
        "Gate2B_Autoimmune_T1D_Memory_and_Indirect_APC_Stealth": g2b,
        "Gate3_Innate_NK_Macrophage_and_IBMIR_Shield": g3,
        "Gate4_Intrinsic_Cytokine_ER_Granzyme_and_Amyloid_Resilience": g4,
        "Gate5_72h_Vascular_Oxygen_and_80yr_Safety": g5,
    }
    gate_logits_unrounded = {
        "Gate1_Maturation_GSIS_and_Paracrine": logit_g1,
        "Gate2A_Allo_Adaptive_T_and_DSA_Stealth": logit_g2a,
        "Gate2B_Autoimmune_T1D_Memory_and_Indirect_APC_Stealth": logit_g2b,
        "Gate3_Innate_NK_Macrophage_and_IBMIR_Shield": logit_g3,
        "Gate4_Intrinsic_Cytokine_ER_Granzyme_and_Amyloid_Resilience": logit_g4,
        "Gate5_72h_Vascular_Oxygen_and_80yr_Safety": logit_g5,
    }
    gates = {k: round(v, 4) for k, v in gates_unrounded.items()}
    bottleneck_gate = min(gates_unrounded.items(), key=lambda kv: kv[1])

    # Propagate gene-level posterior SEs into the 10th-percentile lower credible bound (AT-18, live-wired to lower_10pct_cred_bound_hyperparameters per Audit R10)
    lb_params = _aux_param("lower_10pct_cred_bound_hyperparameters", {})
    if not isinstance(lb_params, dict):
        raise ValueError("Heuristic floor parameters must be an explicit mapping")
    z_mult = _finite_real(lb_params.get("z_multiplier", 1.2816), "Floor z multiplier")
    cut_disc = _finite_real(lb_params.get("locus_cut_linear_discount", 0.008), "Floor locus discount")
    def_g_se = _finite_real(lb_params.get("default_gene_se", 0.35), "Default gene dispersion")
    no_g_se = _finite_real(lb_params.get("no_gene_se", 0.45), "Missing gene dispersion")
    if min(z_mult, cut_disc, def_g_se, no_g_se) < 0:
        raise ValueError("Heuristic floor discounts and dispersions must be nonnegative")

    stack_genes = sorted(
        set(
            ALLO_CLOAK_MODULES[allo_k]["genes"]
            + AUTOANTIGEN_MODULES[auto_k]["genes"]
            + CYTOKINE_GRANZYME_MODULES[cyto_k]["genes"]
            + ER_AMYLOID_MODULES[er_k]["genes"]
            + NICHE_VASCULAR_MODULES[niche_k]["genes"]
            + SAFETY_SWITCH_MODULES[saf_k]["genes"]
        )
    )
    if stack_genes:
        errors = [_profile_standard_error(target_profiles.get(g, {}), def_g_se) for g in stack_genes]
        largest = max(errors)
        # Scaled RMS avoids squaring huge finite SEs or underflowing tiny SEs.
        se_combined = largest * math.sqrt(sum((se / largest) ** 2 for se in errors) / len(errors)) if largest else 0.0
    else:
        se_combined = no_g_se
    b_quad_disc = _sec_param("lower_10pct_cred_bound_b_edit_quadratic_discount", 0.005)
    if b_quad_disc < 0:
        raise ValueError("Base-edit floor discount must be nonnegative")
    lower_10pct_bound = round(
        max(0.0, penalized_index * math.exp(-z_mult * se_combined) - cut_disc * total_cuts), 4
    )
    lower_10pct_bound_with_b_quad = round(
        max(0.0, penalized_index * math.exp(-z_mult * se_combined) - cut_disc * total_cuts - b_quad_disc * (total_base_edits ** 2)), 4
    )

    return {
        "gate_scores": gates,
        "gate_logits_unrounded": gate_logits_unrounded,
        "unpenalized_gate_product": round(unpenalized_product, 4),
        "geometric_mean_gate_score": round(geom_mean, 4),
        "geometric_mean_six_subgate_score": round(geom_mean_six_subgates, 4),
        "limiting_bottleneck_gate": bottleneck_gate[0],
        "limiting_bottleneck_score": round(bottleneck_gate[1], 4),
        "manufacturing_locus_penalty_factor": round(mfg_penalty, 4),
        "series_system_joint_survival_probability": round(penalized_index, 4),
        "series_system_joint_survival_probability_unrounded": penalized_index,
        "lower_10pct_cred_bound": lower_10pct_bound,
        "lower_10pct_cred_bound_with_b_edit_quadratic_discount": lower_10pct_bound_with_b_quad,
        "heuristic_conservative_floor_index": lower_10pct_bound,
        "lower_bound_field_note": (
            "Heuristic conservative scenario floor index combining inverse-root evidence sparsity and locus burden "
            "(NOT a calibrated Bayesian 10th-percentile credible interval; retained under key lower_10pct_cred_bound for backward compatibility; "
            "lower_10pct_cred_bound_with_b_edit_quadratic_discount additionally subtracts 0.005 * B^2 for nickase base-edit stacks per Finding 013)."
        ),
        "estimand_note": "Prior-Anchored Multi-Gate Scenario Index (NOT a calibrated human survival probability).",
    }


def _combination_order_key(result: dict) -> tuple:
    return (
        result["is_feasible_candidate"],
        result["composite_series_system_utility_unrounded"],
        result["composite_series_system_utility"],
        result["unblocked_diagnostic_utility"],
        -result["total_genomic_cuts_K"],
        -result["total_base_edits_B"],
        "AUTO_DUAL_INS_LEADER_AND_DRIP_EDIT" in result["combination_id"],
        result["combination_id"],
    )


def run_combinatorial_multi_gate_search(target_profiles: dict) -> list[dict]:
    results = []
    w_ped, w_adult = _composite_utility_weights()
    for allo_k, auto_k, cyto_k, er_k, niche_k, saf_k in product(
        ALLO_CLOAK_MODULES.keys(),
        AUTOANTIGEN_MODULES.keys(),
        CYTOKINE_GRANZYME_MODULES.keys(),
        ER_AMYLOID_MODULES.keys(),
        NICHE_VASCULAR_MODULES.keys(),
        SAFETY_SWITCH_MODULES.keys(),
    ):
        total_cuts = (
            ALLO_CLOAK_MODULES[allo_k]["cuts"]
            + AUTOANTIGEN_MODULES[auto_k]["cuts"]
            + CYTOKINE_GRANZYME_MODULES[cyto_k]["cuts"]
            + ER_AMYLOID_MODULES[er_k]["cuts"]
            + NICHE_VASCULAR_MODULES[niche_k]["cuts"]
            + SAFETY_SWITCH_MODULES[saf_k]["cuts"]
        )
        total_base_edits = (
            ALLO_CLOAK_MODULES[allo_k]["base_edits"]
            + AUTOANTIGEN_MODULES[auto_k]["base_edits"]
            + CYTOKINE_GRANZYME_MODULES[cyto_k]["base_edits"]
            + ER_AMYLOID_MODULES[er_k]["base_edits"]
            + NICHE_VASCULAR_MODULES[niche_k]["base_edits"]
            + SAFETY_SWITCH_MODULES[saf_k]["base_edits"]
        )

        ped = compute_series_system_utility(
            allo_k, auto_k, cyto_k, er_k, niche_k, saf_k, target_profiles, "Pediatric_Early_Onset_T1D"
        )
        lada = compute_series_system_utility(
            allo_k, auto_k, cyto_k, er_k, niche_k, saf_k, target_profiles, "Adult_Onset_LADA"
        )
        raw_composite = w_ped * ped["series_system_joint_survival_probability"] + w_adult * lada["series_system_joint_survival_probability"]
        graveyard_flags = evaluate_graveyard_rules_for_stack(
            allo_k, auto_k, cyto_k, er_k, niche_k, saf_k, total_base_edits
        )
        has_block = any(r.get("severity_level") == "BLOCK" for r in graveyard_flags)
        if has_block:
            ped["unblocked_diagnostic_survival_index"] = ped["series_system_joint_survival_probability"]
            lada["unblocked_diagnostic_survival_index"] = lada["series_system_joint_survival_probability"]
            ped["series_system_joint_survival_probability"] = 0.0
            ped["series_system_joint_survival_probability_unrounded"] = 0.0
            ped["lower_10pct_cred_bound"] = 0.0
            ped["lower_10pct_cred_bound_with_b_edit_quadratic_discount"] = 0.0
            ped["heuristic_conservative_floor_index"] = 0.0
            lada["series_system_joint_survival_probability"] = 0.0
            lada["series_system_joint_survival_probability_unrounded"] = 0.0
            lada["lower_10pct_cred_bound"] = 0.0
            lada["lower_10pct_cred_bound_with_b_edit_quadratic_discount"] = 0.0
            lada["heuristic_conservative_floor_index"] = 0.0
            composite = 0.0
            exact_comp_unrounded = 0.0
        else:
            composite = raw_composite
            exact_comp_unrounded = (
                w_ped * ped["series_system_joint_survival_probability_unrounded"]
                + w_adult * lada["series_system_joint_survival_probability_unrounded"]
            )

        results.append({
            "combination_id": f"{allo_k}__{auto_k}__{cyto_k}__{er_k}__{niche_k}__{saf_k}",
            "modules": {
                "allo_cloak": ALLO_CLOAK_MODULES[allo_k]["label"],
                "autoantigen_stealth": AUTOANTIGEN_MODULES[auto_k]["label"],
                "cytokine_and_granzyme_shield": CYTOKINE_GRANZYME_MODULES[cyto_k]["label"],
                "er_stress_and_amyloid_shield": ER_AMYLOID_MODULES[er_k]["label"],
                "vascular_and_oxygen_niche": NICHE_VASCULAR_MODULES[niche_k]["label"],
                "safety_switch": SAFETY_SWITCH_MODULES[saf_k]["label"],
            },
            "total_genomic_cuts_K": total_cuts,
            "total_base_edits_B": total_base_edits,
            "multiplex_base_edit_plus_dsb_translocation_risk_flag": bool(total_base_edits >= 2 and total_cuts >= 4),
            "unswitched_immune_evasive_clinical_hold": bool(
                allo_k != "ALLO_NONE_UNEDITED_OR_SYSTEMIC_IMMUNOSUPPRESSION" and saf_k == "SAF_NONE"
            ),
            "is_feasible_candidate": not has_block,
            "unblocked_diagnostic_utility": round(raw_composite, 4),
            "utility_pediatric_early_onset_t1d": ped,
            "utility_adult_onset_lada": lada,
            "composite_series_system_utility": round(composite, 4),
            "composite_series_system_utility_unrounded": exact_comp_unrounded,
            "triggered_graveyard_rules": graveyard_flags,
        })

    results.sort(key=_combination_order_key, reverse=True)
    rounded_tie_counts = Counter(
        (r["is_feasible_candidate"], r["composite_series_system_utility"]) for r in results
    )
    for idx, r in enumerate(results, 1):
        r["global_rank_among_all_combinations"] = idx
        r["rank_tie_group_size"] = rounded_tie_counts[
            (r["is_feasible_candidate"], r["composite_series_system_utility"])
        ]
    return results


def _strict_prob_float_iip0024(val: object, label: str) -> float:
    if isinstance(val, bool) or not isinstance(val, (int, float)):
        raise ValueError(f"{label} must be an explicit finite int or float (not bool/str), got {val!r} (IIP-0024; DEC-103)")
    fv = float(val)
    if not math.isfinite(fv):