OpenIslet

scripts/run_layer4_tissue_and_metabolic_twin.py

Layer 4: Multi-Scale Tissue, Vascular & Metabolic Digital Twin Plane (v0.8.0)

script Release v0.8.0 gen-eb955f8266035aba 713 KB · 47 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/run_layer4_tissue_and_metabolic_twin.py · SHA-256: 624a491d5e418a7d…

                        "pde_per_face_with_15pct_iec_vmax_flux_1500_ieq_cm2_mol_cm2_s": round(0.5 * 1.15 * 1500.0 * (4.0 / 3.0 * math.pi * (0.0075 ** 3)) * 3.40e-8, 14),
                        "unvascularized_100pct_flux_50um_seroma_drop_at_pde_per_face_pure_4p51e11_mmhg": round((0.5 * 1500.0 * (4.0 / 3.0 * math.pi * (0.0075 ** 3)) * 3.40e-8 * 50.0e-4) / (1.584e-5 * 1.35e-9), 2),
                        "unvascularized_100pct_flux_50um_seroma_drop_at_pde_per_face_plus15pct_iec_5p18e11_mmhg": round((0.5 * 1.15 * 1500.0 * (4.0 / 3.0 * math.pi * (0.0075 ** 3)) * 3.40e-8 * 50.0e-4) / (1.584e-5 * 1.35e-9), 2),
                        "vascularized_32pct_external_flux_50um_seroma_drop_at_pde_per_face_pure_4p51e11_mmhg": round(0.32 * (0.5 * 1500.0 * (4.0 / 3.0 * math.pi * (0.0075 ** 3)) * 3.40e-8 * 50.0e-4) / (1.584e-5 * 1.35e-9), 2),
                        "vascularized_32pct_external_flux_50um_seroma_drop_at_pde_per_face_plus15pct_iec_5p18e11_mmhg": round(0.32 * (0.5 * 1.15 * 1500.0 * (4.0 / 3.0 * math.pi * (0.0075 ** 3)) * 3.40e-8 * 50.0e-4) / (1.584e-5 * 1.35e-9), 2),
                        "critical_seroma_film_thickness_for_15mmhg_drop_at_pde_per_face_pure_um": round((1.584e-5 * 1.35e-9 * 15.0 / (0.5 * 1500.0 * (4.0 / 3.0 * math.pi * (0.0075 ** 3)) * 3.40e-8)) * 1e4, 1),
                        "critical_seroma_film_thickness_for_15mmhg_drop_at_pde_per_face_plus15pct_iec_um": round((1.584e-5 * 1.35e-9 * 15.0 / (0.5 * 1.15 * 1500.0 * (4.0 / 3.0 * math.pi * (0.0075 ** 3)) * 3.40e-8)) * 1e4, 1),
                        "unvascularized_100pct_flux_50um_seroma_drop_at_6p75e11_mmhg": 15.78,
                        "unvascularized_100pct_flux_50um_seroma_drop_at_8p89e11_mmhg": round((8.89e-11 * 50.0e-4) / (1.584e-5 * 1.35e-9), 2),
                        "vascularized_32pct_external_flux_50um_seroma_drop_at_6p75e11_mmhg": 5.05,
                        "vascularized_32pct_external_flux_50um_seroma_drop_at_8p89e11_mmhg": round(0.32 * (8.89e-11 * 50.0e-4) / (1.584e-5 * 1.35e-9), 2),
                        "flux_provenance_and_boundary_symmetry_reconciliation_note": (
                            "Reconciles the parametric Fick seroma fluxes against the Layer-4 PDE V_max = 3.40e-8 mol/(cm^3*s) (V_IEQ = 1.767146e-6 cm^3; L4A-F02 [DEC-077]): "
                            "at sigma = 1,500 IEQ/cm^2, two-sided total pure-islet saturated demand is J_total,pure = sigma * V_IEQ * V_max = 9.0124e-11 mol/(cm^2*s), or J_face,pure = 4.5062e-11 mol/(cm^2*s) per symmetric face "
                            "(with +15% iEC stroma: J_total,+iEC = 1.0364e-10 mol/(cm^2*s), J_face,+iEC = 5.1822e-11 mol/(cm^2*s) per face -> 50 um unvascularized seroma drop = 10.54 mmHg pure / 12.11 mmHg +iEC, 32% vascularized drop = 3.37 mmHg pure / 3.88 mmHg +iEC, critical thickness for 15.0 mmHg drop = 71.2 um pure / 61.9 um +iEC). "
                            "The parametric seroma brackets evaluate: (a) J_basal = 3.90e-11 mol/(cm^2*s) (2.60e-14 mol/s/IEQ per face = 0.7526x PDE +iEC per-face V_max, resting basal-glucose OCR -> 9.12 mmHg at 50 um), "
                            "(b) J_peak = 6.75e-11 mol/(cm^2*s) (4.50e-14 mol/s/IEQ per face = 1.3025x PDE +iEC per-face V_max, high-glucose stimulated peak OCR overdrive -> 15.78 mmHg at 50 um, conservative critical thickness 47.5 um vs 61.9 um PDE +iEC per-face), and "
                            "(c) 8.89e-11 mol/(cm^2*s) (single-face-blocked / one-sided drainage of total two-sided pure-islet demand ~9.0124e-11 mol/(cm^2*s) across one boundary -> 20.78 mmHg unvascularized / 6.65 mmHg vascularized at 50 um)."
                        ),
                    },
                    "pericyte_ng2_pdgfrb_microvessel_stabilization_gate": {
                        "wetlab_endpoint": "obs_vascular_pericyte_ng2_pdgfrb_coverage_pct",
                        "min_day90_ng2_pdgfrb_pericyte_coverage_pct": 70.0,
                        "rationale": "Prevents leaky immature VEGF-driven neovessels and chronic seroma re-accumulation in the outer vascularized hydrogel band (MW-R6-S1-15).",
                    },
                    "day1_to_day28_avascular_bridge_cao2_and_shutoff_audit_muse_r6": {
                        "finding_ids": ["MW-R6-S1-12", "MW-R6-S1-14", "MW-R6-S1-15", "AUDIT-REF", "AUDIT-REF"],
                        "day28_functional_beta_survival_endpoint": "obs_day28_functional_beta_survival_fraction",
                        "min_day28_functional_beta_survival_fraction": 0.80,
                        "stepdown_8mM_to_2mM_insulin_shutoff_ratio_endpoint": "obs_gate0m_8mM_to_2mM_insulin_shutoff_ratio",
                        "max_stepdown_8mM_to_2mM_insulin_shutoff_ratio": 0.20,
                        "pouch_iapp_oligomer_a11_endpoint": "obs_pouch_iapp_oligomer_a11_dot_blot_fold",
                        "max_pouch_iapp_oligomer_a11_dot_blot_fold": 1.50,
                        "film_gt_50um_enforces_dxb_cluster_cap_um": 100.0,
                        "film_gt_50um_enforces_areal_loading_cap_ieq_cm2": 1500.0,
                    },
                },
            },
            "day1_to_day28_avascular_bridge_cao2_and_shutoff_audit_muse_r6": {
                "finding_ids": ["MW-R6-S1-12", "MW-R6-S1-14", "MW-R6-S1-15", "AUDIT-REF", "AUDIT-REF"],
                "day28_functional_beta_survival_endpoint": "obs_day28_functional_beta_survival_fraction",
                "min_day28_functional_beta_survival_fraction": 0.80,
                "stepdown_8mM_to_2mM_insulin_shutoff_ratio_endpoint": "obs_gate0m_8mM_to_2mM_insulin_shutoff_ratio",
                "max_stepdown_8mM_to_2mM_insulin_shutoff_ratio": 0.20,
                "pouch_iapp_oligomer_a11_endpoint": "obs_pouch_iapp_oligomer_a11_dot_blot_fold",
                "max_pouch_iapp_oligomer_a11_dot_blot_fold": 1.50,
                "film_gt_50um_enforces_dxb_cluster_cap_um": 100.0,
                "film_gt_50um_enforces_areal_loading_cap_ieq_cm2": 1500.0,
            },
            "stage0_gate_0f_operational_max_periimplant_fluid_film_um": 50.0,
            "stage0_gate_0f_hard_ceiling_with_closed_suction_drain_um": 80.0,
            "stage0_gate_0d_max_periimplant_fluid_film_um": 80.0,
            "stage0_gate_0d_min_explant_en_bloc_recovery_fraction": 0.99,
            "surgical_mitigation": (
                "Micro-fenestrated ePTFE/PDMS cassette ribs + omental fibrin-tack apposition + 72-h closed-suction micro-drain to keep peri-implant fluid film <= 50 um operationally "
                "(47.5 um pure-seroma 100%-flux 15 mmHg limit; and strictly <= 80 um under vascularized outer-band k_perf >= 0.10 s^-1 with DX-b <= 100/80 um cluster cap and 1,500 IEQ/cm^2 low-load, "
                "where external-budget slab/outer-band pO2 is 20.26 mmHg and live coupled spherical cluster core pO2 is 8.95 mmHg at 80 um clusters [4.71 mmHg at 100 um clusters with 3x capsule resistance, or 5.71 mmHg at 100 um clusters with matched D_caps = D_gel])"
            ),
        },
        "chronic_kperf_and_safasl_microgel_solid_fraction_accounting": {
            "in_vitro_vascularized_hydrogel_kperf_s_inv": 0.25,
            "chronic_day90_50um_fbr_capsule_attenuated_kperf_s_inv": 0.1358,
            "stage0_gate_0d_chronic_kperf_pass_floor_s_inv": 0.10,
            "safasl_sathbd_microgel_volume_fraction_at_1500_ieq_cm2_333cm2": {
                "f_islet": 0.0744,
                "f_iec_pericyte_stroma": 0.0131,
                "f_safasl_sathbd_peg_microgels": 0.0600,
                "f_total_solid_dispersed_phase": 0.1475,
                "f_continuous_aqueous_hydrogel_matrix": 0.8525,
                "max_dispersed_phase_percolation_cap": 0.20,
                "passes_rheological_and_maxwell_diffusivity_budget": True,
            },
        },
    }
    part_b_ode = solve_24h_paracrine_and_whole_body_metabolic_ode(
        pde_regimes=part_a_pde["regimes_simulated"]
    )

    lead_regime = next(r for r in part_a_pde["regimes_simulated"] if r["regime_id"] == "LEAD_CENTRAL_LAMINA_PDMS_CAO2_F045_PLUS_CATALASE")
    part_a_pde["explicit_3d_clumping_and_microbead_h2o2_audit_iip_0019"] = (
        build_explicit_3d_clumping_and_microbead_h2o2_audit_iip_0019(lead_regime)
    )
    part_a_pde["lineage_partitioned_metabolic_rest_and_m101_exclusion_audit"] = (
        build_lineage_partitioned_metabolic_rest_and_m101_exclusion_audit_iip_0021()
    )
    part_a_pde["hurdle4_spatial_oxygen_catalase_and_route_challengers_iip_0025"] = (
        build_hurdle4_spatial_oxygen_catalase_and_route_challengers_iip_0025()
    )
    part_a_pde["measured_potency_dec084_mixture_and_glucagon_audit_iip_0028"] = (
        build_measured_potency_dec084_mixture_and_glucagon_audit_iip_0028()
    )
    part_b_ode["exploratory_two_clock_granule_store_sensitivity_audit_iip_0029"] = (
        build_exploratory_mode_b_v2_granule_sensitivity_audit_iip_0029(part_b_ode)
    )

    atlas = {
        "schema_version": "0.8.0",
        "layer": "Layer 4 — Multi-Scale Tissue, Vascular & Metabolic Digital Twin Plane",
        "status": "NUMERICALLY_INTEGRATED_REACTION_DIFFUSION_PDE_AND_METABOLIC_ODE_TWIN",
        "evidence_class": "mechanistic_numerical_pde_ode_simulation_requiring_wetlab_device_qualification",
        "summary": {
            "active_350um_pouch_volume_at_200cm2_cm3": 7.00,
            "passive_islet_only_capacity_ieq_per_cm2": part_a_algebra["passive_capacity_islet_only_ieq_per_cm2"],
            "passive_with_15pct_iec_stroma_capacity_ieq_per_cm2": part_a_algebra["passive_capacity_with_15pct_iec_stroma_ieq_per_cm2"],
            "lead_pouch_min_po2_14d_mmhg": lead_regime["min_slab_po2_across_14_days_mmhg"],
            "lead_pouch_max_h2o2_uM": lead_regime["max_interstitial_h2o2_uM"],
            "lead_pouch_max_ph": lead_regime["max_interstitial_ph"],
            "metabolic_reference_scope": "REFERENCE_FIXED_FUNCTIONAL_BETA_IEQ_NOT_PDE_DERIVED",
            "metabolic_summary_pde_coupling_applied": False,
            "metabolic_summary_source_pde_regime_id": None,
            "lead_uniform_supply_core_po2_mmhg": lead_regime["wigner_seitz_120um_cluster_pericellular_shell_audit_v80_001"]["two_zone_fv_uniform_supply_120um_core_po2_mmhg"],
            "lead_gel_only_supply_core_po2_mmhg": lead_regime["wigner_seitz_120um_cluster_pericellular_shell_audit_v80_001"]["two_zone_fv_gel_only_supply_120um_core_po2_mmhg"],
            "lead_strict_gel_only_numerical_gate_assessment": lead_regime["strict_gel_only_numerical_gate_assessment"],
            "trihormonal_60_30_10_time_in_range_pct": part_b_ode["graft_architectures_compared"][0]["time_in_tight_range_3p9_to_10p0_mM_pct"],
            "trihormonal_60_30_10_min_glucose_mM": part_b_ode["graft_architectures_compared"][0]["min_glucose_mM"],
            "beta_only_min_glucose_mM": part_b_ode["graft_architectures_compared"][1]["min_glucose_mM"],
            "g6pc2_ko_min_glucose_mM": part_b_ode["graft_architectures_compared"][2]["min_glucose_mM"],
        },
        "part_a_exact_oxygen_boundary_value_and_volume_algebra": part_a_algebra,
        "part_a_336h_spatial_reaction_diffusion_pouch_pde": part_a_pde,
        "part_b_24h_trihormonal_paracrine_and_whole_body_metabolic_ode": part_b_ode,
    }

    OUT_PATH.parent.mkdir(parents=True, exist_ok=True)
    with OUT_PATH.open("w", encoding="utf-8") as f:
        json.dump(atlas, f, indent=2)
        f.write("\n")

    print(f"[Layer 4 v0.8.0] Wrote {OUT_PATH.relative_to(REPO_ROOT)}")
    for r in part_a_pde["regimes_simulated"]:
        print(
            f"  [PDE] {r['regime_id']}: min_slab_pO2={r['min_slab_po2_across_14_days_mmhg']} mmHg, "
            f"Dirichlet_upper_bound_120um_core={r['min_120um_cluster_core_po2_mmhg']} mmHg, "
            f"max_H2O2={r['max_interstitial_h2o2_uM']} uM, max_pH={r['max_interstitial_ph']}, pass={r['passes_all_oxygen_peroxide_and_ph_gates']}"
        )
    for g in part_b_ode["graft_architectures_compared"]:
        print(
            f"  [ODE] {g['graft_id']}: TIR={g['time_in_tight_range_3p9_to_10p0_mM_pct']}%, "
            f"min_G={g['min_glucose_mM']} mM ({g['min_glucose_mg_dL']} mg/dL), "
            f"shutoff_t50={g['insulin_secretion_shutoff_half_time_min']} min, "
            f"TBR<3.0mM={g['time_severe_hypoglycemia_lt_3p0_mM_54_mg_dL_pct']}%, pass={g['passes_clinical_glycemic_safety_targets']}"
        )


