OpenIslet

scripts/verify_iip0057_foundry_v2_shield_invvax_insl82i_cuffv2.py

W6-C3 (Provisional Next-Free IIP-0057 / DEC-138 / GATE-36 / GY-035; staging slot iip0057,

script Release v0.8.0 gen-eb955f8266035aba 412 KB · 32 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_iip0057_foundry_v2_shield_invvax_insl82i_cuffv2.py · SHA-256: 1c63dcf649c42be4…

    """Exact converged periodic steady-state 4-state 2-compartment + dLN free-concentration PK solver.

    Solves BOTH:
      (1) Closed-form periodic fixed point (I - M) y* = M d via exact 4x4 RK4 cycle propagator M
      (2) Cycle-by-cycle iteration until relative cycle-to-cycle change < 1e-10
    and computes modeled receptor occupancy via the single consistent free_ligand_ro convention.
    """
    dose_nmol = (dose_mg / mw_kda) * 1e3
    k10 = CL_L_per_day / V1_L
    k12 = Q_L_per_day / V1_L
    k21 = Q_L_per_day / V2_L

    tr = k10 + k12 + k21
    det = k10 * k21
    disc = math.sqrt(max(0.0, tr * tr - 4.0 * det))
    alpha = 0.5 * (tr + disc)
    beta = 0.5 * (tr - disc)
    t_half_alpha_h = (math.log(2.0) / alpha) * 24.0
    t_half_beta_d = math.log(2.0) / beta

    steps_per_cycle = int(round(tau_days / dt_days))
    dt = tau_days / steps_per_cycle

    def deriv(y0: float, y1: float, y2: float, y3: float) -> tuple[float, float, float, float]:
        c1 = y1 / V1_L
        return (
            -ka_per_day * y0,
            ka_per_day * y0 - (k10 + k12) * y1 + k21 * y2,
            k12 * y1 - k21 * y2,
            k_ln_eq_per_day * (kp_dln * c1 - y3),
        )

    def rk4_one_cycle(y_start: list[float]) -> tuple[list[float], float, float]:
        y0, y1, y2, y3 = y_start
        c1_pk = y1 / V1_L
        cln_pk = y3
        for _ in range(steps_per_cycle):
            k1_0, k1_1, k1_2, k1_3 = deriv(y0, y1, y2, y3)
            k2_0, k2_1, k2_2, k2_3 = deriv(
                y0 + 0.5 * dt * k1_0, y1 + 0.5 * dt * k1_1,
                y2 + 0.5 * dt * k1_2, y3 + 0.5 * dt * k1_3,
            )
            k3_0, k3_1, k3_2, k3_3 = deriv(
                y0 + 0.5 * dt * k2_0, y1 + 0.5 * dt * k2_1,
                y2 + 0.5 * dt * k2_2, y3 + 0.5 * dt * k2_3,
            )
            k4_0, k4_1, k4_2, k4_3 = deriv(
                y0 + dt * k3_0, y1 + dt * k3_1,
                y2 + dt * k3_2, y3 + dt * k3_3,
            )
            f = dt / 6.0
            y0 = max(0.0, y0 + f * (k1_0 + 2.0 * k2_0 + 2.0 * k3_0 + k4_0))
            y1 = max(0.0, y1 + f * (k1_1 + 2.0 * k2_1 + 2.0 * k3_1 + k4_1))
            y2 = max(0.0, y2 + f * (k1_2 + 2.0 * k2_2 + 2.0 * k3_2 + k4_2))
            y3 = max(0.0, y3 + f * (k1_3 + 2.0 * k2_3 + 2.0 * k3_3 + k4_3))
            c1_now = y1 / V1_L
            if c1_now > c1_pk:
                c1_pk = c1_now
            if y3 > cln_pk:
                cln_pk = y3
        return [y0, y1, y2, y3], c1_pk, cln_pk

    d_vec = [0.0, dose_nmol, 0.0, 0.0] if route == "IV" else [dose_nmol * F_sc, 0.0, 0.0, 0.0]

    # Cycle 1 readout
    y_c1, _, _ = rk4_one_cycle(d_vec)

    # Method 1: Exact 4x4 periodic fixed point (I - M) y_trough = M d
    M = [[0.0] * 4 for _ in range(4)]
    for col in range(4):
        e = [1.0 if i == col else 0.0 for i in range(4)]
        y_col, _, _ = rk4_one_cycle(e)
        for row in range(4):
            M[row][col] = y_col[row]
    A_mat = [[(1.0 if r == c else 0.0) - M[r][c] for c in range(4)] for r in range(4)]
    rhs = [sum(M[r][c] * d_vec[c] for c in range(4)) for r in range(4)]
    y_trough = _solve_4x4_linear(A_mat, rhs)
    y_trough = [max(0.0, v) for v in y_trough]
    y_post = [y_trough[i] + d_vec[i] for i in range(4)]
    y_check, c1_cmax_ss, cln_cmax_ss = rk4_one_cycle(y_post)
    fixed_pt_rel_err = max(
        abs(y_check[i] - y_trough[i]) / max(1e-12, abs(y_trough[i]))
        for i in range(4)
    )
    require_cond(fixed_pt_rel_err < 1e-10, f"Periodic fixed point did not converge for {name}: err={fixed_pt_rel_err}")

    # Method 2: Cycle-by-cycle iteration to < 1e-10 relative cycle-to-cycle change
    y_it = [0.0, 0.0, 0.0, 0.0]
    cycles_to_converge = 0
    c1_pk_it = 0.0
    for cyc in range(1, max_cycles + 1):
        y_prev = list(y_it)
        y_it, c1_pk_it, _ = rk4_one_cycle([y_it[i] + d_vec[i] for i in range(4)])
        cycles_to_converge = cyc
        rel = max(abs(y_it[i] - y_prev[i]) / max(1e-12, abs(y_it[i])) for i in range(4))
        if rel < conv_tol:
            break
    require_cond(
        abs(c1_pk_it - c1_cmax_ss) / max(1e-12, c1_cmax_ss) < 1e-8,
        f"Periodic fixed-point vs cycle-iteration mismatch for {name}: {c1_cmax_ss} vs {c1_pk_it}",
    )

    c1_tr_ss = y_trough[1] / V1_L
    cln_tr_ss = y_trough[3]
    ro_c1: dict[str, float] = {}
    ro_ss: dict[str, float] = {}
    for kd in (0.1, 1.0, 5.0, 10.0):
        key = f"Kd_{kd:g}nM"
        ro_c1[key] = round(100.0 * free_ligand_ro(y_c1[3], kd), 4)
        ro_ss[key] = round(100.0 * free_ligand_ro(cln_tr_ss, kd), 4)

    sieving = renkin_glomerular_sieving(rh_eff_nm)
    return {
        "modality": name,
        "parameter_basis": parameter_basis,
        "occupancy_convention": OCCUPANCY_CONVENTION,
        "mw_kda": mw_kda,
        "rh_eff_nm": rh_eff_nm,
        "renkin_sieving_coeff": round(sieving, 4),
        "predicted_renal_CL_L_per_day": round(sieving * 172.8, 3),
        "simulated_CL_L_per_day": CL_L_per_day,
        "kp_dln": kp_dln,
        "dose_mg": dose_mg,
        "route": route,
        "tau_days": tau_days,
        "t_half_alpha_h": round(t_half_alpha_h, 3),
        "t_half_beta_days": round(t_half_beta_d, 4),
        "t_half_beta_min": round(t_half_beta_d * 1440.0, 2),
        "periodic_convergence_cycles_le_1e10": cycles_to_converge,
        "periodic_fixed_point_rel_err": float(f"{fixed_pt_rel_err:.2e}"),
        "periodic_ss_Cmax_plasma_nM": round(c1_cmax_ss, 4),
        "periodic_ss_Cmax_dLN_nM": round(cln_cmax_ss, 4),
        "periodic_ss_trough_plasma_nM": round(c1_tr_ss, 4),
        "periodic_ss_trough_dLN_nM": round(cln_tr_ss, 4),
        "cycle1_trough_dLN_RO_pct": ro_c1,
        "periodic_ss_trough_dLN_RO_pct": ro_ss,
    }


def simulate_coupled_nonlinear_tmdd_periodic(
    label: str,
    dose_mg: float,
    tau_days: float,
    kd_off_nM: float,
    kd_on_nM: float = 1.0,
    r_off_nmol: float = 16.60539,
    k_int_off_per_day: float = 0.5,
    b_max_dln_nM: float = 0.083,
    k_int_on_per_day: float = 0.5,
    v_dln_L: float = 0.05,
    mw_kda: float = 150.0,
    F_sc: float = 0.68,
    ka_per_day: float = 0.25,
    V1_L: float = 3.0,
    V2_L: float = 2.8,
    Q_L_per_day: float = 0.50,
    CL_L_per_day: float = 0.092,
    kp_dln: float = 0.25,
    k_ln_eq_per_day: float = 1.0,
    dt_days: float = 1.0 / 24.0,
    conv_tol: float = 1e-10,
    max_cycles: int = 200,
) -> dict[str, Any]:
    """Mass-conserving 6-state coupled nonlinear Michaelis-Menten TMDD periodic ODE (R2-14 closure).

    State vector in nmol: (A_sc, A_central, A_periph, A_dln, A_eliminated_lin, A_eliminated_tmdd).
      - Exact balanced central <-> dLN exchange counterterm: J_cent_to_dln = k_ln_eq * V_dln * (Kp_dln * c1 - cln)
        subtracted from dA_central/dt and added to dA_dln/dt (sum = 0).
      - Single-charged dLN on-target internalization: F_on = Vmax_on_nmol_d * cln / (Kd_on + cln)
        subtracted ONLY from dA_dln/dt and credited to dA_eliminated_tmdd/dt (ZERO double-charging!).
      - Systemic off-target internalization: F_off = Vmax_off_nmol_d * c1 / (Kd_off + c1)
        subtracted from dA_central/dt and credited to dA_eliminated_tmdd/dt.
      - Linear elimination: k10 * A_central subtracted from dA_central/dt and credited to dA_eliminated_lin/dt.
    Verifies exact mass conservation:
      A_sc + A_central + A_periph + A_dln + A_eliminated_lin + A_eliminated_tmdd == Dose_cumulative
    to < 1e-10 relative error at EVERY dosing cycle, using the single free_ligand_ro convention.
    """
    dose_nmol = (dose_mg / mw_kda) * 1e3
    bioavail_dose_nmol = dose_nmol * F_sc
    k10 = CL_L_per_day / V1_L
    k12 = Q_L_per_day / V1_L
    k21 = Q_L_per_day / V2_L
    vmax_off_nmol_d = r_off_nmol * k_int_off_per_day
    vmax_on_nmol_d = b_max_dln_nM * k_int_on_per_day * v_dln_L
    steps = int(round(tau_days / dt_days))
    dt = tau_days / steps

    def deriv(y: list[float]) -> tuple[float, float, float, float, float, float]:
        a_sc, a_c, a_p, a_ln, _, _ = y
        c1 = max(0.0, a_c / V1_L)
        cln = max(0.0, a_ln / v_dln_L)
        j_cent_to_dln = k_ln_eq_per_day * v_dln_L * (kp_dln * c1 - cln)
        f_off = vmax_off_nmol_d * free_ligand_ro(c1, kd_off_nM)
        f_on = vmax_on_nmol_d * free_ligand_ro(cln, kd_on_nM)
        f_lin = k10 * a_c
        return (
            -ka_per_day * a_sc,
            ka_per_day * a_sc - f_lin - k12 * a_c + k21 * a_p - j_cent_to_dln - f_off,
            k12 * a_c - k21 * a_p,
            j_cent_to_dln - f_on,
            f_lin,
            f_off + f_on,
        )

    y = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
    dose_cumulative = 0.0
    max_rel_mass_err = 0.0
    final_rel_mass_err = 0.0
    cyc_used = 0
    c1_pk = 0.0
    rel = 1.0
    for cyc in range(1, max_cycles + 1):
        prev = (y[0], y[1], y[2], y[3])
        y[0] += bioavail_dose_nmol
        dose_cumulative += bioavail_dose_nmol
        c1_pk = y[1] / V1_L
        for _ in range(steps):
            k1 = deriv(y)
            k2 = deriv([y[i] + 0.5 * dt * k1[i] for i in range(6)])
            k3 = deriv([y[i] + 0.5 * dt * k2[i] for i in range(6)])
            k4 = deriv([y[i] + dt * k3[i] for i in range(6)])
            f = dt / 6.0
            y = [y[i] + f * (k1[i] + 2.0 * k2[i] + 2.0 * k3[i] + k4[i]) for i in range(6)]
            require_cond(all(v >= -1e-12 for v in y), f"Negative TMDD mass state for {label}: {y}")
            c1_now = y[1] / V1_L
            if c1_now > c1_pk:
                c1_pk = c1_now
        total_mass = sum(y)
        final_rel_mass_err = abs(total_mass - dose_cumulative) / max(1e-12, dose_cumulative)
        if final_rel_mass_err > max_rel_mass_err:
            max_rel_mass_err = final_rel_mass_err
        require_cond(
            final_rel_mass_err < 1e-10,
            f"TMDD mass ledger conservation violated at cycle {cyc} for {label}: rel_err={final_rel_mass_err}",
        )
        cyc_used = cyc
        rel = max(abs(y[i] - prev[i]) / max(1e-12, abs(y[i])) for i in range(4))
        if rel < conv_tol:
            break

    require_cond(rel < conv_tol, f"Coupled TMDD ODE failed to converge for {label}: rel={rel}")
    c1_tr = y[1] / V1_L
    cln_tr = y[3] / v_dln_L
    on_ro_pct = 100.0 * free_ligand_ro(cln_tr, kd_on_nM)
    off_pk_ro_pct = 100.0 * free_ligand_ro(c1_pk, kd_off_nM)
    off_tr_ro_pct = 100.0 * free_ligand_ro(c1_tr, kd_off_nM)
    off_dln_ro_pct = 100.0 * free_ligand_ro(cln_tr, kd_off_nM)

    return {
        "scenario": label,