scripts/run_layer3_structural_binder_plane.py
Use this file in any AI chat (paste-only or attachment-capable):
Pinned raw file: https://openislet.org/files/gen-eb955f8266035aba/scripts/run_layer3_structural_binder_plane.py · SHA-256: a070de200dfefd3d…
chain = rec.get("auth_asym_id", rec.get("label_asym_id", ""))
identity = (chain, auth_seq_id, ins_code, atom_id)
if identity in identities:
raise ValueError(f"Duplicate selected atom identity in {cif_path}: {identity}")
identities.add(identity)
atoms.append({
"group": rec["group_PDB"], "atom_id": atom_id,
"element": rec.get("type_symbol", "C").upper(),
"comp_id": rec.get("auth_comp_id", rec.get("label_comp_id", "")),
"chain": chain, "seq_id": auth_seq_id, "label_seq_id": label_seq_id,
"ins_code": ins_code, "res_key": f"{auth_seq_id}{ins_code}",
"x": x, "y": y, "z": z, "b_iso": b_iso,
"alt_id": alt_id, "occupancy": occupancy,
})
if source_bytes is not None and not isinstance(source_bytes, bytes):
raise TypeError("mmCIF source_bytes must be an immutable bytes snapshot")
stream = (io.StringIO(source_bytes.decode("utf-8")) if source_bytes is not None
else cif_path.open("r", encoding="utf-8"))
with stream as f:
for raw_line in f:
line = raw_line.strip()
if line.startswith("_atom_site."):
if rows_started:
raise ValueError(f"Atom-site columns cannot change within coordinate rows: {cif_path}")
in_atom_loop = True
for token in line.split():
if not token.startswith("_atom_site."):
raise ValueError(f"Malformed atom-site column header in {cif_path}")
column = token.split(".", 1)[1]
if column in cols:
raise ValueError(f"Duplicate atom-site column in {cif_path}: {column}")
cols.append(column)
continue
if in_atom_loop:
if not line or line.startswith("#"):
continue
if line.startswith(("loop_", "_", "data_", "stop_")):
if pending:
raise ValueError(f"Incomplete atom row in {cif_path}")
if rows_started:
break
in_atom_loop = False
cols = []
continue
rows_started = True
for token in _MMCIF_TOKEN_RE.findall(line):
if token.startswith("#"):
break
if token.startswith(("'", '"')):
if len(token) < 2 or token[-1] != token[0]:
raise ValueError(f"Unterminated quoted atom-site value in {cif_path}")
token = token[1:-1]
pending.append(token)
while len(pending) >= len(cols):
rec = dict(zip(cols, pending[:len(cols)]))
del pending[:len(cols)]
if rec.get("group_PDB") not in {"ATOM", "HETATM"}:
raise ValueError(f"Invalid atom-site record group in {cif_path}")
_append_selected_atom(rec)
if pending:
raise ValueError(f"Incomplete atom row in {cif_path}")
if not atoms:
raise ValueError(f"Zero valid ATOM/HETATM records parsed from {cif_path}")
return atoms
def filter_polymer_atoms(
atoms: List[Dict[str, Any]],
chains: List[str],
seq_range: Optional[Tuple[int, int]] = None,
include_hetatm_peptides: bool = False,
require_all_chains: bool = True,
) -> List[Dict[str, Any]]:
chain_set = set(chains)
if not chain_set:
raise ValueError("chains list in filter_polymer_atoms cannot be empty")
out: List[Dict[str, Any]] = []
for a in atoms:
if a["chain"] not in chain_set:
continue
if a["comp_id"] == "HOH":
continue
if a["group"] != "ATOM" and not (include_hetatm_peptides and a["comp_id"] in {"PCA", "ACE"}):
continue
if seq_range is not None and not (seq_range[0] <= a["seq_id"] <= seq_range[1]):
continue
out.append(a)
if require_all_chains:
present_chains = {a["chain"] for a in out}
missing_chains = sorted(chain_set - present_chains)
if missing_chains:
raise ValueError(
f"Requested chains {sorted(chain_set)} not all present in structure (missing: {missing_chains}; found: {sorted(present_chains)})"
)
return out
def compute_interface_metrics(
atoms_a: List[Dict[str, Any]],
atoms_b: List[Dict[str, Any]],
heavy_cutoff: float = 4.5,
polar_cutoff: float = 3.5,
salt_bridge_cutoff: float = 4.0,
) -> Dict[str, Any]:
"""
Compute exact inter-chain heavy-atom, N/O polar proximity (<=3.5 A), and physiological pH-7.4
ionic salt-bridge (ARG/LYS vs ASP/GLU <=4.0 A) contact networks from experimental mmCIF coordinates,
separating unique residue-level contacts from atom-pair counts and separating histidine (pKa ~ 6.0)
protonation-dependent contacts (closing AUDIT-REF, AUDIT-REF, and 091).
"""
for name, value in (("heavy_cutoff", heavy_cutoff), ("polar_cutoff", polar_cutoff), ("salt_bridge_cutoff", salt_bridge_cutoff)):
if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value) or value <= 0:
raise ValueError(f"{name} must be a finite positive distance")
if max(polar_cutoff, salt_bridge_cutoff) > heavy_cutoff:
raise ValueError("Polar/salt-bridge cutoffs cannot exceed the enumerated heavy-atom cutoff")
backbone_atoms = {"N", "CA", "C", "O", "OXT"}
cationic_atoms_ph74 = {
("ARG", "NE"), ("ARG", "NH1"), ("ARG", "NH2"),
("LYS", "NZ"),
}
his_imidazole_atoms = {("HIS", "ND1"), ("HIS", "NE2")}
anionic_atoms = {
("ASP", "OD1"), ("ASP", "OD2"),
("GLU", "OE1"), ("GLU", "OE2"),
("ASJ", "OD1"), ("ASJ", "OD2"),
}
heavy_a = [a for a in atoms_a if a["element"] != "H"]
heavy_b = [b for b in atoms_b if b["element"] != "H"]
if not heavy_a or not heavy_b:
raise ValueError(f"Empty heavy-atom partner selection in compute_interface_metrics: len(a)={len(heavy_a)}, len(b)={len(heavy_b)}")
chains_a = {a["chain"] for a in heavy_a}
chains_b = {b["chain"] for b in heavy_b}
if chains_a & chains_b:
raise ValueError(f"Partner chain sets must be disjoint in compute_interface_metrics; overlap: {sorted(chains_a & chains_b)}")
coords_a = _finite_real_coordinates([[a["x"], a["y"], a["z"]] for a in heavy_a], "interface A")
coords_b = _finite_real_coordinates([[b["x"], b["y"], b["z"]] for b in heavy_b], "interface B")
with np.errstate(over="ignore", invalid="ignore"):
diff = coords_a[:, None, :] - coords_b[None, :, :]
dist_mat = np.hypot.reduce(diff, axis=-1)
if not np.all(np.isfinite(dist_mat)):
raise ValueError("Interface distance exceeds the finite numeric domain")
min_interatomic_dist = float(np.min(dist_mat))
clash_pairs_lt_2p0a = int(np.sum(dist_mat < 2.0))
heavy_idx_a, heavy_idx_b = np.where(dist_mat <= heavy_cutoff)
heavy_atom_pairs = int(len(heavy_idx_a))
contact_set_a = set(heavy_idx_a.tolist())
contact_set_b = set(heavy_idx_b.tolist())
contact_residues_a = sorted(
{(heavy_a[i]["chain"], heavy_a[i]["seq_id"], heavy_a[i]["ins_code"], heavy_a[i]["res_key"], heavy_a[i]["comp_id"]) for i in heavy_idx_a},
key=lambda t: (t[0], t[1], t[2]),
)
contact_residues_b = sorted(
{(heavy_b[j]["chain"], heavy_b[j]["seq_id"], heavy_b[j]["ins_code"], heavy_b[j]["res_key"], heavy_b[j]["comp_id"]) for j in heavy_idx_b},
key=lambda t: (t[0], t[1], t[2]),
)
residue_pair_min_dist: Dict[Tuple[str, int, str, str, str, str, int, str, str, str], float] = {}
polar_contacts: List[Dict[str, Any]] = []
unique_polar_res_pairs: set = set()
salt_bridges: List[Dict[str, Any]] = []
unique_salt_bridge_res_pairs: set = set()
his_anionic_pairs: List[Dict[str, Any]] = []
bb_bb = 0
bb_sc = 0
sc_sc = 0
for i, j in zip(heavy_idx_a.tolist(), heavy_idx_b.tolist()):
aa = heavy_a[i]
bb = heavy_b[j]
d = float(dist_mat[i, j])
rk = (
aa["chain"], aa["seq_id"], aa["ins_code"], aa["res_key"], aa["comp_id"],
bb["chain"], bb["seq_id"], bb["ins_code"], bb["res_key"], bb["comp_id"],
)
if rk not in residue_pair_min_dist or d < residue_pair_min_dist[rk]:
residue_pair_min_dist[rk] = d
if d <= salt_bridge_cutoff:
ka = (aa["comp_id"], aa["atom_id"])
kb = (bb["comp_id"], bb["atom_id"])
if (ka in cationic_atoms_ph74 and kb in anionic_atoms) or (ka in anionic_atoms and kb in cationic_atoms_ph74):
unique_salt_bridge_res_pairs.add((f"{aa['chain']}:{aa['comp_id']}{aa['res_key']}", f"{bb['chain']}:{bb['comp_id']}{bb['res_key']}"))
salt_bridges.append(
{
"partner_1": f"{aa['chain']}:{aa['comp_id']}{aa['res_key']}.{aa['atom_id']}",
"partner_2": f"{bb['chain']}:{bb['comp_id']}{bb['res_key']}.{bb['atom_id']}",
"distance_angstrom": round(d, 3),
}
)
elif (ka in his_imidazole_atoms and kb in anionic_atoms) or (ka in anionic_atoms and kb in his_imidazole_atoms):
his_anionic_pairs.append(
{
"partner_1": f"{aa['chain']}:{aa['comp_id']}{aa['res_key']}.{aa['atom_id']}",
"partner_2": f"{bb['chain']}:{bb['comp_id']}{bb['res_key']}.{bb['atom_id']}",
"distance_angstrom": round(d, 3),
"protonation_note": "Histidine (pKa ~ 6.0) requires local protonation for ionic salt-bridge formation at pH 7.4",
}
)
if d <= polar_cutoff and aa["element"] in POLAR_ELEMENTS and bb["element"] in POLAR_ELEMENTS:
unique_polar_res_pairs.add((f"{aa['chain']}:{aa['comp_id']}{aa['res_key']}", f"{bb['chain']}:{bb['comp_id']}{bb['res_key']}"))
in_bb_a = aa["atom_id"] in backbone_atoms
in_bb_b = bb["atom_id"] in backbone_atoms
if in_bb_a and in_bb_b:
bb_bb += 1
elif in_bb_a or in_bb_b:
bb_sc += 1
else:
sc_sc += 1
polar_contacts.append(
{
"partner_1": f"{aa['chain']}:{aa['comp_id']}{aa['res_key']}.{aa['atom_id']}",
"partner_2": f"{bb['chain']}:{bb['comp_id']}{bb['res_key']}.{bb['atom_id']}",
"distance_angstrom": round(d, 3),
}
)
polar_contacts.sort(key=lambda x: (x["distance_angstrom"], x["partner_1"], x["partner_2"]))
salt_bridges.sort(key=lambda x: (x["distance_angstrom"], x["partner_1"], x["partner_2"]))
sorted_res_pairs = sorted(residue_pair_min_dist.items(), key=lambda kv: (kv[1], kv[0]))
contact_b_a = [heavy_a[i]["b_iso"] for i in sorted(contact_set_a)]
contact_b_b = [heavy_b[j]["b_iso"] for j in sorted(contact_set_b)]
noncontact_b_a = [heavy_a[i]["b_iso"] for i in range(len(heavy_a)) if i not in contact_set_a]
mean_a, sd_a = _finite_population_moments(contact_b_a) if contact_b_a else (None, None)
mean_b, sd_b = _finite_population_moments(contact_b_b) if contact_b_b else (None, None)
noncontact_mean_a = _finite_population_moments(noncontact_b_a)[0] if noncontact_b_a else None
return {
"evidence_class": "computed_directly_from_experimental_mmcif_coordinates_distance_proximity_screen",
"interface_contact_deduplication_convention": {
"atom_pair_metrics": "heavy_atom_contact_pairs (<=4.5 A), polar_contact_atom_pairs (N/O/S <=3.5 A), and salt_bridge_atom_pairs (<=4.0 A) count all distinct inter-chain heavy-atom pairs meeting each distance cutoff.",
"residue_pair_metrics": "unique_residue_contact_pairs, unique_polar_proximity_residue_pairs, and unique_salt_bridge_residue_pairs_arg_lys_ph74 deduplicate atom contacts to one count per unique (chain_1, seq_id_1) <-> (chain_2, seq_id_2) residue pair using minimum interatomic distance.",
},
"partner_1_chains": sorted(chains_a),
"partner_2_chains": sorted(chains_b),
"heavy_atom_cutoff_angstrom": heavy_cutoff,
"polar_contact_cutoff_angstrom": polar_cutoff,
"salt_bridge_cutoff_angstrom": salt_bridge_cutoff,
"min_interatomic_distance_angstrom": round(min_interatomic_dist, 4),
"steric_clash_atom_pairs_lt_2p0A": clash_pairs_lt_2p0a,
"heavy_atom_contact_pairs": heavy_atom_pairs,
"unique_residue_contact_pairs": len(residue_pair_min_dist),
"polar_contact_atom_pairs": len(polar_contacts),
"unique_polar_proximity_residue_pairs": len(unique_polar_res_pairs),
"salt_bridge_atom_pairs": len(salt_bridges),
"strict_ph74_salt_bridge_atom_pairs": len(salt_bridges),