scripts/run_layer4_tissue_and_metabolic_twin.py
Use this file in any AI chat (paste-only or attachment-capable):
Pinned raw file: https://openislet.org/files/gen-eb955f8266035aba/scripts/run_layer4_tissue_and_metabolic_twin.py · SHA-256: 624a491d5e418a7d…
"iu_per_mg_composite_bead_design_x": 13.29,
},
"full_central_lamina_envelope_2p3800_cm3": {
"volume_cm3": 2.3800,
"total_pouch_catalase_iu": 64260.0,
"iu_per_mg_active_cao2": 81.19,
"iu_per_mg_composite_bead_layout_b": 25.37,
"iu_per_mg_composite_bead_layout_a": 20.30,
},
"total_pouch_hydrated_hydrogel_pore_volume_4p0213_cm3": {
"volume_cm3": 4.0213,
"total_pouch_catalase_iu": 108575.1,
"iu_per_mg_active_cao2": 137.18,
"iu_per_mg_composite_bead_layout_b": 42.87,
"iu_per_mg_composite_bead_layout_a": 34.29,
},
"full_7p00_cm3_pouch_bulk_slab_envelope": {
"volume_cm3": 7.0000,
"total_pouch_catalase_iu": 189000.0,
"iu_per_mg_active_cao2": 238.79,
"iu_per_mg_composite_bead_layout_b": 74.62,
"iu_per_mg_composite_bead_layout_a": 59.70,
},
},
"spatial_enzyme_localization_and_saturation_equivalence_audit": {
"ledger_interpretation": (
"The 5 denominator rows above convert the local saturating capacity V_max = k_1 * K_m = 18.0 s^-1 * 25,000 uM = "
"0.45 M/s = 27,000 IU/mL across 5 candidate physical reference volumes. In the baseline PDE solver, "
"catalytic_rate_s_inv = 18.0 s^-1 is applied uniformly across interior nodes (corresponding to the 189,000 IU bulk-slab "
"or 64,260 IU central-lamina envelope if interpreted as a bulk-volume rate)."
),
"hour0_newton_bvp_spatial_and_dose_controls_uM": {
"uniform_slab_k1_18p0_s_inv_189000_iu_bulk": round(h0_uniform_18, 4),
"central_lamina_masked_k1_18p0_s_inv_64260_iu_lamina": round(h0_masked_18, 4),
"central_lamina_masked_k1_3p1572_s_inv_11271_iu_pore_water_dose": round(h0_masked_pore_dose, 4),
"uniform_slab_k1_1p0734_s_inv_11271_iu_spread_over_7cm3": round(h0_uniform_7cm3_dose, 4),
"design_x_100um_lamina_masked_k1_7p5600_s_inv_22680_iu_pore_water_dose_hour0_nz51": round(h0_dx_masked_22680_iu_51, 4),
"design_x_100um_lamina_masked_k1_7p5600_s_inv_22680_iu_pore_water_dose_hour0_nz201": round(h0_dx_masked_22680_iu, 4),
"design_x_100um_lamina_masked_k1_7p5600_s_inv_22680_iu_336h_pde_nz201_max": dx_fo_201_loc_cat["max_interstitial_h2o2_uM"],
"uncatalyzed_spontaneous_k_0p008_s_inv": round(h0_uncatalyzed, 4),
"nz201_fine_grid_controls_uM": {
"uniform_slab_k1_18p0_s_inv_189000_iu_bulk_nz201": round(h0_uniform_18_201, 4),
"central_lamina_masked_k1_18p0_s_inv_64260_iu_lamina_nz201": round(h0_masked_18_201, 4),
"central_lamina_masked_k1_3p1572_s_inv_11271_iu_pore_water_dose_nz201": round(h0_masked_pore_dose_201, 4),
"uniform_slab_k1_1p0734_s_inv_11271_iu_spread_over_7cm3_nz201": round(h0_uniform_7cm3_dose_201, 4),
"design_x_100um_lamina_masked_k1_7p5600_s_inv_22680_iu_pore_water_dose_hour0_nz201": round(h0_dx_masked_22680_iu, 4),
"design_x_100um_source_119um_mask_k1_6p3529_s_inv_22680_iu_diluted_hour0_nz201": round(h0_dx_22680_diluted_119um_mask_201, 4),
"design_x_100um_source_100um_mask_k1_6p3529_s_inv_19059_iu_hour0_nz201": round(h0_dx_k6p3529_100um_mask_19059_iu_201, 4),
"layout_b_119um_source_119um_mask_k1_6p3529_s_inv_22680_iu_hour0_nz201": round(h0_layout_b_source_and_119um_mask_22680_iu_201, 4),
"uncatalyzed_spontaneous_k_0p008_s_inv_nz201": round(h0_uncatalyzed_201, 4),
},
},
"gate_qualification_note": (
"Restricting k_1 = 18.0 s^-1 strictly to the central CaO2 lamina (64,260 IU) gives peak Hour-0 H2O2 = 0.7256 uM at both nz=51 and nz=201 "
"(vs 0.7248 uM at nz=51 / 0.7249 uM at nz=201 uniform), co-localizing the 11,271.2 IU Layout-B pore-water dose inside the 2.38 cm3 central lamina "
"(bulk-averaged k_1 = 3.1572 s^-1 * mask) gives 4.0599 uM at nz=51 (4.0607 uM at nz=201), and co-localizing the 22,680.0 IU Design-X pore-water dose "
f"inside the 2.00 cm3 100-um central lamina (bulk-averaged k_1 = 7.5600 s^-1 * mask) gives 2.0458 uM at Hour-0 (nz=51; {h0_dx_masked_22680_iu:.4f} uM at nz=201; "
f"or {h0_dx_22680_diluted_119um_mask_201:.4f} uM at nz=201 if 22,680.0 IU is diluted across the 2.38 cm3 119-um Layout-B enzyme mask at k_1 = 18.0 * (0.84/2.38) = 6.3529 s^-1 with 100-um source, "
f"{h0_layout_b_source_and_119um_mask_22680_iu_201:.4f} uM when both source and enzyme span the 119-um Layout-B mask, and {h0_dx_k6p3529_100um_mask_19059_iu_201:.4f} uM at k_1 = 6.3529 s^-1 on the 100-um mask [19,058.8 IU]) "
"and 2.046 uM peak across the 336-h PDE trajectory (nz=201 with t_1/2 = 168 h [9.43%/day exponential enzyme decay, retaining 25.0% activity at 336 h]), all clearing both the <=5.0 uM "
"conservative screen and the <10.0 uM cytotoxic threshold, whereas spreading 11,271.2 IU uniformly across the entire "
"7.00 cm3 slab (k_1 = 1.0734 s^-1) gives 9.8210 uM at nz=51 (9.8158 uM at nz=201; clearing <10.0 uM but exceeding <=5.0 uM). Therefore, immobilized "
"Catalase must be co-localized on/within the central PDMS-CaO2 lamina beads (79,149-158,298 U input loading at "
"100-200 U/mg CaO2; AUDIT-REF, AUDIT-REF, & AUDIT-REF)."
),
},
}
return {
"solver_method": (
"51-node 1D Finite-Difference Newton-Raphson BVP (pO2, H2O2, OH-) + 200-cell conservative two-zone spherical radial "
"Finite-Volume (FV) Wigner-Seitz BVP coupled to 4th-order Runge-Kutta (RK4, dt=0.25h) over t in [0, 336 h]"
),
"intra_cluster_radial_drop_R60um_mmhg": bvp_r60_ref["zero_order_krogh_drop_mmhg"],
"intra_cluster_radial_drop_R150um_mmhg": bvp_r150_ref["zero_order_krogh_drop_mmhg"],
"regimes_simulated": results,
"lead_regime_4_scenario_sensitivity_table_sol_v80_12": sensitivity_table,
"bruggeman_heterogeneous_lamina_diffusivity_torture_test_v80_041": bruggeman_torture_test,
"design_x_100um_lamina_transport_qualification_v80_018": design_x_100um_lamina_qualification,
"catalase_multi_denominator_iu_ledger_v80_093": catalase_multi_denominator_iu_ledger,
"spatial_grid_convergence_51_101_201_401_preastra_a094": grid_convergence,
"vascular_perfusion_conductance_sensitivity_v80_014": perfusion_sensitivity,
"joint_vascular_timing_and_exchange_sensitivity_iip_0002": joint_vascular_iip_0002,
"formulation_specific_cao2_half_life_sensitivity_iip_0010": formulation_cao2_sensitivity_iip_0010,
"post_bridge_endocrine_function_and_recovery_protocol_iip_0004": {
"iip_id": "IIP-0004",
"decision_id": "DEC-082",
"title": "Measure endocrine function after the modelled oxygen bridge and during recovery",
"type": "Missing evidence",
"affects_tests": ["1", "4", "5"],
"affects_designs": ["A", "B", "X"],
"playbook_cross_reference": "docs/STAGE-0-EXECUTION-PLAYBOOK.md (Readout 2 bounded 336-hour history-and-recovery characterisation)",
"primary_motivation_citation": "Wang et al. 2025 PMID:40404627 (PMC12098657; motivates testing survivor endocrine function after hypoxia without treating incubator set-points as pericellular measurements)",
"assembled_device_loading_citation": "Chendke et al. 2023 PMID:37476069",
"scope_and_gate_preservation": "Bounded history-and-recovery characterisation beside Readout 2; keeps the present product, existing gates, and numerical release rules unchanged, and does not relabel the 336-hour bridge as S6's day-14-to-90 chronic supply gate.",
"protocol_clauses": {
"1_test_defended_history": "Reproduce the selected exact-product lead's modelled 336-hour pericellular oxygen trajectory (e.g., from joint_vascular_timing_and_exchange_sensitivity_iip_0002), archive its time series, compare against contemporaneous age- and handling-matched controls, state whether peroxide and pH excursions (lines 1551-1554) are reproduced, record achieved exposure, cluster-size distribution, viable-cell recovery and OCR, distinguish measured surrounding oxygen from inferred core exposure, and include the parental comparator where available.",
"2_independent_sibling_aliquots": "Randomise size-stratified siblings within differentiation block to baseline, 72-hour anchor, end-of-exposure, and recovery readouts (including earliest technically valid point, 48 hours, and 7 days), log actual reoxygenation-to-assay delay, predeclare and log recovery-incubation oxygen separately from brief assay oxygen, assay at Readout 2's 40 mmHg boundary-matched condition as primary, and run the conditional 100 mmHg comparison on additional sibling aliquots where diffusion limitation could contribute without waiving existing Readout 2 qualification under both oxygen conditions.",
"3_visible_outputs_and_denominators": "Retain raw hormone traces and absolute low/high insulin or C-peptide output, basal leak, first-phase response, stimulation index, shut-off t50 and t90 derived from the same step-down trace with distinct definitions, low-glucose glucagon, and identity/processing readouts; report total allocated endocrine cells, starting beta/alpha counts, surviving endocrine cells, and surviving lineage/marker-positive counts separately, with whole-preparation and originally-allocated-input denominators primary for dose accounting.",
"4_model_coupling_scope": "Report history/control ratios, uncertainty, and absolute outputs separately for insulin stimulation, basal secretion, glucagon response, and timing; do not multiply original-input recovery into viable fraction v (which already counts cell loss); note that v scales insulin, stimulated glucagon (alpha_gain also multiplies v), and—unless preserved—local paracrine terms while glucagon basal is separate, so v * S_insulin + alpha_gain * S_glucagon is not an independent two-hormone correction.",
"5_predeclared_confirmation_design": "Treat a small paired pilot (e.g., 3 independent differentiation blocks = 2 residual degrees of freedom for a paired block-level contrast) as establishing feasibility and rough variability rather than equivalence; plan confirmation using a predeclared margin and conservative paired variability bound without reusing existing SI or 72-hour identity-retention thresholds as day-14 absolute-output non-inferiority margins.",
},
"paired_completion_clauses": {
"supplied_area_and_assembled_device_qualification": "Report nominal tissue-bearing area (200 cm^2 at 2,500 IEQ/cm^2; 333.33 cm^2 at S6 low-load 1,500 IEQ/cm^2 for 500,000 IEQ) and oxygen-supported area separately under one conserved supply-and-demand budget, retaining demand from all loaded tissue including uncredited regions, using S6's >= 15 mmHg surface and >= 5 mmHg core criteria for chronic S6, binding vascular access to the loaded and closed state (Chendke et al. 2023 PMID:37476069), and comparing any folded/corrugated capacity advantage against a matched separated reference at equal product, dose, and total supply.",
"treatment_state_applicability": "Record each functional-dose result as graft-only simulation, externally maintained clamp, or insulin-supported treatment state (including tested dose, site, lag, and concurrent treatment inputs), and do not use a graft-only trajectory to certify a treatment state it does not represent.",
"implantation_state_oxygen_release_material": "Bind coupon-derived kinetic parameters, empirical hydrolysis half-life t_1/2, kinetic-law code (Gate_P05_kinetics), CaO2 crystal PSD, composite microbead diameter distribution, catalase surface immobilization state, remaining releasable inventory, peroxide/pH state, and material geometry to the exact CaO2:PDMS formulation (25 wt%, 31.25 wt% [13.86 vol%], or 46.39 wt% [23.45 vol%]; never inherited across wt% recipes per IIP-0010 / DEC-088) as implanted after storage, wetting, loading, and handling; replay preimplant history or initialise its measured residual state once (for the reaction-controlled shrinking-core law, a 68.0 h initial half-life after 24.0 h gives residual stock 0.797084 and residual half-life 63.0488 h, not 44 h, and crossing its 10 h branch requires ~281.145 h).",
},
},
"shrinking_core_coupled_bvp_safety_comparison_ultracode_v80_09": {
"calibration_note": (
f"First-order and shrinking-core laws share {results[2]['cao2_initial_molar_inventory_mmol']:.3f} mmol "
f"({results[2]['cao2_initial_mass_mg_in_7cm3_slab']:.1f} mg) initial CaO2 and matched "
f"{results[2]['cao2_hydrolysis_half_life_hours']:.1f} h half-time. These are conditional chemistry/transport predictions. "
+ "; ".join(
f"{fo['scenario_id']}: first-order min slab {fo['min_slab_po2_mmhg']:.2f} mmHg at {fo['time_of_min_slab_po2_hours']:.0f} h, "
f"Dirichlet upper-bound core {fo['min_120um_cluster_core_po2_mmhg']:.2f}, uniform core {fo['two_zone_fv_uniform_supply_core_po2_mmhg']:.2f}, "
f"gel-only core {fo['two_zone_fv_gel_only_supply_core_po2_mmhg']:.2f}; shrinking-core min slab "
f"{sc['min_slab_po2_across_14_days_mmhg']:.2f} mmHg at {sc['time_of_min_slab_po2_hours']:.0f} h, "
f"Dirichlet upper-bound core {sc['min_120um_cluster_core_po2_mmhg']:.2f}, uniform core "
f"{sc['wigner_seitz_120um_cluster_pericellular_shell_audit_v80_001']['two_zone_fv_uniform_supply_120um_core_po2_mmhg']:.2f}, "
f"gel-only core {sc['wigner_seitz_120um_cluster_pericellular_shell_audit_v80_001']['two_zone_fv_gel_only_supply_120um_core_po2_mmhg']:.2f} mmHg"
for fo, sc in zip(sensitivity_table, shrinking_core_coupled_regimes)
)
),
"coupled_shrinking_core_regimes": shrinking_core_coupled_regimes,
},
}
def _trajectory_half_drop_time(times: np.ndarray, secretion: np.ndarray, start_min: float, end_min: float) -> float | None:
"""Elapsed half-drop time in the actual simulated intervention window; no drop is unavailable."""
x = np.asarray(times)
y = np.asarray(secretion)
if (x.ndim != 1 or y.shape != x.shape or len(x) < 2
or not all(np.issubdtype(a.dtype, np.integer) or np.issubdtype(a.dtype, np.floating) for a in (x, y))
or not np.all(np.isfinite(x)) or not np.all(np.isfinite(y))
or np.any(np.diff(x) <= 0) or np.any(y < 0)
or not all(isinstance(v, (int, float)) and not isinstance(v, bool) and math.isfinite(v) for v in (start_min, end_min))
or start_min >= end_min or x[0] > start_min or x[-1] < end_min):
raise ValueError("half-drop metric requires finite ordered times, nonnegative secretion and a covered intervention window")
selected = (x > start_min) & (x < end_min)
tx = np.r_[start_min, x[selected], end_min]
sy = np.interp(tx, x, y)
initial, nadir = float(sy[0]), float(np.min(sy))
if initial - nadir <= max(1e-12, abs(initial) * 1e-12):
return None
target = nadir + 0.5 * (initial - nadir)
for k in range(1, len(tx)):
if sy[k] <= target:
fraction = (float(sy[k-1]) - target) / (float(sy[k-1]) - float(sy[k]))
return float(tx[k-1] + fraction * (tx[k] - tx[k-1]) - start_min)
return None
def evaluate_measured_washout_trace_completeness_bpr15(
times_min: List[float],
remaining_fraction: List[float],
*,
mass_recovery_fraction: Optional[float] = None,
required_tail_bound_fraction: float = 0.10,
min_observation_window_min: float = 15.0,
) -> Dict[str, Any]:
"""
Validate whether a measured whole-device insulin washout trace sufficiently bounds the
late washout tail before extrapolating an exercise glucose verdict (BPR-15 / DEC-133).
A trace ending before the late fraction is bounded leaves extrapolation unresolved.
"""
if len(times_min) < 2 or len(times_min) != len(remaining_fraction):
return {
"status": "EXTRAPOLATION_UNRESOLVED_INVALID_TRACE",
"tail_bounded": False,
"reason": "Need matching time and remaining_fraction sequences of length >= 2.",
}
t_arr = [float(x) for x in times_min]
s_arr = [float(x) for x in remaining_fraction]
if any(t_arr[i + 1] <= t_arr[i] for i in range(len(t_arr) - 1)):
return {
"status": "EXTRAPOLATION_UNRESOLVED_NON_MONOTONIC_TIME",
"tail_bounded": False,
"reason": "Washout timestamps must be strictly increasing.",
}
obs_window = t_arr[-1] - t_arr[0]
end_remaining = s_arr[-1]
reasons: List[str] = []
if obs_window < min_observation_window_min:
reasons.append(f"observation_window_min={obs_window:.3f} < {min_observation_window_min:.1f}")
if end_remaining > required_tail_bound_fraction:
reasons.append(
f"remaining_fraction_at_end={end_remaining:.4f} > {required_tail_bound_fraction:.2f} (late tail unbounded)"
)
if mass_recovery_fraction is None or not math.isfinite(float(mass_recovery_fraction)) or not (0.80 <= float(mass_recovery_fraction) <= 1.20):
reasons.append(f"mass_recovery_fraction={mass_recovery_fraction!r} missing or outside [0.80, 1.20]")
if reasons:
return {
"status": "EXTRAPOLATION_UNRESOLVED_INSUFFICIENT_TAIL_WINDOW",
"tail_bounded": False,
"observation_window_min": round(obs_window, 6),
"remaining_fraction_at_end": round(end_remaining, 6),
"mass_recovery_fraction": mass_recovery_fraction,
"reasons": reasons,
}
return {