OpenIslet

scripts/verify_iip0043_wholegraft_gate0v_and_calibration.py

IIP-0043 / DEC-122 (CAND-034 / EXP-031 — Bucket 1 Closure, Stage S3-R2 Remediated)

script Release v0.8.0 gen-eb955f8266035aba 1008 KB · 76 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/verify_iip0043_wholegraft_gate0v_and_calibration.py · SHA-256: 20706180ed1ed6a2…

        )
        if not row_ok:
            all_8_crosslinks_ok = False
        eight_crosslinks_rows.append({
            "edge_id": eid,
            "source_queue_id": qid,
            "source_pmid": exp_pmid,
            "pre_iip0043_study_status": spec["pre_iip0043_study_status"],
            "pre_iip0043_prior_edge_ids": exp_priors,
            "previous_edge_state": spec["previous_edge_state"],
            "added_edge_status": spec["added_edge_status"],
            "evidence_scope": spec["evidence_scope"],
            "contextual_scope_note": spec["contextual_scope_note"],
            "expected_relation": exp_relation,
            "expected_target_gate_or_module": exp_target,
            "expected_applicability": exp_applicability,
            "expected_cited_outcome_tuples": exp_outcomes,
            "target_gate_or_module": edge_obj.get("target_gate_or_module") if edge_present else None,
            "relation": edge_obj.get("relation") if edge_present else None,
            "applicability": edge_obj.get("applicability") if edge_present else None,
            "primary_certification_eligible": edge_obj.get("primary_certification_eligible") if edge_present else None,
            "cited_outcome_tuples": cited_tuples,
            "exists_verbatim_in_ceg_v1": edge_present,
            "prior_edges_verified_in_ceg_v1": prior_all_present,
            "expected_relation_verified": relation_exact_match,
            "expected_target_gate_or_module_verified": target_exact_match,
            "expected_applicability_verified": applicability_exact_match,
            "expected_cited_outcome_tuples_verified": outcome_ids_exact_match,
            "verbatim_field_parity_verified": verbatim_fields_ok,
            "reciprocal_cited_by_edge_ids_verified": reciprocal_ok,
            "verified": row_ok,
        })
    eight_crosslinks_ledger = {
        "ceg_source_file": "data/extracted/context_evidence_graph_v1.json",
        "expected_crosslinks_count": len(CEG_DELTA_V33_EIGHT_CROSSLINKS_SPEC),
        "verified_crosslinks_count": sum(1 for r in eight_crosslinks_rows if r["verified"]),
        "all_eight_crosslinks_verified": all_8_crosslinks_ok,
        "all_eight_verbatim_field_parity_verified": bool(
            all_8_crosslinks_ok and all(r["verbatim_field_parity_verified"] for r in eight_crosslinks_rows)
        ),
        "verbatim_field_parity_fields_checked": [
            "edge_id",
            "queue_id",
            "pmid",
            "pre_iip0043_prior_edge_ids",
            "relation",
            "target_gate_or_module",
            "applicability",
            "cited_outcome_tuples",
            "reciprocal_cited_by_edge_ids",
            "primary_certification_eligible",
        ],
        "contextual_scope_summary": (
            "All 8 CEG-DELTA V3.3 cross-link edges are indirect/contextual scoping links "
            "(primary_certification_eligible=false). In particular, M0066:L3 (PMID:41403780, CD155/CD276 mouse study) "
            "provides immune-engraftment context and M0184:L4 (PMID:38956087, human islet stress study) provides "
            "stress-response context, both indirect to NW-08."
        ),
        "edges": eight_crosslinks_rows,
    }

    return {
        "bundle_mode": bundle_mode,
        "protected_manifest_source": manifest_source,
        "protected_files_zero_byte_invariance_ok": all_protected_ok,
        "protected_files_checked_total": len(protected_check),
        "playbook_sec4120_section_hash_verified": playbook_sec4120_ok,
        "protected_files": protected_check,
        "r4_playbook_sec4120_dec114_and_renderer_compatibility": r4_compat,
        "gy030_graveyard_parity": gy030_parity,
        "ceg_delta_v33_eight_crosslinks_ledger": eight_crosslinks_ledger,
        "graveyard_allocation": {
            "guardrail_id": GRAVEYARD_GUARDRAIL_ID,
            "graveyard_card_id": GRAVEYARD_CARD_ID,
            "decollision_note": "GY-030 / OFFGRID_GUARD_020 allocated cleanly to CAND-034 (IIP-0043); CAND-031 owns GY-029.",
        },
        "dual_evaluator_composite_release_governance": {
            "option2_zero_lims_touch_active": True,
            "executable_composite_wrapper": "evaluate_gate0v_composite_release.py",
            "lot_cli_entrypoint": "verify_iip0043_wholegraft_gate0v_and_calibration.py --evaluate-lot <lot.json> --trusted-qualification-store <store>",
            "trusted_store_deployment_prerequisite": (
                "Software record-content and SHA-256 verification leave independent QA operator administration, "
                "write-restricted storage control, and separation of duties over --trusted-qualification-store "
                "as mandatory deployment prerequisites."
            ),
            "non_substitution_rule": (
                "Because scripts/wetlab_contract.py remains 0-byte frozen under Option-2 invariance, "
                "a standalone READY_FOR_ENCAPSULATION_COMPLETE_STAGE0_EVIDENCE verdict from wetlab_contract.py "
                "NEVER clears Gate 0V or clinical release on its own. Clinical release is enforced by "
                "executable evaluate_gate0v_composite_release.py requiring BOTH (1) legacy wetlab_contract.py "
                "READY_FOR_ENCAPSULATION_COMPLETE_STAGE0_EVIDENCE invoked with preserved canonical product_variant_id/"
                "current_lot_id/mcb_id AND (2) tier-matched verify_iip0043 PASS (`PASS_WHOLEGRAFT_BANK_QUALIFICATION`, "
                "`PASS_WHOLEGRAFT_LOT_RELEASE_SURROGATE`, or `PASS_WHOLEGRAFT_AUTOLOGOUS_PROCESS_QUAL`), with prior "
                "bank/process qualification (including the mandatory verified original JSON-object archived bank payload "
                "for LOT_RELEASE_SURROGATE) resolved SOLELY from an independently administered `--trusted-qualification-store`."
            ),
        },
        "live_corpus_counts": {
            "ceg_v1_total_records": len(ceg_studies),
            "ceg_v1_unique_numeric_pmids_case_normalized": len(ceg_pmids),
            "ceg_v1_lowercase_id_type_records_caught": lowercase_id_type_records,
            "ceg_v1_non_pmid_records": len(ceg_studies) - len(ceg_pmids),
            "ring1_extracted_numeric_studies": len(ring1_pmids),
            "ring1_studies_missing_from_ceg_v1_backfill_candidates": {
                "count": len(ring1_only_missing_from_ceg),
                "includes_30074059_ifie2018": "30074059" in ring1_only_missing_from_ceg,
            },
            "ceg_v1_arms": len(ceg.get("arms", {})),
            "ceg_v1_outcomes": len(ceg.get("outcomes", {})),
            "ceg_v1_edges": len(ceg.get("edges", [])),
        },
        "ceg_delta_staging_diff": staging_diff,
    }


