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…

                "locked_shared_ax_pouch_exact_6dp": round(active_tree["locked_2route_shared_ax_pouch_exact"], 6),
                "modular_cell_cuff_pouch_compatibility_required": True,
                "programmatic_2pow12_generator_audit_iip_0022": active_tree,
                "iip_0024_donor_bank_h1_sensitivity_audit": compute_donor_bank_h1_sensitivity_iip_0024(0.25),
                "iip_0028_paired_mcnemar_and_phi_ab_concordance_audit": compute_paired_mcnemar_and_phi_ab_concordance_audit_iip_0028(),
                "dependence_model_disclosure": (
                    "Common-shock ceiling vector c is an uncalibrated dependence assumption; legacy 3-slot pouch union "
                    "and shared-A/X 2-route CaO2+catalase pouch union are reported side by side with explicit labels, "
                    "alongside conditional Hurdle-1 donor-bank failure-share sensitivity (phi_donor = 0.25; IIP-0024; DEC-103) "
                    "and conditional Hurdle-2/3 A-B Frechet dependence sensitivity (phi_AB in [0, 1]; IIP-0028; DEC-106)."
                ),
            },
            "prior_2026_11_15_dec098_baseline": {
                "design_a_hurdles": [0.88, 0.78, 0.56, 0.68],
                "design_b_hurdles": [0.88, 0.79, 0.64, 0.70],
                "design_x_hurdles": [0.88, 0.81, 0.70, 0.68],
                "three_designs_hurdles": [0.88, 0.87, 0.85, 0.79],
                "design_a_rounded_pct": 26,
                "design_b_rounded_pct": 31,
                "design_x_rounded_pct": 34,
                "three_designs_rounded_pct": 51,
                "three_designs_2pow12_locked_exact": round(dec098_ref_tree["locked_3slot_2pow12_exact"], 4),
                "three_designs_stage0_modular_cell_x_pouch_exact": round(dec098_ref_tree["legacy_modular_3slot_cell_x_pouch_exact"], 4),
                "programmatic_2pow12_generator_reproduction_iip_0022": dec098_ref_tree,
            },
            "prior_2026_11_05_baseline": {
                "design_a_hurdles": [0.88, 0.78, 0.50, 0.60],
                "three_designs_hurdles": [0.88, 0.82, 0.72, 0.72],
                "one_design_exact": 0.20592,
                "one_design_rounded_pct": 21,
                "three_designs_exact": 0.37407744,
                "three_designs_rounded_pct": 37,
            },
        },
        "section3_score_and_rank_measure_reconciliation": {
            "overall_50_50_composite_score": {
                "Design_A": 0.1094,
                "Design_X_grid_2": 0.1056,
                "Design_B_grid_25": 0.0675,
                "definition": "Equal 50:50 weight on Pediatric_Early_Onset_T1D and Adult_Onset_LADA (composite_series_system_utility)",
            },
            "childrens_pediatric_t1d_score": {
                "Design_A": 0.1078,
                "Design_X_grid_2": 0.1041,
                "Design_B_grid_25": 0.0665,
                "definition": "Pediatric_Early_Onset_T1D cohort utility (utility_pediatric_early_onset_t1d.series_system_joint_survival_probability)",
            },
            "adults_lada_score": {
                "Design_A": 0.1109,
                "Design_X_grid_2": 0.1070,
                "Design_B_grid_25": 0.0684,
                "definition": "Adult_Onset_LADA cohort utility (utility_adult_onset_lada.series_system_joint_survival_probability)",
            },
            "rank_column_measure": "overall_50_50_composite_score",
            "rank_column_explanation": (
                "global_rank_among_all_combinations (#1 for Design A, #2 for Design X, #25 for Design B out of 2,160) "
                "is sorted on the overall 50:50 composite score (composite_series_system_utility_unrounded / composite_series_system_utility "
                "in _combination_order_key). On the children's score alone (Pediatric_Early_Onset_T1D), Design A ranks #1, Design X ranks #2, and Design B ranks #24."
            ),
        },
        "new_open_question": {
            "id": "OQ-016",
            "title": "Which assumptions and definition of success sit behind the four-hurdle odds estimate?",
            "plain": (
                "The 27%, 31% and 36% single-design figures (Designs A, B and X) and the 53% three-design figure are computational "
                "team judgements for clearing four in-body hurdles in sequence, assuming the edited cells work as designed and pass lab safety "
                "checks before any trial. Layering new untested edits together can shift earlier human-anchored hurdles too, moving from one "
                "design to three depends on how much the designs overlap at each hurdle, and the estimate depends on which clinical outcome counts as success."
            ),
            "detail": (
                "Raised in IIP-0003 (issue #3) and reassessed on 2026-11-16 after IIP-0016..IIP-0024. Each step in the four-hurdle estimate is "
                "judged for a design still in the running after the earlier hurdles, with three-design conditional pass rates derived from an "
                "explicit 4,096-state (2^12) common-shock tree across Designs A (27%), B (31%) and X (36%) giving 52.59% (about 53%) for three "
                "locked slots or 50.78% when Designs A and X share one CaO2+catalase pouch route (55.63% / 54.12% under Stage-0 cell-line x pouch "
                "modularity; up from 21% and 37% on 2026-11-05). Lab release gates "
                "(OQ-012 safety-switch escape, OQ-006 DNA rearrangements, and product-specific Gate 1 insulin and glucagon function plus Stage-0 "
                "construct gates) sit outside the four hurdles as pre-trial pass/fail conditions, and a single clinical endpoint (such as one-year "
                "insulin independence without anti-rejection drugs and without severe hypoglycaemia) must be fixed before replacing starting judgements with data."
            ),
            "settle": (
                "Fix one clinical definition of success, test the per-design and shared failure assumptions in Stage 0-2 experiments, "
                "and replace the computational judgements with measured pass rates as lab and preclinical results arrive."
            ),
            "tests": ["1", "2A", "2B", "3", "4", "5"],
            "designs": ["A", "B", "X"],
            "linked_iip": "IIP-0003",
        },
    }


