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
bindview/compare.py ADDED
@@ -0,0 +1,1854 @@
1
+ """Comparing ligands of one pocket: the difference view (two) and the consensus view (n).
2
+
3
+ One design rule carries both views: **the residues are the invariant, the
4
+ ligand is the variable.** The pocket is laid out once, as a frame of residue
5
+ nodes, and what changes from ligand to ligand is drawn against that frame. A
6
+ residue never moves between panels, so a difference between two panels is a
7
+ difference between two ligands and nothing else.
8
+
9
+ * **Difference view** -- two panels on one frame. Each panel shows one ligand
10
+ and its contacts; a node says whether its residue is contacted by both
11
+ ligands, by this one only, or by the other one only. That classification,
12
+ taken per (residue, interaction type), is the figure, and it is also returned
13
+ as data.
14
+ * **Consensus view** -- one frame, one node per residue, each annotated with
15
+ how many ligands of the set contact it and through which interaction types.
16
+ No per-ligand lines are drawn at any set size: past two or three ligands they
17
+ are what makes such figures unreadable, and conservation is the signal.
18
+
19
+ Whether the ligands are drawn on a common scaffold is decided by
20
+ :mod:`bindview.align` and stated in the figure either way. Each contact keeps the
21
+ confidence of the model it comes from (:mod:`bindview.confidence`); in the
22
+ consensus view the ring around a node is drawn heavy only for the ligands whose
23
+ contact is confidently predicted.
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import copy
29
+ import math
30
+ from dataclasses import dataclass, field, replace
31
+ from pathlib import Path
32
+ from typing import Any, Sequence
33
+
34
+ import numpy as np
35
+
36
+ from .align import (MIN_ATOMS, MIN_FRACTION, CommonCore, core_coords, find_common_core, pocket_transforms,
37
+ pose_coords, pose_frame)
38
+ from .confidence import LOOKS, MARK, PLAIN, Look, look_of
39
+ from .depict import Depiction, depict_ligand
40
+ from .diagram import (_PT_PER_PX, _PX_PER_MM, Diagram, Quality, RenderResult, _better, _confidence_strip, _dedupe,
41
+ _scaled, _set_fans)
42
+ from .errors import RenderError
43
+ from .fingerprint import TYPE_ORDER, Bit, ConsensusRow, Fingerprint, FingerprintTable
44
+ from .graph import Contact, Graph, Node
45
+ from .graphbuild import LigandPart, engine_springs, link_references, poses_from, residue_contacts, unique_ids
46
+ from .geometry import polygon_area, resample_closed
47
+ from .interactions import Interaction, InteractionType
48
+ from .interactive import NOTHING_TO_POINT_AT, NUMBER, ROOT_CLASS
49
+ from .layout import Body, LayoutParams, LayoutResult, LigandField, Port, Pose, layout_bodies
50
+ from .residues import format_residue_label, is_backbone_atom, residue_class
51
+ from .resolve import ResolvedInteraction
52
+ from .scene import Circle, Group, Item, Line, Paint, Polyline, Rect, Scene, Span, Text, items_bounds
53
+ from .styles.base import (Context, LegendEntry, RenderOptions, beyond_any_page, charge_legend, confidence_legend,
54
+ group_residues, group_skeleton, too_small_on_page,
55
+ halo_items, halo_radius, hbond_direction, interaction_data, interaction_title,
56
+ legend_group, link_items, link_legend, make_ports, port_infos, residue_plddt)
57
+ from .styles.ligand_draw import atom_looks, draw_ligand
58
+ from .styles.schematic import _CLASS_LABEL, _CLASS_ORDER, _HBOND_SIDECHAIN, _STYLES, _merge_by_target
59
+ from .styles.summary import text_block, wrap_text
60
+ from .svg import svg_and_css
61
+ from .textmetrics import CAP_HEIGHT, text_width
62
+ from .structure import ResidueKey
63
+ from .theme import Metrics, Palette, get_palette, scheme
64
+
65
+ __all__ = ["Comparison", "Difference", "VIEWS", "TYPE_CODES"]
66
+
67
+ T = InteractionType
68
+ VIEWS = ("difference", "consensus")
69
+
70
+ #: Short codes for interaction types, printed on nodes where a line would not do.
71
+ TYPE_CODES: dict[InteractionType, str] = {
72
+ T.HYDROPHOBIC: "hyd", T.HBOND: "HB", T.SALTBRIDGE: "SB", T.PI_STACKING: "π–π",
73
+ T.PI_CATION: "π–cat", T.HALOGEN: "XB", T.METAL: "M", T.WATER_BRIDGE: "wat",
74
+ T.COVALENT: "cov",
75
+ }
76
+ _CODE_TOKEN = {T.HYDROPHOBIC: "hydrophobic", T.HBOND: "sch_hbond", T.SALTBRIDGE: "sch_saltbridge",
77
+ T.PI_STACKING: "sch_pi_stacking", T.PI_CATION: "sch_pi_cation", T.HALOGEN: "sch_halogen",
78
+ T.METAL: "sch_metal", T.WATER_BRIDGE: "sch_water_bridge", T.COVALENT: "ligand_bond"}
79
+
80
+ _FONT = 9.5 # residue name and number in a node
81
+ _NOTE = 8.5 # annotations under a node
82
+ _THUMB_FONT = 7.5 # smallest text of a ligand thumbnail
83
+ _BOND_LENGTHS = (26.0, 22.0, 19.0)
84
+ _SUBSTITUENT = "‡" # double dagger: contacted only through atoms outside the common core
85
+ _FADED = Look(None, width=0.8, opacity=0.45, level=1)
86
+
87
+
88
+ # ---------------------------------------------------------------------------
89
+ # Data
90
+ # ---------------------------------------------------------------------------
91
+
92
+ @dataclass(frozen=True)
93
+ class Difference:
94
+ """Contacts of two ligands, classified. A contact is a (residue, interaction type) pair, and a residue is
95
+ a chain, a number and an insertion code, whatever the two structures call it: a shared contact carries the
96
+ name that the first ligand's structure gives its residue."""
97
+
98
+ names: tuple[str, str]
99
+ shared: tuple[Bit, ...]
100
+ only_a: tuple[Bit, ...]
101
+ only_b: tuple[Bit, ...]
102
+
103
+ @property
104
+ def tanimoto(self) -> float:
105
+ """How alike the two are: shared bits over all bits."""
106
+ total = len(self.shared) + len(self.only_a) + len(self.only_b)
107
+ return len(self.shared) / total if total else 1.0
108
+
109
+ def residues(self) -> dict[tuple[str, int, str], str]:
110
+ """Each contacted residue as ``"shared"``, ``"a"`` or ``"b"`` (contacted by both ligands
111
+ in any way, or by one of them only)."""
112
+ in_a = {b.residue for b in self.shared + self.only_a}
113
+ in_b = {b.residue for b in self.shared + self.only_b}
114
+ return {res: "shared" if (res in in_a and res in in_b) else ("a" if res in in_a else "b")
115
+ for res in sorted(in_a | in_b)}
116
+
117
+ def as_dict(self) -> dict[str, Any]:
118
+ """The classification as plain data."""
119
+ return {"ligands": list(self.names), "tanimoto": round(self.tanimoto, 3),
120
+ "shared": [b.column for b in self.shared], "only_a": [b.column for b in self.only_a],
121
+ "only_b": [b.column for b in self.only_b],
122
+ "residues": {f"{k[0]}:{k[1]}{k[2]}": v for k, v in self.residues().items()}}
123
+
124
+
125
+ @dataclass
126
+ class _Node:
127
+ """What a frame body stands for."""
128
+
129
+ key: tuple[str, int, str]
130
+ resname: str
131
+ name: str # text in the node, first line
132
+ number: str # second line
133
+ radius: float
134
+ infos: list[list] = field(default_factory=list) # per ligand: PortInfo list
135
+ spans: list[tuple[int, int]] = field(default_factory=list) # per ligand: its slice of the body's ports
136
+ note_at: float = 0.0 # y offset of the annotation below the centre
137
+ ring: float = 0.0 # radius of the conservation ring (consensus view)
138
+ row: ConsensusRow | None = None
139
+
140
+ @property
141
+ def ident(self) -> str:
142
+ chain, number, icode = self.key
143
+ return f"{chain}:{self.resname}{number}{icode}" if chain else f"{self.resname}{number}{icode}"
144
+
145
+ @property
146
+ def numbered(self) -> str:
147
+ return f"{self.key[1]}{self.key[2]}"
148
+
149
+
150
+ @dataclass
151
+ class _Frame:
152
+ """A laid-out residue frame and what is drawn against it."""
153
+
154
+ m: Metrics
155
+ bodies: list[Body]
156
+ layout: LayoutResult
157
+ contexts: list[Context]
158
+ mode: str # core | pose | own | envelope | sequence
159
+ fld: LigandField | None = None
160
+ extra: dict[str, Any] = field(default_factory=dict)
161
+ #: The frame as a graph, and the poses read back out of it: what the panels are drawn from.
162
+ graph: Graph | None = None
163
+ poses: dict[Any, Pose] = field(default_factory=dict)
164
+ label_t: dict[Any, tuple[float, ...]] = field(default_factory=dict)
165
+
166
+
167
+ def _origins(scene: Scene) -> tuple[list[tuple[float, float]], tuple[float, float] | None, Group | None]:
168
+ """Where the diagram frames and the legend ended up on the page: the page offset of every
169
+ ``diagram`` group in drawing order, and of the legend with the legend group itself."""
170
+ frames: list[tuple[float, float]] = []
171
+ found: list[tuple[tuple[float, float], Group]] = []
172
+
173
+ def walk(items: Sequence[Item], dx: float, dy: float) -> None:
174
+ for it in items:
175
+ if not isinstance(it, Group):
176
+ continue
177
+ tx, ty = it.translate or (0.0, 0.0)
178
+ if it.cls == "diagram":
179
+ frames.append((dx + tx, dy + ty))
180
+ elif it.cls == "legend":
181
+ found.append(((dx + tx, dy + ty), it))
182
+ else:
183
+ walk(it.items, dx + tx, dy + ty)
184
+ walk(scene.items, 0.0, 0.0)
185
+ return frames, (found[0][0] if found else None), (found[0][1] if found else None)
186
+
187
+
188
+ def _on_page(graph: Graph, scene: Scene) -> Graph:
189
+ """A copy of a frame's graph with what only the finished page knows: origin, size, legend."""
190
+ out = copy.deepcopy(graph)
191
+ frames, legend_at, legend = _origins(scene)
192
+ if frames:
193
+ out.origin = frames[0]
194
+ out.size = (scene.width, scene.height)
195
+ for panel, at in zip(out.panels, frames):
196
+ panel["origin"] = [at[0], at[1]]
197
+ if legend is not None and legend_at is not None:
198
+ box = items_bounds(legend.items) or (0.0, 0.0, 0.0, 0.0)
199
+ out.nodes.append(Node(id="legend", kind="legend", label="Legend", x=legend_at[0] - out.origin[0],
200
+ y=legend_at[1] - out.origin[1],
201
+ attrs={"width": round(box[2] - box[0], 3), "height": round(box[3] - box[1], 3),
202
+ "offset": [0.0, 0.0]}))
203
+ return out
204
+
205
+
206
+ def _residue_of(hit: ResolvedInteraction) -> tuple[str, int, str]:
207
+ """The residue of a record as a comparison keys it: on the chain the structure resolved it to, which the
208
+ record's own table may leave empty."""
209
+ rec = hit.record
210
+ return (hit.residue.chain if hit.residue is not None else rec.chain, rec.residue_number, rec.insertion_code)
211
+
212
+
213
+ def _arc(cx: float, cy: float, r: float, a0: float, a1: float) -> tuple[tuple[float, float], ...]:
214
+ n = max(2, int(math.ceil(abs(a1 - a0) * r / 2.5)))
215
+ return tuple((cx + r * math.cos(a0 + (a1 - a0) * k / n), cy + r * math.sin(a0 + (a1 - a0) * k / n))
216
+ for k in range(n + 1))
217
+
218
+
219
+ def _merge(deps: Sequence[Depiction], m: Metrics) -> Depiction:
220
+ """Several drawings in one frame, as one obstacle for the layout."""
221
+ atoms: list = []
222
+ bonds: list = []
223
+ rings: list = []
224
+ off = 0
225
+ for dep in deps:
226
+ atoms.extend(replace(a, idx=a.idx + off) for a in dep.atoms)
227
+ bonds.extend(replace(b, a=b.a + off, b=b.b + off) for b in dep.bonds)
228
+ rings.extend(tuple(i + off for i in ring) for ring in dep.rings)
229
+ off += len(dep.atoms)
230
+ return Depiction(atoms=atoms, bonds=bonds, rings=rings, n_heavy=len(atoms), metrics=m)
231
+
232
+
233
+ def _frame_depiction(lig: Any, m: Metrics, xy: dict[str, tuple[float, float]]) -> Depiction:
234
+ """A ligand drawn on frame coordinates.
235
+
236
+ Coordination lines are kept only where the two atoms ended up next to each
237
+ other: a counter-ion that was set down beside the drawing would otherwise
238
+ be tied to its donors by lines running across the whole molecule.
239
+ """
240
+ dep = depict_ligand(lig, m, coords=xy, normalise=False)
241
+ limit = 2.2 * m.bond_length
242
+ dep.bonds = [b for b in dep.bonds if b.kind != "coordination"
243
+ or math.dist(dep.pos(b.a), dep.pos(b.b)) <= limit]
244
+ return dep
245
+
246
+
247
+ def _node_body(node: _Node, body_radius: float, ports: list[Port], note: tuple[float, float] | None,
248
+ priority: float, clearance: float) -> Body:
249
+ pts = np.zeros((0, 2))
250
+ wh = np.zeros((0, 2))
251
+ if note is not None:
252
+ node.note_at = body_radius + 2.0
253
+ pts = np.array([(0.0, body_radius + 2.0 + note[1] / 2.0)])
254
+ wh = np.array([note])
255
+ return Body(key=node.key, kind="disc", shapes_p0=np.zeros((1, 2)), shapes_p1=np.zeros((1, 2)),
256
+ shapes_r=np.array([body_radius]), ports=ports, ligand_clearance=clearance, priority=priority,
257
+ upright_pts=pts, upright_wh=wh, payload=node)
258
+
259
+
260
+ def _node_text(resname: str, key: tuple[str, int, str], with_chain: bool) -> tuple[str, str]:
261
+ num = f"{key[1]}{key[2]}"
262
+ return resname.upper(), (f"{key[0]}:{num}" if with_chain and key[0] else num)
263
+
264
+
265
+ def _node_radius(name: str, number: str) -> float:
266
+ width = max(text_width(name, _FONT, bold=True), text_width(number, _FONT))
267
+ return max(15.0, math.hypot(width / 2.0, CAP_HEIGHT * _FONT + 1.1) + 2.2)
268
+
269
+
270
+ def _code_spans(kinds: Sequence[InteractionType], prefix: str = "", counts: "dict | None" = None,
271
+ sep: str = " ") -> tuple[tuple[Span, ...], float]:
272
+ """Type codes as coloured spans, with the width they take at the annotation size."""
273
+ spans: list[Span] = []
274
+ width = 0.0
275
+ for i, kind in enumerate(kinds):
276
+ lead = (sep if i else "") + prefix
277
+ text = TYPE_CODES[kind] + (f" {counts[kind]}" if counts else "")
278
+ if lead:
279
+ spans.append(Span(lead))
280
+ width += text_width(lead, _NOTE)
281
+ spans.append(Span(text, fill=_CODE_TOKEN[kind]))
282
+ width += text_width(text, _NOTE)
283
+ return tuple(spans), width
284
+
285
+
286
+ def _range(values: Sequence[float], digits: int) -> str:
287
+ lo, hi = min(values), max(values)
288
+ return f"{lo:.{digits}f}" if round(lo, digits) == round(hi, digits) else f"{lo:.{digits}f}–{hi:.{digits}f}"
289
+
290
+
291
+ class _Page:
292
+ """Blocks stacked top to bottom on a page sized to fit them."""
293
+
294
+ def __init__(self, m: Metrics) -> None:
295
+ self.m = m
296
+ self.blocks: list[tuple[Group, float, float, float]] = []
297
+
298
+ def add(self, group: Group, width: float, height: float, gap: float = 10.0) -> None:
299
+ if height > 0:
300
+ self.blocks.append((group, width, height, gap))
301
+
302
+ def text(self, text: str, wrap: float, fill: str = "text_muted", cls: str = "statement", gap: float = 6.0,
303
+ size: float | None = None, bold: bool = False) -> None:
304
+ size = size or self.m.caption_font
305
+ lines = wrap_text(text, size, wrap, bold)
306
+ items, h = text_block(lines, 0.0, 0.0, size, fill, bold=bold)
307
+ self.add(Group(cls, items), max((text_width(ln, size, bold) for ln in lines), default=0.0), h, gap)
308
+
309
+ def build(self, title: str | None, subtitle: str | None, banner: str | None, scene_title: str,
310
+ description: str = "") -> Scene:
311
+ m = self.m
312
+ pad = m.margin
313
+ inner = max([150.0] + [w for _, w, _, _ in self.blocks])
314
+ if title:
315
+ inner = max(inner, text_width(title, m.title_font, bold=True))
316
+ if subtitle:
317
+ inner = max(inner, text_width(subtitle, m.caption_font))
318
+ items: list[Item] = []
319
+ y = pad
320
+ lines: list[str] = []
321
+ if banner:
322
+ lines = wrap_text(banner, m.title_font, max(inner, 330.0), bold=True)
323
+ inner = max(inner, max(text_width(ln, m.title_font, bold=True) for ln in lines))
324
+ y += len(lines) * m.title_font * 1.45 + pad * 0.9
325
+ if title:
326
+ items.append(Text.plain(pad, y + CAP_HEIGHT * m.title_font, title, m.title_font, "text", anchor="start",
327
+ bold=True))
328
+ y += m.title_font * 1.5
329
+ if subtitle:
330
+ items.append(Text.plain(pad, y + CAP_HEIGHT * m.caption_font, subtitle, m.caption_font, "text_muted",
331
+ anchor="start"))
332
+ y += m.caption_font * 1.6
333
+ for i, (group, _w, h, gap) in enumerate(self.blocks):
334
+ y += gap if (i or items) else 0.0
335
+ outer = Group("block", [group])
336
+ outer.translate = (pad, y)
337
+ items.append(outer)
338
+ y += h
339
+ width, height = inner + 2.0 * pad, y + pad
340
+ scene = Scene(width, height, title=scene_title, description=description)
341
+ scene.items = items
342
+ if lines:
343
+ bh = len(lines) * m.title_font * 1.45 + pad * 0.5
344
+ text_items, _ = text_block(lines, pad, pad * 0.35, m.title_font, "background", bold=True)
345
+ flag = Group("model-flag", [Rect(0.0, 0.0, width, bh, Paint(fill="warning"))] + text_items,
346
+ data={"trusted": "false"})
347
+ frame = Rect(1.5, 1.5, width - 3.0, height - 3.0, Paint(stroke="warning", width=3.0, join="miter"))
348
+ scene.items = [flag] + scene.items + [Group("model-flag-frame", [frame])]
349
+ return scene
350
+
351
+
352
+ # ---------------------------------------------------------------------------
353
+ # The comparison
354
+ # ---------------------------------------------------------------------------
355
+
356
+ class Comparison:
357
+ """Two or more ligands of one pocket, each built as a :class:`~bindview.diagram.Diagram`.
358
+
359
+ ``names`` label the ligands in figures and fingerprints (default: each
360
+ diagram's ``name``). The residue numbering is taken to be the same in all
361
+ structures -- that is what makes the residues an invariant. A residue is
362
+ its chain, number and insertion code: one that two structures give two
363
+ names (a point mutant among them) is one residue, in the figures, in
364
+ :meth:`difference` and in :meth:`consensus`, and a warning names it.
365
+ """
366
+
367
+ def __init__(self, diagrams: Sequence[Diagram], names: Sequence[str] | None = None, *,
368
+ min_fraction: float = MIN_FRACTION, min_atoms: int = MIN_ATOMS) -> None:
369
+ if len(diagrams) < 2:
370
+ raise ValueError("a comparison needs at least two ligands")
371
+ self.diagrams = list(diagrams)
372
+ raw = list(names) if names is not None else [d.name or f"ligand {i + 1}" for i, d in enumerate(diagrams)]
373
+ if len(raw) != len(self.diagrams):
374
+ raise ValueError("one name per ligand is needed")
375
+ seen: dict[str, int] = {}
376
+ self.names: list[str] = []
377
+ for nm in raw:
378
+ seen[nm] = seen.get(nm, 0) + 1
379
+ self.names.append(nm if seen[nm] == 1 else f"{nm} ({seen[nm]})")
380
+ self.fingerprints = [Fingerprint.from_diagram(d, nm) for d, nm in zip(self.diagrams, self.names)]
381
+ self.table = FingerprintTable(self.fingerprints)
382
+ #: The common substructure and the verdict on aligning on it.
383
+ self.core: CommonCore = find_common_core([d.ligand for d in self.diagrams], min_fraction, min_atoms)
384
+ #: Backbone RMSD of each structure's pocket on the first one's (``None``: nothing to fit).
385
+ self.pocket_rmsd: list[float | None] = []
386
+ #: Rigid transforms into the first structure's frame (``None``: the pockets are not one pocket).
387
+ self.transforms = pocket_transforms(self.diagrams, rmsds=self.pocket_rmsd)
388
+ self._coords_cache: dict[int, tuple[list[dict[str, tuple[float, float]]], str]] = {}
389
+ self._cache: dict[tuple, tuple] = {}
390
+
391
+ # ------------------------------------------------------------------ data
392
+ @property
393
+ def n(self) -> int:
394
+ """How many ligands are compared."""
395
+ return len(self.diagrams)
396
+
397
+ def consensus(self) -> list[ConsensusRow]:
398
+ """Per residue, how many ligands contact it and how (see :meth:`FingerprintTable.consensus`)."""
399
+ return self.table.consensus()
400
+
401
+ def consensus_contacts(self) -> list[Interaction]:
402
+ """The set as contact records, one per (residue, interaction type): ``occupancy`` is the
403
+ share of the set's ligands that make the contact (see :meth:`FingerprintTable.contacts`)."""
404
+ return self.table.contacts()
405
+
406
+ def diagram(self, k: int = 0) -> Diagram:
407
+ """Ligand ``k`` as a single diagram whose contacts carry the series as their occupancy.
408
+
409
+ Every interaction record of the ligand gets, as ``occupancy``, the share
410
+ of the set's ligands that make the same contact (same residue, same
411
+ interaction type), and the diagram names the set as its ensemble. It
412
+ then renders like any diagram, in either style: a contact every ligand
413
+ makes is drawn at full strength, one that few make is thin and pale.
414
+ This is the channel a trajectory uses, fed from a different ensemble.
415
+ """
416
+ share = {(c.chain, c.residue_number, c.insertion_code, c.type): c.occupancy
417
+ for c in self.consensus_contacts()}
418
+ base = self.diagrams[k]
419
+ resolved = []
420
+ for r in base.interactions:
421
+ rec = r.record
422
+ occupancy = share.get((*_residue_of(r), rec.type))
423
+ resolved.append(replace(r, record=rec.with_(occupancy=occupancy)))
424
+ return Diagram(base.ligand, resolved, structure=base.structure, ligand_key=base.ligand_key,
425
+ name=self.names[k], source=base.source, warnings=base.warnings,
426
+ confidence=base.confidence, ensemble=f"the {self.n} ligands of the set")
427
+
428
+ def difference(self, a: int = 0, b: int = 1) -> Difference:
429
+ """Shared / only-A / only-B contacts of two ligands of the set.
430
+
431
+ Two contacts are one where the residue (chain, number, insertion code) and the interaction type
432
+ are the same; the name of the residue is not compared (see the class).
433
+ """
434
+ first, second = self.fingerprints[a], self.fingerprints[b]
435
+ in_a = {(bit.residue, bit.type) for bit in first.bits}
436
+ in_b = {(bit.residue, bit.type) for bit in second.bits}
437
+ return Difference((self.names[a], self.names[b]),
438
+ tuple(bit for bit in first.columns if (bit.residue, bit.type) in in_b),
439
+ tuple(bit for bit in first.columns if (bit.residue, bit.type) not in in_b),
440
+ tuple(bit for bit in second.columns if (bit.residue, bit.type) not in in_a))
441
+
442
+ def _two_names(self) -> list[str]:
443
+ """A note for every residue that the structures of the set give more than one name."""
444
+ named: dict[tuple[str, int, str], dict[str, list[str]]] = {}
445
+ for fp in self.fingerprints:
446
+ for bit in fp.bits:
447
+ ligands = named.setdefault(bit.residue, {}).setdefault(bit.resname.upper(), [])
448
+ if fp.name not in ligands:
449
+ ligands.append(fp.name)
450
+ out = []
451
+ for (chain, number, icode), names in sorted(named.items()):
452
+ if len(names) > 1:
453
+ said = ", ".join(f"{name} with {' and '.join(ligands)}" for name, ligands in names.items())
454
+ out.append(f"{chain}:{number}{icode} has two names in the set ({said}): it is counted as one residue, "
455
+ "as a comparison goes by chain and number")
456
+ return out
457
+
458
+ @property
459
+ def representative(self) -> int | None:
460
+ """The ligand closest to the common substructure (fewest atoms outside it), when there is one."""
461
+ if not self.core.substantial:
462
+ return None
463
+ return min(range(self.n), key=lambda k: (self.core.sizes[k] - self.core.n_atoms, k))
464
+
465
+ def core_atoms(self, k: int) -> frozenset[str]:
466
+ """Names of ligand ``k``'s atoms in the common substructure (empty when it is not aligned on)."""
467
+ return frozenset(self.core.atoms[k]) if self.core.substantial else frozenset()
468
+
469
+ def contact_via(self) -> dict[tuple[str, int, str], tuple[int, int]]:
470
+ """Per residue: ``(ligands that contact it through an atom of the common core, ligands
471
+ that contact it only through atoms outside the core)``. Empty unless the set is aligned."""
472
+ if not self.core.substantial:
473
+ return {}
474
+ out: dict[tuple[str, int, str], list[int]] = {}
475
+ for k, fp in enumerate(self.fingerprints):
476
+ core = self.core_atoms(k)
477
+ per: dict[tuple[str, int, str], bool] = {}
478
+ for bit, contact in fp.bits.items():
479
+ via_core = any(a in core for a in contact.ligand_atoms)
480
+ per[bit.residue] = per.get(bit.residue, False) or via_core
481
+ for res, via_core in per.items():
482
+ out.setdefault(res, [0, 0])[0 if via_core else 1] += 1
483
+ return {k: (v[0], v[1]) for k, v in out.items()}
484
+
485
+ @property
486
+ def without_bond_orders(self) -> list[str]:
487
+ """The ligands of which only the connectivity is known (no SMILES, and no hydrogens to infer the bond
488
+ orders from). The substructure search takes each of their bonds for a single one, so a double bond of
489
+ another ligand has no match in them: the common substructure can be smaller for it, or missing."""
490
+ return [name for name, dia in zip(self.names, self.diagrams) if dia.ligand.bond_source == "connectivity"]
491
+
492
+ def _core_sentence(self) -> str:
493
+ """What was found to align on, and which ligands went into the search without bond orders."""
494
+ bare = self.without_bond_orders
495
+ if not bare:
496
+ return self.core.describe()
497
+ who = bare[0] if len(bare) == 1 else ", ".join(bare[:-1]) + " and " + bare[-1]
498
+ return (f"{self.core.describe()} {who} {'has' if len(bare) == 1 else 'have'} no bond orders (built from "
499
+ "the connectivity alone, without a SMILES), and a double bond of another ligand has no match there: "
500
+ "the common substructure can be smaller than what the ligands share, or missing.")
501
+
502
+ def alignment(self) -> dict[str, Any]:
503
+ """The alignment decision as plain data."""
504
+ c = self.core
505
+ return {"common_atoms": c.n_atoms, "smallest_ligand_atoms": min(c.sizes), "fraction": round(c.fraction, 3),
506
+ "min_fraction": c.min_fraction, "aligned": c.substantial, "search_complete": c.complete,
507
+ "without_bond_orders": self.without_bond_orders,
508
+ "superposed": all(t is not None for t in self.transforms),
509
+ "pocket_rmsd": [None if r is None else round(r, 2) for r in self.pocket_rmsd],
510
+ "statement": self._core_sentence()}
511
+
512
+ def _numbered_otherwise(self) -> list[str]:
513
+ """The ligands whose pocket has too few residues in common with the first one's to be laid on it: another
514
+ residue numbering, other chain names or another protein (see :func:`bindview.align.pocket_transforms`).
515
+ Residues are compared by chain and number, so what such a ligand shares with the others is not found."""
516
+ if self.diagrams[0].structure is None:
517
+ return []
518
+ return [name for name, dia, fit in zip(self.names, self.diagrams, self.pocket_rmsd)
519
+ if fit is None and dia.structure is not None]
520
+
521
+ def _numbering_note(self, apart: Sequence[str]) -> str:
522
+ return (f"{', '.join(apart)}: the pocket has too few residues in common with that of {self.names[0]} to be "
523
+ "laid on it (another residue numbering, other chain names or another protein). Residues are compared "
524
+ "by chain and number: what is shared with the other ligands is counted as different residues")
525
+
526
+ def _superposition_sentence(self) -> str:
527
+ """Why there is no common spatial frame, in the figure's words."""
528
+ fitted = [r for r in self.pocket_rmsd if r is not None]
529
+ if len(fitted) < self.n:
530
+ return ("The structures do not share a residue numbering to superpose on, so no spatial frame "
531
+ "could be made.")
532
+ return (f"The models do not share one pocket conformation either: after superposition on the residues "
533
+ f"around the ligands the backbone RMSD reaches {max(fitted):.0f} \u00c5, so no spatial frame "
534
+ "is claimed.")
535
+
536
+ # ------------------------------------------------------------------ frames
537
+ def _coords(self, ref: int) -> tuple[list[dict[str, tuple[float, float]]], str]:
538
+ """2D coordinates of every ligand in one frame (bond-length units, y up), and how they
539
+ were brought there: ``core`` / ``pose`` / ``own``."""
540
+ if ref in self._coords_cache:
541
+ return self._coords_cache[ref]
542
+ base = Metrics()
543
+
544
+ def own(k: int) -> dict[str, tuple[float, float]]:
545
+ dep = depict_ligand(self.diagrams[k].ligand, base)
546
+ return {a.name: (a.x / base.bond_length, -a.y / base.bond_length) for a in dep.atoms if a.name}
547
+
548
+ ligs = [d.ligand for d in self.diagrams]
549
+ if self.core.substantial:
550
+ ref_xy = own(ref)
551
+ ref_core = [ref_xy[n] for n in self.core.atoms[ref]]
552
+ out = [ref_xy if k == ref else core_coords(ligs[k], self.core.atoms[k], ref_core) for k in range(self.n)]
553
+ mode = "core"
554
+ elif all(t is not None for t in self.transforms):
555
+ clouds = self._clouds()
556
+ frame = pose_frame(clouds)
557
+ owns = [own(k) for k in range(self.n)]
558
+ arrays = [np.array([owns[k][n] for n in ligs[k].names]) for k in range(self.n)]
559
+ proj = [frame.project(c) for c in clouds]
560
+
561
+ def spread(a: np.ndarray) -> float:
562
+ return float(np.sqrt(((a - a.mean(axis=0)) ** 2).sum(axis=1).mean())) if len(a) else 0.0
563
+ # One magnification for drawings and poses: bond lengths per angstrom.
564
+ scale = sum(spread(a) for a in arrays) / max(sum(spread(p) for p in proj), 1e-6)
565
+ out = [pose_coords(ligs[k].names, arrays[k], proj[k], scale) for k in range(self.n)]
566
+ mode = "pose"
567
+ else:
568
+ out = []
569
+ for k in range(self.n):
570
+ xy = own(k)
571
+ cx = sum(p[0] for p in xy.values()) / len(xy)
572
+ cy = sum(p[1] for p in xy.values()) / len(xy)
573
+ out.append({n: (x - cx, y - cy) for n, (x, y) in xy.items()})
574
+ mode = "own"
575
+ self._coords_cache[ref] = (out, mode)
576
+ return out, mode
577
+
578
+ def _clouds(self) -> list[np.ndarray]:
579
+ """Every ligand's atoms in the first structure's frame."""
580
+ out = []
581
+ for dia, t in zip(self.diagrams, self.transforms):
582
+ assert t is not None
583
+ out.append(dia.ligand.coords3d @ t[0].T + t[1])
584
+ return out
585
+
586
+ def _alignment_sentence(self, mode: str, more: str = "") -> str:
587
+ text = self._core_sentence()
588
+ if mode == "core":
589
+ text += " That substructure sits on identical coordinates in every drawing."
590
+ apart = self._numbered_otherwise()
591
+ if apart:
592
+ who = apart[0] if len(apart) == 1 else ", ".join(apart[:-1]) + " and " + apart[-1]
593
+ text += (f" {who} {'does' if len(apart) == 1 else 'do'} not number the residues of the pocket as "
594
+ f"{self.names[0]} does: residues are compared by chain and number, so what is shared may "
595
+ "be counted as different residues.")
596
+ elif mode == "pose":
597
+ text += " Each ligand is drawn turned to its own pose in the superposed pocket."
598
+ elif mode == "own":
599
+ text += " " + self._superposition_sentence() + " Each ligand is drawn in its own orientation."
600
+ return text + more
601
+
602
+ def _contexts(self, m: Metrics, opts: RenderOptions, palette: Palette, coords: list[dict]) -> list[Context]:
603
+ out = []
604
+ for dia, xy in zip(self.diagrams, coords):
605
+ dep = _frame_depiction(dia.ligand, m, xy)
606
+ drawable = [r for r in dia.interactions if r.ligand is not None]
607
+ out.append(Context(dia.ligand, dep, group_residues(drawable, opts.show_chain), m, palette, opts,
608
+ confidence=dia.confidence if opts.confidence else None))
609
+ return out
610
+
611
+ def _lay_out(self, m: Metrics, bodies: list[Body], obstacle: Depiction,
612
+ extra: Sequence[tuple[float, float, float]] = ()) -> tuple[LayoutResult, LigandField]:
613
+ _set_fans(bodies)
614
+ params = LayoutParams(unit=m.bond_length)
615
+ fld = LigandField(obstacle, reach=(params.reach + 3.0) * m.bond_length, step=max(2.0, m.bond_length / 10.0),
616
+ extra=extra)
617
+ return layout_bodies(fld, bodies, params), fld
618
+
619
+ # ------------------------------------------------------------------ render
620
+ def render(self, view: str = "auto", theme: "str | Palette" = "light", *, metrics: Metrics | None = None,
621
+ pair: tuple[int, int] = (0, 1), min_ligands: int = 1, thumbnails: bool = True,
622
+ **options: Any) -> RenderResult:
623
+ """Draw the comparison.
624
+
625
+ ``view`` is ``"difference"`` (two ligands; ``pair`` picks which two of a
626
+ larger set), ``"consensus"`` (the whole set) or ``"auto"`` (difference
627
+ for two ligands, consensus for more). ``min_ligands`` drops residues
628
+ contacted by fewer ligands from the consensus view, and the figure
629
+ says so. ``thumbnails`` adds the ligands of an aligned set, each drawn
630
+ on the common core. Remaining options are those of
631
+ :class:`~bindview.styles.base.RenderOptions`.
632
+ """
633
+ if view == "auto":
634
+ view = "difference" if self.n == 2 else "consensus"
635
+ if view not in VIEWS:
636
+ raise ValueError(f"unknown view {view!r}; choose from {', '.join(VIEWS)}")
637
+ if view == "difference" and (self.n != 2 or tuple(pair) != (0, 1)):
638
+ a, b = pair
639
+ if a == b or not (0 <= a < self.n and 0 <= b < self.n):
640
+ raise ValueError(f"pair {pair!r} does not name two ligands of this set")
641
+ sub = Comparison([self.diagrams[a], self.diagrams[b]], [self.names[a], self.names[b]],
642
+ min_fraction=self.core.min_fraction, min_atoms=self.core.min_atoms)
643
+ return sub.render("difference", theme, metrics=metrics, **options)
644
+ opts = RenderOptions(**options)
645
+ coloured = opts.plddt_colors # asked for, and not drawn: a comparison draws pLDDT by weight
646
+ opts = replace(opts, plddt_colors=False)
647
+ css_vars = isinstance(theme, str) and theme.lower() == "auto"
648
+ light, dark = scheme(opts.colors)
649
+ palette = light if css_vars else get_palette(theme, opts.colors)
650
+ base = metrics or Metrics()
651
+ key = (view, base, opts, min_ligands, thumbnails, frozenset(palette.elements))
652
+ if key not in self._cache:
653
+ if view == "difference":
654
+ self._cache[key] = self._render_difference(palette, base, opts)
655
+ else:
656
+ self._cache[key] = self._render_consensus(palette, base, opts, min_ligands, thumbnails)
657
+ scene, status, figure, quality, notes, data = self._cache[key]
658
+ if coloured:
659
+ # Said, and not left to be found out: a comparison draws pLDDT by weight, whatever was asked.
660
+ notes = list(notes) + ["plddt_colors is not drawn in a comparison: its figures show pLDDT by stroke "
661
+ "weight and opacity"]
662
+ if options.get("break_lines"):
663
+ # The same, where it was asked for in so many words: asked for and not done has to be said.
664
+ # Left to its default a comparison says nothing; its lines are drawn as they are laid out.
665
+ notes = list(notes) + ["break_lines is not done in a comparison: the lines of its figures are drawn "
666
+ "as they are laid out"]
667
+ unused = [k for k in ("residues", "lines", "exposure", "lining", "solvent_mark", "absent") if options.get(k) is not None]
668
+ if unused:
669
+ notes = list(notes) + [f"{', '.join(unused)}: a setting of a single diagram, which a comparison has not"]
670
+ graph = data.get("_graph")
671
+ # A copy: the views are kept, and what a caller does to the data of one result is not in the next.
672
+ data = copy.deepcopy({k: v for k, v in data.items() if k != "_graph"})
673
+ svg = css = None
674
+ if scene is not None:
675
+ svg, css = svg_and_css(scene, palette, background=opts.background, css_vars=css_vars,
676
+ dark_palette=dark if css_vars else None, interactive=opts.interactive,
677
+ stylesheet=opts.stylesheet)
678
+ if opts.interactive and ROOT_CLASS not in svg.split(">", 1)[0]:
679
+ notes = list(notes) + [NOTHING_TO_POINT_AT]
680
+ conf = {}
681
+ for k in range(self.n):
682
+ c = self.diagrams[k].confidence
683
+ if opts.confidence and c is not None:
684
+ conf[self.names[k]] = self.diagrams[k]._confidence_report(c)
685
+ burial = {self.names[k]: self.diagrams[k]._burial_report() for k in range(self.n)
686
+ if self.diagrams[k].burial() is not None}
687
+ return RenderResult(status=status, svg=svg, figure=figure, warnings=_dedupe(notes), quality=quality,
688
+ style=view, scene=scene,
689
+ # (The theme, whatever the colour scheme, as a ligand's figure reports it.)
690
+ theme="auto" if css_vars else palette.name if isinstance(theme, Palette) else str(theme).lower(),
691
+ confidence=conf or None, data=data, burial=burial or None, css=css,
692
+ graph=None if graph is None else copy.deepcopy(graph))
693
+
694
+ def render_svg(self, path: "str | Path | None" = None, view: str = "auto", theme: "str | Palette" = "light",
695
+ **options: Any) -> RenderResult:
696
+ """Render and, when ``path`` is given and there is a figure, write it."""
697
+ result = self.render(view=view, theme=theme, **options)
698
+ if path is not None and result.svg is not None:
699
+ p = Path(path)
700
+ try:
701
+ p.write_text(result.svg, encoding="utf-8")
702
+ except OSError as exc:
703
+ raise RenderError(f"cannot write {p}: {exc}") from exc
704
+ result.path = p
705
+ return result
706
+
707
+ # -- shared pieces -------------------------------------------------------
708
+ def _banner(self, opts: RenderOptions) -> str | None:
709
+ flagged = []
710
+ for k in range(self.n):
711
+ conf = self.diagrams[k].confidence
712
+ if opts.confidence and conf is not None and conf.marked:
713
+ verdict = f" ({conf.model.flag})" if conf.model is not None and conf.model.flag else ""
714
+ flagged.append(self.names[k] + verdict)
715
+ if not flagged:
716
+ return None
717
+ noun = "Model" if len(flagged) == 1 else "Models"
718
+ return (f"{noun} flagged as not trustworthy: {', '.join(flagged)} — shown for inspection, "
719
+ "not as a result.")
720
+
721
+ def _member_notes(self, opts: RenderOptions) -> tuple[list[str], bool]:
722
+ """Warnings carried over from the single diagrams, and whether any of them is degraded."""
723
+ notes: list[str] = []
724
+ degraded = False
725
+ for name, dia in zip(self.names, self.diagrams):
726
+ notes.extend(f"{name}: {w}" for w in dia.warnings)
727
+ if dia.unresolved:
728
+ n = len(dia.unresolved)
729
+ notes.append(f"{name}: {n} reported interaction{'s' if n != 1 else ''} could not be attached to "
730
+ "a ligand atom; counted in the fingerprint, not drawn")
731
+ degraded = True
732
+ if dia.ligand.bond_source == "connectivity":
733
+ degraded = True
734
+ notes.append(f"{name}: no bond orders (built from the connectivity alone, without a SMILES). The "
735
+ "common substructure of the set is searched with them as they are and can be smaller "
736
+ "for it, or missing: give the ligand's SMILES")
737
+ conf = dia.confidence
738
+ if opts.confidence and conf is not None and conf.marked:
739
+ verdict = f" ({conf.model.flag})" if conf.model is not None and conf.model.flag else ""
740
+ notes.append(f"{name}: the model is flagged as not trustworthy{verdict}; the figure is marked")
741
+ exposed = dia._burial_warning() # none for a chain of residues: the cut is not its own
742
+ if exposed is not None:
743
+ notes.append(f"{name}: {exposed}")
744
+ return notes, degraded
745
+
746
+ def _quality(self, scene: Scene, m: Metrics, opts: RenderOptions, layout: LayoutResult | None,
747
+ n_residues: int, min_font_px: float, estimated: bool = False) -> Quality:
748
+ fit = min(opts.figure_width_mm * _PX_PER_MM / scene.width, opts.figure_height_mm * _PX_PER_MM / scene.height,
749
+ 1.0)
750
+ font_pt = min_font_px * _PT_PER_PX * fit
751
+ required = (math.inf if beyond_any_page(min_font_px * _PT_PER_PX, opts, fixed=True) else
752
+ scene.width * opts.min_font_pt / (min_font_px * _PT_PER_PX) / _PX_PER_MM)
753
+ n_inter = sum(len(d.interactions) for d in self.diagrams)
754
+ return Quality(
755
+ width=scene.width, height=scene.height, bond_length=m.bond_length, n_residues=n_residues,
756
+ n_interactions=n_inter, overlaps=layout.overlaps if layout else 0,
757
+ unplaced=len(layout.unplaced) if layout else 0, line_crossings=layout.line_crossings if layout else 0,
758
+ bond_crossings=layout.bond_crossings if layout else 0, max_stretch=layout.max_stretch if layout else 0.0,
759
+ min_font_pt=font_pt, required_width_mm=required, readable=font_pt >= opts.min_font_pt - 1e-9,
760
+ estimated=estimated, link_hits=layout.link_hits if layout else 0)
761
+
762
+ @staticmethod
763
+ def _text_width(m: Metrics, opts: RenderOptions) -> float:
764
+ """Width that running text and thumbnails may take: the figure's, so they do not pile up."""
765
+ return max(360.0, opts.figure_width_mm * _PX_PER_MM - 2.0 * m.margin)
766
+
767
+ def _models_line(self, opts: RenderOptions, size: float) -> tuple[Group, float, float] | None:
768
+ """One line with the range of the set's model-level evidence."""
769
+ confs = [d.confidence for d in self.diagrams if opts.confidence and d.confidence is not None]
770
+ if not confs:
771
+ return None
772
+ parts: list[tuple[str, str]] = []
773
+ iptm = [c.model.iptm for c in confs if c.model is not None and c.model.iptm is not None]
774
+ if iptm:
775
+ parts.append(("ipTM", _range(iptm, 2)))
776
+ pocket = [c.pocket_plddt for c in confs if c.pocket_plddt is not None]
777
+ if pocket:
778
+ parts.append(("pocket pLDDT", _range(pocket, 0)))
779
+ lig = [c.ligand_plddt for c in confs if c.ligand_plddt is not None]
780
+ if lig:
781
+ parts.append(("ligand pLDDT", _range(lig, 0)))
782
+ if opts.burial:
783
+ buried = [100.0 * b.buried_fraction for b in (d.burial() for d in self.diagrams) if b is not None]
784
+ if buried and parts:
785
+ parts.append(("ligands buried", _range(buried, 0) + " %"))
786
+ if not parts:
787
+ return None
788
+ lead = f"Model confidence over {len(confs)} models "
789
+ spans: list[Span] = [Span(lead)]
790
+ width = text_width(lead, size)
791
+ data = {}
792
+ for i, (label, value) in enumerate(parts):
793
+ head = (" · " if i else "") + label + " "
794
+ spans.extend([Span(head), Span(value, fill="text", bold=True)])
795
+ width += text_width(head, size) + text_width(value, size, bold=True)
796
+ data[label.replace(" ", "-").lower()] = value
797
+ text = Text(0.0, CAP_HEIGHT * size, tuple(spans), size, "text_muted", anchor="start")
798
+ return Group("confidence", [text], data=data), width, size * 1.5
799
+
800
+ def _summary_page(self, m: Metrics, opts: RenderOptions, headline: str, why: str, table: Group, tw: float,
801
+ th: float, foot: Sequence[str], scene_title: str) -> Scene:
802
+ page = _Page(m)
803
+ wrap = max(tw, 360.0)
804
+ models = self._models_line(opts, m.caption_font + 1.0)
805
+ if models is not None:
806
+ page.add(*models, gap=4.0)
807
+ page.text(headline, wrap, fill="text", cls="headline", size=m.title_font, bold=True, gap=8.0)
808
+ page.text(why, wrap, fill="warning", cls="reason", gap=3.0)
809
+ page.add(table, tw, th, gap=12.0)
810
+ for line in foot:
811
+ page.text(line, wrap, cls="footnotes", gap=6.0)
812
+ return page.build(opts.title, opts.subtitle, self._banner(opts), scene_title)
813
+
814
+ # ------------------------------------------------------------------ difference view
815
+ def _render_difference(self, palette: Palette, base: Metrics, opts: RenderOptions) -> tuple:
816
+ diff = self.difference()
817
+ notes, degraded = self._member_notes(opts)
818
+ notes.extend(self._two_names())
819
+ data: dict[str, Any] = {"view": "difference", "alignment": self.alignment(), "difference": diff.as_dict()}
820
+ title = opts.title or f"{self.names[0]} vs {self.names[1]}"
821
+ if not diff.shared and not diff.only_a and not diff.only_b:
822
+ page = _Page(base)
823
+ page.text("No interactions in either supplied set", 330.0, fill="text", cls="empty-state",
824
+ size=base.title_font, bold=True)
825
+ page.text(f"Both ligands ({self.names[0]}, {self.names[1]}) were analysed and no contact was found; "
826
+ "there is nothing to compare.", 330.0, cls="empty-state")
827
+ return page.build(opts.title, opts.subtitle, self._banner(opts), title), "empty", "empty", None, notes, data
828
+
829
+ best: tuple[Scene, Quality, _Frame, str] | None = None
830
+ lengths = [opts.bond_length] if opts.bond_length else list(_BOND_LENGTHS)
831
+ done = False
832
+ for bl in lengths:
833
+ frame = self._difference_frame(_scaled(base, bl), opts, palette)
834
+ for arrangement in ("row", "column"):
835
+ scene, panel_notes = self._difference_scene(frame, diff, opts, palette, arrangement)
836
+ q = self._quality(scene, frame.m, opts, frame.layout, len(frame.bodies), _NOTE)
837
+ if best is None or _better(q, best[1]):
838
+ best = (scene, q, frame, arrangement)
839
+ best_notes = panel_notes
840
+ if q.valid and q.readable:
841
+ best = (scene, q, frame, arrangement)
842
+ best_notes = panel_notes
843
+ done = True
844
+ break
845
+ if done:
846
+ break
847
+ assert best is not None
848
+ scene, q, frame, arrangement = best
849
+ notes = notes + best_notes
850
+ data["arrangement"] = arrangement
851
+ data["frame"] = frame.mode
852
+ if frame.mode == "own":
853
+ notes.append("the structures could not be superposed (no common residue numbering); each ligand is "
854
+ "drawn in its own orientation")
855
+ degraded = True
856
+ elif self._numbered_otherwise(): # on a common scaffold: no frame is missing, the residues are
857
+ notes.append(self._numbering_note(self._numbered_otherwise()))
858
+ degraded = True
859
+ if frame.graph is not None:
860
+ data["_graph"] = _on_page(frame.graph, scene)
861
+ if q.valid and q.readable:
862
+ return scene, "degraded" if degraded else "ok", "difference", q, notes, data
863
+ if not q.valid:
864
+ reason = (f"{q.unplaced} residue(s) could not be placed, {q.overlaps} pair(s) overlap and "
865
+ f"{q.link_hits} interaction line(s) cross another residue")
866
+ else:
867
+ reason = beyond_any_page(_NOTE * _PT_PER_PX, opts, fixed=True) or too_small_on_page(
868
+ q.min_font_pt, q.required_width_mm, q.width, q.height, opts)
869
+ message = f"a two-panel difference view of these ligands is not readable: {reason}"
870
+ if opts.on_unreadable == "render":
871
+ return scene, "unreadable", "difference", q, notes + [message + "; rendered anyway on request"], data
872
+ data.pop("_graph", None) # no node-level figure is handed out
873
+ if opts.on_unreadable == "none":
874
+ return None, "unreadable", "none", q, notes + [message], data
875
+ table, tw, th = self._difference_table(diff, base, opts.figure_width_mm * _PX_PER_MM - 2.0 * base.margin)
876
+ why = (f"A two-panel difference view is not readable at {opts.figure_width_mm:g} mm: {reason}. "
877
+ "Contacts are listed per residue instead.")
878
+ foot = [f"Tanimoto similarity of the two fingerprints: {diff.tanimoto:.2f}.", self._core_sentence()]
879
+ scene = self._summary_page(base, opts, "Contact differences by residue", why, table, tw, th, foot, title)
880
+ return (scene, "unreadable", "summary", q, notes + [message + "; a per-residue summary was drawn instead"],
881
+ data)
882
+
883
+ def _difference_frame(self, m: Metrics, opts: RenderOptions, palette: Palette) -> _Frame:
884
+ coords, mode = self._coords(0)
885
+ ctxs = self._contexts(m, opts, palette, coords)
886
+ by_key = [{g.key: g for g in c.groups} for c in ctxs]
887
+ keys = sorted(set(by_key[0]) | set(by_key[1]))
888
+ with_chain = len({k[0] for k in keys}) > 1
889
+ bits = [{(g.key, r.type) for g in c.groups for r in g.interactions} for c in ctxs]
890
+ bodies = []
891
+ for key in keys:
892
+ grp = by_key[0].get(key) or by_key[1][key]
893
+ name, number = _node_text(grp.resname, key, with_chain)
894
+ radius = max(_node_radius(by_key[k][key].resname.upper(), number + MARK) # (room for either name)
895
+ for k in (0, 1) if key in by_key[k])
896
+ node = _Node(key, grp.resname, name, number, radius)
897
+ ports: list[Port] = []
898
+ for k in (0, 1):
899
+ infos = (_merge_by_target(port_infos(ctxs[k], by_key[k][key], lambda kind: False))
900
+ if key in by_key[k] else [])
901
+ start = len(ports)
902
+ if infos:
903
+ ports.extend(make_ports(ctxs[k], infos,
904
+ lambda info, r=radius: ((0.0, 0.0), r + 1.5, None, r, None)))
905
+ node.infos.append(infos)
906
+ node.spans.append((start, len(ports)))
907
+ note = None
908
+ if key in by_key[0] and key in by_key[1]:
909
+ widths = []
910
+ for k in (0, 1):
911
+ plus = [t for t in TYPE_ORDER if (key, t) in bits[k] and (key, t) not in bits[1 - k]]
912
+ if plus:
913
+ widths.append(_code_spans(plus, "+")[1])
914
+ if widths:
915
+ note = (max(widths) + 2.0, CAP_HEIGHT * _NOTE + 3.0)
916
+ n_drawn = sum(1 for infos in node.infos for i in infos if i.drawn)
917
+ bodies.append(_node_body(node, radius + 1.5, ports, note, float(n_drawn), 0.95 * m.bond_length))
918
+ layout, fld = self._lay_out(m, bodies, _merge([c.dep for c in ctxs], m))
919
+ frame = _Frame(m, bodies, layout, ctxs, mode, fld, {"bits": bits, "by_key": by_key})
920
+ # The engine's result becomes the graph; the panels are drawn from the graph.
921
+ frame.graph = self._difference_graph(frame)
922
+ frame.poses, frame.label_t = poses_from(frame.graph, bodies)
923
+ return frame
924
+
925
+ def _difference_graph(self, frame: _Frame) -> Graph:
926
+ """The frame of a difference view as a graph: two rigid ligands, one set of residue nodes."""
927
+ m = frame.m
928
+ by_key, bits = frame.extra["by_key"], frame.extra["bits"]
929
+ graph = Graph(view="difference", bond_length=float(m.bond_length),
930
+ springs=engine_springs(LayoutParams(unit=m.bond_length)))
931
+ parts = []
932
+ for k in (0, 1):
933
+ conf = frame.contexts[k].confidence
934
+ parts.append(LigandPart(frame.contexts[k].dep, prefix=f"L{k + 1}", group=f"ligand:{k + 1}",
935
+ label=self.names[k], plddt=conf.ligand_atoms if conf is not None else None))
936
+ residues = []
937
+ for body in frame.bodies:
938
+ node: _Node = body.payload
939
+ pose = frame.layout.poses.get(body.key)
940
+ at = frame.layout.label_t.get(body.key, ())
941
+ contacts: list[Contact] = []
942
+ state: dict[str, str] = {}
943
+ own: dict[str, float] = {}
944
+ for k in (0, 1):
945
+ other = 1 - k
946
+ grp = by_key[k].get(node.key)
947
+ state[f"ligand:{k + 1}"] = ("absent" if grp is None else
948
+ ("shared" if node.key in by_key[other] else "only"))
949
+ if grp is not None:
950
+ value = residue_plddt(frame.contexts[k], grp)
951
+ if value is not None:
952
+ own[f"ligand:{k + 1}"] = value
953
+ for c in residue_contacts(parts[k], node.ident, node.infos[k], body.ports, at,
954
+ offset=node.spans[k][0], ligand_group=f"ligand:{k + 1}"):
955
+ c.attrs["shared"] = (node.key, InteractionType(c.type)) in bits[other]
956
+ contacts.append(c)
957
+ graph.contacts.extend(contacts)
958
+ attrs: dict[str, Any] = {"resname": node.resname, "chain": node.key[0], "number": node.key[1],
959
+ "class": residue_class(node.resname), "form": "node",
960
+ "radius": round(node.radius, 3), "contact": state}
961
+ if node.key[2]:
962
+ attrs["icode"] = node.key[2]
963
+ if own:
964
+ attrs["confidence_by_ligand"] = own # one value per model: the residue's pLDDT in each
965
+ gnode = Node(id="R:" + node.ident, kind="residue",
966
+ label=format_residue_label(node.resname, node.key[1], node.key[2], None),
967
+ x=None if pose is None else float(pose.x), y=None if pose is None else float(pose.y),
968
+ anchors=tuple(dict.fromkeys(c.ligand for c in contacts if c.ligand)),
969
+ spring=float(sum(p.weight for p in body.ports)), attrs=attrs)
970
+ residues.append((gnode, contacts))
971
+ unique_ids(graph.contacts)
972
+ for gnode, contacts in residues:
973
+ gnode.contacts = tuple(c.id for c in contacts)
974
+ graph.nodes = parts[0].nodes() + parts[1].nodes() + [n for n, _ in residues]
975
+ graph.groups = [parts[k].rigid_group(panel="AB"[k]) for k in (0, 1)]
976
+ graph.panels = [{"id": "AB"[k], "group": f"ligand:{k + 1}", "label": self.names[k]} for k in (0, 1)]
977
+ graph.meta = {"ligands": list(self.names), "frame": frame.mode}
978
+ link_references(graph)
979
+ return graph
980
+
981
+ def _resname_in(self, k: int, key: tuple[str, int, str]) -> "str | None":
982
+ """The name that the structure of the ``k``-th ligand gives a residue, where it has one."""
983
+ structure = self.diagrams[k].structure
984
+ if structure is None:
985
+ return None
986
+ try:
987
+ return structure.residue_name(ResidueKey(*key))
988
+ except KeyError:
989
+ return None
990
+
991
+ def _difference_panel(self, frame: _Frame, k: int, palette: Palette) -> tuple[Group, dict[str, Any]]:
992
+ m = frame.m
993
+ ctx = frame.contexts[k]
994
+ other = 1 - k
995
+ by_key, bits = frame.extra["by_key"], frame.extra["bits"]
996
+ layers: dict[str, list[Item]] = {"marks": [], "halos": [], "interactions": [], "residues": []}
997
+ seen: dict[str, Any] = {"kinds": [], "classes": [], "levels": set(), "backbone": False, "sidechain": False,
998
+ "plus": [], "notes": [], "states": set()}
999
+ halo_done: set[tuple] = set()
1000
+ dots_done: set[tuple] = set()
1001
+ cap = CAP_HEIGHT * _FONT
1002
+ for body in frame.bodies:
1003
+ pose = frame.poses.get(body.key)
1004
+ if pose is None:
1005
+ continue
1006
+ node: _Node = body.payload
1007
+ grp = by_key[k].get(node.key)
1008
+ # (A residue that the two structures name differently has, in each panel, the name of its own,
1009
+ # also where only the other ligand touches it.)
1010
+ resname = grp.resname if grp is not None else self._resname_in(k, node.key) or node.resname
1011
+ own = resname.upper()
1012
+ cls = residue_class(resname)
1013
+ if cls not in seen["classes"]:
1014
+ seen["classes"].append(cls)
1015
+ state = "absent" if grp is None else ("shared" if node.key in by_key[other] else "only")
1016
+ seen["states"].add(state)
1017
+ g = Group("residue", data={"residue": node.ident, NUMBER: node.numbered, "class": cls, "form": "node",
1018
+ "contact": state})
1019
+ if grp is None:
1020
+ # Contacted by the other ligand only: the node keeps its place and says so.
1021
+ g.title = f"{own.capitalize()}{node.number}: no contact with {self.names[k]}"
1022
+ g.add(Circle(pose.x, pose.y, node.radius, Paint(stroke="bubble_line", width=0.8, dash=(1.2, 2.6))))
1023
+ g.add(Text.plain(pose.x, pose.y - 1.1, own, _FONT, "text_muted"))
1024
+ g.add(Text.plain(pose.x, pose.y + cap + 1.1, node.number, _FONT, "text_muted"))
1025
+ layers["residues"].append(g)
1026
+ continue
1027
+ plddt = residue_plddt(ctx, grp)
1028
+ look = look_of(plddt)
1029
+ if ctx.confidence is not None:
1030
+ seen["levels"].add(look.level)
1031
+ g.title = f"{grp.label}: " + ", ".join(t.label.lower() for t in grp.types)
1032
+ if plddt is not None and look.band is not None:
1033
+ g.data["plddt"] = f"{plddt:.1f}"
1034
+ g.data["confidence"] = look.band
1035
+ g.title += f"; residue pLDDT {plddt:.0f}"
1036
+ heavy = state == "only"
1037
+ g.add(Circle(pose.x, pose.y, node.radius, Paint(fill=f"class_{cls}", opacity=look.opacity)))
1038
+ g.add(Circle(pose.x, pose.y, node.radius - (0.8 if heavy else 0.0),
1039
+ Paint(stroke="bubble_line", width=2.5 if heavy else 0.9)))
1040
+ g.add(Text.plain(pose.x, pose.y - 1.1, own, _FONT, "bubble_text", bold=look.level == 0))
1041
+ g.add(Text.plain(pose.x, pose.y + cap + 1.1, node.number + (MARK if look.mark else ""), _FONT,
1042
+ "bubble_text"))
1043
+ if state == "shared":
1044
+ plus = [t for t in TYPE_ORDER if (node.key, t) in bits[k] and (node.key, t) not in bits[other]]
1045
+ if plus:
1046
+ spans, _ = _code_spans(plus, "+")
1047
+ g.add(Text(pose.x, pose.y + node.note_at + CAP_HEIGHT * _NOTE + 1.5, spans, _NOTE, "text_muted"))
1048
+ seen["plus"].extend(t for t in plus if t not in seen["plus"])
1049
+ layers["residues"].append(g)
1050
+
1051
+ P = np.array([[pose.x, pose.y]])
1052
+ a_all, b_all, _ = body.link_segments(P, np.array([0.0]), np.array([False]))
1053
+ label_t = frame.label_t.get(body.key, ())
1054
+ start = node.spans[k][0]
1055
+ for j, info in enumerate(node.infos[k]):
1056
+ idx = start + j
1057
+ if info.kind not in seen["kinds"]:
1058
+ seen["kinds"].append(info.kind)
1059
+ if ctx.confidence is not None:
1060
+ seen["levels"].add(info.look.level)
1061
+ first = info.interactions[0]
1062
+ data = interaction_data(ctx, grp, info)
1063
+ data["contact"] = "shared" if (node.key, info.kind) in bits[other] else "only"
1064
+ title = "; ".join(interaction_title(r, ctx.ligand, info.plddt) for r in info.interactions)
1065
+ if not info.drawn:
1066
+ # No line for a contact without direction; it stays addressable as data.
1067
+ layers["interactions"].append(Group(f"contact {info.kind.value}", data=data, title=title))
1068
+ continue
1069
+ style = _STYLES[info.kind]
1070
+ arrow = None
1071
+ if info.kind in (T.HBOND, T.WATER_BRIDGE):
1072
+ arrow, note = hbond_direction(first, ctx.dep)
1073
+ if note:
1074
+ seen["notes"].append(f"{self.names[k]}: {note}")
1075
+ if info.kind is T.HBOND:
1076
+ if info.site_kind == "atom" and not is_backbone_atom(grp.resname, info.site_atoms[0]):
1077
+ style = _HBOND_SIDECHAIN
1078
+ seen["sidechain"] = True
1079
+ else:
1080
+ seen["backbone"] = True
1081
+ a = (float(a_all[0, idx, 0]), float(a_all[0, idx, 1]))
1082
+ b = (float(b_all[0, idx, 0]), float(b_all[0, idx, 1]))
1083
+ lg = Group(f"interaction {info.kind.value}", data=data, title=title)
1084
+ lg.extend(link_items(a, b, info.kind, m, label=info.label, arrow=arrow, opacity=info.opacity,
1085
+ style=style, weight=info.weight,
1086
+ label_at=label_t[idx] if idx < len(label_t) else 0.5))
1087
+ if info.target.kind == "ring":
1088
+ dot = (info.target.atoms, style.token)
1089
+ if dot not in dots_done:
1090
+ dots_done.add(dot)
1091
+ lg.add(Circle(info.target.point[0], info.target.point[1], 2.5,
1092
+ Paint(fill=style.token, opacity=info.opacity)))
1093
+ if style.end_dots:
1094
+ lg.add(Circle(a[0], a[1], 2.3, Paint(fill=style.token, opacity=info.opacity)))
1095
+ layers["interactions"].append(lg)
1096
+ if info.target.kind == "group" and ctx.options.charge_halos:
1097
+ halo = (info.target.atoms, style.token)
1098
+ if halo not in halo_done:
1099
+ halo_done.add(halo)
1100
+ layers["halos"].extend(halo_items(group_skeleton(ctx.dep, info.target.atoms),
1101
+ halo_radius(m), style.token))
1102
+ seen["shaded"] = {token for _, token in halo_done}
1103
+
1104
+ dep = ctx.dep
1105
+ if frame.mode == "core":
1106
+ # What is not part of the common substructure is what differs: mark it.
1107
+ core = self.core_atoms(k)
1108
+ outside = {a.idx for a in dep.atoms if a.name and a.name not in core}
1109
+ paint = Paint(stroke="exposure", width=0.62 * m.bond_length, opacity=0.6, cap="round")
1110
+ bonded: set[int] = set()
1111
+ for bond in dep.bonds:
1112
+ if bond.kind == "covalent" and (bond.a in outside or bond.b in outside) \
1113
+ and dep.atoms[bond.a].name and dep.atoms[bond.b].name:
1114
+ pa, pb = dep.pos(bond.a), dep.pos(bond.b)
1115
+ layers["marks"].append(Line(pa[0], pa[1], pb[0], pb[1], paint))
1116
+ bonded |= {bond.a, bond.b}
1117
+ for i in sorted(outside - bonded):
1118
+ p = dep.pos(i)
1119
+ layers["marks"].append(Circle(p[0], p[1], 0.31 * m.bond_length, Paint(fill="exposure", opacity=0.6)))
1120
+ seen["marked"] = bool(layers["marks"])
1121
+ conf = ctx.confidence
1122
+ looks = atom_looks(dep, conf.ligand_atoms) if conf is not None else None
1123
+ if looks:
1124
+ seen["levels"] |= {lk.level for lk in looks}
1125
+ ligand = draw_ligand(dep, palette, m, looks)
1126
+ ligand.data["ligand"] = self.names[k]
1127
+ content = Group("diagram")
1128
+ for name in ("marks", "halos", "interactions"):
1129
+ if layers[name]:
1130
+ content.add(Group(name, layers[name]))
1131
+ content.add(ligand)
1132
+ content.add(Group("residues", layers["residues"]))
1133
+ return content, seen
1134
+
1135
+ def _panel_header(self, k: int, diff: Difference, m: Metrics, opts: RenderOptions) -> tuple[list[Item], float, float]:
1136
+ only = diff.only_a if k == 0 else diff.only_b
1137
+ n = len(diff.shared) + len(only)
1138
+ size = m.title_font - 0.5
1139
+ items: list[Item] = [Text.plain(0.0, CAP_HEIGHT * size, self.names[k], size, "text", anchor="start",
1140
+ bold=True)]
1141
+ width = text_width(self.names[k], size, bold=True)
1142
+ y = size * 1.45
1143
+ line = (f"{n} contact{'s' if n != 1 else ''} (residue × type): {len(diff.shared)} shared, "
1144
+ f"{len(only)} only this ligand")
1145
+ items.append(Text.plain(0.0, y + CAP_HEIGHT * m.caption_font, line, m.caption_font, "text_muted",
1146
+ anchor="start"))
1147
+ width = max(width, text_width(line, m.caption_font))
1148
+ y += m.caption_font * 1.5
1149
+ conf = self.diagrams[k].confidence if opts.confidence else None
1150
+ shown = self.diagrams[k].burial() if opts.burial else None
1151
+ strip = _confidence_strip(conf, m.caption_font, shown) if (conf is not None or shown is not None) else None
1152
+ if strip is not None:
1153
+ items.append(Group("confidence", [Text(0.0, y + CAP_HEIGHT * strip[1], strip[0], strip[1], "text_muted",
1154
+ anchor="start")],
1155
+ data={key: str(v) for key, v in strip[3].items()}))
1156
+ width = max(width, strip[2])
1157
+ y += strip[1] * 1.5
1158
+ return items, width, y
1159
+
1160
+ def _difference_scene(self, frame: _Frame, diff: Difference, opts: RenderOptions, palette: Palette,
1161
+ arrangement: str) -> tuple[Scene, list[str]]:
1162
+ m = frame.m
1163
+ drawn = [self._difference_panel(frame, k, palette) for k in (0, 1)]
1164
+ box = items_bounds([d[0] for d in drawn]) or (0.0, 0.0, 1.0, 1.0)
1165
+ cw, ch = box[2] - box[0], box[3] - box[1]
1166
+ heads = [self._panel_header(k, diff, m, opts) for k in (0, 1)]
1167
+ # One width and one header height for both panels: the frame sits at the same place in each.
1168
+ pw = max(cw, heads[0][1], heads[1][1])
1169
+ hh = max(heads[0][2], heads[1][2]) + 6.0
1170
+ ph = hh + ch
1171
+ gap = 28.0 if arrangement == "row" else 20.0
1172
+ panels = Group("panels")
1173
+ for k in (0, 1):
1174
+ content = drawn[k][0]
1175
+ content.translate = ((pw - cw) / 2.0 - box[0], hh - box[1])
1176
+ panel = Group("panel", [Group("panel-header", heads[k][0]), content],
1177
+ data={"ligand": self.names[k], "panel": "AB"[k]})
1178
+ panel.translate = (k * (pw + gap), 0.0) if arrangement == "row" else (0.0, k * (ph + gap))
1179
+ panels.add(panel)
1180
+ total_w = 2 * pw + gap if arrangement == "row" else pw
1181
+ total_h = ph if arrangement == "row" else 2 * ph + gap
1182
+
1183
+ seen = [d[1] for d in drawn]
1184
+ classes = [c for c in _CLASS_ORDER if any(c in s["classes"] for s in seen)]
1185
+ kinds = [t for t in TYPE_ORDER if any(t in s["kinds"] for s in seen)]
1186
+ levels: set[int] = set().union(*(s["levels"] for s in seen))
1187
+ states: set[str] = set().union(*(s["states"] for s in seen))
1188
+ legend = [LegendEntry(_CLASS_LABEL[c], "swatch", token=f"class_{c}", stroke="bubble_line") for c in classes]
1189
+ if "shared" in states:
1190
+ legend.append(LegendEntry("contact with both ligands", "node", token="panel", weight=0.9))
1191
+ if "only" in states:
1192
+ legend.append(LegendEntry("with this ligand only", "node", token="panel", weight=2.5))
1193
+ if "absent" in states:
1194
+ legend.append(LegendEntry("with the other ligand only", "node", weight=0.8, dash=(1.2, 2.6)))
1195
+ if any(s["backbone"] for s in seen):
1196
+ legend.append(LegendEntry("H-bond (backbone)", "link", kind=T.HBOND, style=_STYLES[T.HBOND], arrow=True))
1197
+ if any(s["sidechain"] for s in seen):
1198
+ legend.append(LegendEntry("H-bond (side chain)", "link", kind=T.HBOND, style=_HBOND_SIDECHAIN,
1199
+ arrow=True))
1200
+ legend.extend(link_legend([t for t in kinds if t is not T.HBOND], _STYLES))
1201
+ if opts.charge_key:
1202
+ legend.extend(charge_legend(set().union(*(s.get("shaded", set()) for s in seen)), _STYLES))
1203
+ plus = [t for t in TYPE_ORDER if any(t in s["plus"] for s in seen)]
1204
+ if plus:
1205
+ legend.append(LegendEntry("+ a contact type only this ligand makes at a shared residue: "
1206
+ + ", ".join(f"{TYPE_CODES[t]} = {t.label.lower()}" for t in plus)))
1207
+ if any(s.get("marked") for s in seen):
1208
+ legend.append(LegendEntry("outside the common substructure", "halo", token="exposure"))
1209
+ legend.extend(confidence_legend(levels))
1210
+
1211
+ page = _Page(m)
1212
+ wrap = max(total_w, self._text_width(m, opts))
1213
+ page.text(self._alignment_sentence(frame.mode), wrap, gap=4.0)
1214
+ page.add(panels, total_w, total_h, gap=12.0)
1215
+ if opts.legend and legend:
1216
+ lg, lw, lh = legend_group(legend, m, wrap)
1217
+ page.add(lg, lw, lh, gap=10.0)
1218
+ if opts.caption:
1219
+ foot = (f"Residue positions are identical in both panels. Fingerprint similarity (Tanimoto) "
1220
+ f"{diff.tanimoto:.2f}: {len(diff.shared)} shared contacts, {len(diff.only_a)} only "
1221
+ f"{self.names[0]}, {len(diff.only_b)} only {self.names[1]}. Hydrophobic contacts carry no line.")
1222
+ page.text(foot, wrap, cls="footnotes")
1223
+ if any(lv > 0 for lv in levels):
1224
+ page.text("Stroke weight and opacity follow each model's pLDDT: a contact is drawn at the lower of "
1225
+ f"its ligand-atom and residue values, a residue at its own. {MARK} marks pLDDT below 50.",
1226
+ wrap, cls="footnotes", gap=3.0)
1227
+ scene = page.build(opts.title, opts.subtitle, self._banner(opts),
1228
+ opts.title or f"{self.names[0]} vs {self.names[1]}",
1229
+ f"Difference view: {self.names[0]} and {self.names[1]}. " + self._core_sentence())
1230
+ return scene, [n for s in seen for n in s["notes"]]
1231
+
1232
+ def _difference_table(self, diff: Difference, m: Metrics, max_w: float) -> tuple[Group, float, float]:
1233
+ """Per-residue listing: what each ligand does at every contacted residue."""
1234
+ rows = []
1235
+ fps = self.fingerprints
1236
+ for res, cls in diff.residues().items():
1237
+ kinds = [[t for t in TYPE_ORDER if any(b.residue == res and b.type is t for b in fp.bits)] for fp in fps]
1238
+ resname = next(b.resname for fp in fps for b in fp.bits if b.residue == res)
1239
+ rows.append((f"{resname.capitalize()}{res[1]}{res[2]}", cls, kinds))
1240
+ font = m.legend_font
1241
+ row_h = font * 1.7
1242
+ name_w = max(text_width(r[0], font, bold=True) for r in rows) + 10.0
1243
+ col_w = [max([text_width(nm, font * 0.9)] + [_code_spans(r[2][k], sep=" · ")[1] for r in rows]) + 14.0
1244
+ for k, nm in enumerate(diff.names)]
1245
+ tag_w = text_width("both", font * 0.9) + 8.0
1246
+ block_w = name_w + sum(col_w) + tag_w
1247
+ gutter = 26.0
1248
+ fit = max(1, int((max_w + gutter) // (block_w + gutter)))
1249
+ n_blocks = max(1, min(fit, -(-len(rows) // 12)))
1250
+ per = -(-len(rows) // n_blocks)
1251
+ g = Group("summary-table")
1252
+ head_h = row_h * 1.15
1253
+ for blk in range(n_blocks):
1254
+ x0 = blk * (block_w + gutter)
1255
+ part = rows[blk * per:(blk + 1) * per]
1256
+ if not part:
1257
+ continue
1258
+ g.add(Text.plain(x0, CAP_HEIGHT * font, "Residue", font * 0.9, "text_muted", anchor="start"))
1259
+ x = x0 + name_w
1260
+ for k, nm in enumerate(diff.names):
1261
+ g.add(Text.plain(x, CAP_HEIGHT * font, nm, font * 0.9, "text_muted", anchor="start"))
1262
+ x += col_w[k]
1263
+ g.add(Line(x0, head_h - 3.0, x0 + block_w, head_h - 3.0, Paint(stroke="panel_border", width=0.8,
1264
+ cap="butt")))
1265
+ for r, (label, cls, kinds) in enumerate(part):
1266
+ y = head_h + r * row_h
1267
+ if r % 2 == 1:
1268
+ g.add(Rect(x0 - 3.0, y, block_w + 6.0, row_h, Paint(fill="panel"), rx=2.0))
1269
+ basel = y + row_h / 2.0 + CAP_HEIGHT * font / 2.0
1270
+ g.add(Text.plain(x0, basel, label, font, "text", anchor="start", bold=cls == "shared"))
1271
+ x = x0 + name_w
1272
+ for k in (0, 1):
1273
+ if kinds[k]:
1274
+ spans, _ = _code_spans(kinds[k], sep=" · ")
1275
+ g.add(Text(x, basel, spans, _NOTE, "text_muted", anchor="start"))
1276
+ else:
1277
+ g.add(Text.plain(x, basel, "–", font, "text_muted", anchor="start"))
1278
+ x += col_w[k]
1279
+ tag = {"shared": "both", "a": "A", "b": "B"}[cls]
1280
+ g.add(Text.plain(x0 + block_w, basel, tag, font * 0.9, "text_muted", anchor="end"))
1281
+ return g, n_blocks * block_w + (n_blocks - 1) * gutter, head_h + per * row_h
1282
+
1283
+ # ------------------------------------------------------------------ consensus view
1284
+ @staticmethod
1285
+ def _levels(rows: Sequence[ConsensusRow], opts: RenderOptions) -> dict[tuple[str, int, str], list[int]] | None:
1286
+ """Per residue, how many ligands contact it at confidence level 0 / 1 / 2, as the rows carry
1287
+ it (``None``: no confidence, or it is switched off)."""
1288
+ if not opts.confidence:
1289
+ return None
1290
+ out = {r.residue: list(r.levels) for r in rows if r.levels is not None}
1291
+ return out or None
1292
+
1293
+ def _render_consensus(self, palette: Palette, base: Metrics, opts: RenderOptions, min_ligands: int,
1294
+ thumbnails: bool) -> tuple:
1295
+ all_rows = self.consensus()
1296
+ rows = [r for r in all_rows if r.n_ligands >= min_ligands]
1297
+ via = self.contact_via()
1298
+ levels = self._levels(all_rows, opts)
1299
+ notes, degraded = self._member_notes(opts)
1300
+ notes.extend(self._two_names())
1301
+ apart = self._numbered_otherwise()
1302
+ if apart:
1303
+ notes.append(self._numbering_note(apart))
1304
+ degraded = True
1305
+ rep = self.representative
1306
+ data: dict[str, Any] = {
1307
+ "view": "consensus", "alignment": self.alignment(), "n_ligands": self.n,
1308
+ "drawn_ligand": self.names[rep] if rep is not None else None,
1309
+ "omitted_residues": len(all_rows) - len(rows), "min_ligands": min_ligands,
1310
+ "consensus": [dict(r.as_dict(), via_core=via.get(r.residue, (None, None))[0],
1311
+ via_substituent_only=via.get(r.residue, (None, None))[1],
1312
+ by_confidence=levels.get(r.residue) if levels else None) for r in all_rows],
1313
+ }
1314
+ title = opts.title or f"Consensus contacts of {self.n} ligands"
1315
+ if not rows:
1316
+ page = _Page(base)
1317
+ head = "No interactions in the supplied sets" if not all_rows else "No residue passes the filter"
1318
+ body = (f"All {self.n} ligands were analysed and no contact was found." if not all_rows else
1319
+ f"No residue is contacted by at least {min_ligands} of the {self.n} ligands.")
1320
+ page.text(head, 330.0, fill="text", cls="empty-state", size=base.title_font, bold=True)
1321
+ page.text(body, 330.0, cls="empty-state")
1322
+ return page.build(opts.title, opts.subtitle, self._banner(opts), title), "empty", "empty", None, notes, data
1323
+
1324
+ spatial = rep is not None or all(t is not None for t in self.transforms)
1325
+ q: Quality | None = None
1326
+ best: tuple[Scene, Quality, _Frame, bool] | None = None
1327
+ if not (opts.on_unreadable != "render" and self._hopeless(opts, rows)):
1328
+ # Without a scaffold and without a common pocket there is no geometry to draw; the
1329
+ # frame is then the sequence, which needs no bond length to try.
1330
+ lengths = ([opts.bond_length] if opts.bond_length else list(_BOND_LENGTHS)) if spatial else [0.0]
1331
+ frames: dict[float, _Frame] = {}
1332
+ done = False
1333
+ for thumbs in ((True, False) if (thumbnails and rep is not None) else (False,)):
1334
+ for bl in lengths:
1335
+ if bl not in frames:
1336
+ frames[bl] = (self._consensus_frame(_scaled(base, bl), opts, palette, rows, via, levels)
1337
+ if spatial else self._sequence_frame(base, opts, rows, via, levels))
1338
+ frame = frames[bl]
1339
+ scene = self._consensus_scene(frame, rows, all_rows, opts, palette, thumbs, min_ligands, levels)
1340
+ q = self._quality(scene, frame.m, opts, frame.layout, len(rows),
1341
+ _THUMB_FONT if thumbs else _NOTE)
1342
+ if best is None or _better(q, best[1]):
1343
+ best = (scene, q, frame, thumbs)
1344
+ if q.valid and q.readable:
1345
+ best = (scene, q, frame, thumbs)
1346
+ done = True
1347
+ break
1348
+ if done:
1349
+ break
1350
+ if best is not None:
1351
+ scene, q, frame, thumbs = best
1352
+ data["frame"] = frame.mode
1353
+ data["thumbnails"] = thumbs
1354
+ if thumbnails and rep is not None and not thumbs and q.valid and q.readable:
1355
+ notes.append("the ligand thumbnails were left out to keep the text readable at the figure size")
1356
+ if frame.graph is not None:
1357
+ data["_graph"] = _on_page(frame.graph, scene)
1358
+ if q.valid and q.readable:
1359
+ return scene, "degraded" if degraded else "ok", "consensus", q, notes, data
1360
+ if not q.valid:
1361
+ reason = (f"{q.unplaced} residue(s) could not be placed, {q.overlaps} pair(s) overlap and "
1362
+ f"{q.link_hits} line(s) cross a residue")
1363
+ else:
1364
+ # (The smallest text of the view as it was drawn: with the ligands small beside it, or without.)
1365
+ reason = (beyond_any_page((_THUMB_FONT if thumbs else _NOTE) * _PT_PER_PX, opts, fixed=True)
1366
+ or too_small_on_page(q.min_font_pt, q.required_width_mm, q.width, q.height, opts))
1367
+ if opts.on_unreadable == "render":
1368
+ message = f"a consensus view of this set is not readable: {reason}; rendered anyway on request"
1369
+ return scene, "unreadable", "consensus", q, notes + [message], data
1370
+ else:
1371
+ reason = beyond_any_page(_NOTE * _PT_PER_PX, opts, fixed=True) or (
1372
+ f"{len(rows)} residue nodes cannot be set in one frame at {opts.figure_width_mm:g} mm "
1373
+ f"with {opts.min_font_pt:g} pt text")
1374
+ message = f"a consensus view of this set is not readable: {reason}"
1375
+ data.pop("_graph", None) # no node-level figure is handed out
1376
+ if opts.on_unreadable == "none":
1377
+ return None, "unreadable", "none", q, notes + [message], data
1378
+ table, tw, th = self._consensus_table(rows, base, opts.figure_width_mm * _PX_PER_MM - 2.0 * base.margin,
1379
+ levels, via)
1380
+ why = (f"A consensus diagram of this set is not readable at {opts.figure_width_mm:g} mm: {reason}. "
1381
+ "Contacts are listed per residue instead.")
1382
+ foot = [self._core_sentence(),
1383
+ "Bar: share of the ligands that contact the residue. Codes give the interaction types and how "
1384
+ "many ligands make each."]
1385
+ scene = self._summary_page(base, opts, "Consensus contacts by residue", why, table, tw, th, foot, title)
1386
+ return (scene, "unreadable", "summary", q, notes + [message + "; a per-residue summary was drawn instead"],
1387
+ data)
1388
+
1389
+ def _hopeless(self, opts: RenderOptions, rows: Sequence[ConsensusRow]) -> bool:
1390
+ """Can this many nodes not possibly be read around one frame? A lower bound, no layout run."""
1391
+ # A node with its annotation takes about 46 x 60 units; packed without any gap they cover this much.
1392
+ area = len(rows) * 46.0 * 60.0
1393
+ side = math.sqrt(area * 1.6)
1394
+ fit = min(opts.figure_width_mm * _PX_PER_MM / side, 1.0)
1395
+ return _NOTE * _PT_PER_PX * fit < opts.min_font_pt - 1e-9
1396
+
1397
+ def _rep_atoms(self, rep: int, key: tuple[str, int, str], ctx: Context) -> list[int]:
1398
+ """Where on the drawn ligand a residue belongs: the atoms it contacts, or -- for a residue
1399
+ that only other ligands contact -- the drawn ligand's atoms nearest to it in its own structure.
1400
+ Empty when the residue cannot be found at all."""
1401
+ for grp in ctx.groups:
1402
+ if grp.key == key:
1403
+ atoms = sorted({i for r in grp.interactions if r.ligand is not None for i in r.ligand.atoms})
1404
+ if atoms:
1405
+ return atoms[:4]
1406
+ dia = self.diagrams[rep]
1407
+ st = dia.structure
1408
+ res = st.find_residue(key[0] or None, key[1], key[2]) if st is not None else None
1409
+ if st is None or res is None:
1410
+ return []
1411
+ pts = np.array([a.xyz for a in st.residue_atoms(res) if a.element not in ("H", "D")], dtype=float)
1412
+ d = np.linalg.norm(dia.ligand.coords3d[:, None, :] - pts[None, :, :], axis=2).min(axis=1)
1413
+ order = sorted(range(len(d)), key=lambda i: (round(float(d[i]), 3), i))
1414
+ return [i for i in order if d[i] <= d[order[0]] + 0.75][:3]
1415
+
1416
+ def _consensus_frame(self, m: Metrics, opts: RenderOptions, palette: Palette, rows: Sequence[ConsensusRow],
1417
+ via: dict, levels: dict | None) -> _Frame:
1418
+ bl = m.bond_length
1419
+ rep = self.representative
1420
+ extra: list[tuple[float, float, float]] = []
1421
+ info: dict[str, Any] = {}
1422
+ if rep is not None:
1423
+ coords, mode = self._coords(rep)
1424
+ ctx = self._contexts(m, opts, palette, coords)[rep]
1425
+ obstacle = ctx.dep
1426
+ anchors = {r.residue: self._rep_atoms(rep, r.residue, ctx) for r in rows}
1427
+ middle = obstacle.centroid(range(obstacle.n_heavy))
1428
+ targets = {res: ([obstacle.pos(i) for i in idx] or [middle]) for res, idx in anchors.items()}
1429
+ contexts = [ctx]
1430
+ info["coords"] = coords
1431
+ info["anchors"] = anchors
1432
+ else:
1433
+ # No common scaffold: no ligand is drawn. The frame is the pocket itself -- the
1434
+ # superposed poses seen in their best-fit plane -- and residues go where they are contacted.
1435
+ mode = "envelope"
1436
+ scale = bl / 1.5 * 0.85
1437
+ clouds = self._clouds()
1438
+ plane = pose_frame(clouds)
1439
+ pts = [plane.project(c) * scale for c in clouds]
1440
+ where: dict[tuple[str, int, str], list[np.ndarray]] = {}
1441
+ for k, dia in enumerate(self.diagrams):
1442
+ for hit in dia.interactions:
1443
+ if hit.ligand is not None:
1444
+ where.setdefault(_residue_of(hit), []).extend(pts[k][i] for i in hit.ligand.atoms)
1445
+ cloud = np.vstack(pts)
1446
+ centre = cloud.mean(axis=0)
1447
+ targets = {}
1448
+ for r in rows:
1449
+ hits = where.get(r.residue)
1450
+ p = np.mean(hits, axis=0) if hits else centre
1451
+ targets[r.residue] = [(float(p[0]), float(p[1]))]
1452
+ extra = [(float(x), float(y), 0.62 * bl) for x, y in cloud]
1453
+ obstacle = Depiction(atoms=[], bonds=[], rings=[], n_heavy=0, metrics=m)
1454
+ contexts = []
1455
+ info["points"] = cloud
1456
+ with_chain = len({r.chain for r in rows}) > 1
1457
+ bodies = []
1458
+ for row in rows:
1459
+ node, body_r, note = self._consensus_node(row, with_chain, via, levels)
1460
+ ts = targets[row.residue]
1461
+ ports = [Port((0.0, 0.0), t, ideal=body_r + 0.95 * bl, weight=1.0 / len(ts), drawn=False) for t in ts]
1462
+ bodies.append(_node_body(node, body_r, ports, note, float(row.n_ligands), 0.5 * bl))
1463
+ layout, fld = self._lay_out(m, bodies, obstacle, extra)
1464
+ info["targets"] = targets
1465
+ frame = _Frame(m, bodies, layout, contexts, mode, fld, info)
1466
+ return self._with_consensus_graph(frame, via)
1467
+
1468
+ def _with_consensus_graph(self, frame: _Frame, via: dict) -> _Frame:
1469
+ """Give a consensus frame its graph, and the poses its nodes are then drawn from.
1470
+
1471
+ A consensus node stands for a set of ligands. Its ``occupancy`` is the
1472
+ share of them that contact the residue at all; each of its contacts is
1473
+ one interaction type, with the share of ligands making it as its
1474
+ ``occupancy`` -- the records of :meth:`consensus_contacts`. No contact
1475
+ has a ligand end: no ligand's atoms are being claimed.
1476
+ """
1477
+ m = frame.m
1478
+ graph = Graph(view="consensus", bond_length=float(m.bond_length),
1479
+ ensemble=f"the {self.n} ligands of the set",
1480
+ springs=engine_springs(LayoutParams(unit=m.bond_length)))
1481
+ part = None
1482
+ if frame.mode == "core":
1483
+ ctx = frame.contexts[0]
1484
+ conf = ctx.confidence
1485
+ part = LigandPart(ctx.dep, label=self.names[self.representative or 0],
1486
+ plddt=conf.ligand_atoms if conf is not None else None)
1487
+ residues = []
1488
+ for body in frame.bodies:
1489
+ node: _Node = body.payload
1490
+ row = node.row
1491
+ assert row is not None
1492
+ pose = frame.layout.poses.get(body.key)
1493
+ contacts = [Contact(id=f"{node.ident}|{c.type.value}", type=c.type.value, residue="R:" + node.ident,
1494
+ ligand=None, drawn=False, distance=c.distance, occupancy=c.occupancy,
1495
+ confidence=c.confidence) for c in row.contacts]
1496
+ graph.contacts.extend(contacts)
1497
+ attrs: dict[str, Any] = {"resname": node.resname, "chain": node.key[0], "number": node.key[1],
1498
+ "class": residue_class(node.resname), "form": "consensus",
1499
+ "radius": round(node.radius, 3), "n_ligands": row.n_ligands,
1500
+ "n_total": row.n_total, "ligands": list(row.ligands)}
1501
+ if node.key[2]:
1502
+ attrs["icode"] = node.key[2]
1503
+ if row.levels is not None:
1504
+ attrs["by_confidence"] = list(row.levels)
1505
+ if via:
1506
+ attrs["via_core"], attrs["via_substituent_only"] = via.get(row.residue, (0, 0))
1507
+ anchors: tuple[str, ...] = ()
1508
+ if part is not None:
1509
+ names = [part.dep.atoms[i].name for i in frame.extra["anchors"].get(row.residue, [])]
1510
+ anchors = tuple(f"L:{n}" for n in names if n)
1511
+ elif frame.mode == "envelope":
1512
+ attrs["anchor_point"] = [float(v) for v in frame.extra["targets"][row.residue][0]]
1513
+ residues.append(Node(id="R:" + node.ident, kind="residue", label=row.label,
1514
+ x=None if pose is None else float(pose.x), y=None if pose is None else float(pose.y),
1515
+ anchors=anchors, spring=float(sum(p.weight for p in body.ports)) or None,
1516
+ contacts=tuple(c.id for c in contacts), occupancy=row.occupancy, attrs=attrs))
1517
+ graph.nodes = (part.nodes() if part is not None else []) + residues
1518
+ graph.groups = [part.rigid_group()] if part is not None else []
1519
+ graph.meta = {"ligands": list(self.names), "frame": frame.mode,
1520
+ "drawn_ligand": self.names[self.representative] if self.representative is not None else None}
1521
+ frame.graph = graph
1522
+ frame.poses, _ = poses_from(graph, frame.bodies, tethered=False)
1523
+ return frame
1524
+
1525
+ def _consensus_node(self, row: ConsensusRow, with_chain: bool, via: dict, levels: dict | None
1526
+ ) -> tuple[_Node, float, tuple[float, float]]:
1527
+ """A consensus node, the radius it occupies with its ring, and the size of its annotation."""
1528
+ name, number = _node_text(row.resname, row.residue, with_chain)
1529
+ if via and via.get(row.residue, (1, 0))[0] == 0:
1530
+ number += _SUBSTITUENT
1531
+ radius = _node_radius(name, number) + 3.0 * row.fraction
1532
+ node = _Node(row.residue, row.resname, name, number, radius, ring=radius + 4.2, row=row)
1533
+ lv = levels.get(row.residue) if levels else None
1534
+ count = f"{row.n_ligands}/{self.n}" + (MARK if (lv is not None and lv[0] + lv[1] == 0) else "")
1535
+ _, tw = _code_spans([t for t, _ in row.types], counts=dict(row.types), sep=" \u00b7 ")
1536
+ note = (max(text_width(count, _FONT, bold=True), tw) + 2.0, CAP_HEIGHT * _FONT + CAP_HEIGHT * _NOTE + 8.0)
1537
+ return node, node.ring + 2.4, note
1538
+
1539
+ def _sequence_frame(self, m: Metrics, opts: RenderOptions, rows: Sequence[ConsensusRow], via: dict,
1540
+ levels: dict | None) -> _Frame:
1541
+ """The frame of last resort: residues in sequence order.
1542
+
1543
+ Used when the set has neither a common scaffold nor a common pocket to
1544
+ look at. Sequence order is a property of the residues themselves, so the
1545
+ arrangement is the same for every ligand and claims nothing about where
1546
+ in space a residue is. Runs of neighbouring residues are kept together
1547
+ and labelled with their range.
1548
+ """
1549
+ ordered = sorted(rows, key=lambda r: (r.chain, r.number, r.icode))
1550
+ with_chain = len({r.chain for r in rows}) > 1
1551
+ built = [self._consensus_node(row, with_chain, via, levels) for row in ordered]
1552
+ widths = [max(2.0 * body_r, note[0]) + 10.0 for _, body_r, note in built]
1553
+ top = max(body_r for _, body_r, _ in built)
1554
+ cell_h = top + max(body_r + 2.0 + note[1] for _, body_r, note in built) + 8.0
1555
+ max_w = self._text_width(m, opts)
1556
+ # Runs: consecutive residues no more than a few positions apart.
1557
+ runs: list[list[int]] = []
1558
+ for i, row in enumerate(ordered):
1559
+ prev = ordered[i - 1] if i else None
1560
+ if prev is not None and prev.chain == row.chain and row.number - prev.number <= 6:
1561
+ runs[-1].append(i)
1562
+ else:
1563
+ runs.append([i])
1564
+ label_h = 15.0
1565
+ run_gap = 18.0
1566
+ line_h = label_h + cell_h + 10.0
1567
+ poses: dict[Any, Pose] = {}
1568
+ marks: list[Item] = []
1569
+ x, y = 0.0, 0.0
1570
+
1571
+ def close(part: list[int], x0: float, x1: float, y0: float) -> None:
1572
+ """Label a stretch of one run with its residue range."""
1573
+ if not part:
1574
+ return
1575
+ first, last = ordered[part[0]], ordered[part[-1]]
1576
+ label = (f"{first.number}{first.icode}" if len(part) == 1 else
1577
+ f"{first.number}{first.icode}\u2013{last.number}{last.icode}")
1578
+ if with_chain and first.chain:
1579
+ label = f"{first.chain}:{label}"
1580
+ marks.append(Line(x0 + 3.0, y0 + label_h - 3.0, x1 - 3.0, y0 + label_h - 3.0,
1581
+ Paint(stroke="panel_border", width=1.0, cap="butt")))
1582
+ marks.append(Text.plain(x0 + 3.0, y0 + CAP_HEIGHT * _NOTE, label, _NOTE, "text_muted", anchor="start"))
1583
+
1584
+ for run in runs:
1585
+ total = sum(widths[i] for i in run)
1586
+ if x > 0.0 and x + total > max_w and total <= max_w:
1587
+ x, y = 0.0, y + line_h # keep a run on one line when it fits on one
1588
+ part: list[int] = []
1589
+ x0 = x
1590
+ for i in run:
1591
+ if part and x + widths[i] > max_w:
1592
+ close(part, x0, x, y) # a run longer than the line continues below
1593
+ part, x, y = [], 0.0, y + line_h
1594
+ x0 = 0.0
1595
+ poses[built[i][0].key] = Pose(x + widths[i] / 2.0, y + label_h + top + 3.0)
1596
+ part.append(i)
1597
+ x += widths[i]
1598
+ close(part, x0, x, y)
1599
+ x += run_gap
1600
+ bodies = [_node_body(node, body_r, [], note, float(node.row.n_ligands if node.row else 0), 0.0)
1601
+ for node, body_r, note in built]
1602
+ layout = LayoutResult(poses=poses, unplaced=[], cost=0.0, overlaps=0, line_crossings=0, bond_crossings=0,
1603
+ max_stretch=0.0)
1604
+ return self._with_consensus_graph(_Frame(m, bodies, layout, [], "sequence", None, {"marks": marks}), via)
1605
+
1606
+ def _consensus_nodes(self, frame: _Frame, levels: dict | None) -> tuple[list[Item], set[int], list[str]]:
1607
+ out: list[Item] = []
1608
+ seen_levels: set[int] = set()
1609
+ classes: list[str] = []
1610
+ cap = CAP_HEIGHT * _FONT
1611
+ by_level = {lk.level: lk for lk in (LOOKS["confident"], LOOKS["low"], LOOKS["very_low"])}
1612
+ for body in frame.bodies:
1613
+ pose = frame.poses.get(body.key)
1614
+ if pose is None:
1615
+ continue
1616
+ node: _Node = body.payload
1617
+ row = node.row
1618
+ assert row is not None
1619
+ cls = residue_class(node.resname)
1620
+ if cls not in classes:
1621
+ classes.append(cls)
1622
+ lv = levels.get(row.residue) if levels else None
1623
+ counts = lv if lv is not None else [row.n_ligands, 0, 0]
1624
+ types = ", ".join(f"{t.label.lower()} ({n})" for t, n in row.types)
1625
+ g = Group("residue", data={"residue": node.ident, NUMBER: node.numbered, "class": cls, "form": "consensus",
1626
+ "n-ligands": str(row.n_ligands), "n-total": str(self.n),
1627
+ "fraction": f"{row.fraction:.3f}",
1628
+ "types": ",".join(t.value for t, _ in row.types)},
1629
+ title=f"{row.label}: contacted by {row.n_ligands} of {self.n} ligands; {types}")
1630
+ if lv is not None:
1631
+ g.data["confident"] = str(lv[0])
1632
+ x, y = pose.x, pose.y
1633
+ # The ring: a faint full track, and an arc as long as the share of ligands that
1634
+ # contact the residue -- heavy where that contact is confidently predicted.
1635
+ g.add(Circle(x, y, node.ring, Paint(stroke="panel_border", width=0.8)))
1636
+ a0 = -math.pi / 2.0
1637
+ for level in (0, 1, 2):
1638
+ if not counts[level]:
1639
+ continue
1640
+ if lv is not None:
1641
+ seen_levels.add(level)
1642
+ look = by_level[level]
1643
+ sweep = 2.0 * math.pi * counts[level] / self.n
1644
+ g.add(Polyline(_arc(x, y, node.ring, a0, a0 + sweep),
1645
+ Paint(stroke="text", width=3.2 * look.width, opacity=look.opacity, cap="butt")))
1646
+ a0 += sweep
1647
+ g.add(Circle(x, y, node.radius, Paint(fill=f"class_{cls}", stroke="bubble_line", width=0.9,
1648
+ opacity=0.5 + 0.5 * row.fraction)))
1649
+ major = row.fraction >= 0.5
1650
+ g.add(Text.plain(x, y - 1.1, node.name, _FONT, "bubble_text", bold=major))
1651
+ g.add(Text.plain(x, y + cap + 1.1, node.number, _FONT, "bubble_text"))
1652
+ count = f"{row.n_ligands}/{self.n}" + (MARK if (lv is not None and lv[0] + lv[1] == 0) else "")
1653
+ top = y + node.note_at
1654
+ g.add(Text.plain(x, top + cap + 1.5, count, _FONT, "text", bold=major))
1655
+ spans, _ = _code_spans([t for t, _ in row.types], counts=dict(row.types), sep=" · ")
1656
+ g.add(Text(x, top + cap + CAP_HEIGHT * _NOTE + 6.0, spans, _NOTE, "text_muted"))
1657
+ out.append(g)
1658
+ return out, seen_levels, classes
1659
+
1660
+ def _envelope(self, frame: _Frame) -> list[Item]:
1661
+ """The footprint of the superposed poses: where the ligands are, without drawing any one of them."""
1662
+ fld = frame.fld
1663
+ assert fld is not None
1664
+ loops = fld.contours(1.0)
1665
+ out: list[Item] = []
1666
+ if loops:
1667
+ sign = polygon_area(loops[0]) >= 0
1668
+ for loop in loops:
1669
+ if (polygon_area(loop) >= 0) != sign or len(loop) < 12:
1670
+ continue
1671
+ pts = resample_closed(loop, 4.0)
1672
+ for _ in range(3):
1673
+ pts = (np.roll(pts, 1, axis=0) + pts + np.roll(pts, -1, axis=0)) / 3.0
1674
+ out.append(Polyline(tuple((float(px), float(py)) for px, py in pts),
1675
+ Paint(fill="exposure", stroke="panel_border", width=1.0, opacity=0.45,
1676
+ dash=(3.0, 2.4)), closed=True))
1677
+ for px, py in frame.extra["points"]:
1678
+ out.append(Circle(float(px), float(py), 1.25, Paint(fill="text_muted", opacity=0.4)))
1679
+ return out
1680
+
1681
+ def _thumbnails(self, coords: list[dict], palette: Palette, max_w: float) -> tuple[Group, float, float]:
1682
+ """Every ligand of an aligned set, small, on the common core: the core faint, what differs in ink."""
1683
+ ms = Metrics().with_(bond_length=11.5, bond_width=1.0, double_offset=2.2, wedge_width=3.0, hash_spacing=1.6,
1684
+ label_gap=1.1, atom_font=8.0, sub_font=_THUMB_FONT, charge_font=_THUMB_FONT)
1685
+ deps = [_frame_depiction(d.ligand, ms, xy) for d, xy in zip(self.diagrams, coords)]
1686
+ boxes = [dep.bounds() for dep in deps]
1687
+ box = (min(b[0] for b in boxes), min(b[1] for b in boxes), max(b[2] for b in boxes), max(b[3] for b in boxes))
1688
+ font = 9.0
1689
+ cell_w = max(box[2] - box[0], 96.0)
1690
+ captions = [wrap_text(nm, font, cell_w, bold=True)[:2] for nm in self.names]
1691
+ cap_h = max(len(c) for c in captions) * font * 1.3 + font * 1.3
1692
+ cell_h = box[3] - box[1] + 5.0 + cap_h
1693
+ gap = 14.0
1694
+ per_row = max(1, int((max_w + gap) // (cell_w + gap)))
1695
+ per_row = min(per_row, -(-self.n // max(1, -(-self.n // per_row)))) # balance the rows
1696
+ g = Group("thumbnails")
1697
+ for k, dep in enumerate(deps):
1698
+ core = self.core_atoms(k)
1699
+ looks = [PLAIN if (a.name and a.name not in core) else _FADED for a in dep.atoms]
1700
+ lig = draw_ligand(dep, palette, ms, looks)
1701
+ lig.translate = ((cell_w - (box[2] - box[0])) / 2.0 - box[0], -box[1])
1702
+ y = box[3] - box[1] + 5.0
1703
+ items: list[Item] = [lig]
1704
+ for line in captions[k]:
1705
+ items.append(Text.plain(cell_w / 2.0, y + CAP_HEIGHT * font, line, font, "text", bold=True))
1706
+ y += font * 1.3
1707
+ n_bits = len(self.fingerprints[k])
1708
+ items.append(Text.plain(cell_w / 2.0, y + CAP_HEIGHT * font, f"{n_bits} contact{'s' if n_bits != 1 else ''}",
1709
+ font, "text_muted"))
1710
+ cell = Group("thumbnail", items, data={"ligand": self.names[k]})
1711
+ cell.translate = ((k % per_row) * (cell_w + gap), (k // per_row) * (cell_h + 10.0))
1712
+ g.add(cell)
1713
+ n_rows = -(-self.n // per_row)
1714
+ return g, per_row * cell_w + (per_row - 1) * gap, n_rows * cell_h + (n_rows - 1) * 10.0
1715
+
1716
+ def _consensus_scene(self, frame: _Frame, rows: Sequence[ConsensusRow], all_rows: Sequence[ConsensusRow],
1717
+ opts: RenderOptions, palette: Palette, thumbs: bool, min_ligands: int,
1718
+ levels: dict | None) -> Scene:
1719
+ m = frame.m
1720
+ rep = self.representative
1721
+ nodes, seen_levels, classes = self._consensus_nodes(frame, levels)
1722
+ content = Group("diagram")
1723
+ if frame.mode == "envelope":
1724
+ content.add(Group("envelope", self._envelope(frame)))
1725
+ elif frame.mode == "sequence":
1726
+ content.add(Group("sequence-frame", list(frame.extra["marks"])))
1727
+ else:
1728
+ assert rep is not None
1729
+ ctx = frame.contexts[0]
1730
+ conf = ctx.confidence
1731
+ looks = atom_looks(ctx.dep, conf.ligand_atoms) if conf is not None else None
1732
+ if looks:
1733
+ seen_levels |= {lk.level for lk in looks}
1734
+ ligand = draw_ligand(ctx.dep, palette, m, looks)
1735
+ ligand.data["ligand"] = self.names[rep]
1736
+ content.add(ligand)
1737
+ content.add(Group("residues", nodes))
1738
+ box = items_bounds([content]) or (0.0, 0.0, 1.0, 1.0)
1739
+ cw, ch = box[2] - box[0], box[3] - box[1]
1740
+ content.translate = (-box[0], -box[1])
1741
+
1742
+ page = _Page(m)
1743
+ wrap = max(cw, self._text_width(m, opts))
1744
+ if frame.mode == "envelope":
1745
+ more = (f" No ligand is drawn: the shaded area is the footprint of the {self.n} superposed poses, and "
1746
+ "each residue stands where it is contacted.")
1747
+ elif frame.mode == "sequence":
1748
+ more = (" " + self._superposition_sentence() + " No ligand is drawn, and the residues are set out in "
1749
+ "sequence order: their place says where they are in the chain, not in the pocket.")
1750
+ else:
1751
+ assert rep is not None
1752
+ more = (f" Drawn: {self.names[rep]}, the member closest to that substructure; each residue stands by "
1753
+ "the atoms that are nearest to it.")
1754
+ page.text(self._alignment_sentence(frame.mode, more), wrap, gap=4.0)
1755
+ models = self._models_line(opts, m.caption_font + 1.0)
1756
+ if models is not None:
1757
+ page.add(*models, gap=6.0)
1758
+ page.add(Group("panel", [content], data={"view": "consensus"}), cw, ch, gap=10.0)
1759
+ if thumbs:
1760
+ # As wide as the page may get before the thumbnails' smallest text drops under the minimum.
1761
+ room = (opts.figure_width_mm * _PX_PER_MM * _THUMB_FONT * _PT_PER_PX / opts.min_font_pt
1762
+ - 2.0 * m.margin)
1763
+ tg, tw, th = self._thumbnails(frame.extra["coords"], palette, max(wrap, room))
1764
+ page.text(f"The {self.n} ligands, each on the common substructure (drawn faint); what differs is in ink.",
1765
+ wrap, gap=12.0)
1766
+ page.add(tg, tw, th, gap=6.0)
1767
+ else:
1768
+ page.text(f"Ligands ({self.n}): " + ", ".join(self.names) + ".", wrap, gap=10.0)
1769
+
1770
+ if opts.legend:
1771
+ legend = [LegendEntry(_CLASS_LABEL[c], "swatch", token=f"class_{c}", stroke="bubble_line")
1772
+ for c in _CLASS_ORDER if c in classes]
1773
+ kinds = [t for t in TYPE_ORDER if any(t is kt for r in rows for kt, _ in r.types)]
1774
+ legend.extend(LegendEntry(f"{TYPE_CODES[t]} = {t.label.lower()}") for t in kinds)
1775
+ if any(n.payload.number.endswith(_SUBSTITUENT) for n in frame.bodies):
1776
+ legend.append(LegendEntry(f"{_SUBSTITUENT} contacted only through atoms outside the common "
1777
+ "substructure"))
1778
+ legend.extend(confidence_legend(seen_levels))
1779
+ lg, lw, lh = legend_group(legend, m, wrap)
1780
+ page.add(lg, lw, lh, gap=10.0)
1781
+ if opts.caption:
1782
+ foot = (f"Ring: share of the {self.n} ligands that contact the residue; n/{self.n} below it, then the "
1783
+ "interaction types with the number of ligands making each. No per-ligand lines are drawn.")
1784
+ page.text(foot, wrap, cls="footnotes")
1785
+ if levels is not None:
1786
+ page.text("A ring segment is heavy where the contact is confidently predicted (pLDDT ≥ 70, the "
1787
+ f"lower of ligand-atom and residue value) and lighter below; {MARK} after a count means "
1788
+ "no ligand's contact with that residue reaches pLDDT 50.", wrap, cls="footnotes", gap=3.0)
1789
+ omitted = len(all_rows) - len(rows)
1790
+ if omitted:
1791
+ page.text(f"{omitted} residue{'s' if omitted != 1 else ''} contacted by fewer than {min_ligands} "
1792
+ f"ligands {'are' if omitted != 1 else 'is'} not shown.", wrap, cls="footnotes", gap=3.0)
1793
+ return page.build(opts.title, opts.subtitle, self._banner(opts),
1794
+ opts.title or f"Consensus contacts of {self.n} ligands",
1795
+ f"Consensus view of {self.n} ligands. " + self._core_sentence())
1796
+
1797
+ def _consensus_table(self, rows: Sequence[ConsensusRow], m: Metrics, max_w: float, levels: dict | None,
1798
+ via: dict) -> tuple[Group, float, float]:
1799
+ font = m.legend_font
1800
+ row_h = font * 1.7
1801
+ bar_w = 64.0
1802
+ name_w = max(text_width(r.label + _SUBSTITUENT, font, bold=True) for r in rows) + 10.0
1803
+ count_w = text_width(f"{self.n}/{self.n}{MARK}", font, bold=True) + 10.0
1804
+ type_w = max(_code_spans([t for t, _ in r.types], counts=dict(r.types), sep=" · ")[1] for r in rows) + 6.0
1805
+ block_w = name_w + count_w + bar_w + 12.0 + type_w
1806
+ gutter = 28.0
1807
+ fit = max(1, int((max_w + gutter) // (block_w + gutter)))
1808
+ n_blocks = max(1, min(fit, -(-len(rows) // 12)))
1809
+ per = -(-len(rows) // n_blocks)
1810
+ by_level = {lk.level: lk for lk in (LOOKS["confident"], LOOKS["low"], LOOKS["very_low"])}
1811
+ g = Group("summary-table")
1812
+ head_h = row_h * 1.15
1813
+ for blk in range(n_blocks):
1814
+ x0 = blk * (block_w + gutter)
1815
+ part = rows[blk * per:(blk + 1) * per]
1816
+ if not part:
1817
+ continue
1818
+ g.add(Text.plain(x0, CAP_HEIGHT * font, "Residue", font * 0.9, "text_muted", anchor="start"))
1819
+ g.add(Text.plain(x0 + name_w, CAP_HEIGHT * font, "ligands", font * 0.9, "text_muted", anchor="start"))
1820
+ g.add(Text.plain(x0 + name_w + count_w + bar_w + 12.0, CAP_HEIGHT * font, "types", font * 0.9,
1821
+ "text_muted", anchor="start"))
1822
+ g.add(Line(x0, head_h - 3.0, x0 + block_w, head_h - 3.0, Paint(stroke="panel_border", width=0.8,
1823
+ cap="butt")))
1824
+ for r, row in enumerate(part):
1825
+ y = head_h + r * row_h
1826
+ if r % 2 == 1:
1827
+ g.add(Rect(x0 - 3.0, y, block_w + 6.0, row_h, Paint(fill="panel"), rx=2.0))
1828
+ basel = y + row_h / 2.0 + CAP_HEIGHT * font / 2.0
1829
+ lv = levels.get(row.residue) if levels else None
1830
+ only_sub = via.get(row.residue, (1, 0))[0] == 0 if via else False
1831
+ rg = Group("residue", data={"residue": f"{row.chain}:{row.resname}{row.number}{row.icode}",
1832
+ NUMBER: f"{row.number}{row.icode}",
1833
+ "n-ligands": str(row.n_ligands), "n-total": str(self.n),
1834
+ "form": "row"})
1835
+ rg.add(Text.plain(x0, basel, row.label + (_SUBSTITUENT if only_sub else ""), font, "text",
1836
+ anchor="start", bold=row.fraction >= 0.5))
1837
+ count = f"{row.n_ligands}/{self.n}" + (MARK if (lv is not None and lv[0] + lv[1] == 0) else "")
1838
+ rg.add(Text.plain(x0 + name_w, basel, count, font, "text", anchor="start", bold=row.fraction >= 0.5))
1839
+ bx = x0 + name_w + count_w
1840
+ cy = y + row_h / 2.0
1841
+ rg.add(Line(bx, cy, bx + bar_w, cy, Paint(stroke="panel_border", width=0.8, cap="butt")))
1842
+ counts = lv if lv is not None else [row.n_ligands, 0, 0]
1843
+ x = bx
1844
+ for level in (0, 1, 2):
1845
+ if counts[level]:
1846
+ w = bar_w * counts[level] / self.n
1847
+ look = by_level[level]
1848
+ rg.add(Line(x, cy, x + w, cy, Paint(stroke="text", width=5.0 * look.width,
1849
+ opacity=look.opacity, cap="butt")))
1850
+ x += w
1851
+ spans, _ = _code_spans([t for t, _ in row.types], counts=dict(row.types), sep=" · ")
1852
+ rg.add(Text(bx + bar_w + 12.0, basel, spans, _NOTE, "text_muted", anchor="start"))
1853
+ g.add(rg)
1854
+ return g, n_blocks * block_w + (n_blocks - 1) * gutter, head_h + per * row_h