bindview 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. bindview/__init__.py +88 -0
  2. bindview/__main__.py +6 -0
  3. bindview/align.py +493 -0
  4. bindview/arrange.js +347 -0
  5. bindview/arrange.py +248 -0
  6. bindview/backends.py +290 -0
  7. bindview/basepairs.py +1711 -0
  8. bindview/chains.py +264 -0
  9. bindview/chem.py +57 -0
  10. bindview/clearance.py +123 -0
  11. bindview/cli.py +990 -0
  12. bindview/compare.py +1854 -0
  13. bindview/confidence.py +531 -0
  14. bindview/consensus.py +303 -0
  15. bindview/covalent.py +220 -0
  16. bindview/depict.py +790 -0
  17. bindview/detect.py +378 -0
  18. bindview/diagram.py +1891 -0
  19. bindview/distance_table.py +589 -0
  20. bindview/ensemble.py +787 -0
  21. bindview/errors.py +47 -0
  22. bindview/exposure.py +207 -0
  23. bindview/features.py +179 -0
  24. bindview/fingerprint.py +469 -0
  25. bindview/fragments.py +304 -0
  26. bindview/geometry.py +482 -0
  27. bindview/graph.py +611 -0
  28. bindview/graphbuild.py +431 -0
  29. bindview/interactions.py +418 -0
  30. bindview/interactive.py +334 -0
  31. bindview/interface.py +1329 -0
  32. bindview/ions.py +155 -0
  33. bindview/layout/__init__.py +15 -0
  34. bindview/layout/body.py +421 -0
  35. bindview/layout/engine.py +1084 -0
  36. bindview/layout/field.py +261 -0
  37. bindview/ligand.py +583 -0
  38. bindview/near.py +67 -0
  39. bindview/options.py +92 -0
  40. bindview/pae.py +991 -0
  41. bindview/peptide.py +610 -0
  42. bindview/plane.py +320 -0
  43. bindview/polymer.py +678 -0
  44. bindview/py.typed +0 -0
  45. bindview/report.py +1407 -0
  46. bindview/residues.py +296 -0
  47. bindview/resolve.py +493 -0
  48. bindview/scene.py +239 -0
  49. bindview/solvent.py +254 -0
  50. bindview/structure.py +1145 -0
  51. bindview/styles/__init__.py +2 -0
  52. bindview/styles/absence.py +180 -0
  53. bindview/styles/base.py +2128 -0
  54. bindview/styles/closeup.py +146 -0
  55. bindview/styles/detailed.py +690 -0
  56. bindview/styles/ligand_draw.py +289 -0
  57. bindview/styles/mixed.py +70 -0
  58. bindview/styles/polymer_draw.py +354 -0
  59. bindview/styles/rings.py +75 -0
  60. bindview/styles/schematic.py +311 -0
  61. bindview/styles/summary.py +147 -0
  62. bindview/svg.py +310 -0
  63. bindview/textmetrics.py +64 -0
  64. bindview/theme.py +317 -0
  65. bindview-0.1.0.dist-info/METADATA +270 -0
  66. bindview-0.1.0.dist-info/RECORD +70 -0
  67. bindview-0.1.0.dist-info/WHEEL +4 -0
  68. bindview-0.1.0.dist-info/entry_points.txt +2 -0
  69. bindview-0.1.0.dist-info/licenses/LICENSE +21 -0
  70. bindview-0.1.0.dist-info/licenses/NOTICE +48 -0
