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…

    if not math.isfinite(raw_mbe) or raw_mbe >= 1e-10:
        raise ValueError(f"Mass balance residual exceeded 1e-10 in {label}: {raw_mbe}")
    return {
        "label": label,
        "grid_nx_ny_nz": [nx, nx, nz],
        "area_cm2": area_cm2,
        "loading_ieq_cm2": round(loading_ieq_cm2, 2),
        "slot_height_um": h_slot_um,
        "cluster_diam_um": cluster_diam_um,
        "bed_po2_mmhg": bed_po2_mmhg,
        "sleeve_um": sleeve_um,
        "sleeve_d_factor": round(sleeve_d_factor, 4),
        "k_perf_gel_s_inv": k_perf_gel_s_inv,
        "k_perf_islet_s_inv": k_perf_islet_s_inv,
        "ocr_mult": round(ocr_mult, 4),
        "alpha_mol_cm3_mmhg": alpha_mol_cm3_mmhg,
        "pitch_um": round(pitch_cm * 1e4, 3),
        "worst_face_mmhg": round(worst_face, 4),
        "worst_core_mmhg": round(worst_core, 4),
        "passes_15_and_5": bool(worst_face >= 15.0 and worst_core >= 5.0),
        "passes_core_5mmhg_floor": bool(worst_core >= 5.0),
        "rel_mass_balance_error_str": f"{raw_mbe:.3e}",
        "mass_balance_bound_lt_1e10": True,
    }


def _solve_1d_slab_fall_t50_min(modes: List[tuple[float, float]], k_int: float) -> float:
    def _frac(t_s: float) -> float:
        tot = 0.0
        for cn, lam in modes:
            if abs(lam - k_int) < 1e-12:
                term = (1.0 + k_int * t_s) * math.exp(-k_int * t_s)
            else:
                term = (lam * math.exp(-k_int * t_s) - k_int * math.exp(-lam * t_s)) / (lam - k_int)
            tot += cn * term
        return tot

    lo, hi = 0.0, 1200.0
    for _ in range(64):
        mid = 0.5 * (lo + hi)
        if _frac(mid) > 0.5:
            lo = mid
        else:
            hi = mid
    return 0.5 * (lo + hi) / 60.0


def _uniform_modes(l_eff_cm: float, d_ins_cm2_s: float, n_modes: int) -> List[tuple[float, float]]:
    modes: List[tuple[float, float]] = []
    pi_2l = math.pi / (2.0 * l_eff_cm)
    for n in range(n_modes):
        odd = 2 * n + 1
        a = odd * pi_2l
        modes.append((8.0 / ((odd * math.pi) ** 2), a * a * d_ins_cm2_s))
    return modes


def _spatial_modes(l_cm: float, r_cm: float, z_c: float, d_ins_cm2_s: float, n_modes: int) -> List[tuple[float, float]]:
    modes: List[tuple[float, float]] = []
    pi_2l = math.pi / (2.0 * l_cm)
    for n in range(n_modes):
        odd = 2 * n + 1
        a = odd * pi_2l
        x = a * r_cm
        sph_factor = 3.0 * (math.sin(x) - x * math.cos(x)) / (x ** 3)
        cn = (4.0 / (odd * math.pi)) * ((-1.0) ** n) * math.cos(a * z_c) * sph_factor
        modes.append((cn, a * a * d_ins_cm2_s))
    return modes


def _bisect_intrinsic_t50_for_target(modes: List[tuple[float, float]], target_fall_t50_min: float = 3.0) -> float:
    lo, hi = 0.5, 3.0
    for _ in range(52):
        mid = 0.5 * (lo + hi)
        k_int = math.log(2.0) / (mid * 60.0)
        if _solve_1d_slab_fall_t50_min(modes, k_int) < target_fall_t50_min:
            lo = mid
        else:
            hi = mid
    return 0.5 * (lo + hi)


