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/ensemble.py
ADDED
|
@@ -0,0 +1,787 @@
|
|
|
1
|
+
"""One ligand in its pocket, from several models of the same complex.
|
|
2
|
+
|
|
3
|
+
A :class:`~bindview.compare.Comparison` holds several *ligands* of one pocket. An
|
|
4
|
+
:class:`Ensemble` holds the other thing that comes in several: *models* of one
|
|
5
|
+
complex -- the samples of a co-fold, the conformations a generative model
|
|
6
|
+
draws, the members of an NMR bundle or the frames of a trajectory written out
|
|
7
|
+
as files, several crystal structures. It answers one question: in how many of
|
|
8
|
+
the models is each contact made, and at what distance?
|
|
9
|
+
|
|
10
|
+
The answer is data (:attr:`Ensemble.contacts`) and one figure
|
|
11
|
+
(:meth:`Ensemble.diagram`): an ordinary :class:`~bindview.diagram.Diagram` of one
|
|
12
|
+
member in which every contact carries, as its ``occupancy``, the share of the
|
|
13
|
+
models that make it. Occupancy is drawn as it always is (weight and opacity of
|
|
14
|
+
the line, :func:`bindview.confidence.occupancy_factors`); nothing here draws.
|
|
15
|
+
|
|
16
|
+
Three rules decide the result, and none of them is a threshold:
|
|
17
|
+
|
|
18
|
+
**Which member is drawn.** The medoid: the model whose ligand lies nearest to
|
|
19
|
+
the others'. Every two models are superposed on their pocket
|
|
20
|
+
(:func:`bindview.align.pocket_transforms_between`), and the distance between them is the
|
|
21
|
+
RMSD of the ligand's heavy atoms after that, without fitting the ligand itself
|
|
22
|
+
and taking the smallest value over the symmetries of the ligand's graph, so
|
|
23
|
+
that a flipped phenyl ring or a turned CF3 is not a difference. ``member=``
|
|
24
|
+
overrules the choice. The order of the models decides ties and nothing else.
|
|
25
|
+
|
|
26
|
+
**When two contacts are one contact.** Same residue, same interaction type,
|
|
27
|
+
same ligand atoms -- with three things said about "same":
|
|
28
|
+
|
|
29
|
+
* ligand atoms that the symmetry of the molecule exchanges count as one atom
|
|
30
|
+
(the fluorines of a CF3, the oxygens of a carboxylate, the two sides of a
|
|
31
|
+
para-substituted ring): a halogen bond made through ``F1`` in two samples
|
|
32
|
+
and through ``F3`` in three is one contact that is always there. Which of a
|
|
33
|
+
phosphate's free oxygens is called ``O1A`` is a convention, and deposited
|
|
34
|
+
structures of one cofactor do not always agree on it;
|
|
35
|
+
* a hydrophobic contact is matched on the residue alone: which carbon a
|
|
36
|
+
detector pairs with which is its bookkeeping, and the figure draws such a
|
|
37
|
+
contact as an arc, not as a line to an atom;
|
|
38
|
+
* the protein atom, the direction of a hydrogen bond and the water of a water
|
|
39
|
+
bridge are not part of it.
|
|
40
|
+
|
|
41
|
+
Occupancy is therefore a count over the contact tables and does not depend on
|
|
42
|
+
the superposition.
|
|
43
|
+
|
|
44
|
+
**A contact the drawn member does not make** is not drawn. A line of a bindview
|
|
45
|
+
figure is a contact of the model it shows, with that model's distance on it.
|
|
46
|
+
Such a contact is a row of :attr:`Ensemble.contacts` with ``in_member`` false,
|
|
47
|
+
and the figure says in a sentence how many there are and names the most
|
|
48
|
+
frequent (:attr:`bindview.diagram.Diagram.remarks`). On request it is drawn
|
|
49
|
+
after all (``Ensemble.diagram(absent="faint")``): faint, with the share of the
|
|
50
|
+
models that make it where a distance would stand, and still not counted as a
|
|
51
|
+
contact of the diagram.
|
|
52
|
+
|
|
53
|
+
Models are read as every structure is: one file a model
|
|
54
|
+
(:func:`bindview.structure.read_structure`), or the models of one file
|
|
55
|
+
(:func:`bindview.structure.read_models`: an NMR bundle, frames written into one
|
|
56
|
+
PDB file). No trajectory format is read. Residues are matched by chain and
|
|
57
|
+
number, as a comparison matches them, and chains are taken as they are named:
|
|
58
|
+
models whose pockets do not carry the same residues are refused, and models of
|
|
59
|
+
a homo-oligomer that name its chains in another order are not put right.
|
|
60
|
+
"""
|
|
61
|
+
|
|
62
|
+
from __future__ import annotations
|
|
63
|
+
|
|
64
|
+
import copy
|
|
65
|
+
import math
|
|
66
|
+
import statistics
|
|
67
|
+
from dataclasses import dataclass, replace
|
|
68
|
+
from pathlib import Path
|
|
69
|
+
from typing import Any, Mapping, Sequence
|
|
70
|
+
|
|
71
|
+
import numpy as np
|
|
72
|
+
from rdkit import Chem
|
|
73
|
+
|
|
74
|
+
from .align import pocket_transforms_between
|
|
75
|
+
from .backends import Polymer
|
|
76
|
+
from .consensus import ResidueShare, lines_of, residue_shares
|
|
77
|
+
from .diagram import DISTANCES, Diagram
|
|
78
|
+
from .errors import EnsembleError, BindviewError
|
|
79
|
+
from .fingerprint import TYPE_ORDER, Fingerprint, FingerprintTable, _write_rows
|
|
80
|
+
from .interactions import Interaction, InteractionType
|
|
81
|
+
from .ligand import Ligand
|
|
82
|
+
from .residues import format_residue_label
|
|
83
|
+
from .resolve import ResolvedInteraction, resolve_interactions
|
|
84
|
+
from .structure import Structure
|
|
85
|
+
|
|
86
|
+
__all__ = ["Ensemble", "EnsembleContact", "symmetry_classes", "contact_key", "MAX_SYMMETRIES", "CONTACT_COLUMNS",
|
|
87
|
+
"ABSENT"]
|
|
88
|
+
|
|
89
|
+
#: What :meth:`Ensemble.diagram` can do with a contact that the drawn member does not make.
|
|
90
|
+
ABSENT = ("named", "faint")
|
|
91
|
+
|
|
92
|
+
#: At most this many symmetries of the ligand's graph are tried for the RMSD of two poses. The
|
|
93
|
+
#: pairing of the atoms by name is always among them; an ensemble says when the search stopped here.
|
|
94
|
+
MAX_SYMMETRIES = 10_000
|
|
95
|
+
#: Two mean distances that differ by less than this (angstrom) are equal: the model given first is drawn.
|
|
96
|
+
_TIE = 1e-3
|
|
97
|
+
#: Contacts the drawn member does not make that the figure names; beyond that it gives their number.
|
|
98
|
+
_NAMED = 3
|
|
99
|
+
_TYPE_RANK = {t: i for i, t in enumerate(TYPE_ORDER)}
|
|
100
|
+
|
|
101
|
+
#: Columns of :meth:`Ensemble.to_csv`, in order.
|
|
102
|
+
CONTACT_COLUMNS = ("chain", "residue_number", "insertion_code", "residue_name", "interaction_type", "ligand_atoms",
|
|
103
|
+
"n_models", "n_total", "occupancy", "in_member", "distance_median", "distance_min",
|
|
104
|
+
"distance_max", "models")
|
|
105
|
+
|
|
106
|
+
_Key = tuple[str, int, str, str, InteractionType, tuple[int, ...]]
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
#: An end of a conjugated group: an oxygen or nitrogen with one neighbour, on an atom that holds another
|
|
110
|
+
#: such end by the other kind of bond. The two oxygens of a carboxylate, the free oxygens of a phosphate
|
|
111
|
+
#: or a sulfonate, those of a nitro group, the nitrogens of an amidine. (RDKit's own pattern for this, in
|
|
112
|
+
#: the symmetric RMSD of ``rdMolAlign``.)
|
|
113
|
+
_TERMINAL = Chem.MolFromSmarts("[O,N;D1;$([O,N;D1]-[*]=[O,N;D1]),$([O,N;D1]=[*]-[O,N;D1])]")
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _symmetric_form(ligand: Ligand) -> Chem.Mol:
|
|
117
|
+
"""The ligand's graph with the ends of every conjugated group made alike.
|
|
118
|
+
|
|
119
|
+
A molecule is written with one of a phosphate's free oxygens double-bonded and the other
|
|
120
|
+
charged, and a graph of that takes the two for different atoms. They are not: which of them is
|
|
121
|
+
called ``O1A`` is a convention, and two deposited structures of one cofactor can disagree on
|
|
122
|
+
it. Here every such end loses its charge, its hydrogens and its bond order, so that the
|
|
123
|
+
symmetry of the graph is that of the molecule. Only symmetry is read off this form; it is not
|
|
124
|
+
a molecule to draw.
|
|
125
|
+
"""
|
|
126
|
+
mol = Chem.RWMol(ligand.mol)
|
|
127
|
+
for (index,) in mol.GetSubstructMatches(_TERMINAL):
|
|
128
|
+
atom = mol.GetAtomWithIdx(index)
|
|
129
|
+
atom.SetFormalCharge(0)
|
|
130
|
+
atom.SetNumExplicitHs(0)
|
|
131
|
+
atom.SetNoImplicit(True)
|
|
132
|
+
for bond in atom.GetBonds():
|
|
133
|
+
bond.SetBondType(Chem.BondType.SINGLE)
|
|
134
|
+
mol.UpdatePropertyCache(strict=False)
|
|
135
|
+
return mol
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def symmetry_classes(ligand: Ligand) -> dict[str, int]:
|
|
139
|
+
"""For every atom of a ligand, by name, the class of atoms it can be exchanged with.
|
|
140
|
+
|
|
141
|
+
Two atoms share a class when the symmetry of the molecule exchanges them: the fluorines of a
|
|
142
|
+
CF3, the two sides of a para-substituted ring, the two oxygens of a carboxylate. These are
|
|
143
|
+
RDKit's canonical ranks without tie-breaking, on the graph with the ends of conjugated groups
|
|
144
|
+
made alike (:func:`_symmetric_form`) and stereochemistry left aside: stereo is read off each
|
|
145
|
+
model's coordinates, and the classes must not depend on which model they were made from.
|
|
146
|
+
"""
|
|
147
|
+
ranks = list(Chem.CanonicalRankAtoms(_symmetric_form(ligand), breakTies=False, includeChirality=False))
|
|
148
|
+
return {name: int(ranks[i]) for i, name in enumerate(ligand.names)}
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def contact_key(r: ResolvedInteraction, ligand: Ligand, classes: Mapping[str, int], *, symmetry: bool = True,
|
|
152
|
+
hydrophobic_by_residue: bool = True) -> "_Key | None":
|
|
153
|
+
"""What makes two records of two models the same contact; ``None`` for a record that is attached nowhere.
|
|
154
|
+
|
|
155
|
+
The residue (chain, number, insertion code, name), the interaction type, and the ligand atoms
|
|
156
|
+
the record was resolved onto, each by its class in ``classes``
|
|
157
|
+
(:func:`symmetry_classes`). The two switches exist so that what each rule merges can be
|
|
158
|
+
counted on a set, which is how the rules are judged; an :class:`Ensemble` uses both rules.
|
|
159
|
+
"""
|
|
160
|
+
if r.ligand is None:
|
|
161
|
+
return None
|
|
162
|
+
rec = r.record
|
|
163
|
+
chain = r.residue.chain if r.residue is not None else rec.chain
|
|
164
|
+
if hydrophobic_by_residue and rec.type is InteractionType.HYDROPHOBIC:
|
|
165
|
+
site: tuple[int, ...] = ()
|
|
166
|
+
elif symmetry:
|
|
167
|
+
site = tuple(sorted({classes[ligand.names[i]] for i in r.ligand.atoms}))
|
|
168
|
+
else:
|
|
169
|
+
# Without the symmetry rule an atom is itself: its own number, below every class.
|
|
170
|
+
order = {name: -1 - k for k, name in enumerate(sorted(classes))}
|
|
171
|
+
site = tuple(sorted({order[ligand.names[i]] for i in r.ligand.atoms}))
|
|
172
|
+
return (chain, rec.residue_number, rec.insertion_code, rec.residue_name.upper(), rec.type, site)
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
@dataclass(frozen=True)
|
|
176
|
+
class EnsembleContact:
|
|
177
|
+
"""One contact of an ensemble: which models make it, and at what distance.
|
|
178
|
+
|
|
179
|
+
``ligand_atoms`` are the atoms of the ligand through which the models make it: one atom, the
|
|
180
|
+
atoms of a ring or of a charged group, several atoms where the models use atoms that the
|
|
181
|
+
molecule's symmetry exchanges, and for a hydrophobic contact every carbon a model pairs with
|
|
182
|
+
the residue. ``distances`` holds, for each model of ``models``, the distance its table
|
|
183
|
+
reports (the shortest, where it has several records of the contact); nothing is measured in
|
|
184
|
+
a model that does not make the contact.
|
|
185
|
+
"""
|
|
186
|
+
|
|
187
|
+
chain: str
|
|
188
|
+
residue_number: int
|
|
189
|
+
insertion_code: str
|
|
190
|
+
residue_name: str
|
|
191
|
+
type: InteractionType
|
|
192
|
+
ligand_atoms: tuple[str, ...]
|
|
193
|
+
models: tuple[int, ...] # indices of the models that make it, ascending
|
|
194
|
+
n_total: int # models in the ensemble
|
|
195
|
+
in_member: bool # the drawn member makes it
|
|
196
|
+
distances: tuple["float | None", ...] # one for each of ``models``
|
|
197
|
+
|
|
198
|
+
@property
|
|
199
|
+
def n_models(self) -> int:
|
|
200
|
+
"""How many models make it."""
|
|
201
|
+
return len(self.models)
|
|
202
|
+
|
|
203
|
+
@property
|
|
204
|
+
def occupancy(self) -> float:
|
|
205
|
+
"""The share of the models that make the contact."""
|
|
206
|
+
return self.n_models / self.n_total
|
|
207
|
+
|
|
208
|
+
def _measured(self) -> list[float]:
|
|
209
|
+
return [d for d in self.distances if d is not None]
|
|
210
|
+
|
|
211
|
+
@property
|
|
212
|
+
def distance_median(self) -> "float | None":
|
|
213
|
+
"""The median of its distance over the models that make it."""
|
|
214
|
+
values = self._measured()
|
|
215
|
+
return float(statistics.median(values)) if values else None
|
|
216
|
+
|
|
217
|
+
@property
|
|
218
|
+
def distance_min(self) -> "float | None":
|
|
219
|
+
"""The shortest of its distances."""
|
|
220
|
+
values = self._measured()
|
|
221
|
+
return min(values) if values else None
|
|
222
|
+
|
|
223
|
+
@property
|
|
224
|
+
def distance_max(self) -> "float | None":
|
|
225
|
+
"""The longest of its distances."""
|
|
226
|
+
values = self._measured()
|
|
227
|
+
return max(values) if values else None
|
|
228
|
+
|
|
229
|
+
@property
|
|
230
|
+
def residue_id(self) -> tuple[str, int, str]:
|
|
231
|
+
"""``(chain, number, insertion code)`` of the residue."""
|
|
232
|
+
return (self.chain, self.residue_number, self.insertion_code)
|
|
233
|
+
|
|
234
|
+
@property
|
|
235
|
+
def residue_label(self) -> str:
|
|
236
|
+
"""The residue as a figure names it."""
|
|
237
|
+
return format_residue_label(self.residue_name, self.residue_number, self.insertion_code, None)
|
|
238
|
+
|
|
239
|
+
def as_dict(self) -> dict[str, Any]:
|
|
240
|
+
"""The contact as plain data."""
|
|
241
|
+
return {"chain": self.chain, "residue_number": self.residue_number, "insertion_code": self.insertion_code,
|
|
242
|
+
"residue_name": self.residue_name, "type": self.type.value, "ligand_atoms": list(self.ligand_atoms),
|
|
243
|
+
"models": list(self.models), "n_models": self.n_models, "n_total": self.n_total,
|
|
244
|
+
"occupancy": self.occupancy, "in_member": self.in_member, "distances": list(self.distances),
|
|
245
|
+
"distance_median": self.distance_median, "distance_min": self.distance_min,
|
|
246
|
+
"distance_max": self.distance_max}
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def _symmetries(ligand: Ligand) -> tuple[np.ndarray, bool]:
|
|
250
|
+
"""The symmetries of a ligand's graph as rows of atom indices, the identity first, and whether
|
|
251
|
+
the search ended by itself (``False``: it was stopped at :data:`MAX_SYMMETRIES`)."""
|
|
252
|
+
n = ligand.n_atoms
|
|
253
|
+
identity = tuple(range(n))
|
|
254
|
+
graph = _symmetric_form(ligand)
|
|
255
|
+
found = graph.GetSubstructMatches(graph, uniquify=False, useChirality=False, maxMatches=MAX_SYMMETRIES)
|
|
256
|
+
rows = [identity] + [tuple(m) for m in found if len(m) == n and tuple(m) != identity]
|
|
257
|
+
return np.array(rows, dtype=int).reshape(-1, n), len(found) < MAX_SYMMETRIES
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def _default_names(models: Sequence[Any]) -> list[str]:
|
|
261
|
+
"""A name for every model: what tells the files apart, else ``model 1``, ``model 2``, ..."""
|
|
262
|
+
numbered = [f"model {i + 1}" for i in range(len(models))]
|
|
263
|
+
if all(isinstance(m, Structure) and m.model is not None for m in models):
|
|
264
|
+
# The models of one file (read_models): each by the number the file gives it.
|
|
265
|
+
of_file = [f"model {m.model}" for m in models]
|
|
266
|
+
if len(set(of_file)) == len(of_file):
|
|
267
|
+
return of_file
|
|
268
|
+
for pick in (lambda p: p.stem, lambda p: f"{p.parent.name}/{p.stem}"):
|
|
269
|
+
names = []
|
|
270
|
+
for m in models:
|
|
271
|
+
source = m.source if isinstance(m, Structure) else m
|
|
272
|
+
names.append(pick(Path(source)) if source else "")
|
|
273
|
+
if all(names) and len(set(names)) == len(names):
|
|
274
|
+
return names
|
|
275
|
+
return numbered
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
class Ensemble:
|
|
279
|
+
"""Several models of one complex, each built as a :class:`~bindview.diagram.Diagram`.
|
|
280
|
+
|
|
281
|
+
``names`` label the models in the result and in the figure's sentences (default ``model 1``,
|
|
282
|
+
``model 2``, ...). ``member`` names the model to draw, by index or by name; left out, the
|
|
283
|
+
medoid is drawn (see the module docstring). ``ensemble`` is what the legend calls the set:
|
|
284
|
+
occupancy is a share, and the figure has to say of what (default ``"the N models"``).
|
|
285
|
+
|
|
286
|
+
All models must hold the same ligand, with the same atom names, and number the residues of
|
|
287
|
+
its pocket alike; an :class:`~bindview.errors.EnsembleError` says where they do not.
|
|
288
|
+
"""
|
|
289
|
+
|
|
290
|
+
def __init__(self, diagrams: Sequence[Diagram], names: "Sequence[str] | None" = None, *,
|
|
291
|
+
member: "int | str | None" = None, ensemble: "str | None" = None) -> None:
|
|
292
|
+
if len(diagrams) < 2:
|
|
293
|
+
raise ValueError("an ensemble needs at least two models")
|
|
294
|
+
self.diagrams = list(diagrams)
|
|
295
|
+
raw = list(names) if names is not None else [f"model {i + 1}" for i in range(len(self.diagrams))]
|
|
296
|
+
if len(raw) != len(self.diagrams):
|
|
297
|
+
raise ValueError("one name per model is needed")
|
|
298
|
+
seen: dict[str, int] = {}
|
|
299
|
+
self.names: list[str] = []
|
|
300
|
+
for nm in raw:
|
|
301
|
+
seen[nm] = seen.get(nm, 0) + 1
|
|
302
|
+
self.names.append(nm if seen[nm] == 1 else f"{nm} ({seen[nm]})")
|
|
303
|
+
#: What the contacts' occupancy is a share of, for the legend.
|
|
304
|
+
self.ensemble = ensemble or f"the {self.n} models"
|
|
305
|
+
#: What deviated from the clean path, in words.
|
|
306
|
+
self.warnings: list[str] = []
|
|
307
|
+
|
|
308
|
+
first = self.diagrams[0].ligand
|
|
309
|
+
for dia, nm in zip(self.diagrams[1:], self.names[1:]):
|
|
310
|
+
if set(dia.ligand.names) != set(first.names):
|
|
311
|
+
only_first = sorted(set(first.names) - set(dia.ligand.names))
|
|
312
|
+
only_this = sorted(set(dia.ligand.names) - set(first.names))
|
|
313
|
+
raise EnsembleError(
|
|
314
|
+
f"{nm} does not hold the ligand of {self.names[0]}: its heavy atoms are named otherwise "
|
|
315
|
+
f"(only in {self.names[0]}: {', '.join(only_first[:6]) or 'none'}; only in {nm}: "
|
|
316
|
+
f"{', '.join(only_this[:6]) or 'none'}). Contacts are matched on the names of the ligand's "
|
|
317
|
+
"atoms, so every model has to name them alike")
|
|
318
|
+
self._classes = symmetry_classes(first)
|
|
319
|
+
#: For two models that superpose: which atom of the second lies where each atom of the first
|
|
320
|
+
#: lies, as indices into the first model's atoms. The identity unless the ligand has a symmetry.
|
|
321
|
+
self._same_place: dict[tuple[int, int], np.ndarray] = {}
|
|
322
|
+
self._made: dict[_Key, dict[int, list[ResolvedInteraction]]] = {}
|
|
323
|
+
|
|
324
|
+
#: RMSD of the ligand's heavy atoms between every two models, pockets superposed (angstrom;
|
|
325
|
+
#: ``nan`` where two pockets do not superpose within 3 angstrom, or a model has no structure).
|
|
326
|
+
self.rmsd: np.ndarray
|
|
327
|
+
#: Backbone RMSD of every two pockets after superposition (angstrom; ``nan`` without structures).
|
|
328
|
+
self.pocket_rmsd: np.ndarray
|
|
329
|
+
self.rmsd, self.pocket_rmsd = self._pose_distances()
|
|
330
|
+
#: Per model, its mean ligand RMSD to the others; ``None`` for a model that is no candidate.
|
|
331
|
+
self.mean_rmsd: "list[float | None]" = []
|
|
332
|
+
#: The model that is drawn, and how it came to be: ``"medoid"``, ``"given"`` or ``"first"``.
|
|
333
|
+
self.member: int
|
|
334
|
+
self.chosen_by: str
|
|
335
|
+
self.member, self.chosen_by = self._choose(member)
|
|
336
|
+
|
|
337
|
+
self._by_key: dict[_Key, EnsembleContact] = {}
|
|
338
|
+
#: Every contact of the ensemble, by residue, interaction type and ligand atom.
|
|
339
|
+
self.contacts: list[EnsembleContact] = self._match()
|
|
340
|
+
self._table: "FingerprintTable | None" = None
|
|
341
|
+
self._counted: "tuple[list[ResidueShare], list[int]] | None" = None
|
|
342
|
+
|
|
343
|
+
# ------------------------------------------------------------------ build
|
|
344
|
+
@classmethod
|
|
345
|
+
def from_structures(cls, models: "Sequence[str | Path | Structure]", ligand: Any, smiles: "str | None" = None,
|
|
346
|
+
interactions: "Sequence[Any] | str | None" = None, *, names: "Sequence[str] | None" = None,
|
|
347
|
+
member: "int | str | None" = None, ensemble: "str | None" = None,
|
|
348
|
+
**options: Any) -> "Ensemble":
|
|
349
|
+
"""Build an ensemble from model files and one contact table for each.
|
|
350
|
+
|
|
351
|
+
Parameters
|
|
352
|
+
----------
|
|
353
|
+
models:
|
|
354
|
+
The models, one file each (mmCIF or PDB), or parsed :class:`Structure` objects: those
|
|
355
|
+
of one file with several models are what ``bindview.read_models(path)`` gives. Every
|
|
356
|
+
model is built by :meth:`Diagram.from_structure <bindview.diagram.Diagram.from_structure>`.
|
|
357
|
+
ligand:
|
|
358
|
+
Which residue is the ligand, as ``Diagram.from_structure`` takes it. One selection for
|
|
359
|
+
all models, or a list with one for each (the same ligand can carry another residue
|
|
360
|
+
number in another file).
|
|
361
|
+
smiles:
|
|
362
|
+
The ligand's SMILES, the same for every model.
|
|
363
|
+
interactions:
|
|
364
|
+
One contact table for each model, in the order of the models: a list of
|
|
365
|
+
:class:`~bindview.interactions.Interaction` or dict rows, or the path of a table. An
|
|
366
|
+
empty table is a model that makes no contact, and counts. ``None`` in place of the
|
|
367
|
+
list, or of one table, detects (the optional PLIP extra); ``"distances"`` makes it from the
|
|
368
|
+
positions of the heavy atoms.
|
|
369
|
+
names, member, ensemble:
|
|
370
|
+
As for :class:`Ensemble`. Left out, the models are named after their files where
|
|
371
|
+
that tells them apart.
|
|
372
|
+
options:
|
|
373
|
+
Passed on to ``Diagram.from_structure`` for every model: ``name`` (the ligand's),
|
|
374
|
+
``plddt``, ``model_confidence``, ``ionize_acids``, ``ligand_as``, ``detail``, ...
|
|
375
|
+
"""
|
|
376
|
+
models = list(models)
|
|
377
|
+
if len(models) < 2:
|
|
378
|
+
raise ValueError("an ensemble needs at least two models")
|
|
379
|
+
ligands = list(ligand) if isinstance(ligand, list) else [ligand] * len(models)
|
|
380
|
+
if len(ligands) != len(models):
|
|
381
|
+
raise ValueError(f"{len(ligands)} ligand selections for {len(models)} models: give one for all, "
|
|
382
|
+
"or a list with one for each")
|
|
383
|
+
if isinstance(interactions, (str, Path)) and interactions != DISTANCES:
|
|
384
|
+
# (A string is a sequence too: its characters would be taken for the tables.)
|
|
385
|
+
raise ValueError(f"interactions takes one contact table for each of the {len(models)} models, in their "
|
|
386
|
+
f"order, and {str(interactions)!r} is one path: give a list with a table for each model")
|
|
387
|
+
tables = ([interactions] * len(models) if interactions is None or interactions == DISTANCES
|
|
388
|
+
else list(interactions))
|
|
389
|
+
if len(tables) != len(models) or any(isinstance(t, (Interaction, Mapping)) for t in tables):
|
|
390
|
+
raise ValueError(f"interactions takes one contact table for each of the {len(models)} models, "
|
|
391
|
+
"in their order (a list of tables, not the rows of one)")
|
|
392
|
+
labels = list(names) if names is not None else _default_names(models)
|
|
393
|
+
if len(labels) != len(models):
|
|
394
|
+
raise ValueError("one name per model is needed")
|
|
395
|
+
diagrams = []
|
|
396
|
+
for model, selection, table, label in zip(models, ligands, tables, labels):
|
|
397
|
+
try:
|
|
398
|
+
diagrams.append(Diagram.from_structure(model, selection, smiles, table, **options))
|
|
399
|
+
except BindviewError as exc:
|
|
400
|
+
raise type(exc)(f"{label}: {exc}") from None
|
|
401
|
+
return cls(diagrams, labels, member=member, ensemble=ensemble)
|
|
402
|
+
|
|
403
|
+
# ------------------------------------------------------------------ data
|
|
404
|
+
@property
|
|
405
|
+
def n(self) -> int:
|
|
406
|
+
"""How many models the ensemble has."""
|
|
407
|
+
return len(self.diagrams)
|
|
408
|
+
|
|
409
|
+
@property
|
|
410
|
+
def table(self) -> FingerprintTable:
|
|
411
|
+
"""The models as fingerprints, one row a model: per residue and interaction type, as
|
|
412
|
+
``Comparison.table`` is for ligands. ``table.consensus()`` gives, per residue, the share of
|
|
413
|
+
the models that contact it at all."""
|
|
414
|
+
if self._table is None:
|
|
415
|
+
self._table = FingerprintTable([Fingerprint.from_diagram(d, nm)
|
|
416
|
+
for d, nm in zip(self.diagrams, self.names)])
|
|
417
|
+
return self._table
|
|
418
|
+
|
|
419
|
+
def to_csv(self, path: "str | Path | None" = None) -> str:
|
|
420
|
+
"""The contacts as a table, one row each (:data:`CONTACT_COLUMNS`); written to ``path`` if given."""
|
|
421
|
+
def num(value: "float | None", digits: int) -> str:
|
|
422
|
+
return "" if value is None else f"{value:.{digits}f}"
|
|
423
|
+
rows = [{"chain": c.chain, "residue_number": str(c.residue_number), "insertion_code": c.insertion_code,
|
|
424
|
+
"residue_name": c.residue_name, "interaction_type": c.type.value,
|
|
425
|
+
"ligand_atoms": " ".join(c.ligand_atoms), "n_models": str(c.n_models), "n_total": str(c.n_total),
|
|
426
|
+
"occupancy": num(c.occupancy, 4), "in_member": "true" if c.in_member else "false",
|
|
427
|
+
"distance_median": num(c.distance_median, 3), "distance_min": num(c.distance_min, 2),
|
|
428
|
+
"distance_max": num(c.distance_max, 2), "models": ";".join(self.names[k] for k in c.models)}
|
|
429
|
+
for c in self.contacts]
|
|
430
|
+
return _write_rows(CONTACT_COLUMNS, rows, path)
|
|
431
|
+
|
|
432
|
+
def diagram(self, absent: str = "named") -> Diagram:
|
|
433
|
+
"""The drawn member as a single diagram whose contacts carry the ensemble as their occupancy.
|
|
434
|
+
|
|
435
|
+
Every interaction record of that model gets, as ``occupancy``, the share of the models
|
|
436
|
+
that make the same contact; its distances stay its own. The diagram names the ensemble
|
|
437
|
+
for the legend and says under itself which model it is
|
|
438
|
+
(:attr:`~bindview.diagram.Diagram.remarks`). It renders like any diagram, in either style.
|
|
439
|
+
The member itself is left untouched.
|
|
440
|
+
|
|
441
|
+
``absent`` says what becomes of a contact that the drawn member does not make and other
|
|
442
|
+
models do. ``"named"`` (default): it is not drawn, and the figure says in a sentence how
|
|
443
|
+
many there are and names the most frequent. ``"faint"``: it is drawn, faint, from its
|
|
444
|
+
residue to the atom of the ligand that lies where the other model's atom lies, with the
|
|
445
|
+
share of the models that make it where a distance would stand; the figure has no distance
|
|
446
|
+
for it, and it is not counted among the diagram's contacts. Either way it is a row of
|
|
447
|
+
:attr:`contacts` with ``in_member`` false.
|
|
448
|
+
"""
|
|
449
|
+
if absent not in ABSENT:
|
|
450
|
+
raise ValueError(f"absent is one of {', '.join(repr(a) for a in ABSENT)}, not {absent!r}")
|
|
451
|
+
base = self.diagrams[self.member]
|
|
452
|
+
resolved = []
|
|
453
|
+
for r in base.interactions:
|
|
454
|
+
key = contact_key(r, base.ligand, self._classes)
|
|
455
|
+
occupancy = self._by_key[key].occupancy if key is not None else None
|
|
456
|
+
resolved.append(replace(r, record=r.record.with_(occupancy=occupancy)))
|
|
457
|
+
dia = copy.copy(base)
|
|
458
|
+
dia.interactions = resolved
|
|
459
|
+
dia.warnings = list(self.warnings) + list(base.warnings)
|
|
460
|
+
dia.ensemble = self.ensemble
|
|
461
|
+
dia._composed = {}
|
|
462
|
+
which, not_drawn = self._remarks()
|
|
463
|
+
if absent == "faint" and not_drawn is not None:
|
|
464
|
+
dia.elsewhere, lost = self._elsewhere(len(resolved))
|
|
465
|
+
k = len(dia.elsewhere)
|
|
466
|
+
name = self.names[self.member]
|
|
467
|
+
drawn = (f"Faint, with the share of the {self.n} models that make it: {k} contact{'s' if k != 1 else ''} "
|
|
468
|
+
f"that other models make and {name} does not.")
|
|
469
|
+
if lost:
|
|
470
|
+
drawn += f" {lost} more could not be placed on {name} and {'are' if lost != 1 else 'is'} not drawn."
|
|
471
|
+
dia.remarks = [which]
|
|
472
|
+
dia.elsewhere_said = (drawn, not_drawn) if k else ("", not_drawn)
|
|
473
|
+
if not k:
|
|
474
|
+
dia.remarks.append(not_drawn)
|
|
475
|
+
else:
|
|
476
|
+
dia.remarks = [which, not_drawn or f"No other model makes a contact that {self.names[self.member]} does not."]
|
|
477
|
+
return dia
|
|
478
|
+
|
|
479
|
+
@property
|
|
480
|
+
def residues(self) -> list[ResidueShare]:
|
|
481
|
+
"""Every residue that any model contacts, with the models that do: the most frequent first
|
|
482
|
+
(:class:`bindview.consensus.ResidueShare`). What :meth:`consensus` draws."""
|
|
483
|
+
return self._by_residue()[0]
|
|
484
|
+
|
|
485
|
+
def _by_residue(self) -> tuple[list[ResidueShare], list[int]]:
|
|
486
|
+
if self._counted is None:
|
|
487
|
+
self._counted = residue_shares(self, _symmetries(self.diagrams[0].ligand)[0])
|
|
488
|
+
return self._counted
|
|
489
|
+
|
|
490
|
+
def consensus(self, least: float = 0.25, atoms: float = 0.5) -> Diagram:
|
|
491
|
+
"""All the models in one diagram, counted by residue (:mod:`bindview.consensus`).
|
|
492
|
+
|
|
493
|
+
Every residue stands in a ring as long as the share of the models that contact it, with their
|
|
494
|
+
number in it. A residue that ``atoms`` of them or more contact is drawn as atoms if one of its
|
|
495
|
+
lines has a direction (any contact but a hydrophobic one), and each of its sites (an atom, a
|
|
496
|
+
ring, a charged group) has one line, to the part of the ligand that most of the models have it
|
|
497
|
+
on, with the share of the models that do; a line that fewer than half of the residue's models
|
|
498
|
+
make is not drawn. Any other residue is its ring alone, and the figure says how many of those
|
|
499
|
+
that ``atoms`` of the models contact are.
|
|
500
|
+
Residues that fewer than ``least`` of the models contact are left out, and the figure names them.
|
|
501
|
+
Where the models give one residue number two names (a point mutant among them), the figure has the
|
|
502
|
+
residue of the model whose ligand it draws, counted over the models that have that residue, and
|
|
503
|
+
names the other.
|
|
504
|
+
|
|
505
|
+
No single model is drawn, so there are no distances, no buried fraction and no confidence, and
|
|
506
|
+
the pocket is not lined: the lines are what most of the models agree on, and the ligand is
|
|
507
|
+
drawn as in the member :meth:`diagram` draws. It renders like any diagram, in either style;
|
|
508
|
+
``residues="bubbles"`` draws every residue as its ring alone.
|
|
509
|
+
"""
|
|
510
|
+
if not 0.0 <= least <= 1.0:
|
|
511
|
+
raise ValueError(f"least is a share of the models, from 0 to 1, not {least!r}")
|
|
512
|
+
if not 0.0 <= atoms <= 1.0:
|
|
513
|
+
raise ValueError(f"atoms is a share of the models, from 0 to 1, not {atoms!r}")
|
|
514
|
+
base = self.diagrams[self.member]
|
|
515
|
+
if isinstance(base.backend, Polymer):
|
|
516
|
+
raise EnsembleError("the consensus of an ensemble is drawn for a ligand that is drawn as atoms, and this one is "
|
|
517
|
+
"a chain: diagram() draws one model of it, with the share of every contact")
|
|
518
|
+
counted, turned = self._by_residue()
|
|
519
|
+
every, elsewhere = self._at_one_place(counted)
|
|
520
|
+
shown = [r for r in every if r.share >= least - 1e-9]
|
|
521
|
+
if every and not shown:
|
|
522
|
+
top = every[0]
|
|
523
|
+
raise EnsembleError(f"no residue is contacted by {100 * least:.0f} % of the models; the most frequent is "
|
|
524
|
+
f"{top.residue_label}, by {top.n_models} of {self.n}: pass a smaller least")
|
|
525
|
+
rows = [x for r in shown for x in lines_of(self, r, r.share >= atoms - 1e-9)]
|
|
526
|
+
for k, row in enumerate(rows):
|
|
527
|
+
row.index = k
|
|
528
|
+
directed = {r.record.residue_id for r in rows if r.type is not InteractionType.HYDROPHOBIC}
|
|
529
|
+
dia = copy.copy(base)
|
|
530
|
+
dia.interactions, dia.elsewhere, dia.elsewhere_said = rows, [], ("", "")
|
|
531
|
+
dia.warnings = list(self.warnings) + list(base.warnings)
|
|
532
|
+
dia.ensemble = self.ensemble
|
|
533
|
+
dia.confidence, dia.pae = None, None
|
|
534
|
+
dia._composed = {}
|
|
535
|
+
dia.shares = {r.residue_id: r for r in shown}
|
|
536
|
+
dia.forms = {f"{r.residue_id[0]}:{r.residue_name.upper()}{r.residue_number}{r.insertion_code}".lstrip(":"):
|
|
537
|
+
"atoms" if r.share >= atoms - 1e-9 and r.residue_id in directed else "bubbles" for r in shown}
|
|
538
|
+
if any(d.confidence is not None for d in self.diagrams):
|
|
539
|
+
dia.warnings.append("the models have a confidence of their own, and it is not drawn: this is no single model")
|
|
540
|
+
rings = [r for r in shown if r.share >= atoms - 1e-9 and r.residue_id not in directed]
|
|
541
|
+
dia.remarks = self._consensus_remarks(every, shown, turned, atoms, rings)
|
|
542
|
+
if elsewhere:
|
|
543
|
+
name = self.names[self.member]
|
|
544
|
+
named = "; ".join(f"{r.residue_label} ({r.n_models} of {self.n})" for r in elsewhere)
|
|
545
|
+
dia.remarks.append(f"Not drawn: {named}, which other models have where {name} has another residue.")
|
|
546
|
+
dia.warnings.append(f"{named}: at one place with another residue of {name}, whose ligand is drawn (the "
|
|
547
|
+
"models do not name that residue alike). Counted in Ensemble.residues, not drawn")
|
|
548
|
+
return dia
|
|
549
|
+
|
|
550
|
+
def _at_one_place(self, counted: "list[ResidueShare]") -> "tuple[list[ResidueShare], list[ResidueShare]]":
|
|
551
|
+
"""The residues that the figure can show, and those it cannot: where the models give one residue number
|
|
552
|
+
two names (a point mutant among them), there are two residues and one place. It goes to the residue
|
|
553
|
+
that the model whose ligand is drawn has there, with the models that residue is counted in; without
|
|
554
|
+
a structure, to the one that more models contact."""
|
|
555
|
+
places: "dict[tuple[str, int, str], list[ResidueShare]]" = {}
|
|
556
|
+
for r in counted:
|
|
557
|
+
places.setdefault(r.residue_id, []).append(r)
|
|
558
|
+
if all(len(group) == 1 for group in places.values()):
|
|
559
|
+
return counted, []
|
|
560
|
+
st = self.diagrams[self.member].structure
|
|
561
|
+
elsewhere: "list[ResidueShare]" = []
|
|
562
|
+
for (chain, number, icode), group in places.items():
|
|
563
|
+
if len(group) > 1:
|
|
564
|
+
key = st.find_residue(chain or None, number, icode) if st is not None else None
|
|
565
|
+
own = st.residue_name(key).upper() if st is not None and key is not None else ""
|
|
566
|
+
kept = next((r for r in group if r.residue_name.upper() == own), group[0])
|
|
567
|
+
elsewhere.extend(r for r in group if r is not kept)
|
|
568
|
+
return [r for r in counted if not any(r is x for x in elsewhere)], elsewhere
|
|
569
|
+
|
|
570
|
+
def _consensus_remarks(self, every: "list[ResidueShare]", shown: "list[ResidueShare]", turned: "list[int]",
|
|
571
|
+
atoms: float, rings: "Sequence[ResidueShare]" = ()) -> list[str]:
|
|
572
|
+
"""``rings``: the residues that ``atoms`` of the models contact and that are a ring alone all the same."""
|
|
573
|
+
many = "half" if atoms == 0.5 else f"{100 * atoms:.0f} %"
|
|
574
|
+
unless = ""
|
|
575
|
+
if rings:
|
|
576
|
+
k = len(rings)
|
|
577
|
+
unless = (", unless its lines are hydrophobic contacts, which have no direction "
|
|
578
|
+
f"({k} here: {'; '.join(r.residue_label for r in rings[:_NAMED])}"
|
|
579
|
+
+ (f"; and {k - _NAMED} more" if k > _NAMED else "") + ")")
|
|
580
|
+
said = [f"Counted by residue, over all {self.n} models: no single one is drawn, and the ligand is drawn as in "
|
|
581
|
+
f"{self.names[self.member]}. A residue that {many} of them or more contact is drawn as atoms{unless}; "
|
|
582
|
+
"a line goes to the part of the ligand that most of them have it on."]
|
|
583
|
+
rest = every[len(shown):]
|
|
584
|
+
if rest:
|
|
585
|
+
k, chains = len(rest), {r.chain for r in every}
|
|
586
|
+
named = "; ".join(format_residue_label(r.residue_name, r.residue_number, r.insertion_code,
|
|
587
|
+
r.chain if len(chains) > 1 else None)
|
|
588
|
+
+ f" ({r.n_models} of {self.n})" for r in rest[:_NAMED])
|
|
589
|
+
more = f"; and {k - _NAMED} more" if k > _NAMED else ""
|
|
590
|
+
said.append(f"Not drawn: {k} residue{'s' if k != 1 else ''} that fewer of the models contact ({named}{more}).")
|
|
591
|
+
if turned:
|
|
592
|
+
k = len(turned)
|
|
593
|
+
said.append(f"The ligand has ends that are alike: in {k} model{'s' if k != 1 else ''} they are named the other "
|
|
594
|
+
"way round, so that the contacts agree best.")
|
|
595
|
+
return said
|
|
596
|
+
|
|
597
|
+
def _elsewhere(self, first_index: int) -> tuple[list[ResolvedInteraction], int]:
|
|
598
|
+
"""The contacts the drawn member does not make, as records on that member: each on the atoms
|
|
599
|
+
of its ligand that lie where the atoms of the model that makes the contact lie, and on the
|
|
600
|
+
protein atoms that model names. No distance: the member has none for it. With them, how
|
|
601
|
+
many could not be attached to the member at all."""
|
|
602
|
+
base = self.diagrams[self.member]
|
|
603
|
+
names = self.diagrams[0].ligand.names
|
|
604
|
+
place = {name: k for k, name in enumerate(names)}
|
|
605
|
+
records = []
|
|
606
|
+
for c in self.contacts:
|
|
607
|
+
if c.in_member:
|
|
608
|
+
continue
|
|
609
|
+
key = next(k for k, v in self._by_key.items() if v is c)
|
|
610
|
+
source = c.models[0] # the first model that makes it speaks for it
|
|
611
|
+
made = sorted(self._made[key][source],
|
|
612
|
+
key=lambda r: r.record.distance if r.record.distance is not None else math.inf)[0]
|
|
613
|
+
lig = self.diagrams[source].ligand
|
|
614
|
+
there = self._same_place.get((source, self.member)) # no common frame: the atoms of the same name
|
|
615
|
+
atoms = [lig.names[i] for i in made.ligand.atoms] # type: ignore[union-attr]
|
|
616
|
+
if there is not None:
|
|
617
|
+
atoms = [names[int(there[place[a]])] for a in atoms]
|
|
618
|
+
fields: dict[str, Any] = {"type": c.type, "residue_number": c.residue_number,
|
|
619
|
+
"residue_name": c.residue_name, "chain": c.chain,
|
|
620
|
+
"insertion_code": c.insertion_code, "occupancy": c.occupancy,
|
|
621
|
+
"ligand_is_donor": made.record.ligand_is_donor}
|
|
622
|
+
if made.ligand.kind == "atom": # type: ignore[union-attr]
|
|
623
|
+
fields["ligand_atom"] = atoms[0]
|
|
624
|
+
else:
|
|
625
|
+
fields["ligand_atoms"] = tuple(atoms)
|
|
626
|
+
if made.protein.kind == "atom" and made.protein.atoms:
|
|
627
|
+
fields["protein_atom"] = made.protein.atoms[0]
|
|
628
|
+
elif made.protein.atoms:
|
|
629
|
+
fields["protein_atoms"] = made.protein.atoms
|
|
630
|
+
records.append(Interaction(**fields))
|
|
631
|
+
if base.structure is None:
|
|
632
|
+
return [], len(records)
|
|
633
|
+
placed = [r for r in resolve_interactions(records, base.ligand, base.structure) if r.ligand is not None]
|
|
634
|
+
for k, r in enumerate(placed):
|
|
635
|
+
r.index, r.absent = first_index + k, True
|
|
636
|
+
return placed, len(records) - len(placed)
|
|
637
|
+
|
|
638
|
+
# ------------------------------------------------------------------ the member
|
|
639
|
+
def _pose_distances(self) -> tuple[np.ndarray, np.ndarray]:
|
|
640
|
+
n = self.n
|
|
641
|
+
dist, pocket = np.full((n, n), np.nan), np.full((n, n), np.nan)
|
|
642
|
+
np.fill_diagonal(dist, 0.0)
|
|
643
|
+
np.fill_diagonal(pocket, 0.0)
|
|
644
|
+
if any(d.structure is None for d in self.diagrams):
|
|
645
|
+
self.warnings.append("a model has no structure: the models cannot be superposed, and no member "
|
|
646
|
+
"can be chosen by pose")
|
|
647
|
+
return dist, pocket
|
|
648
|
+
first = self.diagrams[0].ligand
|
|
649
|
+
symmetries, complete = _symmetries(first)
|
|
650
|
+
if not complete:
|
|
651
|
+
self.warnings.append(f"the ligand has more than {MAX_SYMMETRIES:,} symmetries: the RMSD between two "
|
|
652
|
+
"poses is the smallest over those that were tried, and may be too large")
|
|
653
|
+
# Every model's ligand in the atom order of the first: names are what the models share.
|
|
654
|
+
xyz = []
|
|
655
|
+
for d in self.diagrams:
|
|
656
|
+
place = {name: k for k, name in enumerate(d.ligand.names)}
|
|
657
|
+
xyz.append(np.asarray(d.ligand.coords3d, dtype=float)[[place[name] for name in first.names]])
|
|
658
|
+
fitted = pocket_transforms_between(self.diagrams) # every model is read once
|
|
659
|
+
for i in range(n - 1):
|
|
660
|
+
for j in range(i + 1, n):
|
|
661
|
+
frame, fit = fitted[(i, j)]
|
|
662
|
+
if fit is None:
|
|
663
|
+
raise EnsembleError(
|
|
664
|
+
f"{self.names[j]} and {self.names[i]} have no pocket in common to superpose: fewer than "
|
|
665
|
+
"four residues around the ligand are in both, or under 70 % of them carry the same name. "
|
|
666
|
+
"That is another protein, another numbering or other chain names, not another model of "
|
|
667
|
+
"this complex. Residues are matched by chain and number: name the chains alike first")
|
|
668
|
+
pocket[i, j] = pocket[j, i] = float(fit)
|
|
669
|
+
if frame is None:
|
|
670
|
+
continue # the pockets differ by more than the fit may leave
|
|
671
|
+
rot, shift = frame
|
|
672
|
+
moved = xyz[j] @ rot.T + shift
|
|
673
|
+
delta = xyz[i][None, :, :] - moved[symmetries]
|
|
674
|
+
each = np.sqrt((delta ** 2).sum(axis=2).mean(axis=1))
|
|
675
|
+
best = int(each.argmin())
|
|
676
|
+
dist[i, j] = dist[j, i] = float(each[best])
|
|
677
|
+
there = symmetries[best] # atom q of model i lies where atom there[q] of model j lies
|
|
678
|
+
back = np.empty_like(there)
|
|
679
|
+
back[there] = np.arange(len(there))
|
|
680
|
+
self._same_place[(i, j)], self._same_place[(j, i)] = there, back
|
|
681
|
+
return dist, pocket
|
|
682
|
+
|
|
683
|
+
def _choose(self, member: "int | str | None") -> tuple[int, str]:
|
|
684
|
+
n = self.n
|
|
685
|
+
need = math.ceil((n - 1) / 2) # a distance to at least half of the others
|
|
686
|
+
means: "list[float | None]" = []
|
|
687
|
+
for i in range(n):
|
|
688
|
+
have = [float(self.rmsd[i, j]) for j in range(n) if j != i and not math.isnan(self.rmsd[i, j])]
|
|
689
|
+
means.append(sum(have) / len(have) if have and len(have) >= need else None)
|
|
690
|
+
self.mean_rmsd = means
|
|
691
|
+
apart = [self.names[i] for i in range(n) if means[i] is None]
|
|
692
|
+
candidates = [i for i in range(n) if means[i] is not None]
|
|
693
|
+
if apart and candidates:
|
|
694
|
+
self.warnings.append(f"{', '.join(apart)}: the pocket does not superpose on that of at least half of "
|
|
695
|
+
"the other models within 3 Å. Counted for occupancy; not a candidate for the "
|
|
696
|
+
"member that is drawn")
|
|
697
|
+
if member is not None:
|
|
698
|
+
if isinstance(member, str):
|
|
699
|
+
if member not in self.names:
|
|
700
|
+
raise ValueError(f"no model is named {member!r}; the models are {', '.join(self.names)}")
|
|
701
|
+
return self.names.index(member), "given"
|
|
702
|
+
if not -n <= int(member) < n:
|
|
703
|
+
raise ValueError(f"member {member} is not one of the {n} models")
|
|
704
|
+
return int(member) % n, "given"
|
|
705
|
+
if n == 2 or not candidates:
|
|
706
|
+
if not candidates and not any("no structure" in w for w in self.warnings):
|
|
707
|
+
self.warnings.append("no member could be chosen by pose: the pockets of the models do not "
|
|
708
|
+
"superpose. The first model is drawn")
|
|
709
|
+
return 0, "first"
|
|
710
|
+
best = min(means[i] for i in candidates) # type: ignore[type-var]
|
|
711
|
+
return next(i for i in candidates if means[i] <= best + _TIE), "medoid" # type: ignore[operator]
|
|
712
|
+
|
|
713
|
+
# ------------------------------------------------------------------ the contacts
|
|
714
|
+
def _match(self) -> list[EnsembleContact]:
|
|
715
|
+
first = self.diagrams[0].ligand
|
|
716
|
+
place = {name: k for k, name in enumerate(first.names)}
|
|
717
|
+
made: dict[_Key, dict[int, list[ResolvedInteraction]]] = {}
|
|
718
|
+
for k, dia in enumerate(self.diagrams):
|
|
719
|
+
loose = 0
|
|
720
|
+
for r in dia.interactions:
|
|
721
|
+
key = contact_key(r, dia.ligand, self._classes)
|
|
722
|
+
if key is None:
|
|
723
|
+
loose += 1
|
|
724
|
+
continue
|
|
725
|
+
made.setdefault(key, {}).setdefault(k, []).append(r)
|
|
726
|
+
if loose:
|
|
727
|
+
self.warnings.append(f"{self.names[k]}: {loose} record{'s' if loose != 1 else ''} could not be "
|
|
728
|
+
"attached to the ligand and "
|
|
729
|
+
f"{'are' if loose != 1 else 'is'} not counted")
|
|
730
|
+
self._made = made
|
|
731
|
+
out = []
|
|
732
|
+
for key, by_model in made.items():
|
|
733
|
+
chain, number, icode, resname, kind, _site = key
|
|
734
|
+
models = tuple(sorted(by_model))
|
|
735
|
+
distances = []
|
|
736
|
+
atoms: set[str] = set()
|
|
737
|
+
for k in models:
|
|
738
|
+
reported = [r.record.distance for r in by_model[k] if r.record.distance is not None]
|
|
739
|
+
distances.append(min(reported) if reported else None)
|
|
740
|
+
lig = self.diagrams[k].ligand
|
|
741
|
+
atoms |= {lig.names[i] for r in by_model[k] for i in r.ligand.atoms} # type: ignore[union-attr]
|
|
742
|
+
contact = EnsembleContact(chain, number, icode, resname, kind, tuple(sorted(atoms, key=place.__getitem__)),
|
|
743
|
+
models, self.n, self.member in by_model, tuple(distances))
|
|
744
|
+
self._by_key[key] = contact
|
|
745
|
+
out.append(contact)
|
|
746
|
+
out.sort(key=lambda c: (c.chain, c.residue_number, c.insertion_code, _TYPE_RANK[c.type],
|
|
747
|
+
tuple(place[a] for a in c.ligand_atoms)))
|
|
748
|
+
return out
|
|
749
|
+
|
|
750
|
+
# ------------------------------------------------------------------ what the figure says
|
|
751
|
+
def _remarks(self) -> "tuple[str, str | None]":
|
|
752
|
+
"""Which model the figure shows, and the sentence on the contacts of other models that it
|
|
753
|
+
does not draw (``None`` where there is none)."""
|
|
754
|
+
name, n = self.names[self.member], self.n
|
|
755
|
+
mean = self.mean_rmsd[self.member]
|
|
756
|
+
if self.chosen_by == "medoid":
|
|
757
|
+
# Of the candidates, and over the models its pocket superposes on: all of them, unless a warning says not.
|
|
758
|
+
candidates = sum(m is not None for m in self.mean_rmsd)
|
|
759
|
+
over = sum(not math.isnan(self.rmsd[self.member, k]) for k in range(n)) - 1
|
|
760
|
+
among = (f"of the {n} models" if candidates == n else
|
|
761
|
+
f"of the {candidates} of the {n} models whose pocket superposes on that of at least half of the "
|
|
762
|
+
"others")
|
|
763
|
+
how = ("pockets superposed" if over == n - 1 else
|
|
764
|
+
f"over the {over} models whose pocket superposes on its own")
|
|
765
|
+
which = (f"Shown is {name}: {among}, the one whose ligand lies nearest to the others' "
|
|
766
|
+
f"(RMSD {mean:.2f} Å on average, {how}).")
|
|
767
|
+
elif self.chosen_by == "given":
|
|
768
|
+
which = f"Shown is {name} of the {n} models, as asked."
|
|
769
|
+
else:
|
|
770
|
+
which = f"Shown is {name}, the first of the {n} models."
|
|
771
|
+
which += " Distances are that model's."
|
|
772
|
+
missing = sorted((c for c in self.contacts if not c.in_member), key=lambda c: -c.n_models) # stable
|
|
773
|
+
if not missing:
|
|
774
|
+
return which, None
|
|
775
|
+
chains = {c.chain for c in self.contacts}
|
|
776
|
+
|
|
777
|
+
def said(c: EnsembleContact) -> str:
|
|
778
|
+
label = format_residue_label(c.residue_name, c.residue_number, c.insertion_code,
|
|
779
|
+
c.chain if len(chains) > 1 else None)
|
|
780
|
+
to = (f" to {c.ligand_atoms[0]}" if len(c.ligand_atoms) == 1
|
|
781
|
+
and c.type is not InteractionType.HYDROPHOBIC else "")
|
|
782
|
+
return f"{label} {c.type.label.lower()}{to} ({c.n_models} of {n})"
|
|
783
|
+
k = len(missing)
|
|
784
|
+
named = "; ".join(said(c) for c in missing[:_NAMED])
|
|
785
|
+
more = f"; and {k - _NAMED} more" if k > _NAMED else ""
|
|
786
|
+
return which, (f"Not drawn: {k} contact{'s' if k != 1 else ''} that other models make and {name} does not "
|
|
787
|
+
f"({named}{more}).")
|