@@ -0,0 +1,589 @@
1
+ """A plain distance table of the contacts of a chain: of a peptide that is the ligand, or of an interface.
2
+
3
+ This is NOT an interaction analysis and must not be read as one. bindview analyses no interactions: a table
4
+ of contacts comes from the caller, or from PLIP behind :func:`bindview.detect_interactions`. This table is
5
+ for a structure whose ligand is a chain of its own, or in which two chains touch, when neither is at hand.
6
+ ``bindview report`` draws such a chain from it, and the call it prints is this module's. The criteria are
7
+ deliberately crude -- distances only, because a crystal structure has no hydrogens:
8
+
9
+ hydrogen bond N or O of the ligand within 3.5 A of N or O of the protein, at least
10
+ one of the two able to donate (by residue and atom name); none between
11
+ two atoms that both lie within 3.0 A of one metal atom of the structure:
12
+ the two hold that metal, which is why they are that near each other
13
+ salt bridge an atom of a cationic group within 4.0 A of an atom of an anionic group
14
+ hydrophobic contact two carbons, neither bonded to N or O, within 4.0 A; one per pair of
15
+ residues, the closest
16
+ ring stacking only with ``stacking=True``: an aromatic ring of each (Phe, Tyr, Trp, His,
17
+ a base), centres within 5.5 A, planes within 30 degrees of parallel or of
18
+ perpendicular, the centre of one within 2.0 A of the other's axis (the
19
+ criterion of :func:`ligand_contacts`); one per pair of residues, the
20
+ closest pair of rings. Two rings that stack then have no hydrophobic
21
+ contact between them, as PLIP has it.
22
+
23
+ No angles, no waters, and no row for a metal: a metal only takes away the hydrogen bond between two
24
+ atoms that hold it. The partners are the polymer residues of every other chain; which chain is the
25
+ ligand is said by the caller and never guessed.
26
+
27
+ from bindview import Diagram, read_structure
28
+ from bindview.distance_table import contact_table
29
+
30
+ model = read_structure("model.cif")
31
+ Diagram.from_structure(model, "chain:P", interactions=contact_table(model, "P"))
32
+
33
+ A ligand atom is named as bindview names it in a chain ligand: ``63/OE1`` is atom OE1 of residue 63.
34
+
35
+ :func:`ligand_contacts` is the table for a ligand that is one residue: a small molecule, a cofactor, an
36
+ ion. It goes by the positions of the heavy atoms and by what the ligand is (its rings, its charged
37
+ groups, which of its atoms carry a hydrogen), and so has what the chain table leaves out: a cation over a
38
+ ring, a halogen bond, a metal, and stacking without being asked. It places no hydrogen, so a hydrogen bond has no
39
+ angle, and it knows no water bridge. As in the chain table, two atoms that hold one metal (a sulfonamide's
40
+ nitrogen and a histidine's on one zinc) have no hydrogen bond between them. It is cruder than PLIP, whose
41
+ tables it was measured against, and is there for when PLIP is not: its numbers are in docs/reference.md.
42
+
43
+ from bindview import Diagram, read_structure
44
+ from bindview.distance_table import ligand_contacts
45
+
46
+ model = read_structure("model.cif")
47
+ Diagram.from_structure(model, "LIG_B", smiles=smiles, interactions=ligand_contacts(model, "LIG_B", smiles))
48
+ """
49
+
50
+ from __future__ import annotations
51
+
52
+ from typing import Any, Sequence
53
+
54
+ import numpy as np
55
+
56
+ from .errors import LigandNotFoundError
57
+ from .exposure import WATER_NAMES
58
+ from .near import distance_matrix, nearest_distance
59
+ from .structure import ResidueKey, Structure
60
+
61
+ __all__ = ["contact_table", "interface_contacts", "ligand_contacts", "as_tsv", "HBOND", "SALT", "GREASY", "COLUMNS",
62
+ "STACK", "STACK_ANGLE", "OFF_AXIS", "CATION", "HALOGEN", "HALOGEN_ANGLE", "HALOGEN_AT_ACCEPTOR", "METAL"]
63
+
64
+ HBOND, SALT, GREASY = 3.5, 4.0, 4.0
65
+ COLUMNS = ("interaction_type", "residue_number", "residue_name", "chain", "insertion_code", "protein_atom",
66
+ "ligand_atom", "distance", "angle", "ligand_is_donor", "protein_atoms", "ligand_atoms")
67
+
68
+ _DONORS = {"ARG": {"NE", "NH1", "NH2"}, "LYS": {"NZ"}, "HIS": {"ND1", "NE2"}, "ASN": {"ND2"}, "GLN": {"NE2"},
69
+ "TRP": {"NE1"}, "SER": {"OG"}, "THR": {"OG1"}, "TYR": {"OH"}}
70
+ _ACCEPTOR_N = {"HIS": {"ND1", "NE2"}}
71
+ _CATIONS = {"LYS": ("NZ",), "ARG": ("NE", "NH1", "NH2"), "HIS": ("ND1", "NE2")}
72
+ _ANIONS = {"ASP": ("OD1", "OD2"), "GLU": ("OE1", "OE2"), "PTR": ("O1P", "O2P", "O3P"), "SEP": ("O1P", "O2P", "O3P"),
73
+ "TPO": ("O1P", "O2P", "O3P"), "TYS": ("O1", "O2", "O3")}
74
+
75
+
76
+ def _donates(resname: str, atom: str) -> bool:
77
+ from .residues import can_donate, is_nucleotide
78
+
79
+ if is_nucleotide(resname):
80
+ return can_donate(resname, atom) is True
81
+ return (atom == "N" and resname != "PRO") or atom in _DONORS.get(resname, ())
82
+
83
+
84
+ def _accepts(resname: str, atom: str, element: str) -> bool:
85
+ from .residues import can_accept, is_nucleotide
86
+
87
+ if is_nucleotide(resname):
88
+ return can_accept(resname, atom, element) is True
89
+ return element == "O" or atom in _ACCEPTOR_N.get(resname, ())
90
+
91
+
92
+ def contact_table(structure: Structure, chain: str, partners: "Sequence[str] | None" = None, *,
93
+ stacking: bool = False) -> list[dict[str, object]]:
94
+ """The table for the polymer of ``chain`` as ligand; rows in a fixed order, ready for bindview.
95
+
96
+ ``partners`` restricts the other side to those chains (an interface between two participants);
97
+ by default it is every other chain. The chain may be of any length here. ``stacking`` adds the rings
98
+ that stack, one row for a pair of residues (see the module); left out, the table has no such row.
99
+ Where the structure has a metal, an atom of the chain and an atom of a partner that both lie within
100
+ ``METAL`` (3.0 A) of it have no hydrogen bond between them.
101
+ """
102
+ from .residues import aromatic_rings, canonical_atom, is_nucleotide
103
+
104
+ residues = structure.polymer_residues(chain)
105
+ if not residues:
106
+ chains = sorted({a.chain for a in structure.atoms})
107
+ if chain not in chains:
108
+ raise LigandNotFoundError(f"there is no chain {chain!r} in {structure.source or 'the structure'}: its chains "
109
+ f"are {', '.join(repr(c) for c in chains) or 'none'}")
110
+ raise LigandNotFoundError(f"chain {chain!r} of {structure.source or 'the structure'} has no residue of a "
111
+ f"protein or a nucleic acid: this table is of a chain of residues, and "
112
+ f"ligand_contacts is the one of a ligand that is one residue")
113
+ if partners is not None:
114
+ chains = sorted({a.chain for a in structure.atoms})
115
+ absent = [p for p in partners if p not in chains]
116
+ if absent: # (no rows would read as: the two do not touch)
117
+ raise LigandNotFoundError(f"there is no chain {absent[0]!r} in {structure.source or 'the structure'} to be "
118
+ f"a partner of chain {chain!r}: its chains are "
119
+ f"{', '.join(repr(c) for c in chains)}")
120
+ st, key, given, _ = structure.with_residues_as_ligand(residues)
121
+ comp = {name: res.name.upper() for res in given for name in res.atoms}
122
+ number = {name: res.number for res in given for name in res.atoms}
123
+ lig = [a for a in st.residue_atoms(key) if a.element not in ("H", "D")]
124
+ env = [a for a in st.atoms if a.residue != key and a.element not in ("H", "D") and a.resname.upper() not in WATER_NAMES]
125
+ # The residues of the other side are those of their chains' polymers, as the chain's own are: a residue
126
+ # without N, CA or C, a cap and a modified residue count from either side, and so do the two ends of a chain.
127
+ polymer: set[ResidueKey] = set()
128
+ ends: dict[ResidueKey, str] = {}
129
+ for side in sorted({k.chain for k in st.residues() if k != key and k.chain != chain}):
130
+ if partners is not None and side not in partners:
131
+ continue
132
+ of = st.polymer_residues(side)
133
+ polymer.update(of)
134
+ amino = [k for k in of if {"N", "CA", "C"} <= {a.name for a in st.residue_atoms(k)}]
135
+ if amino:
136
+ if amino[0] == of[0]: # (no cap before the first residue)
137
+ ends[amino[0]] = "N"
138
+ if st.atom_by_name(amino[-1], "OXT") is not None:
139
+ ends[amino[-1]] = "C"
140
+ env = [a for a in env if a.residue in polymer]
141
+ if not env:
142
+ return []
143
+ lxyz = np.array([a.xyz for a in lig], dtype=float)
144
+ exyz = np.array([a.xyz for a in env], dtype=float)
145
+ reach = nearest_distance(exyz, lxyz) # of each atom around: to the nearest atom of the chain
146
+ # Rings: two whose centres are within STACK have atoms within STACK + 3 A of each other, whatever their tilt.
147
+ ringside = [env[i] for i in np.nonzero(reach <= STACK + 3.0)[0]] if stacking else []
148
+ near = np.nonzero(reach < 4.6)[0]
149
+ env = [env[i] for i in near]
150
+ exyz = exyz[near]
151
+ dist = distance_matrix(lxyz, exyz) # (ligand, protein)
152
+ on_one_metal = _on_one_metal(_metals_at(st, lxyz), lxyz, exyz)
153
+ polar = np.array([a.xyz for a in st.atoms if a.element in ("N", "O")], dtype=float)
154
+
155
+ def greasy(atom) -> bool:
156
+ return atom.element == "C" and not (np.linalg.norm(polar - np.array(atom.xyz), axis=1) < 1.7).any()
157
+
158
+ def local(name: str) -> str:
159
+ return name.split("/", 1)[1]
160
+
161
+ first, last = given[0], given[-1]
162
+ capped = any(res.name.upper() == "ACE" for res in given)
163
+
164
+ def charge_group(resname: str, atom: str, lig_name: str | None = None,
165
+ residue: "ResidueKey | None" = None) -> tuple[str, tuple[str, ...]] | None:
166
+ for table, sign in ((_CATIONS, "+"), (_ANIONS, "-")):
167
+ if atom in table.get(resname, ()):
168
+ return sign, table[resname]
169
+ if is_nucleotide(resname) and atom in ("OP1", "OP2", "O1P", "O2P"):
170
+ return "-", ("OP1", "OP2", "O1P", "O2P") # the phosphate, as the file names its oxygens
171
+ if lig_name is not None:
172
+ if atom in ("O", "OXT") and lig_name in last.atoms and any(local(n) == "OXT" for n in last.atoms):
173
+ return "-", ("O", "OXT")
174
+ if atom == "N" and lig_name in first.atoms and not capped and comp[lig_name] != "PRO":
175
+ return "+", ("N",)
176
+ end = ends.get(residue) if residue is not None else None
177
+ if end == "C" and atom in ("O", "OXT"):
178
+ return "-", ("O", "OXT")
179
+ if end == "N" and atom == "N" and resname != "PRO":
180
+ return "+", ("N",)
181
+ return None
182
+
183
+ rows: list[dict[str, object]] = []
184
+ salted: set[tuple[int, int]] = set()
185
+ bridges: dict[tuple, tuple[float, dict[str, object]]] = {}
186
+ for i, a in enumerate(lig):
187
+ ga = charge_group(comp[a.name], local(a.name), a.name)
188
+ if ga is None:
189
+ continue
190
+ for j, b in enumerate(env):
191
+ gb = charge_group(b.resname, b.name, residue=b.residue)
192
+ if gb is None or gb[0] == ga[0] or dist[i, j] > SALT:
193
+ continue
194
+ salted.add((i, j))
195
+ prefix = a.name.split("/", 1)[0] + "/"
196
+ mine = tuple(prefix + n for n in ga[1] if any(x.name == prefix + n for x in lig))
197
+ theirs = tuple(n for n in gb[1] if st.atom_by_name(b.residue, n) is not None)
198
+ ident = (b.residue, mine)
199
+ row = {"interaction_type": "saltbridge", "residue_number": b.resnum, "residue_name": b.resname,
200
+ "chain": b.chain, "insertion_code": b.icode, "protein_atom": "", "ligand_atom": "",
201
+ "distance": round(float(dist[i, j]), 2), "ligand_is_donor": "",
202
+ "protein_atoms": ",".join(theirs), "ligand_atoms": ",".join(mine)}
203
+ if ident not in bridges or dist[i, j] < bridges[ident][0]:
204
+ bridges[ident] = (float(dist[i, j]), row)
205
+ rows.extend(row for _, row in bridges.values())
206
+ for i, a in enumerate(lig):
207
+ if a.element not in ("N", "O"):
208
+ continue
209
+ for j, b in enumerate(env):
210
+ if b.element not in ("N", "O") or dist[i, j] > HBOND or (i, j) in salted or (i, j) in on_one_metal:
211
+ continue
212
+ la, pa = local(a.name), b.name
213
+ lig_d, lig_a = _donates(comp[a.name], la), _accepts(comp[a.name], la, a.element)
214
+ pro_d, pro_a = _donates(b.resname, pa), _accepts(b.resname, pa, b.element)
215
+ one, other = lig_d and pro_a, pro_d and lig_a
216
+ if not (one or other):
217
+ continue
218
+ rows.append({"interaction_type": "hbond", "residue_number": b.resnum, "residue_name": b.resname,
219
+ "chain": b.chain, "insertion_code": b.icode, "protein_atom": pa, "ligand_atom": a.name,
220
+ "distance": round(float(dist[i, j]), 2),
221
+ # No direction where both could donate, or where a histidine ring nitrogen takes
222
+ # part: which of its two nitrogens carries the hydrogen a crystal structure does not say.
223
+ "ligand_is_donor": "" if (one and other) or "HIS" in (
224
+ comp[a.name] if la in ("ND1", "NE2") else "", b.resname if pa in ("ND1", "NE2") else "")
225
+ else str(bool(one)),
226
+ "protein_atoms": "", "ligand_atoms": ""})
227
+ # Rings that stack, when asked for: of a pair of residues, the two rings whose centres are closest.
228
+ stacked: dict[tuple[ResidueKey, str], tuple[set[str], set[str]]] = {} # two residues -> the atoms of their rings
229
+ if stacking:
230
+ by_name = {a.name: a for a in lig}
231
+ chain_rings: list[tuple[str, list[str], np.ndarray, np.ndarray]] = []
232
+ for res in given:
233
+ here = {canonical_atom(res.name.upper(), local(n)): n for n in res.atoms if n in by_name}
234
+ for ring in aromatic_rings(res.name.upper()):
235
+ if all(r in here for r in ring):
236
+ members = [here[r] for r in ring]
237
+ centre, normal = _plane(np.array([by_name[n].xyz for n in members], dtype=float))
238
+ chain_rings.append((res.number, members, centre, normal))
239
+ grouped: dict[ResidueKey, list[Any]] = {}
240
+ for b in ringside:
241
+ grouped.setdefault(b.residue, []).append(b)
242
+ partner_rings: list[tuple[ResidueKey, str, list[str], np.ndarray, np.ndarray]] = []
243
+ for res_key, atoms in grouped.items():
244
+ there = {canonical_atom(atoms[0].resname, b.name): b for b in atoms}
245
+ for ring in aromatic_rings(atoms[0].resname):
246
+ if all(r in there for r in ring):
247
+ centre, normal = _plane(np.array([there[r].xyz for r in ring], dtype=float))
248
+ partner_rings.append((res_key, atoms[0].resname, [there[r].name for r in ring], centre, normal))
249
+ best: dict[tuple[ResidueKey, str], tuple[float, dict[str, object]]] = {}
250
+ for res_number, members, c1, n1 in chain_rings:
251
+ for res_key, resname, others, c2, n2 in partner_rings:
252
+ stack = _stacks(c1, n1, c2, n2)
253
+ if stack is None:
254
+ continue
255
+ both = (res_key, res_number)
256
+ stacked.setdefault(both, (set(), set()))[0].update(members)
257
+ stacked[both][1].update(others)
258
+ row = {"interaction_type": "pi_stacking", "residue_number": res_key.number, "residue_name": resname,
259
+ "chain": res_key.chain, "insertion_code": res_key.icode, "protein_atom": "", "ligand_atom": "",
260
+ "distance": round(stack[0], 2), "ligand_is_donor": "", "protein_atoms": ",".join(others),
261
+ "ligand_atoms": ",".join(members), "angle": round(stack[1], 2)}
262
+ if both not in best or stack[0] < best[both][0]:
263
+ best[both] = (stack[0], row)
264
+ rows.extend(row for _, row in best.values())
265
+ closest: dict[tuple, tuple[float, dict[str, object]]] = {}
266
+ lig_greasy = [greasy(a) for a in lig]
267
+ env_greasy = [greasy(b) for b in env]
268
+ for i, a in enumerate(lig):
269
+ if not lig_greasy[i]:
270
+ continue
271
+ for j, b in enumerate(env):
272
+ if not env_greasy[j] or dist[i, j] > GREASY:
273
+ continue
274
+ pair = (b.residue, number[a.name])
275
+ if pair in stacked and a.name in stacked[pair][0] and b.name in stacked[pair][1]:
276
+ continue # two rings that stack: no hydrophobic contact between them
277
+ row = {"interaction_type": "hydrophobic", "residue_number": b.resnum, "residue_name": b.resname,
278
+ "chain": b.chain, "insertion_code": b.icode, "protein_atom": b.name, "ligand_atom": a.name,
279
+ "distance": round(float(dist[i, j]), 2), "ligand_is_donor": "", "protein_atoms": "",
280
+ "ligand_atoms": ""}
281
+ if pair not in closest or dist[i, j] < closest[pair][0]:
282
+ closest[pair] = (float(dist[i, j]), row)
283
+ rows.extend(row for _, row in closest.values())
284
+ for row in rows:
285
+ named = str(row["ligand_atom"]) or str(row["ligand_atoms"]).split(",")[0]
286
+ row["_ligand_residue_name"] = comp[named] # not a column of the table: for interface_contacts
287
+ order = {"saltbridge": 0, "hbond": 1, "pi_stacking": 2, "hydrophobic": 3}
288
+ rows.sort(key=lambda r: (order[str(r["interaction_type"])], str(r["chain"]), int(str(r["residue_number"])),
289
+ str(r["ligand_atom"]) or str(r["ligand_atoms"]), str(r["protein_atom"])))
290
+ return rows
291
+
292
+
293
+ def interface_contacts(structure: Structure, chains_a: "Sequence[str]", chains_b: "Sequence[str]", *,
294
+ stacking: bool = False) -> list:
295
+ """The same plain table for an interface between two sets of chains, as
296
+ :class:`bindview.interface.InterfaceContact` records with side ``a`` in ``chains_a``. ``stacking`` as
297
+ for :func:`contact_table`."""
298
+ import re
299
+
300
+ from .interactions import InteractionType
301
+ from .interface import InterfaceContact
302
+
303
+ def split(name: str) -> tuple[int, str, str]:
304
+ m = re.fullmatch(r"(-?\d+)([A-Za-z]?)/(.+)", name)
305
+ assert m, name
306
+ return int(m.group(1)), m.group(2), m.group(3)
307
+
308
+ out = []
309
+ for chain in chains_a:
310
+ for row in contact_table(structure, chain, partners=chains_b, stacking=stacking):
311
+ mine = [split(n) for n in (str(row["ligand_atoms"]).split(",") if row["ligand_atoms"]
312
+ else [str(row["ligand_atom"])])]
313
+ theirs = tuple(str(row["protein_atoms"]).split(",")) if row["protein_atoms"] else (str(row["protein_atom"]),)
314
+ donor = {"True": True, "False": False}.get(str(row["ligand_is_donor"]))
315
+ out.append(InterfaceContact(
316
+ type=InteractionType(str(row["interaction_type"])), chain_a=chain, number_a=mine[0][0], icode_a=mine[0][1],
317
+ resname_a=str(row["_ligand_residue_name"]), atoms_a=tuple(m[2] for m in mine),
318
+ chain_b=str(row["chain"]), number_b=int(str(row["residue_number"])),
319
+ icode_b=str(row["insertion_code"]), resname_b=str(row["residue_name"]), atoms_b=theirs,
320
+ distance=float(str(row["distance"])), a_is_donor=donor,
321
+ angle=float(str(row["angle"])) if "angle" in row else None))
322
+ return sorted(out, key=lambda c: c.sort_key)
323
+
324
+
325
+ # ---------------------------------------------------------------------------
326
+ # A ligand that is one residue
327
+ # ---------------------------------------------------------------------------
328
+
329
+ #: Ring to ring, the deviation of two planes from parallel or from perpendicular, and how far a centre
330
+ #: may lie off the other ring's axis; a cation over a ring; a halogen and its angle at the halogen; a
331
+ #: metal. Angstrom and degrees: the published defaults of PLIP (Salentin et al., Nucleic Acids Res. 2015).
332
+ STACK, STACK_ANGLE, OFF_AXIS, CATION, HALOGEN, HALOGEN_ANGLE, METAL = 5.5, 30.0, 2.0, 6.0, 4.0, 135.0, 3.0
333
+ HALOGEN_AT_ACCEPTOR = (90.0, 150.0) # the angle at the acceptor, between the halogen and the atom it is bound to
334
+ _REACH = 8.0 # residues with an atom this near are looked at
335
+ _ORDER = {"saltbridge": 0, "hbond": 1, "pi_stacking": 2, "pi_cation": 3, "halogen": 4, "metal": 5, "hydrophobic": 6}
336
+
337
+
338
+ def _plane(points: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
339
+ """The centre of a ring and the unit normal of its plane."""
340
+ centre = points.mean(axis=0)
341
+ return centre, np.linalg.svd(points - centre)[2][-1]
342
+
343
+
344
+ def _off_axis(point: np.ndarray, centre: np.ndarray, normal: np.ndarray) -> float:
345
+ """How far a point lies from the axis of a ring: the line through its centre along its normal."""
346
+ d = point - centre
347
+ return float(np.sqrt(max(float(d @ d) - float(d @ normal) ** 2, 0.0)))
348
+
349
+
350
+ def _angle(a: np.ndarray, b: np.ndarray, c: np.ndarray) -> float:
351
+ """The angle at ``b`` between ``a`` and ``c``, in degrees."""
352
+ u, v = a - b, c - b
353
+ return float(np.degrees(np.arccos(np.clip(float(u @ v) / float(np.linalg.norm(u) * np.linalg.norm(v)), -1.0, 1.0))))
354
+
355
+
356
+ def _tilt(n1: np.ndarray, n2: np.ndarray) -> float:
357
+ """The angle between two planes, 0 to 90 degrees."""
358
+ return float(np.degrees(np.arccos(min(1.0, abs(float(n1 @ n2))))))
359
+
360
+
361
+ def _stacks(c1: np.ndarray, n1: np.ndarray, c2: np.ndarray, n2: np.ndarray) -> "tuple[float, float] | None":
362
+ """Do two rings stack, by their centres and normals? Their distance and the angle between their planes
363
+ if they do: centres within STACK, planes within STACK_ANGLE of parallel or of perpendicular, and the
364
+ centre of one within OFF_AXIS of the other's axis (the smaller of the two). Both tables ask this."""
365
+ apart = float(np.linalg.norm(c1 - c2))
366
+ tilt = _tilt(n1, n2)
367
+ off = min(_off_axis(c1, c2, n2), _off_axis(c2, c1, n1))
368
+ if apart <= STACK and off <= OFF_AXIS and (tilt <= STACK_ANGLE or tilt >= 90.0 - STACK_ANGLE):
369
+ return apart, tilt
370
+ return None
371
+
372
+
373
+ def _metals_at(structure: Structure, xyz: np.ndarray) -> np.ndarray:
374
+ """The positions of the metal atoms of the structure that have one of the atoms at ``xyz`` within METAL."""
375
+ from .chem import is_metal
376
+
377
+ at = np.array([a.xyz for a in structure.atoms if is_metal(a.element.capitalize())], dtype=float).reshape(-1, 3)
378
+ return at[[bool((np.linalg.norm(xyz - m, axis=1) <= METAL).any()) for m in at]]
379
+
380
+
381
+ def _on_one_metal(metals: np.ndarray, first: np.ndarray, second: np.ndarray) -> set[tuple[int, int]]:
382
+ """The pairs (an atom of ``first``, an atom of ``second``) that both lie within METAL of one of the metal
383
+ atoms at ``metals``. Two such atoms are the metal's: they are about 3 A apart because it is between them,
384
+ and that is no hydrogen bond. Both tables ask this."""
385
+ pairs: set[tuple[int, int]] = set()
386
+ for m in metals:
387
+ mine = np.nonzero(np.linalg.norm(first - m, axis=1) <= METAL)[0]
388
+ theirs = np.nonzero(np.linalg.norm(second - m, axis=1) <= METAL)[0]
389
+ pairs.update((int(i), int(j)) for i in mine for j in theirs)
390
+ return pairs
391
+
392
+
393
+ def ligand_contacts(structure: Structure, ligand: "str | ResidueKey | tuple[str, int]", smiles: "str | None" = None,
394
+ ionize_acids: bool = True) -> list[dict[str, object]]:
395
+ """The table for a ligand that is one residue; rows in a fixed order, ready for bindview.
396
+
397
+ ``smiles`` gives the ligand its bond orders, as it does for the diagram; left out, the file's own
398
+ SMILES is used where it has one. Without bond orders and without hydrogens in the file the ligand
399
+ has no rings that are known to be aromatic and no hydrogens that are known: every N and O may then
400
+ donate or accept, and the table has no stacking and fewer salt bridges.
401
+
402
+ An atom of the ligand and an atom of a residue that both lie within ``METAL`` (3.0 A) of one metal atom
403
+ have no hydrogen bond between them, however near they are: both hold that metal, be it an ion beside the
404
+ ligand, an atom of another residue (a haem's iron) or an atom of the ligand itself.
405
+ """
406
+ from rdkit import Chem
407
+
408
+ from .chem import HALOGENS, is_metal
409
+ from .features import _is_amide_like, perceive_charged_groups, perceive_metals, perceive_rings
410
+ from .ligand import build_ligand
411
+ from .residues import (aromatic_rings, can_accept, can_donate, canonical_atom, charged_groups, is_nucleotide,
412
+ template_for)
413
+
414
+ key = ligand if isinstance(ligand, ResidueKey) else structure.select_ligand(ligand)
415
+ if smiles is None:
416
+ smiles = structure.chem_comp_smiles.get(structure.residue_name(key))
417
+ lig = build_ligand(structure.residue_atoms(key), smiles, ionize_acids=ionize_acids)
418
+ mol: Chem.Mol = lig.mol
419
+ xyz = np.asarray(lig.coords3d, dtype=float).reshape(-1, 3)
420
+ known = lig.bond_source != "connectivity"
421
+ symbol = [a.GetSymbol() for a in mol.GetAtoms()]
422
+
423
+ # -- the surroundings: residues the library has a template for, and metal ions --------------
424
+ partners: list[tuple[ResidueKey, str, list[Any]]] = []
425
+ for k in structure.residues():
426
+ if k == key:
427
+ continue
428
+ name = structure.residue_name(k)
429
+ heavy = [a for a in structure.residue_atoms(k) if a.element not in ("H", "D")]
430
+ if not heavy or name.upper() in WATER_NAMES:
431
+ continue
432
+ ion = len(heavy) == 1 and is_metal(heavy[0].element.capitalize())
433
+ if template_for(name) is None and not ion:
434
+ continue
435
+ at = np.array([a.xyz for a in heavy], dtype=float)
436
+ if np.linalg.norm(at[:, None, :] - xyz[None, :, :], axis=2).min() <= _REACH:
437
+ partners.append((k, name, heavy))
438
+ polar = np.array([a.xyz for a in structure.atoms if a.element in ("N", "O")], dtype=float).reshape(-1, 3)
439
+
440
+ def greasy(atom: Any) -> bool:
441
+ return atom.element == "C" and not (len(polar) and (np.linalg.norm(polar - np.array(atom.xyz), axis=1) < 1.7).any())
442
+
443
+ def row(kind: str, k: ResidueKey, name: str, distance: float, **more: object) -> dict[str, object]:
444
+ out: dict[str, object] = {
445
+ "interaction_type": kind, "residue_number": k.number, "residue_name": name, "chain": k.chain,
446
+ "insertion_code": k.icode, "protein_atom": "", "ligand_atom": "", "distance": round(distance, 2),
447
+ "ligand_is_donor": "", "protein_atoms": "", "ligand_atoms": ""}
448
+ out.update(more)
449
+ return out
450
+
451
+ def names(indices: Sequence[int]) -> str:
452
+ return ",".join(lig.names[i] for i in indices)
453
+
454
+ # -- what the ligand is ------------------------------------------------------------------
455
+ def donates(i: int) -> bool:
456
+ return not known or mol.GetAtomWithIdx(i).GetTotalNumHs() > 0
457
+
458
+ def accepts(i: int) -> bool:
459
+ atom = mol.GetAtomWithIdx(i)
460
+ if not known or symbol[i] == "O":
461
+ return True
462
+ if symbol[i] != "N" or atom.GetTotalNumHs() > 0 or atom.GetFormalCharge() > 0:
463
+ return False
464
+ return atom.GetDegree() == 2 if atom.GetIsAromatic() else not _is_amide_like(atom)
465
+
466
+ safe = ("carboxylate", "guanidinium", "phosphate", "sulfonate") # known from the connectivity alone
467
+ groups = [g for g in perceive_charged_groups(lig)
468
+ if g.kind != "metal" and (g.kind == "anion" or g.rank <= 1) and (known or g.kind in safe)]
469
+ # A nitrogen that carries the charge of a guanidinium is a group by itself too: the larger one counts.
470
+ groups = [g for g in groups if not any(set(g.atoms) < set(h.atoms) and g.charge * h.charge > 0 for h in groups)]
471
+ bearing = {id(g): ([i for i in g.atoms if symbol[i] in ("N", "O")] or list(g.atoms)) for g in groups}
472
+ rings = [(g.atoms, *_plane(xyz[list(g.atoms)])) for g in perceive_rings(lig) if g.rank == 0] if known else []
473
+ metals = perceive_metals(lig)
474
+ metals_at = _metals_at(structure, xyz) # the ligand's own and those beside it, where it lies on one
475
+
476
+ rows: list[dict[str, object]] = []
477
+ for k, name, heavy in partners:
478
+ salted: set[tuple[int, int]] = set() # (atom of the ligand, atom of this residue)
479
+ at = np.array([a.xyz for a in heavy], dtype=float)
480
+ dist = np.linalg.norm(xyz[:, None, :] - at[None, :, :], axis=2) # (ligand, residue)
481
+ by_name = {canonical_atom(name, a.name): j for j, a in enumerate(heavy)}
482
+ given = {canonical_atom(name, a.name): a.name for a in heavy}
483
+ if len(heavy) == 1 and is_metal(heavy[0].element.capitalize()): # 7: a metal that is a residue
484
+ near = [i for i in range(len(xyz)) if symbol[i] in ("N", "O", "S") and dist[i, 0] <= METAL]
485
+ rows.extend(row("metal", k, name, float(dist[i, 0]), protein_atom=heavy[0].name, ligand_atom=lig.names[i])
486
+ for i in near)
487
+ continue
488
+ # 2: salt bridges, an atom of one group to an atom of the other
489
+ res_groups = []
490
+ for sign, wanted in charged_groups(name):
491
+ there = [n for n in wanted if canonical_atom(name, n) in by_name]
492
+ ends = [by_name[canonical_atom(name, n)] for n in there if heavy[by_name[canonical_atom(name, n)]].element in ("N", "O")]
493
+ if ends:
494
+ res_groups.append((sign, list(dict.fromkeys(given[canonical_atom(name, n)] for n in there)),
495
+ list(dict.fromkeys(ends))))
496
+ for g in groups:
497
+ for sign, members, ends in res_groups:
498
+ if sign * g.charge >= 0:
499
+ continue
500
+ sub = dist[np.ix_(bearing[id(g)], ends)]
501
+ if sub.min() > SALT:
502
+ continue
503
+ salted.update((i, j) for i in bearing[id(g)] for j in ends)
504
+ rows.append(row("saltbridge", k, name, float(sub.min()), protein_atoms=",".join(members),
505
+ ligand_atoms=names(g.atoms)))
506
+ # 1: hydrogen bonds between N and O, but not between two atoms on one metal
507
+ on_one_metal = _on_one_metal(metals_at, xyz, at)
508
+ for i in range(len(xyz)):
509
+ if symbol[i] not in ("N", "O"):
510
+ continue
511
+ for j, b in enumerate(heavy):
512
+ if b.element not in ("N", "O") or dist[i, j] > HBOND or (i, j) in salted or (i, j) in on_one_metal:
513
+ continue
514
+ gives, takes = can_donate(name, b.name), can_accept(name, b.name, b.element)
515
+ one = donates(i) and takes is not False # the ligand donates
516
+ other = gives is not False and accepts(i) # the residue donates
517
+ if not (one or other):
518
+ continue
519
+ rows.append(row("hbond", k, name, float(dist[i, j]), protein_atom=b.name, ligand_atom=lig.names[i],
520
+ ligand_is_donor="" if one and other else str(bool(one))))
521
+ # 4 and 5: rings
522
+ res_rings = []
523
+ for ring in aromatic_rings(name):
524
+ if all(n in by_name for n in ring):
525
+ res_rings.append(([given[n] for n in ring], *_plane(at[[by_name[n] for n in ring]])))
526
+ for atoms, centre, normal in rings:
527
+ for members, c2, n2 in res_rings:
528
+ stack = _stacks(centre, normal, c2, n2)
529
+ if stack is not None:
530
+ rows.append(row("pi_stacking", k, name, stack[0], protein_atoms=",".join(members),
531
+ ligand_atoms=names(atoms), angle=round(stack[1], 2)))
532
+ for sign, members, ends in res_groups:
533
+ if sign < 0 or is_nucleotide(name):
534
+ continue
535
+ centre2 = at[ends].mean(axis=0)
536
+ apart = float(np.linalg.norm(centre - centre2))
537
+ if apart <= CATION and _off_axis(centre2, centre, normal) <= OFF_AXIS:
538
+ rows.append(row("pi_cation", k, name, apart, protein_atoms=",".join(members),
539
+ ligand_atoms=names(atoms)))
540
+ for g in groups:
541
+ if g.charge <= 0:
542
+ continue
543
+ centre2 = g.center3d(xyz)
544
+ for members, c2, n2 in res_rings:
545
+ apart = float(np.linalg.norm(centre2 - c2))
546
+ if apart <= CATION and _off_axis(centre2, c2, n2) <= OFF_AXIS:
547
+ rows.append(row("pi_cation", k, name, apart, protein_atoms=",".join(members),
548
+ ligand_atoms=names(g.atoms)))
549
+ # 6: a halogen on a carbon, and what it points at
550
+ for i in range(len(xyz)):
551
+ if symbol[i] not in HALOGENS:
552
+ continue
553
+ carbons = [n.GetIdx() for n in mol.GetAtomWithIdx(i).GetNeighbors() if n.GetSymbol() == "C"]
554
+ best: tuple[float, int] | None = None
555
+ for j, b in enumerate(heavy):
556
+ if b.element not in ("N", "O", "S") or dist[i, j] > HALOGEN or not carbons:
557
+ continue
558
+ if _angle(xyz[carbons[0]], xyz[i], at[j]) < HALOGEN_ANGLE:
559
+ continue
560
+ bound = [m for m in range(len(heavy)) if m != j and np.linalg.norm(at[m] - at[j]) < 1.9]
561
+ if not any(HALOGEN_AT_ACCEPTOR[0] <= _angle(xyz[i], at[j], at[m]) <= HALOGEN_AT_ACCEPTOR[1] for m in bound):
562
+ continue
563
+ if best is None or dist[i, j] < best[0]:
564
+ best = (float(dist[i, j]), j)
565
+ if best is not None:
566
+ rows.append(row("halogen", k, name, best[0], protein_atom=heavy[best[1]].name, ligand_atom=lig.names[i]))
567
+ # 7: a metal of the ligand
568
+ for i in metals:
569
+ rows.extend(row("metal", k, name, float(dist[i, j]), protein_atom=b.name, ligand_atom=lig.names[i])
570
+ for j, b in enumerate(heavy) if b.element in ("N", "O", "S") and dist[i, j] <= METAL)
571
+ # 3: carbon to carbon, the closest pair of a residue
572
+ mine = [i for i in range(len(xyz)) if symbol[i] == "C"
573
+ and not any(n.GetSymbol() in ("N", "O") for n in mol.GetAtomWithIdx(i).GetNeighbors())]
574
+ theirs = [j for j, b in enumerate(heavy) if greasy(b)]
575
+ if mine and theirs:
576
+ sub = dist[np.ix_(mine, theirs)]
577
+ if sub.min() <= GREASY:
578
+ a, b2 = np.unravel_index(int(sub.argmin()), sub.shape)
579
+ rows.append(row("hydrophobic", k, name, float(sub.min()), protein_atom=heavy[theirs[int(b2)]].name,
580
+ ligand_atom=lig.names[mine[int(a)]]))
581
+ rows.sort(key=lambda r: (_ORDER[str(r["interaction_type"])], str(r["chain"]), int(str(r["residue_number"])),
582
+ str(r["ligand_atom"]) or str(r["ligand_atoms"]), str(r["protein_atom"]) or str(r["protein_atoms"])))
583
+ return rows
584
+
585
+
586
+ def as_tsv(rows: list[dict[str, object]]) -> str:
587
+ lines = ["\t".join(COLUMNS)]
588
+ lines += ["\t".join(str(row.get(c, "")) for c in COLUMNS) for row in rows]
589
+ return "\n".join(lines) + "\n"