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/scene.py
ADDED
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
"""A tiny retained scene graph.
|
|
2
|
+
|
|
3
|
+
Renderers do not write SVG. They build a :class:`Scene` out of primitives whose
|
|
4
|
+
colours are palette *tokens*, and :mod:`bindview.svg` serialises it. Two things
|
|
5
|
+
follow: styles share all the plumbing (a second style is a different way of
|
|
6
|
+
filling a scene, nothing more), and the geometry that was drawn can be inspected
|
|
7
|
+
by tests -- "nothing overlaps" is checked on the scene, not on pixels.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
from dataclasses import dataclass, field, replace
|
|
13
|
+
from typing import Sequence
|
|
14
|
+
|
|
15
|
+
__all__ = ["Paint", "Line", "Polygon", "Polyline", "Circle", "Rect", "Path", "Text", "Span",
|
|
16
|
+
"Group", "Scene", "Item", "item_bounds", "items_bounds", "text_box"]
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass(frozen=True)
|
|
20
|
+
class Paint:
|
|
21
|
+
"""How a primitive is painted. ``stroke`` / ``fill`` are palette tokens
|
|
22
|
+
(``"hbond"``, ``"element_N"``) or ``None``; a token starting with ``#`` is a
|
|
23
|
+
literal colour and should only come from a caller-supplied palette."""
|
|
24
|
+
|
|
25
|
+
stroke: str | None = None
|
|
26
|
+
fill: str | None = None
|
|
27
|
+
width: float = 1.0
|
|
28
|
+
dash: tuple[float, ...] = ()
|
|
29
|
+
opacity: float = 1.0
|
|
30
|
+
cap: str = "round"
|
|
31
|
+
join: str = "round"
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@dataclass(frozen=True)
|
|
35
|
+
class Line:
|
|
36
|
+
x1: float
|
|
37
|
+
y1: float
|
|
38
|
+
x2: float
|
|
39
|
+
y2: float
|
|
40
|
+
paint: Paint
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@dataclass(frozen=True)
|
|
44
|
+
class Polyline:
|
|
45
|
+
points: tuple[tuple[float, float], ...]
|
|
46
|
+
paint: Paint
|
|
47
|
+
closed: bool = False
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
@dataclass(frozen=True)
|
|
51
|
+
class Polygon:
|
|
52
|
+
points: tuple[tuple[float, float], ...]
|
|
53
|
+
paint: Paint
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
@dataclass(frozen=True)
|
|
57
|
+
class Circle:
|
|
58
|
+
cx: float
|
|
59
|
+
cy: float
|
|
60
|
+
r: float
|
|
61
|
+
paint: Paint
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
@dataclass(frozen=True)
|
|
65
|
+
class Rect:
|
|
66
|
+
x: float
|
|
67
|
+
y: float
|
|
68
|
+
w: float
|
|
69
|
+
h: float
|
|
70
|
+
paint: Paint
|
|
71
|
+
rx: float = 0.0
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
@dataclass(frozen=True)
|
|
75
|
+
class Path:
|
|
76
|
+
"""Raw path data, already in final coordinates: a list of ``(cmd, numbers...)``."""
|
|
77
|
+
|
|
78
|
+
commands: tuple[tuple, ...]
|
|
79
|
+
paint: Paint
|
|
80
|
+
bbox: tuple[float, float, float, float] | None = None # ink box, when the commands include arcs
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
@dataclass(frozen=True)
|
|
84
|
+
class Span:
|
|
85
|
+
"""A run of text. ``dy`` shifts the baseline (sub/superscripts)."""
|
|
86
|
+
|
|
87
|
+
text: str
|
|
88
|
+
size: float | None = None
|
|
89
|
+
dy: float = 0.0
|
|
90
|
+
fill: str | None = None
|
|
91
|
+
bold: bool | None = None
|
|
92
|
+
italic: bool = False
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
@dataclass(frozen=True)
|
|
96
|
+
class Text:
|
|
97
|
+
"""Text anchored at ``(x, y)`` where ``y`` is the *baseline*."""
|
|
98
|
+
|
|
99
|
+
x: float
|
|
100
|
+
y: float
|
|
101
|
+
spans: tuple[Span, ...]
|
|
102
|
+
size: float
|
|
103
|
+
fill: str
|
|
104
|
+
anchor: str = "middle" # start | middle | end
|
|
105
|
+
bold: bool = False
|
|
106
|
+
italic: bool = False
|
|
107
|
+
opacity: float = 1.0
|
|
108
|
+
|
|
109
|
+
@classmethod
|
|
110
|
+
def plain(cls, x: float, y: float, text: str, size: float, fill: str, anchor: str = "middle",
|
|
111
|
+
bold: bool = False, italic: bool = False, opacity: float = 1.0) -> "Text":
|
|
112
|
+
return cls(x, y, (Span(text),), size, fill, anchor, bold, italic, opacity)
|
|
113
|
+
|
|
114
|
+
@property
|
|
115
|
+
def content(self) -> str:
|
|
116
|
+
return "".join(s.text for s in self.spans)
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
@dataclass
|
|
120
|
+
class Group:
|
|
121
|
+
"""A named group. ``cls`` becomes the SVG class, ``data`` become ``data-*``
|
|
122
|
+
attributes, ``title`` a tooltip. ``opacity`` fades the group *as a whole*:
|
|
123
|
+
strokes that overlap inside it (bonds meeting at an atom) do not add up. What is
|
|
124
|
+
not ``bounded`` takes no room: the page is not made larger for it."""
|
|
125
|
+
|
|
126
|
+
cls: str
|
|
127
|
+
items: list["Item"] = field(default_factory=list)
|
|
128
|
+
data: dict[str, str] = field(default_factory=dict)
|
|
129
|
+
title: str | None = None
|
|
130
|
+
translate: tuple[float, float] | None = None
|
|
131
|
+
opacity: float = 1.0
|
|
132
|
+
bounded: bool = True
|
|
133
|
+
|
|
134
|
+
def add(self, *items: "Item") -> "Group":
|
|
135
|
+
self.items.extend(items)
|
|
136
|
+
return self
|
|
137
|
+
|
|
138
|
+
def extend(self, items: Sequence["Item"]) -> "Group":
|
|
139
|
+
self.items.extend(items)
|
|
140
|
+
return self
|
|
141
|
+
|
|
142
|
+
def copy(self) -> "Group":
|
|
143
|
+
"""A group of its own with the same content: the groups in it are copied too, and what else it holds
|
|
144
|
+
cannot be changed, so the two share that."""
|
|
145
|
+
return replace(self, items=_copies(self.items), data=dict(self.data))
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
Item = Line | Polyline | Polygon | Circle | Rect | Path | Text | Group
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
@dataclass
|
|
152
|
+
class Scene:
|
|
153
|
+
width: float
|
|
154
|
+
height: float
|
|
155
|
+
items: list[Item] = field(default_factory=list)
|
|
156
|
+
title: str = ""
|
|
157
|
+
description: str = ""
|
|
158
|
+
#: The words around the drawing, drawn or left off (:attr:`bindview.diagram.RenderResult.notes`).
|
|
159
|
+
#: Not written into the file.
|
|
160
|
+
notes: list[str] = field(default_factory=list)
|
|
161
|
+
|
|
162
|
+
def add(self, *items: Item) -> None:
|
|
163
|
+
self.items.extend(items)
|
|
164
|
+
|
|
165
|
+
def copy(self) -> "Scene":
|
|
166
|
+
"""A scene of its own with the same content (:meth:`Group.copy`): changing it changes no other."""
|
|
167
|
+
return replace(self, items=_copies(self.items), notes=list(self.notes))
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _copies(items: Sequence[Item]) -> list[Item]:
|
|
171
|
+
return [it.copy() if isinstance(it, Group) else it for it in items]
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
# -- bounds ------------------------------------------------------------------
|
|
175
|
+
|
|
176
|
+
def text_box(t: Text) -> tuple[float, float, float, float]:
|
|
177
|
+
"""Estimated ink box of a text item ``(x0, y0, x1, y1)`` from the metrics table."""
|
|
178
|
+
from .textmetrics import CAP_HEIGHT, DESCENT, text_width
|
|
179
|
+
|
|
180
|
+
width = 0.0
|
|
181
|
+
up, down = CAP_HEIGHT * t.size, 0.0
|
|
182
|
+
shift = 0.0
|
|
183
|
+
for s in t.spans:
|
|
184
|
+
size = s.size if s.size is not None else t.size
|
|
185
|
+
bold = s.bold if s.bold is not None else t.bold
|
|
186
|
+
shift += s.dy
|
|
187
|
+
if s.text:
|
|
188
|
+
width += text_width(s.text, size, bold)
|
|
189
|
+
up = max(up, CAP_HEIGHT * size - shift)
|
|
190
|
+
down = max(down, shift + (DESCENT * size if any(c in "gjpqy()," for c in s.text) else 0.0))
|
|
191
|
+
if t.anchor == "middle":
|
|
192
|
+
x0 = t.x - width / 2.0
|
|
193
|
+
elif t.anchor == "end":
|
|
194
|
+
x0 = t.x - width
|
|
195
|
+
else:
|
|
196
|
+
x0 = t.x
|
|
197
|
+
return (x0, t.y - up, x0 + width, t.y + down)
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def item_bounds(it: "Item") -> tuple[float, float, float, float] | None:
|
|
201
|
+
"""Bounding box of an item in its parent's coordinates, stroke width included."""
|
|
202
|
+
if isinstance(it, Group):
|
|
203
|
+
b = items_bounds(it.items) if it.bounded else None
|
|
204
|
+
if b is None or it.translate is None:
|
|
205
|
+
return b
|
|
206
|
+
dx, dy = it.translate
|
|
207
|
+
return (b[0] + dx, b[1] + dy, b[2] + dx, b[3] + dy)
|
|
208
|
+
if isinstance(it, Text):
|
|
209
|
+
return text_box(it)
|
|
210
|
+
pad = it.paint.width / 2.0 if it.paint.stroke is not None else 0.0
|
|
211
|
+
if isinstance(it, Line):
|
|
212
|
+
return (min(it.x1, it.x2) - pad, min(it.y1, it.y2) - pad, max(it.x1, it.x2) + pad, max(it.y1, it.y2) + pad)
|
|
213
|
+
if isinstance(it, (Polygon, Polyline)):
|
|
214
|
+
xs = [p[0] for p in it.points]
|
|
215
|
+
ys = [p[1] for p in it.points]
|
|
216
|
+
return (min(xs) - pad, min(ys) - pad, max(xs) + pad, max(ys) + pad)
|
|
217
|
+
if isinstance(it, Circle):
|
|
218
|
+
return (it.cx - it.r - pad, it.cy - it.r - pad, it.cx + it.r + pad, it.cy + it.r + pad)
|
|
219
|
+
if isinstance(it, Rect):
|
|
220
|
+
return (it.x - pad, it.y - pad, it.x + it.w + pad, it.y + it.h + pad)
|
|
221
|
+
if isinstance(it, Path):
|
|
222
|
+
if it.bbox is not None:
|
|
223
|
+
return (it.bbox[0] - pad, it.bbox[1] - pad, it.bbox[2] + pad, it.bbox[3] + pad)
|
|
224
|
+
xs, ys = [], []
|
|
225
|
+
for c in it.commands:
|
|
226
|
+
nums = [v for v in c[1:] if isinstance(v, float)]
|
|
227
|
+
xs.extend(nums[0::2])
|
|
228
|
+
ys.extend(nums[1::2])
|
|
229
|
+
if not xs:
|
|
230
|
+
return None
|
|
231
|
+
return (min(xs) - pad, min(ys) - pad, max(xs) + pad, max(ys) + pad)
|
|
232
|
+
return None
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def items_bounds(items: Sequence["Item"]) -> tuple[float, float, float, float] | None:
|
|
236
|
+
boxes = [b for b in (item_bounds(i) for i in items) if b is not None]
|
|
237
|
+
if not boxes:
|
|
238
|
+
return None
|
|
239
|
+
return (min(b[0] for b in boxes), min(b[1] for b in boxes), max(b[2] for b in boxes), max(b[3] for b in boxes))
|
bindview/solvent.py
ADDED
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
"""Predicted solvent sites: where a water could bridge ligand and protein.
|
|
2
|
+
|
|
3
|
+
A predicted model has no solvent. Where the ligand and the protein leave a
|
|
4
|
+
small enclosed gap lined by hydrogen-bond partners on both sides, a water
|
|
5
|
+
molecule is a reasonable guess -- and it is a guess. This module makes it, by
|
|
6
|
+
geometry alone and with NumPy alone:
|
|
7
|
+
|
|
8
|
+
1. a lattice is laid over the space around the ligand's polar atoms;
|
|
9
|
+
2. points too close to any heavy atom to hold a water oxygen are dropped;
|
|
10
|
+
3. points that are open to bulk solvent are dropped (the *enclosure* filter:
|
|
11
|
+
of a set of directions from the point, most must run into the model);
|
|
12
|
+
4. each remaining point is scored by the polar atoms of protein and ligand that
|
|
13
|
+
lie at hydrogen-bond distance **and point at it**;
|
|
14
|
+
5. sites are picked greedily, best first, no two closer than two waters can be.
|
|
15
|
+
|
|
16
|
+
Only *bridging* sites are returned: at least one partner on the protein and
|
|
17
|
+
one on the ligand, because that is what a diagram can draw.
|
|
18
|
+
|
|
19
|
+
What this is not: it is not a hydration model, it knows nothing of energies or
|
|
20
|
+
occupancy, and it cannot tell a water from an ion. What it should be judged by
|
|
21
|
+
is its hit rate against crystallographic waters, not this description:
|
|
22
|
+
``docs/reference.md`` has that measurement. In short, with the waters
|
|
23
|
+
held out of crystal structures it finds about seven bridging waters in ten,
|
|
24
|
+
and nearly half of the sites it proposes have no water in the crystal. That
|
|
25
|
+
was measured where the gap a water left is still in the model; a predicted
|
|
26
|
+
model need not leave one, and there it has not been tested. It is off unless
|
|
27
|
+
asked for, never runs on a structure that contains waters of its own, and
|
|
28
|
+
everything it produces is marked as predicted.
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
from __future__ import annotations
|
|
32
|
+
|
|
33
|
+
import math
|
|
34
|
+
from dataclasses import dataclass
|
|
35
|
+
from typing import Any
|
|
36
|
+
|
|
37
|
+
import numpy as np
|
|
38
|
+
|
|
39
|
+
from .exposure import PROBE, WATER_NAMES, _radius, _sphere
|
|
40
|
+
|
|
41
|
+
__all__ = ["SolventSite", "SolventParams", "predict_solvent_sites", "candidate_points", "water_oxygens",
|
|
42
|
+
"has_waters", "VALIDATION"]
|
|
43
|
+
|
|
44
|
+
#: What is known about how good these predictions are, in one sentence, printed under every figure
|
|
45
|
+
#: that shows one. It is the sentence ``scripts/validate_solvent.py`` writes from the hold-out numbers
|
|
46
|
+
#: (``tests/data/solvent-validation.json``); a test keeps the two equal.
|
|
47
|
+
VALIDATION = ("In a hold-out test on 42 crystal structures they recovered 71 % of the bridging waters, and 46 % of "
|
|
48
|
+
"the predicted sites had no observed water within 1.5 Å.")
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@dataclass(frozen=True)
|
|
52
|
+
class SolventParams:
|
|
53
|
+
"""The knobs of the predictor. The defaults are set from geometry; none is fitted to the validation."""
|
|
54
|
+
|
|
55
|
+
spacing: float = 0.5 # lattice spacing, angstrom
|
|
56
|
+
reach: float = 3.5 # a site lies within this of a ligand N or O
|
|
57
|
+
polar_contact: float = 2.6 # closest a water oxygen comes to an N or O (a short hydrogen bond)
|
|
58
|
+
hbond_max: float = 3.3 # farthest an N or O can be and still count as a partner
|
|
59
|
+
min_enclosure: float = 0.6 # share of directions that must run into the model
|
|
60
|
+
ray_length: float = 8.0 # how far a direction is followed
|
|
61
|
+
n_rays: int = 30
|
|
62
|
+
separation: float = 2.6 # two sites are at least this far apart
|
|
63
|
+
cone_one: float = 100.0 # partner with one bonded heavy atom: site within this angle of its open side
|
|
64
|
+
cone_many: float = 65.0 # ... with two or more
|
|
65
|
+
max_sites: int = 6
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
@dataclass(frozen=True)
|
|
69
|
+
class SolventSite:
|
|
70
|
+
"""One predicted site, with the atoms that would hold a water there."""
|
|
71
|
+
|
|
72
|
+
xyz: tuple[float, float, float]
|
|
73
|
+
score: int # partners pointing at the site
|
|
74
|
+
enclosure: float # 0 = open solvent, 1 = fully enclosed
|
|
75
|
+
protein: tuple[tuple[str, int, str, str, str, float], ...] # (chain, number, icode, resname, atom, distance)
|
|
76
|
+
ligand: tuple[tuple[str, float], ...] # (atom name, distance)
|
|
77
|
+
|
|
78
|
+
@property
|
|
79
|
+
def bridging(self) -> bool:
|
|
80
|
+
return bool(self.protein) and bool(self.ligand)
|
|
81
|
+
|
|
82
|
+
def as_dict(self) -> dict[str, Any]:
|
|
83
|
+
return {"xyz": [round(v, 2) for v in self.xyz], "score": self.score, "enclosure": round(self.enclosure, 2),
|
|
84
|
+
"protein": [{"chain": c, "number": n, "icode": i, "resname": r, "atom": a, "distance": round(d, 2)}
|
|
85
|
+
for c, n, i, r, a, d in self.protein],
|
|
86
|
+
"ligand": [{"atom": a, "distance": round(d, 2)} for a, d in self.ligand], "predicted": True}
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def has_waters(structure: Any) -> bool:
|
|
90
|
+
"""Does the structure contain water molecules of its own?"""
|
|
91
|
+
return any(a.resname.upper() in WATER_NAMES for a in structure.atoms)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def water_oxygens(structure: Any) -> np.ndarray:
|
|
95
|
+
"""Coordinates of every water oxygen in the structure, ``(n, 3)``."""
|
|
96
|
+
return np.array([a.xyz for a in structure.atoms if a.resname.upper() in WATER_NAMES and a.element == "O"],
|
|
97
|
+
dtype=float).reshape(-1, 3)
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _open_sides(xyz: np.ndarray, polar: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
|
|
101
|
+
"""For every polar atom: the unit vector away from its bonded heavy atoms, and how many it has.
|
|
102
|
+
|
|
103
|
+
Bonds are taken from distances (under 1.95 angstrom between heavy atoms),
|
|
104
|
+
which is all a structure without hydrogens offers. The open side is where
|
|
105
|
+
a hydrogen or a lone pair is.
|
|
106
|
+
"""
|
|
107
|
+
out = np.zeros((len(polar), 3))
|
|
108
|
+
count = np.zeros(len(polar), dtype=int)
|
|
109
|
+
for k, i in enumerate(polar):
|
|
110
|
+
d = np.linalg.norm(xyz - xyz[i], axis=1)
|
|
111
|
+
bonded = np.nonzero((d < 1.95) & (d > 0.1))[0]
|
|
112
|
+
count[k] = len(bonded)
|
|
113
|
+
if len(bonded):
|
|
114
|
+
away = -(xyz[bonded] - xyz[i]).sum(axis=0)
|
|
115
|
+
norm = float(np.linalg.norm(away))
|
|
116
|
+
if norm > 1e-6:
|
|
117
|
+
out[k] = away / norm
|
|
118
|
+
return out, count
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
@dataclass(frozen=True)
|
|
122
|
+
class _Scene:
|
|
123
|
+
"""The surroundings of one ligand, as the predictor sees them."""
|
|
124
|
+
|
|
125
|
+
env: list[Any] # heavy atoms that can exclude, enclose or hold a water near the ligand; no waters
|
|
126
|
+
xyz: np.ndarray
|
|
127
|
+
is_lig: np.ndarray
|
|
128
|
+
polar: np.ndarray
|
|
129
|
+
vdw: np.ndarray
|
|
130
|
+
grid: np.ndarray # lattice points within reach of a ligand N or O that have room for a water oxygen
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _scene(structure: Any, ligand: Any, p: SolventParams) -> _Scene | None:
|
|
134
|
+
"""Steps 1 and 2: the lattice around the ligand's polar atoms, and the points with room for a water."""
|
|
135
|
+
atoms = [a for a in structure.atoms if a.element not in ("H", "D") and a.resname.upper() not in WATER_NAMES]
|
|
136
|
+
lig = [a for a in atoms if a.residue == ligand]
|
|
137
|
+
lig_polar = [a for a in lig if a.element in ("N", "O")]
|
|
138
|
+
if not lig_polar:
|
|
139
|
+
return None
|
|
140
|
+
centre_xyz = np.array([a.xyz for a in lig_polar], dtype=float)
|
|
141
|
+
lo, hi = centre_xyz.min(axis=0) - p.reach, centre_xyz.max(axis=0) + p.reach
|
|
142
|
+
# Everything that can exclude, enclose or hold a water near the ligand.
|
|
143
|
+
all_xyz = np.array([a.xyz for a in atoms], dtype=float)
|
|
144
|
+
margin = p.ray_length + 3.0
|
|
145
|
+
near = ((all_xyz >= lo - margin) & (all_xyz <= hi + margin)).all(axis=1)
|
|
146
|
+
env = [a for a, keep in zip(atoms, near) if keep]
|
|
147
|
+
xyz = all_xyz[near]
|
|
148
|
+
is_lig = np.array([a.residue == ligand for a in env])
|
|
149
|
+
polar = np.array([a.element in ("N", "O") for a in env])
|
|
150
|
+
contact = np.array([p.polar_contact if a.element in ("N", "O") else _radius(a.element) + PROBE for a in env])
|
|
151
|
+
vdw = np.array([_radius(a.element) for a in env])
|
|
152
|
+
|
|
153
|
+
# 1. the lattice, on a grid fixed in space, within reach of a ligand N or O
|
|
154
|
+
s = p.spacing
|
|
155
|
+
axes = [np.arange(math.floor(lo[k] / s) * s, hi[k] + s / 2.0, s) for k in range(3)]
|
|
156
|
+
grid = np.stack(np.meshgrid(*axes, indexing="ij"), axis=-1).reshape(-1, 3)
|
|
157
|
+
keep = np.zeros(len(grid), dtype=bool)
|
|
158
|
+
for c in centre_xyz:
|
|
159
|
+
keep |= ((grid - c) ** 2).sum(axis=1) <= p.reach ** 2
|
|
160
|
+
grid = grid[keep]
|
|
161
|
+
# 2. room for a water oxygen
|
|
162
|
+
free = np.ones(len(grid), dtype=bool)
|
|
163
|
+
for start in range(0, len(xyz), 64):
|
|
164
|
+
d = np.linalg.norm(grid[:, None, :] - xyz[None, start:start + 64, :], axis=2)
|
|
165
|
+
free &= (d >= contact[None, start:start + 64] - 1e-9).all(axis=1)
|
|
166
|
+
return _Scene(env, xyz, is_lig, polar, vdw, grid[free])
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def candidate_points(structure: Any, ligand: Any, params: SolventParams | None = None) -> np.ndarray:
|
|
170
|
+
"""Every lattice point near the ligand's polar atoms that merely has room for a water oxygen, ``(n, 3)``.
|
|
171
|
+
|
|
172
|
+
This is where the predictor starts, before enclosure and hydrogen-bond
|
|
173
|
+
partners are looked at. The validation draws its chance baseline from it.
|
|
174
|
+
"""
|
|
175
|
+
scene = _scene(structure, ligand, params or SolventParams())
|
|
176
|
+
return scene.grid if scene is not None else np.zeros((0, 3))
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def predict_solvent_sites(structure: Any, ligand: Any, params: SolventParams | None = None) -> list[SolventSite]:
|
|
180
|
+
"""Bridging solvent sites around one ligand of a structure, best first.
|
|
181
|
+
|
|
182
|
+
Waters in the structure are ignored as atoms (they are what is being
|
|
183
|
+
predicted), so the function can be run on an experimental structure for
|
|
184
|
+
validation; :meth:`Diagram.from_structure` does not call it for one.
|
|
185
|
+
"""
|
|
186
|
+
p = params or SolventParams()
|
|
187
|
+
scene = _scene(structure, ligand, p)
|
|
188
|
+
if scene is None or not len(scene.grid):
|
|
189
|
+
return []
|
|
190
|
+
env, xyz, is_lig, polar, vdw, grid = scene.env, scene.xyz, scene.is_lig, scene.polar, scene.vdw, scene.grid
|
|
191
|
+
s = p.spacing
|
|
192
|
+
|
|
193
|
+
# 3. enclosure and 4. partners, point by point
|
|
194
|
+
rays = _sphere(p.n_rays)
|
|
195
|
+
pol_idx = np.nonzero(polar)[0]
|
|
196
|
+
side, n_bonded = _open_sides(xyz, pol_idx)
|
|
197
|
+
cos_one, cos_many = math.cos(math.radians(p.cone_one)), math.cos(math.radians(p.cone_many))
|
|
198
|
+
pol_xyz = xyz[pol_idx]
|
|
199
|
+
enclosure = np.zeros(len(grid))
|
|
200
|
+
aim = np.zeros(len(grid)) # how squarely the partners point at the point: sum of cosines
|
|
201
|
+
partners: list[np.ndarray] = []
|
|
202
|
+
for g, point in enumerate(grid):
|
|
203
|
+
rel = xyz - point
|
|
204
|
+
dist2 = (rel ** 2).sum(axis=1)
|
|
205
|
+
close = dist2 < (p.ray_length + 2.0) ** 2
|
|
206
|
+
along = rel[close] @ rays.T # (atoms, rays)
|
|
207
|
+
perp2 = dist2[close][:, None] - along ** 2
|
|
208
|
+
hit = (along > 0.0) & (along < p.ray_length) & (perp2 < (vdw[close] ** 2)[:, None])
|
|
209
|
+
enclosure[g] = float(hit.any(axis=0).mean())
|
|
210
|
+
to_point = point - pol_xyz
|
|
211
|
+
dp = np.linalg.norm(to_point, axis=1)
|
|
212
|
+
ok = dp <= p.hbond_max
|
|
213
|
+
cosang = np.einsum("ij,ij->i", to_point, side) / np.maximum(dp, 1e-9)
|
|
214
|
+
pointing = np.where(n_bonded == 0, True, np.where(n_bonded == 1, cosang >= cos_one, cosang >= cos_many))
|
|
215
|
+
chosen = np.nonzero(ok & pointing)[0]
|
|
216
|
+
partners.append(chosen)
|
|
217
|
+
aim[g] = float(np.where(n_bonded[chosen] == 0, 1.0, cosang[chosen]).sum())
|
|
218
|
+
n_lig = np.array([int(is_lig[pol_idx[idx]].sum()) for idx in partners])
|
|
219
|
+
n_pro = np.array([len(idx) for idx in partners]) - n_lig
|
|
220
|
+
score = n_lig + n_pro
|
|
221
|
+
good = (enclosure >= p.min_enclosure) & (n_lig >= 1) & (n_pro >= 1)
|
|
222
|
+
if not good.any():
|
|
223
|
+
return []
|
|
224
|
+
|
|
225
|
+
# 5. greedy pick: most partners, then the point they point at most squarely (a straight
|
|
226
|
+
# hydrogen bond beats a bent one), then the most enclosed, then a fixed order in space
|
|
227
|
+
order = sorted(np.nonzero(good)[0], key=lambda i: (-int(score[i]), -round(float(aim[i]), 3),
|
|
228
|
+
-round(float(enclosure[i]), 6),
|
|
229
|
+
round(float(grid[i, 0]), 3), round(float(grid[i, 1]), 3),
|
|
230
|
+
round(float(grid[i, 2]), 3)))
|
|
231
|
+
taken: list[np.ndarray] = []
|
|
232
|
+
sites: list[SolventSite] = []
|
|
233
|
+
for i in order:
|
|
234
|
+
if any(np.linalg.norm(grid[i] - t) < p.separation for t in taken):
|
|
235
|
+
continue
|
|
236
|
+
# Settle on the middle of the equally good points around the pick, off the lattice.
|
|
237
|
+
same = (good & (score == score[i]) & (aim >= aim[i] - 0.05)
|
|
238
|
+
& (np.linalg.norm(grid - grid[i], axis=1) <= 1.5 * s))
|
|
239
|
+
centre = grid[same].mean(axis=0)
|
|
240
|
+
taken.append(centre)
|
|
241
|
+
pro, ligs = [], []
|
|
242
|
+
for j in partners[i]:
|
|
243
|
+
atom = env[pol_idx[j]]
|
|
244
|
+
d = float(np.linalg.norm(centre - pol_xyz[j]))
|
|
245
|
+
if is_lig[pol_idx[j]]:
|
|
246
|
+
ligs.append((atom.name, d))
|
|
247
|
+
else:
|
|
248
|
+
pro.append((atom.chain, atom.resnum, atom.icode, atom.resname, atom.name, d))
|
|
249
|
+
sites.append(SolventSite((float(centre[0]), float(centre[1]), float(centre[2])), int(score[i]),
|
|
250
|
+
float(enclosure[i]), tuple(sorted(pro, key=lambda t: (t[5], t[0], t[1], t[4]))),
|
|
251
|
+
tuple(sorted(ligs, key=lambda t: (t[1], t[0])))))
|
|
252
|
+
if len(sites) >= p.max_sites:
|
|
253
|
+
break
|
|
254
|
+
return sites
|