def _rank_precision_summary(a_ranks: list[int], b_ranks: list[int], scheme: str, *, max_rank: int | None = None) -> dict:
    """Finite simulation precision only; these are not clinical probabilities."""
    grid_size = math.prod(len(modules) for modules in (
        ALLO_CLOAK_MODULES, AUTOANTIGEN_MODULES, CYTOKINE_GRANZYME_MODULES,
        ER_AMYLOID_MODULES, NICHE_VASCULAR_MODULES, SAFETY_SWITCH_MODULES,
    ))
    max_rank = grid_size if max_rank is None else max_rank
    if type(max_rank) is not int or not 1 <= max_rank <= grid_size:
        raise ValueError("Rank population must be a positive integer within the configured grid")
    if not isinstance(a_ranks, list) or not isinstance(b_ranks, list) or not a_ranks or len(a_ranks) != len(b_ranks) or any(type(rank) is not int or rank < 1 for rank in a_ranks + b_ranks):
        raise ValueError("Rank precision requires aligned nonempty positive integer rank draws")
    if any(rank > max_rank for rank in a_ranks + b_ranks):
        raise ValueError("Rank draws must lie within their declared population")
    def wilson(k, n):
        z = 1.959963984540054
        p = k / n
        den = 1 + z*z/n
        center = (p + z*z/(2*n))/den
        half = z * math.sqrt(p*(1-p)/n + z*z/(4*n*n))/den
        return [center-half, center+half]
    def quantiles(values):
        v = sorted(values)
        def quantile(q):
            index = (len(v)-1)*q
            lo = int(index)
            return v[lo] + (v[min(lo+1,len(v)-1)]-v[lo])*(index-lo)
        return {str(q): quantile(q) for q in (0.025, 0.25, 0.5, 0.75, 0.975)}
    n = len(a_ranks)
    return {"random_seed": 20261022, "sampling_scheme": scheme,
            "precision_status": "EXPLORATORY_FINITE_MONTE_CARLO_NOT_CLINICAL_PROBABILITY",
            "scenario_a_rank1_frequency_wilson95": wilson(sum(r==1 for r in a_ranks),n),
            "scenario_a_top3_frequency_wilson95": wilson(sum(r<=3 for r in a_ranks),n),
            "scenario_a_rank_quantiles_linear": quantiles(a_ranks),
            "scenario_b_rank_quantiles_linear": quantiles(b_ranks)}


