bindview 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. bindview/__init__.py +88 -0
  2. bindview/__main__.py +6 -0
  3. bindview/align.py +493 -0
  4. bindview/arrange.js +347 -0
  5. bindview/arrange.py +248 -0
  6. bindview/backends.py +290 -0
  7. bindview/basepairs.py +1711 -0
  8. bindview/chains.py +264 -0
  9. bindview/chem.py +57 -0
  10. bindview/clearance.py +123 -0
  11. bindview/cli.py +990 -0
  12. bindview/compare.py +1854 -0
  13. bindview/confidence.py +531 -0
  14. bindview/consensus.py +303 -0
  15. bindview/covalent.py +220 -0
  16. bindview/depict.py +790 -0
  17. bindview/detect.py +378 -0
  18. bindview/diagram.py +1891 -0
  19. bindview/distance_table.py +589 -0
  20. bindview/ensemble.py +787 -0
  21. bindview/errors.py +47 -0
  22. bindview/exposure.py +207 -0
  23. bindview/features.py +179 -0
  24. bindview/fingerprint.py +469 -0
  25. bindview/fragments.py +304 -0
  26. bindview/geometry.py +482 -0
  27. bindview/graph.py +611 -0
  28. bindview/graphbuild.py +431 -0
  29. bindview/interactions.py +418 -0
  30. bindview/interactive.py +334 -0
  31. bindview/interface.py +1329 -0
  32. bindview/ions.py +155 -0
  33. bindview/layout/__init__.py +15 -0
  34. bindview/layout/body.py +421 -0
  35. bindview/layout/engine.py +1084 -0
  36. bindview/layout/field.py +261 -0
  37. bindview/ligand.py +583 -0
  38. bindview/near.py +67 -0
  39. bindview/options.py +92 -0
  40. bindview/pae.py +991 -0
  41. bindview/peptide.py +610 -0
  42. bindview/plane.py +320 -0
  43. bindview/polymer.py +678 -0
  44. bindview/py.typed +0 -0
  45. bindview/report.py +1407 -0
  46. bindview/residues.py +296 -0
  47. bindview/resolve.py +493 -0
  48. bindview/scene.py +239 -0
  49. bindview/solvent.py +254 -0
  50. bindview/structure.py +1145 -0
  51. bindview/styles/__init__.py +2 -0
  52. bindview/styles/absence.py +180 -0
  53. bindview/styles/base.py +2128 -0
  54. bindview/styles/closeup.py +146 -0
  55. bindview/styles/detailed.py +690 -0
  56. bindview/styles/ligand_draw.py +289 -0
  57. bindview/styles/mixed.py +70 -0
  58. bindview/styles/polymer_draw.py +354 -0
  59. bindview/styles/rings.py +75 -0
  60. bindview/styles/schematic.py +311 -0
  61. bindview/styles/summary.py +147 -0
  62. bindview/svg.py +310 -0
  63. bindview/textmetrics.py +64 -0
  64. bindview/theme.py +317 -0
  65. bindview-0.1.0.dist-info/METADATA +270 -0
  66. bindview-0.1.0.dist-info/RECORD +70 -0
  67. bindview-0.1.0.dist-info/WHEEL +4 -0
  68. bindview-0.1.0.dist-info/entry_points.txt +2 -0
  69. bindview-0.1.0.dist-info/licenses/LICENSE +21 -0
  70. bindview-0.1.0.dist-info/licenses/NOTICE +48 -0
