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
bindview/detect.py ADDED
@@ -0,0 +1,378 @@
1
+ """Optional interaction detection with PLIP.
2
+
3
+ **Licence boundary.** PLIP is distributed under the GPL-2.0. Nothing else in
4
+ this package imports it: the core (structure reading, ligand building, anchor
5
+ resolution, layout, rendering) works on interaction records supplied by the
6
+ caller and carries no GPL dependency. This module is the only place PLIP is
7
+ touched, it imports PLIP when a detection is run and not when it is loaded
8
+ itself, and it is only reached when a caller passes ``interactions=None``.
9
+ Install it with ``pip install "bindview[plip]"`` (in a clone of the repository,
10
+ ``pip install ".[plip]"``) if you want detection and accept PLIP's terms.
11
+
12
+ The adapter hands PLIP an in-memory PDB rendering of the structure; nothing is
13
+ written to disk and the structure file is never modified.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ from pathlib import Path
19
+ from typing import Any, Sequence
20
+
21
+ from .errors import DetectionUnavailableError, BindviewError, StructureError
22
+ from .exposure import WATER_NAMES
23
+ from .interactions import Interaction, InteractionType
24
+ from .structure import Atom, ResidueKey, Structure, read_structure
25
+
26
+ __all__ = ["detect_interactions", "structure_to_pdb"]
27
+
28
+ T = InteractionType
29
+ _PLIP_HETID = "LIG"
30
+
31
+
32
+ def _atom_name_field(name: str, element: str) -> str:
33
+ """PDB columns 13-16: one-letter elements start in column 14."""
34
+ if len(name) >= 4:
35
+ return name[:4]
36
+ if len(element) == 2:
37
+ return name.ljust(4)
38
+ return (" " + name).ljust(4)
39
+
40
+
41
+ def structure_to_pdb(structure: Structure, ligand: ResidueKey) -> tuple[str, dict[int, Atom], str]:
42
+ """Render a structure as PDB text for a detector that only reads PDB.
43
+
44
+ Returns ``(text, serial -> atom, ligand chain id as written)``. Component
45
+ names longer than three characters (AlphaFold 3 writes ``LIG_B``) do not
46
+ fit the format, so the ligand is written under the name ``LIG``.
47
+ """
48
+ atoms = [a for a in structure.atoms if a.element not in ("H", "D")]
49
+ if len(atoms) > 99999:
50
+ raise StructureError("structure has more than 99,999 heavy atoms and cannot be written as PDB for detection")
51
+ chains: dict[str, str] = {}
52
+ alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
53
+ for a in atoms:
54
+ if a.chain not in chains:
55
+ if len(a.chain) == 1 and a.chain not in chains.values():
56
+ chains[a.chain] = a.chain
57
+ else:
58
+ free = [c for c in alphabet if c not in chains.values()]
59
+ if not free:
60
+ raise StructureError("too many chains to write as PDB for detection")
61
+ chains[a.chain] = free[0]
62
+ lines: list[str] = []
63
+ by_serial: dict[int, Atom] = {}
64
+ for serial, a in enumerate(atoms, start=1):
65
+ if not -999 <= a.resnum <= 9999:
66
+ raise StructureError(f"residue number {a.resnum} does not fit the PDB format needed for detection")
67
+ is_ligand = a.residue == ligand
68
+ resname = _PLIP_HETID if is_ligand else a.resname[:3]
69
+ record = "HETATM" if (a.hetero or is_ligand) else "ATOM "
70
+ lines.append(
71
+ f"{record}{serial:5d} {_atom_name_field(a.name, a.element)} {resname:>3s} {chains[a.chain]}"
72
+ f"{a.resnum:4d}{(a.icode or ' ')[:1]} {a.x:8.3f}{a.y:8.3f}{a.z:8.3f} 1.00 0.00 "
73
+ f"{a.element.upper():>2s}")
74
+ by_serial[serial] = a
75
+ lines.append("END")
76
+ return "\n".join(lines) + "\n", by_serial, chains[ligand.chain]
77
+
78
+
79
+ def _load_plip() -> tuple[Any, Any]:
80
+ try:
81
+ from plip.basic import config
82
+ from plip.structure.preparation import PDBComplex
83
+ except ImportError as exc:
84
+ raise DetectionUnavailableError(
85
+ "interaction detection needs PLIP, which is an optional dependency under the GPL-2.0: "
86
+ "install it with `pip install \"bindview[plip]\"` (in a clone of the repository, `pip install \".[plip]\"`), "
87
+ "pass your own interactions "
88
+ "(interactions=[...]), or have a plain table made from the distances of the heavy atoms "
89
+ "(interactions=\"distances\", --distances-only)") from exc
90
+ return config, PDBComplex
91
+
92
+
93
+ def detect_interactions(structure: "Structure | str | Path", ligand: "ResidueKey | str | tuple[str, int]",
94
+ receptor: str = "protein") -> list[Interaction]:
95
+ """Detect protein-ligand interactions with PLIP and return them as records.
96
+
97
+ ``receptor="nucleic"`` is for a ligand in RNA or DNA: PLIP then takes the nucleic acid for the
98
+ receptor (its ``--dnareceptor``). Left alone it looks at protein only, and finds nothing there.
99
+
100
+ Raises :class:`DetectionUnavailableError` when PLIP is not installed. An
101
+ empty list is a real answer: PLIP ran and found nothing.
102
+ """
103
+ if receptor not in ("protein", "nucleic"):
104
+ raise ValueError(f"receptor is 'protein' or 'nucleic', not {receptor!r}")
105
+ config, PDBComplex = _load_plip()
106
+ st = structure if isinstance(structure, Structure) else read_structure(structure)
107
+ key = ligand if isinstance(ligand, ResidueKey) else st.select_ligand(ligand)
108
+ text, by_serial, chain = structure_to_pdb(st, key)
109
+
110
+ config.NOFIXFILE = True # never write PLIP's "fixed" copy of the input
111
+ before = getattr(config, "DNARECEPTOR", False)
112
+ config.DNARECEPTOR = receptor == "nucleic"
113
+ try:
114
+ mol = PDBComplex()
115
+ mol.load_pdb(text, as_string=True)
116
+ target = None
117
+ for lig in mol.ligands:
118
+ if lig.hetid == _PLIP_HETID and lig.chain == chain and int(lig.position) == key.number:
119
+ target = lig
120
+ break
121
+ if target is None:
122
+ raise BindviewError(f"PLIP did not recognise residue {key} as a ligand")
123
+ mol.characterize_complex(target)
124
+ site = mol.interaction_sets[f"{target.hetid}:{target.chain}:{target.position}"]
125
+ except BindviewError:
126
+ raise
127
+ except Exception as exc: # PLIP / OpenBabel raise assorted exception types
128
+ raise BindviewError(f"PLIP failed on this structure: {exc}") from exc
129
+ finally:
130
+ config.DNARECEPTOR = before # PLIP keeps it for the process: the next call says what it wants
131
+
132
+ def name(serial: int) -> str | None:
133
+ atom = by_serial.get(int(serial))
134
+ return atom.name if atom is not None else None
135
+
136
+ def names(serials: Any) -> tuple[str, ...]:
137
+ return tuple(n for n in (name(s) for s in serials) if n)
138
+
139
+ def base(kind: InteractionType, c: Any, at: Any) -> dict[str, Any]:
140
+ """What every record has. PLIP has the chain as it was written for it, with one letter; the name the
141
+ structure has for it is that of the atom the contact has on the residue's side (``at``, its serial)."""
142
+ atom = by_serial.get(int(at))
143
+ return {"type": kind, "residue_number": int(c.resnr), "residue_name": str(c.restype),
144
+ "chain": atom.chain if atom is not None else str(c.reschain)}
145
+
146
+ def on_ligand(serial: Any) -> bool:
147
+ atom = by_serial.get(int(serial))
148
+ return atom is not None and atom.residue == key
149
+
150
+ out: list[Interaction] = []
151
+ for c in site.hydrophobic_contacts:
152
+ out.append(Interaction(**base(T.HYDROPHOBIC, c, c.bsatom_orig_idx), protein_atom=name(c.bsatom_orig_idx),
153
+ ligand_atom=name(c.ligatom_orig_idx), distance=round(float(c.distance), 2)))
154
+ # A hydroxyl facing a hydroxyl is reported once in each direction; keep the
155
+ # assignment with the straighter donor angle so the pair is one interaction.
156
+ hbonds: dict[tuple[int, int], Interaction] = {}
157
+ for c in list(site.hbonds_ldon) + list(site.hbonds_pdon):
158
+ lig_is_donor = not bool(c.protisdon)
159
+ lig_serial = c.d_orig_idx if lig_is_donor else c.a_orig_idx
160
+ prot_serial = c.a_orig_idx if lig_is_donor else c.d_orig_idx
161
+ rec = Interaction(**base(T.HBOND, c, prot_serial), protein_atom=name(prot_serial),
162
+ ligand_atom=name(lig_serial), distance=round(float(c.distance_ad), 2),
163
+ angle=round(float(c.angle), 2), ligand_is_donor=lig_is_donor)
164
+ pair = (int(prot_serial), int(lig_serial))
165
+ if pair not in hbonds or (rec.angle or 0.0) > (hbonds[pair].angle or 0.0):
166
+ hbonds[pair] = rec
167
+ out.extend(hbonds.values())
168
+ for c in site.halogen_bonds:
169
+ out.append(Interaction(**base(T.HALOGEN, c, c.acc_orig_idx), protein_atom=name(c.acc_orig_idx),
170
+ ligand_atom=name(c.don_orig_idx), distance=round(float(c.distance), 2),
171
+ angle=round(float(c.don_angle), 2)))
172
+ for c in list(site.saltbridge_lneg) + list(site.saltbridge_pneg):
173
+ prot_group = c.positive if c.protispos else c.negative
174
+ lig_group = c.negative if c.protispos else c.positive
175
+ out.append(Interaction(**base(T.SALTBRIDGE, c, prot_group.atoms_orig_idx[0]),
176
+ distance=round(float(c.distance), 2),
177
+ protein_atoms=names(prot_group.atoms_orig_idx),
178
+ ligand_atoms=names(lig_group.atoms_orig_idx)))
179
+ for c in site.pistacking:
180
+ out.append(Interaction(**base(T.PI_STACKING, c, c.proteinring.atoms_orig_idx[0]),
181
+ distance=round(float(c.distance), 2), angle=round(float(c.angle), 2),
182
+ protein_atoms=names(c.proteinring.atoms_orig_idx),
183
+ ligand_atoms=names(c.ligandring.atoms_orig_idx)))
184
+ for c in list(site.pication_laro) + list(site.pication_paro):
185
+ ring_names, charge_names = names(c.ring.atoms_orig_idx), names(c.charge.atoms_orig_idx)
186
+ prot, lig = (charge_names, ring_names) if c.protcharged else (ring_names, charge_names)
187
+ theirs = c.charge if c.protcharged else c.ring
188
+ out.append(Interaction(**base(T.PI_CATION, c, theirs.atoms_orig_idx[0]), distance=round(float(c.distance), 2),
189
+ protein_atoms=prot, ligand_atoms=lig))
190
+ for c in site.metal_complexes:
191
+ if on_ligand(c.metal_orig_idx) and on_ligand(c.target_orig_idx):
192
+ continue # a metal held by its own ligand (cobalamin's Co-N) is not a protein contact
193
+ metal, partner = name(c.metal_orig_idx), name(c.target_orig_idx)
194
+ metal_on_ligand = on_ligand(c.metal_orig_idx)
195
+ out.append(Interaction(**base(T.METAL, c, c.target_orig_idx), distance=round(float(c.distance), 2),
196
+ ligand_atom=metal if metal_on_ligand else partner,
197
+ protein_atom=partner if metal_on_ligand else metal))
198
+ for c in site.water_bridges:
199
+ lig_is_donor = not bool(c.protisdon)
200
+ lig_serial = c.d_orig_idx if lig_is_donor else c.a_orig_idx
201
+ prot_serial = c.a_orig_idx if lig_is_donor else c.d_orig_idx
202
+ water = by_serial.get(int(c.water_orig_idx))
203
+ out.append(Interaction(**base(T.WATER_BRIDGE, c, prot_serial), protein_atom=name(prot_serial),
204
+ ligand_atom=name(lig_serial),
205
+ distance=round(float(c.distance_aw if lig_is_donor else c.distance_dw), 2),
206
+ angle=round(float(c.w_angle), 2), ligand_is_donor=lig_is_donor,
207
+ water=f"{water.chain}:{water.resnum}" if water else None))
208
+ out.sort(key=lambda r: (r.type.value, r.chain, r.residue_number, r.protein_atom or "", r.ligand_atom or "",
209
+ r.distance if r.distance is not None else 0.0))
210
+ return out
211
+
212
+
213
+ # ---------------------------------------------------------------------------
214
+ # Two sets of chains: an interface
215
+ # ---------------------------------------------------------------------------
216
+
217
+ #: PLIP takes a chain as a "peptide ligand" only residue by residue that OpenBabel knows as an
218
+ #: amino acid. A modified residue is dropped from it without a word, and its contacts with it (the
219
+ #: sulfate of a sulfotyrosine, the phosphate of a phosphotyrosine: the recognition feature). Written
220
+ #: under the name of its parent it stays in the chain with all its atoms.
221
+ _PARENTS = {"TYS": "TYR", "PTR": "TYR", "SEP": "SER", "TPO": "THR", "MSE": "MET", "CSO": "CYS", "HYP": "PRO",
222
+ "ALY": "LYS", "MLY": "LYS", "M3L": "LYS"}
223
+
224
+
225
+ def _interface_pdb(structure: Structure, peptides: "set[str]") -> tuple[str, dict[int, Atom], dict[str, str]]:
226
+ """The structure as PDB text for PLIP's peptide mode: ``(text, serial -> atom, chain -> chain as written)``.
227
+
228
+ Two things are not written as the file has them, because PLIP gets them
229
+ wrong otherwise. Residues are numbered 1, 2, 3 ... within their chain: with
230
+ insertion codes (thrombin's 14A to 14L) PLIP collapses residues into one
231
+ and reports contacts that are not there. And a modified residue of a chain
232
+ that is to be a peptide is written as an ATOM record under its parent's
233
+ name (:data:`_PARENTS`). Every atom is mapped back by its serial number,
234
+ so none of this reaches the result.
235
+ """
236
+ atoms = [a for a in structure.atoms if a.element not in ("H", "D")]
237
+ if len(atoms) > 99999:
238
+ raise StructureError("structure has more than 99,999 heavy atoms and cannot be written as PDB for detection")
239
+ alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
240
+ chains: dict[str, str] = {}
241
+ for a in atoms:
242
+ if a.chain not in chains:
243
+ if len(a.chain) == 1 and a.chain not in chains.values():
244
+ chains[a.chain] = a.chain
245
+ else:
246
+ free = [c for c in alphabet if c not in chains.values()]
247
+ if not free:
248
+ raise StructureError("too many chains to write as PDB for detection")
249
+ chains[a.chain] = free[0]
250
+ number: dict[Any, int] = {}
251
+ count: dict[str, int] = {}
252
+ lines: list[str] = []
253
+ by_serial: dict[int, Atom] = {}
254
+ for serial, a in enumerate(atoms, start=1):
255
+ if a.residue not in number:
256
+ count[a.chain] = count.get(a.chain, 0) + 1
257
+ number[a.residue] = count[a.chain]
258
+ if count[a.chain] > 9999:
259
+ raise StructureError(f"chain {a.chain} has more than 9,999 residues and cannot be written as PDB")
260
+ inside = a.chain in peptides and a.resname.upper() not in WATER_NAMES
261
+ resname = _PARENTS.get(a.resname, a.resname) if inside else a.resname
262
+ record = "ATOM " if (inside or not a.hetero) else "HETATM"
263
+ lines.append(
264
+ f"{record}{serial:5d} {_atom_name_field(a.name, a.element)} {resname[:3]:>3s} {chains[a.chain]}"
265
+ f"{number[a.residue]:4d} {a.x:8.3f}{a.y:8.3f}{a.z:8.3f} 1.00 0.00 {a.element.upper():>2s}")
266
+ by_serial[serial] = a
267
+ lines.append("END")
268
+ return "\n".join(lines) + "\n", by_serial, chains
269
+
270
+
271
+ def detect_interface(structure: "Structure | str | Path", chains_a: "Sequence[str]", chains_b: "Sequence[str]"
272
+ ) -> "list[Any]":
273
+ """Contacts between two sets of chains, detected with PLIP's peptide mode.
274
+
275
+ PLIP is a protein-ligand profiler, but a chain can be named as a "peptide
276
+ ligand", of any length, and then its contacts with every other chain are
277
+ reported with the residue and the atoms on both sides. The smaller of the
278
+ two sets is named so; contacts with chains of neither set are dropped.
279
+ Returns :class:`bindview.interface.InterfaceContact` records with side ``a``
280
+ in ``chains_a``.
281
+
282
+ What PLIP does not do here: a cap (``ACE``) is not part of the peptide and
283
+ its contacts are not reported, and a phosphate or sulfate on a residue is
284
+ not seen as a charged group, so its salt bridges come out as hydrogen bonds.
285
+ """
286
+ from .interface import InterfaceContact
287
+
288
+ config, PDBComplex = _load_plip()
289
+ st = structure if isinstance(structure, Structure) else read_structure(structure)
290
+ a_set, b_set = set(chains_a), set(chains_b)
291
+ if not a_set or not b_set or a_set & b_set:
292
+ raise BindviewError("an interface is between two different, non-empty sets of chains")
293
+ present = {a.chain for a in st.atoms}
294
+ missing = sorted((a_set | b_set) - present)
295
+ if missing:
296
+ raise BindviewError(f"no chain {', '.join(missing)} in {st.source or 'the structure'}")
297
+ size = {c: 0 for c in a_set | b_set}
298
+ for atom in st.atoms:
299
+ if atom.chain in size:
300
+ size[atom.chain] += 1
301
+ flipped = sum(size[c] for c in b_set) < sum(size[c] for c in a_set)
302
+ peptides, partners = (b_set, a_set) if flipped else (a_set, b_set)
303
+ text, by_serial, written = _interface_pdb(st, peptides)
304
+ before = (config.PEPTIDES, config.NOFIXFILE)
305
+ config.PEPTIDES = sorted(written[c] for c in peptides)
306
+ config.NOFIXFILE = True
307
+ out: list[Any] = []
308
+
309
+ def side(serials: Any) -> "tuple[Atom, tuple[str, ...]] | None":
310
+ found = [x for x in (by_serial.get(int(s)) for s in serials) if x is not None]
311
+ return (found[0], tuple(x.name for x in found)) if found else None
312
+
313
+ def add(kind: InteractionType, pep: Any, other: Any, **more: Any) -> None:
314
+ if pep is None or other is None or pep[0].chain not in peptides or other[0].chain not in partners:
315
+ return
316
+ one, two = (other, pep) if flipped else (pep, other)
317
+ donor = more.pop("peptide_donates", None)
318
+ out.append(InterfaceContact(
319
+ type=kind, chain_a=one[0].chain, number_a=one[0].resnum, icode_a=one[0].icode, resname_a=one[0].resname,
320
+ atoms_a=one[1], chain_b=two[0].chain, number_b=two[0].resnum, icode_b=two[0].icode,
321
+ resname_b=two[0].resname, atoms_b=two[1],
322
+ a_is_donor=None if donor is None else (donor != flipped), **more))
323
+
324
+ try:
325
+ mol = PDBComplex()
326
+ mol.load_pdb(text, as_string=True)
327
+ for lig in mol.ligands:
328
+ if lig.chain not in config.PEPTIDES:
329
+ continue
330
+ mol.characterize_complex(lig)
331
+ site = mol.interaction_sets[f"{lig.hetid}:{lig.chain}:{lig.position}"]
332
+ for c in site.hydrophobic_contacts:
333
+ add(T.HYDROPHOBIC, side([c.ligatom_orig_idx]), side([c.bsatom_orig_idx]),
334
+ distance=round(float(c.distance), 2))
335
+ for c in list(site.hbonds_ldon) + list(site.hbonds_pdon):
336
+ pep_donates = not bool(c.protisdon)
337
+ pep_serial = c.d_orig_idx if pep_donates else c.a_orig_idx
338
+ other_serial = c.a_orig_idx if pep_donates else c.d_orig_idx
339
+ add(T.HBOND, side([pep_serial]), side([other_serial]), distance=round(float(c.distance_ad), 2),
340
+ angle=round(float(c.angle), 2), peptide_donates=pep_donates)
341
+ for c in list(site.saltbridge_lneg) + list(site.saltbridge_pneg):
342
+ other_group = c.positive if c.protispos else c.negative
343
+ pep_group = c.negative if c.protispos else c.positive
344
+ add(T.SALTBRIDGE, side(pep_group.atoms_orig_idx), side(other_group.atoms_orig_idx),
345
+ distance=round(float(c.distance), 2))
346
+ for c in site.pistacking:
347
+ add(T.PI_STACKING, side(c.ligandring.atoms_orig_idx), side(c.proteinring.atoms_orig_idx),
348
+ distance=round(float(c.distance), 2), angle=round(float(c.angle), 2))
349
+ for c in list(site.pication_laro) + list(site.pication_paro):
350
+ ring, charge = side(c.ring.atoms_orig_idx), side(c.charge.atoms_orig_idx)
351
+ pep, other = (ring, charge) if c.protcharged else (charge, ring)
352
+ add(T.PI_CATION, pep, other, distance=round(float(c.distance), 2))
353
+ for c in site.water_bridges:
354
+ pep_donates = not bool(c.protisdon)
355
+ pep_serial = c.d_orig_idx if pep_donates else c.a_orig_idx
356
+ other_serial = c.a_orig_idx if pep_donates else c.d_orig_idx
357
+ water = by_serial.get(int(c.water_orig_idx))
358
+ add(T.WATER_BRIDGE, side([pep_serial]), side([other_serial]),
359
+ distance=round(float(c.distance_aw if pep_donates else c.distance_dw), 2),
360
+ angle=round(float(c.w_angle), 2), peptide_donates=pep_donates,
361
+ water=f"{water.chain}:{water.resnum}" if water else None)
362
+ except BindviewError:
363
+ raise
364
+ except Exception as exc: # PLIP / OpenBabel raise assorted exception types
365
+ raise BindviewError(f"PLIP failed on this structure: {exc}") from exc
366
+ finally:
367
+ config.PEPTIDES, config.NOFIXFILE = before
368
+ # A hydroxyl facing a hydroxyl is reported once in each direction: keep the straighter one.
369
+ best: dict[tuple, Any] = {}
370
+ rest: list[Any] = []
371
+ for c in out:
372
+ if c.type is not T.HBOND:
373
+ rest.append(c)
374
+ continue
375
+ ident = (c.residue_a, c.atoms_a, c.residue_b, c.atoms_b)
376
+ if ident not in best or (c.angle or 0.0) > (best[ident].angle or 0.0):
377
+ best[ident] = c
378
+ return sorted(rest + list(best.values()), key=lambda c: c.sort_key)