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.
- bindview/__init__.py +88 -0
- bindview/__main__.py +6 -0
- bindview/align.py +493 -0
- bindview/arrange.js +347 -0
- bindview/arrange.py +248 -0
- bindview/backends.py +290 -0
- bindview/basepairs.py +1711 -0
- bindview/chains.py +264 -0
- bindview/chem.py +57 -0
- bindview/clearance.py +123 -0
- bindview/cli.py +990 -0
- bindview/compare.py +1854 -0
- bindview/confidence.py +531 -0
- bindview/consensus.py +303 -0
- bindview/covalent.py +220 -0
- bindview/depict.py +790 -0
- bindview/detect.py +378 -0
- bindview/diagram.py +1891 -0
- bindview/distance_table.py +589 -0
- bindview/ensemble.py +787 -0
- bindview/errors.py +47 -0
- bindview/exposure.py +207 -0
- bindview/features.py +179 -0
- bindview/fingerprint.py +469 -0
- bindview/fragments.py +304 -0
- bindview/geometry.py +482 -0
- bindview/graph.py +611 -0
- bindview/graphbuild.py +431 -0
- bindview/interactions.py +418 -0
- bindview/interactive.py +334 -0
- bindview/interface.py +1329 -0
- bindview/ions.py +155 -0
- bindview/layout/__init__.py +15 -0
- bindview/layout/body.py +421 -0
- bindview/layout/engine.py +1084 -0
- bindview/layout/field.py +261 -0
- bindview/ligand.py +583 -0
- bindview/near.py +67 -0
- bindview/options.py +92 -0
- bindview/pae.py +991 -0
- bindview/peptide.py +610 -0
- bindview/plane.py +320 -0
- bindview/polymer.py +678 -0
- bindview/py.typed +0 -0
- bindview/report.py +1407 -0
- bindview/residues.py +296 -0
- bindview/resolve.py +493 -0
- bindview/scene.py +239 -0
- bindview/solvent.py +254 -0
- bindview/structure.py +1145 -0
- bindview/styles/__init__.py +2 -0
- bindview/styles/absence.py +180 -0
- bindview/styles/base.py +2128 -0
- bindview/styles/closeup.py +146 -0
- bindview/styles/detailed.py +690 -0
- bindview/styles/ligand_draw.py +289 -0
- bindview/styles/mixed.py +70 -0
- bindview/styles/polymer_draw.py +354 -0
- bindview/styles/rings.py +75 -0
- bindview/styles/schematic.py +311 -0
- bindview/styles/summary.py +147 -0
- bindview/svg.py +310 -0
- bindview/textmetrics.py +64 -0
- bindview/theme.py +317 -0
- bindview-0.1.0.dist-info/METADATA +270 -0
- bindview-0.1.0.dist-info/RECORD +70 -0
- bindview-0.1.0.dist-info/WHEEL +4 -0
- bindview-0.1.0.dist-info/entry_points.txt +2 -0
- bindview-0.1.0.dist-info/licenses/LICENSE +21 -0
- bindview-0.1.0.dist-info/licenses/NOTICE +48 -0
bindview/consensus.py
ADDED
|
@@ -0,0 +1,303 @@
|
|
|
1
|
+
"""What the models of an ensemble agree on, counted by residue.
|
|
2
|
+
|
|
3
|
+
:meth:`bindview.ensemble.Ensemble.diagram` draws one model and weighs each of its contacts by the share of the
|
|
4
|
+
models that make it. Where the models differ much, that hides what they agree on. A residue that nearly all of
|
|
5
|
+
them hold the ligand with, each by another atom, has several faint lines; and one that the drawn model happens
|
|
6
|
+
to miss has none, however many of the others contact it. Here a *residue* is counted, and all the models are
|
|
7
|
+
drawn (:meth:`bindview.ensemble.Ensemble.consensus`).
|
|
8
|
+
|
|
9
|
+
The rules:
|
|
10
|
+
|
|
11
|
+
**A residue is contacted in a model** that has any record with it which is attached to the ligand. Its share is a
|
|
12
|
+
count over the tables and depends on nothing else.
|
|
13
|
+
|
|
14
|
+
**The parts of the ligand** (:func:`ligand_parts`). A line goes to a part, not to an atom: whether a lysine is on
|
|
15
|
+
one oxygen of a phosphate or on the other is no difference, and a model often calls the contact a hydrogen bond in
|
|
16
|
+
one sample and a salt bridge in the next. A part is (1) the rings that share atoms; (2) an end group: a phosphorus
|
|
17
|
+
or sulphur with its terminal oxygens and nitrogens, or another atom with two or more such ends (a carboxylate, an
|
|
18
|
+
amidine, a nitro group); (3) a piece of :data:`PIECE` atoms or more of what is left. A smaller piece goes to the
|
|
19
|
+
part that is nearest along the bonds, atom by atom.
|
|
20
|
+
|
|
21
|
+
**A line** stands for the models that have any contact between the residue and that part, and has the colour of the
|
|
22
|
+
kind that most of them make there (of two that equally many make, a covalent bond or a coordination before the others),
|
|
23
|
+
on the atoms that most of them make it with. A residue that is drawn as atoms has
|
|
24
|
+
one line for each of its sites (an atom, a ring, a charged group): to the part that most of the models have it on,
|
|
25
|
+
where at least half of the models that contact the residue do. A residue with no such line has the one that is made
|
|
26
|
+
most. (Half of the residue's own models, and no share of all the models: a share of its own for lines would be one
|
|
27
|
+
more number to explain, and ``least`` would draw lines that a third of a residue's models make.)
|
|
28
|
+
|
|
29
|
+
**Which end is which.** Two ends of a molecule can be the same (the two adenosines of AP5A), and which of them a
|
|
30
|
+
model calls A is a convention. Every model's atoms are named by the symmetry of the molecule that makes its contacts
|
|
31
|
+
agree best with those of the others, starting from the model that is drawn (:func:`matched`). A molecule without
|
|
32
|
+
symmetry has nothing to choose, and the shares of the residues do not depend on it. Those of the lines can only
|
|
33
|
+
rise by it, which the figure says where a model was renamed.
|
|
34
|
+
|
|
35
|
+
**What is drawn how.** A residue that fewer than ``least`` of the models contact is left out, and named. From the
|
|
36
|
+
share ``atoms`` on a residue is drawn as atoms, if any of its lines has a direction. Any other is a ring alone,
|
|
37
|
+
beside the part of the ligand that most of the models have it on, without a line.
|
|
38
|
+
"""
|
|
39
|
+
|
|
40
|
+
from __future__ import annotations
|
|
41
|
+
|
|
42
|
+
from collections import Counter, defaultdict
|
|
43
|
+
from dataclasses import dataclass, field, replace
|
|
44
|
+
from typing import TYPE_CHECKING, Any, Callable, Sequence
|
|
45
|
+
|
|
46
|
+
import numpy as np
|
|
47
|
+
|
|
48
|
+
from .fingerprint import TYPE_ORDER
|
|
49
|
+
from .interactions import Interaction, InteractionType
|
|
50
|
+
from .ligand import Ligand
|
|
51
|
+
from .residues import format_residue_label
|
|
52
|
+
from .resolve import ResolvedInteraction
|
|
53
|
+
|
|
54
|
+
if TYPE_CHECKING:
|
|
55
|
+
from .ensemble import Ensemble
|
|
56
|
+
|
|
57
|
+
__all__ = ["ResidueShare", "ligand_parts", "residue_shares", "PIECE"]
|
|
58
|
+
|
|
59
|
+
#: A piece of the ligand between its rings and end groups is a part of its own from this many atoms on.
|
|
60
|
+
PIECE = 4
|
|
61
|
+
#: The search for the naming that agrees best ends by itself after a few turns; at most this many.
|
|
62
|
+
_TURNS = 10
|
|
63
|
+
#: Of two kinds that equally many models make, the one that says more: a bond and a coordination before all else.
|
|
64
|
+
_RANK = {t: i for i, t in enumerate(sorted(TYPE_ORDER, key=lambda t: t not in (InteractionType.COVALENT,
|
|
65
|
+
InteractionType.METAL)))}
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
@dataclass(frozen=True)
|
|
69
|
+
class _Made:
|
|
70
|
+
"""One contact of one model, on the atoms of the first model's ligand."""
|
|
71
|
+
|
|
72
|
+
model: int
|
|
73
|
+
atoms: tuple[int, ...]
|
|
74
|
+
resolved: ResolvedInteraction
|
|
75
|
+
|
|
76
|
+
@property
|
|
77
|
+
def kind(self) -> InteractionType:
|
|
78
|
+
return self.resolved.type
|
|
79
|
+
|
|
80
|
+
@property
|
|
81
|
+
def site(self) -> tuple[str, tuple[str, ...]]:
|
|
82
|
+
return (self.resolved.protein.kind, self.resolved.protein.atoms)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
@dataclass(frozen=True)
|
|
86
|
+
class ResidueShare:
|
|
87
|
+
"""A residue, and the models of an ensemble that contact it."""
|
|
88
|
+
|
|
89
|
+
chain: str
|
|
90
|
+
residue_number: int
|
|
91
|
+
insertion_code: str
|
|
92
|
+
residue_name: str
|
|
93
|
+
models: tuple[int, ...] # indices of the models that contact it, ascending
|
|
94
|
+
n_total: int # models in the ensemble
|
|
95
|
+
#: For each kind of contact, how many of the models make one with the residue; the most frequent first.
|
|
96
|
+
kinds: tuple[tuple[InteractionType, int], ...]
|
|
97
|
+
#: For each part of the ligand, the contacts with it.
|
|
98
|
+
places: "dict[int, list[_Made]]" = field(repr=False, compare=False, default_factory=dict)
|
|
99
|
+
|
|
100
|
+
@property
|
|
101
|
+
def n_models(self) -> int:
|
|
102
|
+
"""How many models contact the residue."""
|
|
103
|
+
return len(self.models)
|
|
104
|
+
|
|
105
|
+
@property
|
|
106
|
+
def share(self) -> float:
|
|
107
|
+
"""The share of the models that do."""
|
|
108
|
+
return len(self.models) / self.n_total
|
|
109
|
+
|
|
110
|
+
@property
|
|
111
|
+
def residue_id(self) -> tuple[str, int, str]:
|
|
112
|
+
"""``(chain, number, insertion code)`` of the residue."""
|
|
113
|
+
return (self.chain, self.residue_number, self.insertion_code)
|
|
114
|
+
|
|
115
|
+
@property
|
|
116
|
+
def residue_label(self) -> str:
|
|
117
|
+
"""The residue as a figure names it."""
|
|
118
|
+
return format_residue_label(self.residue_name, self.residue_number, self.insertion_code, None)
|
|
119
|
+
|
|
120
|
+
@property
|
|
121
|
+
def said(self) -> str:
|
|
122
|
+
"""In words, for a tooltip."""
|
|
123
|
+
kinds = ", ".join(f"{kind.label.lower()} {n}" for kind, n in self.kinds)
|
|
124
|
+
return f"contacted in {self.n_models} of {self.n_total} models ({kinds})"
|
|
125
|
+
|
|
126
|
+
def models_at(self, part: int) -> set[int]:
|
|
127
|
+
"""The models that have it on one part of the ligand."""
|
|
128
|
+
return {m.model for m in self.places.get(part, ())}
|
|
129
|
+
|
|
130
|
+
def kind_at(self, part: int) -> InteractionType:
|
|
131
|
+
"""The kind of contact that most models make with this part of the ligand."""
|
|
132
|
+
models: "dict[InteractionType, set[int]]" = defaultdict(set)
|
|
133
|
+
for m in self.places[part]:
|
|
134
|
+
models[m.kind].add(m.model)
|
|
135
|
+
return max(models, key=lambda kind: (len(models[kind]), -_RANK[kind]))
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def ligand_parts(ligand: Ligand) -> list[tuple[int, ...]]:
|
|
139
|
+
"""The parts of a ligand, as indices of its atoms (see the module)."""
|
|
140
|
+
mol = ligand.mol
|
|
141
|
+
heavy = [a.GetIdx() for a in mol.GetAtoms() if a.GetAtomicNum() > 1]
|
|
142
|
+
seeds: list[set[int]] = []
|
|
143
|
+
for ring in mol.GetRingInfo().AtomRings():
|
|
144
|
+
atoms = set(ring)
|
|
145
|
+
for other in [s for s in seeds if s & atoms]:
|
|
146
|
+
seeds.remove(other)
|
|
147
|
+
atoms |= other
|
|
148
|
+
seeds.append(atoms)
|
|
149
|
+
taken: set[int] = set().union(*seeds) if seeds else set()
|
|
150
|
+
for a in mol.GetAtoms():
|
|
151
|
+
if a.GetIdx() in taken:
|
|
152
|
+
continue
|
|
153
|
+
ends = [b.GetIdx() for b in a.GetNeighbors()
|
|
154
|
+
if b.GetAtomicNum() in (7, 8) and sum(c.GetAtomicNum() > 1 for c in b.GetNeighbors()) == 1]
|
|
155
|
+
if len(ends) >= 2 or (ends and a.GetAtomicNum() in (15, 16)):
|
|
156
|
+
seeds.append({a.GetIdx(), *ends})
|
|
157
|
+
taken |= seeds[-1]
|
|
158
|
+
seeds.sort(key=min)
|
|
159
|
+
left = set(heavy) - taken
|
|
160
|
+
pieces: list[set[int]] = []
|
|
161
|
+
while left:
|
|
162
|
+
piece, front = set(), [min(left)]
|
|
163
|
+
while front:
|
|
164
|
+
i = front.pop()
|
|
165
|
+
if i in piece:
|
|
166
|
+
continue
|
|
167
|
+
piece.add(i)
|
|
168
|
+
front.extend(b.GetIdx() for b in mol.GetAtomWithIdx(i).GetNeighbors() if b.GetIdx() in left)
|
|
169
|
+
left -= piece
|
|
170
|
+
pieces.append(piece)
|
|
171
|
+
for piece in pieces:
|
|
172
|
+
held = any(b.GetIdx() in taken for i in piece for b in mol.GetAtomWithIdx(i).GetNeighbors())
|
|
173
|
+
if len(piece) >= PIECE or not held:
|
|
174
|
+
seeds.append(piece)
|
|
175
|
+
owner = {i: k for k, atoms in enumerate(seeds) for i in atoms}
|
|
176
|
+
front = sorted(owner, key=lambda i: (owner[i], i))
|
|
177
|
+
while front: # breadth first: an atom goes to the part nearest to it
|
|
178
|
+
fresh: list[int] = []
|
|
179
|
+
for i in front:
|
|
180
|
+
for b in mol.GetAtomWithIdx(i).GetNeighbors():
|
|
181
|
+
if b.GetAtomicNum() > 1 and b.GetIdx() not in owner:
|
|
182
|
+
owner[b.GetIdx()] = owner[i]
|
|
183
|
+
fresh.append(b.GetIdx())
|
|
184
|
+
front = fresh
|
|
185
|
+
out: "dict[int, list[int]]" = defaultdict(list)
|
|
186
|
+
for i in sorted(owner):
|
|
187
|
+
out[owner[i]].append(i)
|
|
188
|
+
return [tuple(out[k]) for k in sorted(out)]
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def matched(ens: "Ensemble", symmetries: np.ndarray) -> tuple["dict[tuple, list[_Made]]", list[int]]:
|
|
192
|
+
"""Every attached contact of every model by its residue, on the atoms of the first model's ligand; and for
|
|
193
|
+
each model which of the symmetries its atoms are named by (the first is the names as they are)."""
|
|
194
|
+
first = ens.diagrams[0].ligand
|
|
195
|
+
place = {name: i for i, name in enumerate(first.names)}
|
|
196
|
+
raw: "list[list[tuple[tuple, tuple[int, ...], ResolvedInteraction]]]" = []
|
|
197
|
+
for d in ens.diagrams:
|
|
198
|
+
rows = []
|
|
199
|
+
for r in d.interactions:
|
|
200
|
+
if r.ligand is None:
|
|
201
|
+
continue
|
|
202
|
+
chain = r.residue.chain if r.residue is not None else r.record.chain
|
|
203
|
+
key = (chain, r.record.residue_number, r.record.insertion_code, r.record.residue_name.upper())
|
|
204
|
+
rows.append((key, tuple(place[d.ligand.names[i]] for i in r.ligand.atoms), r))
|
|
205
|
+
raw.append(rows)
|
|
206
|
+
keys = {key: i for i, key in enumerate(sorted({key for rows in raw for key, _, _ in rows}))}
|
|
207
|
+
pairs = [np.array(sorted({(keys[key], a) for key, atoms, _ in rows for a in atoms}), dtype=int).reshape(-1, 2)
|
|
208
|
+
for rows in raw]
|
|
209
|
+
|
|
210
|
+
def seen(k: int, p: int) -> np.ndarray:
|
|
211
|
+
out = np.zeros((len(keys), len(place)), dtype=int)
|
|
212
|
+
out[pairs[k][:, 0], symmetries[p][pairs[k][:, 1]]] = 1
|
|
213
|
+
return out
|
|
214
|
+
|
|
215
|
+
def best(k: int, others: np.ndarray) -> int:
|
|
216
|
+
# The first of equal ones: the names as they are, if they do as well as any.
|
|
217
|
+
return int(others[pairs[k][:, 0][None, :], symmetries[:, pairs[k][:, 1]]].sum(axis=1).argmax())
|
|
218
|
+
|
|
219
|
+
choice = [0] * ens.n
|
|
220
|
+
if len(symmetries) > 1 and keys:
|
|
221
|
+
known = seen(ens.member, 0)
|
|
222
|
+
choice = [0 if k == ens.member else best(k, known) for k in range(ens.n)]
|
|
223
|
+
for _ in range(_TURNS):
|
|
224
|
+
# Every model against all the others as they are named now; all at once, so that the order of
|
|
225
|
+
# the models decides nothing. The drawn one keeps its names: it is the one the others are named by.
|
|
226
|
+
total = sum((seen(k, choice[k]) for k in range(ens.n)), np.zeros_like(known))
|
|
227
|
+
new = [0 if k == ens.member else best(k, total - seen(k, choice[k])) for k in range(ens.n)]
|
|
228
|
+
if new == choice:
|
|
229
|
+
break
|
|
230
|
+
choice = new
|
|
231
|
+
made: "dict[tuple, list[_Made]]" = {}
|
|
232
|
+
for k, rows in enumerate(raw):
|
|
233
|
+
for key, atoms, r in rows:
|
|
234
|
+
made.setdefault(key, []).append(_Made(k, tuple(int(symmetries[choice[k]][a]) for a in atoms), r))
|
|
235
|
+
return made, choice
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def residue_shares(ens: "Ensemble", symmetries: np.ndarray) -> tuple[list[ResidueShare], list[int]]:
|
|
239
|
+
"""Every residue that any model contacts, the most frequent first; and the models whose ends were named the
|
|
240
|
+
other way round."""
|
|
241
|
+
made, choice = matched(ens, symmetries)
|
|
242
|
+
owner = {i: k for k, atoms in enumerate(ligand_parts(ens.diagrams[0].ligand)) for i in atoms}
|
|
243
|
+
out = []
|
|
244
|
+
for (chain, number, icode, name), contacts in made.items():
|
|
245
|
+
kinds: "dict[InteractionType, set[int]]" = defaultdict(set)
|
|
246
|
+
places: "dict[int, list[_Made]]" = defaultdict(list)
|
|
247
|
+
for m in contacts:
|
|
248
|
+
kinds[m.kind].add(m.model)
|
|
249
|
+
on = Counter(owner[a] for a in m.atoms if a in owner)
|
|
250
|
+
if on:
|
|
251
|
+
places[min(on, key=lambda p: (-on[p], p))].append(m)
|
|
252
|
+
out.append(ResidueShare(
|
|
253
|
+
chain, number, icode, name, tuple(sorted({m.model for m in contacts})), ens.n,
|
|
254
|
+
tuple((t, len(kinds[t])) for t in sorted(kinds, key=lambda t: (-len(kinds[t]), _RANK[t]))), dict(places)))
|
|
255
|
+
out.sort(key=lambda r: (-r.n_models, r.chain, r.residue_number, r.insertion_code))
|
|
256
|
+
turned = [k for k, p in enumerate(choice)
|
|
257
|
+
if any(owner.get(int(symmetries[p][a])) != owner.get(a) for a in range(len(symmetries[p])))]
|
|
258
|
+
return out, turned
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
def lines_of(ens: "Ensemble", residue: ResidueShare, atoms: bool) -> list[ResolvedInteraction]:
|
|
262
|
+
"""The lines of a residue, on the ligand of the drawn model: see the module."""
|
|
263
|
+
base = ens.diagrams[ens.member]
|
|
264
|
+
names = ens.diagrams[0].ligand.names
|
|
265
|
+
here = {name: i for i, name in enumerate(base.ligand.names)}
|
|
266
|
+
order = sorted(residue.places, key=lambda p: (-len(residue.models_at(p)), p))
|
|
267
|
+
wanted = [p for p in order if 2 * len(residue.models_at(p)) >= residue.n_models] if atoms else []
|
|
268
|
+
sites: set = set()
|
|
269
|
+
out = []
|
|
270
|
+
for p in wanted or order[:1]:
|
|
271
|
+
kind = residue.kind_at(p)
|
|
272
|
+
there = [m for m in residue.places[p] if m.kind is kind]
|
|
273
|
+
on = _most(there, lambda m: m.atoms)
|
|
274
|
+
there = [m for m in there if m.atoms == on]
|
|
275
|
+
site = _most(there, lambda m: m.site)
|
|
276
|
+
if site in sites:
|
|
277
|
+
continue
|
|
278
|
+
sites.add(site)
|
|
279
|
+
# A line is attached as the models' own contacts are, to the same atoms: nothing is looked for.
|
|
280
|
+
of = next(m for m in there if m.site == site).resolved
|
|
281
|
+
assert of.ligand is not None
|
|
282
|
+
one = len(on) == 1
|
|
283
|
+
out.append(replace(
|
|
284
|
+
of, ligand=replace(of.ligand, atoms=tuple(here[names[a]] for a in on)), method="named", delta=None,
|
|
285
|
+
computed_distance=None, notes=[], absent=False,
|
|
286
|
+
record=Interaction(
|
|
287
|
+
type=kind, residue_number=residue.residue_number, residue_name=residue.residue_name,
|
|
288
|
+
chain=residue.chain, insertion_code=residue.insertion_code,
|
|
289
|
+
occupancy=len(residue.models_at(p)) / ens.n,
|
|
290
|
+
ligand_is_donor=_most(there, lambda m: m.resolved.record.ligand_is_donor),
|
|
291
|
+
ligand_atom=names[on[0]] if one else None, ligand_atoms=() if one else tuple(names[a] for a in on),
|
|
292
|
+
protein_atom=site[1][0] if site[0] == "atom" and site[1] else None,
|
|
293
|
+
protein_atoms=() if site[0] == "atom" else tuple(site[1]))))
|
|
294
|
+
return out
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
def _most(made: "Sequence[_Made]", of: "Callable[[_Made], Any]") -> Any:
|
|
298
|
+
"""What most of the models have: a model counts once, however many records it has. Of what equally
|
|
299
|
+
many models have, the first."""
|
|
300
|
+
models: "dict[Any, set[int]]" = {}
|
|
301
|
+
for m in made:
|
|
302
|
+
models.setdefault(of(m), set()).add(m.model)
|
|
303
|
+
return max(models, key=lambda value: len(models[value]))
|
bindview/covalent.py
ADDED
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
"""A ligand that is bound to its target by a covalent bond.
|
|
2
|
+
|
|
3
|
+
A contact table has no such row: what finds contacts looks for pairs of atoms that are near each other and not
|
|
4
|
+
bonded. A covalent inhibitor is bonded, and its figure has to say so. ``Diagram.from_structure(covalent=True)``
|
|
5
|
+
looks for the bond in the model:
|
|
6
|
+
|
|
7
|
+
* **declared**: a ``_struct_conn`` row of a covalent kind (mmCIF), a ``LINK`` record (PDB);
|
|
8
|
+
* **by distance**: an atom of the ligand within :data:`TOLERANCE` ångström of the sum of the covalent radii of a
|
|
9
|
+
nitrogen, oxygen, sulphur or selenium of a residue. A model that was made (a co-fold, an ensemble) declares
|
|
10
|
+
nothing.
|
|
11
|
+
|
|
12
|
+
The bond becomes a row of the kind ``covalent``, drawn as a bond on a highlight from atom to atom. A table can
|
|
13
|
+
bring such rows itself. Two things follow from the bond, for a row that was found and for one that was brought:
|
|
14
|
+
|
|
15
|
+
* a contact between atoms that the bond joins or brings within three bonds of each other (the cysteine's carbon and
|
|
16
|
+
the carbon it is bound through) is the bond's and no contact, and is left out;
|
|
17
|
+
* the ligand is drawn as it is bound. A SMILES is as a rule that of the free ligand: where the atom that is bound
|
|
18
|
+
has a multiple bond there, and the model has that bond at the length of a lower order (the double bond of an
|
|
19
|
+
acrylamide at 1.5 Å), it is drawn at the lower order (:func:`as_bound`).
|
|
20
|
+
|
|
21
|
+
Off unless it is asked for: what is drawn of a model does not change by itself.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
from __future__ import annotations
|
|
25
|
+
|
|
26
|
+
from collections import deque
|
|
27
|
+
from dataclasses import dataclass
|
|
28
|
+
from typing import TYPE_CHECKING, Iterable, Sequence
|
|
29
|
+
|
|
30
|
+
import numpy as np
|
|
31
|
+
from rdkit import Chem
|
|
32
|
+
|
|
33
|
+
from .chem import covalent_radius, is_metal, quiet_rdkit
|
|
34
|
+
from .exposure import WATER_NAMES
|
|
35
|
+
from .interactions import Interaction, InteractionType
|
|
36
|
+
from .ligand import Ligand
|
|
37
|
+
from .structure import Atom, ResidueKey, Structure
|
|
38
|
+
|
|
39
|
+
if TYPE_CHECKING: # pragma: no cover
|
|
40
|
+
from .resolve import ResolvedInteraction
|
|
41
|
+
|
|
42
|
+
__all__ = ["CovalentBond", "covalent_bonds", "as_bound", "drop_bonded", "TOLERANCE"]
|
|
43
|
+
|
|
44
|
+
T = InteractionType
|
|
45
|
+
#: How much longer than the sum of the covalent radii a bond that the file does not declare may be, in ångström.
|
|
46
|
+
TOLERANCE = 0.25
|
|
47
|
+
#: ... and how long one is at most that it declares.
|
|
48
|
+
DECLARED_AT_MOST = 2.6
|
|
49
|
+
#: A contact between atoms that are at most this many bonds apart is no contact.
|
|
50
|
+
BONDED = 3
|
|
51
|
+
_NUCLEOPHILES = frozenset({"N", "O", "S", "Se"})
|
|
52
|
+
#: The two atoms of the bond that joins a residue to the next of its chain: of a protein, of a nucleic acid.
|
|
53
|
+
_CHAIN_BONDS = ({"N", "C"}, {"P", "O3'"})
|
|
54
|
+
#: The length above which a bond of the first order (or bond) is taken for one of the second: halfway between the two.
|
|
55
|
+
_LENGTHS: "dict[frozenset[str], dict[int, float]]" = {
|
|
56
|
+
frozenset({"C"}): {3: 1.27, 2: 1.43},
|
|
57
|
+
frozenset({"C", "N"}): {3: 1.22, 2: 1.37},
|
|
58
|
+
frozenset({"C", "O"}): {2: 1.32},
|
|
59
|
+
frozenset({"C", "S"}): {2: 1.72},
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
@dataclass(frozen=True)
|
|
64
|
+
class CovalentBond:
|
|
65
|
+
"""A bond between an atom of the ligand and an atom of a residue."""
|
|
66
|
+
|
|
67
|
+
ligand_atom: str
|
|
68
|
+
residue: ResidueKey
|
|
69
|
+
resname: str
|
|
70
|
+
atom: str
|
|
71
|
+
distance: float
|
|
72
|
+
declared: bool
|
|
73
|
+
|
|
74
|
+
def as_interaction(self) -> Interaction:
|
|
75
|
+
return Interaction(type=T.COVALENT, residue_number=self.residue.number, residue_name=self.resname,
|
|
76
|
+
chain=self.residue.chain, insertion_code=self.residue.icode, protein_atom=self.atom,
|
|
77
|
+
ligand_atom=self.ligand_atom, distance=round(self.distance, 2))
|
|
78
|
+
|
|
79
|
+
def __str__(self) -> str:
|
|
80
|
+
how = "declared by the file" if self.declared else "found by distance"
|
|
81
|
+
return f"{self.ligand_atom} is bound to {self.resname.capitalize()}{self.residue.number} {self.atom} " \
|
|
82
|
+
f"({self.distance:.2f} Å, {how})"
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def covalent_bonds(structure: Structure, ligand: ResidueKey) -> list[CovalentBond]:
|
|
86
|
+
"""The covalent bonds between a residue of the structure and everything else in it, a water and a metal left
|
|
87
|
+
out, and the bonds of a chain the residue is part of (the peptide bond or the phosphodiester to the residue
|
|
88
|
+
before it and to the one after it): the declared ones first, then those by distance."""
|
|
89
|
+
own = {a.name: a for a in structure.residue_atoms(ligand) if a.element not in ("H", "D")}
|
|
90
|
+
out: list[CovalentBond] = []
|
|
91
|
+
chain = [k for k in structure.residues() if k.chain == ligand.chain]
|
|
92
|
+
beside: "set[ResidueKey]" = set() # the residues before and after it in the file
|
|
93
|
+
if ligand in chain:
|
|
94
|
+
at = chain.index(ligand)
|
|
95
|
+
beside = set(chain[max(at - 1, 0):at + 2]) - {ligand}
|
|
96
|
+
|
|
97
|
+
def add(mine: Atom, other: Atom, declared: bool) -> None:
|
|
98
|
+
if is_metal(mine.element) or is_metal(other.element) or other.resname.upper() in WATER_NAMES:
|
|
99
|
+
return
|
|
100
|
+
if other.residue in beside and {mine.name.replace("*", "'"), other.name.replace("*", "'")} in _CHAIN_BONDS:
|
|
101
|
+
return # the next residue of its own chain
|
|
102
|
+
if any(b.ligand_atom == mine.name and b.residue == other.residue and b.atom == other.name for b in out):
|
|
103
|
+
return
|
|
104
|
+
d = float(np.linalg.norm(np.array(mine.xyz) - np.array(other.xyz)))
|
|
105
|
+
if declared and d > DECLARED_AT_MOST:
|
|
106
|
+
return
|
|
107
|
+
out.append(CovalentBond(mine.name, other.residue, other.resname, other.name, d, declared))
|
|
108
|
+
|
|
109
|
+
for link in structure.links:
|
|
110
|
+
for (me, my_atom), (it, its_atom) in (((link.a, link.a_atom), (link.b, link.b_atom)),
|
|
111
|
+
((link.b, link.b_atom), (link.a, link.a_atom))):
|
|
112
|
+
if me == ligand and it != ligand and my_atom in own:
|
|
113
|
+
other = structure.atom_by_name(it, its_atom)
|
|
114
|
+
if other is not None:
|
|
115
|
+
add(own[my_atom], other, True)
|
|
116
|
+
others = [a for a in structure.atoms if a.residue != ligand and a.element in _NUCLEOPHILES
|
|
117
|
+
and a.resname.upper() not in WATER_NAMES]
|
|
118
|
+
if own and others:
|
|
119
|
+
there = np.array([a.xyz for a in others], dtype=float)
|
|
120
|
+
bound = {(b.ligand_atom) for b in out}
|
|
121
|
+
for mine in own.values():
|
|
122
|
+
if mine.name in bound:
|
|
123
|
+
continue
|
|
124
|
+
d = np.linalg.norm(there - np.array(mine.xyz, dtype=float), axis=1)
|
|
125
|
+
k = int(np.argmin(d))
|
|
126
|
+
if d[k] <= covalent_radius(mine.element) + covalent_radius(others[k].element) + TOLERANCE:
|
|
127
|
+
add(mine, others[k], False)
|
|
128
|
+
return out
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def as_bound(lig: Ligand, atom: int) -> "str | None":
|
|
132
|
+
"""Draw the ligand as it is bound through ``atom``: the multiple bond there at the order its length in the
|
|
133
|
+
model says. Changes ``lig.mol``; returns what was done in words, or ``None``."""
|
|
134
|
+
if lig.bond_source != "template":
|
|
135
|
+
return None
|
|
136
|
+
mol = Chem.RWMol(lig.mol)
|
|
137
|
+
for bond in mol.GetAtomWithIdx(atom).GetBonds():
|
|
138
|
+
order = {Chem.BondType.DOUBLE: 2, Chem.BondType.TRIPLE: 3}.get(bond.GetBondType())
|
|
139
|
+
other = bond.GetOtherAtomIdx(atom)
|
|
140
|
+
if order is None:
|
|
141
|
+
continue
|
|
142
|
+
longest = _LENGTHS.get(frozenset({lig.element(atom), lig.element(other)}), {}).get(order)
|
|
143
|
+
length = float(np.linalg.norm(lig.coords3d[atom] - lig.coords3d[other]))
|
|
144
|
+
if longest is None or length <= longest:
|
|
145
|
+
continue
|
|
146
|
+
bond.SetBondType(Chem.BondType.SINGLE if order == 2 else Chem.BondType.DOUBLE)
|
|
147
|
+
bond.SetStereo(Chem.BondStereo.STEREONONE)
|
|
148
|
+
for end in (atom, other):
|
|
149
|
+
for b in mol.GetAtomWithIdx(end).GetBonds():
|
|
150
|
+
b.SetBondDir(Chem.BondDir.NONE)
|
|
151
|
+
# The atom that is bound has the new bond in place of the old one's; the other end takes a hydrogen.
|
|
152
|
+
far = mol.GetAtomWithIdx(other)
|
|
153
|
+
far.SetNumExplicitHs(far.GetNumExplicitHs() + 1)
|
|
154
|
+
out = mol.GetMol()
|
|
155
|
+
with quiet_rdkit():
|
|
156
|
+
Chem.SanitizeMol(out)
|
|
157
|
+
Chem.AssignStereochemistry(out, cleanIt=True, force=True)
|
|
158
|
+
lig.mol = out
|
|
159
|
+
was, now = ("double", "single") if order == 2 else ("triple", "double")
|
|
160
|
+
return (f"drawn as bound: the {was} bond {lig.names[atom]}–{lig.names[other]} of the SMILES is {length:.2f} "
|
|
161
|
+
f"Å long in the model, and is drawn {now}")
|
|
162
|
+
bound = mol.GetAtomWithIdx(atom)
|
|
163
|
+
if bound.GetSymbol() in _NUCLEOPHILES and bound.GetNumExplicitHs() > 0 and not bound.GetIsAromatic():
|
|
164
|
+
bound.SetNumExplicitHs(bound.GetNumExplicitHs() - 1) # its hydrogen is where the bond is now
|
|
165
|
+
out = mol.GetMol()
|
|
166
|
+
with quiet_rdkit():
|
|
167
|
+
out.UpdatePropertyCache(strict=False)
|
|
168
|
+
lig.mol = out
|
|
169
|
+
return f"drawn as bound: {lig.names[atom]} without the hydrogen that its bond to the target took the place of"
|
|
170
|
+
return None
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def _steps(pairs: "Iterable[tuple[int, int]]", start: int) -> "dict[int, int]":
|
|
174
|
+
"""How many bonds away from ``start`` every atom is that bonds lead to."""
|
|
175
|
+
near: "dict[int, list[int]]" = {}
|
|
176
|
+
for a, b in pairs:
|
|
177
|
+
near.setdefault(a, []).append(b)
|
|
178
|
+
near.setdefault(b, []).append(a)
|
|
179
|
+
out, queue = {start: 0}, deque([start])
|
|
180
|
+
while queue:
|
|
181
|
+
a = queue.popleft()
|
|
182
|
+
for b in near.get(a, ()):
|
|
183
|
+
if b not in out:
|
|
184
|
+
out[b] = out[a] + 1
|
|
185
|
+
queue.append(b)
|
|
186
|
+
return out
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def drop_bonded(resolved: "Sequence[ResolvedInteraction]", lig: Ligand, structure: "Structure | None"
|
|
190
|
+
) -> "tuple[list[ResolvedInteraction], list[ResolvedInteraction]]":
|
|
191
|
+
"""The contacts without those between atoms that a covalent bond of the list joins or brings within
|
|
192
|
+
:data:`BONDED` bonds of each other; and those."""
|
|
193
|
+
bonds = [r for r in resolved if r.type is T.COVALENT and r.ligand is not None and r.residue is not None]
|
|
194
|
+
if not bonds or structure is None:
|
|
195
|
+
return list(resolved), []
|
|
196
|
+
mine = [(b.GetBeginAtomIdx(), b.GetEndAtomIdx()) for b in lig.mol.GetBonds()]
|
|
197
|
+
kept: "list[ResolvedInteraction]" = []
|
|
198
|
+
dropped: "list[ResolvedInteraction]" = []
|
|
199
|
+
for r in resolved:
|
|
200
|
+
apart = None
|
|
201
|
+
if r.type is not T.COVALENT and r.ligand is not None and r.residue is not None:
|
|
202
|
+
for b in bonds:
|
|
203
|
+
if b.residue != r.residue or not b.protein.atoms or not r.protein.atoms:
|
|
204
|
+
continue
|
|
205
|
+
atoms = [a for a in structure.residue_atoms(r.residue) if a.element not in ("H", "D")]
|
|
206
|
+
index = {a.name: k for k, a in enumerate(atoms)}
|
|
207
|
+
xyz = np.array([a.xyz for a in atoms], dtype=float)
|
|
208
|
+
d = np.linalg.norm(xyz[:, None, :] - xyz[None, :, :], axis=2)
|
|
209
|
+
theirs = [(i, j) for i in range(len(atoms)) for j in range(i + 1, len(atoms))
|
|
210
|
+
if d[i, j] <= 1.3 * (covalent_radius(atoms[i].element) + covalent_radius(atoms[j].element))]
|
|
211
|
+
if b.protein.atoms[0] not in index:
|
|
212
|
+
continue
|
|
213
|
+
here = _steps(mine, b.ligand.atom) # type: ignore[union-attr]
|
|
214
|
+
there = _steps(theirs, index[b.protein.atoms[0]])
|
|
215
|
+
steps = [here[i] + 1 + there[index[n]] for i in r.ligand.atoms if i in here
|
|
216
|
+
for n in r.protein.atoms if n in index and index[n] in there]
|
|
217
|
+
if steps and (apart is None or min(steps) < apart):
|
|
218
|
+
apart = min(steps)
|
|
219
|
+
(dropped if apart is not None and apart <= BONDED else kept).append(r)
|
|
220
|
+
return kept, dropped
|