scripts/verify_iip0057_foundry_v2_shield_invvax_insl82i_cuffv2.py
Use this file in any AI chat (paste-only or attachment-capable):
Pinned raw file: https://openislet.org/files/gen-eb955f8266035aba/scripts/verify_iip0057_foundry_v2_shield_invvax_insl82i_cuffv2.py · SHA-256: 1c63dcf649c42be4…
"dibasic_count": len(dibasic),
}
def count_non_native_junction_kmers(native_core: str, conjugated_seq: str) -> int:
wt_kmers: set[str] = set()
for k in (8, 9, 10, 11):
for i in range(len(native_core) - k + 1):
wt_kmers.add(native_core[i : i + k])
n_native = len(native_core)
cnt = 0
for k in (8, 9, 10, 11):
for i in range(len(conjugated_seq) - k + 1):
if i + k > n_native:
if conjugated_seq[i : i + k] not in wt_kmers:
cnt += 1
return cnt
# ---------------------------------------------------------------------------
# Deterministic Coordinate-Based RCSB Heavy-Atom Contact Counter (Zero Hardcoding)
# ---------------------------------------------------------------------------
def _count_heavy_atom_contacts(
binder_atoms: list[list[Any]],
target_atoms: list[list[Any]],
cutoff_A: float,
) -> tuple[int, dict[str, int], dict[str, int]]:
c2 = cutoff_A * cutoff_A
total = 0
per_t: dict[str, int] = collections.Counter()
per_b: dict[str, int] = collections.Counter()
for bc, br, ba, _, bx, by, bz in binder_atoms:
for tc, tr, ta, _, tx, ty, tz in target_atoms:
dx = bx - tx
dy = by - ty
dz = bz - tz
if dx * dx + dy * dy + dz * dz <= c2:
total += 1
per_t[f"{ta}{tr}"] += 1
per_b[f"{bc}:{ba}{br}"] += 1
return total, dict(per_t), dict(per_b)
def compute_deterministic_pdb_contacts(coords_path: Path) -> dict[str, Any]:
"""Compute exact heavy-atom interface contacts directly from verified RCSB CC0-1.0 3D coordinates."""
require_cond(coords_path.is_file(), f"Missing RCSB coordinate subset file: {coords_path}")
actual_sha = sha256_file(coords_path)
require_cond(
actual_sha == EXPECTED_RCSB_COORDS_SHA256,
f"RCSB coordinate subset SHA-256 mismatch: {actual_sha} != {EXPECTED_RCSB_COORDS_SHA256}",
)
payload = load_strict_json(coords_path)
require_cond(isinstance(payload, dict) and isinstance(payload.get("complexes"), dict), "Malformed RCSB coords JSON")
complex_results: dict[str, Any] = {}
for key, entry in payload["complexes"].items():
b_atoms = entry["binder_atoms"]
a_atoms = entry["dq_alpha_atoms"]
beta_atoms = entry["dq_beta_atoms"]
p_atoms = entry["peptide_atoms"]
cdr_ranges = entry.get("cdr_ranges") or {}
cut_out: dict[str, Any] = {}
for cut_lbl, cut_val in (("le_4p5A", 4.5), ("le_4p0A", 4.0)):
n_a, _, _ = _count_heavy_atom_contacts(b_atoms, a_atoms, cut_val)
n_b, _, _ = _count_heavy_atom_contacts(b_atoms, beta_atoms, cut_val)
n_p, pep_res_counts, b_pep_counts = _count_heavy_atom_contacts(b_atoms, p_atoms, cut_val)
tot = n_a + n_b + n_p
require_cond(tot > 0, f"Zero heavy-atom contacts computed for {key} at {cut_val} A")
sorted_pep = sorted(pep_res_counts.items(), key=lambda x: (-x[1], x[0]))
max_res, max_cnt = sorted_pep[0] if sorted_pep else ("none", 0)
cdr_breakdown: dict[str, int] = {}
for loop_name, spec in cdr_ranges.items():
lch, rlo, rhi = spec[0], int(spec[1]), int(spec[2])
cnt_loop = 0
for bk, v in b_pep_counts.items():
bc, bres = bk.split(":")
rnum = int(bres[1:])
if bc == lch and rlo <= rnum <= rhi:
cnt_loop += v
cdr_breakdown[loop_name] = cnt_loop
rec_cut: dict[str, Any] = {
"cutoff_A": cut_val,
"total_contact_pairs": tot,
"dq_alpha_pairs": n_a,
"dq_beta_pairs": n_b,
"peptide_pairs": n_p,
"peptide_share_pct": round(100.0 * n_p / tot, 2),
"dq_alpha_share_pct": round(100.0 * n_a / tot, 2),
"dq_beta_share_pct": round(100.0 * n_b / tot, 2),
"distinct_peptide_residues_contacted": len(pep_res_counts),
"max_single_pep_residue": max_res,
"max_single_pep_residue_pairs": max_cnt,
"max_single_pep_residue_share_pct": round(100.0 * max_cnt / n_p, 2) if n_p else 0.0,
}
if cdr_breakdown:
rec_cut["cdr_peptide_contact_pairs"] = cdr_breakdown
if "CDR_H3" in cdr_breakdown and n_p:
rec_cut["cdr_h3_share_of_peptide_contacts_pct"] = round(100.0 * cdr_breakdown["CDR_H3"] / n_p, 2)
cut_out[cut_lbl] = rec_cut
complex_results[key] = {
"pdb_id": entry["pdb_id"],
"source_cif_sha256": entry["source_cif_sha256"],
"license": entry["license"],
"primary_pmid": entry["primary_pmid"],
"format": entry["format"],
"comparator_disclosure": entry["comparator_disclosure"],
"peptide_sequence_resolved": entry["peptide_sequence_resolved"],
"peptide_range": entry["peptide_range"],
"mhc_alpha_range": entry["mhc_alpha_range"],
"mhc_beta_range": entry["mhc_beta_range"],
"contacts_le_4p5A": cut_out["le_4p5A"],
"contacts_le_4p0A": cut_out["le_4p0A"],
}
require_cond(
complex_results["8W84_DONQ52_parent_DQ25_glia_a2"]["contacts_le_4p5A"]["peptide_pairs"] == 141
and complex_results["8W84_DONQ52_parent_DQ25_glia_a2"]["contacts_le_4p5A"]["total_contact_pairs"] == 341,
"8W84 coordinate contact check failed",
)
require_cond(
complex_results["6DFX_T1D3_TCR_DQ8_InsB_R3_copy1"]["contacts_le_4p5A"]["peptide_pairs"] == 102
and complex_results["6DFX_T1D3_TCR_DQ8_InsB_R3_copy1"]["contacts_le_4p5A"]["total_contact_pairs"] == 340,
"6DFX coordinate contact check failed",
)
require_cond(
complex_results["6XP6_3C11_Fab_DQ25_glia_a2_copy1"]["contacts_le_4p5A"]["peptide_pairs"] == 66
and complex_results["6XP6_3C11_Fab_DQ25_glia_a2_copy1"]["contacts_le_4p5A"]["total_contact_pairs"] == 298,
"6XP6 coordinate contact check failed",
)
require_cond(
complex_results["8VD2_ET650_4_TCR_DQ8_HIP"]["contacts_le_4p5A"]["peptide_pairs"] == 123
and complex_results["8VD2_ET650_4_TCR_DQ8_HIP"]["contacts_le_4p5A"]["total_contact_pairs"] == 398,
"8VD2 coordinate contact check failed",
)
u_entry = payload["unbound_comparators"]["8VDU_DQ8_HIP6_unbound_crest_copy1"]
mhc_atoms = u_entry["mhc_atoms"]
by_res: dict[int, list[list[Any]]] = collections.defaultdict(list)
for atom in u_entry["peptide_atoms"]:
by_res[int(atom[1])].append(atom)
crest_res: list[str] = []
buried_res: list[str] = []
c2_45 = 4.5 * 4.5
for rseq in sorted(by_res):
r_atoms = by_res[rseq]
aa = r_atoms[0][2]
n_mhc = 0
for _, _, _, _, px, py, pz in r_atoms:
for _, _, _, _, mx, my, mz in mhc_atoms:
dx, dy, dz = px - mx, py - my, pz - mz
if dx * dx + dy * dy + dz * dz <= c2_45:
n_mhc += 1
ratio = n_mhc / max(1, len(r_atoms))
if ratio >= 5.0:
buried_res.append(f"{aa}{rseq}")
else:
crest_res.append(f"{aa}{rseq}")
unbound_8vdu = {
"pdb_id": u_entry["pdb_id"],
"source_cif_sha256": u_entry["source_cif_sha256"],
"license": u_entry["license"],
"primary_pmid": u_entry["primary_pmid"],
"format": u_entry["format"],
"comparator_disclosure": u_entry["comparator_disclosure"],
"peptide_sequence_resolved": u_entry["peptide_sequence_resolved"],
"n_residues": len(by_res),
"tcr_facing_crest_residues": crest_res,
"mhc_buried_anchor_residues": buried_res,
}
return {
"coordinate_subset_relpath": "data/structures/rcsb_shield_interface_coords_v0.9.0.json",
"coordinate_subset_sha256": actual_sha,
"computation_mode": "DETERMINISTIC_3D_HEAVY_ATOM_COORDINATE_COUNTER_ZERO_HARDCODED_COUNTS",
"comparator_scope_note": (
"All five structures are deposited RCSB CC0-1.0 experimental comparator complexes (celiac Fabs or TCRs). "
"They define structural design benchmarks and do NOT establish mass, specificity, Fc silencing, or binding "
"affinity of the yet-to-be-expressed Foundry v2.0 bispecific Fab."
),
"complexes": complex_results,
"unbound_comparators": {"8VDU_DQ8_HIP6_unbound_crest_copy1": unbound_8vdu},
}
# ---------------------------------------------------------------------------
# PART A: Converged Periodic SHIELD PK, Mass-Conserving TMDD & >=15 uM Gate
# ---------------------------------------------------------------------------
def renkin_glomerular_sieving(rh_nm: float, r_pore_nm: float = 5.2, charge_cutoff_nm: float = 3.6) -> float:
if rh_nm >= charge_cutoff_nm:
return 0.0
lam = rh_nm / r_pore_nm
if lam >= 1.0:
return 0.0
steric = (1.0 - lam) ** 2
drag = 1.0 - 2.104 * lam + 2.09 * (lam ** 3) - 0.95 * (lam ** 5)
return max(0.0, min(1.0, steric * drag))
def free_ligand_ro(c_free_nM: float, kd_nM: float) -> float:
"""Single consistent free-ligand modeled receptor occupancy convention: C_free / (C_free + Kd)."""
if c_free_nM <= 0.0 or kd_nM <= 0.0:
return 0.0
return min(1.0, max(0.0, c_free_nM / (c_free_nM + kd_nM)))
def _solve_4x4_linear(A_in: list[list[float]], b_in: list[float]) -> list[float]:
A = [list(row) for row in A_in]
b = list(b_in)
for i in range(4):
piv = max(range(i, 4), key=lambda r: abs(A[r][i]))
require_cond(abs(A[piv][i]) > 1e-15, "Singular 4x4 periodic fixed-point matrix")
A[i], A[piv] = A[piv], A[i]
b[i], b[piv] = b[piv], b[i]
div = A[i][i]
for j in range(i, 4):
A[i][j] /= div
b[i] /= div
for r in range(4):
if r != i:
fac = A[r][i]
for j in range(i, 4):
A[r][j] -= fac * A[i][j]
b[r] -= fac * b[i]
return b
def simulate_linear_periodic_pk(
name: str,
mw_kda: float,
rh_eff_nm: float,
dose_mg: float,
tau_days: float,
route: str,
F_sc: float,
ka_per_day: float,
V1_L: float,
V2_L: float,
Q_L_per_day: float,
CL_L_per_day: float,
kp_dln: float,
k_ln_eq_per_day: float,
dt_days: float = 1.0 / 24.0,
conv_tol: float = 1e-10,
max_cycles: int = 500,
parameter_basis: str = "modeled_linear_pk_pending_nhp_human_pk",
) -> dict[str, Any]: