OpenIslet

scripts/verify_iip0034_planar_and_portfolio.py

Deterministic Planar Route 3P Physics, Colony-Screening, Exact Decimal DEC-103 R3P-05 Thinning,

script Release v0.8.0 gen-eb955f8266035aba 111 KB · 8 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_iip0034_planar_and_portfolio.py · SHA-256: 24ff92056312d1e8…

    core_fn = getattr(rank_mod, "_compute_multiparadigm_2pow4n_portfolio_iip0034_core", None)
    if core_fn is None:
        core_fn = rank_mod.compute_multiparadigm_2pow4n_portfolio_iip0034
    mp = core_fn()
    all_rows = (
        list(mp.get("conservative_zero_h2_h3_lift_4x3_architectural", []))
        + list(mp.get("stage0_gated_conditional_4x3_off_the_shelf", []))
        + list(mp.get("stage0_gated_5arm_unified_bridge", []))
    )
    max_4096_err = max(float(r["incumbent_4096_state_max_abs_err"]) for r in all_rows)
    if not math.isfinite(max_4096_err) or max_4096_err > 1e-12:
        raise ValueError(f"4096-state parity violation: {max_4096_err}")

    pa = (0.88, 0.78, 0.57, 0.69)
    pb = (0.88, 0.79, 0.64, 0.70)
    px = (0.88, 0.82, 0.73, 0.69)
    c_base = (0.88, 0.87, 0.89, 0.85)
    live = rank_mod.compute_common_shock_2pow12_portfolio_tree(pa, pb, px, c_base)
    inadm_diag = rank_mod._run_dp_and_verify_parity_iip0034(
        "INADMISSIBLE_DIAGONAL_SELF_CHECK",
        [pa, pb, px],
        rank_mod._live_canonical_incumbent_dists_iip0034(),
        list(c_base),
        float(live["locked_2route_shared_ax_pouch_exact"]),
        float(live["modular_2route_shared_ax_pouch_exact"]),
        math.prod(c_base),
        stage0_status="SELF_CHECK_INADMISSIBLE_DIAGONAL",
        cell_classes=("UNHARDENED_A_B_X", "UNHARDENED_A_B_X", "UNHARDENED_A_B_X"),
        route_ids=("R3P", "R3P", "R3P"),
    )
    if not (inadm_diag["locked_pct"] == 0.0 and inadm_diag["modular_k100_pct"] == 0.0 and inadm_diag["modular_k90_pct"] == 0.0):
        raise ValueError(f"Inadmissible diagonal leaked non-zero survival: {inadm_diag}")

    by_sc = {r["scenario"]: r for r in all_rows}
    pareto_path = active_root / PARETO_REL_PATH
    if not pareto_path.is_file():
        raise ValueError(f"Missing Pareto artifact: {pareto_path}")
    pareto_sha = hashlib.sha256(pareto_path.read_bytes()).hexdigest()
    if pareto_sha != EXPECTED_PARETO_SHA256:
        raise ValueError(f"Pareto SHA-256 drift: {pareto_sha} != {EXPECTED_PARETO_SHA256}")

    return {
        "schema_version": "openislet_iip0034_planar_and_portfolio_verification_v0.8.0",
        "proposal_id": "IIP-0034",
        "decision_id": "DEC-113",
        "license": "CC-BY-4.0",
        "epistemic_status": "DETERMINISTIC_CONTINUUM_AND_PORTFOLIO_REPLAY_STAGE0_PENDING",
        "live_headline_odds_delta_pp": 0.0,
        "pareto_sha256_verified": pareto_sha,
        "design_y_v2_product_registry_audit": registry_audit,
        "r3p05_dec103_thinning_boundary_audit": r3p05_audit,
        "planar_mechanics_and_clearance": mechanics,
        "planar_3d_fvm_oxygen_envelopes": fvm_cases,
        "fvm_model_assumptions_and_convergence_note": (
            "Periodic unit-cell 3D FVM solved on 28x28x32 meshes (grid refinement to 56x56x64-80x80x96 shifts "
            "marginal 120 um face/core values by tenths of mmHg without altering any combined face/core gate class). "
            "Post-anastomosis 2.5x GSIS OCR multiplier scales both islet and stromal gel sinks conservatively; "
            "direct intra-islet perfusion is a modeled scenario pending loaded-envelope measurement."
        ),
        "planar_30mmhg_buffer_solubility_sensitivity": {
            "alpha_nominal_mol_cm3_mmhg": ALPHA_LOW_SALT,
            "alpha_phys_buffer_mol_cm3_mmhg": ALPHA_PHYS_BUFFER,
            "hybrid333_h180_bed30_clean_phys_buffer": solubility_sensitivity_30mmhg,
            "hybrid333_h180_bed35_120um_clean_phys_buffer": solubility_sensitivity_120um_bed35,
            "caveat": (
                "Switching Bunsen solubility from nominal 1.34e-9 to physiological-buffer 1.27e-9 mol/(cm^3*mmHg) "
                "drops Hybrid-333 H180 clean 65 um at a 30 mmHg bed from 15.2152 to 14.4198 mmHg (< 15.0 mmHg face floor) "
                "and drops Day-0 avascular 120 um Hybrid-333 H180 at a 35 mmHg bed from 15.3775/5.9609 to "
                "14.3801/4.5487 mmHg (failing both face and core floors); additionally 10 um of 0.5x D fibrin at 35 mmHg "
                "drops 65 um Hybrid-333 H180 face to 14.72 mmHg (< 15.0 mmHg) despite being inside the 30 um thickness cap."
            ),
        },
        "planar_1d_insulin_shutoff_fall_t50": shutoff,
        "sequential_bxb1_colony_screening_audit": colonies,
        "portfolio_compatibility_and_4096_state_audit": {
            "allowed_cell_route_pairs": {
                k: sorted(v) for k, v in sorted(rank_mod.ALLOWED_CELL_ROUTE_PAIRS_IIP0034.items())
            },
            "unhardened_abx_barred_from_route3p": (
                "R3P" not in rank_mod.ALLOWED_CELL_ROUTE_PAIRS_IIP0034["UNHARDENED_A_B_X"]
                and "R3P" not in rank_mod.ALLOWED_CELL_ROUTE_PAIRS_IIP0034["UNEDITED_AUTO_NEGATIVE_CONTROL"]
                and "R3P" in rank_mod.ALLOWED_CELL_ROUTE_PAIRS_IIP0034["DESIGN_Y_FULLSTACK_V2"]
                and "R3P" in rank_mod.ALLOWED_CELL_ROUTE_PAIRS_IIP0034["D1B_AUTO_C_V2"]
            ),
            "design_y_v2_bound_strictly_to_route3p_matching_registry": registry_audit["design_y_v2_bound_strictly_to_route3p_matching_registry"],
            "locked_path_compatibility_enforced": True,
            "inadmissible_diagonal_locked_pct": inadm_diag["locked_pct"],
            "inadmissible_diagonal_modular_k100_pct": inadm_diag["modular_k100_pct"],
            "inadmissible_diagonal_modular_k90_pct": inadm_diag["modular_k90_pct"],
            "ordinary_scenario_count_checked": len(all_rows),
            "total_evaluated_rows_including_sensitivities": (
                len(all_rows)
                + len(mp.get("phi_h4_sensitivity_counterexamples", []))
                + len(mp.get("cross_hurdle_negative_coupling_sensitivity", []))
            ),
            "max_4096_state_incumbent_abs_err": max_4096_err,
            "w_b1_modular_compatible_pct": by_sc["W_B1_4Arm_Y@PrePerf3P_ZeroLift_c4u0.92_phiYX0.75_phiH4=0.25"]["modular_k100_pct"],
            "w_b1_prohibited_modular_mass_excluded_pp": by_sc["W_B1_4Arm_Y@PrePerf3P_ZeroLift_c4u0.92_phiYX0.75_phiH4=0.25"]["prohibited_modular_mass_excluded_pp"],
            "w_b5_modular_compatible_pct": by_sc["W_B5_4Arm_Y@PrePerf3P_Nested(90/92)_c4u0.92_phiYX0.75_phiH4=0.25"]["modular_k100_pct"],
            "w_b5_prohibited_modular_mass_excluded_pp": by_sc["W_B5_4Arm_Y@PrePerf3P_Nested(90/92)_c4u0.92_phiYX0.75_phiH4=0.25"]["prohibited_modular_mass_excluded_pp"],
            "w_b9_locked_phiH4_0p50_pct": by_sc["W_B9_4Arm_Y@PrePerf3P_Nested(90/92)_pY4=0.68_c4u0.90_phi1.0_50"]["locked_pct"],
            "w_b10_prohibited_modular_mass_excluded_pp": by_sc["W_B10_4Arm_Y@Hybrid3P_Nested(90/92)_c4u0.92_phiYX0.75_phiH4=0.25"]["prohibited_modular_mass_excluded_pp"],
            "w_b9_phiH4_0p60_sensitivity_counterexample": mp["phi_h4_sensitivity_counterexamples"][0],
            "w_b3_equalized_y_marginals_sensitivity_counterexample": mp["phi_h4_sensitivity_counterexamples"][1],
            "cross_hurdle_negative_coupling_sensitivity": mp["cross_hurdle_negative_coupling_sensitivity"],
            "five_arm_bridge_registration_status": mp["five_arm_bridge_registration_status"],
        },
    }


