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/__init__.py
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
"""bindview -- publication-quality figures of molecular interactions.
|
|
2
|
+
|
|
3
|
+
A figure::
|
|
4
|
+
|
|
5
|
+
from bindview import Diagram
|
|
6
|
+
|
|
7
|
+
dia = Diagram.from_structure("model.cif", ligand="LIG_B", smiles="CC(=O)N1CCN(CC1)...", interactions="distances")
|
|
8
|
+
result = dia.render_svg("figure.svg") # result.status, .warnings, .svg, .graph, ...
|
|
9
|
+
|
|
10
|
+
``interactions`` is a table of contacts (a path, or a list of records), ``"distances"`` for a plain one made from the heavy
|
|
11
|
+
atoms, or ``None`` to detect them with PLIP (optional, GPL-2.0).
|
|
12
|
+
|
|
13
|
+
Where to look::
|
|
14
|
+
|
|
15
|
+
bindview.options() every keyword of render, with its default
|
|
16
|
+
bindview.options("colour") those that mention a word
|
|
17
|
+
help(bindview.Diagram.from_structure) what goes in
|
|
18
|
+
help(bindview.Diagram.render) what comes out
|
|
19
|
+
|
|
20
|
+
Other figures::
|
|
21
|
+
|
|
22
|
+
dia.arrange() by hand in a browser: drag, turn, flip
|
|
23
|
+
Comparison([dia_a, dia_b, ...]) several ligands of one pocket
|
|
24
|
+
Ensemble.from_structures(models, "LIG", smiles, "distances") several models of one complex
|
|
25
|
+
.consensus() .diagram() all of them in one figure; one of them, with shares
|
|
26
|
+
Interface(structure, ["A", "B"], contacts) the contacts between two chains
|
|
27
|
+
BasePairs(structure, ["A", "B"], pairs) two strands of RNA or DNA
|
|
28
|
+
|
|
29
|
+
A predicted model brings its confidence into the figure, read only where the file declares it. A peptide is drawn as a chain of
|
|
30
|
+
its residues. The core imports RDKit and NumPy and nothing else.
|
|
31
|
+
"""
|
|
32
|
+
|
|
33
|
+
from __future__ import annotations
|
|
34
|
+
|
|
35
|
+
from typing import Any
|
|
36
|
+
|
|
37
|
+
from .backends import LigandBackend, Polymer, SmallMolecule
|
|
38
|
+
from .basepairs import (BasePair, BasePairs, BaseStack, pairs_from_contacts, pairs_from_dot_bracket,
|
|
39
|
+
pairs_within_from_table,
|
|
40
|
+
read_fr3d_pairs, read_fr3d_stacks, read_mmcif_pairs, read_rnapolis_pairs,
|
|
41
|
+
read_rnapolis_stacks)
|
|
42
|
+
from .interface import Interface, InterfaceContact, Participant, load_interface_contacts
|
|
43
|
+
from .compare import VIEWS, Comparison, Difference
|
|
44
|
+
from .confidence import Confidence, ModelConfidence
|
|
45
|
+
from .diagram import STYLES, Diagram, Quality, RenderResult
|
|
46
|
+
from .consensus import ResidueShare
|
|
47
|
+
from .ensemble import Ensemble, EnsembleContact
|
|
48
|
+
from .errors import (DetectionUnavailableError, EnsembleError, GraphError, InteractionError, LigandBuildError,
|
|
49
|
+
LigandNotFoundError, BindviewError, RenderError, StructureError)
|
|
50
|
+
from .fingerprint import Fingerprint, FingerprintTable
|
|
51
|
+
from .graph import Graph
|
|
52
|
+
from .interactions import Interaction, InteractionType, load_interactions, parse_interactions
|
|
53
|
+
from .options import options
|
|
54
|
+
from .peptide import Peptide, perceive_peptide
|
|
55
|
+
from .structure import Structure, read_models, read_structure
|
|
56
|
+
from .svg import stylesheet
|
|
57
|
+
from .theme import DARK, LIGHT, Metrics, Palette
|
|
58
|
+
|
|
59
|
+
__version__ = "0.1.0"
|
|
60
|
+
|
|
61
|
+
__all__ = [
|
|
62
|
+
"Diagram", "RenderResult", "Quality", "STYLES", "options", "stylesheet",
|
|
63
|
+
"Interaction", "InteractionType", "load_interactions", "parse_interactions", "detect_interactions",
|
|
64
|
+
"Structure", "read_structure", "read_models",
|
|
65
|
+
"Confidence", "ModelConfidence",
|
|
66
|
+
"Comparison", "Difference", "VIEWS", "Fingerprint", "FingerprintTable", "Graph",
|
|
67
|
+
"Ensemble", "EnsembleContact", "ResidueShare",
|
|
68
|
+
"LigandBackend", "SmallMolecule", "Polymer", "Peptide", "perceive_peptide",
|
|
69
|
+
"Interface", "InterfaceContact", "Participant", "load_interface_contacts",
|
|
70
|
+
"BasePairs", "BasePair", "BaseStack", "read_mmcif_pairs", "read_fr3d_pairs", "read_fr3d_stacks",
|
|
71
|
+
"read_rnapolis_pairs", "read_rnapolis_stacks", "pairs_from_dot_bracket", "pairs_from_contacts",
|
|
72
|
+
"pairs_within_from_table",
|
|
73
|
+
"Palette", "Metrics", "LIGHT", "DARK",
|
|
74
|
+
"BindviewError", "StructureError", "LigandNotFoundError", "LigandBuildError", "InteractionError",
|
|
75
|
+
"DetectionUnavailableError", "RenderError", "GraphError", "EnsembleError",
|
|
76
|
+
"__version__",
|
|
77
|
+
]
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def detect_interactions(structure: Any, ligand: Any) -> "list[Interaction]":
|
|
81
|
+
"""Detect interactions with PLIP (optional, GPL-2.0). See :mod:`bindview.detect`.
|
|
82
|
+
|
|
83
|
+
Defined here as a thin wrapper so that importing :mod:`bindview` never imports
|
|
84
|
+
the detector.
|
|
85
|
+
"""
|
|
86
|
+
from .detect import detect_interactions as _detect
|
|
87
|
+
|
|
88
|
+
return _detect(structure, ligand)
|
bindview/__main__.py
ADDED
bindview/align.py
ADDED
|
@@ -0,0 +1,493 @@
|
|
|
1
|
+
"""Putting several ligands of one pocket into one drawing frame.
|
|
2
|
+
|
|
3
|
+
A comparison is only readable if the thing that is the same looks the same.
|
|
4
|
+
Two ways of getting there, and one rule about when to use neither:
|
|
5
|
+
|
|
6
|
+
* **Common substructure.** When the ligands share a substantial substructure
|
|
7
|
+
(a congeneric series), every ligand is drawn with that substructure on the
|
|
8
|
+
same 2D coordinates, so the shared part is identical in every drawing and
|
|
9
|
+
only the differences move.
|
|
10
|
+
* **Pose.** When they do not, a forced maximum-common-substructure alignment
|
|
11
|
+
would look confident and mean nothing. The alignment is refused, and each
|
|
12
|
+
ligand is instead turned to match its own pose in the superposed pocket --
|
|
13
|
+
an orientation the data supports whatever the chemistry.
|
|
14
|
+
* The refusal is a number, not a judgement call: the common substructure must
|
|
15
|
+
cover ``min_fraction`` of the smallest ligand's heavy atoms (default 60 %)
|
|
16
|
+
and at least ``min_atoms`` atoms. Both numbers are reported with the result,
|
|
17
|
+
so a figure can say why it did or did not align.
|
|
18
|
+
|
|
19
|
+
The substructure search is RDKit's FMCS, seeded with the common substructure of
|
|
20
|
+
the Murcko scaffolds, which is what makes it fast. Every search has a time limit
|
|
21
|
+
of 30 s and is back at it whatever it is given (:class:`_Clock`). A seeded search
|
|
22
|
+
that is stopped there is made again without the seed; a result that the limit cut
|
|
23
|
+
short is marked incomplete rather than silently used as if it were the maximum.
|
|
24
|
+
|
|
25
|
+
The scaffold of a ligand is RDKit's, and where RDKit gives none it is made here
|
|
26
|
+
(:func:`_framework`), because a comparison must not fall with it: a build of RDKit
|
|
27
|
+
can raise ``bad any cast`` for every molecule, and any RDKit refuses a ligand of which
|
|
28
|
+
only the connectivity is known, where a clash in the model has given an atom more
|
|
29
|
+
bonds than its element can have.
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
from __future__ import annotations
|
|
33
|
+
|
|
34
|
+
import math
|
|
35
|
+
import time
|
|
36
|
+
from dataclasses import dataclass
|
|
37
|
+
from typing import TYPE_CHECKING, Sequence
|
|
38
|
+
|
|
39
|
+
import numpy as np
|
|
40
|
+
from rdkit import Chem
|
|
41
|
+
from rdkit.Chem import rdDepictor, rdFMCS
|
|
42
|
+
from rdkit.Chem.Scaffolds import MurckoScaffold
|
|
43
|
+
from rdkit.Geometry import Point2D
|
|
44
|
+
|
|
45
|
+
from .chem import quiet_rdkit
|
|
46
|
+
from .ligand import Ligand
|
|
47
|
+
from .structure import Structure
|
|
48
|
+
|
|
49
|
+
if TYPE_CHECKING: # pragma: no cover
|
|
50
|
+
from .diagram import Diagram
|
|
51
|
+
|
|
52
|
+
__all__ = ["CommonCore", "find_common_core", "core_coords", "pocket_transforms", "pocket_transforms_between",
|
|
53
|
+
"PoseFrame", "pose_frame", "pose_coords", "MIN_FRACTION", "MIN_ATOMS"]
|
|
54
|
+
|
|
55
|
+
#: A common substructure is worth aligning on when it covers this fraction of
|
|
56
|
+
#: the smallest ligand's heavy atoms ...
|
|
57
|
+
MIN_FRACTION = 0.6
|
|
58
|
+
#: ... and has at least this many atoms.
|
|
59
|
+
MIN_ATOMS = 6
|
|
60
|
+
_TIMEOUT = 30 # seconds for one search; a safety net, see the module docstring
|
|
61
|
+
_RDKIT_BOND = 1.5 # bond length of RDKit's depictor
|
|
62
|
+
_SNAP = math.radians(30.0) # a drawing is turned to its pose in steps of this: bonds stay on the usual grid
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
@dataclass(frozen=True)
|
|
66
|
+
class CommonCore:
|
|
67
|
+
"""The common substructure of a set of ligands, and whether it is worth aligning on."""
|
|
68
|
+
|
|
69
|
+
n_atoms: int
|
|
70
|
+
atoms: tuple[tuple[str, ...], ...] # per ligand: names of its core atoms, in the order of the core
|
|
71
|
+
sizes: tuple[int, ...] # heavy atoms per ligand
|
|
72
|
+
min_fraction: float
|
|
73
|
+
min_atoms: int
|
|
74
|
+
complete: bool = True # False if the search hit its timeout
|
|
75
|
+
|
|
76
|
+
@property
|
|
77
|
+
def fraction(self) -> float:
|
|
78
|
+
"""Share of the smallest ligand's heavy atoms that the core covers."""
|
|
79
|
+
smallest = min(self.sizes) if self.sizes else 0
|
|
80
|
+
return self.n_atoms / smallest if smallest else 0.0
|
|
81
|
+
|
|
82
|
+
@property
|
|
83
|
+
def substantial(self) -> bool:
|
|
84
|
+
return self.n_atoms >= self.min_atoms and self.fraction >= self.min_fraction - 1e-9
|
|
85
|
+
|
|
86
|
+
def describe(self) -> str:
|
|
87
|
+
"""One sentence for the figure: what was found and what was done with it."""
|
|
88
|
+
smallest = min(self.sizes) if self.sizes else 0
|
|
89
|
+
what = (f"the largest common substructure has {self.n_atoms} of {smallest} heavy atoms of the smallest "
|
|
90
|
+
f"ligand ({100.0 * self.fraction:.0f} %)")
|
|
91
|
+
if self.substantial:
|
|
92
|
+
text = f"Aligned on a common substructure: {what}."
|
|
93
|
+
else:
|
|
94
|
+
# The share is the reason where it is too small; else the core has too few atoms, whatever its share.
|
|
95
|
+
short = (f"below the {100.0 * self.min_fraction:.0f} % needed"
|
|
96
|
+
if self.fraction < self.min_fraction - 1e-9 else f"fewer than the {self.min_atoms} atoms needed")
|
|
97
|
+
text = f"No common scaffold: {what}, {short} to align on. No substructure alignment was made."
|
|
98
|
+
if not self.complete:
|
|
99
|
+
text += " The substructure search stopped at its time limit."
|
|
100
|
+
return text
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
class _OutOfTime(Exception):
|
|
104
|
+
"""A search is at its time limit."""
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
class _Clock(rdFMCS.MCSFinalMatchCheck):
|
|
108
|
+
"""Ends a search at its time limit, from inside it.
|
|
109
|
+
|
|
110
|
+
RDKit looks at its own clock between two candidates only. One candidate that many bonds leave, and
|
|
111
|
+
that does not match with all of them, has every subset of those bonds tried before the clock is read
|
|
112
|
+
again: a seed of a macrolide's rings with its 19 substituents is half a million subsets. This check is
|
|
113
|
+
asked at every match, accepts each, and raises once the limit is over.
|
|
114
|
+
"""
|
|
115
|
+
|
|
116
|
+
def __init__(self, seconds: float) -> None:
|
|
117
|
+
super().__init__()
|
|
118
|
+
self.end = time.monotonic() + seconds
|
|
119
|
+
|
|
120
|
+
def __call__(self, *args: object) -> bool:
|
|
121
|
+
if time.monotonic() > self.end:
|
|
122
|
+
raise _OutOfTime
|
|
123
|
+
return True
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
@dataclass(frozen=True)
|
|
127
|
+
class _Stopped:
|
|
128
|
+
"""What a search that was ended at its limit found: nothing that can be used."""
|
|
129
|
+
|
|
130
|
+
numAtoms: int = 0
|
|
131
|
+
smartsString: str = ""
|
|
132
|
+
canceled: bool = True
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def _fmcs(mols: Sequence[Chem.Mol], seed: str = "", orders: bool = True) -> "rdFMCS.MCSResult | _Stopped":
|
|
136
|
+
"""RDKit's search, which is back within :data:`_TIMEOUT` seconds whatever it is given. With ``orders``
|
|
137
|
+
an aromatic bond matches an aromatic one only; without, it matches a single bond as well."""
|
|
138
|
+
params = rdFMCS.MCSParameters()
|
|
139
|
+
params.Timeout = _TIMEOUT # type: ignore[assignment] # (RDKit's stubs)
|
|
140
|
+
params.AtomTyper = rdFMCS.AtomCompare.CompareElements
|
|
141
|
+
params.BondTyper = rdFMCS.BondCompare.CompareOrderExact if orders else rdFMCS.BondCompare.CompareOrder
|
|
142
|
+
params.AtomCompareParameters.RingMatchesRingOnly = True
|
|
143
|
+
params.BondCompareParameters.RingMatchesRingOnly = True
|
|
144
|
+
params.BondCompareParameters.CompleteRingsOnly = True
|
|
145
|
+
params.InitialSeed = seed # type: ignore[assignment]
|
|
146
|
+
params.FinalMatchChecker = _Clock(_TIMEOUT)
|
|
147
|
+
try:
|
|
148
|
+
return rdFMCS.FindMCS(list(mols), params)
|
|
149
|
+
except _OutOfTime:
|
|
150
|
+
return _Stopped()
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def _framework(mol: Chem.Mol) -> Chem.Mol:
|
|
154
|
+
"""The Murcko scaffold of a molecule, made without RDKit's ``MurckoDecompose``.
|
|
155
|
+
|
|
156
|
+
The rings, what joins them, and what is double-bonded to either. An atom at the end of a chain is
|
|
157
|
+
taken away, then the atom that has become an end, until none is left: what remains are the rings
|
|
158
|
+
and the chains between them (a molecule without a ring leaves nothing). An atom that was taken
|
|
159
|
+
away and is double-bonded to one that remains is put back. An atom that lost a neighbour is left
|
|
160
|
+
as RDKit leaves it: an aromatic heteroatom gets a hydrogen, any other atom loses its chirality and
|
|
161
|
+
takes the hydrogens its valence asks for.
|
|
162
|
+
|
|
163
|
+
The atoms keep their order, so the molecule is the one RDKit's ``GetScaffoldForMol`` gives, atom
|
|
164
|
+
for atom, and a search that is seeded with it finds the same.
|
|
165
|
+
"""
|
|
166
|
+
n = mol.GetNumAtoms()
|
|
167
|
+
nbrs = [[b.GetOtherAtomIdx(a.GetIdx()) for b in a.GetBonds()] for a in mol.GetAtoms()]
|
|
168
|
+
keep, degree = [True] * n, [len(x) for x in nbrs]
|
|
169
|
+
ends = [i for i in range(n) if degree[i] <= 1]
|
|
170
|
+
while ends:
|
|
171
|
+
i = ends.pop()
|
|
172
|
+
if not keep[i]:
|
|
173
|
+
continue
|
|
174
|
+
keep[i] = False
|
|
175
|
+
for j in nbrs[i]:
|
|
176
|
+
if keep[j]:
|
|
177
|
+
degree[j] -= 1
|
|
178
|
+
if degree[j] <= 1:
|
|
179
|
+
ends.append(j)
|
|
180
|
+
core = list(keep)
|
|
181
|
+
for b in mol.GetBonds():
|
|
182
|
+
i, j = b.GetBeginAtomIdx(), b.GetEndAtomIdx()
|
|
183
|
+
if b.GetBondType() == Chem.BondType.DOUBLE and core[i] != core[j]:
|
|
184
|
+
keep[i] = keep[j] = True
|
|
185
|
+
rw = Chem.RWMol(mol)
|
|
186
|
+
for i in range(n):
|
|
187
|
+
if keep[i]:
|
|
188
|
+
continue
|
|
189
|
+
for j in nbrs[i]:
|
|
190
|
+
if keep[j]:
|
|
191
|
+
atom = rw.GetAtomWithIdx(j)
|
|
192
|
+
if atom.GetIsAromatic() and atom.GetAtomicNum() != 6:
|
|
193
|
+
atom.SetNumExplicitHs(1)
|
|
194
|
+
else:
|
|
195
|
+
atom.SetChiralTag(Chem.ChiralType.CHI_UNSPECIFIED)
|
|
196
|
+
atom.SetNoImplicit(False)
|
|
197
|
+
atom.SetNumExplicitHs(0)
|
|
198
|
+
for i in range(n - 1, -1, -1): # from the last, so that no index moves under the loop
|
|
199
|
+
if not keep[i]:
|
|
200
|
+
rw.RemoveAtom(i)
|
|
201
|
+
out = rw.GetMol()
|
|
202
|
+
out.ClearComputedProps()
|
|
203
|
+
out.UpdatePropertyCache(strict=False)
|
|
204
|
+
Chem.GetSymmSSSR(out)
|
|
205
|
+
return out
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def _scaffold(mol: Chem.Mol) -> Chem.Mol:
|
|
209
|
+
"""The Murcko scaffold of a molecule: RDKit's, and the one made here where RDKit raises."""
|
|
210
|
+
try:
|
|
211
|
+
return MurckoScaffold.GetScaffoldForMol(mol)
|
|
212
|
+
except (RuntimeError, ValueError): # (RDKit's valence error is a ValueError)
|
|
213
|
+
return _framework(mol)
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def find_common_core(ligands: Sequence[Ligand], min_fraction: float = MIN_FRACTION,
|
|
217
|
+
min_atoms: int = MIN_ATOMS) -> CommonCore:
|
|
218
|
+
"""The maximum common substructure of ``ligands``, with the verdict on whether to align on it.
|
|
219
|
+
|
|
220
|
+
Elements must match, and bond orders: a single, a double, a triple and an aromatic bond match their
|
|
221
|
+
own kind (a phenyl ring is no cyclohexyl ring). Where the bond orders of one of the ligands are not
|
|
222
|
+
known, only its connectivity, all its bonds are single ones to the search, and an aromatic bond of
|
|
223
|
+
another ligand matches a single one: a double bond of another ligand still does not. An atom of a
|
|
224
|
+
ring matches an atom of a ring only, and a ring is in the substructure whole or not at all.
|
|
225
|
+
"""
|
|
226
|
+
sizes = tuple(lig.n_atoms for lig in ligands)
|
|
227
|
+
empty = CommonCore(0, tuple(() for _ in ligands), sizes, min_fraction, min_atoms)
|
|
228
|
+
if len(ligands) < 2 or min(sizes) < 2:
|
|
229
|
+
return empty
|
|
230
|
+
mols = [lig.mol for lig in ligands]
|
|
231
|
+
orders = all(lig.bond_source != "connectivity" for lig in ligands)
|
|
232
|
+
with quiet_rdkit():
|
|
233
|
+
scaffolds = [_scaffold(m) for m in mols]
|
|
234
|
+
seed, complete = "", True
|
|
235
|
+
if all(s.GetNumAtoms() >= 3 for s in scaffolds):
|
|
236
|
+
first = _fmcs(scaffolds, orders=orders)
|
|
237
|
+
complete = not first.canceled
|
|
238
|
+
if first.numAtoms >= 3:
|
|
239
|
+
seed = first.smartsString
|
|
240
|
+
result = _fmcs(mols, seed, orders)
|
|
241
|
+
if result.numAtoms == 0 and seed:
|
|
242
|
+
# The scaffold core did not extend, or the seeded search was stopped at its limit: search unseeded.
|
|
243
|
+
result = _fmcs(mols, orders=orders)
|
|
244
|
+
complete = complete and not result.canceled
|
|
245
|
+
if result.numAtoms == 0:
|
|
246
|
+
return CommonCore(0, empty.atoms, sizes, min_fraction, min_atoms, complete)
|
|
247
|
+
query = Chem.MolFromSmarts(result.smartsString)
|
|
248
|
+
matches = []
|
|
249
|
+
for lig, mol in zip(ligands, mols):
|
|
250
|
+
match = mol.GetSubstructMatch(query)
|
|
251
|
+
if not match: # cannot happen for a true common substructure
|
|
252
|
+
return CommonCore(0, empty.atoms, sizes, min_fraction, min_atoms, False)
|
|
253
|
+
matches.append(tuple(lig.names[i] for i in match))
|
|
254
|
+
return CommonCore(int(result.numAtoms), tuple(matches), sizes, min_fraction, min_atoms, complete)
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def core_coords(lig: Ligand, core_names: Sequence[str], reference: Sequence[tuple[float, float]]
|
|
258
|
+
) -> dict[str, tuple[float, float]]:
|
|
259
|
+
"""2D coordinates of ``lig`` (bond-length units, y up) with its core atoms **on** ``reference``.
|
|
260
|
+
|
|
261
|
+
The core atoms are locked to the reference positions and RDKit's depictor
|
|
262
|
+
lays out the rest around them, so the shared part of two ligands is
|
|
263
|
+
identical to the last digit and only what differs is drawn differently.
|
|
264
|
+
"""
|
|
265
|
+
index = {name: i for i, name in enumerate(lig.names)}
|
|
266
|
+
locked = {index[name]: Point2D(float(x) * _RDKIT_BOND, float(y) * _RDKIT_BOND)
|
|
267
|
+
for name, (x, y) in zip(core_names, reference)}
|
|
268
|
+
mol = Chem.Mol(lig.mol)
|
|
269
|
+
mol.RemoveAllConformers()
|
|
270
|
+
with quiet_rdkit():
|
|
271
|
+
prefer = rdDepictor.GetPreferCoordGen()
|
|
272
|
+
rdDepictor.SetPreferCoordGen(False)
|
|
273
|
+
try:
|
|
274
|
+
rdDepictor.Compute2DCoords(mol, coordMap=locked, canonOrient=False, clearConfs=True)
|
|
275
|
+
finally:
|
|
276
|
+
rdDepictor.SetPreferCoordGen(prefer)
|
|
277
|
+
conf = mol.GetConformer()
|
|
278
|
+
out = {}
|
|
279
|
+
for i, name in enumerate(lig.names):
|
|
280
|
+
p = conf.GetAtomPosition(i)
|
|
281
|
+
out[name] = (float(p.x) / _RDKIT_BOND, float(p.y) / _RDKIT_BOND)
|
|
282
|
+
# Counter-ions and other pieces that hold no core atom are set down in a row
|
|
283
|
+
# under the drawing instead of wherever the depictor left them.
|
|
284
|
+
anchored = [frag for frag in Chem.GetMolFrags(mol) if any(i in locked for i in frag)]
|
|
285
|
+
loose = [frag for frag in Chem.GetMolFrags(mol) if not any(i in locked for i in frag)]
|
|
286
|
+
if loose and anchored:
|
|
287
|
+
main = [out[lig.names[i]] for frag in anchored for i in frag]
|
|
288
|
+
x0, y0 = min(p[0] for p in main), min(p[1] for p in main)
|
|
289
|
+
for j, frag in enumerate(loose):
|
|
290
|
+
fx = sum(out[lig.names[i]][0] for i in frag) / len(frag)
|
|
291
|
+
fy = sum(out[lig.names[i]][1] for i in frag) / len(frag)
|
|
292
|
+
for i in frag:
|
|
293
|
+
x, y = out[lig.names[i]]
|
|
294
|
+
out[lig.names[i]] = (x - fx + x0 + 2.4 * j, y - fy + y0 - 1.6)
|
|
295
|
+
for name, (x, y) in zip(core_names, reference):
|
|
296
|
+
out[name] = (float(x), float(y)) # exactly, not to depictor precision
|
|
297
|
+
return out
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
# ---------------------------------------------------------------------------
|
|
301
|
+
# Pocket superposition and pose-based orientation
|
|
302
|
+
# ---------------------------------------------------------------------------
|
|
303
|
+
|
|
304
|
+
_BACKBONE = ("N", "CA", "C")
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
def _kabsch(mobile: np.ndarray, target: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
|
|
308
|
+
"""``(R, t)`` with ``target ~ mobile @ R.T + t`` (least squares, proper rotation)."""
|
|
309
|
+
mc, tc = mobile.mean(axis=0), target.mean(axis=0)
|
|
310
|
+
h = (mobile - mc).T @ (target - tc)
|
|
311
|
+
u, _, vt = np.linalg.svd(h)
|
|
312
|
+
d = np.sign(np.linalg.det(vt.T @ u.T)) or 1.0
|
|
313
|
+
rot = vt.T @ np.diag([1.0, 1.0, d]) @ u.T
|
|
314
|
+
return rot, tc - mc @ rot.T
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
def _backbone(st: Structure) -> dict[tuple[str, int, str], tuple[str, dict[str, np.ndarray]]]:
|
|
318
|
+
"""Backbone atoms of every polymer residue: ``(chain, number, icode) -> (name, {atom: xyz})``."""
|
|
319
|
+
coords = st.coords
|
|
320
|
+
out: dict[tuple[str, int, str], tuple[str, dict[str, np.ndarray]]] = {}
|
|
321
|
+
for a in st.atoms:
|
|
322
|
+
if not a.hetero and a.name in _BACKBONE:
|
|
323
|
+
out.setdefault((a.chain, a.resnum, a.icode), (a.resname, {}))[1][a.name] = coords[a.index]
|
|
324
|
+
return out
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
def _near(backbone: dict, lig_xyz: np.ndarray, radius: float) -> set[tuple[str, int, str]]:
|
|
328
|
+
out = set()
|
|
329
|
+
for key, (_name, atoms) in backbone.items():
|
|
330
|
+
pts = np.array(list(atoms.values()))
|
|
331
|
+
if float(np.linalg.norm(pts[:, None, :] - lig_xyz[None, :, :], axis=2).min()) <= radius:
|
|
332
|
+
out.add(key)
|
|
333
|
+
return out
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
#: A structure is superposed by its residues with a backbone atom within this many angstrom of its ligand.
|
|
337
|
+
_RADIUS = 10.0
|
|
338
|
+
#: Share of the residues around the ligands that must carry the same name in both structures ...
|
|
339
|
+
_MIN_IDENTITY = 0.7
|
|
340
|
+
#: ... and the backbone RMSD (angstrom) the fit may leave, for the two to count as one pocket.
|
|
341
|
+
_MAX_RMSD = 3.0
|
|
342
|
+
|
|
343
|
+
|
|
344
|
+
_Pocket = tuple[dict[tuple[str, int, str], tuple[str, dict[str, np.ndarray]]], set[tuple[str, int, str]]]
|
|
345
|
+
_Fit = tuple[tuple[np.ndarray, np.ndarray] | None, float | None]
|
|
346
|
+
|
|
347
|
+
|
|
348
|
+
def _pocket(dia: "Diagram") -> "_Pocket | None":
|
|
349
|
+
"""What a structure is superposed by: its backbone, and the residues of it around its ligand."""
|
|
350
|
+
if dia.structure is None:
|
|
351
|
+
return None
|
|
352
|
+
backbone = _backbone(dia.structure)
|
|
353
|
+
return backbone, _near(backbone, dia.ligand.coords3d, _RADIUS)
|
|
354
|
+
|
|
355
|
+
|
|
356
|
+
def _fit(ref: _Pocket, own: _Pocket) -> _Fit:
|
|
357
|
+
"""The transform that puts the structure of ``own`` into the frame of ``ref``, and the backbone RMSD that
|
|
358
|
+
the fit leaves: no transform where that is more than 3 angstrom, and neither where no fit can be made."""
|
|
359
|
+
(ref_bb, ref_near), (own_bb, own_near) = ref, own
|
|
360
|
+
both = sorted((ref_near | own_near) & set(ref_bb) & set(own_bb))
|
|
361
|
+
same = [key for key in both if ref_bb[key][0] == own_bb[key][0]]
|
|
362
|
+
if len(same) < 4 or len(same) < _MIN_IDENTITY * len(both):
|
|
363
|
+
return None, None
|
|
364
|
+
mobile, target = [], []
|
|
365
|
+
for key in same:
|
|
366
|
+
for atom in _BACKBONE:
|
|
367
|
+
if atom in ref_bb[key][1] and atom in own_bb[key][1]:
|
|
368
|
+
mobile.append(own_bb[key][1][atom])
|
|
369
|
+
target.append(ref_bb[key][1][atom])
|
|
370
|
+
rot, shift = _kabsch(np.array(mobile), np.array(target))
|
|
371
|
+
rmsd = float(np.sqrt((((np.array(mobile) @ rot.T + shift) - np.array(target)) ** 2).sum(axis=1).mean()))
|
|
372
|
+
return ((rot, shift) if rmsd <= _MAX_RMSD else None), rmsd
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
def pocket_transforms(diagrams: "Sequence[Diagram]", rmsds: "list[float | None] | None" = None
|
|
376
|
+
) -> list[tuple[np.ndarray, np.ndarray] | None]:
|
|
377
|
+
"""Rigid transforms that put every structure into the frame of the first.
|
|
378
|
+
|
|
379
|
+
Each structure is superposed on the first by the backbone atoms (N, CA,
|
|
380
|
+
C) of the residues around either ligand. The residue numbering is what a
|
|
381
|
+
comparison takes as given, and it is checked rather than trusted: an entry
|
|
382
|
+
is ``None`` -- no common frame -- unless at least four residues match, 70 %
|
|
383
|
+
of the residues compared carry the same name in both structures, and the
|
|
384
|
+
fit leaves a backbone RMSD of at most 3 angstrom. Two different proteins
|
|
385
|
+
share a few (number, name) pairs by chance and do not pass this; neither do
|
|
386
|
+
two models of one protein whose pockets are folded differently. ``rmsds``,
|
|
387
|
+
if given, receives the RMSD of every fit that was made (``None`` where no
|
|
388
|
+
fit was possible).
|
|
389
|
+
"""
|
|
390
|
+
out: list[tuple[np.ndarray, np.ndarray] | None] = []
|
|
391
|
+
if rmsds is not None:
|
|
392
|
+
rmsds[:] = [None] * len(diagrams)
|
|
393
|
+
base = _pocket(diagrams[0])
|
|
394
|
+
if base is None:
|
|
395
|
+
return [None] * len(diagrams)
|
|
396
|
+
for k, dia in enumerate(diagrams):
|
|
397
|
+
if k == 0:
|
|
398
|
+
out.append((np.eye(3), np.zeros(3)))
|
|
399
|
+
if rmsds is not None:
|
|
400
|
+
rmsds[k] = 0.0
|
|
401
|
+
continue
|
|
402
|
+
own = _pocket(dia)
|
|
403
|
+
if own is None:
|
|
404
|
+
out.append(None)
|
|
405
|
+
continue
|
|
406
|
+
frame, rmsd = _fit(base, own)
|
|
407
|
+
if rmsds is not None:
|
|
408
|
+
rmsds[k] = rmsd
|
|
409
|
+
out.append(frame)
|
|
410
|
+
return out
|
|
411
|
+
|
|
412
|
+
|
|
413
|
+
def pocket_transforms_between(diagrams: "Sequence[Diagram]") -> dict[tuple[int, int], _Fit]:
|
|
414
|
+
"""For every two structures ``i < j``: the transform that puts ``j`` into the frame of ``i`` and the backbone
|
|
415
|
+
RMSD of the fit, as :func:`pocket_transforms` gives them for the two (``None`` for either as there, and
|
|
416
|
+
for both where one has no structure). Every structure is read once, however many it is compared with."""
|
|
417
|
+
pockets = [_pocket(dia) for dia in diagrams]
|
|
418
|
+
out: dict[tuple[int, int], _Fit] = {}
|
|
419
|
+
for i, ref in enumerate(pockets):
|
|
420
|
+
for j in range(i + 1, len(pockets)):
|
|
421
|
+
own = pockets[j]
|
|
422
|
+
out[(i, j)] = _fit(ref, own) if ref is not None and own is not None else (None, None)
|
|
423
|
+
return out
|
|
424
|
+
|
|
425
|
+
|
|
426
|
+
@dataclass(frozen=True)
|
|
427
|
+
class PoseFrame:
|
|
428
|
+
"""A plane through the superposed ligands: where 3D poses are looked at from."""
|
|
429
|
+
|
|
430
|
+
origin: np.ndarray # (3,) centroid of all ligand atoms
|
|
431
|
+
axes: np.ndarray # (2, 3) orthonormal in-plane axes, widest first
|
|
432
|
+
|
|
433
|
+
def project(self, xyz: np.ndarray) -> np.ndarray:
|
|
434
|
+
return (np.asarray(xyz, dtype=float) - self.origin) @ self.axes.T
|
|
435
|
+
|
|
436
|
+
|
|
437
|
+
def pose_frame(clouds: Sequence[np.ndarray]) -> PoseFrame:
|
|
438
|
+
"""The best-fit plane of all ligand atoms (already in one 3D frame).
|
|
439
|
+
|
|
440
|
+
The two in-plane axes are the directions of largest spread, so the view is
|
|
441
|
+
the one in which the poses overlap least. Their signs are fixed by a rule
|
|
442
|
+
(positive third moment, then first atom), which makes the frame a function
|
|
443
|
+
of the coordinates alone.
|
|
444
|
+
"""
|
|
445
|
+
pts = np.vstack([np.asarray(c, dtype=float).reshape(-1, 3) for c in clouds])
|
|
446
|
+
origin = pts.mean(axis=0)
|
|
447
|
+
centred = pts - origin
|
|
448
|
+
if len(pts) < 3:
|
|
449
|
+
return PoseFrame(origin, np.array([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]))
|
|
450
|
+
_, _, vt = np.linalg.svd(centred, full_matrices=False)
|
|
451
|
+
axes = vt[:2].copy()
|
|
452
|
+
for i in range(2):
|
|
453
|
+
proj = centred @ axes[i]
|
|
454
|
+
skew = float((proj ** 3).sum())
|
|
455
|
+
if abs(skew) < 1e-6:
|
|
456
|
+
skew = float(proj[0])
|
|
457
|
+
if skew < 0:
|
|
458
|
+
axes[i] = -axes[i]
|
|
459
|
+
return PoseFrame(origin, axes)
|
|
460
|
+
|
|
461
|
+
|
|
462
|
+
def pose_coords(names: Sequence[str], own_xy: np.ndarray, projected: np.ndarray, scale: float
|
|
463
|
+
) -> dict[str, tuple[float, float]]:
|
|
464
|
+
"""Turn a ligand's own 2D drawing so that it matches its projected 3D pose.
|
|
465
|
+
|
|
466
|
+
``own_xy`` are the drawing's coordinates (bond-length units, y up),
|
|
467
|
+
``projected`` the same atoms in the pose plane (angstrom). The drawing is
|
|
468
|
+
rotated -- and mirrored if that fits better -- by the least-squares fit,
|
|
469
|
+
with the angle snapped to steps of 30 degrees so bonds stay on the usual
|
|
470
|
+
drawing grid, and moved so that its centre sits where the pose's centre is
|
|
471
|
+
(``scale`` bond lengths per angstrom). The drawing itself is not distorted.
|
|
472
|
+
"""
|
|
473
|
+
u = np.asarray(own_xy, dtype=float).reshape(-1, 2)
|
|
474
|
+
p = np.asarray(projected, dtype=float).reshape(-1, 2)
|
|
475
|
+
uc, pc = u.mean(axis=0), p.mean(axis=0)
|
|
476
|
+
best: tuple[float, np.ndarray] | None = None
|
|
477
|
+
for mirror in (False, True):
|
|
478
|
+
v = (u - uc) * (np.array([1.0, -1.0]) if mirror else 1.0)
|
|
479
|
+
# Optimal rotation angle of v onto p - pc (2D Procrustes in closed form).
|
|
480
|
+
num = float((v[:, 0] * (p[:, 1] - pc[1]) - v[:, 1] * (p[:, 0] - pc[0])).sum())
|
|
481
|
+
den = float((v[:, 0] * (p[:, 0] - pc[0]) + v[:, 1] * (p[:, 1] - pc[1])).sum())
|
|
482
|
+
theta = round(math.atan2(num, den) / _SNAP) * _SNAP
|
|
483
|
+
c, s = math.cos(theta), math.sin(theta)
|
|
484
|
+
turned = np.column_stack([v[:, 0] * c - v[:, 1] * s, v[:, 0] * s + v[:, 1] * c])
|
|
485
|
+
# Compare shapes at the pose's own size, so the choice does not depend on the units.
|
|
486
|
+
size_t = math.sqrt(float((turned ** 2).sum())) or 1.0
|
|
487
|
+
size_p = math.sqrt(float(((p - pc) ** 2).sum())) or 1.0
|
|
488
|
+
err = round(float(((turned / size_t - (p - pc) / size_p) ** 2).sum()), 9)
|
|
489
|
+
if best is None or err < best[0] - 1e-9:
|
|
490
|
+
best = (err, turned)
|
|
491
|
+
assert best is not None
|
|
492
|
+
placed = best[1] + pc * scale
|
|
493
|
+
return {name: (float(placed[i, 0]), float(placed[i, 1])) for i, name in enumerate(names)}
|