@@ -0,0 +1,311 @@
1
+ """The schematic style, after Maestro's Ligand Interaction Diagram.
2
+
3
+ The ligand is drawn exactly as in the detailed style; what changes is how the
4
+ protein is shown. Every residue is a bubble coloured by residue class, pointing
5
+ at the ligand atoms it contacts. Only directional interactions get a line
6
+ (H-bonds as arrows from donor to acceptor, solid for backbone and dashed for
7
+ side chain; pi and charge interactions to ring centroids and charged groups);
8
+ a hydrophobic contact is a stretch of the lining, and beside a ligand that is
9
+ drawn as a chain of residues a fine line as well. The lining is the wall of the
10
+ pocket around the ligand: a stretch for each contact, in the colour of the part
11
+ of the residue that makes it, and open where nothing does (docs/reference.md). Grey
12
+ halos mark ligand atoms that are exposed to solvent.
13
+
14
+ What is drawn here is how this style draws unless it is told otherwise: the
15
+ lines, the lining and the halos are settings (:class:`~.base.Settings`).
16
+
17
+ This module supplies the bodies and the drawing. The chemistry, the anchor
18
+ resolution and the layout engine are those of the detailed style.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import math
24
+ from dataclasses import dataclass
25
+ from typing import TYPE_CHECKING, Sequence
26
+
27
+ import numpy as np
28
+
29
+ from ..confidence import PLAIN, Look, occupancy_factors
30
+ from ..interactions import InteractionType
31
+ from ..interactive import NUMBER
32
+ from ..layout import Body
33
+ from ..scene import Circle, Group, Paint, Path, Text
34
+ from ..textmetrics import CAP_HEIGHT, text_width
35
+ from . import absence as other_protein
36
+ from .base import (_CLASS_LABEL, _CLASS_ORDER, SCHEMATIC_LINKS, SCHEMATIC_SIDECHAIN, STYLE_SETTINGS, Context,
37
+ Drawn, PortInfo, ResidueGroup, Settings, StyleDrawing, finish_drawing, group_skeleton, halo_items, halo_radius,
38
+ hbond_direction, interaction_data, interaction_title, is_distance, lining_claims, link_items, make_ports,
39
+ marked_label, port_infos, predicted_items, predicted_style, residue_occupancy, residue_plddt,
40
+ set_lanes)
41
+ from .rings import ring_items, ring_reach, ring_title
42
+
43
+ if TYPE_CHECKING:
44
+ from ..consensus import ResidueShare
45
+
46
+ __all__ = ["SchematicStyle"]
47
+
48
+ T = InteractionType
49
+
50
+ _STYLES = SCHEMATIC_LINKS
51
+ _HBOND_SIDECHAIN = SCHEMATIC_SIDECHAIN
52
+
53
+ _FONT = 9.5
54
+ _TIP = 1.3 # teardrop tip distance from the centre, in radii
55
+
56
+
57
+ @dataclass
58
+ class _Bubble:
59
+ group: ResidueGroup
60
+ ports: list[PortInfo]
61
+ radius: float
62
+ name: str
63
+ number: str
64
+ plddt: float | None = None # the residue's own pLDDT
65
+ look: Look = PLAIN
66
+ occupancy: float | None = None # that of the residue's most persistent contact
67
+ share: "ResidueShare | None" = None # it stands in a ring: the models that contact it
68
+ form = "bubble"
69
+
70
+ @property
71
+ def ident(self) -> str:
72
+ return self.group.node_ident
73
+
74
+
75
+ def _bubble_text(grp: ResidueGroup, look: Look = PLAIN) -> tuple[str, str]:
76
+ chain, number, icode = grp.key
77
+ num = f"{number}{icode}"
78
+ if "(" in grp.label and chain: # the caller asked for chains to be shown
79
+ num = f"{chain}:{num}"
80
+ return grp.resname.upper(), marked_label(num + ("†" if grp.beyond else ""), look)
81
+
82
+
83
+ #: Outline of a bubble by confidence level: (dash, width factor). Solid, dashed, dotted --
84
+ #: a difference in kind, so it survives greyscale where a paler fill alone would not.
85
+ _OUTLINE: dict[int, tuple[tuple[float, ...], float]] = {0: ((), 1.0), 1: ((3.6, 2.2), 1.0), 2: ((1.1, 2.3), 1.15)}
86
+
87
+
88
+ class SchematicStyle:
89
+ name = "schematic"
90
+
91
+ def __init__(self, settings: "Settings | None" = None) -> None:
92
+ self.settings = settings or STYLE_SETTINGS["schematic"]
93
+
94
+ def ligand_obstacles(self, ctx: Context) -> list[tuple[float, float, float]]:
95
+ return []
96
+
97
+ # ------------------------------------------------------------------ bodies
98
+ def bodies(self, ctx: Context) -> list[Body]:
99
+ return [self.body(ctx, grp) for grp in ctx.groups]
100
+
101
+ def body(self, ctx: Context, grp: ResidueGroup) -> Body:
102
+ m = ctx.metrics
103
+ plddt = residue_plddt(ctx, grp)
104
+ look = ctx.look(plddt)
105
+ name, number = _bubble_text(grp, look)
106
+ width = max(text_width(name, _FONT, bold=True), text_width(number, _FONT))
107
+ radius = max(15.0, math.hypot(width / 2.0, CAP_HEIGHT * _FONT + 1.1) + 2.2)
108
+ infos = _merge_by_target(port_infos(ctx, grp, self.settings.labelled(ctx.options)))
109
+ share = ctx.share_of(grp)
110
+ if share is not None:
111
+ return self._ring_body(ctx, grp, share, infos, look, plddt)
112
+ set_lanes([i for i in infos if i.drawn and i.target.unit is not None]) # merging may have left fewer
113
+ # A bubble is one point; two links from it to one residue of a chain ligand leave it side by side.
114
+ ports = make_ports(ctx, infos, lambda info: ((0.0, info.lane), radius + 1.5, None, radius, None))
115
+ n_drawn = sum(1 for i in infos if i.drawn)
116
+ return Body(
117
+ key=grp.uid, kind="disc", shapes_p0=np.zeros((1, 2)), shapes_p1=np.zeros((1, 2)),
118
+ shapes_r=np.array([radius + 1.5]),
119
+ ports=ports, ligand_clearance=0.95 * m.bond_length, priority=float(n_drawn),
120
+ payload=_Bubble(grp, infos, radius, name, number, plddt, look, residue_occupancy(grp)))
121
+
122
+ def _ring_body(self, ctx: Context, grp: ResidueGroup, share: "ResidueShare", infos: list[PortInfo], look: Look,
123
+ plddt: "float | None") -> Body:
124
+ """A residue that is its ring alone: beside what most of the models have it on, without a line."""
125
+ bl = ctx.metrics.bond_length
126
+ radius = ring_reach(grp.label, share)
127
+ for info in infos:
128
+ info.drawn, info.label = False, None
129
+ ports = make_ports(ctx, infos, lambda info: ((0.0, 0.0), radius, None, radius, None))
130
+ for port, info in zip(ports, infos):
131
+ port.ideal, port.weight = radius + 0.6 * bl, info.occupancy or 0.1
132
+ return Body(
133
+ key=grp.uid, kind="disc", shapes_p0=np.zeros((1, 2)), shapes_p1=np.zeros((1, 2)),
134
+ shapes_r=np.array([radius]), ports=ports, ligand_clearance=0.6 * bl, priority=0.0,
135
+ payload=_Bubble(grp, infos, radius, grp.label, "", plddt, look, share.share, share))
136
+
137
+ # ------------------------------------------------------------------ drawing
138
+ def draw(self, ctx: Context, bodies: list[Body], poses: dict, label_ts: dict | None = None) -> StyleDrawing:
139
+ d = Drawn({"backdrop": [], "halos": [], "interactions": [], "residues": []})
140
+ self.draw_bodies(ctx, bodies, poses, label_ts or {}, d)
141
+ return finish_drawing(ctx, self.settings, d)
142
+
143
+ def draw_bodies(self, ctx: Context, bodies: Sequence[Body], poses: dict, label_ts: dict, d: Drawn) -> None:
144
+ m = ctx.metrics
145
+ layers, kinds, notes = d.layers, d.kinds, d.notes
146
+ links = self.settings.lines
147
+ asked = sorted({level for level in (ctx.detail_of(b.payload.group) for b in bodies)
148
+ if level in ("backbone", "sidechain", "atoms")})
149
+ if asked:
150
+ # A level that was asked for and is not drawn is said, in the result: bubbles have no atoms.
151
+ notes.append(f"the residues around {ctx.dep.called if ctx.dep.units else 'the ligand'} are drawn as "
152
+ f"bubbles, without the atoms that detail {' and '.join(repr(a) for a in asked)} asks "
153
+ f"for: the schematic style has none for them (the detailed style draws them)")
154
+ for body in bodies:
155
+ pose = poses.get(body.key)
156
+ if pose is None:
157
+ continue
158
+ bub: _Bubble = body.payload
159
+ grp = bub.group
160
+ cls = grp.residue_class
161
+ # What the bubble is filled with, and its stretch of the pocket's outline with it: the colour
162
+ # of its class, or, where the figure colours by pLDDT and the residue has one, that of its band.
163
+ fill = ctx.fill_of(bub.look, f"class_{cls}")
164
+ ink = ctx.text_on(bub.look, "bubble_text")
165
+ if fill == f"class_{cls}" and cls not in d.classes:
166
+ d.classes.append(cls)
167
+ d.beyond = d.beyond or grp.beyond
168
+ d.placed.append(((pose.x, pose.y), bub.radius, fill))
169
+ d.claims.extend(lining_claims(ctx, grp, bub.look, bub.ports, [(pose.x, pose.y)] * len(bub.ports)))
170
+ P = np.array([[pose.x, pose.y]])
171
+ A = np.array([0.0])
172
+ M = np.array([False])
173
+ a_all, b_all, _ = body.link_segments(P, A, M)
174
+ label_t = label_ts.get(body.key, ())
175
+ tx = sum(i.target.point[0] for i in bub.ports) / len(bub.ports)
176
+ ty = sum(i.target.point[1] for i in bub.ports) / len(bub.ports)
177
+ theta = math.atan2(ty - pose.y, tx - pose.x)
178
+ look = bub.look
179
+ if ctx.confidence is not None:
180
+ d.levels.add(look.level)
181
+ # A residue that only other models contact is set back like one outside the contact set.
182
+ away = grp.absent or grp.faint
183
+ muted = grp.beyond or away
184
+ opacity = min(look.opacity * occupancy_factors(bub.occupancy, ctx.options.occupancy_style == "steps")[1], 0.55 if muted else 1.0)
185
+ title = f"{grp.label}: " + ", ".join(t.label.lower() for t in grp.types)
186
+ g = Group("residue", data={"residue": grp.ident, NUMBER: grp.numbered, "class": cls, "form": "bubble"},
187
+ title=title)
188
+ if grp.parts > 1:
189
+ g.data["drawing"] = f"{grp.part + 1} of {grp.parts}"
190
+ if bub.plddt is not None and look.band is not None:
191
+ g.data["plddt"] = f"{bub.plddt:.1f}"
192
+ g.data["confidence"] = look.band
193
+ g.title = f"{title}; residue pLDDT {bub.plddt:.0f}"
194
+ dash, wide = _OUTLINE[look.level]
195
+ mark: Group | None = None
196
+ if grp.lost:
197
+ d.lost = True
198
+ g.data[other_protein.FROM] = other_protein.said_of(ctx.options)
199
+ if not grp.faint:
200
+ mark = other_protein.marker_group(grp, ctx.options)
201
+ mark.add(other_protein.disc(pose.x, pose.y, bub.radius))
202
+ layers.setdefault("backdrop", []).append(mark)
203
+ if bub.share is not None:
204
+ d.rings = True
205
+ g.title = ring_title(grp.label, bub.share)
206
+ g.data["n-models"] = f"{bub.share.n_models}/{bub.share.n_total}"
207
+ g.extend(ring_items(pose.x, pose.y, grp.label, bub.share, fill, ink))
208
+ layers["residues"].append(g)
209
+ continue
210
+ if look.level == 0:
211
+ g.add(_teardrop((pose.x, pose.y), bub.radius, theta,
212
+ Paint(fill=fill, stroke="bubble_line", width=0.9, opacity=opacity)))
213
+ else:
214
+ # Fill and outline are separate items: the fill fades, the outline changes kind.
215
+ g.add(_teardrop((pose.x, pose.y), bub.radius, theta, Paint(fill=fill, opacity=opacity)))
216
+ g.add(_teardrop((pose.x, pose.y), bub.radius, theta,
217
+ Paint(stroke="bubble_line", width=0.9 * wide, dash=dash,
218
+ opacity=0.55 if muted else 1.0)))
219
+ cap = CAP_HEIGHT * _FONT
220
+ text_opacity = (0.55 if muted else 1.0) * (1.0 if look.level == 0 else 0.85)
221
+ g.add(Text.plain(pose.x, pose.y - 1.1, bub.name, _FONT, ink, bold=look.level == 0 and not away,
222
+ opacity=text_opacity))
223
+ g.add(Text.plain(pose.x, pose.y + cap + 1.1, bub.number, _FONT, ink, opacity=text_opacity))
224
+ layers["residues"].append(g)
225
+
226
+ for k, info in enumerate(bub.ports):
227
+ d.occupancy = d.occupancy or info.occupancy is not None
228
+ if not info.drawn:
229
+ continue
230
+ if info.predicted:
231
+ d.predicted = True
232
+ elif info.kind is T.HYDROPHOBIC:
233
+ d.whole = True
234
+ elif info.kind not in kinds:
235
+ kinds.append(info.kind)
236
+ if info.plddt is not None:
237
+ d.levels.add(info.look.level)
238
+ d.absent = d.absent or info.absent
239
+ first = info.interactions[0]
240
+ style = predicted_style(links.styles[info.kind]) if info.predicted else links.styles[info.kind]
241
+ arrow = None
242
+ if info.kind in (T.HBOND, T.WATER_BRIDGE) and not info.predicted:
243
+ arrow, note = hbond_direction(first, ctx.dep)
244
+ if note:
245
+ notes.append(note)
246
+ if info.kind is T.HBOND:
247
+ style, which = links.hbond(info, grp)
248
+ d.hbonds.add(which)
249
+ a = (float(a_all[0, k, 0]), float(a_all[0, k, 1]))
250
+ b = (float(b_all[0, k, 0]), float(b_all[0, k, 1]))
251
+ lg = Group(f"interaction {info.kind.value}", data=interaction_data(ctx, grp, info),
252
+ title="; ".join(interaction_title(r, ctx.ligand, info.plddt, ctx.dep)
253
+ for r in info.interactions))
254
+ at = label_t[k] if k < len(label_t) else 0.5
255
+ if info.predicted:
256
+ lg.extend(predicted_items(a, b, info, at, m, style, info.opacity, ctx.options.solvent_mark))
257
+ else:
258
+ lg.extend(link_items(a, b, info.kind, m, label=info.label, arrow=arrow, tag=info.tag,
259
+ opacity=info.opacity, style=style, weight=info.weight, label_at=at,
260
+ glow=info.glow))
261
+ d.glows = d.glows or info.glow is not None
262
+ if info.tag is not None:
263
+ d.tags.append(info.tag[1])
264
+ d.has_distances = d.has_distances or is_distance(info.label)
265
+ if info.target.kind == "ring":
266
+ key = (info.target.atoms, style.token)
267
+ if key not in d.dots_done:
268
+ d.dots_done.add(key)
269
+ lg.add(Circle(info.target.point[0], info.target.point[1], 2.5,
270
+ Paint(fill=style.token, opacity=info.opacity)))
271
+ if style.end_dots:
272
+ lg.add(Circle(a[0], a[1], 2.3, Paint(fill=style.token, opacity=info.opacity)))
273
+ layers["interactions"].append(lg)
274
+ if mark is not None:
275
+ mark.add(other_protein.stroke([a, b], m.interaction_width))
276
+ if info.target.kind == "group" and ctx.options.charge_halos:
277
+ key = (info.target.atoms, style.token)
278
+ if key not in d.halo_done:
279
+ d.halo_done.add(key)
280
+ layers["halos"].extend(halo_items(group_skeleton(ctx.dep, info.target.atoms),
281
+ halo_radius(m), style.token))
282
+
283
+
284
+ def _merge_by_target(infos: list[PortInfo]) -> list[PortInfo]:
285
+ """One link per (interaction type, ligand site).
286
+
287
+ A bubble stands for the whole residue, so two contacts that differ only in
288
+ which protein atom or ring makes them (tryptophan's two rings stacking on
289
+ one ligand ring) would be the same line drawn twice.
290
+ """
291
+ merged: dict[tuple, PortInfo] = {}
292
+ for info in infos:
293
+ key = (info.kind, *info.target.key)
294
+ seen = merged.get(key)
295
+ if seen is None:
296
+ merged[key] = info
297
+ else:
298
+ seen.absorb(info)
299
+ return list(merged.values())
300
+
301
+
302
+ def _teardrop(centre: tuple[float, float], radius: float, theta: float, paint: Paint) -> Path:
303
+ """A disc drawn out to a point in direction ``theta``."""
304
+ cx, cy = centre
305
+ phi = math.acos(1.0 / _TIP)
306
+ tip = (cx + _TIP * radius * math.cos(theta), cy + _TIP * radius * math.sin(theta))
307
+ p1 = (cx + radius * math.cos(theta + phi), cy + radius * math.sin(theta + phi))
308
+ p2 = (cx + radius * math.cos(theta - phi), cy + radius * math.sin(theta - phi))
309
+ reach = _TIP * radius
310
+ return Path((("M", tip[0], tip[1]), ("L", p1[0], p1[1]), ("A", radius, radius, 0, 1, 1, p2[0], p2[1]), ("Z",)),
311
+ paint, bbox=(cx - reach, cy - reach, cx + reach, cy + reach))
@@ -0,0 +1,147 @@
1
+ """Figures for the cases where an atom-level diagram is not the right answer.
2
+
3
+ Two situations, kept strictly apart because they mean different things:
4
+
5
+ * **empty** -- the complex was analysed and nothing was found. The figure shows
6
+ the ligand and says so in words, so nobody mistakes it for a diagram whose
7
+ annotations failed to render.
8
+ * **summary** -- there are interactions, but too many, on too large a ligand,
9
+ for an atom-level drawing to be legible at the requested figure size. Rather
10
+ than a hairball, the contacts are tabulated per residue, and the figure says
11
+ why it is a table.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ from typing import Mapping, Sequence
17
+
18
+ from ..confidence import MARK, look_of
19
+ from ..interactions import InteractionType
20
+ from ..scene import Circle, Group, Item, Line, Paint, Rect, Text
21
+ from ..textmetrics import CAP_HEIGHT, text_width
22
+ from ..theme import Metrics
23
+ from . import absence as other_protein
24
+ from .base import LINK_STYLES, ResidueGroup
25
+
26
+ __all__ = ["wrap_text", "text_block", "summary_table"]
27
+
28
+ T = InteractionType
29
+ _ORDER = [T.HBOND, T.SALTBRIDGE, T.PI_STACKING, T.PI_CATION, T.HALOGEN, T.METAL, T.WATER_BRIDGE, T.HYDROPHOBIC,
30
+ T.COVALENT]
31
+ _SHORT = {T.HBOND: "H-bond", T.SALTBRIDGE: "Salt bridge", T.PI_STACKING: "π–π",
32
+ T.PI_CATION: "π–cation", T.HALOGEN: "Halogen", T.METAL: "Metal",
33
+ T.WATER_BRIDGE: "Water", T.HYDROPHOBIC: "Hydrophobic", T.COVALENT: "Covalent"}
34
+
35
+
36
+ def wrap_text(text: str, size: float, max_width: float, bold: bool = False) -> list[str]:
37
+ """Greedy word wrap using the metrics table."""
38
+ lines: list[str] = []
39
+ cur = ""
40
+ for word in text.split():
41
+ trial = word if not cur else f"{cur} {word}"
42
+ if cur and text_width(trial, size, bold) > max_width:
43
+ lines.append(cur)
44
+ cur = word
45
+ else:
46
+ cur = trial
47
+ if cur:
48
+ lines.append(cur)
49
+ return lines
50
+
51
+
52
+ def text_block(lines: Sequence[str], x: float, y: float, size: float, fill: str, bold: bool = False
53
+ ) -> tuple[list[Item], float]:
54
+ """Stacked lines of text starting at top ``y``, set from the left. Returns ``(items, height)``."""
55
+ items: list[Item] = []
56
+ step = size * 1.45
57
+ for k, line in enumerate(lines):
58
+ items.append(Text.plain(x, y + k * step + CAP_HEIGHT * size, line, size, fill, anchor="start", bold=bold))
59
+ return items, (len(lines) * step if lines else 0.0)
60
+
61
+
62
+ _ABBREVIATED = {T.SALTBRIDGE: "Salt br.", T.PI_STACKING: "\u03c0\u2013\u03c0", T.PI_CATION: "\u03c0\u2013cat.",
63
+ T.HYDROPHOBIC: "Hydroph.", T.WATER_BRIDGE: "Water", T.HALOGEN: "Halog."}
64
+
65
+
66
+ def summary_table(groups: Sequence[ResidueGroup], metrics: Metrics, max_width: float,
67
+ plddt: "Mapping[tuple[str, int, str], float] | None" = None) -> tuple[Group, float, float]:
68
+ """Residue-by-type contact table. Returns ``(group, width, height)``; origin top-left.
69
+
70
+ Long tables are set in as many side-by-side blocks as fit ``max_width``;
71
+ column headings are abbreviated when that is what it takes to fit a second
72
+ block, because a tall single column wastes the figure. With ``plddt``
73
+ (residue key -> value) a confidence column is added and a residue below 70
74
+ is set in regular rather than bold type, below 50 with the mark.
75
+ """
76
+ kinds = [k for k in _ORDER if any(k in g.types for g in groups)]
77
+ font = metrics.legend_font
78
+ head_font = font * 0.9
79
+ row_h = font * 1.7
80
+ name_w = max((text_width(g.label + "\u2020", font, bold=True) for g in groups), default=40.0) + 8.0
81
+ dist_w = text_width("0.00 \u00c5", font) + 8.0
82
+ conf_w = text_width("pLDDT", head_font) + 12.0 if plddt else 0.0
83
+ gutter = 26.0
84
+
85
+ def plan(headers: dict) -> tuple[list[float], float, int]:
86
+ cols = [max(text_width(headers[k], head_font) + 8.0, 30.0) for k in kinds]
87
+ width = name_w + sum(cols) + conf_w + dist_w
88
+ return cols, width, max(1, int((max_width + gutter) // (width + gutter)))
89
+
90
+ headers = dict(_SHORT)
91
+ cols, block_w, fit = plan(headers)
92
+ if len(groups) > 16:
93
+ short = {**_SHORT, **_ABBREVIATED}
94
+ cols2, block_w2, fit2 = plan(short)
95
+ if fit2 > fit:
96
+ headers, cols, block_w, fit = short, cols2, block_w2, fit2
97
+ n_blocks = max(1, min(fit, -(-len(groups) // 10))) # no block shorter than about ten rows
98
+ rows = -(-len(groups) // n_blocks)
99
+ offs = [name_w]
100
+ for c in cols:
101
+ offs.append(offs[-1] + c)
102
+
103
+ g = Group("summary-table")
104
+ head_h = row_h * 1.15
105
+ for blk in range(n_blocks):
106
+ x0 = blk * (block_w + gutter)
107
+ part = list(groups[blk * rows:(blk + 1) * rows])
108
+ if not part:
109
+ continue
110
+ g.add(Text.plain(x0, CAP_HEIGHT * font, "Residue", head_font, "text_muted", anchor="start"))
111
+ for c, k in enumerate(kinds):
112
+ g.add(Text.plain(x0 + offs[c] + cols[c] / 2.0, CAP_HEIGHT * font, headers[k], head_font,
113
+ LINK_STYLES[k].token))
114
+ g.add(Text.plain(x0 + block_w, CAP_HEIGHT * font, "closest", head_font, "text_muted", anchor="end"))
115
+ if plddt:
116
+ g.add(Text.plain(x0 + offs[-1] + conf_w / 2.0, CAP_HEIGHT * font, "pLDDT", head_font, "text_muted"))
117
+ g.add(Line(x0, head_h - 3.0, x0 + block_w, head_h - 3.0, Paint(stroke="panel_border", width=0.8, cap="butt")))
118
+ for r, grp in enumerate(part):
119
+ y = head_h + r * row_h
120
+ if r % 2 == 1:
121
+ g.add(Rect(x0 - 3.0, y, block_w + 6.0, row_h, Paint(fill="panel"), rx=2.0))
122
+ base = y + row_h / 2.0 + CAP_HEIGHT * font / 2.0
123
+ if grp.lost and not grp.faint:
124
+ name = text_width(grp.label, font, bold=True)
125
+ g.add(Group("absence", [other_protein.plate(x0 + name / 2.0, y + row_h / 2.0, name, CAP_HEIGHT * font)],
126
+ data={"residue": grp.ident}, opacity=other_protein.OPACITY))
127
+ value = plddt.get(grp.key) if plddt else None
128
+ look = look_of(value)
129
+ g.add(Text.plain(x0, base, grp.label + ("\u2020" if grp.beyond else ""), font,
130
+ "beyond" if grp.beyond or grp.faint else "text", anchor="start",
131
+ bold=look.level == 0 and not grp.faint, italic=grp.faint))
132
+ if value is not None:
133
+ g.add(Text.plain(x0 + offs[-1] + conf_w / 2.0, base, f"{value:.0f}" + (MARK if look.mark else ""),
134
+ font, "text" if look.level == 0 else "text_muted", bold=look.level == 0))
135
+ for c, k in enumerate(kinds):
136
+ n = sum(1 for i in grp.interactions if i.type is k)
137
+ if not n:
138
+ continue
139
+ cx = x0 + offs[c] + cols[c] / 2.0
140
+ g.add(Circle(cx - (5.5 if n > 1 else 0.0), y + row_h / 2.0, 3.4, Paint(fill=LINK_STYLES[k].token)))
141
+ if n > 1:
142
+ g.add(Text.plain(cx + 1.0, base, f"\u00d7{n}", head_font, LINK_STYLES[k].token, anchor="start"))
143
+ ds = [i.record.distance for i in grp.interactions if i.record.distance is not None]
144
+ if ds:
145
+ g.add(Text.plain(x0 + block_w, base, f"{min(ds):.2f} \u00c5", font, "text_muted", anchor="end"))
146
+ width = n_blocks * block_w + (n_blocks - 1) * gutter
147
+ return g, width, head_h + rows * row_h