def compute_planar_insulin_shutoff_table() -> Dict[str, Any]:
    """Exact 1D bilateral slab Fourier-series insulin shutoff reporting BOTH 45-mode & converged 5,000-mode reference."""
    d_ins_cm2_s = 5.0e-7  # hydrated hydrogel insulin diffusivity (~1/3 free-water 1.5e-6 cm^2/s)
    t50_intrinsic_min = 1.75  # hardcoded proposal modeling assumption (NOT a reported Nair 2019 fitted half-time)
    k_int = math.log(2.0) / (t50_intrinsic_min * 60.0)
    n_modes_ref = 5000
    n_modes_45 = 45
    cases = [
        ("H180_clean", 180.0, 0.0, 1.0),
        ("H180_plus_15um_fibrin", 180.0, 15.0, 0.5),
        ("H200_clean", 200.0, 0.0, 1.0),
        ("H220_clean_BARRED", 220.0, 0.0, 1.0),
    ]
    rows: List[Dict[str, Any]] = []
    h200_unif_modes_45: List[tuple[float, float]] = []
    h200_unif_modes_ref: List[tuple[float, float]] = []
    for lbl, h_um, df_um, d_fib_factor in cases:
        l_eff_cm = (0.5 * h_um + (df_um / d_fib_factor)) * 1e-4
        m45 = _uniform_modes(l_eff_cm, d_ins_cm2_s, n_modes_45)
        mref = _uniform_modes(l_eff_cm, d_ins_cm2_s, n_modes_ref)
        if lbl == "H200_clean":
            h200_unif_modes_45 = m45
            h200_unif_modes_ref = mref
        t50_45 = _solve_1d_slab_fall_t50_min(m45, k_int)
        t50_ref = _solve_1d_slab_fall_t50_min(mref, k_int)
        rows.append({
            "case": lbl,
            "slot_height_um": h_um,
            "fibrin_sleeve_um": df_um,
            "effective_half_thickness_um": round(l_eff_cm * 1e4, 2),
            "modeled_fall_t50_converged_5000mode_min": round(t50_ref, 5),
            "modeled_fall_t50_45mode_min": round(t50_45, 5),
            "modeled_fall_t50_min": round(t50_ref, 3),
            "passes_lt_3p0_min": bool(t50_ref < 3.0),
        })

    spatial_rows: List[Dict[str, Any]] = []
    h200_sp_modes_ref: List[tuple[float, float]] = []
    h200_sp_t50_ref = 0.0
    for lbl, h_um, diam_um in [
        ("Spatial_65um_Bilayer_H180_clean", 180.0, 65.0),
        ("Spatial_65um_Bilayer_H200_clean", 200.0, 65.0),
        ("Spatial_120um_CenteredVPIO_H180_clean_FAIL", 180.0, 120.0),
        ("Spatial_120um_CenteredVPIO_H200_clean_FAIL", 200.0, 120.0),
    ]:
        l_cm = 0.5 * h_um * 1e-4
        r_cm = 0.5 * diam_um * 1e-4
        z_c = (l_cm - r_cm - 15.0e-4) if diam_um <= 80.0 else 0.0
        m45 = _spatial_modes(l_cm, r_cm, z_c, d_ins_cm2_s, n_modes_45)
        mref = _spatial_modes(l_cm, r_cm, z_c, d_ins_cm2_s, n_modes_ref)
        t50_45 = _solve_1d_slab_fall_t50_min(m45, k_int)
        t50_ref = _solve_1d_slab_fall_t50_min(mref, k_int)
        if lbl == "Spatial_65um_Bilayer_H200_clean":
            h200_sp_modes_ref = mref
            h200_sp_t50_ref = t50_ref
        spatial_rows.append({
            "case": lbl,
            "slot_height_um": h_um,
            "cluster_diam_um": diam_um,
            "sphere_center_offset_um": round(z_c * 1e4, 2),
            "modeled_fall_t50_converged_5000mode_min": round(t50_ref, 6),
            "modeled_fall_t50_45mode_min": round(t50_45, 6),
            "modeled_fall_t50_min": round(t50_ref, 3),
            "passes_lt_3p0_min": bool(t50_ref < 3.0),
        })

    cutoff_unif_45 = _bisect_intrinsic_t50_for_target(h200_unif_modes_45, 3.0)
    cutoff_unif_ref = _bisect_intrinsic_t50_for_target(h200_unif_modes_ref, 3.0)
    cutoff_sp_ref = _bisect_intrinsic_t50_for_target(h200_sp_modes_ref, 3.0)
    margin_sp_h200_s = (3.0 - h200_sp_t50_ref) * 60.0

    return {
        "model_assumptions": {
            "d_insulin_hydrogel_cm2_s": d_ins_cm2_s,
            "unencapsulated_intrinsic_t50_min": t50_intrinsic_min,
            "intrinsic_t50_parameter_provenance": "proposal_modeling_assumption_not_reported_nair_fit",
            "reference_fourier_modes": n_modes_ref,
            "comparison_truncated_fourier_modes": n_modes_45,
            "h200_uniform_clean_cutoff_intrinsic_t50_5000mode_min": round(cutoff_unif_ref, 6),
            "h200_uniform_clean_cutoff_intrinsic_t50_45mode_min": round(cutoff_unif_45, 6),
            "h200_spatial_65um_clean_cutoff_intrinsic_t50_5000mode_min": round(cutoff_sp_ref, 6),
            "h200_spatial_65um_clean_margin_below_3min_seconds": round(margin_sp_h200_s, 3),
            "fibrin_sleeve_model": "effective_homogeneous_transit_thickness_approximation",
            "caveat": (
                "Continuum 1D bilateral slab Fourier model using a 1.75-min intrinsic shutoff modeling assumption "
                "(motivated by Nair 2019 S3d step-down context, NOT a directly reported Nair fitted half-time). "
                f"Converged {n_modes_ref:,}-mode reference shifts uniform slabs by +0.008-0.009 min vs {n_modes_45} modes "
                f"(uniform H200 3.0-min intrinsic cutoff: {cutoff_unif_ref:.6f} min at {n_modes_ref:,} modes "
                f"[1.808982 min at 30,000 modes] vs {cutoff_unif_45:.6f} min at {n_modes_45} modes) and spatial projections "
                f"by <= 0.000014 min (spatial 65 um H200 cutoff: {cutoff_sp_ref:.6f} min, nominal margin {margin_sp_h200_s:.3f} s; "
                "centered 120 um VPIOs fail clean at 3.070 / 3.385 min even where Hybrid H180 nominal oxygen passes). "
                "Borderline H200 remains an unqualified scenario pending empirical chamber-corrected loaded-envelope perifusion (R3P-04)."
            ),
        },
        "cases": rows,
        "spatially_weighted_1d_projection_cases": spatial_rows,
    }


