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.
Files changed (70) hide show
  1. bindview/__init__.py +88 -0
  2. bindview/__main__.py +6 -0
  3. bindview/align.py +493 -0
  4. bindview/arrange.js +347 -0
  5. bindview/arrange.py +248 -0
  6. bindview/backends.py +290 -0
  7. bindview/basepairs.py +1711 -0
  8. bindview/chains.py +264 -0
  9. bindview/chem.py +57 -0
  10. bindview/clearance.py +123 -0
  11. bindview/cli.py +990 -0
  12. bindview/compare.py +1854 -0
  13. bindview/confidence.py +531 -0
  14. bindview/consensus.py +303 -0
  15. bindview/covalent.py +220 -0
  16. bindview/depict.py +790 -0
  17. bindview/detect.py +378 -0
  18. bindview/diagram.py +1891 -0
  19. bindview/distance_table.py +589 -0
  20. bindview/ensemble.py +787 -0
  21. bindview/errors.py +47 -0
  22. bindview/exposure.py +207 -0
  23. bindview/features.py +179 -0
  24. bindview/fingerprint.py +469 -0
  25. bindview/fragments.py +304 -0
  26. bindview/geometry.py +482 -0
  27. bindview/graph.py +611 -0
  28. bindview/graphbuild.py +431 -0
  29. bindview/interactions.py +418 -0
  30. bindview/interactive.py +334 -0
  31. bindview/interface.py +1329 -0
  32. bindview/ions.py +155 -0
  33. bindview/layout/__init__.py +15 -0
  34. bindview/layout/body.py +421 -0
  35. bindview/layout/engine.py +1084 -0
  36. bindview/layout/field.py +261 -0
  37. bindview/ligand.py +583 -0
  38. bindview/near.py +67 -0
  39. bindview/options.py +92 -0
  40. bindview/pae.py +991 -0
  41. bindview/peptide.py +610 -0
  42. bindview/plane.py +320 -0
  43. bindview/polymer.py +678 -0
  44. bindview/py.typed +0 -0
  45. bindview/report.py +1407 -0
  46. bindview/residues.py +296 -0
  47. bindview/resolve.py +493 -0
  48. bindview/scene.py +239 -0
  49. bindview/solvent.py +254 -0
  50. bindview/structure.py +1145 -0
  51. bindview/styles/__init__.py +2 -0
  52. bindview/styles/absence.py +180 -0
  53. bindview/styles/base.py +2128 -0
  54. bindview/styles/closeup.py +146 -0
  55. bindview/styles/detailed.py +690 -0
  56. bindview/styles/ligand_draw.py +289 -0
  57. bindview/styles/mixed.py +70 -0
  58. bindview/styles/polymer_draw.py +354 -0
  59. bindview/styles/rings.py +75 -0
  60. bindview/styles/schematic.py +311 -0
  61. bindview/styles/summary.py +147 -0
  62. bindview/svg.py +310 -0
  63. bindview/textmetrics.py +64 -0
  64. bindview/theme.py +317 -0
  65. bindview-0.1.0.dist-info/METADATA +270 -0
  66. bindview-0.1.0.dist-info/RECORD +70 -0
  67. bindview-0.1.0.dist-info/WHEEL +4 -0
  68. bindview-0.1.0.dist-info/entry_points.txt +2 -0
  69. bindview-0.1.0.dist-info/licenses/LICENSE +21 -0
  70. bindview-0.1.0.dist-info/licenses/NOTICE +48 -0
