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/polymer.py
ADDED
|
@@ -0,0 +1,678 @@
|
|
|
1
|
+
"""A chain ligand as drawable geometry: residues on a path, the rest as atoms.
|
|
2
|
+
|
|
3
|
+
The result is an ordinary :class:`~bindview.depict.Depiction`, so that the layout
|
|
4
|
+
engine, the audit and the styles work on it unchanged. What makes it a chain:
|
|
5
|
+
|
|
6
|
+
* every residue is a :class:`~bindview.depict.DepUnit` -- a labelled box -- and
|
|
7
|
+
all atoms of the residue sit at its centre, so a contact that names any of
|
|
8
|
+
them lands on the residue;
|
|
9
|
+
* consecutive residues are joined by a ``chain`` bond, which the engine treats
|
|
10
|
+
as ink it must not cross;
|
|
11
|
+
* atoms that are in no residue (a fatty acid on its linker, a terminal cap) keep
|
|
12
|
+
positions of their own: they are laid out as the small molecule they are and
|
|
13
|
+
set beside the residue they are bonded to.
|
|
14
|
+
|
|
15
|
+
**The path is a column.** Residue labels are horizontal text, so residues of a
|
|
16
|
+
protein read best to the left and right of a vertical chain, one above the
|
|
17
|
+
other like a list; along a horizontal chain their labels would collide at any
|
|
18
|
+
legible pitch. A chain is therefore drawn top to bottom from its N-terminus,
|
|
19
|
+
and it does not bend: a bend would put two stretches of chain side by side with
|
|
20
|
+
no room between them for what contacts either. The three-dimensional path of
|
|
21
|
+
the peptide is not shown, and nothing in the figure suggests that it is.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
from __future__ import annotations
|
|
25
|
+
|
|
26
|
+
import math
|
|
27
|
+
from dataclasses import dataclass
|
|
28
|
+
from typing import Collection, Hashable, Mapping, Sequence
|
|
29
|
+
|
|
30
|
+
import numpy as np
|
|
31
|
+
from rdkit import Chem
|
|
32
|
+
|
|
33
|
+
from .chem import quiet_rdkit
|
|
34
|
+
from .depict import AtomLabel, DepAtom, DepBond, Depiction, DepUnit, LabelRun, depict_ligand
|
|
35
|
+
from .geometry import Box, Point
|
|
36
|
+
from .ligand import Ligand
|
|
37
|
+
from .peptide import Appendage, Peptide, PeptideResidue
|
|
38
|
+
from .plane import Arrangement, passes_through
|
|
39
|
+
from .residues import PHOSPHATE, TAIL, canonical_atom, canonical_resname, residue_class, template_for, written
|
|
40
|
+
from .scene import Span
|
|
41
|
+
from .textmetrics import CAP_HEIGHT, text_width
|
|
42
|
+
from .theme import Metrics
|
|
43
|
+
|
|
44
|
+
__all__ = ["depict_polymer", "unit_label", "UNIT_FONT", "INDEX_FONT", "UNIT_HEIGHT", "PIECE_GAP", "Piece",
|
|
45
|
+
"lay_piece", "piece_sides", "stack_column", "shown_atoms"]
|
|
46
|
+
|
|
47
|
+
UNIT_FONT = 10.5 # the residue's code
|
|
48
|
+
INDEX_FONT = 8.0 # its position in the chain
|
|
49
|
+
UNIT_HEIGHT = 17.0
|
|
50
|
+
_PAD = 6.0 # between text and the box, left and right
|
|
51
|
+
_GAP = 2.5 # between code and position
|
|
52
|
+
#: Centre-to-centre distance of two residues never falls below this (it is ``Metrics.chain_pitch`` bond lengths).
|
|
53
|
+
MIN_PITCH = UNIT_HEIGHT + 5.0
|
|
54
|
+
#: A crosslink is drawn as a bracket this far outside the boxes, and the next one this much further.
|
|
55
|
+
BRACKET_OUT = 9.0
|
|
56
|
+
BRACKET_STEP = 6.0
|
|
57
|
+
#: Where atoms of a residue are drawn beside its box: the room between the ink of one residue's atoms
|
|
58
|
+
#: and the ink of another residue, its atoms or its box.
|
|
59
|
+
PIECE_GAP = 6.0
|
|
60
|
+
#: What is bonded to nothing of the chain (an ion that the chain and the protein hold between them) stands this
|
|
61
|
+
#: many bond lengths from the box of its residue: as far as such an ion stands from its donor in a drawing of atoms.
|
|
62
|
+
_LOOSE = 1.35
|
|
63
|
+
#: How far every atom of a piece that hangs off a residue stands clear of the box's edge, in bond lengths.
|
|
64
|
+
_CLEAR = 0.3
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def unit_label(res: PeptideResidue) -> tuple[str, str]:
|
|
68
|
+
"""What a residue's box says: its code, and its number (as deposited, or its position in the chain)."""
|
|
69
|
+
return res.code3, res.shown
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def unit_width(peptide: Peptide) -> float:
|
|
73
|
+
"""One width for all boxes of a chain: the column reads as a column."""
|
|
74
|
+
widest = max(text_width(code, UNIT_FONT, bold=True) + _GAP + text_width(num, INDEX_FONT)
|
|
75
|
+
for code, num in (unit_label(r) for r in peptide.residues))
|
|
76
|
+
return math.ceil(widest + 2.0 * _PAD)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _class_of(res: PeptideResidue) -> str:
|
|
80
|
+
return residue_class(res.name) if res.known else "other"
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _sub_ligand(lig: Ligand, keep: Sequence[int]) -> tuple[Ligand, list[int]]:
|
|
84
|
+
"""A ligand made of some atoms of another, and for each of its atoms the index it had there."""
|
|
85
|
+
order = sorted(set(keep))
|
|
86
|
+
rw = Chem.RWMol(lig.mol)
|
|
87
|
+
wanted = set(order)
|
|
88
|
+
for idx in sorted((a.GetIdx() for a in rw.GetAtoms() if a.GetIdx() not in wanted), reverse=True):
|
|
89
|
+
rw.RemoveAtom(idx)
|
|
90
|
+
mol = rw.GetMol()
|
|
91
|
+
with quiet_rdkit():
|
|
92
|
+
Chem.SanitizeMol(mol, catchErrors=True)
|
|
93
|
+
return Ligand(mol=mol, names=[lig.names[i] for i in order], coords3d=np.asarray(lig.coords3d)[order],
|
|
94
|
+
bond_source=lig.bond_source), order
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _rotated(points: np.ndarray, about: np.ndarray, angle: float) -> np.ndarray:
|
|
98
|
+
c, s = math.cos(angle), math.sin(angle)
|
|
99
|
+
rel = points - about
|
|
100
|
+
return about + np.column_stack([rel[:, 0] * c - rel[:, 1] * s, rel[:, 0] * s + rel[:, 1] * c])
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _place_appendage(lig: Ligand, app: Appendage, metrics: Metrics, method: str, start: Point, direction: Point,
|
|
104
|
+
exact: "Mapping[str, Point] | None") -> tuple[Depiction, list[int]]:
|
|
105
|
+
"""The appendage drawn as atoms, growing from ``start`` in ``direction``.
|
|
106
|
+
|
|
107
|
+
``start`` is where the bond to the chain leaves the residue's box. The
|
|
108
|
+
atoms are laid out as for any small molecule and then turned as one body,
|
|
109
|
+
so that the piece runs away from the chain. A piece that no bond holds to
|
|
110
|
+
the chain is not turned: it is set off from the box, level with ``start``.
|
|
111
|
+
"""
|
|
112
|
+
holders = sorted({a for _, a, _ in app.attachments})
|
|
113
|
+
sub, order = _sub_ligand(lig, list(app.atoms) + holders)
|
|
114
|
+
back = {orig: k for k, orig in enumerate(order)}
|
|
115
|
+
own = {lig.names[a] for a in app.atoms}
|
|
116
|
+
if exact is not None and all(n in exact for n in own):
|
|
117
|
+
# A stored layout: every atom where the graph has it; the holder where the bond leaves the box.
|
|
118
|
+
final = {n: exact.get(n, start) for n in sub.names}
|
|
119
|
+
else:
|
|
120
|
+
first = depict_ligand(sub, metrics, method=method)
|
|
121
|
+
xy = np.array([first.atoms[k].pos for k in range(len(order))], dtype=float)
|
|
122
|
+
if app.attachments:
|
|
123
|
+
holder = back[app.attachments[0][1]]
|
|
124
|
+
mine = [back[a] for a in app.atoms]
|
|
125
|
+
away = xy[mine].mean(axis=0) - xy[holder]
|
|
126
|
+
if float(np.hypot(*away)) < 1e-6:
|
|
127
|
+
away = xy[back[app.attachments[0][2]]] - xy[holder]
|
|
128
|
+
turn = math.atan2(direction[1], direction[0]) - math.atan2(float(away[1]), float(away[0]))
|
|
129
|
+
# A long piece turned by its middle can fold back over the column: of the turns 15 degrees apart,
|
|
130
|
+
# the nearest one that keeps every atom of the piece clear of the box's edge, and where none does,
|
|
131
|
+
# the clearest, set off from the edge.
|
|
132
|
+
out = np.array(direction, dtype=float)
|
|
133
|
+
margin = _CLEAR * metrics.bond_length
|
|
134
|
+
best: "tuple[float, np.ndarray] | None" = None
|
|
135
|
+
for step in (0, 1, -1, 2, -2, 3, -3, 4, -4, 5, -5, 6, -6):
|
|
136
|
+
tried = _rotated(xy, xy[holder], turn + math.radians(15.0 * step))
|
|
137
|
+
tried = tried + (np.array(start, dtype=float) - tried[holder])
|
|
138
|
+
clear = float(((tried[mine] - np.array(start, dtype=float)) @ out).min())
|
|
139
|
+
if best is None or clear > best[0]:
|
|
140
|
+
best = (clear, tried)
|
|
141
|
+
if clear >= margin:
|
|
142
|
+
best = (clear, tried)
|
|
143
|
+
break
|
|
144
|
+
assert best is not None
|
|
145
|
+
xy = best[1] if best[0] >= margin else best[1] + out * (margin - best[0])
|
|
146
|
+
else:
|
|
147
|
+
# Its atom nearest to the box at that distance from it, and the piece level with where it starts.
|
|
148
|
+
out = np.array(direction, dtype=float)
|
|
149
|
+
across = np.array([-out[1], out[0]])
|
|
150
|
+
xy = xy - out * float((xy @ out).min()) - across * float((xy @ across).mean())
|
|
151
|
+
xy = xy + np.array(start, dtype=float) + out * _LOOSE * metrics.bond_length
|
|
152
|
+
final = {n: (float(xy[k, 0]), float(xy[k, 1])) for k, n in enumerate(sub.names)}
|
|
153
|
+
bl = metrics.bond_length
|
|
154
|
+
coords = {n: (p[0] / bl, -p[1] / bl) for n, p in final.items()}
|
|
155
|
+
dep = depict_ligand(sub, metrics, coords=coords, normalise=False, exact=dict(final))
|
|
156
|
+
return dep, order
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def _nearest_residue(lig: Ligand, peptide: Peptide, app: Appendage) -> int:
|
|
160
|
+
"""The position of the residue beside whose box a piece stands that no bond holds to the chain: of an ion
|
|
161
|
+
that the chain holds (``lig.coordination``), the residue of the nearest atom that holds it; of anything
|
|
162
|
+
else, the residue of the atom nearest to it in the model."""
|
|
163
|
+
mine = list(app.atoms)
|
|
164
|
+
donors = [d for m, d in lig.coordination if m in mine and peptide.residue_of(d) is not None]
|
|
165
|
+
among = donors or [a for res in peptide.residues for a in res.atoms]
|
|
166
|
+
xyz = np.asarray(lig.coords3d, dtype=float)
|
|
167
|
+
apart = np.linalg.norm(xyz[among][:, None, :] - xyz[mine][None, :, :], axis=2).min(axis=1)
|
|
168
|
+
res = peptide.residue_of(among[int(np.argmin(apart))])
|
|
169
|
+
assert res is not None
|
|
170
|
+
return res.position
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def _column(n: int, pitch: float) -> list[Point]:
|
|
174
|
+
return [(0.0, k * pitch) for k in range(n)]
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
# ---------------------------------------------------------------------------
|
|
178
|
+
# Atoms of a residue drawn beside its box
|
|
179
|
+
# ---------------------------------------------------------------------------
|
|
180
|
+
|
|
181
|
+
@dataclass(frozen=True)
|
|
182
|
+
class Piece:
|
|
183
|
+
"""The atoms of one residue of the column that are drawn as atoms: where each stands, relative to
|
|
184
|
+
the centre of the residue's box; the rectangles their ink fills there, atom by atom and half a bond
|
|
185
|
+
at a time (for the room between residues: one rectangle round a whole side chain would claim the
|
|
186
|
+
empty corners beside it); and the parts they come in -- the side chain, the nitrogen, the carbonyl
|
|
187
|
+
-- each with the point of the box it starts from, if it starts from one."""
|
|
188
|
+
|
|
189
|
+
xy: "dict[int, Point]"
|
|
190
|
+
rects: "tuple[Box, ...]"
|
|
191
|
+
parts: "tuple[tuple[tuple[int, ...], Point | None], ...]" = ()
|
|
192
|
+
#: The bonds among these atoms, and the bonds that hold them to the box: from a point of the box
|
|
193
|
+
#: (relative to its centre) to an atom.
|
|
194
|
+
bonds: "tuple[tuple[int, int], ...]" = ()
|
|
195
|
+
stems: "tuple[tuple[Point, int], ...]" = ()
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def shown_atoms(peptide: Peptide, involved: "Mapping[int, Collection[int]]") -> dict[int, tuple[int, ...]]:
|
|
199
|
+
"""Which atoms of which residue are drawn beside its box, by position in the chain.
|
|
200
|
+
|
|
201
|
+
``involved`` are, for a position, the atoms of that residue that a directional contact names.
|
|
202
|
+
Only such a residue is drawn with atoms, and only if ``peptide.detail`` asks for more than boxes:
|
|
203
|
+
then the part that makes the contact and what the level adds (:func:`bindview.fragments.fragment_atoms`),
|
|
204
|
+
without the alpha carbon, which is the box. A proline's nitrogen stays in the box too: its ring
|
|
205
|
+
closes on it. A residue that is not one of the twenty, or a contact through an atom the template
|
|
206
|
+
does not have, leaves the residue a box.
|
|
207
|
+
"""
|
|
208
|
+
from .fragments import fragment_atoms
|
|
209
|
+
|
|
210
|
+
if peptide.detail in (None, "box"):
|
|
211
|
+
return {}
|
|
212
|
+
out: dict[int, tuple[int, ...]] = {}
|
|
213
|
+
for res in peptide.residues:
|
|
214
|
+
atoms = involved.get(res.position)
|
|
215
|
+
if not atoms or not res.known:
|
|
216
|
+
continue
|
|
217
|
+
local = {i: n for i, n in res.atom_names}
|
|
218
|
+
if any(i not in local for i in atoms):
|
|
219
|
+
continue
|
|
220
|
+
keep = fragment_atoms(res.name, [local[i] for i in atoms], peptide.detail)
|
|
221
|
+
if keep is None:
|
|
222
|
+
continue
|
|
223
|
+
if res.kind == "nucleotide":
|
|
224
|
+
# Under the template's names (a file may say O1P for OP1); the box is the sugar's C4'.
|
|
225
|
+
local = {i: canonical_atom(res.name, n) for i, n in local.items()}
|
|
226
|
+
hidden = {"C4'"}
|
|
227
|
+
else:
|
|
228
|
+
hidden = {"CA", "N"} if canonical_resname(res.name) == "PRO" else {"CA"}
|
|
229
|
+
chosen = tuple(i for i in res.atoms if local.get(i) in keep and local[i] not in hidden)
|
|
230
|
+
if chosen:
|
|
231
|
+
out[res.position] = chosen
|
|
232
|
+
return out
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def piece_sides(order: "Sequence[int]", partners: "Mapping[int, Collection[Hashable]]") -> dict[int, int]:
|
|
236
|
+
"""On which side of the column each residue's side chain stands: +1 right, -1 left.
|
|
237
|
+
|
|
238
|
+
``order`` are the positions of the residues that are drawn with atoms, from the top of the column;
|
|
239
|
+
``partners`` are, for a position, whatever makes directional contacts with its drawn atoms. Two
|
|
240
|
+
residues that share a partner stand on the same side, so that the partner does not have to be on
|
|
241
|
+
both sides of the column; the groups this makes alternate, the topmost to the right.
|
|
242
|
+
"""
|
|
243
|
+
group = {p: p for p in order}
|
|
244
|
+
|
|
245
|
+
def find(p: int) -> int:
|
|
246
|
+
while group[p] != p:
|
|
247
|
+
group[p] = group[group[p]]
|
|
248
|
+
p = group[p]
|
|
249
|
+
return p
|
|
250
|
+
|
|
251
|
+
seen: dict[Hashable, int] = {}
|
|
252
|
+
for p in order:
|
|
253
|
+
for partner in sorted(partners.get(p, ()), key=repr):
|
|
254
|
+
if partner in seen:
|
|
255
|
+
group[find(p)] = find(seen[partner])
|
|
256
|
+
else:
|
|
257
|
+
seen[partner] = p
|
|
258
|
+
sides: dict[int, int] = {}
|
|
259
|
+
turn: dict[int, int] = {}
|
|
260
|
+
for p in order:
|
|
261
|
+
root = find(p)
|
|
262
|
+
if root not in turn:
|
|
263
|
+
turn[root] = 1 if len(turn) % 2 == 0 else -1
|
|
264
|
+
sides[p] = turn[root]
|
|
265
|
+
return sides
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
def lay_piece(res: PeptideResidue, shown: "Sequence[int]", side: int, half_w: float, half_h: float,
|
|
269
|
+
metrics: Metrics) -> Piece:
|
|
270
|
+
"""Where the atoms of a residue stand that are drawn beside its box.
|
|
271
|
+
|
|
272
|
+
The box is the alpha carbon. The side chain stands on ``side`` of it, laid out as its template is
|
|
273
|
+
and turned so that its middle is on the level of the box. The backbone nitrogen stands on the line
|
|
274
|
+
of the column above the box and the carbonyl carbon below it, as the chain runs; the oxygen beside
|
|
275
|
+
that carbon, on the side away from the side chain.
|
|
276
|
+
"""
|
|
277
|
+
from .fragments import _unit_layout
|
|
278
|
+
|
|
279
|
+
if res.kind == "nucleotide":
|
|
280
|
+
return _lay_nucleotide(res, shown, side, half_w, half_h, metrics)
|
|
281
|
+
length = metrics.bond_length * metrics.protein_bond_scale
|
|
282
|
+
font = metrics.protein_atom_font
|
|
283
|
+
local = {i: n for i, n in res.atom_names}
|
|
284
|
+
by_name = {local[i]: i for i in shown}
|
|
285
|
+
xy: dict[int, Point] = {}
|
|
286
|
+
template = template_for(res.name)
|
|
287
|
+
assert template is not None
|
|
288
|
+
chain = tuple(n for n in template.sidechain if n in by_name)
|
|
289
|
+
if chain:
|
|
290
|
+
unit, _rings = _unit_layout(canonical_resname(res.name), ("CA",) + chain)
|
|
291
|
+
pts = np.array(unit, dtype=float)
|
|
292
|
+
pts = pts - pts[0]
|
|
293
|
+
middle = pts[1:].mean(axis=0)
|
|
294
|
+
turn = -math.atan2(float(middle[1]), float(middle[0]))
|
|
295
|
+
c, s = math.cos(turn), math.sin(turn)
|
|
296
|
+
for name, (px, py) in zip(chain, pts[1:]):
|
|
297
|
+
x, y = float(px * c - py * s), float(px * s + py * c)
|
|
298
|
+
xy[by_name[name]] = (side * (half_w + x * length), -y * length)
|
|
299
|
+
if "N" in by_name:
|
|
300
|
+
xy[by_name["N"]] = (0.0, -half_h - length)
|
|
301
|
+
if "C" in by_name:
|
|
302
|
+
xy[by_name["C"]] = (0.0, half_h + length)
|
|
303
|
+
if "O" in by_name:
|
|
304
|
+
base = xy[by_name["C"]] if "C" in by_name else (0.0, half_h)
|
|
305
|
+
xy[by_name["O"]] = (base[0] - side * length * math.sin(math.radians(60.0)),
|
|
306
|
+
base[1] + length * math.cos(math.radians(60.0)))
|
|
307
|
+
|
|
308
|
+
parts: "list[tuple[tuple[int, ...], Point | None]]" = []
|
|
309
|
+
if chain:
|
|
310
|
+
parts.append((tuple(by_name[n] for n in chain), (side * half_w, 0.0)))
|
|
311
|
+
if "N" in by_name:
|
|
312
|
+
parts.append(((by_name["N"],), None))
|
|
313
|
+
below = tuple(by_name[n] for n in ("C", "O") if n in by_name)
|
|
314
|
+
if below:
|
|
315
|
+
parts.append((below, None))
|
|
316
|
+
names = {i: local[i] for i in shown}
|
|
317
|
+
from .residues import template_bonds
|
|
318
|
+
|
|
319
|
+
bonds = tuple((by_name[a], by_name[b]) for a, b, _order in template_bonds(canonical_resname(res.name))
|
|
320
|
+
if a in by_name and b in by_name)
|
|
321
|
+
stems: "list[tuple[Point, int]]" = []
|
|
322
|
+
if chain:
|
|
323
|
+
stems.append(((side * half_w, 0.0), by_name[chain[0]]))
|
|
324
|
+
if canonical_resname(res.name) == "PRO" and "CD" in by_name:
|
|
325
|
+
stems.append(((side * half_w, 0.0), by_name["CD"])) # the ring closes on the box
|
|
326
|
+
if "N" in by_name:
|
|
327
|
+
stems.append(((0.0, -half_h), by_name["N"]))
|
|
328
|
+
if "C" in by_name:
|
|
329
|
+
stems.append(((0.0, half_h), by_name["C"]))
|
|
330
|
+
return Piece(xy, ink_rects(xy, names, font, bonds, stems), tuple(parts), bonds, tuple(stems))
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
def _lay_nucleotide(res: PeptideResidue, shown: "Sequence[int]", side: int, half_w: float, half_h: float,
|
|
334
|
+
metrics: Metrics) -> Piece:
|
|
335
|
+
"""Where the atoms of a nucleotide stand that are drawn beside its box (docs/reference.md has the rule).
|
|
336
|
+
|
|
337
|
+
The box is the sugar's C4'. The base, and the atoms of the sugar that are drawn other than C4' and O3',
|
|
338
|
+
stand on ``side`` of it, laid out as their template is and turned so that their middle is on the level
|
|
339
|
+
of the box; where neither C3' nor O4' is drawn, the base hangs on the box by C1'. C5', O5' and P stand
|
|
340
|
+
on the line of the column above the box, where the chain comes in, the phosphate's free oxygens beside
|
|
341
|
+
P; O3' below the box, where the chain goes on.
|
|
342
|
+
"""
|
|
343
|
+
from .fragments import _unit_layout
|
|
344
|
+
from .residues import template_bonds
|
|
345
|
+
|
|
346
|
+
length = metrics.bond_length * metrics.protein_bond_scale
|
|
347
|
+
font = metrics.protein_atom_font
|
|
348
|
+
resname = canonical_resname(res.name)
|
|
349
|
+
local = {i: canonical_atom(res.name, n) for i, n in res.atom_names}
|
|
350
|
+
by_name = {local[i]: i for i in shown}
|
|
351
|
+
template = template_for(res.name)
|
|
352
|
+
assert template is not None
|
|
353
|
+
xy: dict[int, Point] = {}
|
|
354
|
+
above = (*TAIL, "P") # C5', O5', P: one above the other, from the box up
|
|
355
|
+
beside = tuple(n for n in template.atoms if n in by_name and n not in PHOSPHATE + TAIL + ("C4'", "O3'"))
|
|
356
|
+
attach = tuple(n for n in ("C3'", "O4'") if n in beside)
|
|
357
|
+
if beside:
|
|
358
|
+
if attach:
|
|
359
|
+
unit, _rings = _unit_layout(resname, ("C4'",) + beside)
|
|
360
|
+
pts = np.array(unit, dtype=float)
|
|
361
|
+
anchor, rest = pts[0], pts[1:]
|
|
362
|
+
else:
|
|
363
|
+
# Hung on the box by C1': a point one bond beyond C1', away from the base, stands for C4'.
|
|
364
|
+
unit, _rings = _unit_layout(resname, beside)
|
|
365
|
+
rest = np.array(unit, dtype=float)
|
|
366
|
+
root = rest[beside.index("C1'")] if "C1'" in beside else rest[0]
|
|
367
|
+
away = root - rest.mean(axis=0)
|
|
368
|
+
norm = float(np.linalg.norm(away))
|
|
369
|
+
anchor = root + (away / norm if norm > 1e-9 else np.array([-1.0, 0.0]))
|
|
370
|
+
rest = rest - anchor
|
|
371
|
+
middle = rest.mean(axis=0)
|
|
372
|
+
turn = -math.atan2(float(middle[1]), float(middle[0]))
|
|
373
|
+
c, s = math.cos(turn), math.sin(turn)
|
|
374
|
+
for name, (px, py) in zip(beside, rest):
|
|
375
|
+
x, y = float(px * c - py * s), float(px * s + py * c)
|
|
376
|
+
xy[by_name[name]] = (side * (half_w + x * length), -y * length)
|
|
377
|
+
y_up = -half_h
|
|
378
|
+
for name in above:
|
|
379
|
+
if name in by_name:
|
|
380
|
+
y_up -= length
|
|
381
|
+
xy[by_name[name]] = (0.0, y_up)
|
|
382
|
+
if "P" in by_name:
|
|
383
|
+
px, py = xy[by_name["P"]]
|
|
384
|
+
for name, way in (("OP1", -side), ("OP2", side)):
|
|
385
|
+
if name in by_name:
|
|
386
|
+
xy[by_name[name]] = (px + way * length * math.sin(math.radians(60.0)),
|
|
387
|
+
py - length * math.cos(math.radians(60.0)))
|
|
388
|
+
if "O3'" in by_name:
|
|
389
|
+
xy[by_name["O3'"]] = (0.0, half_h + length)
|
|
390
|
+
|
|
391
|
+
parts: "list[tuple[tuple[int, ...], Point | None]]" = []
|
|
392
|
+
if beside:
|
|
393
|
+
parts.append((tuple(by_name[n] for n in beside), (side * half_w, 0.0)))
|
|
394
|
+
up = tuple(by_name[n] for n in (*above, "OP1", "OP2") if n in by_name)
|
|
395
|
+
if up:
|
|
396
|
+
parts.append((up, (0.0, -half_h)))
|
|
397
|
+
if "O3'" in by_name:
|
|
398
|
+
parts.append(((by_name["O3'"],), (0.0, half_h)))
|
|
399
|
+
names = {i: local[i] for i in shown}
|
|
400
|
+
bonds = tuple((by_name[a], by_name[b]) for a, b, _order in template_bonds(resname)
|
|
401
|
+
if a in by_name and b in by_name)
|
|
402
|
+
stems: "list[tuple[Point, int]]" = []
|
|
403
|
+
for name in (attach or (("C1'",) if "C1'" in beside else beside[:1])):
|
|
404
|
+
stems.append(((side * half_w, 0.0), by_name[name]))
|
|
405
|
+
lowest = next((n for n in above if n in by_name), None)
|
|
406
|
+
if lowest is not None:
|
|
407
|
+
stems.append(((0.0, -half_h), by_name[lowest]))
|
|
408
|
+
if "O3'" in by_name:
|
|
409
|
+
stems.append(((0.0, half_h), by_name["O3'"]))
|
|
410
|
+
return Piece(xy, ink_rects(xy, names, font, bonds, stems), tuple(parts), bonds, tuple(stems))
|
|
411
|
+
|
|
412
|
+
|
|
413
|
+
def ink_rects(xy: "Mapping[int, Point]", names: "Mapping[int, str]", font: float,
|
|
414
|
+
bonds: "Sequence[tuple[int, int]]", stems: "Sequence[tuple[Point, int]]",
|
|
415
|
+
at: Point = (0.0, 0.0)) -> "tuple[Box, ...]":
|
|
416
|
+
"""The ink of a piece as small rectangles: every atom (a carbon is a corner of the drawing, any
|
|
417
|
+
other atom its name in ``font``), and every bond in two halves. One rectangle round a whole side
|
|
418
|
+
chain would claim the empty corners beside it. ``stems`` start at points of the box, which are
|
|
419
|
+
given relative to ``at``; ``xy`` are the atoms where they stand."""
|
|
420
|
+
# (A carbon is where bonds meet: their halves are its ink. Only an atom with a name has more.)
|
|
421
|
+
out = list(piece_rects([((i,), None) for i in xy if names[i][:1] != "C"], xy, names, font))
|
|
422
|
+
lines = [(xy[a], xy[b]) for a, b in bonds] + [((at[0] + s[0], at[1] + s[1]), xy[i]) for s, i in stems]
|
|
423
|
+
for (ax, ay), (bx, by) in lines:
|
|
424
|
+
mx, my = (ax + bx) / 2.0, (ay + by) / 2.0
|
|
425
|
+
for (px, py), (qx, qy) in (((ax, ay), (mx, my)), ((mx, my), (bx, by))):
|
|
426
|
+
out.append((min(px, qx) - 1.0, min(py, qy) - 1.0, max(px, qx) + 1.0, max(py, qy) + 1.0))
|
|
427
|
+
return tuple(out)
|
|
428
|
+
|
|
429
|
+
|
|
430
|
+
def piece_rects(parts: "Sequence[tuple[Sequence[int], Point | None]]", xy: "Mapping[int, Point]",
|
|
431
|
+
names: "Mapping[int, str]", font: float, at: Point = (0.0, 0.0)) -> "tuple[Box, ...]":
|
|
432
|
+
"""The rectangle that the ink of each part of a piece fills: its atoms where ``xy`` has them (a
|
|
433
|
+
carbon is a corner of the drawing, any other atom its name in ``font``), and the point of the box
|
|
434
|
+
the part starts from, which is given relative to ``at``."""
|
|
435
|
+
def ink(i: int) -> Box:
|
|
436
|
+
x, y = xy[i]
|
|
437
|
+
if names[i][:1] == "C":
|
|
438
|
+
return (x - 2.0, y - 2.0, x + 2.0, y + 2.0)
|
|
439
|
+
w, h = text_width(names[i], font) + 2.0, CAP_HEIGHT * font + 2.0
|
|
440
|
+
return (x - w / 2.0, y - h / 2.0, x + w / 2.0, y + h / 2.0)
|
|
441
|
+
|
|
442
|
+
rects: list[Box] = []
|
|
443
|
+
for atoms, start in parts:
|
|
444
|
+
boxes = [ink(i) for i in atoms]
|
|
445
|
+
if start is not None:
|
|
446
|
+
boxes.append((at[0] + start[0], at[1] + start[1], at[0] + start[0], at[1] + start[1]))
|
|
447
|
+
rects.append((min(b[0] for b in boxes), min(b[1] for b in boxes),
|
|
448
|
+
max(b[2] for b in boxes), max(b[3] for b in boxes)))
|
|
449
|
+
return tuple(rects)
|
|
450
|
+
|
|
451
|
+
|
|
452
|
+
def stack_column(n: int, pitch: float, half_w: float, half_h: float, pieces: "Mapping[int, Piece]") -> list[Point]:
|
|
453
|
+
"""The centres of the boxes of a column in which some residues have atoms beside their boxes.
|
|
454
|
+
|
|
455
|
+
Boxes are ``pitch`` apart, as in every column. A residue is moved further down by the least it takes
|
|
456
|
+
for the ink of its atoms to keep :data:`PIECE_GAP` from the ink of every residue above it, atoms
|
|
457
|
+
and box, and for its box to keep that from their atoms. ``pieces`` by index in the column.
|
|
458
|
+
"""
|
|
459
|
+
box: Box = (-half_w, -half_h, half_w, half_h)
|
|
460
|
+
ys = [0.0]
|
|
461
|
+
for k in range(1, n):
|
|
462
|
+
y = ys[k - 1] + pitch
|
|
463
|
+
mine = pieces[k].rects if k in pieces else ()
|
|
464
|
+
for j in range(k):
|
|
465
|
+
theirs = pieces[j].rects if j in pieces else ()
|
|
466
|
+
pairs = [(a, b) for a in theirs for b in mine] + [(a, box) for a in theirs] + [(box, b) for b in mine]
|
|
467
|
+
for a, b in pairs:
|
|
468
|
+
if a[0] < b[2] + PIECE_GAP and b[0] < a[2] + PIECE_GAP:
|
|
469
|
+
y = max(y, ys[j] + a[3] + PIECE_GAP - b[1])
|
|
470
|
+
ys.append(y)
|
|
471
|
+
return [(0.0, y) for y in ys]
|
|
472
|
+
|
|
473
|
+
|
|
474
|
+
def _name_label(pos: Point, text: str, font: float) -> AtomLabel:
|
|
475
|
+
"""An atom's name as its label, the way the fragments around a chain carry theirs."""
|
|
476
|
+
x, y = pos
|
|
477
|
+
w, cap = text_width(text, font), CAP_HEIGHT * font
|
|
478
|
+
box: Box = (x - w / 2.0, y - cap / 2.0, x + w / 2.0, y + cap / 2.0)
|
|
479
|
+
return AtomLabel((LabelRun(x, y + cap / 2.0, "middle", (Span(text, size=font),), box),), box)
|
|
480
|
+
|
|
481
|
+
|
|
482
|
+
def depict_polymer(lig: Ligand, peptide: Peptide, metrics: Metrics, *, method: str = "auto",
|
|
483
|
+
unit_xy: "Mapping[int, Point] | None" = None,
|
|
484
|
+
exact: "Mapping[str, Point] | None" = None,
|
|
485
|
+
plane: "Arrangement | None" = None, scale: "float | None" = None,
|
|
486
|
+
shown: "Mapping[int, Sequence[int]] | None" = None,
|
|
487
|
+
sides: "Mapping[int, int] | None" = None, labels: str = "names") -> Depiction:
|
|
488
|
+
"""The chain depiction of a peptide ligand.
|
|
489
|
+
|
|
490
|
+
``unit_xy`` (position -> centre) and ``exact`` (atom name -> point, for
|
|
491
|
+
atoms outside the chain) redraw a stored layout: positions are then taken
|
|
492
|
+
as they are.
|
|
493
|
+
|
|
494
|
+
With ``plane`` the residues do not stand in a column: each box stands
|
|
495
|
+
where its residue lies on the plane through them (:mod:`bindview.plane`),
|
|
496
|
+
at one scale, and boxes that would cover each other are pushed apart by
|
|
497
|
+
the least it takes. What that did to the arrangement is measured and goes
|
|
498
|
+
with the depiction (``Depiction.plane``). ``scale`` (page units per
|
|
499
|
+
ångström) is the scale of a stored layout.
|
|
500
|
+
|
|
501
|
+
``shown`` (position -> atoms, :func:`shown_atoms`) are the atoms of a
|
|
502
|
+
residue that are drawn beside its box, ``sides`` (position -> +1 or -1,
|
|
503
|
+
:func:`piece_sides`) the side its side chain stands on, ``labels`` what is
|
|
504
|
+
written on them (:func:`bindview.residues.written`), which moves none of
|
|
505
|
+
them: they are stacked by the room their names take. A column only:
|
|
506
|
+
on a plane there is no side of a box that is nobody's.
|
|
507
|
+
"""
|
|
508
|
+
n = len(peptide)
|
|
509
|
+
width = unit_width(peptide)
|
|
510
|
+
half_w, half_h = width / 2.0, UNIT_HEIGHT / 2.0
|
|
511
|
+
pitch = max(MIN_PITCH, metrics.chain_pitch * metrics.bond_length)
|
|
512
|
+
on_plane = None
|
|
513
|
+
if plane is not None and len(plane.xy) != n:
|
|
514
|
+
raise ValueError(f"{len(plane.xy)} places on the plane for {n} residues")
|
|
515
|
+
pieces: dict[int, Piece] = {} # by index in the column
|
|
516
|
+
if shown and plane is None:
|
|
517
|
+
for k, res in enumerate(peptide.residues):
|
|
518
|
+
if shown.get(res.position):
|
|
519
|
+
pieces[k] = lay_piece(res, shown[res.position], (sides or {}).get(res.position, 1), half_w,
|
|
520
|
+
half_h, metrics)
|
|
521
|
+
if plane is not None and unit_xy is None:
|
|
522
|
+
centres, on_plane = plane.place(pitch, half_w, half_h)
|
|
523
|
+
elif pieces:
|
|
524
|
+
centres = stack_column(n, pitch, half_w, half_h, pieces)
|
|
525
|
+
else:
|
|
526
|
+
centres = _column(n, pitch)
|
|
527
|
+
if unit_xy is not None:
|
|
528
|
+
given = [unit_xy.get(r.position, centres[k]) for k, r in enumerate(peptide.residues)]
|
|
529
|
+
centres = [(float(p[0]), float(p[1])) for p in given]
|
|
530
|
+
if plane is not None:
|
|
531
|
+
# A stored layout: the boxes are where they were put, and are measured where they are.
|
|
532
|
+
on_plane = plane.measure(centres, scale if scale else plane.scale(pitch), None, half_w, half_h)
|
|
533
|
+
|
|
534
|
+
mol = lig.mol
|
|
535
|
+
atoms: list[DepAtom | None] = [None] * lig.n_atoms
|
|
536
|
+
units: list[DepUnit] = []
|
|
537
|
+
for k, res in enumerate(peptide.residues):
|
|
538
|
+
cx, cy = centres[k]
|
|
539
|
+
box: Box = (cx - half_w, cy - half_h, cx + half_w, cy + half_h)
|
|
540
|
+
code, number = unit_label(res)
|
|
541
|
+
piece = pieces.get(k)
|
|
542
|
+
beside: dict[int, Point] = {}
|
|
543
|
+
if piece is not None:
|
|
544
|
+
# Atoms of their own beside the box: where the piece has them, or where a stored layout does.
|
|
545
|
+
for i, (ox, oy) in piece.xy.items():
|
|
546
|
+
beside[i] = (cx + ox, cy + oy)
|
|
547
|
+
if exact is not None and lig.names[i] in exact:
|
|
548
|
+
beside[i] = (float(exact[lig.names[i]][0]), float(exact[lig.names[i]][1]))
|
|
549
|
+
units.append(DepUnit(index=k, position=res.position, name=res.name, text=code, x=cx, y=cy, box=box,
|
|
550
|
+
anchor=res.ca, atoms=res.atoms,
|
|
551
|
+
backbone=tuple(a for a in res.atoms if res.is_backbone(a)),
|
|
552
|
+
residue_class=_class_of(res), number=number,
|
|
553
|
+
beside=tuple(sorted(beside)),
|
|
554
|
+
side=(sides or {}).get(res.position, 1) if piece is not None else 0,
|
|
555
|
+
n=res.n, c=res.c,
|
|
556
|
+
rects=ink_rects(beside, {i: written(res.name_of(i) or "C", labels) for i in beside},
|
|
557
|
+
metrics.protein_atom_font, piece.bonds, piece.stems, (cx, cy))
|
|
558
|
+
if piece is not None else ()))
|
|
559
|
+
for i in res.atoms:
|
|
560
|
+
atom = mol.GetAtomWithIdx(i)
|
|
561
|
+
if i in beside:
|
|
562
|
+
px, py = beside[i]
|
|
563
|
+
word = written(res.name_of(i) or atom.GetSymbol(), labels)
|
|
564
|
+
own = None if atom.GetSymbol() == "C" else _name_label((px, py), word, metrics.protein_atom_font)
|
|
565
|
+
atoms[i] = DepAtom(idx=i, x=px, y=py, element=atom.GetSymbol(), name=lig.names[i],
|
|
566
|
+
hcount=atom.GetTotalNumHs(), charge=atom.GetFormalCharge(),
|
|
567
|
+
isotope=atom.GetIsotope(), label=own, aromatic=atom.GetIsAromatic())
|
|
568
|
+
continue
|
|
569
|
+
# The box is the residue's ink: one label, on its alpha carbon, so that the field and the
|
|
570
|
+
# audit see it once.
|
|
571
|
+
label = AtomLabel(runs=(LabelRun(cx, cy, "middle", (), box),), box=box) if i == res.ca else None
|
|
572
|
+
atoms[i] = DepAtom(idx=i, x=cx, y=cy, element=atom.GetSymbol(), name=lig.names[i],
|
|
573
|
+
hcount=atom.GetTotalNumHs(), charge=atom.GetFormalCharge(),
|
|
574
|
+
isotope=atom.GetIsotope(), label=label, aromatic=atom.GetIsAromatic())
|
|
575
|
+
|
|
576
|
+
bonds: list[DepBond] = []
|
|
577
|
+
for k in range(n - 1):
|
|
578
|
+
if peptide.residues[k].position in peptide.breaks:
|
|
579
|
+
# Residues are missing here (from the model, or left out because they are not at the
|
|
580
|
+
# interface that is drawn): no backbone, but a dotted line that says the chain goes on.
|
|
581
|
+
# On a plane only within a stretch: a dotted line from one loop to the next would cross
|
|
582
|
+
# the figure and say nothing.
|
|
583
|
+
if plane is None:
|
|
584
|
+
dotted = peptide.sequential
|
|
585
|
+
else:
|
|
586
|
+
# ... and not where it would run under a third box: it would be read as that box's line.
|
|
587
|
+
dotted = (peptide.residues[k].position in plane.joins
|
|
588
|
+
and not any(passes_through(centres[k], centres[k + 1], u.box)
|
|
589
|
+
for u in units if u.index not in (k, k + 1)))
|
|
590
|
+
if dotted:
|
|
591
|
+
bonds.append(DepBond(peptide.residues[k].ca, peptide.residues[k + 1].ca, 1, kind="gap"))
|
|
592
|
+
continue
|
|
593
|
+
bonds.append(DepBond(peptide.residues[k].ca, peptide.residues[k + 1].ca, 1, kind="chain"))
|
|
594
|
+
if peptide.cyclic and n > 2:
|
|
595
|
+
bonds.append(DepBond(peptide.residues[-1].ca, peptide.residues[0].ca, 1, kind="closure"))
|
|
596
|
+
for x in peptide.crosslinks:
|
|
597
|
+
bonds.append(DepBond(peptide.residue(x.a[0]).ca, peptide.residue(x.b[0]).ca, 1, kind="crosslink"))
|
|
598
|
+
|
|
599
|
+
notes: list[str] = []
|
|
600
|
+
extra: list[DepAtom] = []
|
|
601
|
+
rings: list[tuple[int, ...]] = []
|
|
602
|
+
taken: list[tuple[int, int]] = [] # (residue position, side) already holding an appendage
|
|
603
|
+
explicit = {i for piece in pieces.values() for i in piece.xy}
|
|
604
|
+
if explicit:
|
|
605
|
+
# The bonds of the atoms that stand beside their boxes, with the orders the molecule has.
|
|
606
|
+
kekulized = Chem.Mol(mol)
|
|
607
|
+
flat = True
|
|
608
|
+
with quiet_rdkit():
|
|
609
|
+
try:
|
|
610
|
+
Chem.Kekulize(kekulized, clearAromaticFlags=True)
|
|
611
|
+
except Exception: # not kekulizable: aromatic bonds are drawn as such
|
|
612
|
+
flat = False
|
|
613
|
+
home = {i: k for k, res in enumerate(peptide.residues) for i in res.atoms}
|
|
614
|
+
for mb in (kekulized if flat else mol).GetBonds():
|
|
615
|
+
ia, ib = mb.GetBeginAtomIdx(), mb.GetEndAtomIdx()
|
|
616
|
+
if ia not in explicit and ib not in explicit:
|
|
617
|
+
continue
|
|
618
|
+
ka, kb = home.get(ia), home.get(ib)
|
|
619
|
+
if ka is not None and kb is not None and ka != kb:
|
|
620
|
+
# A bond from one residue to another is drawn where the two stand one above the other
|
|
621
|
+
# and it is the peptide bond between them, carbonyl carbon above, nitrogen below. A
|
|
622
|
+
# column in the order of the interface has neighbours in the chain far apart: a bond
|
|
623
|
+
# between those would be a line across the boxes in between.
|
|
624
|
+
upper, lower = (ia, ib) if ka < kb else (ib, ia)
|
|
625
|
+
up, low = peptide.residues[min(ka, kb)], peptide.residues[max(ka, kb)]
|
|
626
|
+
if abs(ka - kb) != 1 or upper != up.c or lower != low.n:
|
|
627
|
+
continue
|
|
628
|
+
ringed = mb.GetIsAromatic() and not flat
|
|
629
|
+
mult = 1 if ringed else max(1, min(3, int(round(mb.GetBondTypeAsDouble()))))
|
|
630
|
+
bonds.append(DepBond(ia, ib, mult, aromatic=ringed))
|
|
631
|
+
rings.extend(tuple(ring) for ring in mol.GetRingInfo().AtomRings() if all(i in explicit for i in ring))
|
|
632
|
+
# An appendage goes to the side of the box that the residue's own side chain does not stand on.
|
|
633
|
+
taken.extend((peptide.residues[k].position, (sides or {}).get(peptide.residues[k].position, 1))
|
|
634
|
+
for k in sorted(pieces))
|
|
635
|
+
for app in sorted(peptide.appendages, key=lambda a: (a.attachments, a.atoms)):
|
|
636
|
+
if app.attachments:
|
|
637
|
+
position, holder, _first = app.attachments[0]
|
|
638
|
+
name = peptide.residue(position).name_of(holder)
|
|
639
|
+
else:
|
|
640
|
+
position, name = _nearest_residue(lig, peptide, app), None
|
|
641
|
+
cx, cy = centres[position - 1]
|
|
642
|
+
if name == "N" and position == 1 and not peptide.cyclic:
|
|
643
|
+
start, direction = (cx, cy - half_h), (0.0, -1.0) # a cap on the N-terminus: upward
|
|
644
|
+
elif name in ("C", "OXT") and position == n and not peptide.cyclic:
|
|
645
|
+
start, direction = (cx, cy + half_h), (0.0, 1.0) # on the C-terminus: downward
|
|
646
|
+
else:
|
|
647
|
+
side = 1 if (position, 1) not in taken else -1 # to the right, then to the left
|
|
648
|
+
taken.append((position, side))
|
|
649
|
+
start, direction = (cx + side * half_w, cy), (float(side), 0.0)
|
|
650
|
+
sub, order = _place_appendage(lig, app, metrics, method, start, direction, exact)
|
|
651
|
+
local: dict[int, int] = {} # index in the piece -> index in this depiction
|
|
652
|
+
for k, orig in enumerate(order):
|
|
653
|
+
local[k] = orig
|
|
654
|
+
if orig in app.atoms:
|
|
655
|
+
d = sub.atoms[k]
|
|
656
|
+
atoms[orig] = DepAtom(idx=orig, x=d.x, y=d.y, element=d.element, name=d.name, hcount=d.hcount,
|
|
657
|
+
charge=d.charge, isotope=d.isotope, label=d.label, aromatic=d.aromatic)
|
|
658
|
+
for d in sub.atoms[len(order):]: # hydrogens the drawing adds at a stereocentre
|
|
659
|
+
local[d.idx] = lig.n_atoms + len(extra)
|
|
660
|
+
extra.append(DepAtom(idx=local[d.idx], x=d.x, y=d.y, element=d.element, name=None, hcount=d.hcount,
|
|
661
|
+
charge=d.charge, isotope=d.isotope, label=d.label, aromatic=d.aromatic))
|
|
662
|
+
for b in sub.bonds:
|
|
663
|
+
ia, ib = local[b.a], local[b.b]
|
|
664
|
+
if ia not in app.atoms and ib not in app.atoms and ia < lig.n_atoms and ib < lig.n_atoms:
|
|
665
|
+
continue # a bond between two atoms of the chain: not this piece's
|
|
666
|
+
bonds.append(DepBond(ia, ib, b.order, b.stereo, b.aromatic, b.kind))
|
|
667
|
+
rings.extend(tuple(local[i] for i in ring) for ring in sub.rings
|
|
668
|
+
if all(local[i] in app.atoms for i in ring))
|
|
669
|
+
notes.extend(sub.notes)
|
|
670
|
+
|
|
671
|
+
placed = [d for d in atoms if d is not None]
|
|
672
|
+
if len(placed) != lig.n_atoms: # cannot happen: every atom is in a residue or an appendage
|
|
673
|
+
raise ValueError(f"{lig.n_atoms - len(placed)} ligand atom(s) are in neither a residue nor an appendage")
|
|
674
|
+
return Depiction(atoms=placed + extra, bonds=bonds, rings=rings, n_heavy=lig.n_atoms, metrics=metrics,
|
|
675
|
+
coord_source="chain", notes=notes, units=tuple(units),
|
|
676
|
+
open_ends=peptide.open_ends if (peptide.sequential and plane is None) else (False, False),
|
|
677
|
+
pairwise=peptide.pairwise, sequential=peptide.sequential, called=peptide.called,
|
|
678
|
+
arranged="plane" if plane is not None else "column", plane=on_plane)
|