def compute_sequential_colony_screening_audit() -> Dict[str, Any]:
    """Forward binomial colony screening math from explicitly declared planning rates (no back-solving)."""
    p_single_17kb = 0.00219   # 0.219% assumed single-step 17.2 kb efficiency
    p_step1_10p5kb = 0.01294  # 1.294% assumed Step-1 10.45 kb attP-GT efficiency
    p_step2_6p9kb = 0.02117   # 2.117% assumed Step-2 6.91 kb attP-CA efficiency

    def _n_for_conf(p: float, target_conf: float) -> int:
        return int(math.ceil(math.log(1.0 - target_conf) / math.log(1.0 - p)))

    def _joint_prob(n1: int, n2: int) -> float:
        return (1.0 - ((1.0 - p_step1_10p5kb) ** n1)) * (1.0 - ((1.0 - p_step2_6p9kb) ** n2))

    per_stage_for_95_joint = math.sqrt(0.95)
    n_single_95 = _n_for_conf(p_single_17kb, 0.95)
    n1_95_stage = _n_for_conf(p_step1_10p5kb, 0.95)
    n2_95_stage = _n_for_conf(p_step2_6p9kb, 0.95)
    n1_95_joint = _n_for_conf(p_step1_10p5kb, per_stage_for_95_joint)
    n2_95_joint = _n_for_conf(p_step2_6p9kb, per_stage_for_95_joint)
    exact_joint_per_stage_95 = _joint_prob(n1_95_stage, n2_95_stage)
    exact_joint_true_95 = _joint_prob(n1_95_joint, n2_95_joint)

    # Exact exhaustive integer minimization for >= 95% joint probability of >= 1 colony at each step
    best_total = n1_95_joint + n2_95_joint
    min_allocs: List[List[int]] = []
    for n1 in range(1, best_total + 1):
        p1 = 1.0 - ((1.0 - p_step1_10p5kb) ** n1)
        if p1 < 0.95:
            continue
        rem = 1.0 - (0.95 / p1)
        n2 = int(math.ceil(math.log(rem) / math.log(1.0 - p_step2_6p9kb)))
        if _joint_prob(n1, n2) < 0.95:
            n2 += 1
        tot = n1 + n2
        if tot < best_total:
            best_total = tot
            min_allocs = [[n1, n2]]
        elif tot == best_total:
            min_allocs.append([n1, n2])

    return {
        "assumed_forward_per_colony_rates": {
            "single_step_17kb": p_single_17kb,
            "step1_10p5kb_attp_gt": p_step1_10p5kb,
            "step2_6p9kb_attp_ca": p_step2_6p9kb,
        },
        "transferred_planning_rates_note": (
            "Forward planning calculation of P(>=1 acceptable colony at each sequential step) from explicitly declared "
            "independent-draw planning rates (not back-solved from colony counts); Pandey 2024/2025 (PMID:38858586) "
            "provides no exact-product yield for Design Y, and direct hiPSC integration rates remain unmeasured pending Stage-0 Y-05."
        ),
        "single_step_17kb_n95": n_single_95,
        "two_stage_per_stage_95pct_colonies": [n1_95_stage, n2_95_stage],
        "two_stage_per_stage_95pct_total": n1_95_stage + n2_95_stage,
        "two_stage_per_stage_95pct_continuous_lower_bound_pct": round(100.0 * (0.95 * 0.95), 2),
        "two_stage_per_stage_95pct_joint_success_pct": round(100.0 * exact_joint_per_stage_95, 4),
        "per_stage_confidence_for_true_95pct_joint_pct": round(100.0 * per_stage_for_95_joint, 4),
        "two_stage_equal_margin_95pct_joint_colonies": [n1_95_joint, n2_95_joint],
        "two_stage_equal_margin_95pct_joint_total": n1_95_joint + n2_95_joint,
        "two_stage_equal_margin_95pct_joint_exact_success_pct": round(100.0 * exact_joint_true_95, 4),
        "two_stage_exact_minimum_95pct_joint_total": best_total,
        "two_stage_exact_minimum_95pct_joint_allocation_count": len(min_allocs),
        "two_stage_exact_minimum_95pct_joint_allocations": min_allocs,
        "two_stage_equal_margin_455_at_1p0pct_floor_joint_pct": round(
            100.0 * (1.0 - (0.99 ** n1_95_joint)) * (1.0 - (0.99 ** n2_95_joint)), 4
        ),
        "allocation_uniqueness_note": (
            f"{n1_95_joint} + {n2_95_joint} = {n1_95_joint + n2_95_joint} is the equal-margin (sqrt(0.95) per-stage) "
            f"allocation, NOT the minimum total: exact integer minimization gives {best_total} colonies across "
            f"{len(min_allocs)} qualifying splits ({min_allocs[0][0]}+{min_allocs[0][1]} through "