def main() -> None:
    parser = argparse.ArgumentParser(description="Deterministic planar Route 3P & portfolio verifier (IIP-0034 / DEC-113).")
    mode = parser.add_mutually_exclusive_group()
    mode.add_argument("--write", action="store_true", help=f"Write canonical JSON artifact to {DEFAULT_OUT_PATH}")
    mode.add_argument("--check", action="store_true", help=f"Verify byte-identical match against {DEFAULT_OUT_PATH}")
    args = parser.parse_args()

    payload = compute_full_verification(ROOT)
    serialized = json.dumps(payload, indent=2, ensure_ascii=False, allow_nan=False) + "\n"
    expected_bytes = serialized.encode("utf-8")
    expected_sha = hashlib.sha256(expected_bytes).hexdigest()
    if args.write:
        DEFAULT_OUT_PATH.parent.mkdir(parents=True, exist_ok=True)
        DEFAULT_OUT_PATH.write_bytes(expected_bytes)
        print(f"Wrote {DEFAULT_OUT_PATH} ({len(expected_bytes)} bytes, SHA-256={expected_sha})")
    elif args.check:
        if not DEFAULT_OUT_PATH.is_file():
            raise SystemExit(f"Missing verification artifact: {DEFAULT_OUT_PATH}")
        existing_bytes = DEFAULT_OUT_PATH.read_bytes()
        try:
            existing_obj = json.loads(existing_bytes.decode("utf-8"))
        except Exception as exc:
            raise SystemExit(f"Invalid JSON in {DEFAULT_OUT_PATH}: {exc}") from exc
        existing_canonical_bytes = (
            json.dumps(existing_obj, indent=2, ensure_ascii=False, allow_nan=False) + "\n"
        ).encode("utf-8")
        if existing_bytes != existing_canonical_bytes:
            raise SystemExit(
                f"Verification artifact formatting byte/SHA-256 drift detected in {DEFAULT_OUT_PATH}"
            )

        def _norm_mbe_diagnostic(obj: Any, source_label: str) -> Any:
            if isinstance(obj, dict):
                out_d: dict[str, Any] = {}
                for k, v in obj.items():
                    if k == "rel_mass_balance_error_str":
                        if not isinstance(v, str):
                            raise SystemExit(f"Non-string rel_mass_balance_error_str in {source_label}: {v!r}")
                        try:
                            fv = float(v)
                        except ValueError as exc:
                            raise SystemExit(f"Non-numeric rel_mass_balance_error_str in {source_label}: {v!r}") from exc
                        if not math.isfinite(fv) or fv < 0.0 or fv > 1e-10:
                            raise SystemExit(
                                f"Mass balance residual out of [0, 1e-10] bound in {source_label}: {v!r}"
                            )
                        out_d[k] = "__MBE_DIAGNOSTIC_BOUNDED_LE_1E10__"
                    else:
                        out_d[k] = _norm_mbe_diagnostic(v, source_label)
                return out_d
            if isinstance(obj, list):
                return [_norm_mbe_diagnostic(item, source_label) for item in obj]
            return obj

        norm_existing_bytes = (
            json.dumps(_norm_mbe_diagnostic(existing_obj, "on-disk receipt"), indent=2, ensure_ascii=False, allow_nan=False) + "\n"
        ).encode("utf-8")
        norm_expected_bytes = (
            json.dumps(_norm_mbe_diagnostic(payload, "recomputed payload"), indent=2, ensure_ascii=False, allow_nan=False) + "\n"
        ).encode("utf-8")
        existing_sha = hashlib.sha256(norm_existing_bytes).hexdigest()
        norm_expected_sha = hashlib.sha256(norm_expected_bytes).hexdigest()
        if norm_existing_bytes != norm_expected_bytes or existing_sha != norm_expected_sha:
            raise SystemExit(
                f"Verification artifact substantive byte/SHA-256 drift detected in {DEFAULT_OUT_PATH}: "
                f"found {existing_sha}, expected {norm_expected_sha}"
            )
        if not PORTFOLIO_PATH.is_file():
            raise SystemExit(f"Missing shipped portfolio artifact: {PORTFOLIO_PATH}")
        shipped_portfolio_bytes = PORTFOLIO_PATH.read_bytes()
        expected_portfolio = rank_mod.compute_multiparadigm_2pow4n_portfolio_iip0034()
        expected_portfolio_bytes = (
            json.dumps(expected_portfolio, indent=2, ensure_ascii=False, allow_nan=False) + "\n"
        ).encode("utf-8")
        shipped_p_sha = hashlib.sha256(shipped_portfolio_bytes).hexdigest()
        expected_p_sha = hashlib.sha256(expected_portfolio_bytes).hexdigest()
        if shipped_portfolio_bytes != expected_portfolio_bytes or shipped_p_sha != expected_p_sha:
            raise SystemExit(
                f"Shipped multiparadigm portfolio byte/SHA-256 drift detected in {PORTFOLIO_PATH}: "
                f"found {shipped_p_sha}, expected {expected_p_sha}"
            )
        print(
            f"OK: {DEFAULT_OUT_PATH} (SHA-256={expected_sha}) and "
            f"{PORTFOLIO_PATH} (SHA-256={expected_p_sha}) match deterministic replay byte-for-byte."
        )
    else:
        print(serialized)


if __name__ == "__main__":
    main()