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/interface.py ADDED
@@ -0,0 +1,1329 @@
1
+ """An interface: the contacts between two polymer participants, drawn with a focus.
2
+
3
+ A ligand diagram has a centre, the ligand, and the residues stand around it.
4
+ An interface has none. What this module draws instead has a **spine**: the
5
+ residues of one participant that touch the other, as a column of residue boxes
6
+ in the order of their sequence, with a dotted line wherever residues in
7
+ between are left out. The residues of the other participant are drawn around
8
+ that column with their contacts, at the resolution of the style: with the
9
+ atoms that make the contacts, or as bubbles. Resolution is therefore mixed,
10
+ and the figure says which participant is drawn how.
11
+
12
+ A column orders a line, which is the right picture of a binder that is one
13
+ stretch of its chain and the wrong one of three loops that lie side by side.
14
+ Where the residues of the spine come in several stretches they can therefore
15
+ be set out on a **plane**, each box where its residue lies in space
16
+ (:mod:`bindview.plane`), provided that picture is faithful, which is measured
17
+ and written in the figure. That is asked for (``layout="auto"`` lets the rule
18
+ of :meth:`Interface._verdict` choose, ``layout="plane"`` names it); left alone,
19
+ an interface is drawn as a column.
20
+
21
+ An interface is an ordered list of participants with contacts between
22
+ neighbours in that order. Two participants are the plain case. Three are the
23
+ same object: in ``MHC - peptide - receptor`` the middle one touches both and is
24
+ the spine.
25
+
26
+ A whole interface is rarely drawn. A figure holds about thirty residues of the
27
+ spine; with more, or when the whole does not lay out, it narrows to a **site**,
28
+ chosen by a stated rule (:func:`choose_site`), and says which site and how
29
+ much of the interface that is.
30
+
31
+ Nothing here detects contacts. They are supplied
32
+ (:class:`InterfaceContact`, :func:`load_interface_contacts`) or come from PLIP's
33
+ peptide mode behind :func:`bindview.detect.detect_interface`.
34
+ """
35
+
36
+ from __future__ import annotations
37
+
38
+ from dataclasses import dataclass, field, replace
39
+ from operator import index as whole_number
40
+ from pathlib import Path
41
+ from typing import Any, Iterable, Iterator, Mapping, Sequence
42
+
43
+ import numpy as np
44
+
45
+ from .errors import BindviewError, InteractionError
46
+ from .exposure import WATER_NAMES
47
+ from .fragments import check_detail
48
+ from .interactions import Interaction, InteractionType, check_confidence_scale
49
+ from .pae import (IPSAE_CUTOFF, PAE_SHOWN, PAE_STRONG, Ipsae, Pae, PaeDraws, ipsae_of, pae_shown, pae_tag,
50
+ read_pae)
51
+ from .plane import (APART, ERROR_MAX, KEPT_MIN, MIN_RESIDUES, NEAR, STRETCH_GAP, Arrangement, Fidelity, Placed,
52
+ stretches)
53
+ from .structure import ResidueKey, Structure, read_structure
54
+
55
+ __all__ = ["Participant", "InterfaceContact", "Site", "Interface", "InterfaceIpsae", "choose_site",
56
+ "load_interface_contacts", "dump_interface_contacts", "MAX_SPINE", "LAYOUTS"]
57
+
58
+ #: How the residues of the spine are set out: in a ``column`` (the default), on a ``plane`` (each where
59
+ #: it lies in space), or as the rule decides (``auto``; :meth:`Interface._verdict`, in words in
60
+ #: ``Interface.layout_rule``).
61
+ LAYOUTS = ("auto", "column", "plane")
62
+
63
+ #: Residues of the spine a figure shows at most. The default page takes 54 boxes and nothing around
64
+ #: them.
65
+ MAX_SPINE = 30
66
+ #: The carbon and the nitrogen of a peptide bond, or an oxygen and the phosphorus after it, are this near at most (ångström).
67
+ _BOND = 2.0
68
+
69
+ COLUMNS = ("interaction_type", "chain_a", "residue_number_a", "insertion_code_a", "residue_name_a", "atoms_a",
70
+ "chain_b", "residue_number_b", "insertion_code_b", "residue_name_b", "atoms_b", "distance", "angle",
71
+ "a_is_donor", "confidence", "pae", "water")
72
+
73
+
74
+ @dataclass(frozen=True)
75
+ class Participant:
76
+ """One side of an interface: a name, and the chains it consists of.
77
+
78
+ ``detail`` is how much of its residues is drawn where they are drawn with
79
+ atoms (:data:`bindview.fragments.DETAILS`): ``"box"``, ``"backbone"``,
80
+ ``"sidechain"`` or ``"atoms"``. ``None`` leaves it to the figure
81
+ (``Interface(detail=...)``). Where that names no level either, the column
82
+ is drawn as boxes and the residues around it as the style has them.
83
+ """
84
+
85
+ name: str
86
+ chains: tuple[str, ...]
87
+ detail: "str | None" = None
88
+
89
+ def __post_init__(self) -> None:
90
+ try:
91
+ check_detail(self.detail, f"the detail of {self.name or 'a participant'}")
92
+ except ValueError as exc:
93
+ raise BindviewError(str(exc)) from None
94
+
95
+ @classmethod
96
+ def parse(cls, spec: "str | Participant | Sequence[str]") -> "Participant":
97
+ """``"A"``, ``"D+E"`` or ``"receptor=D+E"``; or a sequence of chain names."""
98
+ if isinstance(spec, Participant):
99
+ return spec
100
+ if isinstance(spec, str):
101
+ name, _, chains = spec.rpartition("=")
102
+ parts = tuple(c.strip() for c in chains.replace(",", "+").split("+") if c.strip())
103
+ else:
104
+ name, parts = "", tuple(str(c) for c in spec)
105
+ if not parts:
106
+ raise BindviewError(f"a participant needs at least one chain: {spec!r}")
107
+ return cls(name.strip() or ("chain " + parts[0] if len(parts) == 1 else "chains " + ", ".join(parts)), parts)
108
+
109
+
110
+ @dataclass(frozen=True)
111
+ class InterfaceContact:
112
+ """One contact across an interface, with the residue and the atoms on both sides.
113
+
114
+ ``confidence`` (pLDDT scale, 0 to 100) and ``pae`` (predicted aligned error
115
+ between the two residues, ångström) ride on the contact into the graph.
116
+ ``pae`` is what the reliability of a contact between two chains means in a
117
+ predicted complex, and is written on the contact's line. Where it is the
118
+ median over several draws of the model, ``pae_draws`` are the values of
119
+ the draws.
120
+ """
121
+
122
+ type: InteractionType
123
+ chain_a: str
124
+ number_a: int
125
+ resname_a: str
126
+ atoms_a: tuple[str, ...]
127
+ chain_b: str
128
+ number_b: int
129
+ resname_b: str
130
+ atoms_b: tuple[str, ...]
131
+ icode_a: str = ""
132
+ icode_b: str = ""
133
+ distance: float | None = None
134
+ angle: float | None = None
135
+ a_is_donor: bool | None = None
136
+ confidence: float | None = None
137
+ pae: float | None = None
138
+ water: str | None = None
139
+ pae_draws: tuple[float, ...] = ()
140
+
141
+ def __post_init__(self) -> None:
142
+ object.__setattr__(self, "type", InteractionType(self.type) if not isinstance(self.type, InteractionType)
143
+ else self.type)
144
+ object.__setattr__(self, "atoms_a", tuple(self.atoms_a))
145
+ object.__setattr__(self, "atoms_b", tuple(self.atoms_b))
146
+ object.__setattr__(self, "pae_draws", tuple(float(v) for v in self.pae_draws))
147
+ for value in (self.pae, *self.pae_draws):
148
+ if value is not None and not 0.0 <= float(value) < float("inf"):
149
+ raise InteractionError(f"the contact of {self.residue_a} with {self.residue_b} has a PAE of "
150
+ f"{float(value):g}: a PAE is a number of ångström from 0")
151
+
152
+ @property
153
+ def residue_a(self) -> ResidueKey:
154
+ """``(chain, number, insertion code)`` on the first side."""
155
+ return ResidueKey(self.chain_a, int(self.number_a), self.icode_a)
156
+
157
+ @property
158
+ def residue_b(self) -> ResidueKey:
159
+ """``(chain, number, insertion code)`` on the second side."""
160
+ return ResidueKey(self.chain_b, int(self.number_b), self.icode_b)
161
+
162
+ @property
163
+ def sort_key(self) -> tuple:
164
+ """The order of contacts in a table."""
165
+ return (self.type.value, self.residue_a, self.atoms_a, self.residue_b, self.atoms_b, self.distance or 0.0)
166
+
167
+ def flipped(self) -> "InterfaceContact":
168
+ """The same contact seen from the other side."""
169
+ return replace(self, chain_a=self.chain_b, number_a=self.number_b, icode_a=self.icode_b,
170
+ resname_a=self.resname_b, atoms_a=self.atoms_b, chain_b=self.chain_a, number_b=self.number_a,
171
+ icode_b=self.icode_a, resname_b=self.resname_a, atoms_b=self.atoms_a,
172
+ a_is_donor=None if self.a_is_donor is None else not self.a_is_donor)
173
+
174
+ def as_interaction(self) -> Interaction:
175
+ """The contact as a record of a ligand diagram whose ligand is side ``a`` (the spine): its atoms
176
+ are named as in a chain ligand, ``63/OE1``."""
177
+ mine = tuple(f"{self.number_a}{self.icode_a}/{n}" for n in self.atoms_a)
178
+ one = len(mine) == 1 and len(self.atoms_b) == 1
179
+ return Interaction(
180
+ type=self.type, residue_number=self.number_b, residue_name=self.resname_b, chain=self.chain_b,
181
+ insertion_code=self.icode_b, protein_atom=self.atoms_b[0] if one else None,
182
+ ligand_atom=mine[0] if one else None, ligand_atoms=() if one else mine,
183
+ protein_atoms=() if one else self.atoms_b, distance=self.distance, angle=self.angle,
184
+ ligand_is_donor=self.a_is_donor, water=self.water, confidence=self.confidence, pae=self.pae,
185
+ pae_draws=self.pae_draws)
186
+
187
+
188
+ def dump_interface_contacts(contacts: Iterable[InterfaceContact]) -> str:
189
+ """The contacts as a tab-separated table (:data:`COLUMNS`; and ``pae_draws``, the value of each
190
+ draw behind a median, where any contact has them)."""
191
+ def cell(value: Any) -> str:
192
+ return "" if value is None else ",".join(str(v) for v in value) if isinstance(value, tuple) else str(value)
193
+
194
+ contacts = list(contacts)
195
+ draws = any(c.pae_draws for c in contacts)
196
+ lines = ["\t".join(COLUMNS + (("pae_draws",) if draws else ()))]
197
+ for c in contacts:
198
+ lines.append("\t".join(cell(v) for v in (
199
+ c.type.value, c.chain_a, c.number_a, c.icode_a, c.resname_a, c.atoms_a, c.chain_b, c.number_b, c.icode_b,
200
+ c.resname_b, c.atoms_b, c.distance, c.angle, c.a_is_donor, c.confidence, c.pae, c.water)
201
+ + ((c.pae_draws,) if draws else ())))
202
+ return "\n".join(lines) + "\n"
203
+
204
+
205
+ def load_interface_contacts(path: "str | Path") -> list[InterfaceContact]:
206
+ """Read a table written by :func:`dump_interface_contacts` (or by hand, with those columns). Empty
207
+ lines and lines that begin with ``#`` are passed over; an error names the line of the file."""
208
+ text = Path(path).read_text(encoding="utf-8-sig") # (-sig: without a byte order mark, if it has one)
209
+ rows = [(n, line.split("\t")) for n, line in enumerate(text.splitlines(), start=1)
210
+ if line.strip() and not line.startswith("#")]
211
+ if not rows:
212
+ return []
213
+ head = [h.strip() for h in rows[0][1]]
214
+ need = {"interaction_type", "chain_a", "residue_number_a", "residue_name_a", "chain_b", "residue_number_b",
215
+ "residue_name_b"}
216
+ if not need <= set(head):
217
+ raise BindviewError(f"{path}: an interface table needs the columns {', '.join(sorted(need))}")
218
+ out = []
219
+ for n, row in rows[1:]:
220
+ d = dict(zip(head, (cell.strip() for cell in row)))
221
+
222
+ def number(key: str) -> "float | None":
223
+ return float(d[key]) if d.get(key) else None
224
+
225
+ try:
226
+ out.append(InterfaceContact(
227
+ type=InteractionType(d["interaction_type"]), chain_a=d["chain_a"], number_a=int(d["residue_number_a"]),
228
+ icode_a=d.get("insertion_code_a", ""), resname_a=d["residue_name_a"],
229
+ atoms_a=tuple(a for a in d.get("atoms_a", "").split(",") if a), chain_b=d["chain_b"],
230
+ number_b=int(d["residue_number_b"]), icode_b=d.get("insertion_code_b", ""),
231
+ resname_b=d["residue_name_b"], atoms_b=tuple(a for a in d.get("atoms_b", "").split(",") if a),
232
+ distance=number("distance"), angle=number("angle"),
233
+ a_is_donor={"true": True, "false": False}.get(d.get("a_is_donor", "").lower()),
234
+ confidence=number("confidence"), pae=number("pae"), water=d.get("water") or None,
235
+ pae_draws=tuple(float(v) for v in d.get("pae_draws", "").split(",") if v.strip())))
236
+ except KeyError as exc:
237
+ raise BindviewError(f"{path}, line {n}: the row ends before the column {exc}") from exc
238
+ except (ValueError, BindviewError) as exc:
239
+ raise BindviewError(f"{path}, line {n}: {exc}") from exc
240
+ return out
241
+
242
+
243
+ @dataclass(frozen=True)
244
+ class Site:
245
+ """The part of an interface a figure shows, and how it was chosen."""
246
+
247
+ kind: str # whole | seed | cluster | window
248
+ residues: tuple[ResidueKey, ...] # of the spine, in the order of its sequence
249
+ of_residues: int # residues of the spine at the interface in all
250
+ contacts: int
251
+ of_contacts: int
252
+ rule: str # in words, for the figure
253
+
254
+ @property
255
+ def whole(self) -> bool:
256
+ return self.kind == "whole"
257
+
258
+
259
+ def _span(residues: Sequence[ResidueKey]) -> str:
260
+ first, last = residues[0], residues[-1]
261
+ return (f"{first.number}{first.icode}" if len(residues) == 1
262
+ else f"{first.number}{first.icode} to {last.number}{last.icode}")
263
+
264
+
265
+ def _joined(structure: Structure, a: ResidueKey, b: ResidueKey) -> bool:
266
+ """Is residue ``b`` bonded to ``a`` before it: by a peptide bond, or by the phosphate of a nucleotide?"""
267
+ for before, after in (("C", "N"), ("O3'", "P"), ("O3*", "P")):
268
+ one, other = structure.atom_by_name(a, before), structure.atom_by_name(b, after)
269
+ if one is not None and other is not None:
270
+ return float(np.linalg.norm(np.array(one.xyz) - np.array(other.xyz))) <= _BOND
271
+ return False
272
+
273
+
274
+ def _places(structure: Structure, keys: Sequence[ResidueKey]) -> dict[ResidueKey, int]:
275
+ """Where each residue of a chain stands in it, for what is said and drawn of stretches and neighbours.
276
+
277
+ One after the other in the order of the file, and as far apart as their numbers where the file leaves
278
+ residues out between two: a loop that was not modelled lies between its two ends in the figure as it
279
+ does in the chain. Numbers that jump between two residues bonded to each other (the numbering of
280
+ another protein, or one without a zero) leave nothing out."""
281
+ places: dict[ResidueKey, int] = {}
282
+ at = 0
283
+ for k, key in enumerate(keys):
284
+ if k:
285
+ step = abs(key.number - keys[k - 1].number)
286
+ at += 1 if step <= 1 or _joined(structure, keys[k - 1], key) else step
287
+ places[key] = at
288
+ return places
289
+
290
+
291
+ def choose_site(contacts: Sequence[InterfaceContact], order: Sequence[ResidueKey], index: "dict[ResidueKey, int]",
292
+ *, limit: int = MAX_SPINE, seed: "ResidueKey | None" = None, radius: float = 8.0,
293
+ structure: "Structure | None" = None) -> Site:
294
+ """Which residues of the spine a figure shows. Deterministic, and in words in the result.
295
+
296
+ ``contacts`` have the spine as side ``a``; ``order`` are the residues of the
297
+ spine at the interface in the order of its sequence, ``index`` the place of
298
+ every residue of the spine in its chain.
299
+
300
+ * With a ``seed`` residue (of either side): the residues of the spine at
301
+ the interface that have an atom within ``radius`` ångström of it; the
302
+ nearest ``limit`` if there are more.
303
+ * Otherwise the whole interface, if it has no more than ``limit`` residues
304
+ of the spine.
305
+ * Otherwise whole contact clusters, those with the most contacts first, as
306
+ many as fit: two residues of the spine are in one cluster if they are
307
+ neighbours in the sequence or touch the same residue of the partner.
308
+ * If that is still too large: its ``limit`` consecutive residues (in the
309
+ order of the spine) that carry the most contacts.
310
+ """
311
+ if limit < 1:
312
+ raise BindviewError(f"a site shows 1 residue or more, not {limit!r}")
313
+ per: dict[ResidueKey, int] = {k: 0 for k in order}
314
+ for c in contacts:
315
+ per[c.residue_a] += 1
316
+ total = len(contacts)
317
+
318
+ def made(kind: str, residues: Sequence[ResidueKey], rule: str) -> Site:
319
+ chosen = tuple(k for k in order if k in set(residues))
320
+ return Site(kind, chosen, len(order), sum(per[k] for k in chosen), total, rule)
321
+
322
+ if seed is not None:
323
+ if structure is None:
324
+ raise BindviewError("a site around a residue needs the structure")
325
+ centre = np.array([a.xyz for a in structure.residue_atoms(seed) if a.element not in ("H", "D")], dtype=float)
326
+ if not len(centre):
327
+ raise BindviewError(f"no residue {seed} to centre the site on")
328
+ near: list[tuple[float, int, ResidueKey]] = []
329
+ for n, k in enumerate(order):
330
+ pts = np.array([a.xyz for a in structure.residue_atoms(k) if a.element not in ("H", "D")], dtype=float)
331
+ d = float(np.linalg.norm(pts[:, None, :] - centre[None, :, :], axis=2).min())
332
+ if d <= radius:
333
+ near.append((d, n, k))
334
+ if not near:
335
+ raise BindviewError(f"no residue of the spine at the interface lies within {radius:g} Å of {seed}")
336
+ picked = [k for _, _, k in sorted(near)[:limit]]
337
+ return made("seed", picked, f"within {radius:g} Å of {structure.residue_name(seed).title()}"
338
+ f"{seed.number}{seed.icode} of chain {seed.chain}")
339
+ if len(order) <= limit:
340
+ return made("whole", order, "the whole interface")
341
+ parent = {k: k for k in order}
342
+
343
+ def find(k: ResidueKey) -> ResidueKey:
344
+ while parent[k] != k:
345
+ parent[k] = parent[parent[k]]
346
+ k = parent[k]
347
+ return k
348
+
349
+ for a, b in zip(order, order[1:]):
350
+ if a.chain == b.chain and index[b] - index[a] == 1:
351
+ parent[find(b)] = find(a)
352
+ by_partner: dict[ResidueKey, ResidueKey] = {}
353
+ for c in contacts:
354
+ first = by_partner.setdefault(c.residue_b, c.residue_a)
355
+ if find(first) != find(c.residue_a):
356
+ parent[find(c.residue_a)] = find(first)
357
+ clusters: dict[ResidueKey, list[ResidueKey]] = {}
358
+ for k in order:
359
+ clusters.setdefault(find(k), []).append(k)
360
+ ranked = sorted(clusters.values(), key=lambda ks: (-sum(per[k] for k in ks), order.index(ks[0])))
361
+ best = ranked[0]
362
+ if len(best) <= limit:
363
+ # The clusters with the most contacts, as many as fit. Not the largest alone: of an interface
364
+ # in many small clusters that is a small part (8 of 33 residues where they come in 13 clusters).
365
+ taken: list[ResidueKey] = []
366
+ n = 0
367
+ for cluster in ranked:
368
+ if len(taken) + len(cluster) <= limit:
369
+ taken.extend(cluster)
370
+ n += 1
371
+ return made("cluster", taken, f"the {n} of its {len(ranked)} contact clusters with the most contacts "
372
+ f"that fit a figure")
373
+ sums = [sum(per[k] for k in best[i:i + limit]) for i in range(len(best) - limit + 1)]
374
+ start = sums.index(max(sums))
375
+ window = best[start:start + limit]
376
+ return made("window", window, f"the {limit} consecutive residues of the interface with the most contacts, "
377
+ f"residues {_span(window)}")
378
+
379
+
380
+ def _site_meta(site: Site) -> dict[str, Any]:
381
+ """A site as the graph of its figure holds it (``meta.interface.site``)."""
382
+ return {"kind": site.kind, "rule": site.rule, "residues": len(site.residues),
383
+ "of_residues": site.of_residues, "contacts": site.contacts, "of_contacts": site.of_contacts}
384
+
385
+
386
+ @dataclass
387
+ class _Info:
388
+ """What the figure says about the interface: handed to the chain backend."""
389
+
390
+ legend: str
391
+ notes: list[str] = field(default_factory=list)
392
+ meta: dict[str, Any] = field(default_factory=dict)
393
+ #: Further lines of the legend, and further numbers for the line under the title (label, value).
394
+ legend_extra: list[str] = field(default_factory=list)
395
+ #: Which of the notes are of the PAE as it is written on the lines: not those of a figure that draws it as a glow.
396
+ tag_notes: list[str] = field(default_factory=list)
397
+ strip: list[tuple[str, str]] = field(default_factory=list)
398
+ #: ... and the same numbers as ``data-`` attributes of that line, for a page that reads the figure.
399
+ strip_data: dict[str, str] = field(default_factory=dict)
400
+ #: Said in the result as well as in the figure.
401
+ warnings: list[str] = field(default_factory=list)
402
+ #: What still has to be said when the figure could not be drawn and a table stands in its place.
403
+ summary_notes: list[str] = field(default_factory=list)
404
+ #: What the boxes are called as a whole, for the line under the title: a column, or boxes on a plane.
405
+ shape: str = "column"
406
+
407
+ def said(self, dep: Any = None) -> list[str]:
408
+ """The footnotes of the figure as it was drawn: with boxes on a plane, what was measured of
409
+ them where they stand goes in after the sentence that says they are on a plane."""
410
+ placed = getattr(dep, "plane", None)
411
+ if placed is None:
412
+ return list(self.notes)
413
+ return self.notes[:1] + [_fidelity_sentence(placed)] + self.notes[1:]
414
+
415
+ def described(self, dep: Any = None) -> str:
416
+ """One sentence on boxes that stand on a plane, for the description of the figure; empty otherwise."""
417
+ placed = getattr(dep, "plane", None)
418
+ if placed is None:
419
+ return ""
420
+ f = placed.fidelity
421
+ return (f"The boxes stand where their residues lie on the plane through them: {_percent(f.kept)} of "
422
+ f"neighbour relations kept, distances off by {_percent(f.error)}.")
423
+
424
+ def meta_for(self, dep: Any = None) -> dict[str, Any]:
425
+ """The graph's ``meta.interface`` for the figure as it was drawn."""
426
+ out = dict(self.meta)
427
+ placed = getattr(dep, "plane", None)
428
+ if placed is not None:
429
+ out["plane"] = {"drawn": True, **placed.as_dict()}
430
+ return out
431
+
432
+
433
+ def _percent(value: float) -> str:
434
+ return f"{100.0 * value:.0f} %"
435
+
436
+
437
+ def _shortfall(bare: Fidelity) -> str:
438
+ """Why a projection is not drawn: its two numbers against what is required."""
439
+ return (f"a projection would keep {_percent(bare.kept)} of neighbour relations and be off by "
440
+ f"{_percent(bare.error)} in distances; at least {_percent(KEPT_MIN)} and at most "
441
+ f"{_percent(ERROR_MAX)} are required")
442
+
443
+
444
+ def _fidelity_sentence(placed: Placed) -> str:
445
+ """What was measured of the boxes on the plane, in words for the figure."""
446
+ f = placed.fidelity
447
+ if f.pairs:
448
+ wrong = []
449
+ if f.false:
450
+ wrong.append(f"{f.false} {'is' if f.false == 1 else 'are'} drawn as neighbours and "
451
+ f"{'lies' if f.false == 1 else 'lie'} more than {APART:g} \u00c5 apart in space")
452
+ if f.lost:
453
+ wrong.append(f"{f.lost} {'is' if f.lost == 1 else 'are'} neighbours in space and drawn more than "
454
+ f"{APART:g} \u00c5 apart")
455
+ pairs = (f"{f.pairs} pairs of boxes are neighbours (centres within {NEAR:g} \u00c5) in the figure or in "
456
+ f"space" if f.pairs != 1 else
457
+ f"One pair of boxes are neighbours (centres within {NEAR:g} \u00c5) in the figure or in space")
458
+ said = (f"{pairs}; " + ("; ".join(wrong) if wrong else "none is a neighbour in the one and more than "
459
+ f"{APART:g} \u00c5 apart in the other")
460
+ + f": {_percent(f.kept)} of neighbour relations are kept.")
461
+ else:
462
+ said = f"No two boxes are neighbours (centres within {NEAR:g} \u00c5), in the figure or in space."
463
+ said += (f" Distances between the centres of boxes differ from those in space by {_percent(f.error)} "
464
+ f"(root mean square). The residues' centres lie {placed.rms:.1f} \u00c5 (root mean square) off the plane")
465
+ if placed.moved:
466
+ said += (f"; {placed.moved} box{'es were' if placed.moved != 1 else ' was'} moved off "
467
+ f"{'their places' if placed.moved != 1 else 'its place'} to keep boxes apart")
468
+ return "Measured on the boxes as drawn: " + said[0].lower() + said[1:] + "."
469
+
470
+
471
+ @dataclass(frozen=True)
472
+ class InterfaceIpsae:
473
+ """ipSAE between the participant of the column and one of the others (:func:`bindview.pae.ipsae`).
474
+
475
+ ``first`` is the participant of the column. ``draws`` holds the score of one matrix, or of every
476
+ draw of the model in the order the draws were given; :attr:`forward` and :attr:`backward` are then
477
+ the medians over the draws, as the PAE of a contact is.
478
+ """
479
+
480
+ first: str
481
+ second: str
482
+ draws: tuple[Ipsae, ...]
483
+
484
+ @property
485
+ def forward(self) -> float:
486
+ """Aligned on a residue of ``first``, scored over ``second``."""
487
+ return float(np.median([d.forward.value for d in self.draws]))
488
+
489
+ @property
490
+ def backward(self) -> float:
491
+ """Aligned on a residue of ``second``, scored over ``first``."""
492
+ return float(np.median([d.backward.value for d in self.draws]))
493
+
494
+ @property
495
+ def cutoff(self) -> float:
496
+ return self.draws[0].cutoff
497
+
498
+
499
+ @dataclass
500
+ class _Verdict:
501
+ """What a site is drawn as, and why: the outcome of :meth:`Interface._verdict`."""
502
+
503
+ layout: str
504
+ rule: str
505
+ runs: "list[tuple[int, int]]"
506
+ arrangement: "Arrangement | None" = None
507
+ considered: "Arrangement | None" = None
508
+ #: A column that stands in for a plane: in the order of the sequence, whatever spreads contacts least.
509
+ sequence_only: bool = False
510
+
511
+
512
+ class Interface:
513
+ """The contacts between two (or three) polymer participants as one figure.
514
+
515
+ ``participants`` in order; contacts are between neighbours. ``contacts``
516
+ are :class:`InterfaceContact` records in either orientation, or ``None``
517
+ to detect them with PLIP (:func:`bindview.detect.detect_interface`).
518
+ ``spine`` names the participant drawn as the column of boxes (default: of
519
+ three the middle one, which touches both others; of two the one that is a
520
+ single chain where the other is several, else the one with fewer residues
521
+ at the interface, and the first where they have as many). ``site`` is a
522
+ residue to centre a site on, as ``"A:84"``.
523
+ ``layout`` is how the boxes are set out: ``"column"`` (the default),
524
+ ``"plane"`` (each where its residue lies in space), or ``"auto"``, which
525
+ lets the rule of :meth:`_verdict` choose between the two. What a figure
526
+ is drawn as is :attr:`layout`, and why, in words, :attr:`layout_rule`,
527
+ which for the default says what the rule would have chosen.
528
+ ``pae`` is the model's predicted aligned error (:mod:`bindview.pae`): one
529
+ file for the model that is drawn, or several for the draws of one model,
530
+ whose median a contact then carries.
531
+ ``ipsae`` asks for a score of the interface as a whole, computed from that
532
+ matrix (:func:`bindview.pae.ipsae`): ``True`` for the usual cut-off of 10 Å,
533
+ or the cut-off in ångström as a number with a point (``15.0``; a whole
534
+ number is refused, since ``1`` could mean either). The figure then prints
535
+ it under its title, in its two directions, and says what it is;
536
+ :attr:`ipsae` holds it. Left out, nothing is computed.
537
+ ``model_confidence`` is what a model says of itself as a whole (ipTM and
538
+ the like), as for a ligand diagram: a mapping, a
539
+ :class:`~bindview.confidence.ModelConfidence`, the path of a JSON file that
540
+ has those keys, or ``"auto"`` (the default), which reads AlphaFold 3's
541
+ summary file where it lies beside the model.
542
+ ``detail`` is how much of a residue is drawn where it makes a directional
543
+ contact: ``"box"``, ``"backbone"``, ``"sidechain"`` or ``"atoms"``, for
544
+ every participant that names no level of its own, or a mapping from the
545
+ name of a participant to its level. Left alone, the column is drawn as
546
+ boxes and the residues around it as the style has them. Atoms stand beside
547
+ the boxes of a column only, not of a plane.
548
+ """
549
+
550
+ def __init__(self, structure: "Structure | str | Path", participants: Sequence["str | Participant | Sequence[str]"],
551
+ contacts: "Iterable[InterfaceContact] | None" = None, *, spine: "str | None" = None,
552
+ site: "str | ResidueKey | None" = None, radius: float = 8.0, max_residues: int = MAX_SPINE,
553
+ name: "str | None" = None, order: str = "auto",
554
+ pae: "str | Path | Pae | PaeDraws | Sequence[str | Path | Pae] | None" = None,
555
+ layout: str = "column", detail: "str | Mapping[str, str | None] | None" = None,
556
+ ipsae: "bool | float" = False, model_confidence: Any = "auto") -> None:
557
+ if order not in ("auto", "sequence", "interface"):
558
+ raise BindviewError(f"order is 'auto', 'sequence' or 'interface', not {order!r}")
559
+ if layout not in LAYOUTS:
560
+ raise BindviewError(f"layout is {', '.join(repr(v) for v in LAYOUTS[:-1])} or {LAYOUTS[-1]!r}, "
561
+ f"not {layout!r}")
562
+ try:
563
+ most = 0 if isinstance(max_residues, bool) else whole_number(max_residues)
564
+ except TypeError:
565
+ most = 0
566
+ if most < 1:
567
+ raise BindviewError(f"max_residues is a whole number of residues, 1 or more, not {max_residues!r}")
568
+ self.order = order
569
+ #: What was asked for; :attr:`layout` is what a figure of the site is drawn as.
570
+ self.layout_asked = layout
571
+ self.layout = "column"
572
+ self.layout_rule = ""
573
+ self._arrangement: "Arrangement | None" = None
574
+ self._considered: "Arrangement | None" = None
575
+ self._runs: list[tuple[int, int]] = []
576
+ self._sequence_only = False
577
+ self._no_plane: dict[tuple[ResidueKey, ...], str] = {}
578
+ self._columns: dict[tuple[ResidueKey, ...], Any] = {}
579
+ self.structure = structure if isinstance(structure, Structure) else read_structure(structure)
580
+ self.participants = tuple(Participant.parse(p) for p in participants)
581
+ if not 2 <= len(self.participants) <= 3:
582
+ raise BindviewError("an interface is drawn between two participants, or along three in a row; "
583
+ f"{len(self.participants)} were named")
584
+ chains = [c for p in self.participants for c in p.chains]
585
+ if len(set(chains)) != len(chains):
586
+ raise BindviewError("a chain can be in one participant only")
587
+ #: How much of a residue of each participant is drawn where it makes a directional contact,
588
+ #: by the participant's name: its own level, else the figure's, else ``None`` (the column as
589
+ #: boxes, the residues around it as the style has them).
590
+ self.detail = self._details(detail)
591
+ present = {a.chain for a in self.structure.atoms}
592
+ missing = [c for c in chains if c not in present]
593
+ if missing:
594
+ raise BindviewError(f"no chain {', '.join(missing)} in {self.structure.source or 'the structure'}")
595
+ self.source = "supplied"
596
+ if contacts is None:
597
+ from .detect import detect_interface
598
+
599
+ contacts = [c for a, b in zip(self.participants, self.participants[1:])
600
+ for c in detect_interface(self.structure, a.chains, b.chains)]
601
+ self.source = "detected"
602
+ self.notes: list[str] = []
603
+ contacts = list(contacts)
604
+ # Before anything is drawn, and of the whole interface: a site would show the mistake in part.
605
+ check_confidence_scale((c.confidence for c in contacts), "The contacts of this interface")
606
+ #: The model's predicted aligned error, where there is one: AlphaFold 3's confidences file, the
607
+ #: ``pae_*.npz`` of a Boltz model (its rows are those of the structure), or a
608
+ #: :class:`~bindview.pae.Pae`; several of them are the draws of one model, and a pair's value is
609
+ #: then their median (:class:`~bindview.pae.PaeDraws`). A contact that brings no value of its own
610
+ #: gets the one of its two residues.
611
+ self.pae = read_pae(pae, self.structure)
612
+ #: The pairs of residues with a contact whose PAE was read from the matrix and did not come with it.
613
+ self._from_matrix: set[frozenset[ResidueKey]] = set()
614
+ if self.pae is not None:
615
+ given = contacts
616
+ contacts = [c if c.pae is not None else self._with_pae(c) for c in given]
617
+ self._from_matrix = {frozenset((c.residue_a, c.residue_b)) for c, was in zip(contacts, given)
618
+ if was.pae is None and c.pae is not None}
619
+ if contacts and all(c.pae is None for c in contacts):
620
+ # A figure without a word about PAE would read as a confident one, not as an unmeasured one.
621
+ names = sorted(set(self.pae.chains))
622
+ raise BindviewError(
623
+ f"{self.pae.source or 'the PAE matrix'} has no value for any contact of this interface: the "
624
+ f"residues in contact are not in it (it has chain{'s' if len(names) != 1 else ''} "
625
+ f"{', '.join(repr(n) for n in names)}, residue numbers {min(self.pae.numbers)} to "
626
+ f"{max(self.pae.numbers)})")
627
+ self.contacts = self._between_neighbours(list(contacts))
628
+ if not self.contacts:
629
+ raise BindviewError("no contact between the participants: there is no interface to draw")
630
+ self.spine = self._spine(spine)
631
+ if len(self.spine.chains) != 1:
632
+ raise BindviewError(f"the spine has to be one chain; {self.spine.name} has {len(self.spine.chains)}. "
633
+ "Name the other participant as the spine")
634
+ if layout == "plane" and self._beside:
635
+ raise BindviewError(
636
+ f"{self.spine.name} is asked for with the atoms of its residues (detail "
637
+ f"{self.detail[self.spine.name]!r}) and with its boxes where they lie on a plane (layout 'plane'). "
638
+ f"Atoms are drawn beside the boxes of a column only: a column has a side of every box that is "
639
+ f"nobody's, and boxes that stand where their residues lie have none. Ask for one of the two")
640
+ self.name = name
641
+ self.radius = radius
642
+ self.max_residues = max_residues
643
+ self.seed = self._seed(site)
644
+ self._oriented = [c if c.chain_a in self.spine.chains else c.flipped() for c in self.contacts]
645
+ chain = self.spine.chains[0]
646
+ keys = [k for k in self.structure.residues() if k.chain == chain
647
+ and self.structure.residue_name(k).upper() not in WATER_NAMES]
648
+ self._index = _places(self.structure, keys)
649
+ touched = {c.residue_a for c in self._oriented}
650
+ unknown = sorted(touched - set(keys))
651
+ if unknown:
652
+ raise BindviewError(f"a contact names residue {unknown[0]}, which is not in the structure")
653
+ self._order = [k for k in keys if k in touched]
654
+ #: What the model says of itself as a whole, as it was handed in (see the class).
655
+ self.model_confidence = model_confidence
656
+ #: ipSAE between the participant of the column and each of the others, where it was asked for.
657
+ self.ipsae: list[InterfaceIpsae] = self._scores(ipsae)
658
+ #: The site and the diagram of the figure that was drawn last; before any, those the interface
659
+ #: was built with, which every figure starts from (:meth:`render`).
660
+ self.site = choose_site(self._oriented, self._order, self._index, limit=max_residues, seed=self.seed,
661
+ radius=radius, structure=self.structure)
662
+ self.diagram = self._diagram(self.site)
663
+ self._built = self.site
664
+ self._diagrams: dict[Site, Any] = {self.site: self.diagram}
665
+
666
+ def _scores(self, asked: "bool | float") -> "list[InterfaceIpsae]":
667
+ """ipSAE of the participant of the column with each of the others, from the PAE that was given."""
668
+ if asked is False or asked is None:
669
+ return []
670
+ if isinstance(asked, int) and not isinstance(asked, bool):
671
+ # 1 is True almost everywhere, and would be a cut-off of 1 Å here: neither is guessed.
672
+ raise BindviewError(f"ipsae={asked!r}: ipsae is True, for the usual cut-off of {IPSAE_CUTOFF:g} Å, or the "
673
+ f"cut-off in ångström as a number with a point ({float(asked)!r})")
674
+ if self.pae is None:
675
+ raise BindviewError("ipSAE is computed from the model's PAE matrix, and none was given: hand it in "
676
+ "with pae=")
677
+ cutoff = IPSAE_CUTOFF if asked is True else float(asked)
678
+
679
+ def residues(p: Participant) -> list[ResidueKey]:
680
+ return [k for k in self.structure.residues()
681
+ if k.chain in p.chains and self.structure.residue_name(k).upper() not in WATER_NAMES]
682
+
683
+ return [InterfaceIpsae(self.spine.name, other.name,
684
+ ipsae_of(self.pae, residues(self.spine), residues(other), cutoff,
685
+ structure=self.structure))
686
+ for other in self.others]
687
+
688
+ def _details(self, detail: "str | Mapping[str, str | None] | None") -> dict[str, "str | None"]:
689
+ """The level of every participant: its own, or the one the figure was given for it."""
690
+ names = [p.name for p in self.participants]
691
+ try:
692
+ if detail is None or isinstance(detail, str):
693
+ given = dict.fromkeys(names, check_detail(detail))
694
+ else:
695
+ unknown = [k for k in detail if k not in names]
696
+ if unknown:
697
+ raise ValueError(f"detail names {unknown[0]!r}, which is not a participant of this interface "
698
+ f"({', '.join(repr(n) for n in names)})")
699
+ given = {n: check_detail(detail.get(n), f"the detail of {n}") for n in names}
700
+ except ValueError as exc:
701
+ raise BindviewError(str(exc)) from None
702
+ return {p.name: p.detail if p.detail is not None else given[p.name] for p in self.participants}
703
+
704
+ @property
705
+ def _beside(self) -> bool:
706
+ """Are atoms of the column's residues to be drawn beside their boxes?"""
707
+ return self.detail[self.spine.name] not in (None, "box")
708
+
709
+ def _with_pae(self, c: InterfaceContact) -> InterfaceContact:
710
+ """A contact with the PAE of its two residues: of one matrix, or the median over the draws
711
+ with the value of every draw beside it."""
712
+ assert self.pae is not None
713
+ if isinstance(self.pae, PaeDraws):
714
+ each = self.pae.each(c.residue_a, c.residue_b)
715
+ known = tuple(v for v in each if v is not None)
716
+ # A value for every draw, or none: a median beside four of five values would not be theirs.
717
+ return replace(c, pae=self.pae.between(c.residue_a, c.residue_b),
718
+ pae_draws=known if len(known) == len(each) else ())
719
+ return replace(c, pae=self.pae.between(c.residue_a, c.residue_b))
720
+
721
+ # ------------------------------------------------------------------ construction
722
+ @classmethod
723
+ def from_structure(cls, structure: "Structure | str | Path",
724
+ participants: Sequence["str | Participant | Sequence[str]"], **options: Any) -> "Interface":
725
+ """The same as the class itself, under the name the other figures are built by
726
+ (``Diagram.from_structure``, ``Ensemble.from_structures``)."""
727
+ return cls(structure, participants, **options)
728
+
729
+ def _between_neighbours(self, contacts: list[InterfaceContact]) -> list[InterfaceContact]:
730
+ owner = {c: i for i, p in enumerate(self.participants) for c in p.chains}
731
+ out, elsewhere = [], 0
732
+ for c in contacts:
733
+ i, j = owner.get(c.chain_a), owner.get(c.chain_b)
734
+ if i is None or j is None or abs(i - j) != 1:
735
+ elsewhere += 1
736
+ continue
737
+ out.append(c if i < j else c.flipped())
738
+ if elsewhere:
739
+ self.notes.append(f"{elsewhere} contact{'s' if elsewhere != 1 else ''} not between neighbouring "
740
+ f"participants {'were' if elsewhere != 1 else 'was'} left out")
741
+ return sorted(out, key=lambda c: c.sort_key)
742
+
743
+ def _spine(self, named: "str | None") -> Participant:
744
+ if named is not None:
745
+ for n, p in enumerate(self.participants):
746
+ if named == p.name or named in p.chains or named == "+".join(p.chains):
747
+ if len(self.participants) == 3 and n != 1:
748
+ # The contacts are between neighbours: one at an end has none with the other end.
749
+ middle, far = self.participants[1], self.participants[2 - n]
750
+ raise BindviewError(
751
+ f"the spine of three participants in a row is the middle one, which touches both "
752
+ f"others: {p.name} is at an end and does not touch {far.name}. Name {p.name} in the "
753
+ f"middle to draw the other two around it, or draw it with {middle.name} alone")
754
+ return p
755
+ raise BindviewError(f"no participant {named!r} to be the spine")
756
+ if len(self.participants) == 3:
757
+ return self.participants[1]
758
+ a, b = self.participants
759
+ n_a = len({c.residue_a for c in self.contacts})
760
+ n_b = len({c.residue_b for c in self.contacts})
761
+ single = [p for p in (a, b) if len(p.chains) == 1]
762
+ if len(single) == 1:
763
+ return single[0]
764
+ return a if n_a <= n_b else b
765
+
766
+ def _seed(self, site: "str | ResidueKey | None") -> "ResidueKey | None":
767
+ if site is None or isinstance(site, ResidueKey):
768
+ return site
769
+ chain, _, rest = str(site).partition(":")
770
+ digits = rest.rstrip("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz")
771
+ try:
772
+ key = self.structure.find_residue(chain, int(digits), rest[len(digits):])
773
+ except ValueError:
774
+ key = None
775
+ if key is None:
776
+ raise BindviewError(f"no residue {site!r} to centre the site on (write it as chain:number, 'A:84')")
777
+ return key
778
+
779
+ def _diagram(self, site: Site) -> Any:
780
+ from .backends import Polymer
781
+ from .diagram import Diagram
782
+
783
+ self._decide(site)
784
+ shown = set(site.residues)
785
+ records = [c.as_interaction() for c in self._oriented if c.residue_a in shown]
786
+ # The column's level is the chain's; the levels of the participants around it go by their chains.
787
+ level = {"ligand": self.detail[self.spine.name], "protein": None}
788
+ around = {c: self.detail[p.name] for p in self.others for c in p.chains if self.detail[p.name] is not None}
789
+ if self.layout == "plane":
790
+ # On the plane the boxes are not in any order of their own: the residues as the chain has them.
791
+ st, key, given, notes = self.structure.with_residues_as_ligand(list(site.residues))
792
+ dia = Diagram._assemble(st, key, given, list(notes) + list(self.notes), None, records,
793
+ name=self.name or self.title, ligand_as="chain", source=self.source,
794
+ detail=level, model_confidence=self.model_confidence)
795
+ dia.detail_by_chain = dict(around)
796
+ assert isinstance(dia.backend, Polymer)
797
+ drawn = [r.number for r in dia.backend.peptide.residues]
798
+ if drawn == [f"{k.number}{k.icode}" for k in site.residues]:
799
+ dia.backend.interface = self._info(site)
800
+ dia.backend.arrangement = self._arrangement
801
+ dia.backend.peptide = replace(dia.backend.peptide, pairwise=True, sequential=True,
802
+ called=self.spine.name, open_ends=(False, False))
803
+ return dia
804
+ # A residue without a backbone is no box of its own: there is then no place for every box.
805
+ self._no_plane[tuple(site.residues)] = ("not every residue of them has a backbone of its own, "
806
+ "so not every one can be given its place")
807
+ self._decide(site)
808
+ st, key, given, notes = self.structure.with_residues_as_ligand(self._arranged(site.residues))
809
+ dia = Diagram._assemble(st, key, given, list(notes) + list(self.notes), None, records,
810
+ name=self.name or self.title, ligand_as="chain", source=self.source,
811
+ detail=level, model_confidence=self.model_confidence)
812
+ dia.detail_by_chain = dict(around)
813
+ assert isinstance(dia.backend, Polymer)
814
+ dia.backend.interface = self._info(site)
815
+ # The column starts and ends where the interface does, which is seldom where the chain does.
816
+ chain_keys = sorted(self._index, key=lambda k: self._index[k])
817
+ dia.backend.peptide = replace(dia.backend.peptide, pairwise=True, sequential=not self._along(site.residues),
818
+ called=self.spine.name,
819
+ open_ends=(site.residues[0] != chain_keys[0],
820
+ site.residues[-1] != chain_keys[-1]))
821
+ return dia
822
+
823
+ # ------------------------------------------------------------------ column or plane
824
+ def _centre(self, key: ResidueKey) -> np.ndarray:
825
+ """The centre of a residue: the centroid of its heavy atoms."""
826
+ return np.array([a.xyz for a in self.structure.residue_atoms(key) if a.element not in ("H", "D")],
827
+ dtype=float).mean(axis=0)
828
+
829
+ def _viewer(self, residues: Sequence[ResidueKey]) -> tuple[Participant, np.ndarray]:
830
+ """From whose side the plane is seen, and the direction to them: the participant with the
831
+ most pairs of residues in contact with those that are drawn (the first named, on a tie)."""
832
+ shown = set(residues)
833
+ owner = {c: p for p in self.others for c in p.chains}
834
+ pairs: dict[str, dict[tuple[ResidueKey, ResidueKey], None]] = {p.name: {} for p in self.others}
835
+ for c in self._oriented:
836
+ if c.residue_a in shown:
837
+ pairs[owner[c.chain_b].name][(c.residue_a, c.residue_b)] = None
838
+ who = max(self.others, key=lambda p: len(pairs[p.name]))
839
+ ways = []
840
+ for a, b in pairs[who.name]:
841
+ v = self._centre(b) - self._centre(a)
842
+ length = float(np.linalg.norm(v))
843
+ if length > 1e-6:
844
+ ways.append(v / length)
845
+ return who, (np.mean(ways, axis=0) if ways else np.zeros(3))
846
+
847
+ def _project(self, residues: Sequence[ResidueKey], runs: Sequence[tuple[int, int]]) -> Arrangement:
848
+ """The residues on the plane through their centres, seen from the partner's side."""
849
+ centres = np.array([self._centre(k) for k in residues], dtype=float)
850
+ _, toward = self._viewer(residues)
851
+ joins = [k + 1 for first, last in runs for k in range(first, last)
852
+ if self._index[residues[k + 1]] - self._index[residues[k]] > 1]
853
+ return Arrangement.of(centres, toward, joins)
854
+
855
+ def _spans(self, residues: Sequence[ResidueKey], runs: Sequence[tuple[int, int]]) -> str:
856
+ return ", ".join(_span(residues[first:last + 1]) for first, last in runs)
857
+
858
+ def _decide(self, site: Site) -> None:
859
+ """Column or plane for this site: sets :attr:`layout` and, in words, :attr:`layout_rule`."""
860
+ said = self._verdict(site, self.layout_asked)
861
+ self._column_for_atoms = False
862
+ if said.layout == "plane" and self._beside:
863
+ # Left to the rule, these residues would stand on a plane. Their atoms were asked for, and
864
+ # atoms stand beside the boxes of a column: the column it is, and the figure says why.
865
+ said = _Verdict("column", f"a column, because the atoms of its residues are drawn beside their boxes "
866
+ f"(detail {self.detail[self.spine.name]!r}) and boxes on a plane have no "
867
+ f"side for them; the rule alone would draw these residues {said.rule}",
868
+ said.runs, considered=said.considered)
869
+ self._column_for_atoms = True
870
+ self.layout, self.layout_rule, self._runs = said.layout, said.rule, said.runs
871
+ self._arrangement, self._considered, self._sequence_only = said.arrangement, said.considered, said.sequence_only
872
+
873
+ def _verdict(self, site: Site, asked: str) -> "_Verdict":
874
+ """What a site is drawn as when ``asked`` for a column, a plane, or the rule (``auto``).
875
+
876
+ **The column is the default**, and nothing about it depends on the rule: an interface is
877
+ drawn as a column unless the caller asks otherwise. What the rule would have chosen is said
878
+ in the result all the same.
879
+
880
+ The rule, where it is asked for:
881
+
882
+ * A **column** when fewer than three residues are shown, and when the residues that are
883
+ shown are one stretch of the chain (no more than :data:`~bindview.plane.STRETCH_GAP` residues
884
+ that are not at the interface between one and the next): a contiguous binder reads best as
885
+ the list it is.
886
+ * Otherwise the **plane**: each box where its residue lies on the least-squares plane through
887
+ their centres -- if the projection is faithful (:class:`~bindview.plane.Fidelity`).
888
+ * If it is not (the interface is too curved for one plane) the column again, in the order of
889
+ the sequence, and the figure says that the arrangement is not shown.
890
+
891
+ Asked for outright, the plane is drawn for one stretch as well, and still not for a
892
+ projection that is not faithful.
893
+ """
894
+ residues = list(site.residues)
895
+ runs = stretches([self._index[k] for k in residues])
896
+ spine, n = self.spine.name, len(residues)
897
+ some = f"{len(runs)} stretches" if len(runs) != 1 else "one stretch"
898
+ if asked == "column":
899
+ rule = "a column, the default"
900
+ try:
901
+ would = self._verdict(site, "auto").layout
902
+ except (ValueError, np.linalg.LinAlgError):
903
+ would = "column" # the column is drawn whatever the rule trips over
904
+ if would == "plane":
905
+ rule += (f'; asked to choose (layout "auto"), the rule would draw these residues on the plane '
906
+ f"through them: they come in {some} of the chain")
907
+ return _Verdict("column", rule, runs)
908
+ if n < MIN_RESIDUES:
909
+ return _Verdict("column", f"a column: {'one residue does' if n == 1 else f'{n} residues do'} not make "
910
+ f"a plane", runs)
911
+ if asked == "auto" and len(runs) == 1:
912
+ return _Verdict("column", f"a column: the residues of {spine} at the interface that are shown are one "
913
+ f"stretch of its chain ({self._spans(residues, runs)})", runs)
914
+ why, they = ((f"the residues of {spine} at the interface that are shown come in {some} of its chain", "they")
915
+ if asked == "auto" else ("the plane was asked for", "the residues"))
916
+ failed = self._no_plane.get(tuple(residues))
917
+ if failed is not None:
918
+ return _Verdict("column", f"a column in the order of the sequence: {why}, but {failed}", runs,
919
+ sequence_only=True)
920
+ arrangement = self._project(residues, runs)
921
+ if not arrangement.bare.ok:
922
+ return _Verdict("column", f"a column in the order of the sequence: {why}, but {they} do not lie near "
923
+ f"enough to one plane to be drawn where they lie "
924
+ f"({_shortfall(arrangement.bare)})", runs, considered=arrangement,
925
+ sequence_only=True)
926
+ return _Verdict("plane", f"on the plane through them: {why}", runs, arrangement=arrangement,
927
+ considered=arrangement)
928
+
929
+ def reach(self, column: Sequence[ResidueKey]) -> int:
930
+ """How far the contacts of the residues around a column are spread along it, summed over those
931
+ residues (in boxes). It is what makes lines long, makes them cross, and makes a residue be
932
+ drawn twice; of two orders of the column the one with the smaller reach is the better drawing."""
933
+ place = {k: i for i, k in enumerate(column)}
934
+ spread: dict[ResidueKey, tuple[int, int]] = {}
935
+ for c in self._oriented:
936
+ if c.residue_a in place:
937
+ lo, hi = spread.get(c.residue_b, (place[c.residue_a], place[c.residue_a]))
938
+ spread[c.residue_b] = (min(lo, place[c.residue_a]), max(hi, place[c.residue_a]))
939
+ return sum(hi - lo for lo, hi in spread.values())
940
+
941
+ def _along(self, residues: Sequence[ResidueKey]) -> bool:
942
+ """Is the column ordered along the interface (and not by the sequence)? By default where that
943
+ shortens the reach of the residues around it; where it does not, the sequence is kept."""
944
+ if len(residues) < 3 or self.order == "sequence":
945
+ return False
946
+ if self.order == "interface":
947
+ return True
948
+ if self._sequence_only:
949
+ # Several stretches that could not be drawn where they lie: no order that promises
950
+ # neighbours in space either.
951
+ return False
952
+ return self.reach(self._by_position(residues)) < self.reach(residues)
953
+
954
+ def _arranged(self, residues: Sequence[ResidueKey]) -> list[ResidueKey]:
955
+ """The residues of the spine in the order of the column."""
956
+ return self._by_position(residues) if self._along(residues) else list(residues)
957
+
958
+ def _by_position(self, residues: Sequence[ResidueKey]) -> list[ResidueKey]:
959
+ """The residues along the long axis of the interface: the first principal axis of their alpha carbons."""
960
+ centres = []
961
+ for k in residues:
962
+ atoms = self.structure.residue_atoms(k)
963
+ ca = [a.xyz for a in atoms if a.name == "CA"] or [a.xyz for a in atoms]
964
+ centres.append(ca[0])
965
+ xyz = np.array(centres, dtype=float)
966
+ _, _, axes = np.linalg.svd(xyz - xyz.mean(axis=0), full_matrices=False)
967
+ along = (xyz - xyz.mean(axis=0)) @ axes[0]
968
+ if along[0] > along[-1]:
969
+ along = -along # the residue that comes first in the sequence nearer the top
970
+ return [k for _, _, k in sorted(zip(along.tolist(), range(len(residues)), residues))]
971
+
972
+ # ------------------------------------------------------------------ what the figure says
973
+ @property
974
+ def others(self) -> tuple[Participant, ...]:
975
+ """The participants that stand around the spine."""
976
+ return tuple(p for p in self.participants if p is not self.spine)
977
+
978
+ @property
979
+ def title(self) -> str:
980
+ """What the figure is called unless it is given a title."""
981
+ return " – ".join(p.name for p in self.participants)
982
+
983
+ def _info(self, site: Site) -> _Info:
984
+ spine, others = self.spine, " and ".join(p.name for p in self.others)
985
+ plane = self.layout == "plane"
986
+ if plane:
987
+ assert self._arrangement is not None
988
+ viewer, _ = self._viewer(site.residues)
989
+ tilt = self._arrangement.tilt
990
+ seen = (f"seen from the side of {viewer.name}" if tilt is None or tilt <= 45.0 else
991
+ f"seen at right angles to that plane ({viewer.name} lies {tilt:.0f}\u00b0 off that line of sight)")
992
+ some = f"{len(self._runs)} stretches" if len(self._runs) != 1 else "one stretch"
993
+ notes = [f"An interface has no centre. The residues of {spine.name} that touch {others} come in {some} "
994
+ f"of its chain: each box stands where its residue's centre lies on the plane through those "
995
+ f"centres, at one scale, {seen}; a line joins neighbours in the chain, a dotted line two with up "
996
+ f"to {'three' if STRETCH_GAP == 3 else STRETCH_GAP} residues between them. Those of {others} "
997
+ f"are not drawn where they lie but beside the boxes they touch. A line to one of them is a "
998
+ f"pair of residues, at the shortest of its contacts of one kind."]
999
+ else:
1000
+ if self._along(site.residues):
1001
+ how = ("as boxes, ordered along the interface and not by their sequence: neighbours in the column "
1002
+ "are neighbours in space")
1003
+ else:
1004
+ how = ("as boxes, in the order of the sequence; a dotted line stands for residues in between that "
1005
+ "do not")
1006
+ notes = [f"An interface has no centre. The residues of {spine.name} that touch {others} stand in a "
1007
+ f"column, {how}; those of {others} around it. A line is a pair of residues, at the shortest of "
1008
+ f"its contacts of one kind."]
1009
+ unshown: "str | None" = None
1010
+ if not plane and self._sequence_only:
1011
+ # Several stretches, and no plane for them: the column is a list, and has to say so.
1012
+ some = f"{len(self._runs)} stretches" if len(self._runs) != 1 else "one stretch"
1013
+ failed = self._no_plane.get(tuple(site.residues))
1014
+ reason = (failed if failed is not None else
1015
+ f"they do not lie near enough to one plane ({_shortfall(self._considered.bare)})"
1016
+ if self._considered is not None else "that was not possible")
1017
+ if len(self._runs) > 1:
1018
+ unshown = (f"These residues come in {some} of the chain, which no column can set out as they lie in "
1019
+ f"space. They are not drawn where they lie either: {reason}. How the stretches lie to "
1020
+ f"each other is not shown.")
1021
+ else:
1022
+ unshown = (f"These residues were to be drawn where they lie, and are not: {reason}. The column is "
1023
+ f"their order in the chain and nothing more.")
1024
+ notes.append(unshown)
1025
+ directional = any(c.type is not InteractionType.HYDROPHOBIC for c in self._oriented
1026
+ if c.residue_a in set(site.residues))
1027
+ if self._beside and not plane and directional:
1028
+ # Boxes with atoms beside them: what the atoms are, and what a line from one of them is.
1029
+ more = {"backbone": ", and with them its backbone nitrogen and carbonyl",
1030
+ "sidechain": ", and with them the whole side chain",
1031
+ "atoms": ", and with them every other atom of the residue"}[self.detail[spine.name] or "atoms"]
1032
+ notes.append(f"Where a residue of {spine.name} makes a contact that has a direction (an H-bond, a salt "
1033
+ f"bridge and the like), the atoms that make it are drawn beside its box{more}. The box "
1034
+ f"is the residue's alpha carbon. A line that ends on such an atom is the contact of that "
1035
+ f"atom and gives its distance; a line that ends on a box stands for the pair of residues.")
1036
+ if site.whole:
1037
+ notes.append(f"All {site.of_residues} residues of {spine.name} at the interface are shown, with "
1038
+ f"{site.of_contacts} contacts.")
1039
+ else:
1040
+ notes.append(f"A site, not the whole interface: {len(site.residues)} of the {site.of_residues} residues "
1041
+ f"of {spine.name} at the interface ({site.rule}), with {site.contacts} of "
1042
+ f"{site.of_contacts} contacts.")
1043
+ meta = {"participants": [{"name": p.name, "chains": list(p.chains)} for p in self.participants],
1044
+ "spine": spine.name,
1045
+ "spine_order": None if plane else "interface" if self._along(site.residues) else "sequence",
1046
+ "contacts_from": self.source,
1047
+ "site": _site_meta(site),
1048
+ "layout": self.layout, "layout_rule": self.layout_rule, "stretches": len(self._runs)}
1049
+ if any(v is not None for v in self.detail.values()):
1050
+ # Said only where a level was asked for: the graph of a figure without one has no such key.
1051
+ meta["detail"] = {p.name: self.detail[p.name] for p in self.participants}
1052
+ if self._considered is not None and not plane:
1053
+ # A plane that was looked at and not drawn: what it would have been, and against what.
1054
+ considered = self._considered
1055
+ meta["plane"] = {"drawn": False, **considered.bare.as_dict(),
1056
+ "out_of_plane_rms": round(considered.rms, 2),
1057
+ "thresholds": {"neighbours_kept_min": KEPT_MIN, "distance_error_max": ERROR_MAX,
1058
+ "neighbour_within": NEAR, "apart_beyond": APART}}
1059
+ info = _Info(f"Residue of {spine.name}, numbered as in the structure file", notes, meta,
1060
+ shape="plane" if plane else "column")
1061
+ if unshown is not None:
1062
+ info.summary_notes.append(unshown)
1063
+ shown = [c for c in self._oriented if c.residue_a in set(site.residues)]
1064
+ errors = [c.pae for c in shown if c.pae is not None]
1065
+ if errors:
1066
+ # A PAE is a number of two residues, and so is a line of the figure: counted by pair.
1067
+ pairs: dict[tuple[ResidueKey, ResidueKey], float | None] = {}
1068
+ for c in shown:
1069
+ key = (c.residue_a, c.residue_b)
1070
+ known = pairs.get(key)
1071
+ pairs[key] = c.pae if known is None else known if c.pae is None else min(known, c.pae)
1072
+ # Draws are said of a figure all of whose values are medians of the same number of draws.
1073
+ counts = {len(c.pae_draws) for c in shown if c.pae is not None}
1074
+ draws = counts.pop() if len(counts) == 1 else 0
1075
+ by_draw = [[c.pae_draws[k] for c in shown if c.pae is not None] for k in range(draws if draws > 1 else 0)]
1076
+ read = any(frozenset((c.residue_a, c.residue_b)) in self._from_matrix for c in shown)
1077
+ self._say_pae(info, errors, len(shown), [v for v in pairs.values() if v is not None], len(pairs),
1078
+ from_matrix=read, by_draw=by_draw,
1079
+ draws=self.pae if isinstance(self.pae, PaeDraws) else None)
1080
+ if self.ipsae:
1081
+ self._say_ipsae(info, self.ipsae)
1082
+ return info
1083
+
1084
+ @staticmethod
1085
+ def _say_ipsae(info: _Info, scores: "Sequence[InterfaceIpsae]") -> None:
1086
+ """What a figure says of the ipSAE that was asked for: the numbers under the title, in both
1087
+ directions, and in a footnote what they are. No verdict: there is no threshold of bindview's."""
1088
+ n_draws = len(scores[0].draws)
1089
+ cutoff = scores[0].cutoff
1090
+ # Short, because the line under the title does not wrap: which value is which is in the footnote.
1091
+ info.strip.append(("ipSAE", " \u00b7 ".join(f"{s.forward:.2f} / {s.backward:.2f}" for s in scores)))
1092
+ info.strip_data["ipsae"] = " ".join(f"{s.forward:.2f} {s.backward:.2f}" for s in scores)
1093
+ info.strip_data["ipsae-cutoff"] = f"{cutoff:g}"
1094
+ first = scores[0].first
1095
+ said = (f"ipSAE (Dunbrack 2025) is a score from 0 to 1 of how well the model places two chains against "
1096
+ f"each other. It is worked out from the PAE of every pair of their residues that is below "
1097
+ f"{cutoff:g} \u00c5, not from the contacts shown here. It has a direction: ")
1098
+ if len(scores) == 1:
1099
+ said += (f"the first value is with the model aligned on a residue of {first} and scored over "
1100
+ f"{scores[0].second}, the second the reverse.")
1101
+ else:
1102
+ pairs = " and ".join(f"{first} with {s.second}" for s in scores)
1103
+ said += (f"of each pair of values the first is with the model aligned on a residue of {first} and "
1104
+ f"scored over the other participant, the second the reverse. The pairs are {pairs}, in "
1105
+ f"that order.")
1106
+ if n_draws > 1:
1107
+ each = "; ".join(", ".join(f"{d.forward.value:.2f} / {d.backward.value:.2f}" for d in s.draws)
1108
+ for s in scores)
1109
+ said += f" Each value is the median of {n_draws} draws of the model (draw by draw: {each})."
1110
+ if any(d.same_chain for s in scores for d in s.draws):
1111
+ said += (" Both sides are parts of one chain of this model. The score was defined for two chains, and "
1112
+ "residues that follow each other in a chain have a low PAE whatever its domains do.")
1113
+ left_out = max(d.left_out for s in scores for d in s.draws)
1114
+ if left_out:
1115
+ said += (f" {left_out} residue{'s' if left_out != 1 else ''} of the two sides "
1116
+ f"{'have' if left_out != 1 else 'has'} no alpha carbon and "
1117
+ f"{'are' if left_out != 1 else 'is'} not in it.")
1118
+ info.notes.append(said)
1119
+ info.summary_notes.append(said)
1120
+ info.meta["ipsae"] = {
1121
+ "cutoff": cutoff, "d0": "from the residues below the cut-off, for each aligned residue",
1122
+ "scores": [{"aligned_on": a, "scored_over": b, "value": round(v, 3),
1123
+ **({"by_draw": [round(x, 3) for x in each_draw]} if n_draws > 1 else {})}
1124
+ for s in scores
1125
+ for a, b, v, each_draw in (
1126
+ (s.first, s.second, s.forward, [d.forward.value for d in s.draws]),
1127
+ (s.second, s.first, s.backward, [d.backward.value for d in s.draws]))]}
1128
+ if n_draws > 1:
1129
+ info.meta["ipsae"].update({"draws": n_draws, "over_draws": "median"})
1130
+
1131
+ @staticmethod
1132
+ def _say_pae(info: _Info, errors: Sequence[float], n_contacts: int, pairs: Sequence[float],
1133
+ n_pairs: int, from_matrix: bool = False, by_draw: "Sequence[Sequence[float]]" = (),
1134
+ draws: "PaeDraws | None" = None) -> None:
1135
+ """What a figure says about the predicted aligned error of its contacts, beside the tags on the lines.
1136
+
1137
+ ``errors`` are the values of the contacts, ``pairs`` those of the residue pairs they are between
1138
+ (``n_pairs`` with the pairs that have none). ``from_matrix``: values among them were read from a
1139
+ matrix, so it is known which of its two directions they are; values that came with the contacts
1140
+ are taken as given, whether a matrix was handed in beside them or not.
1141
+ ``by_draw``: where every value is the median over the draws of a model, the contacts' values in
1142
+ each draw. The figure then says that it shows a median, of how many, and what each draw says;
1143
+ and, from ``draws``, where a draw names the copies of a chain in another order than the
1144
+ structure that is drawn.
1145
+ """
1146
+ lo, hi = pae_shown(min(errors)), pae_shown(max(errors))
1147
+ tagged = sum(1 for v in pairs if pae_tag(v) is not None)
1148
+ n_draws = len(by_draw)
1149
+ info.strip.append((f"contact PAE, median of {n_draws} draws" if n_draws else "contact PAE",
1150
+ f"{min(errors):.1f} \u00c5" if round(min(errors), 1) == round(max(errors), 1)
1151
+ else f"{min(errors):.1f}\u2013{max(errors):.1f} \u00c5"))
1152
+ info.strip_data.update({"contact-pae-min": f"{min(errors):.1f}", "contact-pae-max": f"{max(errors):.1f}"})
1153
+ if n_draws:
1154
+ info.strip_data["contact-pae-draws"] = str(n_draws)
1155
+ what = ("PAE (predicted aligned error) is the model's expected error, in \u00e5ngstr\u00f6m, in placing one "
1156
+ "residue of a contact relative to the other: low is confident, about 32 means no idea. It is not "
1157
+ "pLDDT")
1158
+ info.notes.append(what + ", which line weight, dashes and ? show.")
1159
+ info.tag_notes.append(info.notes[-1])
1160
+ info.summary_notes.append(what + ". The range under the title is over all contacts; this table does not "
1161
+ "give it contact by contact.")
1162
+ if n_draws:
1163
+ # A median of draws is not what one draw says: how many, why the median, and each draw's own range.
1164
+ spans = [f"{min(v):.1f}\u2013{max(v):.1f}" for v in by_draw]
1165
+ each = ", ".join(spans[:-1]) + " and " + spans[-1]
1166
+ # Said of the draws that were handed in: how many times the model was sampled in all is not known here.
1167
+ said = (f"The PAE comes from {n_draws} samples of the model ({n_draws} draws). The PAE of a contact is "
1168
+ f"the median of its {n_draws} values, not the largest, which would rise with the number of "
1169
+ f"draws whatever the model knows. Draw by draw the contacts shown here range over {each} \u00c5.")
1170
+ renamed = draws.renamed if draws is not None else []
1171
+ if renamed:
1172
+ # Copies of a chain are named as the model pleases, draw by draw: said where it happened.
1173
+ groups = " and ".join(", ".join(g[:-1]) + " and " + g[-1] for g in draws.copies) # type: ignore[union-attr]
1174
+ said += (f" Chains {groups} are copies of one another, and the model names them in another order "
1175
+ f"in {len(renamed)} of these {n_draws} draws: the chains of every draw were matched to "
1176
+ f"those of the structure shown here, by superposition, before its values were read.")
1177
+ info.notes.append(said)
1178
+ info.summary_notes.append(said)
1179
+ if tagged:
1180
+ info.legend_extra.append(f"Predicted aligned error (PAE) of a contact in \u00c5"
1181
+ + (f", median of {n_draws} draws" if n_draws else "") + f": written from "
1182
+ f"{PAE_SHOWN} \u00c5, bold from {PAE_STRONG} \u00c5. Not pLDDT")
1183
+ if tagged == len(pairs):
1184
+ lead = ("The one residue pair in contact has" if tagged == 1
1185
+ else f"All {tagged} residue pairs in contact have")
1186
+ else:
1187
+ lead = f"{tagged} of the {len(pairs)} residue pairs in contact {'has' if tagged == 1 else 'have'}"
1188
+ note = (f"{lead} a PAE of {PAE_SHOWN} \u00c5 or more, written on "
1189
+ f"{'its line' if tagged == 1 else 'their lines'}.")
1190
+ else:
1191
+ note = f"No contact here reaches {PAE_SHOWN} \u00c5, so none carries a PAE on its line."
1192
+ if len(pairs) < n_pairs:
1193
+ none = n_pairs - len(pairs)
1194
+ note += f" For {none} more pair{'s' if none != 1 else ''} there is no PAE."
1195
+ info.notes.append(note)
1196
+ info.tag_notes.append(note)
1197
+ assert lo is not None and hi is not None
1198
+ if lo >= PAE_STRONG:
1199
+ # Said of every contact only where every contact has a value.
1200
+ whom = ("Every contact in this figure has a PAE" if len(errors) == n_contacts
1201
+ else "Every contact in this figure that has a PAE has one")
1202
+ info.warnings.append(
1203
+ f"{whom} of {PAE_STRONG} \u00c5 or more: the model does not place "
1204
+ f"the two sides against each other, whatever the pLDDT of their residues.")
1205
+ info.meta["pae"] = {"min": round(min(errors), 2), "max": round(max(errors), 2),
1206
+ "median": round(float(np.median(list(errors))), 2), "with_a_value": len(errors),
1207
+ "of_contacts": n_contacts, "pairs": len(pairs), "of_pairs": n_pairs,
1208
+ "pairs_written": tagged, "written_from": PAE_SHOWN, "bold_from": PAE_STRONG}
1209
+ if from_matrix:
1210
+ info.meta["pae"]["direction"] = "the smaller of the two directions of the matrix"
1211
+ if n_draws:
1212
+ info.meta["pae"].update({
1213
+ "draws": n_draws, "over_draws": "median",
1214
+ "by_draw": [{"min": round(min(v), 2), "median": round(float(np.median(list(v))), 2),
1215
+ "max": round(max(v), 2)} for v in by_draw]})
1216
+ if draws is not None and draws.copies:
1217
+ info.meta["pae"].update({"copies": draws.copies, "chains_matched_by": "superposition",
1218
+ "draws_named_otherwise": draws.renamed})
1219
+
1220
+ # ------------------------------------------------------------------ rendering
1221
+ def render(self, style: str = "detailed", **options: Any) -> Any:
1222
+ """Render the figure. When the site that was chosen cannot be drawn legibly and nobody asked
1223
+ for it by name, the figure narrows to a smaller one, twice at most, and says so.
1224
+
1225
+ Every figure starts from the site the interface was built with, whatever an earlier figure
1226
+ had to narrow to: what one style or one page cannot lay out does not decide what the next is
1227
+ given. After a render, :attr:`site`, :attr:`diagram` and :attr:`layout` are those of the
1228
+ figure it drew. A ``graph`` is a figure of the site it was made for: it is drawn at that
1229
+ site or it is not drawn, never narrowed.
1230
+ """
1231
+ given = options.get("graph")
1232
+ sites = self._sites()
1233
+ site = next(sites)
1234
+ if given is not None:
1235
+ held = (given.meta.get("interface") or {}).get("site")
1236
+ site = next((s for s in self._sites() if _site_meta(s) == held), site)
1237
+ self._show(site)
1238
+ result = self._draw(style, options)
1239
+ while result.status == "unreadable" and given is None:
1240
+ narrower = next(sites, None)
1241
+ if narrower is None:
1242
+ break
1243
+ self._show(narrower)
1244
+ result = self._draw(style, options)
1245
+ result.warnings.append(f"the interface could not be drawn legibly with more residues: narrowed to "
1246
+ f"{len(self.site.residues)} residues of {self.spine.name} ({self.site.rule})")
1247
+ return result
1248
+
1249
+ def _sites(self) -> "Iterator[Site]":
1250
+ """The site the interface was built with, and after it the sites a figure narrows to where it
1251
+ cannot be drawn legibly: twice at most, each time to three fifths of the residues and to no
1252
+ fewer than eight. A site that was asked for by name is not narrowed."""
1253
+ site = self._built
1254
+ yield site
1255
+ for _ in range(2):
1256
+ if self.seed is not None or len(site.residues) <= 8:
1257
+ return
1258
+ site = choose_site(self._oriented, self._order, self._index, limit=max(8, (len(site.residues) * 3) // 5))
1259
+ yield site
1260
+
1261
+ def _show(self, site: Site) -> None:
1262
+ """Make ``site`` the one the next figure is of: its diagram, which is built once, and its layout."""
1263
+ if site == self.site:
1264
+ return
1265
+ if site in self._diagrams:
1266
+ self._decide(site)
1267
+ else:
1268
+ self._diagrams[site] = self._diagram(site)
1269
+ self.site, self.diagram = site, self._diagrams[site]
1270
+
1271
+ def _draw(self, style: str, options: "dict[str, Any]") -> Any:
1272
+ """One figure of the site as it stands. Where the residues were to stand on a plane and that
1273
+ cannot be laid out legibly, the column is drawn in its place, and the figure and the result say so."""
1274
+ given = options.get("graph")
1275
+ held = (given.meta.get("interface") or {}) if given is not None else {}
1276
+ if given is not None and held.get("layout", "column") != self.layout:
1277
+ # A graph is drawn as what it holds. The one case this object can serve from where it
1278
+ # stands: the column it drew itself in place of a plane that could not be laid out.
1279
+ column = self._column_instead(self.site) if self.layout == "plane" else None
1280
+ if column is None or column.backend.interface.meta["layout_rule"] != held.get("layout_rule"):
1281
+ raise BindviewError(
1282
+ f"the graph holds {'boxes on a plane' if held.get('layout') == 'plane' else 'a column'}, and "
1283
+ f"this interface is drawn {'on a plane' if self.layout == 'plane' else 'as a column'}: build it "
1284
+ f"with layout={held.get('layout', 'column')!r} to draw that graph")
1285
+ result = column.render(style=style, **options)
1286
+ result.warnings.extend(column.backend.interface.warnings)
1287
+ return result
1288
+ mine = self.diagram.backend.interface.meta.get("spine_order")
1289
+ if given is not None and "spine_order" in held and held["spine_order"] != mine:
1290
+ # The boxes of a graph are known by their place in the column: another order, other residues.
1291
+ raise BindviewError(f"the graph holds a column in the order of the {held['spine_order']}, and this "
1292
+ f"interface orders its column by the {mine}: build it with "
1293
+ f"order={held['spine_order']!r} to draw that graph")
1294
+ result = self.diagram.render(style=style, **options)
1295
+ result.warnings.extend(self.diagram.backend.interface.warnings)
1296
+ if self.layout == "column" and (self._sequence_only or self.layout_asked == "plane"
1297
+ or self._column_for_atoms):
1298
+ # A plane that the rule would have drawn, or that was asked for, and is not: said in the result.
1299
+ result.warnings.append(f"{self.spine.name} is drawn as {self.layout_rule}")
1300
+ if self.layout != "plane" or result.status != "unreadable" or given is not None:
1301
+ return result
1302
+ column = self._column_instead(self.site)
1303
+ result = column.render(style=style, **options)
1304
+ info = column.backend.interface
1305
+ result.warnings.extend(info.warnings)
1306
+ result.warnings.append(f"{self.spine.name} is drawn as {info.meta['layout_rule']}")
1307
+ return result
1308
+
1309
+ def _column_instead(self, site: Site) -> Any:
1310
+ """The column of a site whose plane cannot be laid out legibly: for the figure that was asked
1311
+ for and no other. The object stays what it is, so that what one style cannot lay out does not
1312
+ decide what the other is given."""
1313
+ key = tuple(site.residues)
1314
+ if key not in self._columns:
1315
+ self._no_plane[key] = "a figure with the boxes where they lie could not be laid out legibly"
1316
+ try:
1317
+ self._columns[key] = self._diagram(site)
1318
+ finally:
1319
+ del self._no_plane[key]
1320
+ self._decide(site)
1321
+ return self._columns[key]
1322
+
1323
+ def render_svg(self, path: "str | Path | None" = None, style: str = "detailed", **options: Any) -> Any:
1324
+ """Draw the interface and write it to ``path``, where one is given."""
1325
+ result = self.render(style=style, **options)
1326
+ if path is not None and result.svg is not None:
1327
+ Path(path).write_text(result.svg, encoding="utf-8")
1328
+ result.path = Path(path)
1329
+ return result