@@ -0,0 +1,1084 @@
1
+ """Seeded placement plus constrained refinement.
2
+
3
+ The problem: put every residue near the ligand atoms it contacts, with nothing
4
+ on top of anything else. A pocket's residues crowd one face of the ligand, so
5
+ "put each where it wants to be" piles them up, and plain force relaxation from
6
+ such a start gets stuck with labels trapped on the wrong side of the skeleton.
7
+
8
+ The engine therefore works in stages, all deterministic:
9
+
10
+ 1. **Seeded placement.** Bodies are taken most-constrained first. For each one
11
+ a few thousand candidate poses around its ligand atoms are scored with one
12
+ cost function (link lengths, lines crossing ligand bonds or running over
13
+ ligand ink, lines crossing other lines, distance from the ligand) and the
14
+ cheapest pose that collides with nothing already placed is taken. Collision
15
+ is a hard constraint, never a penalty, so an accepted pose is overlap-free
16
+ by construction.
17
+ 2. **Re-placement passes.** Each body in turn is lifted and re-seated against
18
+ all the others, until a full pass changes nothing. This undoes the myopia of
19
+ the greedy order.
20
+ 3. **Ejection chains.** A body that is still badly placed (a long link, a line
21
+ through the skeleton) usually is so because others took the room it needed
22
+ first. It is tried at the poses it would like; whoever is in the way is
23
+ lifted and re-seated; the exchange is kept if the total cost falls.
24
+ 4. **Polish.** A pattern search nudges every body by shrinking steps (and
25
+ rotates fragments slightly) under the same hard constraints plus a soft
26
+ preference for even spacing, which is what makes the result look composed
27
+ rather than merely legal.
28
+
29
+ A body that cannot be seated anywhere within reach is reported as unplaced; the
30
+ caller decides what to do with a diagram that could not be laid out.
31
+ """
32
+
33
+ from __future__ import annotations
34
+
35
+ import hashlib
36
+ import math
37
+ from dataclasses import dataclass, field, fields
38
+ from typing import Any, Mapping, Sequence
39
+
40
+ import numpy as np
41
+
42
+ from ..geometry import capsule_gaps, points_segments_distance, segments_distance
43
+ from .body import Body, Port, Pose
44
+ from .field import LigandField, segment_cross_matrix
45
+
46
+ __all__ = ["LayoutParams", "LayoutResult", "layout_bodies", "layout_key", "audit_layout"]
47
+
48
+ # Where along its link a distance label may sit, in order of preference.
49
+ _LABEL_T = np.array([0.5, 0.4, 0.6, 0.31, 0.69])
50
+
51
+
52
+ @dataclass(frozen=True)
53
+ class LayoutParams:
54
+ unit: float = 30.0 # one bond length; makes the cost terms dimensionless
55
+ solid_gap: float = 5.0 # minimum clearance between two bodies
56
+ line_gap: float = 3.0 # minimum clearance between a link line and another body
57
+ label_ligand_gap: float = 3.0 # minimum clearance between a distance label and ligand ink
58
+ reach: float = 7.0 # candidate search radius, in units
59
+ improve_passes: int = 5
60
+ eject_threshold: float = 1.6 # bodies this much costlier than their ligand-only best get an ejection attempt
61
+ eject_candidates: int = 5
62
+ eject_rounds: int = 2
63
+ max_candidates: int = 4000 # feasible candidate poses kept per body
64
+ eject_max_blockers: int = 4
65
+ give_up: int = 0 # with this many unplaced after a round of ejections the layout is left as it is (0: never)
66
+ w_length: float = 1.0
67
+ w_short: float = 4.0 # a link shorter than ideal costs this much more than a long one
68
+ w_bond_cross: float = 3.0
69
+ w_sight_cross: float = 0.5
70
+ w_line_cross: float = 1.4
71
+ w_ink: float = 2.0
72
+ ink_gap: float = 2.5
73
+ w_hug: float = 0.12
74
+ w_axis: float = 0.35
75
+ w_soft: float = 0.6
76
+ soft_gap: float = 10.0
77
+ w_blocked_sight: float = 0.8
78
+ w_near_line: float = 1.0
79
+ w_self: float = 3.0 # a link running over its own residue's drawing
80
+ w_assoc: float = 1.2 # a line-less contact sitting nearer to some other ligand atom
81
+ w_fan: float = 1.5 # two links into one site at (nearly) the same angle
82
+
83
+
84
+ @dataclass
85
+ class LayoutResult:
86
+ poses: dict[Any, Pose]
87
+ unplaced: list[Any]
88
+ cost: float
89
+ overlaps: int
90
+ line_crossings: int
91
+ bond_crossings: int
92
+ max_stretch: float
93
+ label_t: dict[Any, tuple[float, ...]] = field(default_factory=dict)
94
+ link_hits: int = 0 # links passing through a body they do not belong to
95
+ left: int = 0 # bodies without a place after the first round of ejections
96
+ abandoned: bool = False # left as it was then (``LayoutParams.give_up``)
97
+
98
+ @property
99
+ def ok(self) -> bool:
100
+ return not self.unplaced and self.overlaps == 0 and self.link_hits == 0
101
+
102
+
103
+ @dataclass
104
+ class _World:
105
+ """A placed body's geometry on the page."""
106
+
107
+ sp0: np.ndarray
108
+ sp1: np.ndarray
109
+ sr: np.ndarray
110
+ la: np.ndarray # drawn link segments
111
+ lb: np.ndarray
112
+ lt: np.ndarray # the ligand points they aim at
113
+
114
+
115
+ @dataclass
116
+ class _Geo:
117
+ """Page geometry of ``N`` poses of one body."""
118
+
119
+ pos: np.ndarray # (N, 2) body origins
120
+ p0: np.ndarray # (N, S, 2) solids: the body proper first, then distance labels
121
+ p1: np.ndarray
122
+ r: np.ndarray # (S,)
123
+ a: np.ndarray # (N, K, 2) visible link ends (protein side)
124
+ b: np.ndarray # (N, K, 2) visible link ends (ligand side)
125
+ ports: np.ndarray # (N, K, 2) port centres
126
+
127
+ def __getitem__(self, sl: "slice | np.ndarray") -> "_Geo":
128
+ return _Geo(self.pos[sl], self.p0[sl], self.p1[sl], self.r, self.a[sl], self.b[sl], self.ports[sl])
129
+
130
+
131
+ @dataclass
132
+ class _Batch:
133
+ """The feasible candidate poses of one body, cheapest first, with their
134
+ geometry. Computed once: the ligand does not move."""
135
+
136
+ pos: np.ndarray
137
+ ang: np.ndarray
138
+ mir: np.ndarray
139
+ base: np.ndarray
140
+ label_t: np.ndarray
141
+ geo: _Geo
142
+
143
+ def __len__(self) -> int:
144
+ return len(self.base)
145
+
146
+
147
+ class _Engine:
148
+ def __init__(self, fld: LigandField, bodies: Sequence[Body], params: LayoutParams) -> None:
149
+ self.field = fld
150
+ self.bodies = list(bodies)
151
+ self.p = params
152
+ self.pos: dict[int, np.ndarray] = {}
153
+ self.ang: dict[int, float] = {}
154
+ self.mir: dict[int, bool] = {}
155
+ self.lt: dict[int, np.ndarray] = {}
156
+ self.world: dict[int, _World] = {}
157
+ self._cand_cache: dict[tuple[int, bool], _Batch] = {}
158
+ #: A number for every pose that a body has been placed in, the same one when it comes back to it.
159
+ self._tags: list[dict[tuple, int]] = [{} for _ in self.bodies]
160
+ self.tag: dict[int, int] = {}
161
+ #: For the candidates of a body, what is known of each against each placed body (0: nothing, 1: they are
162
+ #: clear of each other, 2: they are not), and the pose of the placed body that it is known for.
163
+ self._known: dict[tuple[int, bool], tuple[np.ndarray, np.ndarray]] = {}
164
+ #: What a body costs against the ligand alone in a pose it was placed in, whether it may stand there, and its geometry.
165
+ self._priced: list[dict[int, tuple[float, bool, _Geo]]] = [{} for _ in self.bodies]
166
+
167
+ # -- bookkeeping -------------------------------------------------------
168
+ def _set(self, i: int, pos: np.ndarray, ang: float, mir: bool, label_t: np.ndarray) -> None:
169
+ body = self.bodies[i]
170
+ self.pos[i] = np.array(pos, dtype=float)
171
+ self.ang[i] = float(ang)
172
+ self.mir[i] = bool(mir)
173
+ self.lt[i] = np.array(label_t, dtype=float)
174
+ P, A, M = self.pos[i][None, :], np.array([ang]), np.array([mir])
175
+ if body.n_ports:
176
+ links = body.link_segments(P, A, M)
177
+ d = body._drawn
178
+ la, lb, lt = links[0][0][d], links[1][0][d], body._targets[d]
179
+ else:
180
+ links = None
181
+ la = lb = lt = np.zeros((0, 2))
182
+ p0, p1, r, _ = body.solids(P, A, M, self.lt[i][None, :], links)
183
+ self.world[i] = _World(p0[0], p1[0], r, la, lb, lt)
184
+ self.tag[i] = self._tags[i].setdefault((self.pos[i].tobytes(), self.ang[i], self.mir[i], self.lt[i].tobytes()),
185
+ len(self._tags[i]) + 1)
186
+
187
+ def _unset(self, i: int) -> None:
188
+ for d in (self.pos, self.ang, self.mir, self.lt, self.world, self.tag):
189
+ d.pop(i, None)
190
+
191
+ def _snapshot(self, ids: Sequence[int]) -> dict[int, tuple]:
192
+ # (Nothing here is ever changed in place: a pose that is set is a new one.)
193
+ return {i: (self.pos[i], self.ang[i], self.mir[i], self.lt[i], self.world[i], self.tag[i])
194
+ for i in ids if i in self.world}
195
+
196
+ def _restore(self, snap: dict[int, tuple], ids: Sequence[int]) -> None:
197
+ for i in ids:
198
+ self._unset(i)
199
+ for i, state in snap.items():
200
+ self.pos[i], self.ang[i], self.mir[i], self.lt[i], self.world[i], self.tag[i] = state
201
+
202
+ def _others(self, exclude: int, among: "Sequence[int] | None" = None
203
+ ) -> tuple[_World, np.ndarray, np.ndarray, list[int]]:
204
+ """Concatenated geometry of every placed body but ``exclude`` (or of those
205
+ ``among`` them); the owner (as an index into the returned id list) of
206
+ each solid and of each line; and the ids."""
207
+ ids = [j for j in (sorted(self.world) if among is None else among) if j != exclude]
208
+ if not ids:
209
+ z = np.zeros((0, 2))
210
+ return _World(z, z, np.zeros(0), z, z, z), np.zeros(0, dtype=int), np.zeros(0, dtype=int), ids
211
+ ws = [self.world[j] for j in ids]
212
+ sowner = np.repeat(np.arange(len(ids)), [len(w.sr) for w in ws])
213
+ lowner = np.repeat(np.arange(len(ids)), [len(w.la) for w in ws])
214
+ return (_World(np.concatenate([w.sp0 for w in ws]), np.concatenate([w.sp1 for w in ws]),
215
+ np.concatenate([w.sr for w in ws]), np.concatenate([w.la for w in ws]),
216
+ np.concatenate([w.lb for w in ws]), np.concatenate([w.lt for w in ws])), sowner, lowner, ids)
217
+
218
+ # -- candidates --------------------------------------------------------
219
+ def _candidates(self, body: Body, wide: bool = False) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
220
+ p = self.p
221
+ reach = p.reach * p.unit * (1.8 if wide else 1.0)
222
+ if body.kind == "disc":
223
+ lo = body.radius + body.ligand_clearance
224
+ targets = body._targets if body.n_ports else self.field.atom_xy
225
+ ideal = float(body._ideal.max()) if body.n_ports else lo
226
+ cells = self.field.cells(lo, lo + reach, stride=2)
227
+ if len(cells) == 0:
228
+ return np.zeros((0, 2)), np.zeros(0), np.zeros(0, dtype=bool)
229
+ d = np.linalg.norm(cells[:, None, :] - targets[None, :, :], axis=2).min(axis=1)
230
+ cells = cells[d <= ideal + reach]
231
+ return cells, np.zeros(len(cells)), np.zeros(len(cells), dtype=bool)
232
+ # Fragment: sweep the primary port around its target and try a fan of orientations.
233
+ port = body.ports[0]
234
+ mults = (1.0, 1.15, 1.32, 1.52, 1.78, 2.1, 2.5, 3.0) + ((3.8, 4.8, 6.0) if wide else ())
235
+ phis = np.deg2rad(np.arange(0.0, 360.0, 7.5))
236
+ deltas = np.deg2rad(np.array([0.0, 20.0, -20.0, 42.0, -42.0, 68.0, -68.0])) \
237
+ if body.rotatable else np.array([0.0])
238
+ mirrors = (False, True) if body.mirrorable else (False,)
239
+ pos_l, ang_l, mir_l = [], [], []
240
+ tx, ty = port.target
241
+ for mlt in mults:
242
+ length = port.ideal * mlt
243
+ if length > reach + port.ideal:
244
+ break
245
+ for phi in phis:
246
+ px, py = tx + length * math.cos(phi), ty + length * math.sin(phi)
247
+ for mirror in mirrors:
248
+ ax, ay = body.axis[0], (-body.axis[1] if mirror else body.axis[1])
249
+ base = math.atan2(ay, ax)
250
+ lx, ly = port.local[0], (-port.local[1] if mirror else port.local[1])
251
+ for dl in deltas:
252
+ theta = (phi + dl) - base if body.rotatable else 0.0
253
+ c, s = math.cos(theta), math.sin(theta)
254
+ # Body origin such that the port lands on (px, py).
255
+ pos_l.append((px - (lx * c - ly * s), py - (lx * s + ly * c)))
256
+ ang_l.append(theta)
257
+ mir_l.append(mirror)
258
+ return (np.array(pos_l, dtype=float).reshape(-1, 2), np.array(ang_l, dtype=float),
259
+ np.array(mir_l, dtype=bool))
260
+
261
+ def _geo(self, body: Body, pos: np.ndarray, ang: np.ndarray, mir: np.ndarray, label_t: np.ndarray,
262
+ links: tuple[np.ndarray, np.ndarray, np.ndarray] | None = None) -> _Geo:
263
+ n = len(pos)
264
+ if body.n_ports:
265
+ if links is None:
266
+ links = body.link_segments(pos, ang, mir)
267
+ a, b = links[0], links[1]
268
+ ports = body.ports_world(pos, ang, mir)
269
+ else:
270
+ a = b = ports = np.zeros((n, 0, 2))
271
+ p0, p1, r, _ = body.solids(pos, ang, mir, label_t, links)
272
+ return _Geo(pos, p0, p1, r, a, b, ports)
273
+
274
+ def _batch(self, i: int, wide: bool = False) -> _Batch:
275
+ """Feasible candidate poses of body ``i`` scored against the ligand,
276
+ cheapest first (cached: the ligand does not move, so this never changes)."""
277
+ key = (i, wide)
278
+ hit = self._cand_cache.get(key)
279
+ if hit is None:
280
+ body = self.bodies[i]
281
+ pos, ang, mir = self._candidates(body, wide)
282
+ # Throw away what the ligand alone rules out, cheaply, before the full scoring.
283
+ for some in (slice(0, None, 6), slice(0, None)):
284
+ # (A sixth of the points rules most of them out.)
285
+ if len(pos):
286
+ pts, rr = body.ligand_samples(pos, ang, mir, some)
287
+ keep = ((self.field.sdf(pts) - rr[None, :]) >= body.ligand_clearance - 1e-9).all(axis=1)
288
+ pos, ang, mir = pos[keep], ang[keep], mir[keep]
289
+ if len(pos):
290
+ keep = body.self_clear(pos, ang, mir)
291
+ pos, ang, mir = pos[keep], ang[keep], mir[keep]
292
+ links = body.link_segments(pos, ang, mir) if body.n_ports and len(pos) else None
293
+ if links is not None:
294
+ keep = self._links_may(body, pos, ang, mir, links)
295
+ pos, ang, mir = pos[keep], ang[keep], mir[keep]
296
+ links = (links[0][keep], links[1][keep], links[2][keep])
297
+ base, ok, lt = self._base(body, pos, ang, mir, checked=True, links=links)
298
+ idx = np.nonzero(ok)[0]
299
+ idx = idx[np.argsort(_classes(base[idx]), kind="stable")][: self.p.max_candidates]
300
+ pos, ang, mir, base, lt = pos[idx], ang[idx], mir[idx], base[idx], lt[idx]
301
+ if links is not None:
302
+ links = (links[0][idx], links[1][idx], links[2][idx])
303
+ hit = _Batch(pos, ang, mir, base, lt, self._geo(body, pos, ang, mir, lt, links))
304
+ self._cand_cache[key] = hit
305
+ return hit
306
+
307
+ # -- costs -------------------------------------------------------------
308
+ def _links_may(self, body: Body, pos: np.ndarray, ang: np.ndarray, mir: np.ndarray,
309
+ links: tuple[np.ndarray, np.ndarray, np.ndarray]) -> np.ndarray:
310
+ """``(N,)`` booleans: are the links of a pose long enough, and do they run through nothing they may not?"""
311
+ a, b, length = links
312
+ ok = (length >= body._minlen[None, :] - 1e-9).all(axis=1)
313
+ for k, port in enumerate(body.ports):
314
+ if port.drawn:
315
+ ok &= ~self.field.boxes_crossed(a[:, k], b[:, k], body._targets[k], reach=float(body._reach[k]))
316
+ if port.clear_of or port.clear_of_name:
317
+ ok &= ~_through_names(body, port, a[:, k], b[:, k], pos, ang, mir)
318
+ return ok
319
+
320
+ def _base(self, body: Body, pos: np.ndarray, ang: np.ndarray, mir: np.ndarray, checked: bool = False,
321
+ links: tuple[np.ndarray, np.ndarray, np.ndarray] | None = None
322
+ ) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
323
+ """Cost, feasibility and distance-label positions of poses against the ligand alone. ``checked``: that the
324
+ body and its links are where they may be is known already."""
325
+ p, u = self.p, self.p.unit
326
+ n = len(pos)
327
+ cost = np.zeros(n)
328
+ label_t = np.full((n, body.n_ports), 0.5)
329
+ if n == 0:
330
+ return cost, np.zeros(0, dtype=bool), label_t
331
+ if checked:
332
+ ok = np.ones(n, dtype=bool)
333
+ else:
334
+ pts, rr = body.ligand_samples(pos, ang, mir)
335
+ ok = ((self.field.sdf(pts) - rr[None, :]) >= body.ligand_clearance - 1e-9).all(axis=1)
336
+ ok &= body.self_clear(pos, ang, mir)
337
+ if body.n_ports:
338
+ a, b, length = links if links is not None else body.link_segments(pos, ang, mir)
339
+ rel = (length - body._ideal[None, :]) / u
340
+ pen = np.where(rel >= 0.0, rel * rel, p.w_short * rel * rel)
341
+ cost += p.w_length * (pen * body._weight[None, :]).sum(axis=1)
342
+ if not checked:
343
+ ok &= self._links_may(body, pos, ang, mir, (a, b, length))
344
+ ports = body.ports_world(pos, ang, mir)
345
+ ts = np.linspace(0.0, 1.0, 7)[None, :, None]
346
+ own_solids = None
347
+ # Beside a chain ligand several links of one residue end on one box and run side by side:
348
+ # there their labels have to keep clear of each other as well.
349
+ chain = len(self.field.unit_boxes) > 0
350
+ labels: list[tuple[np.ndarray, float, float]] = []
351
+ for k, port in enumerate(body.ports):
352
+ if port.drawn:
353
+ cost += p.w_bond_cross * self.field.bond_crossings(a[:, k], b[:, k])
354
+ samples = a[:, k][:, None, :] + (b[:, k] - a[:, k])[:, None, :] * ts
355
+ free = max(0.55 * u, port.target_radius + 6.0)
356
+ far = np.linalg.norm(samples - body._targets[k][None, None, :], axis=2) > free
357
+ cost += p.w_ink * ((self.field.sdf(samples) < p.ink_gap) & far).sum(axis=1)
358
+ if port.label_size is not None:
359
+ # Slide the distance label along the link to the first spot clear of ligand ink.
360
+ w, h = port.label_size
361
+ half = max(0.0, (w - h) / 2.0)
362
+ centre = a[:, k][:, None, :] + (b[:, k] - a[:, k])[:, None, :] * _LABEL_T[None, :, None]
363
+ clear = np.minimum(
364
+ np.minimum(self.field.sdf(centre), self.field.sdf(centre + np.array([half, 0.0]))),
365
+ self.field.sdf(centre - np.array([half, 0.0]))) - (h / 2.0 + 1.0)
366
+ good = clear >= p.label_ligand_gap
367
+ for other, ow, oh in labels:
368
+ good &= ~((np.abs(centre[:, :, 0] - other[:, None, 0]) < (w + ow) / 2.0 + 1.0)
369
+ & (np.abs(centre[:, :, 1] - other[:, None, 1]) < (h + oh) / 2.0 + 1.0))
370
+ if port.clear_of or port.clear_of_name:
371
+ # At a level of detail a residue has more lines, and they run closer together:
372
+ # the label of one does not stand on another line of the same residue.
373
+ off = np.array([half, 0.0])
374
+ for j, sibling in enumerate(body.ports):
375
+ if j != k and sibling.drawn:
376
+ for t_i in range(len(_LABEL_T)):
377
+ c = centre[:, t_i, :]
378
+ gap = segments_distance(c - off, c + off, a[:, j], b[:, j]) - (h / 2.0 + 1.0)
379
+ good[:, t_i] &= gap >= 1.0
380
+ if body.kind == "fragment":
381
+ if own_solids is None:
382
+ own_solids = body.solids(pos, ang, mir, None, (a, b, length))
383
+ s0, s1, sr, sx = own_solids
384
+ keep = ~sx
385
+ off = np.array([half, 0.0])
386
+ seated = np.zeros(n, dtype=bool)
387
+ for t_i in range(len(_LABEL_T)):
388
+ # (A pose whose label has a place already is not asked about the next ones.)
389
+ at = np.nonzero(good[:, t_i] & ~seated)[0]
390
+ if len(at):
391
+ c = centre[at, t_i, :]
392
+ gap = segments_distance((c - off)[:, None, :], (c + off)[:, None, :], s0[at][:, keep, :],
393
+ s1[at][:, keep, :]) - sr[None, keep] - (h / 2.0 + 1.0)
394
+ good[at, t_i] = (gap >= 1.5).all(axis=1)
395
+ seated[at] |= good[at, t_i]
396
+ choice = np.argmax(good, axis=1)
397
+ ok &= good.any(axis=1)
398
+ label_t[:, k] = _LABEL_T[choice]
399
+ cost += 0.05 * choice
400
+ if chain:
401
+ labels.append((centre[np.arange(n), choice], w, h))
402
+ if body.kind == "fragment":
403
+ if own_solids is None:
404
+ own_solids = body.solids(pos, ang, mir, None, (a, b, length))
405
+ s0, s1, sr, sx = own_solids
406
+ gap = segments_distance(a[:, k][:, None, :], b[:, k][:, None, :], s0, s1) - sr[None, :]
407
+ over = (gap < 0.5) & ~sx[None, :]
408
+ at, m = np.nonzero(over)
409
+ if len(at):
410
+ # (What the link ends on does not count.)
411
+ pk = ports[at, k]
412
+ over[at, m] = (segments_distance(pk, pk, s0[at, m], s1[at, m]) - sr[m]) > port.port_radius + 2.0
413
+ cost += p.w_self * over.sum(axis=1)
414
+ else:
415
+ tgt = np.broadcast_to(body._targets[k], (n, 2))
416
+ cost += p.w_sight_cross * body._weight[k] * self.field.bond_crossings(ports[:, k], tgt)
417
+ if body.rotatable:
418
+ out = ports[:, 0, :] - body._targets[0][None, :]
419
+ out /= np.maximum(np.linalg.norm(out, axis=1), 1e-9)[:, None]
420
+ axis = body._xd(body.axis, ang, mir)
421
+ dev = np.arccos(np.clip((out * axis).sum(axis=1), -1.0, 1.0))
422
+ cost += p.w_axis * dev * dev
423
+ if body.kind == "disc":
424
+ lo = body.radius + body.ligand_clearance
425
+ cost += p.w_hug * np.maximum(0.0, self.field.sdf(pos) - lo) / u
426
+ sight = ~body._drawn
427
+ if sight.any() and len(self.field.atom_xy) > int(sight.sum()):
428
+ # A contact without a line is read off by proximity: the body should be
429
+ # closer to the atoms it contacts than to any other atom of the ligand.
430
+ mine = body._targets[sight]
431
+ atoms = self.field.atom_xy
432
+ other = np.linalg.norm(atoms[:, None, :] - mine[None, :, :], axis=2).min(axis=1) > 1.0
433
+ if other.any():
434
+ at = ports[:, sight, :].mean(axis=1) if body.kind != "disc" else pos
435
+ d_own = np.linalg.norm(at[:, None, :] - mine[None, :, :], axis=2).min(axis=1)
436
+ d_other = np.linalg.norm(at[:, None, :] - atoms[other][None, :, :], axis=2).min(axis=1)
437
+ cost += p.w_assoc * float(body._weight[sight].sum()) * np.maximum(0.0, (d_own - d_other) / u + 0.2)
438
+ return cost, ok, label_t
439
+
440
+ def _blocked(self, i: int, g: _Geo, others: "tuple[_World, np.ndarray, np.ndarray, list[int]]", soft: bool = False,
441
+ every: bool = True) -> tuple[np.ndarray, "np.ndarray | None"]:
442
+ """Which of ``others`` (columns) each pose of body ``i`` (rows) is not clear of; with ``soft`` also how far
443
+ they are apart (``inf`` where that is further than anyone asks).
444
+
445
+ Unless ``every`` is set, a pose is not looked at further once something is found in its way: then one
446
+ ``True`` is all that its row says, and a row without one is clear of all of them.
447
+
448
+ Most poses are nowhere near most placed bodies, so exact capsule distances are only computed for the
449
+ pairs whose bounding circles come within reach of each other.
450
+ """
451
+ body, p = self.bodies[i], self.p
452
+ w, sowner, lowner, ids = others
453
+ n, nb = len(g.pos), len(ids)
454
+ bad = np.zeros((n, nb), dtype=bool)
455
+ gaps = np.full((n, nb), np.inf) if soft else None
456
+ if n == 0 or not ids:
457
+ return bad, gaps
458
+ rows = np.arange(n) # the poses that are still looked at, as rows of the answer
459
+
460
+ def left() -> bool:
461
+ nonlocal g, rows
462
+ if not every:
463
+ free = ~bad[rows].any(axis=1)
464
+ if not free.all():
465
+ rows, g = rows[free], g[free]
466
+ return len(rows) > 0
467
+
468
+ sp = body.n_proper
469
+ nd = g.p0.shape[1] - sp
470
+ mids = (w.sp0 + w.sp1) / 2.0
471
+ ext = np.linalg.norm(w.sp1 - w.sp0, axis=1) / 2.0 + w.sr
472
+ least = p.solid_gap - 1e-9
473
+ # Body proper against placed solids.
474
+ reach = body.proper_radius + max(p.solid_gap, p.soft_gap if soft else 0.0)
475
+ pi, mj = np.nonzero(_apart(g.pos, mids) <= reach + ext[None, :])
476
+ if len(pi) and sp:
477
+ d = self._gap(g.p0[pi, :sp, :], g.p1[pi, :sp, :], g.r[:sp], w.sp0[mj], w.sp1[mj], w.sr[mj],
478
+ max(p.solid_gap, p.soft_gap if soft else 0.0))
479
+ if gaps is not None:
480
+ np.minimum.at(gaps, (pi, sowner[mj]), d)
481
+ hit = d < least
482
+ bad[pi[hit], sowner[mj[hit]]] = True
483
+ # Distance labels against placed solids (they sit out on the links, away from the body).
484
+ for k in range(sp, sp + nd):
485
+ if not left():
486
+ return bad, gaps
487
+ c = (g.p0[:, k, :] + g.p1[:, k, :]) / 2.0
488
+ half = float(np.linalg.norm(g.p1[0, k, :] - g.p0[0, k, :])) / 2.0 + g.r[k]
489
+ pi, mj = np.nonzero(_apart(c, mids) <= half + p.solid_gap + ext[None, :])
490
+ if len(pi):
491
+ d = segments_distance(g.p0[pi, k, :], g.p1[pi, k, :], w.sp0[mj], w.sp1[mj]) - g.r[k] - w.sr[mj]
492
+ if gaps is not None:
493
+ np.minimum.at(gaps, (rows[pi], sowner[mj]), d)
494
+ hit = d < least
495
+ bad[rows[pi[hit]], sowner[mj[hit]]] = True
496
+ if len(w.la) and left():
497
+ # Body and its labels against placed link lines.
498
+ lmid = (w.la + w.lb) / 2.0
499
+ lext = np.linalg.norm(w.lb - w.la, axis=1) / 2.0
500
+ li, lj = np.nonzero(_apart(g.pos, lmid) <= body.proper_radius + p.line_gap + lext[None, :])
501
+ if len(li) and sp:
502
+ d = self._gap(g.p0[li, :sp, :], g.p1[li, :sp, :], g.r[:sp], w.la[lj], w.lb[lj], 0.0, p.line_gap)
503
+ hit = d < p.line_gap - 1e-9
504
+ bad[rows[li[hit]], lowner[lj[hit]]] = True
505
+ for k in range(sp, sp + nd):
506
+ if not left():
507
+ return bad, gaps
508
+ c = (g.p0[:, k, :] + g.p1[:, k, :]) / 2.0
509
+ half = float(np.linalg.norm(g.p1[0, k, :] - g.p0[0, k, :])) / 2.0 + g.r[k]
510
+ li, lj = np.nonzero(points_segments_distance(c, w.la, w.lb) <= half + p.line_gap)
511
+ if len(li):
512
+ d = segments_distance(g.p0[li, k, :], g.p1[li, k, :], w.la[lj], w.lb[lj]) - g.r[k]
513
+ hit = d < p.line_gap - 1e-9
514
+ bad[rows[li[hit]], lowner[lj[hit]]] = True
515
+ for k, port in enumerate(body.ports):
516
+ if port.drawn and left():
517
+ hit = self._under(g.a[:, k, :], g.b[:, k, :], w, mids, ext, sowner, nb, p.line_gap)
518
+ bad[rows] |= hit
519
+ return bad, gaps
520
+
521
+ @staticmethod
522
+ def _gap(p0: np.ndarray, p1: np.ndarray, r: np.ndarray, q0: np.ndarray, q1: np.ndarray, rq: "np.ndarray | float",
523
+ within: float) -> np.ndarray:
524
+ """How far a body is from one capsule, for pairs of a pose of it and a capsule: ``p0``, ``p1`` are the
525
+ capsules of the body in each of ``N`` poses (``(N, S, 2)``, radii ``(S,)``), ``q0``, ``q1`` the other
526
+ capsule in each (``(N, 2)``, radii ``(N,)`` or one for all). Exact where it is less than ``within``; some
527
+ number that is no less where it is not."""
528
+ half = np.sqrt((p1[:, :, 0] - p0[:, :, 0]) ** 2 + (p1[:, :, 1] - p0[:, :, 1]) ** 2) / 2.0
529
+ span = np.sqrt((q1[:, 0] - q0[:, 0]) ** 2 + (q1[:, 1] - q0[:, 1]) ** 2) / 2.0
530
+ dx = (p0[:, :, 0] + p1[:, :, 0]) / 2.0 - ((q0[:, 0] + q1[:, 0]) / 2.0)[:, None]
531
+ dy = (p0[:, :, 1] + p1[:, :, 1]) / 2.0 - ((q0[:, 1] + q1[:, 1]) / 2.0)[:, None]
532
+ # (Two capsules are at least as far apart as their middles are, less what each reaches from its own.)
533
+ at_least = np.sqrt(dx * dx + dy * dy) - half - span[:, None] - r[None, :] - np.reshape(rq, (-1, 1))
534
+ m, s = np.nonzero(at_least <= within + 1e-6)
535
+ out = np.where(at_least <= within + 1e-6, np.inf, at_least)
536
+ if len(m):
537
+ d = segments_distance(p0[m, s], p1[m, s], q0[m], q1[m])
538
+ out[m, s] = d - r[s] - (rq[m] if isinstance(rq, np.ndarray) else rq)
539
+ return out.min(axis=1)
540
+
541
+ @staticmethod
542
+ def _under(a: np.ndarray, b: np.ndarray, w: _World, mids: np.ndarray, ext: np.ndarray, sowner: np.ndarray, nb: int,
543
+ limit: float) -> np.ndarray:
544
+ """``(len(a), nb)`` booleans: does the line ``a[i] -> b[i]`` come within ``limit`` of a solid of that placed body?"""
545
+ hits = np.zeros((len(a), nb), dtype=bool)
546
+ # Cull on the distance of the solids' centres to the segment.
547
+ mj, pi = np.nonzero(points_segments_distance(mids, a, b) <= ext[:, None] + limit)
548
+ if len(pi):
549
+ d = segments_distance(a[pi], b[pi], w.sp0[mj], w.sp1[mj]) - w.sr[mj]
550
+ sel = d < limit - 1e-9
551
+ hits[pi[sel], sowner[mj[sel]]] = True
552
+ return hits
553
+
554
+ def _crowding(self, i: int, g: _Geo, others: "tuple[_World, np.ndarray, np.ndarray, list[int]]",
555
+ gaps: "np.ndarray | None" = None) -> np.ndarray:
556
+ """What poses cost against the bodies already placed, beside what rules a pose out; ``gaps``: how far each
557
+ is from each of them, where even spacing counts."""
558
+ body, p, u = self.bodies[i], self.p, self.p.unit
559
+ w, sowner, _, ids = others
560
+ n, nb = len(g.pos), len(ids)
561
+ cost = np.zeros(n)
562
+ if n == 0 or not ids:
563
+ return cost
564
+ if gaps is not None:
565
+ short = np.maximum(0.0, (p.soft_gap - np.minimum(gaps, p.soft_gap)) / u)
566
+ cost += p.w_soft * (short * short).sum(axis=1)
567
+ nl = len(w.la)
568
+ sights = [k for k, port in enumerate(body.ports) if not port.drawn]
569
+ if sights:
570
+ mids = (w.sp0 + w.sp1) / 2.0
571
+ ext = np.linalg.norm(w.sp1 - w.sp0, axis=1) / 2.0 + w.sr
572
+ for k, port in enumerate(body.ports):
573
+ if not port.drawn:
574
+ hits = self._under(g.ports[:, k, :], np.broadcast_to(body._targets[k], (n, 2)), w, mids, ext, sowner, nb, 0.0)
575
+ cost += p.w_blocked_sight * body._weight[k] * hits.sum(axis=1)
576
+ elif nl:
577
+ ak, bk = g.a[:, k, :], g.b[:, k, :]
578
+ cost += p.w_line_cross * segment_cross_matrix(ak, bk, w.la, w.lb).sum(axis=1)
579
+ # Two links that run side by side (typically into the same atom)
580
+ # read as one thick line; keep their outer halves apart.
581
+ mid = (ak + bk) / 2.0
582
+ cost += p.w_near_line * (points_segments_distance(mid, w.la, w.lb) < 2.0 * p.line_gap).sum(axis=1)
583
+ if port.fan > 0.0:
584
+ # Links into the same site should fan out around it, not queue on one side.
585
+ tgt = body._targets[k]
586
+ same = np.linalg.norm(w.lt - tgt[None, :], axis=1) < 1.0
587
+ if same.any():
588
+ u1 = ak - tgt[None, :]
589
+ u1 /= np.maximum(np.linalg.norm(u1, axis=1), 1e-9)[:, None]
590
+ u2 = w.la[same] - tgt[None, :]
591
+ u2 /= np.maximum(np.linalg.norm(u2, axis=1), 1e-9)[:, None]
592
+ ang = np.arccos(np.clip(u1 @ u2.T, -1.0, 1.0))
593
+ tight = np.maximum(0.0, 1.0 - ang / port.fan)
594
+ cost += p.w_fan * (tight * tight).sum(axis=1)
595
+ return cost
596
+
597
+ def _collide(self, i: int, g: _Geo, soft: bool = False) -> tuple[np.ndarray, np.ndarray]:
598
+ """Cost and feasibility of poses against the bodies already placed."""
599
+ others = self._others(i)
600
+ bad, gaps = self._blocked(i, g, others, soft)
601
+ return self._crowding(i, g, others, gaps), ~bad.any(axis=1)
602
+
603
+ def _blockers(self, i: int, g: _Geo) -> set[int]:
604
+ """The placed bodies that make the single pose given infeasible."""
605
+ others = self._others(i)
606
+ bad, _ = self._blocked(i, g, others)
607
+ return {others[3][j] for j in np.nonzero(bad[0])[0]}
608
+
609
+ def _score(self, i: int, pos: np.ndarray, ang: np.ndarray, mir: np.ndarray, soft: bool = False
610
+ ) -> tuple[np.ndarray, np.ndarray]:
611
+ """Total cost of poses (``inf`` where infeasible) and their label positions."""
612
+ body = self.bodies[i]
613
+ links = body.link_segments(pos, ang, mir) if body.n_ports else None
614
+ base, ok, lt = self._base(body, pos, ang, mir, links=links)
615
+ extra, ok2 = self._collide(i, self._geo(body, pos, ang, mir, lt, links), soft)
616
+ total = base + extra
617
+ total[~(ok & ok2)] = np.inf
618
+ return total, lt
619
+
620
+ def _current(self, i: int) -> float:
621
+ """What body ``i`` costs where it stands (``inf`` where it may not)."""
622
+ hit = self._priced[i].get(self.tag[i])
623
+ if hit is None:
624
+ # Against the ligand, which does not move: once for every pose the body is placed in.
625
+ body = self.bodies[i]
626
+ pos, ang, mir = self.pos[i][None, :], np.array([self.ang[i]]), np.array([self.mir[i]])
627
+ links = body.link_segments(pos, ang, mir) if body.n_ports else None
628
+ base, ok, lt = self._base(body, pos, ang, mir, links=links)
629
+ hit = self._priced[i][self.tag[i]] = (float(base[0]), bool(ok[0]), self._geo(body, pos, ang, mir, lt, links))
630
+ own, stands, geo = hit
631
+ extra, clear = self._collide(i, geo)
632
+ return own + float(extra[0]) if stands and clear[0] else math.inf
633
+
634
+ # -- search ------------------------------------------------------------
635
+ def _best(self, i: int, wide: bool = False, upper: float = np.inf
636
+ ) -> tuple[float, np.ndarray, float, bool, np.ndarray] | None:
637
+ """Cheapest feasible candidate pose for body ``i`` against everything placed.
638
+
639
+ Only poses cheaper than ``upper`` are of interest to the caller, and a
640
+ pose can never cost less than its ligand-only cost, so the search stops
641
+ as soon as the (sorted) candidates reach that bound. The answer is the
642
+ same as an unbounded search whenever one below ``upper`` exists.
643
+ """
644
+ batch = self._batch(i, wide)
645
+ n = len(batch)
646
+ if n == 0:
647
+ return None
648
+ ids = [j for j in sorted(self.world) if j != i]
649
+ known = self._known_of(i, wide, n, ids)
650
+ best_cost, best_j = float(upper), -1
651
+ chunk = 128 if self.bodies[i].kind == "fragment" else 768
652
+ start = 0
653
+ while start < n:
654
+ if batch.base[start] >= best_cost:
655
+ break # sorted: every remaining candidate is already worse
656
+ j, cost = self._cheapest(i, batch, start, min(n, start + chunk), best_cost, ids, known)
657
+ if j >= 0 and cost < best_cost - 1e-9:
658
+ best_cost, best_j = cost, j
659
+ start += chunk
660
+ chunk = min(chunk * 2, 1024)
661
+ if best_j < 0:
662
+ return None
663
+ return (best_cost, batch.pos[best_j], float(batch.ang[best_j]), bool(batch.mir[best_j]),
664
+ batch.label_t[best_j])
665
+
666
+ def _known_of(self, i: int, wide: bool, n: int, ids: Sequence[int]) -> np.ndarray:
667
+ """What is known of the candidates of body ``i`` against the placed bodies ``ids``, where they are now."""
668
+ hit = self._known.get((i, wide))
669
+ if hit is None:
670
+ hit = self._known[(i, wide)] = (np.zeros((len(self.bodies), n), dtype=np.uint8),
671
+ np.zeros(len(self.bodies), dtype=np.int64))
672
+ known, tags = hit
673
+ for j in ids:
674
+ if tags[j] != self.tag[j]:
675
+ known[j], tags[j] = 0, self.tag[j]
676
+ return known
677
+
678
+ def _cheapest(self, i: int, batch: _Batch, start: int, stop: int, bound: float, ids: Sequence[int],
679
+ known: np.ndarray) -> tuple[int, float]:
680
+ """The cheapest feasible one of the candidates ``start:stop`` and its cost, or ``(-1, inf)``.
681
+
682
+ A candidate that costs more by itself than one that was found costs with everything around it is not
683
+ looked at; and one that something known is in the way of is not looked at again. Neither changes
684
+ which one is the cheapest (the first of those that cost the same, :func:`_least`).
685
+ """
686
+ found: list[np.ndarray] = []
687
+ costs: list[np.ndarray] = []
688
+ others = None
689
+ least, at, step = bound, start, 128
690
+ while at < stop and batch.base[at] <= least + 1e-6:
691
+ rows = np.arange(at, min(stop, at + step))
692
+ rows = rows[batch.base[rows] <= least + 1e-6]
693
+ rows = self._clear(i, batch, rows, ids, known)
694
+ if len(rows):
695
+ if others is None:
696
+ others = self._others(i)
697
+ cost = batch.base[rows] + self._crowding(i, batch.geo[rows], others)
698
+ found.append(rows)
699
+ costs.append(cost)
700
+ least = min(least, float(cost.min()))
701
+ at += step
702
+ step = min(step * 2, 512)
703
+ if not found:
704
+ return -1, math.inf
705
+ total = np.concatenate(costs)
706
+ j = _least(total)
707
+ return int(np.concatenate(found)[j]), float(total[j])
708
+
709
+ def _clear(self, i: int, batch: _Batch, rows: np.ndarray, ids: Sequence[int], known: np.ndarray) -> np.ndarray:
710
+ """Those of the candidates ``rows`` that are clear of everything placed; what is found goes into ``known``."""
711
+ if not ids:
712
+ return rows
713
+ at = np.array(ids)
714
+ state = known[np.ix_(at, rows)]
715
+ free = ~(state == 2).any(axis=0)
716
+ rows, fresh = rows[free], at[(state[:, free] == 0).any(axis=1)]
717
+ if len(rows) and len(fresh):
718
+ bad, _ = self._blocked(i, batch.geo[rows], self._others(i, fresh.tolist()), every=False)
719
+ clear = ~bad.any(axis=1)
720
+ # (Of a candidate that something is in the way of, only that is known.)
721
+ known[np.ix_(fresh, rows[clear])] = 1
722
+ pose, body = np.nonzero(bad)
723
+ known[fresh[body], rows[pose]] = 2
724
+ rows = rows[clear]
725
+ return rows
726
+
727
+ def _seat(self, i: int) -> bool:
728
+ hit = self._best(i) or self._best(i, wide=True)
729
+ if hit is None:
730
+ return False
731
+ self._set(i, hit[1], hit[2], hit[3], hit[4])
732
+ return True
733
+
734
+ def _order(self) -> list[int]:
735
+ """Most constrained first: fragments, then discs with the fewest places to go."""
736
+ def room(i: int) -> int:
737
+ if self.bodies[i].kind != "disc":
738
+ return 0
739
+ return int((np.round(self._batch(i).base, 6) < 1.5).sum()) # (rounded: a last bit decides nothing)
740
+ keyed = [(-self.bodies[i].priority, room(i), i) for i in range(len(self.bodies))]
741
+ return [i for _, _, i in sorted(keyed)]
742
+
743
+ def run(self) -> LayoutResult:
744
+ order = self._order()
745
+ for i in order:
746
+ self._seat(i)
747
+ self._replace_passes(order)
748
+ left, abandoned = len(self.bodies) - len(self.world), False
749
+ for k in range(self.p.eject_rounds):
750
+ more = self._eject_pass(order)
751
+ if more:
752
+ self._replace_passes(order)
753
+ if k == 0:
754
+ left = len(self.bodies) - len(self.world)
755
+ abandoned = 0 < self.p.give_up <= left
756
+ if not more or abandoned:
757
+ break
758
+ if not abandoned:
759
+ self._polish(order)
760
+ unplaced = [i for i in order if i not in self.world]
761
+ result = self._result(unplaced)
762
+ result.left, result.abandoned = left, abandoned
763
+ return result
764
+
765
+ def _replace_passes(self, order: Sequence[int]) -> None:
766
+ for _ in range(self.p.improve_passes):
767
+ moved = False
768
+ for i in order:
769
+ if i in self.world:
770
+ now = self._current(i)
771
+ if len(self._batch(i)) and now <= float(self._batch(i).base[0]) + 1e-6:
772
+ continue # already at its ligand-only optimum
773
+ saved = self._snapshot([i])
774
+ self._unset(i)
775
+ hit = self._best(i, upper=now)
776
+ if hit is not None and hit[0] < now - 1e-6:
777
+ self._set(i, hit[1], hit[2], hit[3], hit[4])
778
+ moved = True
779
+ else:
780
+ self._restore(saved, [i])
781
+ elif self._seat(i):
782
+ moved = True
783
+ if not moved:
784
+ break
785
+
786
+ def _eject_pass(self, order: Sequence[int]) -> bool:
787
+ """Try to seat badly placed bodies where they want to be, moving whoever is in the way."""
788
+ p = self.p
789
+ improved = False
790
+ costs = {i: self._current(i) for i in self.world}
791
+ # Worth trying only where a body pays clearly more than the ligand alone would make it pay.
792
+ gain = {i: costs[i] - (float(self._batch(i).base[0]) if len(self._batch(i)) else costs[i])
793
+ for i in self.world}
794
+ worst = sorted((i for i in order if i in self.world and gain[i] > p.eject_threshold),
795
+ key=lambda i: (-round(gain[i], 6), i))
796
+ for i in worst + [i for i in order if i not in self.world]:
797
+ batch = self._batch(i)
798
+ now = self._current(i) if i in self.world else 1e6
799
+ limit = int(np.searchsorted(batch.base, now - p.eject_threshold * 0.6))
800
+ if limit == 0:
801
+ continue
802
+ # Spread the trials: the cheapest pose in each direction from the body's first target.
803
+ tried: list[int] = []
804
+ seen: set[int] = set()
805
+ tgt = self.bodies[i]._targets[0] if self.bodies[i].n_ports else np.zeros(2)
806
+ rel = (batch.geo.ports[:limit, 0, :] if self.bodies[i].n_ports else batch.pos[:limit]) - tgt
807
+ sectors = _sectors(rel)
808
+ for j in range(limit):
809
+ if int(sectors[j]) in seen:
810
+ continue
811
+ seen.add(int(sectors[j]))
812
+ tried.append(j)
813
+ if len(tried) >= p.eject_candidates or len(seen) == 8:
814
+ break
815
+ all_ids = sorted(self.world)
816
+ snap = self._snapshot(all_ids)
817
+ for j in tried:
818
+ self._unset(i)
819
+ geo = batch.geo[j:j + 1]
820
+ blockers = self._blockers(i, geo)
821
+ if not blockers or len(blockers) > p.eject_max_blockers:
822
+ self._restore(snap, [i])
823
+ continue
824
+ # An exchange is judged by the bodies that move; what they do to the
825
+ # rest (crossed lines, blocked sightlines) is part of their own cost.
826
+ before = now + sum(costs[bk] for bk in blockers)
827
+ for bk in blockers:
828
+ self._unset(bk)
829
+ _, ok = self._collide(i, geo)
830
+ done = bool(ok[0])
831
+ if done:
832
+ self._set(i, batch.pos[j], float(batch.ang[j]), bool(batch.mir[j]), batch.label_t[j])
833
+ after = self._current(i)
834
+ for bk in sorted(blockers, key=lambda b: order.index(b)):
835
+ hit = self._best(bk, upper=before - after) if after < before else None
836
+ if hit is None:
837
+ done = False
838
+ break
839
+ self._set(bk, hit[1], hit[2], hit[3], hit[4])
840
+ after += hit[0]
841
+ if done and after < before - 1e-6:
842
+ improved = True
843
+ costs = {k: self._current(k) for k in self.world}
844
+ break
845
+ self._restore(snap, sorted(set(all_ids) | {i} | blockers))
846
+ return improved
847
+
848
+ def _polish(self, order: Sequence[int]) -> None:
849
+ dirs = [(1.0, 0.0), (-1.0, 0.0), (0.0, 1.0), (0.0, -1.0),
850
+ (0.7071, 0.7071), (0.7071, -0.7071), (-0.7071, 0.7071), (-0.7071, -0.7071)]
851
+ for step in (6.0, 3.0, 1.5, 0.75):
852
+ for _ in range(3):
853
+ moved = False
854
+ for i in order:
855
+ if i not in self.world:
856
+ continue
857
+ body = self.bodies[i]
858
+ cand_pos = [self.pos[i]] + [self.pos[i] + step * np.array(d) for d in dirs]
859
+ cand_ang = [self.ang[i]] * len(cand_pos)
860
+ if body.rotatable:
861
+ turn = step / max(body.radius, 12.0)
862
+ local = body.ports[0].local
863
+ ly = -local[1] if self.mir[i] else local[1]
864
+ pivot = np.array(Pose(float(self.pos[i][0]), float(self.pos[i][1]), self.ang[i],
865
+ self.mir[i]).apply(local))
866
+ for sgn in (1.0, -1.0):
867
+ # Rotate about the primary port so the link end stays put.
868
+ th = self.ang[i] + sgn * turn
869
+ c, s = math.cos(th), math.sin(th)
870
+ cand_pos.append(pivot - np.array([local[0] * c - ly * s, local[0] * s + ly * c]))
871
+ cand_ang.append(th)
872
+ pos = np.array(cand_pos)
873
+ ang = np.array(cand_ang)
874
+ mir = np.full(len(pos), self.mir[i])
875
+ total, lt = self._score(i, pos, ang, mir, soft=True)
876
+ j = _least(total)
877
+ if j != 0 and total[j] < total[0] - 1e-7:
878
+ self._set(i, pos[j], float(ang[j]), self.mir[i], lt[j])
879
+ moved = True
880
+ if not moved:
881
+ break
882
+
883
+ # -- reporting ---------------------------------------------------------
884
+ def _result(self, unplaced: Sequence[int]) -> LayoutResult:
885
+ poses: dict[Any, Pose] = {}
886
+ label_t: dict[Any, tuple[float, ...]] = {}
887
+ total = 0.0
888
+ stretch = 0.0
889
+ bond_x = 0
890
+ box_hits = 0
891
+ for i in sorted(self.world):
892
+ body = self.bodies[i]
893
+ poses[body.key] = Pose(float(self.pos[i][0]), float(self.pos[i][1]), self.ang[i], self.mir[i])
894
+ label_t[body.key] = tuple(float(v) for v in self.lt[i])
895
+ c = self._current(i)
896
+ total += c if math.isfinite(c) else 0.0
897
+ if body.n_ports:
898
+ P, A, M = self.pos[i][None, :], np.array([self.ang[i]]), np.array([self.mir[i]])
899
+ a, b, length = body.link_segments(P, A, M)
900
+ stretch = max(stretch, float((length[0] / np.maximum(body._ideal, 1e-9)).max()))
901
+ d = body._drawn
902
+ if d.any():
903
+ bond_x += int(self.field.bond_crossings(a[0][d], b[0][d]).sum())
904
+ box_hits += sum(int(self.field.boxes_crossed(a[0][k:k + 1], b[0][k:k + 1], body._targets[k],
905
+ reach=float(body._reach[k]))[0])
906
+ for k in np.nonzero(d)[0])
907
+ # ... and so, for a residue drawn at a level of detail, is a link through a name of its
908
+ # own residue that it may not run through, and a label that stands on a sibling link.
909
+ strict = [k for k in np.nonzero(d)[0] if body.ports[k].clear_of or body.ports[k].clear_of_name]
910
+ box_hits += sum(int(_through_names(body, body.ports[k], a[0][k:k + 1], b[0][k:k + 1], P, A, M)[0])
911
+ for k in strict)
912
+ if strict:
913
+ box_hits += _labels_on_siblings(body, a, b, np.asarray(self.lt[i], dtype=float)[None, :])
914
+ # Independent audit of the final state: nothing here trusts the search.
915
+ ids = sorted(self.world)
916
+ overlaps = 0
917
+ line_x = 0
918
+ link_hits = box_hits # ... a link across a residue box of a chain ligand is one as well
919
+ for n_, i in enumerate(ids):
920
+ wi = self.world[i]
921
+ for j in ids[n_ + 1:]:
922
+ wj = self.world[j]
923
+ if len(wi.sr) and len(wj.sr) and capsule_gaps(wi.sp0, wi.sp1, wi.sr, wj.sp0, wj.sp1, wj.sr).min() < -0.5:
924
+ overlaps += 1
925
+ if len(wi.la) and len(wj.la):
926
+ line_x += int(segment_cross_matrix(wi.la, wi.lb, wj.la, wj.lb).sum())
927
+ for wa, wb in ((wi, wj), (wj, wi)):
928
+ if len(wa.la) and len(wb.sr):
929
+ gaps = capsule_gaps(wa.la, wa.lb, np.zeros(len(wa.la)), wb.sp0, wb.sp1, wb.sr)
930
+ link_hits += int((gaps.min(axis=1) < -0.5).sum())
931
+ return LayoutResult(poses=poses, unplaced=[self.bodies[i].key for i in unplaced], cost=total,
932
+ overlaps=overlaps, line_crossings=line_x, bond_crossings=bond_x,
933
+ max_stretch=stretch, label_t=label_t, link_hits=link_hits)
934
+
935
+
936
+ def _classes(scores: np.ndarray, within: float = 1e-9) -> np.ndarray:
937
+ """Scores as they are compared: each stands for the least of its class, and two scores are of one class where
938
+ they lie within ``within`` of each other, or of a score between them.
939
+
940
+ Two scores that differ by a last bit are so equal wherever they lie. Each rounded by itself they are not: a
941
+ rounding has edges, and scores that are products of short decimals lie on them.
942
+ """
943
+ arr = np.asarray(scores, dtype=float)
944
+ if len(arr) < 2:
945
+ return arr
946
+ order = np.argsort(arr, kind="stable")
947
+ ordered = arr[order]
948
+ with np.errstate(invalid="ignore"):
949
+ first = np.concatenate([[True], np.diff(ordered) > within])
950
+ first |= ~np.isfinite(ordered)
951
+ least = ordered[np.maximum.accumulate(np.where(first, np.arange(len(ordered)), 0))]
952
+ out = np.empty_like(arr)
953
+ out[order] = least
954
+ return out
955
+
956
+
957
+ def _least(scores: np.ndarray, within: float = 1e-9) -> int:
958
+ """Where the least of ``scores`` is, and of those that are equal to it (:func:`_classes`) the first."""
959
+ arr = np.asarray(scores, dtype=float)
960
+ low = float(arr.min())
961
+ if not math.isfinite(low):
962
+ return int(np.argmin(arr))
963
+ while True:
964
+ reach = float(arr[arr <= low + within].max())
965
+ if reach <= low:
966
+ break
967
+ low = reach
968
+ return int(np.argmax(arr <= low))
969
+
970
+
971
+ def _sectors(rel: np.ndarray) -> np.ndarray:
972
+ """Which of eight sectors of 45 degrees each direction lies in, the first about the x axis.
973
+
974
+ The candidates of a fragment stand every 7.5 degrees, and so every sixth of them exactly on the edge
975
+ between two sectors. The angle is rounded before it is divided: such a direction is in the sector
976
+ above the edge, and not in the one that the last bit of its angle happens to say."""
977
+ degrees = np.round(np.degrees(np.arctan2(rel[:, 1], rel[:, 0])), 6) % 360.0
978
+ return ((degrees + 22.5) // 45.0).astype(int) % 8
979
+
980
+
981
+ def _apart(points: np.ndarray, others: np.ndarray) -> np.ndarray:
982
+ """How far each of ``points`` is from each of ``others``: ``(len(points), len(others))``."""
983
+ dx = points[:, 0][:, None] - others[:, 0]
984
+ dy = points[:, 1][:, None] - others[:, 1]
985
+ return np.sqrt(dx * dx + dy * dy)
986
+
987
+
988
+ def _through_names(body: Body, port: Port, a: np.ndarray, b: np.ndarray, pos: np.ndarray, ang: np.ndarray,
989
+ mir: np.ndarray) -> np.ndarray:
990
+ """Does the visible part of a link, ``a[i] -> b[i]`` for the pose ``i``, run through a name of its
991
+ own body that it may not run through: the name of an atom (``port.clear_of``), or the body's own
992
+ name (``port.clear_of_name``)? One boolean for each pose."""
993
+ hit = np.zeros(len(a), dtype=bool)
994
+ if port.clear_of:
995
+ u0, u1, ur = body.upright_capsules(pos, ang, mir)
996
+ sel = list(port.clear_of)
997
+ gap = segments_distance(a[:, None, :], b[:, None, :], u0[:, sel, :], u1[:, sel, :]) - ur[None, sel]
998
+ hit |= (gap < 0.0).any(axis=1)
999
+ if port.clear_of_name and body.label is not None:
1000
+ centre = body.label_centre(pos, ang, mir)
1001
+ assert centre is not None
1002
+ off = np.array([max(0.0, (body.label.width - body.label.height) / 2.0), 0.0])
1003
+ gap = segments_distance(a, b, centre - off, centre + off) - (body.label.height / 2.0 + body.label.pad)
1004
+ hit |= gap < 0.0
1005
+ return hit
1006
+
1007
+
1008
+ def _labels_on_siblings(body: Body, a: np.ndarray, b: np.ndarray, label_t: np.ndarray) -> int:
1009
+ """How many labels of a body's drawn links stand on another drawn link of the same body, for the one
1010
+ pose whose visible link ends are ``a`` and ``b`` (``(1, K, 2)``) and whose labels are at ``label_t``."""
1011
+ idx = np.nonzero(body._has_dlabel)[0]
1012
+ if not len(idx):
1013
+ return 0
1014
+ d0, d1, dr = body.dlabel_capsules(a, b, label_t)
1015
+ count = 0
1016
+ for m, k in enumerate(idx):
1017
+ for j, sibling in enumerate(body.ports):
1018
+ if j != k and sibling.drawn and body.ports[k].drawn:
1019
+ gap = segments_distance(d0[:, m], d1[:, m], a[:, j], b[:, j]) - dr[m]
1020
+ count += int(gap[0] < 0.0)
1021
+ return count
1022
+
1023
+
1024
+ def layout_bodies(fld: LigandField, bodies: Sequence[Body], params: LayoutParams | None = None) -> LayoutResult:
1025
+ """Place ``bodies`` around the ligand described by ``fld``."""
1026
+ if not bodies:
1027
+ return LayoutResult({}, [], 0.0, 0, 0, 0, 0.0)
1028
+ return _Engine(fld, bodies, params or LayoutParams()).run()
1029
+
1030
+
1031
+ def layout_key(fld: LigandField, bodies: Sequence[Body], params: LayoutParams | None = None) -> str:
1032
+ """A digest of all that :func:`layout_bodies` depends on: where it is the same, so is the layout, and
1033
+ nothing has to be laid out again. What a figure is called, how it is coloured and what is written in it
1034
+ is not in it, unless it changes the size of something."""
1035
+ h = hashlib.blake2b(digest_size=20)
1036
+
1037
+ def put(value: Any) -> None:
1038
+ if isinstance(value, np.ndarray):
1039
+ h.update(f"{value.dtype.str}{value.shape}".encode())
1040
+ h.update(np.ascontiguousarray(value).tobytes())
1041
+ elif isinstance(value, (list, tuple)):
1042
+ h.update(f"[{len(value)}".encode())
1043
+ for item in value:
1044
+ put(item)
1045
+ else:
1046
+ h.update(repr(value).encode() + b"\0")
1047
+
1048
+ put(fld.key)
1049
+ for body in bodies:
1050
+ for f in fields(body):
1051
+ if f.name == "ports":
1052
+ for port in body.ports:
1053
+ put([getattr(port, p.name) for p in fields(port)])
1054
+ elif f.init and f.name != "payload":
1055
+ put(getattr(body, f.name))
1056
+ put(params or LayoutParams())
1057
+ return h.hexdigest()
1058
+
1059
+
1060
+ def audit_layout(fld: LigandField, bodies: Sequence[Body], poses: "dict[Any, Pose]",
1061
+ label_t: "Mapping[Any, Sequence[float]] | None" = None,
1062
+ params: LayoutParams | None = None) -> LayoutResult:
1063
+ """Measure a placement that was made elsewhere, without searching.
1064
+
1065
+ The poses may come from a stored layout or from a person dragging nodes;
1066
+ nothing is moved. What comes back is the same independent audit that closes
1067
+ every layout run -- overlaps, links through other bodies, crossings -- so a
1068
+ layout from outside is held to the standard of one from the engine. A body
1069
+ without a pose is reported as unplaced.
1070
+ """
1071
+ if not bodies:
1072
+ return LayoutResult({}, [], 0.0, 0, 0, 0, 0.0)
1073
+ engine = _Engine(fld, bodies, params or LayoutParams())
1074
+ unplaced = []
1075
+ for i, body in enumerate(engine.bodies):
1076
+ pose = poses.get(body.key)
1077
+ if pose is None:
1078
+ unplaced.append(i)
1079
+ continue
1080
+ at = list((label_t or {}).get(body.key, ()))
1081
+ if len(at) != body.n_ports:
1082
+ at = [0.5] * body.n_ports
1083
+ engine._set(i, np.array([pose.x, pose.y], dtype=float), pose.angle, pose.mirror, np.array(at, dtype=float))
1084
+ return engine._result(unplaced)