DESIGN_X_RNLS_SUBTRACTION_RATIONALE_GY026_OLD = (
    "Design X promotes the RNLS-WT / TXNIP-KO subtraction challenger to preserve the full +3.39 mmHg oxygen headroom"
)
DESIGN_X_RNLS_SUBTRACTION_RATIONALE_GY026_NEW = (
    "Design X retains the RNLS-WT / TXNIP-WT chassis (superseded under GY-026 in Wave-6 atomic fold-in) to preserve oxygen headroom"
)


def regenerate_layer4_atlas_gy026(*, verify_live_pde: bool = True) -> Dict[str, Any]:
    """Governed GY-026 Layer-4 regeneration entry point: runs live slab algebra + optional live Design-X
    336h PDE solver (`DESIGN_X_100UM_LAMINA_EPS042_FO_51`) against the baseline atlas to prove exact
    numerical parity, supersedes the two stale TXNIP-KO promotion passages from the single-source-of-truth
    module constant, asserts zero remaining TXNIP-KO promotion text, and writes OUT_PATH."""
    if not OUT_PATH.is_file():
        raise FileNotFoundError(f"Missing baseline Layer-4 atlas for GY-026 regeneration: {OUT_PATH}")
    raw_txt = OUT_PATH.read_text(encoding="utf-8")
    atlas = json.loads(raw_txt)
    live_alg = verify_exact_slab_source_distribution_algebra()
    if atlas.get("part_a_exact_oxygen_boundary_value_and_volume_algebra") != live_alg:
        raise ValueError("Live Layer-4 exact slab algebra diverged from baseline atlas!")
    live_pde_verified = False
    if verify_live_pde:
        a_dx = 100.0 / 350.0
        dx_fo_51_live = _run_single_pouch_pde_regime(
            "DESIGN_X_100UM_LAMINA_EPS042_FO_51",
            0.45,
            "central",
            68.0,
            True,
            0.97,
            release_kinetics_law="first_order",
            nz_override=51,
            demand_spatial_mode="outer_annulus",
            lamina_d_o2_scale=0.42 ** 1.5,
            lamina_half_width_fraction=a_dx,
            _assess_numerical_gate=False,
        )
        ref_dx = atlas["part_a_336h_spatial_reaction_diffusion_pouch_pde"]["design_x_100um_lamina_transport_qualification_v80_018"]["first_order_nz51"]
        live_slab = dx_fo_51_live["min_slab_po2_across_14_days_mmhg"]
        live_core = dx_fo_51_live["wigner_seitz_120um_cluster_pericellular_shell_audit_v80_001"]["two_zone_fv_gel_only_supply_120um_core_po2_mmhg"]
        if abs(live_slab - ref_dx["min_slab_po2_mmhg"]) > 1e-6 or abs(live_core - ref_dx["gel_only_120um_core_po2_mmhg"]) > 1e-6:
            raise ValueError(f"Live Design-X 336h PDE diverged from atlas: live=({live_slab},{live_core}) vs ref={ref_dx}")
        live_pde_verified = True
    occ = raw_txt.count(DESIGN_X_RNLS_SUBTRACTION_RATIONALE_GY026_OLD)
    if occ != 2:
        raise ValueError(f"Expected exactly 2 stale TXNIP-KO rationale passages in Layer-4 atlas, found {occ}")
    updated_txt = raw_txt.replace(
        DESIGN_X_RNLS_SUBTRACTION_RATIONALE_GY026_OLD,
        DESIGN_X_RNLS_SUBTRACTION_RATIONALE_GY026_NEW,
    )
    if "TXNIP-KO" in updated_txt or "TXNIP_KO" in updated_txt:
        raise ValueError("Residual TXNIP-KO token detected in regenerated Layer-4 atlas!")
    json.loads(updated_txt)
    OUT_PATH.write_text(updated_txt, encoding="utf-8")
    return {
        "regenerated_path": str(OUT_PATH),
        "live_algebra_verified": True,
        "live_design_x_336h_pde_verified": live_pde_verified,
        "passages_superseded": occ,
        "residual_txnip_ko_tokens": 0,
    }


if __name__ == "__main__":
    if "--regenerate-gy026" in sys.argv:
        rep = regenerate_layer4_atlas_gy026(verify_live_pde="--algebra-only" not in sys.argv)
        print(json.dumps(rep))
    else:
        main()