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/graphbuild.py
ADDED
|
@@ -0,0 +1,431 @@
|
|
|
1
|
+
"""Between the layout engine and the renderers: building a :class:`~bindview.graph.Graph`
|
|
2
|
+
from a laid-out diagram, and reading poses back out of one.
|
|
3
|
+
|
|
4
|
+
The engine places bodies; a renderer draws them. In between sits the graph:
|
|
5
|
+
:func:`diagram_graph` turns the engine's result into nodes and contacts, and
|
|
6
|
+
:func:`poses_from` gives a renderer the poses the graph holds -- whether the
|
|
7
|
+
graph was made a moment ago, loaded from JSON, or edited by someone dragging a
|
|
8
|
+
node. A renderer therefore never sees the engine's own result.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
from typing import Any, Mapping, Sequence
|
|
14
|
+
|
|
15
|
+
import numpy as np
|
|
16
|
+
|
|
17
|
+
from .depict import Depiction, atom_keys, depict_ligand
|
|
18
|
+
from .errors import GraphError
|
|
19
|
+
from .graph import Contact, Graph, Node, RigidGroup
|
|
20
|
+
from .layout import SPRINGS, Body, LayoutParams, LayoutResult, Pose
|
|
21
|
+
from .layout.body import Port
|
|
22
|
+
from .ligand import Ligand
|
|
23
|
+
from .styles.base import Context, PortInfo, Target
|
|
24
|
+
from .theme import Metrics
|
|
25
|
+
|
|
26
|
+
__all__ = ["LigandPart", "diagram_graph", "residue_contacts", "poses_from", "depiction_from", "engine_springs",
|
|
27
|
+
"unique_ids"]
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def engine_springs(params: LayoutParams) -> dict[str, float]:
|
|
31
|
+
"""The layout engine's spring constants, as the graph carries them.
|
|
32
|
+
|
|
33
|
+
``link`` / ``sightline`` / ``eyelash`` are the weights by class of tie
|
|
34
|
+
(:data:`bindview.layout.SPRINGS`); ``length`` and ``short`` are the engine's
|
|
35
|
+
``w_length`` and ``w_short``; ``unit`` is the length that makes them
|
|
36
|
+
dimensionless (one bond length). A tie of weight ``w`` and rest length
|
|
37
|
+
``ideal`` costs ``length * w * ((d - ideal) / unit) ** 2`` at length ``d``,
|
|
38
|
+
times ``short`` while ``d < ideal``.
|
|
39
|
+
"""
|
|
40
|
+
return {**SPRINGS, "length": params.w_length, "short": params.w_short, "unit": params.unit}
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class LigandPart:
|
|
44
|
+
"""The nodes of one drawn ligand: its atoms, and the ring centroids and groups contacts land on."""
|
|
45
|
+
|
|
46
|
+
def __init__(self, dep: Depiction, *, prefix: str = "L", group: str = "ligand", label: str = "",
|
|
47
|
+
plddt: "Mapping[str, float] | None" = None, exposure: Any = None) -> None:
|
|
48
|
+
self.dep = dep
|
|
49
|
+
self.prefix = prefix
|
|
50
|
+
self.group_id = group
|
|
51
|
+
self.label = label
|
|
52
|
+
self._atoms: list[Node] = []
|
|
53
|
+
self._extra: dict[str, Node] = {}
|
|
54
|
+
self._units: list[Node] = []
|
|
55
|
+
self._outside: list[Node] = [] # of a chain ligand: the nodes of its atoms outside the chain
|
|
56
|
+
self._pieces: dict[str, list[str]] = {}
|
|
57
|
+
if dep.units:
|
|
58
|
+
self._chain(plddt, exposure)
|
|
59
|
+
return
|
|
60
|
+
for atom, key in zip(dep.atoms, atom_keys(dep)):
|
|
61
|
+
node = Node(id=f"{prefix}:{key}", kind="ligand_atom", label=atom.name or atom.element, x=atom.x,
|
|
62
|
+
y=atom.y, group=group, attrs={"element": atom.element})
|
|
63
|
+
if atom.name is None:
|
|
64
|
+
node.attrs["drawing_only"] = True # a hydrogen the depiction adds at a stereocentre
|
|
65
|
+
elif plddt is not None and atom.name in plddt:
|
|
66
|
+
node.confidence = float(plddt[atom.name])
|
|
67
|
+
if exposure is not None and atom.name is not None and atom.idx < len(exposure):
|
|
68
|
+
node.attrs["exposure"] = round(float(exposure[atom.idx]), 4)
|
|
69
|
+
self._atoms.append(node)
|
|
70
|
+
names = [a.name for a in dep.atoms]
|
|
71
|
+
self.coordination = [[names[b.a], names[b.b]] for b in dep.bonds
|
|
72
|
+
if b.kind == "coordination" and names[b.a] and names[b.b]]
|
|
73
|
+
|
|
74
|
+
def _chain(self, plddt: "Mapping[str, float] | None", exposure: Any) -> None:
|
|
75
|
+
"""The nodes of a ligand drawn as a chain: one per residue, and one per atom outside the chain.
|
|
76
|
+
|
|
77
|
+
A residue is a node of its own and belongs to no rigid group unless
|
|
78
|
+
something outside the chain is bonded to it: then the two form one, so
|
|
79
|
+
that a lipid follows the lysine it sits on and nothing else does.
|
|
80
|
+
"""
|
|
81
|
+
dep, prefix = self.dep, self.prefix
|
|
82
|
+
holder: dict[int, int] = {} # atom outside the chain -> index of the unit that holds its piece
|
|
83
|
+
outside = [a.idx for a in dep.atoms if dep.unit_of(a.idx) is None]
|
|
84
|
+
nbrs: dict[int, list[int]] = {i: [] for i in outside}
|
|
85
|
+
touch: dict[int, int] = {}
|
|
86
|
+
for b in dep.bonds:
|
|
87
|
+
if b.kind != "covalent":
|
|
88
|
+
continue
|
|
89
|
+
ua, ub = dep.unit_of(b.a), dep.unit_of(b.b)
|
|
90
|
+
if ua is None and ub is None:
|
|
91
|
+
nbrs[b.a].append(b.b)
|
|
92
|
+
nbrs[b.b].append(b.a)
|
|
93
|
+
elif ua is None and ub is not None:
|
|
94
|
+
touch.setdefault(b.a, ub.index)
|
|
95
|
+
elif ub is None and ua is not None:
|
|
96
|
+
touch.setdefault(b.b, ua.index)
|
|
97
|
+
for start in sorted(touch): # flood each piece from where it is held
|
|
98
|
+
stack = [start]
|
|
99
|
+
while stack:
|
|
100
|
+
i = stack.pop()
|
|
101
|
+
if i in holder:
|
|
102
|
+
continue
|
|
103
|
+
holder[i] = touch[start]
|
|
104
|
+
stack.extend(nbrs[i])
|
|
105
|
+
group_of = {u: f"{self.group_id}:at{dep.units[u].position}" for u in set(holder.values())}
|
|
106
|
+
for unit in dep.units:
|
|
107
|
+
names = [dep.atoms[a].name or "" for a in unit.atoms]
|
|
108
|
+
# A residue of the ligand is a group of its atoms that a contact attaches to as a whole: the
|
|
109
|
+
# kind schema 1.0 already has for that. Its atoms are not nodes of their own in this drawing,
|
|
110
|
+
# so they are named in ``atoms`` and ``members`` stays empty.
|
|
111
|
+
node = Node(id=f"{prefix}:res:{unit.position}", kind="ligand_group",
|
|
112
|
+
label=f"{unit.text}{unit.number or unit.position}", x=unit.x, y=unit.y,
|
|
113
|
+
group=group_of.get(unit.index),
|
|
114
|
+
attrs={"form": "chain_residue", "resname": unit.name, "position": unit.position,
|
|
115
|
+
**({"number": unit.number} if unit.number not in ("", str(unit.position)) else {}),
|
|
116
|
+
"class": unit.residue_class, "atoms": names,
|
|
117
|
+
"backbone": [dep.atoms[a].name or "" for a in unit.backbone],
|
|
118
|
+
"width": round(unit.box[2] - unit.box[0], 3),
|
|
119
|
+
"height": round(unit.box[3] - unit.box[1], 3)})
|
|
120
|
+
values = [plddt[n] for n in names if plddt is not None and n in plddt]
|
|
121
|
+
if values:
|
|
122
|
+
node.confidence = float(sum(values) / len(values))
|
|
123
|
+
if unit.beside:
|
|
124
|
+
# Those of its atoms that stand beside the box as atoms of their own, and are nodes.
|
|
125
|
+
node.attrs["beside"] = [dep.atoms[a].name or "" for a in unit.beside]
|
|
126
|
+
self._units.append(node)
|
|
127
|
+
if unit.index in group_of:
|
|
128
|
+
self._pieces.setdefault(group_of[unit.index], []).append(node.id)
|
|
129
|
+
keys = atom_keys(dep)
|
|
130
|
+
by_idx: dict[int, Node] = {}
|
|
131
|
+
for atom in dep.atoms:
|
|
132
|
+
if dep.unit_of(atom.idx) is not None:
|
|
133
|
+
continue
|
|
134
|
+
piece = group_of.get(holder.get(atom.idx, -1))
|
|
135
|
+
node = Node(id=f"{prefix}:{keys[atom.idx]}", kind="ligand_atom", label=atom.name or atom.element,
|
|
136
|
+
x=atom.x, y=atom.y, group=piece, attrs={"element": atom.element})
|
|
137
|
+
if atom.name is None:
|
|
138
|
+
node.attrs["drawing_only"] = True
|
|
139
|
+
nb = dep.neighbours(atom.idx)
|
|
140
|
+
piece = group_of.get(holder.get(nb[0], -1)) if nb else None
|
|
141
|
+
node.group = piece
|
|
142
|
+
elif plddt is not None and atom.name in plddt:
|
|
143
|
+
node.confidence = float(plddt[atom.name])
|
|
144
|
+
if exposure is not None and atom.name is not None and atom.idx < len(exposure):
|
|
145
|
+
node.attrs["exposure"] = round(float(exposure[atom.idx]), 4)
|
|
146
|
+
by_idx[atom.idx] = node
|
|
147
|
+
if piece is not None:
|
|
148
|
+
self._pieces.setdefault(piece, []).append(node.id)
|
|
149
|
+
# ``_atoms`` is indexed by depiction atom: an atom of the chain stands for its residue's node.
|
|
150
|
+
self._atoms = [by_idx[a.idx] if a.idx in by_idx else self._units[dep.unit_of(a.idx).index] # type: ignore[union-attr]
|
|
151
|
+
for a in dep.atoms]
|
|
152
|
+
self._outside = [by_idx[i] for i in sorted(by_idx)]
|
|
153
|
+
self.coordination = []
|
|
154
|
+
|
|
155
|
+
def anchor(self, target: Target, label: str = "") -> Node:
|
|
156
|
+
"""The node a link target stands for: an atom, or the centroid / group node made for it."""
|
|
157
|
+
if target.unit is not None:
|
|
158
|
+
return self._units[target.unit]
|
|
159
|
+
if target.kind == "atom":
|
|
160
|
+
return self._atoms[target.atoms[0]]
|
|
161
|
+
ring = target.kind == "ring"
|
|
162
|
+
members = [self._atoms[i] for i in target.atoms]
|
|
163
|
+
ident = f"{self.prefix}:{'ring' if ring else 'group'}:{'-'.join(m.label for m in members)}"
|
|
164
|
+
node = self._extra.get(ident)
|
|
165
|
+
if node is None:
|
|
166
|
+
node = Node(id=ident, kind="ring_centroid" if ring else "ligand_group",
|
|
167
|
+
label=label or ("ring" if ring else "group"), x=float(target.point[0]),
|
|
168
|
+
y=float(target.point[1]), group=self.group_id, members=tuple(m.id for m in members))
|
|
169
|
+
self._extra[ident] = node
|
|
170
|
+
return node
|
|
171
|
+
|
|
172
|
+
def nodes(self) -> list[Node]:
|
|
173
|
+
if self._units:
|
|
174
|
+
return self._units + self._outside + list(self._extra.values())
|
|
175
|
+
return self._atoms + list(self._extra.values())
|
|
176
|
+
|
|
177
|
+
def rigid_group(self, **attrs: Any) -> RigidGroup:
|
|
178
|
+
"""The ligand as one rigid body: its depiction keeps its internal geometry whatever moves."""
|
|
179
|
+
extra = dict(attrs)
|
|
180
|
+
if self.coordination:
|
|
181
|
+
extra["coordination"] = self.coordination
|
|
182
|
+
return RigidGroup(id=self.group_id, label=self.label, members=tuple(n.id for n in self.nodes()),
|
|
183
|
+
movable=True, attrs=extra)
|
|
184
|
+
|
|
185
|
+
def rigid_groups(self, **attrs: Any) -> list[RigidGroup]:
|
|
186
|
+
"""The rigid bodies of the ligand: the whole of it when it is drawn as atoms; for a chain, only
|
|
187
|
+
each piece outside the chain together with the residue that holds it."""
|
|
188
|
+
if not self._units:
|
|
189
|
+
return [self.rigid_group(**attrs)]
|
|
190
|
+
for node in self._extra.values(): # a ring or group of atoms outside the chain follows its piece
|
|
191
|
+
first = next((n for n in self._atoms if n.id in node.members), None)
|
|
192
|
+
if first is not None and first.group is not None:
|
|
193
|
+
node.group = first.group
|
|
194
|
+
self._pieces.setdefault(first.group, []).append(node.id)
|
|
195
|
+
else:
|
|
196
|
+
node.group = None
|
|
197
|
+
return [RigidGroup(id=gid, label=self.label, members=tuple(members), movable=True, attrs=dict(attrs))
|
|
198
|
+
for gid, members in sorted(self._pieces.items())]
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def residue_contacts(part: LigandPart, ident: str, infos: Sequence[PortInfo], ports: Sequence[Port],
|
|
202
|
+
label_t: Sequence[float], offset: int = 0, **attrs: Any) -> list[Contact]:
|
|
203
|
+
"""One contact per tether of a residue, in tether order.
|
|
204
|
+
|
|
205
|
+
``infos`` and ``ports`` run in parallel (``ports[offset + k]`` is the tie of
|
|
206
|
+
``infos[k]``); ``label_t`` is the engine's label position for every port.
|
|
207
|
+
"""
|
|
208
|
+
out = []
|
|
209
|
+
for k, info in enumerate(infos):
|
|
210
|
+
port = ports[offset + k]
|
|
211
|
+
first = info.interactions[0]
|
|
212
|
+
group_label = first.ligand.group_kind if first.ligand is not None else ""
|
|
213
|
+
anchor = part.anchor(info.target, group_label)
|
|
214
|
+
cid = "|".join((ident, info.kind.value, anchor.id, f"{info.site_kind}:{','.join(info.site_atoms)}"))
|
|
215
|
+
# Where along the line its text sits: kept for a line that carries only a tag (a predicted
|
|
216
|
+
# aligned error and no distance) as for one with a label, or a redraw would not find it.
|
|
217
|
+
at = label_t[offset + k] if (info.shown and offset + k < len(label_t)) else None
|
|
218
|
+
contact = Contact(
|
|
219
|
+
id=cid, type=info.kind.value, residue="R:" + ident, ligand=anchor.id, drawn=info.drawn,
|
|
220
|
+
distance=first.record.distance, occupancy=info.occupancy, confidence=info.plddt, label=info.label,
|
|
221
|
+
label_t=None if at is None else float(at), ideal=float(port.ideal), min_length=float(port.min_length),
|
|
222
|
+
weight=float(port.weight), site=info.site_kind, protein_atoms=tuple(info.site_atoms),
|
|
223
|
+
records=tuple(r.index for r in info.interactions), attrs=dict(attrs))
|
|
224
|
+
if info.beyond:
|
|
225
|
+
contact.attrs["beyond"] = True
|
|
226
|
+
errors = [r.record.pae for r in info.interactions if r.record.pae is not None]
|
|
227
|
+
if errors:
|
|
228
|
+
contact.attrs["pae"] = round(min(errors), 2) # carried for the reader of the graph; not drawn
|
|
229
|
+
draws = next(r.record.pae_draws for r in info.interactions if r.record.pae == min(errors))
|
|
230
|
+
if len(draws) > 1:
|
|
231
|
+
contact.attrs["pae_draws"] = [round(v, 2) for v in draws]
|
|
232
|
+
if info.target.unit is not None:
|
|
233
|
+
# A residue of a chain ligand makes it: say which, with which atoms, and whether by its backbone.
|
|
234
|
+
unit = part.dep.units[info.target.unit]
|
|
235
|
+
made_by = [a for r in info.interactions if r.ligand is not None for a in r.ligand.atoms]
|
|
236
|
+
contact.ligand_residue = anchor.label
|
|
237
|
+
contact.attrs["ligand_atoms"] = list(dict.fromkeys(part.dep.atoms[a].name or "" for a in made_by))
|
|
238
|
+
contact.attrs["ligand_part"] = unit.part(made_by)
|
|
239
|
+
out.append(contact)
|
|
240
|
+
return out
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def unique_ids(contacts: Sequence[Contact]) -> None:
|
|
244
|
+
"""Make contact ids unique in place (two tethers can differ only in what a style merged away)."""
|
|
245
|
+
seen: dict[str, int] = {}
|
|
246
|
+
for c in contacts:
|
|
247
|
+
seen[c.id] = seen.get(c.id, 0) + 1
|
|
248
|
+
if seen[c.id] > 1:
|
|
249
|
+
c.id = f"{c.id}#{seen[c.id]}"
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def link_references(graph: Graph) -> None:
|
|
253
|
+
"""Fill in, on every ligand node, the contacts that land on it."""
|
|
254
|
+
by_id = {n.id: n for n in graph.nodes}
|
|
255
|
+
for c in graph.contacts:
|
|
256
|
+
if c.ligand is not None and c.ligand in by_id:
|
|
257
|
+
node = by_id[c.ligand]
|
|
258
|
+
if c.id not in node.contacts:
|
|
259
|
+
node.contacts = node.contacts + (c.id,)
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def diagram_graph(view: str, ctx: Context, bodies: Sequence[Body], layout: LayoutResult, params: LayoutParams,
|
|
263
|
+
*, name: str = "", exposure: Any = None) -> Graph:
|
|
264
|
+
"""The graph of a single-ligand diagram, from what the layout engine returned.
|
|
265
|
+
|
|
266
|
+
Each body's payload gives its residue (``group``), its tethers (``ports``,
|
|
267
|
+
parallel to the body's own ports) and how it is drawn (``form``).
|
|
268
|
+
"""
|
|
269
|
+
conf = ctx.confidence
|
|
270
|
+
part = LigandPart(ctx.dep, label=name, plddt=conf.ligand_atoms if conf is not None else None,
|
|
271
|
+
exposure=exposure)
|
|
272
|
+
graph = Graph(view=view, bond_length=float(ctx.metrics.bond_length), ensemble=ctx.ensemble,
|
|
273
|
+
springs=engine_springs(params))
|
|
274
|
+
residues = []
|
|
275
|
+
waters: list[tuple[Node, Contact]] = []
|
|
276
|
+
for body in bodies:
|
|
277
|
+
pay = body.payload
|
|
278
|
+
grp = pay.group
|
|
279
|
+
pose = layout.poses.get(body.key)
|
|
280
|
+
contacts = residue_contacts(part, grp.node_ident, pay.ports, body.ports, layout.label_t.get(body.key, ()))
|
|
281
|
+
graph.contacts.extend(contacts)
|
|
282
|
+
attrs: dict[str, Any] = {"resname": grp.resname, "chain": grp.key[0], "number": grp.key[1],
|
|
283
|
+
"class": grp.residue_class, "form": pay.form,
|
|
284
|
+
"radius": round(float(body.proper_radius), 3)}
|
|
285
|
+
if grp.key[2]:
|
|
286
|
+
attrs["icode"] = grp.key[2]
|
|
287
|
+
if grp.parts > 1:
|
|
288
|
+
# One of several drawings of this residue, each beside the stretch of the chain it touches there.
|
|
289
|
+
attrs["drawing"] = grp.part + 1
|
|
290
|
+
attrs["drawings"] = grp.parts
|
|
291
|
+
if grp.beyond:
|
|
292
|
+
attrs["beyond"] = True
|
|
293
|
+
share = ctx.share_of(grp)
|
|
294
|
+
if share is not None:
|
|
295
|
+
# A figure of all the models of an ensemble: how many of them contact it.
|
|
296
|
+
attrs["n_models"], attrs["n_total"] = share.n_models, share.n_total
|
|
297
|
+
if pose is not None and any(info.predicted for info in pay.ports):
|
|
298
|
+
# A predicted solvent site is a node of its own, where its label is drawn on the line.
|
|
299
|
+
a_all, b_all, _ = body.link_segments(np.array([[pose.x, pose.y]]), np.array([pose.angle]),
|
|
300
|
+
np.array([pose.mirror]))
|
|
301
|
+
for k, (info, contact) in enumerate(zip(pay.ports, contacts)):
|
|
302
|
+
if not info.predicted:
|
|
303
|
+
continue
|
|
304
|
+
at = 0.5 if contact.label_t is None else contact.label_t
|
|
305
|
+
x = float(a_all[0, k, 0] + (b_all[0, k, 0] - a_all[0, k, 0]) * at)
|
|
306
|
+
y = float(a_all[0, k, 1] + (b_all[0, k, 1] - a_all[0, k, 1]) * at)
|
|
307
|
+
tag = (info.interactions[0].record.water or "").partition(":")[2]
|
|
308
|
+
extra: dict[str, Any] = {"predicted": True}
|
|
309
|
+
if tag.isdigit() and int(tag) < len(ctx.solvent_sites):
|
|
310
|
+
found = ctx.solvent_sites[int(tag)].as_dict()
|
|
311
|
+
extra.update({"score": found["score"], "enclosure": found["enclosure"], "xyz": found["xyz"],
|
|
312
|
+
"partners": {"protein": found["protein"], "ligand": found["ligand"]}})
|
|
313
|
+
site = Node(id=f"W:{tag or len(waters)}", kind="solvent_site", label="predicted water", x=x, y=y,
|
|
314
|
+
movable=False, anchors=tuple(a for a in (contact.ligand, "R:" + grp.node_ident) if a),
|
|
315
|
+
contacts=(contact.id,), attrs=extra)
|
|
316
|
+
contact.attrs["predicted"] = True
|
|
317
|
+
contact.attrs["via"] = site.id
|
|
318
|
+
waters.append((site, contact))
|
|
319
|
+
node = Node(id="R:" + grp.node_ident, kind="residue", label=grp.label,
|
|
320
|
+
x=None if pose is None else float(pose.x), y=None if pose is None else float(pose.y),
|
|
321
|
+
angle=0.0 if pose is None else float(pose.angle), mirror=bool(pose.mirror) if pose else False,
|
|
322
|
+
anchors=tuple(dict.fromkeys(c.ligand for c in contacts if c.ligand)),
|
|
323
|
+
spring=float(sum(p.weight for p in body.ports)), contacts=(), confidence=pay.plddt,
|
|
324
|
+
occupancy=pay.occupancy, attrs=attrs)
|
|
325
|
+
residues.append((node, contacts))
|
|
326
|
+
unique_ids(graph.contacts)
|
|
327
|
+
for node, contacts in residues:
|
|
328
|
+
node.contacts = tuple(c.id for c in contacts)
|
|
329
|
+
for site, contact in waters: # ids were made unique above: follow them
|
|
330
|
+
site.contacts = (contact.id,)
|
|
331
|
+
graph.nodes = part.nodes() + [node for node, _ in residues] + [site for site, _ in waters]
|
|
332
|
+
graph.groups = part.rigid_groups()
|
|
333
|
+
link_references(graph)
|
|
334
|
+
return graph
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
def polymer_positions(graph: Graph, *, prefix: str = "L") -> tuple[dict[int, tuple[float, float]],
|
|
338
|
+
dict[str, tuple[float, float]]]:
|
|
339
|
+
"""Where a graph has a chain ligand: its residues by position, and its atoms outside the chain by name
|
|
340
|
+
(``H@<name>`` for a hydrogen the drawing adds). Positions are taken as they stand."""
|
|
341
|
+
units: dict[int, tuple[float, float]] = {}
|
|
342
|
+
atoms: dict[str, tuple[float, float]] = {}
|
|
343
|
+
for node in graph.nodes:
|
|
344
|
+
if not node.id.startswith(prefix + ":"):
|
|
345
|
+
continue
|
|
346
|
+
if node.kind == "ligand_group" and "position" in node.attrs:
|
|
347
|
+
if node.x is None or node.y is None:
|
|
348
|
+
raise GraphError(f"ligand residue {node.id} has no position in the graph")
|
|
349
|
+
try:
|
|
350
|
+
units[int(node.attrs["position"])] = (node.x, node.y)
|
|
351
|
+
except (KeyError, TypeError, ValueError) as exc:
|
|
352
|
+
raise GraphError(f"ligand residue {node.id} has no usable 'position': {exc}") from exc
|
|
353
|
+
elif node.kind == "ligand_atom":
|
|
354
|
+
if node.x is None or node.y is None:
|
|
355
|
+
raise GraphError(f"ligand atom {node.id} has no position in the graph")
|
|
356
|
+
atoms[node.id[len(prefix) + 1:]] = (node.x, node.y)
|
|
357
|
+
if not units:
|
|
358
|
+
raise GraphError("the graph does not hold a ligand drawn as a chain: none of its nodes is a residue "
|
|
359
|
+
"of the ligand")
|
|
360
|
+
return units, atoms
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
def poses_from(graph: Graph, bodies: Sequence[Body], tethered: bool = True
|
|
364
|
+
) -> tuple[dict[Any, Pose], dict[Any, tuple[float, ...]]]:
|
|
365
|
+
"""The poses a graph holds for ``bodies``, and where the label of each tether sits.
|
|
366
|
+
|
|
367
|
+
A body is matched to its node by the residue it stands for; a node without
|
|
368
|
+
a position leaves its body unplaced. A graph that was not made for these
|
|
369
|
+
bodies -- another complex, or other render options -- is refused. With
|
|
370
|
+
``tethered=False`` the node's contacts are not ties (a consensus node's
|
|
371
|
+
contacts stand for a set of ligands) and only positions are read.
|
|
372
|
+
"""
|
|
373
|
+
by_id = {c.id: c for c in graph.contacts}
|
|
374
|
+
poses: dict[Any, Pose] = {}
|
|
375
|
+
label_t: dict[Any, tuple[float, ...]] = {}
|
|
376
|
+
for body in bodies:
|
|
377
|
+
ident = body.payload.ident
|
|
378
|
+
node = graph.find("R:" + ident)
|
|
379
|
+
if node is None:
|
|
380
|
+
raise GraphError(f"the graph has no node for residue {ident}: it was not made for this diagram")
|
|
381
|
+
if not tethered:
|
|
382
|
+
if node.x is not None and node.y is not None:
|
|
383
|
+
poses[body.key] = Pose(node.x, node.y, node.angle, node.mirror)
|
|
384
|
+
continue
|
|
385
|
+
drawn, form = node.attrs.get("form"), getattr(body.payload, "form", None)
|
|
386
|
+
if drawn is not None and form is not None and drawn != form:
|
|
387
|
+
raise GraphError(f"residue {ident} is drawn as {form!r} in this diagram and as {drawn!r} in the graph: "
|
|
388
|
+
"the graph was made with other options (residues=, detail=)")
|
|
389
|
+
if len(node.contacts) != body.n_ports:
|
|
390
|
+
raise GraphError(f"residue {ident} has {body.n_ports} tether(s) in this diagram and "
|
|
391
|
+
f"{len(node.contacts)} in the graph: the graph was made with other data or options")
|
|
392
|
+
if node.x is None or node.y is None:
|
|
393
|
+
continue
|
|
394
|
+
poses[body.key] = Pose(node.x, node.y, node.angle, node.mirror)
|
|
395
|
+
at = []
|
|
396
|
+
for cid in node.contacts:
|
|
397
|
+
if cid not in by_id:
|
|
398
|
+
raise GraphError(f"residue {ident} refers to an unknown contact {cid!r}")
|
|
399
|
+
value = by_id[cid].label_t
|
|
400
|
+
at.append(0.5 if value is None else value)
|
|
401
|
+
label_t[body.key] = tuple(at)
|
|
402
|
+
return poses, label_t
|
|
403
|
+
|
|
404
|
+
|
|
405
|
+
def depiction_from(lig: Ligand, metrics: Metrics, graph: Graph, *, prefix: str = "L",
|
|
406
|
+
group: str = "ligand") -> Depiction:
|
|
407
|
+
"""The ligand drawn where a graph has its atoms -- to the last digit.
|
|
408
|
+
|
|
409
|
+
The atoms' positions are taken as they stand, so a graph that went through
|
|
410
|
+
JSON redraws the identical figure and one whose ligand was moved redraws it
|
|
411
|
+
moved. The ligand is a rigid body in the graph, and nothing here checks
|
|
412
|
+
that it stayed one: positions are simply used.
|
|
413
|
+
"""
|
|
414
|
+
bl = metrics.bond_length
|
|
415
|
+
exact: dict[str, tuple[float, float]] = {}
|
|
416
|
+
for node in graph.nodes:
|
|
417
|
+
if node.kind != "ligand_atom" or node.group != group or not node.id.startswith(prefix + ":"):
|
|
418
|
+
continue
|
|
419
|
+
if node.x is None or node.y is None:
|
|
420
|
+
raise GraphError(f"ligand atom {node.id} has no position in the graph")
|
|
421
|
+
exact[node.id[len(prefix) + 1:]] = (node.x, node.y)
|
|
422
|
+
missing = [n for n in lig.names if n not in exact]
|
|
423
|
+
if missing:
|
|
424
|
+
raise GraphError("the graph does not hold this ligand: it has no node for atom(s) "
|
|
425
|
+
+ ", ".join(missing[:6]))
|
|
426
|
+
coords = {n: (exact[n][0] / bl, -exact[n][1] / bl) for n in lig.names}
|
|
427
|
+
try:
|
|
428
|
+
pairs = [(str(a), str(b)) for a, b in graph.group(group).attrs.get("coordination", [])]
|
|
429
|
+
except (TypeError, ValueError) as exc:
|
|
430
|
+
raise GraphError(f"malformed 'coordination' of group {group!r}: {exc}") from exc
|
|
431
|
+
return depict_ligand(lig, metrics, coords=coords, normalise=False, exact=exact, coordination=pairs)
|