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/depict.py
ADDED
|
@@ -0,0 +1,790 @@
|
|
|
1
|
+
"""From a named-atom molecule to drawable geometry.
|
|
2
|
+
|
|
3
|
+
Produces a :class:`Depiction`: 2D positions for every ligand atom (in SVG user
|
|
4
|
+
units, y pointing down), the atom labels with their boxes, the bonds with
|
|
5
|
+
order and stereo style, and the ring membership needed to place double bonds.
|
|
6
|
+
Nothing here knows about residues or interactions.
|
|
7
|
+
|
|
8
|
+
Coordinates come from RDKit's bundled CoordGen (BSD-3), which draws ring
|
|
9
|
+
systems and macrocycles the way a chemist would, with RDKit's own depictor as a
|
|
10
|
+
fallback; the better of the two by a clash / crossing count is kept. The choice
|
|
11
|
+
and everything after it are deterministic.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import math
|
|
17
|
+
from dataclasses import dataclass, field
|
|
18
|
+
from typing import Any, Sequence
|
|
19
|
+
|
|
20
|
+
import numpy as np
|
|
21
|
+
from rdkit import Chem
|
|
22
|
+
from rdkit.Chem import rdCoordGen, rdDepictor
|
|
23
|
+
from rdkit.Geometry import Point3D
|
|
24
|
+
|
|
25
|
+
from .chem import is_metal, quiet_rdkit
|
|
26
|
+
from .errors import BindviewError
|
|
27
|
+
from .geometry import Box, Point, box_expand, box_union, segment_box_entry, segments_intersect
|
|
28
|
+
from .ligand import Ligand
|
|
29
|
+
from .scene import Span
|
|
30
|
+
from .textmetrics import CAP_HEIGHT, DESCENT, text_width
|
|
31
|
+
from .theme import Metrics
|
|
32
|
+
|
|
33
|
+
__all__ = ["Depiction", "DepAtom", "DepBond", "AtomLabel", "LabelRun", "depict_ligand", "layout_score",
|
|
34
|
+
"atom_keys"]
|
|
35
|
+
|
|
36
|
+
_MINUS = "−"
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@dataclass(frozen=True)
|
|
40
|
+
class LabelRun:
|
|
41
|
+
"""One ``<text>`` element of an atom label: an anchor point plus spans."""
|
|
42
|
+
|
|
43
|
+
x: float
|
|
44
|
+
y: float # baseline
|
|
45
|
+
anchor: str # start | middle | end
|
|
46
|
+
spans: tuple[Span, ...]
|
|
47
|
+
box: Box
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
@dataclass(frozen=True)
|
|
51
|
+
class AtomLabel:
|
|
52
|
+
runs: tuple[LabelRun, ...]
|
|
53
|
+
box: Box # union of all runs
|
|
54
|
+
|
|
55
|
+
@property
|
|
56
|
+
def boxes(self) -> tuple[Box, ...]:
|
|
57
|
+
return tuple(r.box for r in self.runs)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
@dataclass
|
|
61
|
+
class DepAtom:
|
|
62
|
+
idx: int
|
|
63
|
+
x: float
|
|
64
|
+
y: float
|
|
65
|
+
element: str
|
|
66
|
+
name: str | None # structure-file atom name; None for depiction-only hydrogens
|
|
67
|
+
hcount: int = 0
|
|
68
|
+
charge: int = 0
|
|
69
|
+
isotope: int = 0
|
|
70
|
+
label: AtomLabel | None = None
|
|
71
|
+
aromatic: bool = False
|
|
72
|
+
|
|
73
|
+
@property
|
|
74
|
+
def pos(self) -> Point:
|
|
75
|
+
return (self.x, self.y)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
@dataclass
|
|
79
|
+
class DepBond:
|
|
80
|
+
a: int
|
|
81
|
+
b: int
|
|
82
|
+
order: int # 1, 2, 3
|
|
83
|
+
stereo: str = "none" # none | wedge | hash (narrow end at ``a``)
|
|
84
|
+
aromatic: bool = False # only set when the molecule could not be kekulized
|
|
85
|
+
#: covalent | coordination, and in a chain ligand: chain (the peptide bond between two units),
|
|
86
|
+
#: closure (the one that closes a ring of units) and crosslink (any other bond between two units)
|
|
87
|
+
kind: str = "covalent"
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
@dataclass(frozen=True)
|
|
91
|
+
class DepUnit:
|
|
92
|
+
"""One residue of a chain ligand as it is drawn: a labelled box standing for all of its atoms.
|
|
93
|
+
|
|
94
|
+
Every atom of the residue sits, in the depiction, at the centre of the box:
|
|
95
|
+
a contact that names any of them lands on the residue. ``anchor`` is the
|
|
96
|
+
atom that carries the box (the alpha carbon).
|
|
97
|
+
|
|
98
|
+
``beside`` are the atoms of the residue that are drawn beside the box as
|
|
99
|
+
atoms of their own (a residue that makes a directional contact, where the
|
|
100
|
+
chain is drawn with more than boxes: ``Peptide.detail``). They have places
|
|
101
|
+
of their own, and a directional contact that names one of them lands on it.
|
|
102
|
+
"""
|
|
103
|
+
|
|
104
|
+
index: int # into ``Depiction.units``
|
|
105
|
+
position: int # 1-based, from the N-terminus of the chain as perceived
|
|
106
|
+
name: str # "LYS", "XAA"
|
|
107
|
+
text: str # what is printed: "Lys", "D-Phe"
|
|
108
|
+
x: float
|
|
109
|
+
y: float
|
|
110
|
+
box: Box
|
|
111
|
+
anchor: int
|
|
112
|
+
atoms: tuple[int, ...]
|
|
113
|
+
backbone: tuple[int, ...] # the atoms of it that are backbone
|
|
114
|
+
residue_class: str = "other"
|
|
115
|
+
number: str = "" # what is printed beside the code: the deposited number, or the position
|
|
116
|
+
beside: tuple[int, ...] = () # the atoms of it that stand beside the box as atoms of their own
|
|
117
|
+
side: int = 0 # ... and on which side of the box its side chain stands: +1 right, -1 left
|
|
118
|
+
n: int = -1 # its backbone nitrogen and its carbonyl carbon (-1: not known), for the
|
|
119
|
+
c: int = -1 # link to the next residue where one of the two is drawn
|
|
120
|
+
#: The rectangles that the ink of its drawn atoms fills, on the page: every atom, and every bond in
|
|
121
|
+
#: two halves. A line that is another residue's does not run across one of them.
|
|
122
|
+
rects: tuple[Box, ...] = ()
|
|
123
|
+
|
|
124
|
+
@property
|
|
125
|
+
def pos(self) -> Point:
|
|
126
|
+
return (self.x, self.y)
|
|
127
|
+
|
|
128
|
+
def part(self, atoms: Sequence[int]) -> str:
|
|
129
|
+
"""Which part of the residue these atoms are: ``backbone`` where all of them are, else the
|
|
130
|
+
``base`` of a nucleotide or the ``side chain`` of an amino acid."""
|
|
131
|
+
if all(a in self.backbone for a in atoms):
|
|
132
|
+
return "backbone"
|
|
133
|
+
return "base" if self.residue_class == "nucleotide" else "side chain"
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
@dataclass
|
|
137
|
+
class Depiction:
|
|
138
|
+
atoms: list[DepAtom]
|
|
139
|
+
bonds: list[DepBond]
|
|
140
|
+
rings: list[tuple[int, ...]]
|
|
141
|
+
n_heavy: int # atoms[:n_heavy] map 1:1 onto Ligand atoms
|
|
142
|
+
metrics: Metrics
|
|
143
|
+
coord_source: str = ""
|
|
144
|
+
notes: list[str] = field(default_factory=list)
|
|
145
|
+
#: The residues of a chain ligand, in chain order; empty for a ligand drawn as atoms.
|
|
146
|
+
units: tuple[DepUnit, ...] = ()
|
|
147
|
+
#: For a chain: does it go on beyond its first and its last unit (see ``Peptide.open_ends``)?
|
|
148
|
+
open_ends: tuple[bool, bool] = (False, False)
|
|
149
|
+
#: One line per pair of residues and kind of contact, instead of one per pair of atoms
|
|
150
|
+
#: (the figure of an interface; see ``Peptide.pairwise``).
|
|
151
|
+
pairwise: bool = False
|
|
152
|
+
#: Are the units of a chain in the order of its sequence (see ``Peptide.sequential``)?
|
|
153
|
+
sequential: bool = True
|
|
154
|
+
#: What the chain is called in a tooltip (see ``Peptide.called``).
|
|
155
|
+
called: str = "the ligand"
|
|
156
|
+
#: How the units of a chain are set out: in a ``column``, or on a ``plane``, each where its residue
|
|
157
|
+
#: lies in space (:mod:`bindview.plane`) ...
|
|
158
|
+
arranged: str = "column"
|
|
159
|
+
#: ... and then what became of that arrangement on the page (:class:`bindview.plane.Placed`).
|
|
160
|
+
plane: Any = None
|
|
161
|
+
_unit_of: dict[int, int] = field(default_factory=dict, repr=False, compare=False)
|
|
162
|
+
_home_of: dict[int, int] = field(default_factory=dict, repr=False, compare=False)
|
|
163
|
+
|
|
164
|
+
def __post_init__(self) -> None:
|
|
165
|
+
self._home_of = {a: u.index for u in self.units for a in u.atoms}
|
|
166
|
+
self._unit_of = {a: k for a, k in self._home_of.items() if a not in self.units[k].beside}
|
|
167
|
+
|
|
168
|
+
# -- lookups -----------------------------------------------------------
|
|
169
|
+
def pos(self, idx: int) -> Point:
|
|
170
|
+
a = self.atoms[idx]
|
|
171
|
+
return (a.x, a.y)
|
|
172
|
+
|
|
173
|
+
def unit_of(self, idx: int) -> DepUnit | None:
|
|
174
|
+
"""The chain residue an atom is drawn as part of (its box stands for it), or ``None``: an atom
|
|
175
|
+
outside the chain, or one that is drawn beside its residue's box as an atom of its own."""
|
|
176
|
+
k = self._unit_of.get(idx)
|
|
177
|
+
return None if k is None else self.units[k]
|
|
178
|
+
|
|
179
|
+
def home_of(self, idx: int) -> DepUnit | None:
|
|
180
|
+
"""The chain residue an atom belongs to, whether its box stands for it or it is drawn beside it."""
|
|
181
|
+
k = self._home_of.get(idx)
|
|
182
|
+
return None if k is None else self.units[k]
|
|
183
|
+
|
|
184
|
+
def unit_for(self, idxs: Sequence[int], whole: bool = False) -> DepUnit | None:
|
|
185
|
+
"""The chain residue whose box these atoms are all drawn as part of, or ``None``.
|
|
186
|
+
|
|
187
|
+
``whole``: the residue they all belong to, whether or not some of them are drawn as atoms
|
|
188
|
+
of their own. A contact without a direction is one with the residue, whatever is drawn of it.
|
|
189
|
+
"""
|
|
190
|
+
table = self._home_of if whole else self._unit_of
|
|
191
|
+
found = {table.get(i) for i in idxs}
|
|
192
|
+
if len(found) != 1:
|
|
193
|
+
return None
|
|
194
|
+
k = found.pop()
|
|
195
|
+
return None if k is None else self.units[k]
|
|
196
|
+
|
|
197
|
+
def landing(self, idxs: Sequence[int]) -> tuple[int, ...]:
|
|
198
|
+
"""The atoms a directional contact that names ``idxs`` lands on: those of them that are drawn
|
|
199
|
+
as atoms of their own, where a residue has some drawn and some not; all of them otherwise."""
|
|
200
|
+
own = tuple(i for i in idxs if i in self._home_of and i not in self._unit_of)
|
|
201
|
+
return own if own and len(own) < len(idxs) and all(i in self._home_of for i in idxs) else tuple(idxs)
|
|
202
|
+
|
|
203
|
+
def centroid(self, idxs: Sequence[int]) -> Point:
|
|
204
|
+
xs = [self.atoms[i].x for i in idxs]
|
|
205
|
+
ys = [self.atoms[i].y for i in idxs]
|
|
206
|
+
return (sum(xs) / len(xs), sum(ys) / len(ys))
|
|
207
|
+
|
|
208
|
+
def neighbours(self, idx: int, covalent_only: bool = True) -> list[int]:
|
|
209
|
+
out = []
|
|
210
|
+
for b in self.bonds:
|
|
211
|
+
if covalent_only and b.kind != "covalent":
|
|
212
|
+
continue
|
|
213
|
+
if b.a == idx:
|
|
214
|
+
out.append(b.b)
|
|
215
|
+
elif b.b == idx:
|
|
216
|
+
out.append(b.a)
|
|
217
|
+
return out
|
|
218
|
+
|
|
219
|
+
def bounds(self) -> Box:
|
|
220
|
+
boxes: list[Box] = []
|
|
221
|
+
for a in self.atoms:
|
|
222
|
+
boxes.append(a.label.box if a.label else (a.x, a.y, a.x, a.y))
|
|
223
|
+
return box_union(boxes)
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def clip_to_labels(pa: Point, pb: Point, la: AtomLabel | None, lb: AtomLabel | None,
|
|
227
|
+
gap: float) -> tuple[Point, Point] | None:
|
|
228
|
+
"""Shorten segment ``pa->pb`` so it stops short of the labels at either end."""
|
|
229
|
+
a, b = pa, pb
|
|
230
|
+
if la is not None:
|
|
231
|
+
a = _enter(pb, pa, la, gap)
|
|
232
|
+
if lb is not None:
|
|
233
|
+
b = _enter(pa, pb, lb, gap)
|
|
234
|
+
# Still pointing the same way and of positive length?
|
|
235
|
+
if (b[0] - a[0]) * (pb[0] - pa[0]) + (b[1] - a[1]) * (pb[1] - pa[1]) <= 1e-6:
|
|
236
|
+
return None
|
|
237
|
+
return a, b
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def _enter(outside: Point, centre: Point, label: AtomLabel, gap: float) -> Point:
|
|
241
|
+
"""First point where ``outside->centre`` meets any (padded) box of ``label``."""
|
|
242
|
+
best: Point = centre
|
|
243
|
+
best_d = float("inf")
|
|
244
|
+
for box in label.boxes:
|
|
245
|
+
hit = segment_box_entry(outside, centre, box_expand(box, gap))
|
|
246
|
+
if hit == centre and not _contains(box_expand(box, gap), centre):
|
|
247
|
+
continue # segment misses this box entirely
|
|
248
|
+
d = math.hypot(hit[0] - outside[0], hit[1] - outside[1])
|
|
249
|
+
if d < best_d:
|
|
250
|
+
best_d, best = d, hit
|
|
251
|
+
return best
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def _contains(box: Box, p: Point) -> bool:
|
|
255
|
+
return box[0] <= p[0] <= box[2] and box[1] <= p[1] <= box[3]
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
# ---------------------------------------------------------------------------
|
|
259
|
+
# Coordinates
|
|
260
|
+
# ---------------------------------------------------------------------------
|
|
261
|
+
|
|
262
|
+
def layout_score(mol: Chem.Mol, xy: np.ndarray) -> tuple[int, int]:
|
|
263
|
+
"""``(atom clashes, bond crossings)`` of a 2D layout with unit bond length."""
|
|
264
|
+
n = mol.GetNumAtoms()
|
|
265
|
+
if n < 3:
|
|
266
|
+
return (0, 0)
|
|
267
|
+
d = np.linalg.norm(xy[:, None, :] - xy[None, :, :], axis=2)
|
|
268
|
+
clashes = int(((d < 0.45) & ~np.eye(n, dtype=bool)).sum() // 2)
|
|
269
|
+
segs = [(b.GetBeginAtomIdx(), b.GetEndAtomIdx()) for b in mol.GetBonds()]
|
|
270
|
+
crossings = 0
|
|
271
|
+
for i in range(len(segs)):
|
|
272
|
+
a, b = segs[i]
|
|
273
|
+
pa, pb = (xy[a, 0], xy[a, 1]), (xy[b, 0], xy[b, 1])
|
|
274
|
+
for j in range(i + 1, len(segs)):
|
|
275
|
+
c, e = segs[j]
|
|
276
|
+
if a in (c, e) or b in (c, e):
|
|
277
|
+
continue
|
|
278
|
+
if segments_intersect(pa, pb, (xy[c, 0], xy[c, 1]), (xy[e, 0], xy[e, 1])):
|
|
279
|
+
crossings += 1
|
|
280
|
+
return (clashes, crossings)
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def _conf_xy(mol: Chem.Mol) -> np.ndarray:
|
|
284
|
+
conf = mol.GetConformer()
|
|
285
|
+
return np.array([[conf.GetAtomPosition(i).x, conf.GetAtomPosition(i).y] for i in range(mol.GetNumAtoms())])
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
def _normalise(mol: Chem.Mol, xy: np.ndarray) -> np.ndarray:
|
|
289
|
+
lengths = [float(np.linalg.norm(xy[b.GetBeginAtomIdx()] - xy[b.GetEndAtomIdx()])) for b in mol.GetBonds()]
|
|
290
|
+
scale = float(np.median(lengths)) if lengths else 1.0
|
|
291
|
+
return xy / scale if scale > 1e-9 else xy
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
def _coordgen(mol: Chem.Mol) -> np.ndarray:
|
|
295
|
+
m = Chem.Mol(mol)
|
|
296
|
+
m.RemoveAllConformers()
|
|
297
|
+
rdCoordGen.AddCoords(m)
|
|
298
|
+
return _normalise(m, _conf_xy(m))
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
def _rdkit_coords(mol: Chem.Mol) -> np.ndarray:
|
|
302
|
+
m = Chem.Mol(mol)
|
|
303
|
+
m.RemoveAllConformers()
|
|
304
|
+
prefer = rdDepictor.GetPreferCoordGen()
|
|
305
|
+
rdDepictor.SetPreferCoordGen(False)
|
|
306
|
+
try:
|
|
307
|
+
rdDepictor.Compute2DCoords(m, canonOrient=True)
|
|
308
|
+
finally:
|
|
309
|
+
rdDepictor.SetPreferCoordGen(prefer)
|
|
310
|
+
return _normalise(m, _conf_xy(m))
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
def _choose_coords(mol: Chem.Mol, method: str, notes: list[str]) -> tuple[np.ndarray, str]:
|
|
314
|
+
n = mol.GetNumAtoms()
|
|
315
|
+
if n == 1:
|
|
316
|
+
return np.zeros((1, 2)), "trivial"
|
|
317
|
+
if method == "rdkit":
|
|
318
|
+
return _rdkit_coords(mol), "rdkit"
|
|
319
|
+
try:
|
|
320
|
+
cg = _coordgen(mol)
|
|
321
|
+
cg_score = layout_score(mol, cg)
|
|
322
|
+
except Exception: # pragma: no cover - CoordGen is robust; keep a net anyway
|
|
323
|
+
cg, cg_score = None, (10**6, 10**6)
|
|
324
|
+
if method == "coordgen" and cg is not None:
|
|
325
|
+
return cg, "coordgen"
|
|
326
|
+
if cg is not None and cg_score == (0, 0):
|
|
327
|
+
return cg, "coordgen"
|
|
328
|
+
rd = _rdkit_coords(mol)
|
|
329
|
+
rd_score = layout_score(mol, rd)
|
|
330
|
+
if cg is None or rd_score < cg_score:
|
|
331
|
+
if rd_score != (0, 0):
|
|
332
|
+
notes.append(f"ligand 2D layout has {rd_score[0]} atom clash(es) and {rd_score[1]} bond crossing(s)")
|
|
333
|
+
return rd, "rdkit"
|
|
334
|
+
notes.append(f"ligand 2D layout has {cg_score[0]} atom clash(es) and {cg_score[1]} bond crossing(s)")
|
|
335
|
+
return cg, "coordgen"
|
|
336
|
+
|
|
337
|
+
|
|
338
|
+
def _orient_landscape(xy: np.ndarray) -> np.ndarray:
|
|
339
|
+
"""Rotate by a multiple of 30 degrees so the drawing is wider than tall.
|
|
340
|
+
|
|
341
|
+
Multiples of 30 keep bonds on the usual drawing grid, and the orientation
|
|
342
|
+
CoordGen chose (often a textbook one) is kept unless turning it shrinks the
|
|
343
|
+
height noticeably.
|
|
344
|
+
"""
|
|
345
|
+
if len(xy) < 3:
|
|
346
|
+
return xy
|
|
347
|
+
best_k, best_h = 0, None
|
|
348
|
+
heights = []
|
|
349
|
+
for k in range(6):
|
|
350
|
+
ang = math.radians(30.0 * k)
|
|
351
|
+
c, s = math.cos(ang), math.sin(ang)
|
|
352
|
+
y = xy[:, 0] * s + xy[:, 1] * c
|
|
353
|
+
heights.append(float(y.max() - y.min()))
|
|
354
|
+
best_h = min(heights)
|
|
355
|
+
if heights[0] <= best_h * 1.12 + 1e-9:
|
|
356
|
+
best_k = 0
|
|
357
|
+
else:
|
|
358
|
+
best_k = min(range(6), key=lambda k: (round(heights[k], 6), min(k, 6 - k)))
|
|
359
|
+
if best_k == 0:
|
|
360
|
+
return xy
|
|
361
|
+
# Prefer the smaller of the two equivalent turns (k*30 or k*30-180).
|
|
362
|
+
ang = math.radians(30.0 * best_k if best_k <= 3 else 30.0 * best_k - 180.0)
|
|
363
|
+
c, s = math.cos(ang), math.sin(ang)
|
|
364
|
+
return np.column_stack([xy[:, 0] * c - xy[:, 1] * s, xy[:, 0] * s + xy[:, 1] * c])
|
|
365
|
+
|
|
366
|
+
|
|
367
|
+
def _place_fragments(mol: Chem.Mol, xy: np.ndarray, coordination: Sequence[tuple[int, int]],
|
|
368
|
+
names: Sequence[str], notes: list[str], bridging: Sequence[int] = ()
|
|
369
|
+
) -> tuple[np.ndarray, list[tuple[int, int]]]:
|
|
370
|
+
"""Seat coordinated metals among their donors; move loose fragments clear. An ion between the ligand and the
|
|
371
|
+
protein (``bridging``) is seated outside the ligand, beside the donors that hold it."""
|
|
372
|
+
frags = [tuple(f) for f in Chem.GetMolFrags(mol)]
|
|
373
|
+
drawn: list[tuple[int, int]] = []
|
|
374
|
+
if len(frags) < 2:
|
|
375
|
+
return xy, drawn
|
|
376
|
+
xy = xy.copy()
|
|
377
|
+
main = max(frags, key=lambda f: (len(f), -min(f)))
|
|
378
|
+
others = sorted((f for f in frags if f != main), key=min)
|
|
379
|
+
donors_of: dict[int, list[int]] = {}
|
|
380
|
+
for metal, donor in coordination:
|
|
381
|
+
donors_of.setdefault(metal, []).append(donor)
|
|
382
|
+
|
|
383
|
+
main_idx = np.array(sorted(main))
|
|
384
|
+
for m_idx in (b for b in bridging if b in donors_of):
|
|
385
|
+
donors = sorted(donors_of[m_idx])
|
|
386
|
+
placed = {k for k, _ in drawn}
|
|
387
|
+
near_to = np.array([i for i in range(len(xy)) if i in main or (i in placed and i != m_idx)])
|
|
388
|
+
best: "tuple[float, np.ndarray] | None" = None
|
|
389
|
+
for d in donors:
|
|
390
|
+
for k in range(24):
|
|
391
|
+
ang = math.radians(15.0 * k)
|
|
392
|
+
spot = xy[d] + 1.35 * np.array([math.cos(ang), math.sin(ang)])
|
|
393
|
+
if float(np.linalg.norm(xy[near_to] - spot, axis=1).min()) < 1.0:
|
|
394
|
+
continue
|
|
395
|
+
# Near to every donor that holds it, and away from everything else.
|
|
396
|
+
far = sum(abs(float(np.linalg.norm(xy[e] - spot)) - 1.35) for e in donors)
|
|
397
|
+
away = [int(i) for i in near_to if i not in donors]
|
|
398
|
+
clear = float(np.linalg.norm(xy[away] - spot, axis=1).min()) if away else 9.0
|
|
399
|
+
cost = round(far - 0.5 * min(clear, 2.5), 6)
|
|
400
|
+
if best is None or cost < best[0]:
|
|
401
|
+
best = (cost, spot)
|
|
402
|
+
if best is None:
|
|
403
|
+
continue
|
|
404
|
+
xy[m_idx] = best[1]
|
|
405
|
+
others = [f for f in others if f != (m_idx,)]
|
|
406
|
+
drawn.extend((m_idx, d) for d in donors if float(np.linalg.norm(xy[d] - best[1])) <= 2.6)
|
|
407
|
+
seated: list[int] = []
|
|
408
|
+
loose: list[tuple[int, ...]] = []
|
|
409
|
+
for frag in others:
|
|
410
|
+
done = False
|
|
411
|
+
if len(frag) == 1 and is_metal(mol.GetAtomWithIdx(frag[0]).GetSymbol()) and frag[0] in donors_of:
|
|
412
|
+
m_idx = frag[0]
|
|
413
|
+
donors = sorted(donors_of[m_idx])
|
|
414
|
+
pts = xy[donors]
|
|
415
|
+
keep = list(range(len(donors)))
|
|
416
|
+
for _ in range(4):
|
|
417
|
+
centre = np.median(pts[keep], axis=0)
|
|
418
|
+
near = [k for k in range(len(donors)) if np.linalg.norm(pts[k] - centre) <= 2.6]
|
|
419
|
+
if len(near) < 2 or near == keep:
|
|
420
|
+
keep = near if len(near) >= 2 else keep
|
|
421
|
+
break
|
|
422
|
+
keep = near
|
|
423
|
+
if len(keep) >= 2:
|
|
424
|
+
centre = pts[keep].mean(axis=0)
|
|
425
|
+
# Only the covalent skeleton and metals already seated can block the seat;
|
|
426
|
+
# loose fragments are moved out of the way afterwards.
|
|
427
|
+
block = np.concatenate([main_idx, np.array(seated, dtype=int)])
|
|
428
|
+
if float(np.linalg.norm(xy[block] - centre, axis=1).min()) >= 0.75:
|
|
429
|
+
xy[m_idx] = centre
|
|
430
|
+
seated.append(m_idx)
|
|
431
|
+
done = True
|
|
432
|
+
for k, d in enumerate(donors):
|
|
433
|
+
if k in keep:
|
|
434
|
+
drawn.append((m_idx, d))
|
|
435
|
+
else:
|
|
436
|
+
notes.append(
|
|
437
|
+
f"coordination {names[m_idx]}\u2013{names[d]} is not drawn: the two atoms are "
|
|
438
|
+
f"far apart in the 2D layout")
|
|
439
|
+
if not done:
|
|
440
|
+
loose.append(frag)
|
|
441
|
+
|
|
442
|
+
for frag in loose:
|
|
443
|
+
fa = np.array(frag)
|
|
444
|
+
rest = np.array([i for i in range(len(xy)) if i not in frag])
|
|
445
|
+
d = np.linalg.norm(xy[fa][:, None, :] - xy[rest][None, :, :], axis=2)
|
|
446
|
+
if d.min() >= 1.6:
|
|
447
|
+
continue
|
|
448
|
+
# Park it to the right of everything else, level with the main fragment.
|
|
449
|
+
right = float(xy[rest][:, 0].max())
|
|
450
|
+
mid_y = float(xy[list(main)][:, 1].mean())
|
|
451
|
+
cur = xy[fa]
|
|
452
|
+
shift = np.array([right + 2.0 - float(cur[:, 0].min()), mid_y - float(cur[:, 1].mean())])
|
|
453
|
+
xy[fa] = cur + shift
|
|
454
|
+
return xy, drawn
|
|
455
|
+
|
|
456
|
+
|
|
457
|
+
# ---------------------------------------------------------------------------
|
|
458
|
+
# Labels
|
|
459
|
+
# ---------------------------------------------------------------------------
|
|
460
|
+
|
|
461
|
+
def _needs_label(element: str, degree: int, charge: int, isotope: int) -> bool:
|
|
462
|
+
if element != "C":
|
|
463
|
+
return True
|
|
464
|
+
return degree == 0 or charge != 0 or isotope != 0
|
|
465
|
+
|
|
466
|
+
|
|
467
|
+
def _charge_text(charge: int) -> str:
|
|
468
|
+
sign = "+" if charge > 0 else _MINUS
|
|
469
|
+
return (str(abs(charge)) if abs(charge) > 1 else "") + sign
|
|
470
|
+
|
|
471
|
+
|
|
472
|
+
def _h_side(pos: Point, nbrs: Sequence[Point]) -> str:
|
|
473
|
+
"""Where the hydrogens of a label go: E, W, N or S (N is up on the page)."""
|
|
474
|
+
if not nbrs:
|
|
475
|
+
return "E"
|
|
476
|
+
vecs = []
|
|
477
|
+
for q in nbrs:
|
|
478
|
+
dx, dy = q[0] - pos[0], q[1] - pos[1]
|
|
479
|
+
n = math.hypot(dx, dy)
|
|
480
|
+
if n > 1e-9:
|
|
481
|
+
vecs.append((dx / n, dy / n))
|
|
482
|
+
if not vecs:
|
|
483
|
+
return "E"
|
|
484
|
+
if len(vecs) == 1:
|
|
485
|
+
return "W" if vecs[0][0] > 0.2 else "E"
|
|
486
|
+
best, best_score = "E", -2.0
|
|
487
|
+
# y grows downward, so "N" (up) is the direction (0, -1).
|
|
488
|
+
for side, d in (("E", (1.0, 0.0)), ("W", (-1.0, 0.0)), ("S", (0.0, 1.0)), ("N", (0.0, -1.0))):
|
|
489
|
+
score = min(1.0 - (d[0] * v[0] + d[1] * v[1]) for v in vecs) # 0 = on a bond, 2 = opposite
|
|
490
|
+
if score > best_score + 0.05:
|
|
491
|
+
best, best_score = side, score
|
|
492
|
+
return best
|
|
493
|
+
|
|
494
|
+
|
|
495
|
+
def make_label(pos: Point, element: str, hcount: int, charge: int, isotope: int, nbrs: Sequence[Point],
|
|
496
|
+
font: float, sub_font: float, charge_font: float) -> AtomLabel:
|
|
497
|
+
"""Lay out an atom label: symbol centred on the atom, hydrogens to the free side."""
|
|
498
|
+
x, y = pos
|
|
499
|
+
cap = CAP_HEIGHT * font
|
|
500
|
+
base = y + cap / 2.0
|
|
501
|
+
ws = text_width(element, font)
|
|
502
|
+
desc = DESCENT * font * 0.8 if any(ch in "gjpqy" for ch in element) else 0.0
|
|
503
|
+
runs: list[LabelRun] = [LabelRun(x, base, "middle", (Span(element),),
|
|
504
|
+
(x - ws / 2.0, y - cap / 2.0, x + ws / 2.0, y + cap / 2.0 + desc))]
|
|
505
|
+
side = _h_side(pos, nbrs) if hcount > 0 else "E"
|
|
506
|
+
sub_drop = 0.26 * font
|
|
507
|
+
sup_rise = 0.46 * font
|
|
508
|
+
|
|
509
|
+
def h_spans() -> tuple[list[Span], float, float]:
|
|
510
|
+
"""Spans for 'H' plus count; returns (spans, width, extra depth below baseline)."""
|
|
511
|
+
spans = [Span("H")]
|
|
512
|
+
width = text_width("H", font)
|
|
513
|
+
depth = 0.0
|
|
514
|
+
if hcount > 1:
|
|
515
|
+
cnt = str(hcount)
|
|
516
|
+
spans.append(Span(cnt, size=sub_font, dy=sub_drop))
|
|
517
|
+
spans.append(Span("", dy=-sub_drop)) # restore the baseline
|
|
518
|
+
width += text_width(cnt, sub_font)
|
|
519
|
+
depth = sub_drop
|
|
520
|
+
return spans, width, depth
|
|
521
|
+
|
|
522
|
+
charge_spans: list[Span] = []
|
|
523
|
+
charge_w = 0.0
|
|
524
|
+
if charge:
|
|
525
|
+
txt = _charge_text(charge)
|
|
526
|
+
charge_spans = [Span(txt, size=charge_font, dy=-sup_rise), Span("", dy=sup_rise)]
|
|
527
|
+
charge_w = text_width(txt, charge_font)
|
|
528
|
+
top_with_charge = y - cap / 2.0 - (sup_rise + CAP_HEIGHT * charge_font - cap if charge else 0.0)
|
|
529
|
+
top_with_charge = min(top_with_charge, y - cap / 2.0)
|
|
530
|
+
pad = 0.6
|
|
531
|
+
|
|
532
|
+
if isotope:
|
|
533
|
+
iso = str(isotope)
|
|
534
|
+
wi = text_width(iso, charge_font)
|
|
535
|
+
runs.append(LabelRun(x - ws / 2.0 - pad, base, "end",
|
|
536
|
+
(Span(iso, size=charge_font, dy=-sup_rise), Span("", dy=sup_rise)),
|
|
537
|
+
(x - ws / 2.0 - pad - wi, y - cap / 2.0 - sup_rise * 0.4, x - ws / 2.0 - pad, y)))
|
|
538
|
+
|
|
539
|
+
right: list[Span] = []
|
|
540
|
+
right_w, right_depth = 0.0, 0.0
|
|
541
|
+
left: list[Span] = []
|
|
542
|
+
left_w, left_depth = 0.0, 0.0
|
|
543
|
+
if hcount > 0 and side == "E":
|
|
544
|
+
hs, hw, hd = h_spans()
|
|
545
|
+
right, right_w, right_depth = hs + charge_spans, hw + charge_w, hd
|
|
546
|
+
elif hcount > 0 and side == "W":
|
|
547
|
+
hs, hw, hd = h_spans()
|
|
548
|
+
left, left_w, left_depth = hs, hw, hd
|
|
549
|
+
right, right_w = charge_spans, charge_w
|
|
550
|
+
elif hcount > 0: # N or S: hydrogens stacked above / below
|
|
551
|
+
hs, hw, hd = h_spans()
|
|
552
|
+
gap = 2.2
|
|
553
|
+
if side == "S":
|
|
554
|
+
hb = base + cap + gap
|
|
555
|
+
else:
|
|
556
|
+
hb = base - cap - gap - hd
|
|
557
|
+
runs.append(LabelRun(x, hb, "middle", tuple(hs),
|
|
558
|
+
(x - hw / 2.0, hb - cap, x + hw / 2.0, hb + hd)))
|
|
559
|
+
right, right_w = charge_spans, charge_w
|
|
560
|
+
elif charge:
|
|
561
|
+
only_right = [p for p in nbrs if p[0] - x > 0.2 * math.hypot(p[0] - x, p[1] - y)]
|
|
562
|
+
if len(nbrs) == 1 and only_right:
|
|
563
|
+
left, left_w = charge_spans, charge_w # e.g. "-O" when the bond leaves to the right
|
|
564
|
+
else:
|
|
565
|
+
right, right_w = charge_spans, charge_w
|
|
566
|
+
|
|
567
|
+
if right:
|
|
568
|
+
x0 = x + ws / 2.0 + pad
|
|
569
|
+
has_charge = bool(charge) and any(s.dy < 0 for s in right)
|
|
570
|
+
top = top_with_charge if has_charge else y - cap / 2.0
|
|
571
|
+
runs.append(LabelRun(x0, base, "start", tuple(right),
|
|
572
|
+
(x0, top, x0 + right_w, y + cap / 2.0 + right_depth)))
|
|
573
|
+
if left:
|
|
574
|
+
x1 = x - ws / 2.0 - pad - (text_width(str(isotope), charge_font) + pad if isotope else 0.0)
|
|
575
|
+
has_charge = bool(charge) and any(s.dy < 0 for s in left)
|
|
576
|
+
top = top_with_charge if has_charge else y - cap / 2.0
|
|
577
|
+
runs.append(LabelRun(x1, base, "end", tuple(left),
|
|
578
|
+
(x1 - left_w, top, x1, y + cap / 2.0 + left_depth)))
|
|
579
|
+
return AtomLabel(tuple(runs), box_union(r.box for r in runs))
|
|
580
|
+
|
|
581
|
+
|
|
582
|
+
# ---------------------------------------------------------------------------
|
|
583
|
+
# The depiction
|
|
584
|
+
# ---------------------------------------------------------------------------
|
|
585
|
+
|
|
586
|
+
def depict_ligand(lig: Ligand, metrics: Metrics, method: str = "auto",
|
|
587
|
+
coords: dict[str, tuple[float, float]] | None = None, normalise: bool = True,
|
|
588
|
+
exact: "dict[str, tuple[float, float]] | None" = None,
|
|
589
|
+
coordination: "Sequence[tuple[str, str]] | None" = None) -> Depiction:
|
|
590
|
+
"""Compute the drawable geometry of a ligand.
|
|
591
|
+
|
|
592
|
+
``method`` is ``"auto"`` (CoordGen unless it yields clashes), ``"coordgen"``
|
|
593
|
+
or ``"rdkit"``. ``coords`` overrides it with caller-supplied 2D positions
|
|
594
|
+
keyed by atom name (any scale and orientation; y up). With
|
|
595
|
+
``normalise=False`` those positions are taken as they are, in units of one
|
|
596
|
+
bond length: this is how several ligands are drawn in one common frame,
|
|
597
|
+
where rescaling each by its own median bond would move shared atoms apart.
|
|
598
|
+
|
|
599
|
+
``exact`` and ``coordination`` exist to redraw a stored layout to the last
|
|
600
|
+
digit. ``exact`` gives final drawing positions (user units, y down) by atom
|
|
601
|
+
name -- and ``"H@<name>"`` for a hydrogen the drawing adds on that atom --
|
|
602
|
+
which replace the computed ones before labels are set. ``coordination``
|
|
603
|
+
names the metal-donor pairs to draw, in order, instead of all of them.
|
|
604
|
+
"""
|
|
605
|
+
with quiet_rdkit():
|
|
606
|
+
return _depict(lig, metrics, method, coords, normalise, exact, coordination)
|
|
607
|
+
|
|
608
|
+
|
|
609
|
+
def atom_keys(dep: "Depiction") -> list[str]:
|
|
610
|
+
"""A stable key for every depicted atom: its structure-file name, or ``H@<name>`` for a
|
|
611
|
+
hydrogen that exists only in the drawing (on the atom it is bonded to)."""
|
|
612
|
+
keys: list[str] = []
|
|
613
|
+
seen: dict[str, int] = {}
|
|
614
|
+
for atom in dep.atoms:
|
|
615
|
+
if atom.name:
|
|
616
|
+
key = atom.name
|
|
617
|
+
else:
|
|
618
|
+
nbrs = dep.neighbours(atom.idx)
|
|
619
|
+
key = "H@" + (dep.atoms[nbrs[0]].name or "?" if nbrs else "?")
|
|
620
|
+
seen[key] = seen.get(key, 0) + 1
|
|
621
|
+
keys.append(key if seen[key] == 1 else f"{key}#{seen[key]}")
|
|
622
|
+
return keys
|
|
623
|
+
|
|
624
|
+
|
|
625
|
+
def _part_added_hydrogens(dep: Depiction, placed: "set[int]") -> None:
|
|
626
|
+
"""Part two hydrogens of stereocentres that the drawing puts on one another.
|
|
627
|
+
|
|
628
|
+
RDKit sets a hydrogen it adds at a stereocentre on the bisector of its atom's free angle. At two
|
|
629
|
+
neighbouring ring fusions (C8 and C14 of a steroid) the two free angles open into one corner and the
|
|
630
|
+
two bisectors end in one point: H on H. Where two such hydrogens are closer than half a bond, each
|
|
631
|
+
turns within its own free angle, keeping clear of its atom's bonds, to where the two, and each of them
|
|
632
|
+
from every other atom, are farthest apart. A hydrogen stays between the same two neighbours, so its
|
|
633
|
+
wedge says what it said. Hydrogens nowhere near another are left where RDKit put them."""
|
|
634
|
+
bl = dep.metrics.bond_length
|
|
635
|
+
added = [a.idx for a in dep.atoms[dep.n_heavy:] if a.element == "H" and a.idx not in placed
|
|
636
|
+
and len(dep.neighbours(a.idx)) == 1]
|
|
637
|
+
margin = math.radians(30.0)
|
|
638
|
+
|
|
639
|
+
def choices(h: int) -> list[Point]:
|
|
640
|
+
(p,) = dep.neighbours(h)
|
|
641
|
+
px, py = dep.pos(p)
|
|
642
|
+
hx, hy = dep.pos(h)
|
|
643
|
+
r = math.hypot(hx - px, hy - py)
|
|
644
|
+
here = math.atan2(hy - py, hx - px)
|
|
645
|
+
others = sorted((math.atan2(dep.atoms[j].y - py, dep.atoms[j].x - px) - here) % math.tau
|
|
646
|
+
for j in dep.neighbours(p) if j != h)
|
|
647
|
+
if not others:
|
|
648
|
+
return [(hx, hy)]
|
|
649
|
+
lo, hi = others[-1] - math.tau, others[0] # the free angle the hydrogen stands in, around 0
|
|
650
|
+
if hi - lo <= 2 * margin:
|
|
651
|
+
return [(hx, hy)]
|
|
652
|
+
steps = 24
|
|
653
|
+
turns = [lo + margin + (hi - lo - 2 * margin) * k / steps for k in range(steps + 1)]
|
|
654
|
+
return [(px + r * math.cos(here + t), py + r * math.sin(here + t)) for t in turns]
|
|
655
|
+
|
|
656
|
+
for i, h in enumerate(added):
|
|
657
|
+
for k in added[i + 1:]:
|
|
658
|
+
if math.dist(dep.pos(h), dep.pos(k)) >= 0.5 * bl:
|
|
659
|
+
continue
|
|
660
|
+
fixed = {h, k, *dep.neighbours(h), *dep.neighbours(k)}
|
|
661
|
+
rest = [a.pos for a in dep.atoms if a.idx not in fixed]
|
|
662
|
+
|
|
663
|
+
def clear(q: Point) -> float:
|
|
664
|
+
return min((math.dist(q, o) for o in rest), default=math.inf)
|
|
665
|
+
|
|
666
|
+
# the nearest of: the two hydrogens to each other, either to any other atom; the least turn on a
|
|
667
|
+
# tie; and never their two bonds across one another
|
|
668
|
+
ph, pk = dep.pos(dep.neighbours(h)[0]), dep.pos(dep.neighbours(k)[0])
|
|
669
|
+
ways = [(round(min(math.dist(a, b), clear(a), clear(b)), 6),
|
|
670
|
+
-(math.dist(a, dep.pos(h)) + math.dist(b, dep.pos(k))), a, b)
|
|
671
|
+
for a in choices(h) for b in choices(k) if not segments_intersect(ph, a, pk, b)]
|
|
672
|
+
if ways:
|
|
673
|
+
_, _, a, b = max(ways, key=lambda c: (c[0], c[1]))
|
|
674
|
+
(dep.atoms[h].x, dep.atoms[h].y), (dep.atoms[k].x, dep.atoms[k].y) = a, b
|
|
675
|
+
|
|
676
|
+
|
|
677
|
+
def _load_rdkit_drawing() -> Any:
|
|
678
|
+
from rdkit.Chem.Draw import rdMolDraw2D
|
|
679
|
+
|
|
680
|
+
return rdMolDraw2D
|
|
681
|
+
|
|
682
|
+
|
|
683
|
+
def _rdkit_drawing() -> Any:
|
|
684
|
+
"""RDKit's drawing module, loaded when a ligand is drawn and not with the package. RDKit's wheel links that
|
|
685
|
+
one module against the system libraries libXrender and libexpat, which a minimal container image does not
|
|
686
|
+
have: loaded with the package, it kept ``import bindview`` itself from working there."""
|
|
687
|
+
try:
|
|
688
|
+
return _load_rdkit_drawing()
|
|
689
|
+
except ImportError as exc:
|
|
690
|
+
raise BindviewError(
|
|
691
|
+
f"RDKit's drawing module, which sets the wedges and the double bonds of a ligand, cannot be loaded: "
|
|
692
|
+
f"{exc}. On Linux it needs the system libraries libXrender and libexpat, which a minimal container "
|
|
693
|
+
f"image leaves out (Debian and Ubuntu: apt-get install libxrender1 libexpat1)") from exc
|
|
694
|
+
|
|
695
|
+
|
|
696
|
+
def _depict(lig: Ligand, metrics: Metrics, method: str,
|
|
697
|
+
coords: dict[str, tuple[float, float]] | None, normalise: bool = True,
|
|
698
|
+
exact: "dict[str, tuple[float, float]] | None" = None,
|
|
699
|
+
coordination: "Sequence[tuple[str, str]] | None" = None) -> Depiction:
|
|
700
|
+
notes: list[str] = []
|
|
701
|
+
mol = Chem.Mol(lig.mol)
|
|
702
|
+
n = mol.GetNumAtoms()
|
|
703
|
+
|
|
704
|
+
if coords is not None:
|
|
705
|
+
missing = [nm for nm in lig.names if nm not in coords]
|
|
706
|
+
if missing:
|
|
707
|
+
raise ValueError(f"supplied 2D coordinates lack atoms: {', '.join(missing[:6])}")
|
|
708
|
+
xy = np.array([coords[nm] for nm in lig.names], dtype=float).reshape(-1, 2)
|
|
709
|
+
if normalise:
|
|
710
|
+
xy = _normalise(mol, xy)
|
|
711
|
+
source = "supplied"
|
|
712
|
+
drawn_coord = [(m, d) for m, d in lig.coordination]
|
|
713
|
+
if coordination is not None:
|
|
714
|
+
index = {name: i for i, name in enumerate(lig.names)}
|
|
715
|
+
drawn_coord = [(index[a], index[b]) for a, b in coordination if a in index and b in index]
|
|
716
|
+
else:
|
|
717
|
+
xy, source = _choose_coords(mol, method, notes)
|
|
718
|
+
xy = _orient_landscape(xy)
|
|
719
|
+
xy, drawn_coord = _place_fragments(mol, xy, lig.coordination, lig.names, notes, lig.bridging)
|
|
720
|
+
|
|
721
|
+
# Hand RDKit the final (y-up) coordinates and let it kekulize, add the
|
|
722
|
+
# hydrogens that stereo at ring fusions needs, and choose the wedges.
|
|
723
|
+
mol.RemoveAllConformers()
|
|
724
|
+
conf = Chem.Conformer(n)
|
|
725
|
+
for i in range(n):
|
|
726
|
+
conf.SetAtomPosition(i, Point3D(float(xy[i, 0]), float(xy[i, 1]), 0.0))
|
|
727
|
+
conf.Set3D(False)
|
|
728
|
+
mol.AddConformer(conf, assignId=True)
|
|
729
|
+
kekulized = True
|
|
730
|
+
draw = Chem.Mol(mol)
|
|
731
|
+
has_stereo = lig.bond_source in ("template", "geometry")
|
|
732
|
+
drawing = _rdkit_drawing()
|
|
733
|
+
try:
|
|
734
|
+
draw = drawing.PrepareMolForDrawing(mol, kekulize=True, addChiralHs=has_stereo,
|
|
735
|
+
wedgeBonds=has_stereo, forceCoords=False)
|
|
736
|
+
except Exception:
|
|
737
|
+
kekulized = False
|
|
738
|
+
try:
|
|
739
|
+
draw = drawing.PrepareMolForDrawing(mol, kekulize=False, addChiralHs=has_stereo,
|
|
740
|
+
wedgeBonds=has_stereo, forceCoords=False)
|
|
741
|
+
except Exception:
|
|
742
|
+
draw = Chem.Mol(mol)
|
|
743
|
+
notes.append("stereo wedges could not be assigned")
|
|
744
|
+
notes.append("the ligand could not be kekulized; aromatic bonds are drawn dashed")
|
|
745
|
+
|
|
746
|
+
bl = metrics.bond_length
|
|
747
|
+
dconf = draw.GetConformer()
|
|
748
|
+
atoms: list[DepAtom] = []
|
|
749
|
+
for a in draw.GetAtoms():
|
|
750
|
+
i = a.GetIdx()
|
|
751
|
+
p = dconf.GetAtomPosition(i)
|
|
752
|
+
atoms.append(DepAtom(
|
|
753
|
+
idx=i, x=float(p.x) * bl, y=-float(p.y) * bl, element=a.GetSymbol(),
|
|
754
|
+
name=lig.names[i] if i < n else None,
|
|
755
|
+
hcount=a.GetTotalNumHs(), charge=a.GetFormalCharge(), isotope=a.GetIsotope(),
|
|
756
|
+
aromatic=a.GetIsAromatic(),
|
|
757
|
+
))
|
|
758
|
+
|
|
759
|
+
bonds: list[DepBond] = []
|
|
760
|
+
for b in draw.GetBonds():
|
|
761
|
+
order = int(round(b.GetBondTypeAsDouble())) if not b.GetIsAromatic() or kekulized else 1
|
|
762
|
+
order = max(1, min(3, order))
|
|
763
|
+
stereo = "none"
|
|
764
|
+
d = b.GetBondDir()
|
|
765
|
+
if d == Chem.BondDir.BEGINWEDGE:
|
|
766
|
+
stereo = "wedge"
|
|
767
|
+
elif d == Chem.BondDir.BEGINDASH:
|
|
768
|
+
stereo = "hash"
|
|
769
|
+
bonds.append(DepBond(b.GetBeginAtomIdx(), b.GetEndAtomIdx(), order, stereo,
|
|
770
|
+
aromatic=(b.GetIsAromatic() and not kekulized)))
|
|
771
|
+
for metal, donor in drawn_coord:
|
|
772
|
+
bonds.append(DepBond(metal, donor, 1, kind="coordination"))
|
|
773
|
+
|
|
774
|
+
dep = Depiction(atoms=atoms, bonds=bonds, rings=[tuple(r) for r in draw.GetRingInfo().AtomRings()],
|
|
775
|
+
n_heavy=n, metrics=metrics, coord_source=source, notes=notes)
|
|
776
|
+
placed: set[int] = set()
|
|
777
|
+
if exact:
|
|
778
|
+
for atom, key in zip(atoms, atom_keys(dep)):
|
|
779
|
+
if key in exact:
|
|
780
|
+
atom.x, atom.y = float(exact[key][0]), float(exact[key][1])
|
|
781
|
+
placed.add(atom.idx)
|
|
782
|
+
_part_added_hydrogens(dep, placed)
|
|
783
|
+
|
|
784
|
+
for atom in atoms:
|
|
785
|
+
degree = len(dep.neighbours(atom.idx))
|
|
786
|
+
if _needs_label(atom.element, degree, atom.charge, atom.isotope):
|
|
787
|
+
nbrs = [dep.pos(j) for j in dep.neighbours(atom.idx, covalent_only=False)]
|
|
788
|
+
atom.label = make_label(atom.pos, atom.element, atom.hcount, atom.charge, atom.isotope, nbrs,
|
|
789
|
+
metrics.atom_font, metrics.sub_font, metrics.charge_font)
|
|
790
|
+
return dep
|