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/ligand.py ADDED
@@ -0,0 +1,583 @@
1
+ """Building the ligand as an RDKit molecule *from the structure file*.
2
+
3
+ The whole point of this module is the atom-name map. A SMILES laid out on its
4
+ own has an atom order unrelated to the structure file, so an interaction
5
+ reported against ``F2`` could not be attached to anything. Building the
6
+ molecule from the ``_atom_site`` records keeps each name on its atom through
7
+ bond perception and 2D layout.
8
+
9
+ The route:
10
+
11
+ 1. atoms + 3D conformer from the structure, ``atomName`` set on every atom;
12
+ 2. connectivity from geometry (``rdDetermineBonds.DetermineConnectivity``);
13
+ 3. bond orders, charges and hydrogen counts from a SMILES template;
14
+ 4. 2D coordinates.
15
+
16
+ Two hardening steps sit between 2 and 3, both needed by real AlphaFold 3 output:
17
+
18
+ * Geometry produces bonds the template does not have -- metal coordination
19
+ (cobalamin's Co-N) and outright clashes (a peptide ligand with two atoms
20
+ 1.9 A apart). Those are identified by the template match and removed, so the
21
+ drawn molecule is exactly the template's graph. Coordination bonds are kept
22
+ aside for display as intra-ligand contacts.
23
+ * After transfer the result is checked against the template by canonical
24
+ SMILES. A mismatch is an error, never a silently different molecule.
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ from dataclasses import dataclass, field
30
+ from typing import Sequence
31
+
32
+ import numpy as np
33
+ from rdkit import Chem
34
+ from rdkit.Chem import rdDetermineBonds
35
+ from rdkit.Geometry import Point3D
36
+
37
+ from .chem import is_metal, quiet_rdkit
38
+ from .errors import LigandBuildError
39
+ from .structure import Atom
40
+
41
+ __all__ = ["Ligand", "build_ligand"]
42
+
43
+ _COV_FACTORS = (1.3, 1.4, 1.5, 1.6)
44
+ #: Of the ways a template fits the atoms of the model, how many are looked at. A drug has a handful (a benzene
45
+ #: ring turned over, the two oxygens of an acid), a peptide more than can be counted.
46
+ _WAYS = 1000
47
+ #: What the model has to say for one way against another, in ångström for each bond order that the two put on
48
+ #: another bond: half of what a single and a double bond differ by in length.
49
+ _TELLS_APART = 0.1
50
+ #: What a hydrogen of the file counts, in ångström, on an atom to which a way gives none (or the reverse).
51
+ _HYDROGEN = 0.1
52
+ #: A hydrogen of the file is on the heavy atom next to it, if that is no further than this (ångström).
53
+ _HYDROGEN_BOND = 1.6
54
+
55
+
56
+ @dataclass
57
+ class Ligand:
58
+ """A ligand with named atoms.
59
+
60
+ Attributes
61
+ ----------
62
+ mol:
63
+ Sanitized heavy-atom RDKit molecule. Atom ``i`` carries the property
64
+ ``atomName`` and corresponds to ``names[i]`` / ``coords3d[i]``.
65
+ names:
66
+ Structure-file atom name of every atom.
67
+ coords3d:
68
+ ``(n, 3)`` model coordinates.
69
+ bond_source:
70
+ ``"template"`` (orders from SMILES), ``"geometry"`` (orders inferred
71
+ from a 3D structure that has hydrogens), ``"connectivity"`` (orders
72
+ unknown, drawn single) or ``"single-atom"``.
73
+ coordination:
74
+ Intra-ligand metal coordination pairs ``(metal_idx, donor_idx)`` that
75
+ geometry reported and the template does not bond.
76
+ artefact_bonds:
77
+ Geometric bonds dropped because the template has no such bond and no
78
+ metal is involved -- atoms the model placed too close together.
79
+ diagnostics:
80
+ Human-readable notes on anything that deviated from the clean path.
81
+ """
82
+
83
+ mol: Chem.Mol
84
+ names: list[str]
85
+ coords3d: np.ndarray
86
+ bond_source: str
87
+ smiles: str | None = None
88
+ coordination: list[tuple[int, int]] = field(default_factory=list)
89
+ artefact_bonds: list[tuple[int, int]] = field(default_factory=list)
90
+ stereo_mismatches: list[str] = field(default_factory=list)
91
+ ionized: list[int] = field(default_factory=list)
92
+ diagnostics: list[str] = field(default_factory=list)
93
+ #: For a ligand that is a polymer chain of its own in the structure file: its residues as the
94
+ #: file gives them (:class:`bindview.structure.ChainResidue`), and the chain's name. Empty otherwise.
95
+ given: tuple = ()
96
+ chain: str = ""
97
+ #: The ions between the ligand and the protein that are drawn with it (:mod:`bindview.ions`).
98
+ bridging: list[int] = field(default_factory=list)
99
+
100
+ def __post_init__(self) -> None:
101
+ self._index = {n: i for i, n in enumerate(self.names)}
102
+
103
+ @property
104
+ def n_atoms(self) -> int:
105
+ return len(self.names)
106
+
107
+ def index_of(self, name: str) -> int | None:
108
+ """Atom index for a structure-file atom name, or ``None``."""
109
+ return self._index.get(name)
110
+
111
+ def element(self, idx: int) -> str:
112
+ return self.mol.GetAtomWithIdx(idx).GetSymbol()
113
+
114
+ def apart(self) -> "list[tuple[tuple[int, ...], tuple[int, float] | None, tuple[int, float]]]":
115
+ """The parts of the ligand that the model binds to nothing else of it, by a bond or by coordination
116
+ (a hydroxide the model has not put on its cobalt). For each: its atoms; the nearest metal of the
117
+ rest and how far it is, where the rest has one; and the nearest atom of the rest and how far.
118
+ Distances in the model, in ångström. Empty for a ligand in one piece."""
119
+ parent = list(range(self.n_atoms))
120
+
121
+ def root(i: int) -> int:
122
+ while parent[i] != i:
123
+ i = parent[i]
124
+ return i
125
+
126
+ pairs = [(b.GetBeginAtomIdx(), b.GetEndAtomIdx()) for b in self.mol.GetBonds()] + list(self.coordination)
127
+ for i, j in pairs:
128
+ if root(i) != root(j):
129
+ parent[root(i)] = root(j)
130
+ parts: dict[int, list[int]] = {}
131
+ for i in range(self.n_atoms):
132
+ parts.setdefault(root(i), []).append(i)
133
+ if len(parts) < 2:
134
+ return []
135
+ main = max(parts.values(), key=lambda p: (len(p), -min(p)))
136
+ out = []
137
+ for part in sorted((p for p in parts.values() if p is not main), key=min):
138
+ rest = [i for i in range(self.n_atoms) if i not in part]
139
+ d = np.linalg.norm(self.coords3d[part][:, None, :] - self.coords3d[rest][None, :, :], axis=2)
140
+ near = rest[int(d.min(axis=0).argmin())]
141
+ metals = [k for k, i in enumerate(rest) if is_metal(self.element(i))]
142
+ metal = None
143
+ if metals:
144
+ k = min(metals, key=lambda k: float(d[:, k].min()))
145
+ metal = (rest[k], float(d[:, k].min()))
146
+ out.append((tuple(part), metal, (near, float(d.min()))))
147
+ return out
148
+
149
+
150
+ # ---------------------------------------------------------------------------
151
+
152
+
153
+ def _seed_mol(atoms: Sequence[Atom]) -> Chem.RWMol:
154
+ m = Chem.RWMol()
155
+ conf = Chem.Conformer(len(atoms))
156
+ for i, a in enumerate(atoms):
157
+ try:
158
+ atom = Chem.Atom(a.element)
159
+ except Exception as exc: # RDKit raises a generic error for unknown symbols
160
+ raise LigandBuildError(f"unknown element {a.element!r} on ligand atom {a.name}") from exc
161
+ atom.SetProp("atomName", a.name)
162
+ atom.SetNoImplicit(True)
163
+ m.AddAtom(atom)
164
+ conf.SetAtomPosition(i, Point3D(a.x, a.y, a.z))
165
+ conf.Set3D(True)
166
+ m.AddConformer(conf, assignId=True)
167
+ return m
168
+
169
+
170
+ def _stripped_template(template: Chem.Mol) -> Chem.Mol:
171
+ """Template reduced to its bare graph: single bonds, no charges, no H counts."""
172
+ q = Chem.RWMol(template)
173
+ for b in q.GetBonds():
174
+ b.SetBondType(Chem.BondType.SINGLE)
175
+ b.SetIsAromatic(False)
176
+ for a in q.GetAtoms():
177
+ a.SetFormalCharge(0)
178
+ a.SetIsAromatic(False)
179
+ a.SetNoImplicit(True)
180
+ a.SetNumExplicitHs(0)
181
+ a.SetNumRadicalElectrons(0)
182
+ a.SetChiralTag(Chem.ChiralType.CHI_UNSPECIFIED)
183
+ a.SetIsotope(0)
184
+ return q.GetMol()
185
+
186
+
187
+ def _bare_graph(m: Chem.RWMol) -> Chem.Mol:
188
+ g = Chem.RWMol(m)
189
+ for b in g.GetBonds():
190
+ b.SetBondType(Chem.BondType.SINGLE)
191
+ b.SetIsAromatic(False)
192
+ for a in g.GetAtoms():
193
+ a.SetFormalCharge(0)
194
+ a.SetIsAromatic(False)
195
+ a.SetNoImplicit(True)
196
+ a.SetNumExplicitHs(0)
197
+ a.SetNumRadicalElectrons(0)
198
+ return g.GetMol()
199
+
200
+
201
+ def _connect(atoms: Sequence[Atom], cov_factor: float) -> Chem.RWMol:
202
+ m = _seed_mol(atoms)
203
+ try:
204
+ rdDetermineBonds.DetermineConnectivity(m, covFactor=cov_factor)
205
+ except Exception as exc:
206
+ raise LigandBuildError(f"could not perceive ligand connectivity: {exc}") from exc
207
+ return m
208
+
209
+
210
+ def _fit_template(template: Chem.Mol, n_heavy: int, diagnostics: list[str]) -> Chem.Mol:
211
+ """Drop template fragments the structure cannot contain (e.g. counter-ions)."""
212
+ if template.GetNumAtoms() <= n_heavy:
213
+ return template
214
+ frags = list(Chem.GetMolFrags(template, asMols=True))
215
+ if len(frags) == 1:
216
+ return template
217
+ frags.sort(key=lambda f: -f.GetNumAtoms())
218
+ kept: list[Chem.Mol] = []
219
+ total = 0
220
+ for f in frags:
221
+ if total + f.GetNumAtoms() <= n_heavy:
222
+ kept.append(f)
223
+ total += f.GetNumAtoms()
224
+ if not kept or total != n_heavy:
225
+ return template
226
+ out = kept[0]
227
+ for f in kept[1:]:
228
+ out = Chem.CombineMols(out, f)
229
+ diagnostics.append(
230
+ f"SMILES has {template.GetNumAtoms()} heavy atoms, the structure {n_heavy}: "
231
+ f"{len(frags) - len(kept)} template fragment(s) not present in the structure were ignored")
232
+ return out
233
+
234
+
235
+ def _hydrogens_on(heavy: Sequence[Atom], hydrogens: Sequence[Atom]) -> np.ndarray:
236
+ """How many hydrogens the file has on each heavy atom: every hydrogen on the atom next to it."""
237
+ xyz = np.array([a.xyz for a in heavy], dtype=float)
238
+ count = np.zeros(len(heavy), dtype=int)
239
+ for h in hydrogens:
240
+ apart = np.linalg.norm(xyz - np.array(h.xyz, dtype=float), axis=1)
241
+ if apart.min() <= _HYDROGEN_BOND:
242
+ count[int(apart.argmin())] += 1
243
+ return count
244
+
245
+
246
+ def _best_way(ways: Sequence[Sequence[int]], template: Chem.Mol, atoms: Sequence[Atom],
247
+ hydrogens: Sequence[Atom], diagnostics: list[str]) -> Sequence[int]:
248
+ """Of the ways the template fits the atoms of the model, the one the model's geometry agrees with best.
249
+
250
+ The graph without bond orders has symmetries that the molecule does not have: 4-hydroxycyclohexanone fits
251
+ with the ketone on either oxygen. A benzene ring turned over is no other way: the same molecule on the
252
+ same atoms. Of the others there are two sorts.
253
+
254
+ Ways that differ inside the molecule, in the bond orders, charge or hydrogens of an atom with more than
255
+ one neighbour. A way is the better the shorter the bonds of the model on which it puts its higher orders
256
+ (the sum of order times length) and, in a file with hydrogens, the fewer hydrogens it gives an atom more
257
+ or less than the file has on it. Another than the first is taken only where it is better by more than
258
+ ``_TELLS_APART`` for each bond order that it puts on another bond. Where the model does not tell another
259
+ from the one taken, ``diagnostics`` says so.
260
+
261
+ Ways that differ in the ends of one group alone: the oxygens of a carboxylate or a phosphate, the
262
+ nitrogens of a guanidinium. They are one group either way, and which of its bonds a model has the
263
+ shorter says nothing: the ends stay as the first way has them, unless the hydrogens of the file say
264
+ which of them has one.
265
+ """
266
+ if len(ways) == 1:
267
+ return ways[0]
268
+ on = np.array(ways) # (ways, atoms of the template): the atom of the model
269
+ rows, n = np.arange(len(ways))[:, None], len(atoms)
270
+ xyz = np.array([a.xyz for a in atoms], dtype=float)
271
+ moves = (on != on[0]).any(axis=0) # the atoms of the template that not all ways put alike
272
+ bonds = [b for b in template.GetBonds() if moves[b.GetBeginAtomIdx()] or moves[b.GetEndAtomIdx()]]
273
+ i = on[:, np.array([b.GetBeginAtomIdx() for b in bonds], dtype=int)]
274
+ j = on[:, np.array([b.GetEndAtomIdx() for b in bonds], dtype=int)]
275
+ pairs, where = np.unique(np.minimum(i, j) * n + np.maximum(i, j), return_inverse=True)
276
+ orders = np.zeros((len(ways), len(pairs))) # (ways, pairs of atoms): the bond order put there
277
+ orders[rows, where.reshape(i.shape)] = [b.GetBondTypeAsDouble() for b in bonds]
278
+ misfit = orders @ np.linalg.norm(xyz[pairs // n] - xyz[pairs % n], axis=1)
279
+ off = np.zeros(len(ways)) # the hydrogens a way gives that the file has not there
280
+ if hydrogens:
281
+ wanted = np.array([a.GetTotalNumHs() for a in template.GetAtoms()])[moves]
282
+ off = np.abs(wanted - _hydrogens_on(atoms, hydrogens)[on[:, moves]]).sum(axis=1)
283
+ misfit = misfit + _HYDROGEN * off
284
+
285
+ # What a way gives an atom besides its bonds; the ways that are alike inside the molecule are of one sort.
286
+ kinds: dict[tuple, int] = {}
287
+ kind = np.zeros((len(ways), n), dtype=int)
288
+ kind[rows, on[:, moves]] = np.array([kinds.setdefault(
289
+ (a.GetFormalCharge(), a.GetTotalNumHs(), a.GetIsAromatic(), a.GetNumRadicalElectrons(), a.GetIsotope()),
290
+ len(kinds) + 1) for a in template.GetAtoms()])[moves]
291
+ inside = np.zeros(n, dtype=bool)
292
+ inside[on[0]] = [a.GetDegree() > 1 for a in template.GetAtoms()]
293
+ mark = np.hstack([kind[:, inside], orders[:, inside[pairs // n] & inside[pairs % n]]])
294
+ differs = (mark != mark[0]).any(axis=0)
295
+ alike = np.zeros(len(ways), dtype=int) # the same number for ways of one sort
296
+ if differs.any():
297
+ alike = np.unique(mark[:, differs], axis=0, return_inverse=True)[1].reshape(-1)
298
+
299
+ def beside(way: int) -> tuple[np.ndarray, np.ndarray]:
300
+ """Of each sort, the way to hold against this one: the fewest hydrogens off, then the fewest bond
301
+ orders on another bond than here, then the first. And that number of bond orders, of every way."""
302
+ apart = np.abs(orders - orders[way]).sum(axis=1) / 2
303
+ order = np.lexsort((apart, off, alike))
304
+ return np.sort(order[np.r_[True, alike[order][1:] != alike[order][:-1]]]), apart
305
+
306
+ stand, apart = beside(0)
307
+ cost = misfit[stand] + _TELLS_APART * apart[stand]
308
+ best = int(stand[np.flatnonzero(cost <= cost.min() + 1e-9)[0]])
309
+ stand, apart = beside(best)
310
+ as_good = (alike[stand] != alike[best]) & (misfit[stand] - misfit[best] <= _TELLS_APART * apart[stand] + 1e-9)
311
+ for way in stand[as_good][:1]:
312
+ differ = set(np.flatnonzero(kind[way] != kind[best]).tolist())
313
+ differ.update(int(end) for pair in pairs[orders[way] != orders[best]] for end in (pair // n, pair % n))
314
+ named = [atoms[k].name for k in sorted(differ)]
315
+ diagnostics.append(
316
+ "the SMILES fits the model's atoms in more than one way, and the model's geometry does not say "
317
+ f"which: another way gives {', '.join(named[:8])}{' ...' if len(named) > 8 else ''} other bond "
318
+ "orders, charges or hydrogens")
319
+ return ways[best]
320
+
321
+
322
+ def _apply_template(atoms: Sequence[Atom], template: Chem.Mol, diagnostics: list[str],
323
+ hydrogens: Sequence[Atom] = ()
324
+ ) -> tuple[Chem.Mol, list[tuple[int, int]], list[tuple[int, int]]] | None:
325
+ """Template route. Returns ``None`` when the template cannot be matched. ``hydrogens``: those of the file,
326
+ which help to say how the template lies where it fits in more than one way (:func:`_best_way`)."""
327
+ query = _stripped_template(template)
328
+ coords = np.array([a.xyz for a in atoms], dtype=float)
329
+ for factor in _COV_FACTORS:
330
+ m = _connect(atoms, factor)
331
+ ways = _bare_graph(m).GetSubstructMatches(query, uniquify=False, maxMatches=_WAYS)
332
+ if not ways or len(ways[0]) != template.GetNumAtoms():
333
+ continue
334
+ if len(set(ways[0])) != m.GetNumAtoms():
335
+ # Template smaller than the ligand in the file: a different molecule.
336
+ return None
337
+ if factor != _COV_FACTORS[0]:
338
+ diagnostics.append(
339
+ f"template matched only after relaxing the bond-length tolerance to {factor:.2f}x covalent radii "
340
+ f"(stretched bonds in the model)")
341
+ match = _best_way(ways, template, atoms, hydrogens, diagnostics)
342
+ keep = {frozenset((match[b.GetBeginAtomIdx()], match[b.GetEndAtomIdx()])) for b in template.GetBonds()}
343
+ coordination: list[tuple[int, int]] = []
344
+ artefacts: list[tuple[int, int]] = []
345
+ for b in list(m.GetBonds()):
346
+ i, j = b.GetBeginAtomIdx(), b.GetEndAtomIdx()
347
+ if frozenset((i, j)) in keep:
348
+ continue
349
+ ei, ej = m.GetAtomWithIdx(i).GetSymbol(), m.GetAtomWithIdx(j).GetSymbol()
350
+ if is_metal(ei) or is_metal(ej):
351
+ coordination.append((i, j) if is_metal(ei) else (j, i))
352
+ else:
353
+ artefacts.append((min(i, j), max(i, j)))
354
+ m.RemoveBond(i, j)
355
+ for b in template.GetBonds():
356
+ b2 = m.GetBondBetweenAtoms(match[b.GetBeginAtomIdx()], match[b.GetEndAtomIdx()])
357
+ b2.SetBondType(b.GetBondType())
358
+ b2.SetIsAromatic(b.GetIsAromatic())
359
+ for a in template.GetAtoms():
360
+ a2 = m.GetAtomWithIdx(match[a.GetIdx()])
361
+ a2.SetFormalCharge(a.GetFormalCharge())
362
+ a2.SetIsAromatic(a.GetIsAromatic())
363
+ a2.SetNoImplicit(True)
364
+ a2.SetNumExplicitHs(a.GetTotalNumHs())
365
+ a2.SetNumRadicalElectrons(a.GetNumRadicalElectrons())
366
+ a2.SetIsotope(a.GetIsotope())
367
+ mol = m.GetMol()
368
+ try:
369
+ Chem.SanitizeMol(mol)
370
+ except Exception as exc:
371
+ metals = sorted({a.GetSymbol() for a in mol.GetAtoms() if is_metal(a.GetSymbol())})
372
+ hint = (f". The ligand holds a metal ({', '.join(metals)}): a SMILES that writes the bonds to a metal "
373
+ f"like those between any two atoms gives the metal's neighbours a valence they cannot have. "
374
+ f"Without a SMILES the ligand is drawn from its connectivity alone") if metals else ""
375
+ raise LigandBuildError(f"template bond orders do not sanitize on the model geometry: {exc}{hint}") from exc
376
+ got = Chem.MolToSmiles(mol, isomericSmiles=False)
377
+ want = Chem.MolToSmiles(template, isomericSmiles=False)
378
+ if got != want:
379
+ raise LigandBuildError(
380
+ "ligand built from the structure is not the template molecule "
381
+ f"(built {got!r}, template {want!r})")
382
+ for i, j in artefacts:
383
+ d = float(np.linalg.norm(coords[i] - coords[j]))
384
+ diagnostics.append(
385
+ f"model geometry puts {atoms[i].name} and {atoms[j].name} {d:.2f} A apart without a bond in the "
386
+ f"template; treated as a clash, not drawn as a bond")
387
+ return mol, coordination, artefacts
388
+ return None
389
+
390
+
391
+ def _from_geometry(heavy: Sequence[Atom], hydrogens: Sequence[Atom], diagnostics: list[str]
392
+ ) -> tuple[Chem.Mol, str]:
393
+ """No usable template: infer what can honestly be inferred from coordinates.
394
+
395
+ Bond orders can be derived from geometry only when the structure carries
396
+ hydrogens, because the method works by satisfying valences. On heavy atoms
397
+ alone (all AlphaFold 3 output, most crystal structures) it "satisfies" them
398
+ with multiple bonds that are not there -- benzene comes out with three
399
+ triple bonds. In that situation only the connectivity is trustworthy, so
400
+ that is all that is drawn, and the result says so.
401
+ """
402
+ if hydrogens:
403
+ everything = list(heavy) + list(hydrogens)
404
+ try:
405
+ trial = _seed_mol(everything)
406
+ rdDetermineBonds.DetermineBonds(trial, charge=0)
407
+ mol = Chem.RemoveHs(trial.GetMol())
408
+ Chem.SanitizeMol(mol)
409
+ if mol.GetNumAtoms() == len(heavy):
410
+ diagnostics.append("no SMILES template: bond orders were inferred from the 3D geometry "
411
+ "(the structure has hydrogens)")
412
+ return mol, "geometry"
413
+ except Exception:
414
+ pass
415
+ m = _connect(heavy, _COV_FACTORS[0])
416
+ for a in m.GetAtoms():
417
+ a.SetNoImplicit(True)
418
+ a.SetNumExplicitHs(0)
419
+ a.SetNumRadicalElectrons(0)
420
+ mol = m.GetMol()
421
+ mol.UpdatePropertyCache(strict=False)
422
+ Chem.FastFindRings(mol)
423
+ why = ("bond orders could not be inferred from the geometry" if hydrogens else
424
+ "the structure has no hydrogens, so bond orders cannot be inferred from geometry")
425
+ diagnostics.append(f"no SMILES template and {why}: only the connectivity is known, "
426
+ "all bonds are drawn single and hydrogens are not shown")
427
+ return mol, "connectivity"
428
+
429
+
430
+ def _compare_stereo(mol: Chem.Mol, template: Chem.Mol, names: list[str]) -> list[str]:
431
+ """Stereocentres whose model (3D) configuration differs from the SMILES."""
432
+ query = Chem.Mol(template)
433
+ Chem.AssignStereochemistry(query, cleanIt=True, force=True)
434
+ match = mol.GetSubstructMatch(query, useChirality=False)
435
+ if not match:
436
+ return []
437
+ out: list[str] = []
438
+ for a in query.GetAtoms():
439
+ want = a.GetProp("_CIPCode") if a.HasProp("_CIPCode") else None
440
+ b = mol.GetAtomWithIdx(match[a.GetIdx()])
441
+ got = b.GetProp("_CIPCode") if b.HasProp("_CIPCode") else None
442
+ if want and got and want != got:
443
+ out.append(f"{names[b.GetIdx()]} is {got} in the model, {want} in the SMILES")
444
+ elif want and not got:
445
+ out.append(f"{names[b.GetIdx()]} is {want} in the SMILES, undefined in the model")
446
+ return out
447
+
448
+
449
+ # Acids that are deprotonated at physiological pH. Drawn ionised so that a salt
450
+ # bridge lands on a visibly charged group; bases are left as the SMILES has
451
+ # them, because their protonation is not safe to assert from structure alone.
452
+ _ACID_SMARTS = (
453
+ "[CX3](=[OX1])[OX2H1]", # carboxylic acid
454
+ "[PX4](=[OX1])[OX2H1]", # phosphoric / phosphonic acid
455
+ "[SX4](=[OX1])(=[OX1])[OX2H1]", # sulfonic / sulfuric acid
456
+ )
457
+
458
+
459
+ def _ionize_acids(mol: Chem.Mol) -> tuple[Chem.Mol, list[int]]:
460
+ """Deprotonate carboxylic, phosphoric and sulfonic acid OH groups."""
461
+ targets: set[int] = set()
462
+ for smarts in _ACID_SMARTS:
463
+ patt = Chem.MolFromSmarts(smarts)
464
+ for match in mol.GetSubstructMatches(patt):
465
+ targets.add(match[-1])
466
+ if not targets:
467
+ return mol, []
468
+ rw = Chem.RWMol(mol)
469
+ for i in sorted(targets):
470
+ atom = rw.GetAtomWithIdx(i)
471
+ atom.SetNumExplicitHs(0)
472
+ atom.SetNoImplicit(True)
473
+ atom.SetFormalCharge(-1)
474
+ out = rw.GetMol()
475
+ Chem.SanitizeMol(out)
476
+ return out, sorted(targets)
477
+
478
+
479
+ def _clear_pseudo_stereo(mol: Chem.Mol) -> None:
480
+ """Drop stereo on P / S centres that only look chiral.
481
+
482
+ A phosphate drawn ``P(=O)(O)`` distinguishes two oxygens that are
483
+ equivalent by resonance; the 3D coordinates then yield an R/S label, and a
484
+ wedge, that means nothing chemically.
485
+ """
486
+ changed = False
487
+ for atom in mol.GetAtoms():
488
+ if atom.GetSymbol() not in ("P", "S") or atom.GetChiralTag() == Chem.ChiralType.CHI_UNSPECIFIED:
489
+ continue
490
+ terminal_o = [n for n in atom.GetNeighbors() if n.GetSymbol() in ("O", "S") and n.GetDegree() == 1]
491
+ if len(terminal_o) >= 2:
492
+ atom.SetChiralTag(Chem.ChiralType.CHI_UNSPECIFIED)
493
+ changed = True
494
+ if changed:
495
+ Chem.AssignStereochemistry(mol, cleanIt=True, force=True)
496
+
497
+
498
+ def build_ligand(atoms: Sequence[Atom], smiles: str | None = None, ionize_acids: bool = True) -> Ligand:
499
+ """Build a :class:`Ligand` from structure atoms and an optional SMILES template.
500
+
501
+ Hydrogens present in the structure are not drawn; the diagram is drawn on the
502
+ heavy-atom skeleton with hydrogen counts taken from the template.
503
+
504
+ A SMILES can fit the atoms in more than one way: the bonds of the structure have
505
+ no orders, and without them the ketone and the hydroxyl of 4-hydroxycyclohexanone
506
+ are alike. The way is taken whose bond orders agree best with the bond lengths of
507
+ the structure and, where the file has hydrogens, with the hydrogens on each atom;
508
+ where the structure does not tell two ways apart, the first, and ``diagnostics``
509
+ says so. The ends of one group (the two oxygens of a carboxylate) are one group
510
+ either way: they lie as the first way has them, whatever their bond lengths,
511
+ unless the hydrogens of the file say which of them has one.
512
+
513
+ With ``ionize_acids`` (default) carboxylic, phosphoric and sulfonic acid
514
+ groups are deprotonated for display, as they are at physiological pH.
515
+ """
516
+ heavy = [a for a in atoms if a.element not in ("H", "D")]
517
+ hydrogens = [a for a in atoms if a.element in ("H", "D")]
518
+ if not heavy:
519
+ raise LigandBuildError("ligand has no heavy atoms")
520
+ names = [a.name for a in heavy]
521
+ if len(set(names)) != len(names):
522
+ dup = sorted({n for n in names if names.count(n) > 1})
523
+ raise LigandBuildError(f"ligand atom names are not unique: {', '.join(dup[:6])}")
524
+ coords = np.array([a.xyz for a in heavy], dtype=float)
525
+ diagnostics: list[str] = []
526
+
527
+ with quiet_rdkit():
528
+ template: Chem.Mol | None = None
529
+ if smiles:
530
+ template = Chem.MolFromSmiles(smiles)
531
+ if template is None:
532
+ raise LigandBuildError(f"SMILES does not parse: {smiles!r}")
533
+ for a in template.GetAtoms():
534
+ a.SetAtomMapNum(0) # ([CH3:1]: which atom is which in a reaction, nothing of the molecule)
535
+ template = _fit_template(template, len(heavy), diagnostics)
536
+
537
+ if len(heavy) == 1:
538
+ m = _seed_mol(heavy)
539
+ atom = m.GetAtomWithIdx(0)
540
+ if template is not None and template.GetNumAtoms() == 1 \
541
+ and template.GetAtomWithIdx(0).GetSymbol() == atom.GetSymbol():
542
+ t = template.GetAtomWithIdx(0)
543
+ atom.SetFormalCharge(t.GetFormalCharge())
544
+ atom.SetNumExplicitHs(t.GetTotalNumHs())
545
+ elif template is not None:
546
+ diagnostics.append("SMILES does not describe the single ligand atom in the structure; ignored")
547
+ mol = m.GetMol()
548
+ mol.UpdatePropertyCache(strict=False)
549
+ return Ligand(mol=mol, names=names, coords3d=coords, bond_source="single-atom",
550
+ smiles=smiles, diagnostics=diagnostics)
551
+
552
+ coordination: list[tuple[int, int]] = []
553
+ artefacts: list[tuple[int, int]] = []
554
+ source = "template"
555
+ built = _apply_template(heavy, template, diagnostics, hydrogens) if template is not None else None
556
+ if built is not None:
557
+ mol, coordination, artefacts = built
558
+ else:
559
+ if template is not None:
560
+ diagnostics.append(
561
+ "the SMILES template does not match the ligand in the structure "
562
+ f"({template.GetNumAtoms()} template atoms, {len(heavy)} structure atoms); it was not used")
563
+ mol, source = _from_geometry(heavy, hydrogens, diagnostics)
564
+
565
+ ionized: list[int] = []
566
+ if ionize_acids and source in ("template", "geometry"):
567
+ mol, ionized = _ionize_acids(mol)
568
+
569
+ stereo: list[str] = []
570
+ if source != "connectivity":
571
+ try:
572
+ Chem.AssignStereochemistryFrom3D(mol)
573
+ _clear_pseudo_stereo(mol)
574
+ except Exception: # pragma: no cover - defensive, RDKit rarely fails here
575
+ diagnostics.append("stereochemistry could not be perceived from the 3D coordinates")
576
+ if template is not None and source == "template":
577
+ stereo = _compare_stereo(mol, template, names)
578
+ if stereo:
579
+ diagnostics.append(
580
+ f"{len(stereo)} stereocentre(s) differ between the model and the SMILES: " + "; ".join(stereo))
581
+ return Ligand(mol=mol, names=names, coords3d=coords, bond_source=source, smiles=smiles,
582
+ coordination=sorted(coordination), artefact_bonds=sorted(artefacts),
583
+ stereo_mismatches=stereo, ionized=ionized, diagnostics=diagnostics)
bindview/near.py ADDED
@@ -0,0 +1,67 @@
1
+ """Distances between atoms in space, a block of rows at a time.
2
+
3
+ ``np.linalg.norm(a[:, None, :] - b[None, :, :], axis=2)`` holds the difference of every pair before it
4
+ holds one distance: rows of ``a`` times rows of ``b`` times three numbers. For a ligand against its pocket
5
+ that is nothing; for a chain of a thousand residues against a complex it is gigabytes. The functions here
6
+ give the same numbers, pair for pair to the last bit (the arithmetic of a pair does not depend on the
7
+ block it is in), and never hold more than :data:`BLOCK` numbers of differences at once.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from typing import Iterator
13
+
14
+ import numpy as np
15
+
16
+ __all__ = ["BLOCK", "distance_matrix", "nearest_distance", "pairs_within"]
17
+
18
+ #: Numbers in one block of differences: 8 MB of floats (the square and the sum that follow are of that size too).
19
+ BLOCK = 1_000_000
20
+
21
+
22
+ def _points(xyz: object) -> np.ndarray:
23
+ return np.asarray(xyz, dtype=float).reshape(-1, 3)
24
+
25
+
26
+ def _blocks(a: np.ndarray, b: np.ndarray) -> Iterator[tuple[int, np.ndarray]]:
27
+ """``(first row, distances)`` from a block of rows of ``a`` to every row of ``b``."""
28
+ rows = max(1, BLOCK // (3 * max(1, len(b))))
29
+ for start in range(0, len(a), rows):
30
+ yield start, np.linalg.norm(a[start:start + rows, None, :] - b[None, :, :], axis=2)
31
+
32
+
33
+ def distance_matrix(a: object, b: object) -> np.ndarray:
34
+ """The distance from each point of ``a`` to each of ``b``: ``(len(a), len(b))``."""
35
+ a, b = _points(a), _points(b)
36
+ out = np.empty((len(a), len(b)), dtype=float)
37
+ for start, d in _blocks(a, b):
38
+ out[start:start + len(d)] = d
39
+ return out
40
+
41
+
42
+ def nearest_distance(a: object, b: object) -> np.ndarray:
43
+ """For each point of ``a`` the distance to the nearest point of ``b``; infinite where ``b`` has none."""
44
+ a, b = _points(a), _points(b)
45
+ out = np.full(len(a), np.inf, dtype=float)
46
+ if len(b):
47
+ for start, d in _blocks(a, b):
48
+ out[start:start + len(d)] = d.min(axis=1)
49
+ return out
50
+
51
+
52
+ def pairs_within(a: object, b: object, cutoff: float) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
53
+ """The pairs of a point of ``a`` and a point of ``b`` at most ``cutoff`` apart: the index in ``a``, the
54
+ index in ``b`` and the distance, in the order of the first index and then of the second."""
55
+ a, b = _points(a), _points(b)
56
+ first: list[np.ndarray] = []
57
+ second: list[np.ndarray] = []
58
+ apart: list[np.ndarray] = []
59
+ if len(b):
60
+ for start, d in _blocks(a, b):
61
+ i, j = np.nonzero(d <= cutoff)
62
+ first.append(i + start)
63
+ second.append(j)
64
+ apart.append(d[i, j])
65
+ if not first:
66
+ return np.zeros(0, dtype=int), np.zeros(0, dtype=int), np.zeros(0, dtype=float)
67
+ return np.concatenate(first), np.concatenate(second), np.concatenate(apart)