# ---------------------------------------------------------------------------
# Part D: OQ-016 §5.5 Invariance, Detection Power & Two-Stage FPR Pass Power
# ---------------------------------------------------------------------------
def quantify_oq016_and_tail_risk_reduction(openislet_root: Path) -> Dict[str, Any]:
    port_path = openislet_root / "data" / "extracted" / "islet1_5arm_autologous_portfolio_v0.8.0.json"
    port = strict_json_load_file(port_path, preserve_boundary_decimals=False)
    inv = port["live_3x2_baseline_invariant"]

    # Detection power under independent-cell model P(K >= 1 | p_true, n, eta) = 1 - (1 - p_true * eta)^n
    tail_risk_rows = []
    for p_true_pct in (0.05, 0.10, 0.25, 0.50, 1.00, 5.00):
        with _clean_dec_ctx(80, ROUND_HALF_EVEN):
            p_true = Decimal(str(p_true_pct)) / Decimal(100)
            eta = Decimal("0.80")
            q_eff = Decimal(1) - p_true * eta
        p_miss_1p = _pow_directed(q_eff, 13244, 80, ROUND_CEILING)
        p_miss_3p = _pow_directed(q_eff, 15990, 80, ROUND_CEILING)
        with _clean_dec_ctx(80, ROUND_FLOOR):
            p_det_1p = Decimal(1) - p_miss_1p
            p_det_3p = Decimal(1) - p_miss_3p
        tail_risk_rows.append({
            "silent_non_beta_reservoir_prevalence_pct": p_true_pct,
            "infected_cells_if_in_alpha_240M": int(240_000_000 * (p_true_pct / 100.0)),
            "infected_cells_if_in_iec_100M": int(100_125_000 * (p_true_pct / 100.0)),
            "infected_cells_if_in_pericyte_33M": int(33_375_000 * (p_true_pct / 100.0)),
            "legacy_beta_only_gate0v_detection_prob_pct": 0.0,
            "exp031_1pathogen_n13244_eta0p80_detection_prob_pct": _dec_to_float_pct(p_det_1p, 6),
            "exp031_3pathogen_n15990_eta0p80_detection_prob_pct": _dec_to_float_pct(p_det_3p, 6),
            "residual_miss_prob_3pathogen": format(p_miss_3p, ".4e"),
            "statistical_model_note": "Exact binomial Clopper-Pearson confidence applies strictly at deff=1.0 (independent binary observations); clustered lots (deff > 1.0) route to HOLD_CLUSTERED_DEFF_GT_1_REQUIRES_CLUSTER_LEVEL_INFERENCE.",
        })

    # B3 / R03-M1: Modeled two-stage screening/control clean-lot pass probability derived PROGRAMMATICALLY
    # from TRUE Clopper-Pearson U95 cutoffs at fixed sample sizes (n_panel = 15,990, n_ctrl = 20,000) across
    # 15 independent panels under perfect Stage-2 confirmation (models ONLY screening + negative-control checks,
    # NOT full-protocol pass probability across calibrants, latent ddPCR, Gate 0V-A, Gate 0V-Geno, or Gate 0V-Kill):
    #   - True U95 <= 0.15% admits k <= 20 (U95(20,20000) = 0.145277% <= 0.15%; U95(21,20000) = 0.151167% > 0.15%)
    #     -> 97.6508% modeled 15-panel screening/control pass probability at nominal FPR = 5e-4!
    #   - True U95 <= 0.10% admits k <= 12 (U95(12,20000) = 0.097195% <= 0.10%; U95(13,20000) = 0.103323% > 0.10%)
    #     -> collapses to 3.0034% modeled 15-panel screening/control pass probability at nominal FPR = 5e-4!
    fpr_comparison = []
    n_panel = 15990
    max_s1_events = int(n_panel * 0.002)  # 31
    n_ctrl = 20000
    alpha_ctrl = Decimal("0.05")

    def _max_admissible_k_for_true_u95(cap: Decimal) -> int:
        k_max = -1
        for k_try in range(0, 60):
            if exact_clopper_pearson_upper_general(k_try, n_ctrl, alpha_ctrl, prec=60) <= cap:
                k_max = k_try
            else:
                break
        return k_max

    max_ctrl_uncal_0p05 = 10  # Uncalibrated empirical <= 0.05% of 20,000
    max_ctrl_true_u95_0p10 = _max_admissible_k_for_true_u95(Decimal("0.0010"))  # 12
    max_ctrl_true_u95_0p15 = _max_admissible_k_for_true_u95(Decimal("0.0015"))  # 20
    u95_at_k20_pct = _dec_to_float_pct(exact_clopper_pearson_upper_general(max_ctrl_true_u95_0p15, n_ctrl, alpha_ctrl, prec=60), 6)
    u95_at_k21_pct = _dec_to_float_pct(exact_clopper_pearson_upper_general(max_ctrl_true_u95_0p15 + 1, n_ctrl, alpha_ctrl, prec=60), 6)

    for fpr_val in (1e-6, 1e-5, 1e-4, 5e-4):
        fpr_dec = Decimal(str(fpr_val))
        p_naive_all15 = (1.0 - fpr_val) ** (15 * n_panel)
        lam = n_panel * fpr_val
        p_s1_single = float(_binomial_tail_lower_eq_interval(max_s1_events, n_panel, fpr_dec, prec=30)[0])
        p_s1_all15 = p_s1_single ** 15
        p_ctrl_0p05_single = float(_binomial_tail_lower_eq_interval(max_ctrl_uncal_0p05, n_ctrl, fpr_dec, prec=30)[0])
        p_ctrl_0p05_all15_complete = (p_s1_single * p_ctrl_0p05_single) ** 15
        p_ctrl_u95_0p10_single = float(_binomial_tail_lower_eq_interval(max_ctrl_true_u95_0p10, n_ctrl, fpr_dec, prec=30)[0])
        p_complete_u95_0p10_all15 = (p_s1_single * p_ctrl_u95_0p10_single) ** 15
        p_ctrl_u95_0p15_single = float(_binomial_tail_lower_eq_interval(max_ctrl_true_u95_0p15, n_ctrl, fpr_dec, prec=30)[0])
        p_complete_u95_0p15_all15 = (p_s1_single * p_ctrl_u95_0p15_single) ** 15
        scoped_model_desc = (
            "Modeled two-stage screening/control clean-lot pass probability at fixed sample sizes "
            "(n_panel=15,990, n_ctrl=20,000) across 15 independent panels under perfect Stage-2 confirmation; "
            "excludes spike-calibrant, latent-ddPCR, Gate 0V-A, Gate 0V-Geno, and Gate 0V-Kill pass probabilities."
        )
        fpr_comparison.append({
            "stage1_flow_fpr": fpr_val,
            "expected_false_positives_per_panel_15990": round(lam, 3),
            "expected_false_positives_per_neg_ctrl_20000": round(n_ctrl * fpr_val, 3),
            "true_u95_0p15pct_max_admissible_k": max_ctrl_true_u95_0p15,
            "true_u95_at_max_admissible_k_pct": u95_at_k20_pct,
            "true_u95_at_first_rejected_k_pct": u95_at_k21_pct,
            "true_u95_0p10pct_max_admissible_k": max_ctrl_true_u95_0p10,
            "naive_conjunctive_raw_k0_p_pass_all15_pct": round(p_naive_all15 * 100.0, 4),
            "stage1_screen_only_p_pass_all15_pct": round(p_s1_all15 * 100.0, 4),
            "true_u95_0p15pct_ctrl_single_panel_p_pass_pct": round(p_ctrl_u95_0p15_single * 100.0, 4),
            # R04-M1: Primary scoped machine-readable fields accurately naming the modeled 15-panel screen+control scope
            "modeled_two_stage_screening_control_15panel_pass_pct": round(p_complete_u95_0p15_all15 * 100.0, 4),
            "modeled_two_stage_screening_control_15panel_pass_pct_at_u95_0p10pct": round(p_complete_u95_0p10_all15 * 100.0, 4),
            "modeled_two_stage_screening_control_15panel_pass_pct_at_uncal_0p05pct": round(p_ctrl_0p05_all15_complete * 100.0, 4),
            "modeled_two_stage_screening_control_scope": scoped_model_desc,
            "modeled_screening_and_control_pass_probability_scope": scoped_model_desc,
            "clears_80pct_modeled_screening_and_control_criterion": bool(p_complete_u95_0p15_all15 >= 0.80),
            # Explicitly documented deprecated legacy aliases retained strictly for backward JSON-key compatibility
            "deprecated_legacy_field_aliases": {
                "status": "DEPRECATED_BACKWARD_COMPAT_ALIASES_DO_NOT_INTERPRET_AS_FULL_PROTOCOL_END_TO_END",
                "true_u95_0p15pct_complete_end_to_end_all15_p_pass_pct": "Deprecated alias for modeled_two_stage_screening_control_15panel_pass_pct (15-panel Stage-1 screen + neg-control model only)",
                "true_u95_0p10pct_ctrl_cap_complete_all15_p_pass_pct": "Deprecated alias for modeled_two_stage_screening_control_15panel_pass_pct_at_u95_0p10pct",
                "uncalibrated_0p05pct_emp_ctrl_cap_complete_all15_p_pass_pct": "Deprecated alias for modeled_two_stage_screening_control_15panel_pass_pct_at_uncal_0p05pct",
                "clears_80pct_complete_clean_lot_qualification_criterion": "Deprecated alias for clears_80pct_modeled_screening_and_control_criterion",
            },
            "uncalibrated_0p05pct_emp_ctrl_cap_complete_all15_p_pass_pct": round(p_ctrl_0p05_all15_complete * 100.0, 4),
            "true_u95_0p10pct_ctrl_cap_complete_all15_p_pass_pct": round(p_complete_u95_0p10_all15 * 100.0, 4),
            "true_u95_0p15pct_complete_end_to_end_all15_p_pass_pct": round(p_complete_u95_0p15_all15 * 100.0, 4),
            "clears_80pct_complete_clean_lot_qualification_criterion": bool(p_complete_u95_0p15_all15 >= 0.80),
        })

    return {
        "oq016_live_headline_delta_pp": 0.0,
        "live_3x2_baseline_preserved": {
            "locked_pct": inv["locked_pct"],
            "modular_k100_pct": inv["modular_k100_pct"],
            "modular_k90_pct": inv["modular_k90_pct"],
            "shared_ceiling_pct": inv["shared_ceiling_pct"],
        },
        "substantive_modeling_reason_for_zero_headline_delta": (
            "IIP-0043 introduces and extends Stage-0 candidate qualification checks targeting five pre-IND "
            "surveillance and calibration blindspots pending physical confirmation (non-beta viral reservoirs "
            "and innate-antiviral/intrinsic-stress resilience under Blueprint Gates 1, 2B, and 4; acute "
            "24-h/72-h stressed pan-lineage AP1903 viability/erasure screening and 72-hour NW-08 oxygen-bridge "
            "verification linked to Blueprint Gate 5 per ISLET-1-BLUEPRINT.md §1.2, while long-horizon "
            "pan-lineage clonogenic eradication remains owned by Blueprint Gate 5 / legacy MCB clonogenic "
            "outgrowth trials in wetlab_contract.py and ISLET-1-BLUEPRINT.md §4.5) without modifying any "
            "H1-H4 therapeutic ceiling (c = [0.88, 0.87, 0.89, 0.85])."
        ),
        "statistical_family_and_coverage_scope": (
            "The 30-test global FWER <= 0.05 allocation (alpha = floor(1/600)) governs the named 3-pathogen x "
            "5-lineage x 2-stage Day-28 surveillance assay endpoint family; Gate 0V-Kill, latent-genome ddPCR, "
            "and ectopic-receptor addenda are reported and gated separately under their explicit directional "
            "one-sided per-estimand sampling models (assuming independent representative binary observations "
            "with a common event probability p per component; independent trials with unequal unit event "
            "probabilities fall outside the standard common-probability binomial model). "