def _numeric_scalar_paths(value, prefix=""):
    if isinstance(value, dict):
        return [p for key, val in value.items() for p in _numeric_scalar_paths(val, f"{prefix}.{key}".strip("."))]
    if isinstance(value, list):
        return [p for idx, val in enumerate(value) for p in _numeric_scalar_paths(val, f"{prefix}[{idx}] pre".replace(" pre", ""))]
    return [prefix] if isinstance(value, (int,float)) and not isinstance(value,bool) else []


def _direct_output_score(combination: dict, gate_noise: list[float]) -> float:
    """Re-evaluate exact production utility under paired output-logit noise.

    Display-rounded manufacturing fields are never numerical inputs. The same
    recipient weights and engineering prior registry serve both estimands.
    """
    ped = combination["utility_pediatric_early_onset_t1d"]["gate_logits_unrounded"]
    adult = combination["utility_adult_onset_lada"]["gate_logits_unrounded"]
    if len(gate_noise) != len(ped) or set(ped) != set(adult):
        raise ValueError("Output-logit sensitivity requires aligned gates and one noise term per gate")
    if not combination.get("is_feasible_candidate", True):
        return 0.0
    if combination["utility_pediatric_early_onset_t1d"].get("estimand_note", "").startswith("Zero evidence loaded"):
        return 0.0
    mfg = engineering_complexity_discount(
        combination["total_genomic_cuts_K"], combination["total_base_edits_B"],
        _finite_real(ENGINEERING_PRIORS_AND_SENSITIVITY_TABLE["locus_dsb_penalty_rate_lambda_K"]["point_estimate"], "Locus penalty rate"),
        _finite_real(ENGINEERING_PRIORS_AND_SENSITIVITY_TABLE["base_edit_nickase_penalty_factor_gamma_B"]["point_estimate"], "Base-edit penalty factor"),
    )
    _gate_sigmoid = sigmoid_unclipped if sigmoid is _DEFAULT_CLAMPED_SIGMOID else sigmoid
    ped_prod = adult_prod = 1.0
    for gate, noise in zip(ped, gate_noise):
        noise = _finite_real(noise, "Output-logit perturbation")
        ped_prod *= _gate_sigmoid(ped[gate] + noise)
        adult_prod *= _gate_sigmoid(adult[gate] + noise)
    w_ped, w_adult = _composite_utility_weights()
    return mfg * (w_ped * ped_prod + w_adult * adult_prod)


def compute_direct_output_logit_sensitivity_analysis(target_profiles, all_combos, studies=None, omics=None):
    """Seed-replayable evaluation with registry restoration even after errors."""
    import copy
    original_registry = copy.deepcopy(COMPLETE_GATE_COEFFICIENT_REGISTRY)
    original_priors = copy.deepcopy(ENGINEERING_PRIORS_AND_SENSITIVITY_TABLE)
    try:
        return _compute_direct_output_logit_sensitivity_analysis(target_profiles, all_combos, studies, omics)
    finally:
        COMPLETE_GATE_COEFFICIENT_REGISTRY.clear()
        COMPLETE_GATE_COEFFICIENT_REGISTRY.update(original_registry)
        ENGINEERING_PRIORS_AND_SENSITIVITY_TABLE.clear()
        ENGINEERING_PRIORS_AND_SENSITIVITY_TABLE.update(original_priors)


