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,690 @@
1
+ """The detailed style, after LigPlot.
2
+
3
+ Every ligand atom and bond is drawn. A residue that makes a *directional*
4
+ contact (H-bond, salt bridge, halogen bond, metal coordination, pi interaction)
5
+ has the part of it that makes the contact drawn explicitly, in a second colour,
6
+ with the interaction line running atom to atom (or to a ring centroid, or to
7
+ a charged group, which can be shaded). A residue that only makes hydrophobic contacts is
8
+ an "eyelash": its name inside an arc of lashes that faces the ligand atoms it
9
+ touches, which carry matching spokes. No line is drawn for a hydrophobic
10
+ contact, because a line would claim a direction the contact does not have.
11
+ Beside a ligand that is drawn as a chain of residues one is, a fine one without
12
+ a distance: there a contact is not read off by what lies beside what.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import math
18
+ from dataclasses import dataclass, field, replace
19
+ from typing import TYPE_CHECKING, Sequence
20
+
21
+ import numpy as np
22
+
23
+ from ..confidence import PLAIN, Look, occupancy_factors
24
+ from ..depict import AtomLabel, DepAtom, DepBond, Depiction, LabelRun
25
+ from ..fragments import Fragment, build_fragment, conformations
26
+ from ..geometry import Point, free_direction, sub, unit
27
+ from ..interactions import InteractionType
28
+ from ..interactive import NUMBER
29
+ from ..layout import SPRINGS, Body, Port, Pose
30
+ from ..layout.body import LabelSpec
31
+ from ..residues import aromatic_rings, canonical_resname, is_nucleotide, written
32
+ from ..scene import Circle, Group, Line, Paint, Rect, Span, Text
33
+ from ..textmetrics import CAP_HEIGHT, text_width
34
+ from . import absence as other_protein
35
+ from .base import (CHAIN_CONTACT_LENGTH, STYLE_SETTINGS, Context, Drawn, PortInfo, ResidueGroup, Settings,
36
+ StyleDrawing, eyelash_items, eyelash_mark, finish_drawing, group_skeleton, halo_items, halo_radius,
37
+ hbond_direction, interaction_data, interaction_title, is_distance, label_size, lining_claims, link_items,
38
+ make_ports, marked_label, port_infos, predicted_items, predicted_style, residue_occupancy,
39
+ residue_plddt, share_label, spoke_items, spoke_reach, tag_slack)
40
+ from .ligand_draw import bond_items, coloured_bond_items, plddt_underlay
41
+ from .rings import ring_items, ring_reach, ring_title
42
+
43
+ if TYPE_CHECKING:
44
+ from ..consensus import ResidueShare
45
+
46
+ __all__ = ["DetailedStyle"]
47
+
48
+ #: Between the name of a residue and the share that is written under it.
49
+ _SHARE_GAP = 3.2
50
+
51
+ #: The plate a residue's name stands on where the figure colours by pLDDT: how far it reaches beyond
52
+ #: the letters to either side and above and below, and how round its corners are.
53
+ _PLATE = (3.2, 2.6, 3.0)
54
+
55
+ T = InteractionType
56
+
57
+ # Atoms a charged-group halo is drawn along, per residue.
58
+ _HALO_ATOMS = {
59
+ "ARG": ("CZ", "NE", "NH1", "NH2"), "ASP": ("CG", "OD1", "OD2"), "GLU": ("CD", "OE1", "OE2"),
60
+ "LYS": ("NZ",), "HIS": ("CG", "ND1", "CE1", "NE2", "CD2"),
61
+ }
62
+
63
+
64
+ @dataclass
65
+ class _Payload:
66
+ group: ResidueGroup
67
+ form: str # fragment | eyelash | chip
68
+ ports: list[PortInfo]
69
+ label_text: str
70
+ frag: Fragment | None = None
71
+ local: dict[str, Point] = field(default_factory=dict)
72
+ arc_radius: float = 0.0
73
+ plddt: float | None = None # the residue's own pLDDT
74
+ look: Look = PLAIN
75
+ occupancy: float | None = None # that of the residue's most persistent contact
76
+ #: Where a level of detail was asked for and the model has confidence: the look of every atom of
77
+ #: the fragment, by name (its own, or its residue's where the model gives one value for a residue).
78
+ own: "dict[str, Look] | None" = None
79
+ detail: "str | None" = None # the level that was asked for, if one was
80
+ share: "ResidueShare | None" = None # its name stands in a ring: the models that contact it
81
+ below: "str | None" = None # written under its name: the share of an ensemble, where no line has it
82
+
83
+ @property
84
+ def ident(self) -> str:
85
+ return self.group.node_ident
86
+
87
+
88
+ def _bands(pay: _Payload, dep: Depiction) -> "list[str | None]":
89
+ """The pLDDT band of every atom that is drawn of a residue: its own where it is drawn at its own, and the
90
+ residue's otherwise."""
91
+ return [(pay.own[a.name].band if pay.own is not None and a.name in pay.own else pay.look.band) for a in dep.atoms]
92
+
93
+
94
+ def _label_text(grp: ResidueGroup, look: Look = PLAIN) -> str:
95
+ return marked_label(grp.label + ("†" if grp.beyond else ""), look)
96
+
97
+
98
+ #: Beside a chain ligand a residue that makes hydrophobic contacts only is seated before the others:
99
+ #: its line is the shortest there is, so it has the fewest places to go.
100
+ _CHAIN_EYELASH_FIRST = 30.0
101
+
102
+
103
+ class DetailedStyle:
104
+ name = "detailed"
105
+
106
+ def __init__(self, settings: "Settings | None" = None) -> None:
107
+ self.settings = settings or STYLE_SETTINGS["detailed"]
108
+
109
+ def ligand_obstacles(self, ctx: Context, groups: "Sequence[ResidueGroup] | None" = None
110
+ ) -> list[tuple[float, float, float]]:
111
+ """Discs covering the contact spokes that will be drawn on ligand atoms."""
112
+ atoms: set[int] = set()
113
+ for grp in ctx.groups if groups is None else groups:
114
+ for r in grp.interactions:
115
+ if r.type is T.HYDROPHOBIC and r.ligand is not None and r.ligand.kind == "atom" \
116
+ and ctx.dep.home_of(r.ligand.atom) is None: # on a chain residue it is a line
117
+ atoms.add(r.ligand.atom)
118
+ return [(*ctx.dep.pos(a), spoke_reach(ctx.dep, a, ctx.metrics) + 0.5) for a in sorted(atoms)]
119
+
120
+ # ------------------------------------------------------------------ bodies
121
+ def bodies(self, ctx: Context) -> list[Body]:
122
+ return [self.body(ctx, grp) for grp in ctx.groups]
123
+
124
+ def body(self, ctx: Context, grp: ResidueGroup) -> Body:
125
+ return self._eyelash_body(ctx, grp) if grp.only_hydrophobic else self._fragment_body(ctx, grp)
126
+
127
+ def _eyelash_body(self, ctx: Context, grp: ResidueGroup) -> Body:
128
+ m = ctx.metrics
129
+ plddt = residue_plddt(ctx, grp)
130
+ look = ctx.look(plddt)
131
+ text = _label_text(grp, look)
132
+ share = ctx.share_of(grp)
133
+ if share is not None:
134
+ text += f" {share.n_models}/{share.n_total}" # an eyelash has no room for a ring
135
+ w = text_width(text, m.residue_font, bold=True)
136
+ h = CAP_HEIGHT * m.residue_font
137
+ occupancy = residue_occupancy(grp)
138
+ below = share_label(occupancy) if ctx.shares_written and share is None else None
139
+ if below:
140
+ # It has no line to write its share on: the share stands under its name.
141
+ w = max(w, text_width(below, m.distance_font))
142
+ h += _SHARE_GAP + CAP_HEIGHT * m.distance_font
143
+ arc = math.hypot(w / 2.0, h / 2.0) + 4.5
144
+ radius = arc + m.lash_length
145
+ infos = port_infos(ctx, grp, self.settings.labelled(ctx.options))
146
+ clearance = 4.5
147
+ ports = []
148
+ for info in infos:
149
+ if info.drawn:
150
+ # A residue of a chain ligand: the contact is a line from the lashes to the residue's box.
151
+ visible, least = (v * m.bond_length for v in CHAIN_CONTACT_LENGTH)
152
+ # Only a tag asks for more room here: a line without one keeps these two lengths.
153
+ written = label_size(info.shown, m.distance_font) if (info.tag and info.shown) else None
154
+ if written is not None:
155
+ # Its predicted aligned error is written on the line: it needs the room.
156
+ visible, least = max(visible, written[0] + 24.0), max(least, written[0] + 13.0)
157
+ ends = radius + info.target.extent + tag_slack(ctx.dep, info)
158
+ ports.append(Port((0.0, 0.0), info.target.point, ideal=ends + visible, min_length=ends + least,
159
+ weight=SPRINGS["eyelash"] / len(infos), drawn=True, port_radius=radius + 1.0,
160
+ target_radius=info.target.radius, target_caps=info.target.caps,
161
+ label_size=written))
162
+ continue
163
+ reach = max(spoke_reach(ctx.dep, a, m) for a in info.target.atoms)
164
+ ports.append(Port((0.0, 0.0), info.target.point, ideal=radius + clearance + reach + 3.0,
165
+ weight=SPRINGS["eyelash"] / len(infos), drawn=False))
166
+ return Body(key=grp.uid, kind="disc", shapes_p0=np.zeros((1, 2)), shapes_p1=np.zeros((1, 2)),
167
+ shapes_r=np.array([radius]),
168
+ ports=ports, ligand_clearance=clearance,
169
+ priority=_CHAIN_EYELASH_FIRST if any(i.drawn for i in infos) else 0.0,
170
+ payload=_Payload(grp, "eyelash", infos, text, arc_radius=arc, plddt=plddt, look=look,
171
+ occupancy=occupancy, below=below))
172
+
173
+ def _fragment_body(self, ctx: Context, grp: ResidueGroup) -> Body:
174
+ m = ctx.metrics
175
+ infos = port_infos(ctx, grp, self.settings.labelled(ctx.options))
176
+ involved: set[str] = set()
177
+ for info in infos:
178
+ if info.kind is T.HYDROPHOBIC and info.drawn:
179
+ continue # beside a chain ligand: a line from the residue, not from one of its atoms
180
+ if info.site_kind in ("atom", "ring", "group"):
181
+ involved |= set(info.site_atoms)
182
+ # The level that was asked for adds to the part that makes the contact; "box" draws no atoms at all.
183
+ level = "box" if self.settings.form_of(grp) == "names" else ctx.detail_of(grp)
184
+ like = None
185
+ if is_nucleotide(grp.resname):
186
+ # How this figure's contacts name the atoms of a nucleotide: every nucleotide is named so.
187
+ like = [n for g in ctx.groups for r in g.interactions
188
+ for n in (r.record.protein_atom or "", *r.record.protein_atoms) if n]
189
+ frag = (build_fragment(grp.resname, involved, m.bond_length * m.protein_bond_scale, level, like)
190
+ if involved and level != "box" else None)
191
+ if frag is None or any(i.site_kind == "residue" for i in infos):
192
+ return self._chip_body(ctx, grp, infos)
193
+
194
+ shape = self._conformation(ctx, frag, infos)
195
+ cx = sum(q[0] for q in shape.values()) / len(shape)
196
+ cy = sum(q[1] for q in shape.values()) / len(shape)
197
+ local = {a: (x - cx, y - cy) for a, (x, y) in shape.items()}
198
+ upright_pts: list[Point] = []
199
+ upright_wh: list[tuple[float, float]] = []
200
+ upright_of: dict[str, int] = {}
201
+ for a in frag.atoms:
202
+ if frag.elements[a] != "C":
203
+ upright_of[a] = len(upright_pts)
204
+ upright_pts.append(local[a])
205
+ upright_wh.append((text_width(written(a, ctx.options.atom_labels), m.protein_atom_font) + 1.0,
206
+ CAP_HEIGHT * m.protein_atom_font + 1.0))
207
+ p0: list[Point] = []
208
+ p1: list[Point] = []
209
+ rr: list[float] = []
210
+ for a, b, order in frag.bonds:
211
+ p0.append(local[a])
212
+ p1.append(local[b])
213
+ rr.append(m.protein_bond_width / 2.0 + 1.0 + (m.double_offset * 0.5 if order > 1 else 0.0))
214
+
215
+ hr = halo_radius(m) * m.protein_bond_scale
216
+ spoked: set[str] = set()
217
+
218
+ def locate(info: PortInfo):
219
+ if info.kind is T.HYDROPHOBIC and info.drawn:
220
+ # It leaves where the residue's name stands: at the alpha carbon of what is drawn of it.
221
+ return local[frag.root], 2.6, None, 3.0, None
222
+ if info.site_kind == "atom" or len(info.site_atoms) == 1:
223
+ name = info.site_atoms[0]
224
+ if not info.drawn:
225
+ spoked.add(name)
226
+ return local[name], 2.6, upright_of.get(name), (9.0 if name in upright_of else 3.0), None
227
+ pts = [local[n] for n in info.site_atoms]
228
+ centre = (sum(p[0] for p in pts) / len(pts), sum(p[1] for p in pts) / len(pts))
229
+ spread = max(math.hypot(q[0] - centre[0], q[1] - centre[1]) for q in pts)
230
+ if info.site_kind == "ring":
231
+ return centre, 3.6, None, spread, None
232
+ # A charged group: the link stops at its halo or at the labels of its atoms.
233
+ names = [n for n in _HALO_ATOMS.get(canonical_resname(grp.resname), info.site_atoms) if n in local]
234
+ chosen = set(names)
235
+ segs = [(local[a], local[b]) for a, b, _ in frag.bonds if a in chosen and b in chosen] \
236
+ or [(local[n], local[n]) for n in names]
237
+ caps = (np.array([q[0] for q in segs], dtype=float), np.array([q[1] for q in segs], dtype=float),
238
+ np.full(len(segs), hr + 1.0))
239
+ ups = tuple(upright_of[n] for n in names if n in upright_of)
240
+ return centre, 6.0, None, 0.62 * (spread + hr), (caps, ups)
241
+
242
+ ports = make_ports(ctx, infos, locate)
243
+ if level is not None:
244
+ # At a level a fragment has atoms that none of its lines ends on, and its lines come from
245
+ # the atoms beside a column, from more than one side. None of them runs through the name
246
+ # of an atom it does not end on, and one that ends on an atom does not run through the
247
+ # residue's name: forbidden in the layout and counted in the audit, as a line across the
248
+ # atoms beside a box is. (A line that leaves where the name stands ends on the name.)
249
+ for port, info in zip(ports, infos):
250
+ if info.drawn:
251
+ whole = info.kind is T.HYDROPHOBIC
252
+ ends_on = set() if whole else set(info.site_atoms)
253
+ port.clear_of = tuple(sorted(j for name, j in upright_of.items() if name not in ends_on))
254
+ port.clear_of_name = not whole
255
+ for name in sorted(spoked):
256
+ # Room for the contact spokes drawn on this atom.
257
+ p0.append(local[name])
258
+ p1.append(local[name])
259
+ rr.append(9.0)
260
+ root = local[frag.root]
261
+ bonded = [local[b if a == frag.root else a] for a, b, _ in frag.bonds if frag.root in (a, b)]
262
+ # The name goes into the widest gap between the bonds at the alpha carbon.
263
+ away = free_direction(root, bonded) if bonded else (-1.0, 0.0)
264
+ plddt = residue_plddt(ctx, grp)
265
+ look = ctx.look(plddt)
266
+ text = _label_text(grp, look)
267
+ lw, lh, gap = text_width(text, m.residue_font, bold=True) + 2.0, CAP_HEIGHT * m.residue_font + 3.0, 4.0
268
+ share = ctx.share_of(grp)
269
+ if share is not None:
270
+ # Its name stands in its ring, which touches what is drawn of it.
271
+ lw = lh = 2.0 * ring_reach(grp.label, share)
272
+ gap = 1.5
273
+ axis = unit(sub(root, ports[0].local), away)
274
+ if math.hypot(root[0] - ports[0].local[0], root[1] - ports[0].local[1]) < 1e-6:
275
+ axis = away
276
+ n_drawn = sum(1 for i in infos if i.drawn)
277
+ own = None
278
+ conf = ctx.confidence
279
+ if conf is not None and ctx.options.confidence and (
280
+ level is not None or (ctx.options.plddt_by_atom and conf.per_atom)):
281
+ # Every atom at its own pLDDT: at a level that was asked for, and without one where the model
282
+ # gives the atoms of a residue values of their own (``plddt_by_atom``).
283
+ own = {a: ctx.look(conf.atom(grp.key, a)) for a in frag.atoms}
284
+ return Body(
285
+ key=grp.uid, kind="fragment", shapes_p0=np.array(p0, dtype=float).reshape(-1, 2),
286
+ shapes_p1=np.array(p1, dtype=float).reshape(-1, 2), shapes_r=np.array(rr, dtype=float), ports=ports,
287
+ label=LabelSpec(anchor=root, direction=away, width=lw, height=lh, gap=gap),
288
+ rotatable=True, mirrorable=True, ligand_clearance=0.3 * m.bond_length, axis=axis,
289
+ priority=10.0 + n_drawn + 0.01 * len(frag.atoms),
290
+ upright_pts=np.array(upright_pts, dtype=float).reshape(-1, 2),
291
+ upright_wh=np.array(upright_wh, dtype=float).reshape(-1, 2),
292
+ payload=_Payload(grp, "fragment", infos, text, frag=frag, local=local, plddt=plddt, look=look,
293
+ # (With a ring the share is the ring's, and the atoms are drawn in full.)
294
+ occupancy=residue_occupancy(grp) if share is None else None, own=own, detail=level,
295
+ share=share))
296
+
297
+ @staticmethod
298
+ def _conformation(ctx: Context, frag: Fragment, infos: list[PortInfo]) -> dict[str, Point]:
299
+ """Pick the flat layout of a fragment whose contact atoms are spaced like their targets.
300
+
301
+ With one contact point the template layout is used. With several, the
302
+ distance between two contact atoms should resemble the distance between
303
+ the ligand sites they go to, so that both links can be short; a residue
304
+ reaching the ligand with backbone and side-chain tip is drawn kinked
305
+ rather than as a rod with one end stranded.
306
+ """
307
+ pts: list[tuple[tuple[str, ...], Point]] = []
308
+ for info in infos:
309
+ if info.kind is T.HYDROPHOBIC and info.drawn:
310
+ continue # beside a chain ligand it leaves from the residue, not from an atom
311
+ if info.site_kind in ("atom", "ring", "group") and info.site_atoms:
312
+ pts.append((info.site_atoms, info.target.point))
313
+ sites = {p[0] for p in pts}
314
+ if len(sites) < 2:
315
+ return dict(frag.xy)
316
+
317
+ def centre(xy: dict[str, Point], names: tuple[str, ...]) -> Point:
318
+ return (sum(xy[n][0] for n in names) / len(names), sum(xy[n][1] for n in names) / len(names))
319
+
320
+ slack = 1.2 * ctx.metrics.bond_length
321
+ best, best_score = dict(frag.xy), None
322
+ for n_flips, xy in enumerate(conformations(frag)):
323
+ score = 0.0
324
+ for i in range(len(pts)):
325
+ for j in range(i + 1, len(pts)):
326
+ if pts[i][0] == pts[j][0]:
327
+ continue
328
+ a, b = centre(xy, pts[i][0]), centre(xy, pts[j][0])
329
+ have = math.hypot(a[0] - b[0], a[1] - b[1])
330
+ want = math.hypot(pts[i][1][0] - pts[j][1][0], pts[i][1][1] - pts[j][1][1])
331
+ # Being a little further apart than the targets is free: links fan out.
332
+ score += max(0.0, abs(have - want) - slack) ** 2
333
+ score = round(score, 6)
334
+ if best_score is None or score < best_score - 1e-9:
335
+ best, best_score = xy, score
336
+ return best
337
+
338
+ def _chip_body(self, ctx: Context, grp: ResidueGroup, infos: list[PortInfo]) -> Body:
339
+ """A residue we have no template for: its name, with links ending on it."""
340
+ m = ctx.metrics
341
+ plddt = residue_plddt(ctx, grp)
342
+ look = ctx.look(plddt)
343
+ text = _label_text(grp, look)
344
+ wh = (text_width(text, m.residue_font, bold=True) + 4.0, CAP_HEIGHT * m.residue_font + 5.0)
345
+ share = ctx.share_of(grp)
346
+ if share is not None:
347
+ wh = (2.0 * ring_reach(grp.label, share),) * 2
348
+ ports = make_ports(ctx, infos, lambda info: ((0.0, 0.0), 0.0, 0, wh[0] / 2.0, None))
349
+ return Body(key=grp.uid, kind="disc", shapes_p0=np.zeros((0, 2)), shapes_p1=np.zeros((0, 2)),
350
+ shapes_r=np.zeros(0), ports=ports, ligand_clearance=6.0, priority=5.0,
351
+ upright_pts=np.array([(0.0, 0.0)]), upright_wh=np.array([wh]),
352
+ payload=_Payload(grp, "chip", infos, text, plddt=plddt, look=look,
353
+ occupancy=residue_occupancy(grp), detail=ctx.detail_of(grp), share=share))
354
+
355
+ # ------------------------------------------------------------------ drawing
356
+ def draw(self, ctx: Context, bodies: list[Body], poses: dict, label_ts: dict | None = None) -> StyleDrawing:
357
+ d = Drawn({"halos": [], "interactions": [], "contacts": [], "residues": []})
358
+ self.draw_bodies(ctx, bodies, poses, label_ts or {}, d)
359
+ return finish_drawing(ctx, self.settings, d)
360
+
361
+ def draw_bodies(self, ctx: Context, bodies: Sequence[Body], poses: dict, label_ts: dict, d: Drawn) -> None:
362
+ m = ctx.metrics
363
+ layers, kinds, notes = d.layers, d.kinds, d.notes
364
+ links = self.settings.lines
365
+
366
+ for body in bodies:
367
+ pose = poses.get(body.key)
368
+ if pose is None:
369
+ continue
370
+ pay: _Payload = body.payload
371
+ grp = pay.group
372
+ d.beyond = d.beyond or grp.beyond
373
+ P = np.array([[pose.x, pose.y]])
374
+ A = np.array([pose.angle])
375
+ M = np.array([pose.mirror])
376
+ a_all, b_all, _ = body.link_segments(P, A, M)
377
+ ports_w = body.ports_world(P, A, M)[0]
378
+ label_t = label_ts.get(body.key, ())
379
+ res_group = Group("residue", data={"residue": grp.ident, NUMBER: grp.numbered, "class": grp.residue_class,
380
+ "form": pay.form})
381
+ if grp.parts > 1:
382
+ res_group.data["drawing"] = f"{grp.part + 1} of {grp.parts}"
383
+ # A residue that only other models contact is set back like one outside the contact set.
384
+ away = grp.absent or grp.faint
385
+ muted = grp.beyond or away
386
+ label_fill = "beyond" if muted else "protein_label"
387
+ look = pay.look
388
+ occ_width, occ_opacity = occupancy_factors(pay.occupancy, ctx.options.occupancy_style == "steps")
389
+ if ctx.confidence is not None:
390
+ d.levels.add(look.level)
391
+ if pay.plddt is not None and look.band is not None:
392
+ res_group.data["plddt"] = f"{pay.plddt:.1f}"
393
+ res_group.data["confidence"] = look.band
394
+ res_group.title = f"{grp.label}: residue pLDDT {pay.plddt:.0f}"
395
+
396
+ if pay.detail is not None:
397
+ res_group.data["detail"] = pay.detail
398
+ mark: Group | None = None
399
+ if grp.lost:
400
+ d.lost = True
401
+ res_group.data[other_protein.FROM] = other_protein.said_of(ctx.options)
402
+ if not grp.faint:
403
+ mark = other_protein.marker_group(grp, ctx.options)
404
+ layers.setdefault("backdrop", []).append(mark)
405
+ frag_dep: Depiction | None = None
406
+ frag_index: dict[str, int] = {}
407
+ if pay.form == "fragment":
408
+ assert pay.frag is not None
409
+ frag_dep, frag_index = self._fragment_depiction(ctx, pay, pose)
410
+ d.atoms_at_level = d.atoms_at_level or pay.detail is not None
411
+ d.atoms_by_own = d.atoms_by_own or (pay.own is not None and pay.detail is None)
412
+ if pay.own is None:
413
+ # The fragment fades as one object, so bonds meeting at an atom do not add up.
414
+ drawn = Group("fragment", opacity=min(look.opacity * occ_opacity, 0.55 if away else 1.0))
415
+ self._draw_fragment(ctx, pay, frag_dep, drawn)
416
+ res_group.add(drawn)
417
+ else:
418
+ # Every atom at its own confidence: each level fades as one object.
419
+ d.levels.update(lk.level for lk in pay.own.values())
420
+ res_group.extend(self._fragment_by_atom(ctx, pay, frag_dep, occ_width,
421
+ 0.55 * occ_opacity if grp.faint else occ_opacity))
422
+ centre = body.label_centre(P, A, M)
423
+ assert centre is not None
424
+ lx, ly = float(centre[0, 0]), float(centre[0, 1])
425
+ if ctx.by_colour and not ctx.by_bond:
426
+ # The atoms that are drawn of the residue stand on colour, like those of the ligand:
427
+ # each at its own band where it is drawn at its own pLDDT, at the residue's otherwise.
428
+ under = plddt_underlay(frag_dep, _bands(pay, frag_dep))
429
+ if under is not None:
430
+ layers.setdefault("backdrop", []).append(under)
431
+ if mark is not None:
432
+ mark.extend(other_protein.skeleton(frag_dep, other_protein.UNDER * frag_dep.metrics.bond_length))
433
+ else:
434
+ lx, ly = pose.x, pose.y
435
+ # (A residue whose bonds have the colour says it with them.)
436
+ plate = "" if ctx.by_bond and pay.form == "fragment" else ctx.fill_of(look, "")
437
+ if plate:
438
+ # ... and its name stands on the colour of the residue's own band.
439
+ half_w = text_width(pay.label_text, m.residue_font, bold=look.level == 0) / 2.0 + _PLATE[0]
440
+ half_h = CAP_HEIGHT * m.residue_font / 2.0 + _PLATE[1]
441
+ res_group.add(Rect(lx - half_w, ly - half_h, 2.0 * half_w, 2.0 * half_h, Paint(fill=plate),
442
+ rx=_PLATE[2]))
443
+ label_fill = ctx.text_on(look, label_fill)
444
+ name_box = None
445
+ if pay.form == "fragment" and pay.detail is not None:
446
+ # Where the name is printed, for the lines that leave from where it stands (below).
447
+ half_w = text_width(pay.label_text, m.residue_font, bold=look.level == 0) / 2.0
448
+ half_h = CAP_HEIGHT * m.residue_font / 2.0
449
+ name_box = (lx - half_w, ly - half_h, lx + half_w, ly + half_h)
450
+ if pay.form == "eyelash":
451
+ targets = [info.target.point for info in pay.ports]
452
+ res_group.extend(eyelash_items((pose.x, pose.y), pay.arc_radius, targets, m,
453
+ opacity=min(look.opacity * occ_opacity,
454
+ 0.55 if muted else 1.0),
455
+ weight=look.width * occ_width))
456
+ if mark is not None:
457
+ mark.extend(eyelash_mark((pose.x, pose.y), pay.arc_radius, targets, m))
458
+ if mark is not None:
459
+ mark.add(other_protein.disc(lx, ly, ring_reach(grp.label, pay.share)) if pay.share is not None else
460
+ other_protein.plate(lx, ly, text_width(pay.label_text, m.residue_font, bold=look.level == 0),
461
+ CAP_HEIGHT * m.residue_font))
462
+ if pay.share is not None:
463
+ self._ring(ctx, body, pose, (lx, ly), res_group, d)
464
+ else:
465
+ if pay.below:
466
+ res_group.add(Text.plain(lx, ly + (CAP_HEIGHT * m.residue_font + _SHARE_GAP) / 2.0
467
+ + CAP_HEIGHT * m.distance_font / 2.0, pay.below, m.distance_font, "hydrophobic",
468
+ opacity=0.55 if muted else max(0.7, occ_opacity)))
469
+ ly -= (_SHARE_GAP + CAP_HEIGHT * m.distance_font) / 2.0
470
+ # The name stays legible at any confidence; its weight is the greyscale channel.
471
+ res_group.add(Text.plain(lx, ly + CAP_HEIGHT * m.residue_font / 2.0, pay.label_text, m.residue_font,
472
+ label_fill, bold=look.level == 0 and not away, italic=muted,
473
+ opacity=1.0 if look.level == 0 else max(0.72, look.opacity + 0.2)))
474
+ layers["residues"].append(res_group)
475
+ d.placed.append(((pose.x, pose.y), float(body.proper_radius),
476
+ ctx.fill_of(look, f"class_{grp.residue_class}")))
477
+ d.claims.extend(lining_claims(ctx, grp, look, pay.ports,
478
+ [(float(q[0]), float(q[1])) for q in ports_w]))
479
+
480
+ for k, info in enumerate(pay.ports):
481
+ if info.predicted:
482
+ d.predicted = True
483
+ elif info.kind is T.HYDROPHOBIC:
484
+ d.lashes = True
485
+ elif info.kind not in kinds:
486
+ kinds.append(info.kind)
487
+ d.absent = d.absent or info.absent
488
+ opacity = info.opacity
489
+ weight = info.weight
490
+ if info.plddt is not None:
491
+ d.levels.add(info.look.level)
492
+ d.occupancy = d.occupancy or info.occupancy is not None
493
+ first = info.interactions[0]
494
+ if not info.drawn:
495
+ # Hydrophobic: spokes on the ligand atom, and on the fragment atom if one is drawn.
496
+ port_pt = (float(ports_w[k][0]), float(ports_w[k][1]))
497
+ g = Group("contact hydrophobic", data=interaction_data(ctx, grp, info),
498
+ title=interaction_title(first, ctx.ligand, info.plddt, ctx.dep))
499
+ for atom in info.target.atoms:
500
+ g.extend(spoke_items(ctx.dep, atom, port_pt, m, opacity, weight))
501
+ if frag_dep is not None and info.site_kind == "atom" and info.site_atoms[0] in frag_index:
502
+ fm = frag_dep.metrics.with_(spoke_inner=4.5, spoke_outer=8.5)
503
+ g.extend(spoke_items(frag_dep, frag_index[info.site_atoms[0]], info.target.point, fm,
504
+ opacity, weight))
505
+ if g.items:
506
+ layers["contacts"].append(g)
507
+ if mark is not None:
508
+ mark.extend(other_protein.under(g.items, m.interaction_width))
509
+ continue
510
+ a = (float(a_all[0, k, 0]), float(a_all[0, k, 1]))
511
+ b = (float(b_all[0, k, 0]), float(b_all[0, k, 1]))
512
+ arrow = None
513
+ if info.kind in (T.HBOND, T.WATER_BRIDGE) and not info.predicted:
514
+ arrow, note = hbond_direction(first, ctx.dep)
515
+ if note:
516
+ notes.append(note)
517
+ g = Group(f"interaction {info.kind.value}", data=interaction_data(ctx, grp, info),
518
+ title="; ".join(interaction_title(r, ctx.ligand, info.plddt, ctx.dep)
519
+ for r in info.interactions))
520
+ at = label_t[k] if k < len(label_t) else 0.5
521
+ if name_box is not None and info.kind is T.HYDROPHOBIC:
522
+ # A contact with the residue as a whole leaves where the residue's name stands. At a
523
+ # level of detail a fragment stands where its atom's partner is, which is beside the
524
+ # column and not on it, and such a line can come from the side the name is on: it
525
+ # then ends on the name, as the lines of a residue that is a name alone do.
526
+ a, at = _from_the_name(a, b, at, name_box)
527
+ style = links.styles[info.kind]
528
+ if info.predicted:
529
+ # A guess is drawn as a different kind of line, with its label set off as a node.
530
+ g.extend(predicted_items(a, b, info, at, m, predicted_style(style), opacity,
531
+ ctx.options.solvent_mark))
532
+ else:
533
+ if info.kind is T.HBOND:
534
+ style, which = links.hbond(info, grp)
535
+ d.hbonds.add(which)
536
+ g.extend(link_items(a, b, info.kind, m, label=info.label, arrow=arrow, opacity=opacity,
537
+ label_at=at, weight=weight, tag=info.tag, style=style, glow=info.glow))
538
+ d.glows = d.glows or info.glow is not None
539
+ if info.tag is not None:
540
+ d.tags.append(info.tag[1])
541
+ d.has_distances = d.has_distances or is_distance(info.label)
542
+ if info.target.kind == "ring":
543
+ key = (info.target.atoms, style.token)
544
+ if key not in d.dots_done:
545
+ d.dots_done.add(key)
546
+ tp = info.target.point
547
+ g.add(Circle(tp[0], tp[1], 2.5, _fill(style.token, opacity)))
548
+ if info.site_kind == "ring" and pay.form == "fragment":
549
+ pp = ports_w[k]
550
+ g.add(Circle(float(pp[0]), float(pp[1]), 2.3, _fill(style.token, opacity)))
551
+ layers["interactions"].append(g)
552
+ if mark is not None:
553
+ mark.add(other_protein.stroke([a, b], m.interaction_width))
554
+ if info.target.kind == "group" and ctx.options.charge_halos:
555
+ key = (info.target.atoms, style.token)
556
+ if key not in d.halo_done:
557
+ d.halo_done.add(key)
558
+ layers["halos"].extend(halo_items(group_skeleton(ctx.dep, info.target.atoms),
559
+ halo_radius(m), style.token))
560
+ if info.site_kind == "group" and frag_dep is not None and ctx.options.charge_halos:
561
+ names = [n for n in _HALO_ATOMS.get(canonical_resname(grp.resname), info.site_atoms)
562
+ if n in frag_index]
563
+ res_key = (grp.uid, style.token)
564
+ if names and res_key not in d.halo_done:
565
+ d.halo_done.add(res_key)
566
+ layers["halos"].extend(halo_items(
567
+ group_skeleton(frag_dep, [frag_index[n] for n in names]),
568
+ halo_radius(m) * m.protein_bond_scale, style.token))
569
+
570
+ @staticmethod
571
+ def _ring(ctx: Context, body: Body, pose: Pose, at: Point, group: Group, d: Drawn) -> None:
572
+ """The name of a residue in its ring, and a bond to the ring from the atom that the name belongs to."""
573
+ grp, share = body.payload.group, body.payload.share
574
+ d.rings = True
575
+ if grp.residue_class not in d.classes:
576
+ d.classes.append(grp.residue_class)
577
+ group.title = ring_title(grp.label, share)
578
+ group.data["n-models"] = f"{share.n_models}/{share.n_total}"
579
+ if body.label is not None:
580
+ x, y = pose.apply(body.label.anchor)
581
+ far, inside = math.hypot(at[0] - x, at[1] - y), ring_reach(grp.label, share) - 1.0
582
+ if far > inside:
583
+ group.add(Line(x, y, at[0] - (at[0] - x) / far * inside, at[1] - (at[1] - y) / far * inside,
584
+ Paint(stroke="protein_bond", width=ctx.metrics.protein_bond_width)))
585
+ group.extend(ring_items(at[0], at[1], grp.label, share, f"class_{grp.residue_class}"))
586
+
587
+ def _fragment_depiction(self, ctx: Context, pay: _Payload, pose: Pose) -> tuple[Depiction, dict[str, int]]:
588
+ """The fragment on the page, as a small depiction the bond drawer understands."""
589
+ frag = pay.frag
590
+ assert frag is not None
591
+ m = ctx.metrics
592
+ fm = m.with_(bond_width=m.protein_bond_width * pay.look.width * occupancy_factors(pay.occupancy, ctx.options.occupancy_style == "steps")[0],
593
+ double_offset=m.double_offset * 0.8,
594
+ label_gap=1.5,
595
+ atom_font=m.protein_atom_font, bond_length=m.bond_length * m.protein_bond_scale)
596
+ index = {a: i for i, a in enumerate(frag.atoms)}
597
+ ring_atoms = {a for ring in aromatic_rings(frag.resname) for a in ring}
598
+ atoms = []
599
+ for a in frag.atoms:
600
+ x, y = pose.apply(pay.local[a])
601
+ atom = DepAtom(idx=index[a], x=x, y=y, element=frag.elements[a], name=a, aromatic=a in ring_atoms)
602
+ if frag.elements[a] != "C":
603
+ word = written(a, ctx.options.atom_labels)
604
+ w = text_width(word, fm.atom_font)
605
+ cap = CAP_HEIGHT * fm.atom_font
606
+ box = (x - w / 2.0, y - cap / 2.0, x + w / 2.0, y + cap / 2.0)
607
+ atom.label = AtomLabel((LabelRun(x, y + cap / 2.0, "middle", (Span(word),), box),), box)
608
+ atoms.append(atom)
609
+ bonds = [DepBond(index[a], index[b], order) for a, b, order in frag.bonds]
610
+ rings = [tuple(index[a] for a in ring) for ring in frag.rings]
611
+ return Depiction(atoms=atoms, bonds=bonds, rings=rings, n_heavy=len(atoms), metrics=fm), index
612
+
613
+ def _fragment_by_atom(self, ctx: Context, pay: _Payload, dep: Depiction, occ_width: float,
614
+ occ_opacity: float) -> list[Group]:
615
+ """The fragment with every atom at its own look: a bond at the weaker of its two ends, and one
616
+ group for each level of confidence, the weakest underneath."""
617
+ assert pay.frag is not None and pay.own is not None
618
+ m = ctx.metrics
619
+ looks = [pay.own[a] for a in pay.frag.atoms]
620
+ out: list[Group] = []
621
+ for level in sorted({lk.level for lk in looks}, reverse=True):
622
+ seen = next(lk for lk in looks if lk.level == level)
623
+ fine = replace(dep, metrics=dep.metrics.with_(bond_width=m.protein_bond_width * seen.width * occ_width))
624
+ part = Group("fragment", opacity=seen.opacity * occ_opacity)
625
+ if seen.band is not None:
626
+ part.data["confidence"] = seen.band
627
+ for bond in fine.bonds:
628
+ if max(looks[bond.a].level, looks[bond.b].level) == level:
629
+ part.extend(coloured_bond_items(fine, bond, [lk.band for lk in looks], "protein_bond") if ctx.by_bond
630
+ else bond_items(fine, bond, stroke="protein_bond"))
631
+ for atom in fine.atoms:
632
+ if atom.label is None or looks[atom.idx].level != level:
633
+ continue
634
+ token = ctx.palette.element_token(atom.element, on_protein=True)
635
+ for run in atom.label.runs:
636
+ part.add(Text(run.x, run.y, run.spans, fine.metrics.atom_font, token, run.anchor))
637
+ if part.items:
638
+ out.append(part)
639
+ return out
640
+
641
+ def _draw_fragment(self, ctx: Context, pay: _Payload, dep: Depiction, out: Group) -> None:
642
+ for bond in dep.bonds:
643
+ out.extend(coloured_bond_items(dep, bond, _bands(pay, dep), "protein_bond") if ctx.by_bond
644
+ else bond_items(dep, bond, stroke="protein_bond"))
645
+ for atom in dep.atoms:
646
+ if atom.label is None:
647
+ continue
648
+ token = ctx.palette.element_token(atom.element, on_protein=True)
649
+ for run in atom.label.runs:
650
+ out.add(Text(run.x, run.y, run.spans, dep.metrics.atom_font, token, run.anchor))
651
+
652
+
653
+ #: How far from the name of its residue a line stops that ends on the name.
654
+ _NAME_GAP = 2.0
655
+
656
+
657
+ def _from_the_name(a: Point, b: Point, at: float, name: "tuple[float, float, float, float]") -> tuple[Point, float]:
658
+ """A line from ``a`` (at its residue) to ``b`` that runs through the residue's name (the box of
659
+ its text): the point it starts from instead, :data:`_NAME_GAP` beyond the name on the way to
660
+ ``b``, and where its label is along the shortened line (``at`` is its place along the whole one;
661
+ the label stays where it was, or goes to the new start if it stood on the part that is gone).
662
+ Unchanged if the line does not meet the name, or ends in it."""
663
+ dx, dy = b[0] - a[0], b[1] - a[1]
664
+
665
+ def within(box: "tuple[float, float, float, float]") -> "tuple[float, float] | None":
666
+ t0, t1 = 0.0, 1.0
667
+ for p, q in ((-dx, a[0] - box[0]), (dx, box[2] - a[0]), (-dy, a[1] - box[1]), (dy, box[3] - a[1])):
668
+ if abs(p) < 1e-9:
669
+ if q < 0.0:
670
+ return None
671
+ continue
672
+ r = q / p
673
+ if p < 0.0:
674
+ t0 = max(t0, r)
675
+ else:
676
+ t1 = min(t1, r)
677
+ return (t0, t1) if t0 < t1 else None
678
+
679
+ if within(name) is None:
680
+ return a, at
681
+ around = within((name[0] - _NAME_GAP, name[1] - _NAME_GAP, name[2] + _NAME_GAP, name[3] + _NAME_GAP))
682
+ assert around is not None
683
+ leaves = around[1]
684
+ if leaves >= 1.0:
685
+ return a, at
686
+ return (a[0] + dx * leaves, a[1] + dy * leaves), max(0.0, (at - leaves) / (1.0 - leaves))
687
+
688
+
689
+ def _fill(token: str, opacity: float):
690
+ return Paint(fill=token, opacity=opacity)