"""Per-residue interface of the 1:1 human growth hormone : receptor complex (1A22).

Used in content/guides/alanine-scanning-hotspots.mdx. For each receptor (chain B)
residue it reports the surface area lost on binding hGH (chain A) and the number
of heavy-atom contacts within 4 A. Waters and heteroatoms are removed; first model.
Buried area per residue = SASA of the receptor alone minus SASA in the complex
(Shrake-Rupley, 1.4 A probe, 960 points, Biopython).

    python -I hgh_interface.py <pdb-file>
"""
import copy
import sys

from Bio.PDB import NeighborSearch, PDBParser, ShrakeRupley
from Bio.PDB.Model import Model
from Bio.PDB.Structure import Structure

model = PDBParser(QUIET=True).get_structure("1A22", sys.argv[1])[0]
for ch in model:
    for r in list(ch):
        if r.id[0] != " ":
            ch.detach_child(r.id)


def sasa(chains):
    m = Model(0)
    for c in chains:
        m.add(copy.deepcopy(model[c]))
    s = Structure("x")
    s.add(m)
    ShrakeRupley(probe_radius=1.4, n_points=960).compute(s, level="R")
    return {(c.id, r.id[1]): r.sasa for c in m for r in c}


both = sasa(["A", "B"])
alone = sasa(["B"])
atoms_a = [a for a in model["A"].get_atoms()]
ns = NeighborSearch(atoms_a)
rows = []
for r in model["B"]:
    key = ("B", r.id[1])
    lost = alone[key] - both[key]
    n = sum(len(ns.search(a.coord, 4.0, "A")) for a in r)
    near = any(ns.search(a.coord, 4.0, "R") for a in r)
    rows.append((r.id[1], r.get_resname(), lost, n, near))
contact = [x for x in rows if x[4]]
print("receptor residues with a heavy atom within 4 A of hGH:", len(contact))
print("residues losing >=1 A2:", sum(1 for x in rows if x[2] >= 1))
tot = sum(x[2] for x in rows)
print("total buried (receptor side) A2: %.0f" % tot)
w = [x[2] for x in rows if x[0] in (304, 369)]
print("Trp104 + Trp169 buried A2: %.1f = %.1f%%" % (sum(w), 100 * sum(w) / tot))
rank = sorted(rows, key=lambda x: -x[2])
for i, x in enumerate(rank[:25], 1):
    print(i, x[1], x[0] - 200, "%.1f" % x[2], x[3])
# chain B is numbered with a +200 offset in 1A22 (Trp104 is B304, Trp169 is B369)
for pos in (243, 304, 306, 365, 369):
    i = [k for k, x in enumerate(rank, 1) if x[0] == pos][0]
    x = rank[i - 1]
    print("rank", i, x[1], x[0] - 200, "%.1f" % x[2], x[3])