def _compute_direct_output_logit_sensitivity_analysis(
    target_profiles: dict,
    all_combos: list[dict],
    studies: list[dict] | None = None,
    omics: dict | None = None,
) -> dict:
    """
    Computes (1) the exact variance decomposition across the uniform 2,160-stack grid (six pooled
    pediatric gate logits with all three gene-signal channels zeroed vs loaded) and (2) a direct
    output-logit Monte Carlo perturbation analysis adding N(0, sigma_logit^2) noise directly to the
    six output gate logits (resolving Audit A03 + AUDIT-REF full 8/8 auxiliary leaf sampling
    and upstream profile rebuild).
    """
    import random
    import statistics

    zero_profiles = {
        g: {
            **v,
            "net_evidence_and_constraint_score": 0.0,
            "net_evidence_ko_score": 0.0,
            "net_evidence_gof_score": 0.0,
            "net_evidence_preserve_score": 0.0,
            "weighted_deleterious_penalty_score": 0.0,
        }
        for g, v in target_profiles.items()
    }
    corpus_only_profiles = {
        g: {
            **v,
            "net_evidence_ko_score": round(float(v.get("net_evidence_ko_score", 0.0)) - float(v.get("omics_ko_constraint_adjustment", 0.0)), 4),
            "net_evidence_gof_score": round(float(v.get("net_evidence_gof_score", 0.0)) - float(v.get("omics_gof_constraint_adjustment", 0.0)), 4),
            "net_evidence_preserve_score": round(float(v.get("net_evidence_preserve_score", 0.0)) - float(v.get("omics_gof_constraint_adjustment", 0.0)), 4),
            "net_evidence_and_constraint_score": round(
                float(v.get("net_evidence_and_constraint_score", 0.0))
                - (
                    float(v.get("omics_gof_constraint_adjustment", 0.0))
                    if v.get("default_perturbation_direction") == "Gain_of_Function_or_KnockIn"
                    else float(v.get("omics_ko_constraint_adjustment", 0.0))
                ),
                4,
            ),
        }
        for g, v in target_profiles.items()
    }
    omics_only_profiles = {
        g: {
            **v,
            "net_evidence_ko_score": round(float(v.get("omics_ko_constraint_adjustment", 0.0)), 4),
            "net_evidence_gof_score": round(float(v.get("omics_gof_constraint_adjustment", 0.0)), 4),
            "net_evidence_preserve_score": round(float(v.get("omics_gof_constraint_adjustment", 0.0)), 4),
            "net_evidence_and_constraint_score": round(
                float(v.get("omics_gof_constraint_adjustment", 0.0))
                if v.get("default_perturbation_direction") == "Gain_of_Function_or_KnockIn"
                else float(v.get("omics_ko_constraint_adjustment", 0.0)),
                4,
            ),
            "weighted_deleterious_penalty_score": 0.0,
        }
        for g, v in target_profiles.items()
    }
    zero_combos = run_combinatorial_multi_gate_search(zero_profiles)
    zero_by_id = {c["combination_id"]: c for c in zero_combos}
    identifiers = [candidate["combination_id"] for candidate in all_combos]
    if len(identifiers) != len(set(identifiers)) or set(identifiers) != set(zero_by_id):
        raise ValueError("Sensitivity requires each evaluated grid combination exactly once")
    all_combos = sorted(all_combos, key=_combination_order_key, reverse=True)
    corpus_only_by_id = {c["combination_id"]: c for c in run_combinatorial_multi_gate_search(corpus_only_profiles)}
    omics_only_by_id = {c["combination_id"]: c for c in run_combinatorial_multi_gate_search(omics_only_profiles)}

    structural_logits = []
    actual_logits = []
    corpus_only_logits = []