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/basepairs.py ADDED
@@ -0,0 +1,1711 @@
1
+ """Two chains of RNA or DNA and the base pairs between them, drawn as their secondary structures facing
2
+ each other.
3
+
4
+ An :class:`~bindview.Interface` of two nucleic-acid chains is a column of one strand with the other around
5
+ it, and a base pair is one of its hydrogen bonds among the others. What a reader of such an interface asks
6
+ is another thing: which nucleotides pair across, in which register, by which edges (the Leontis–Westhof
7
+ family of the pair), where on each strand's own fold, and what stacks across. :class:`BasePairs` draws
8
+ that.
9
+
10
+ The pairs are **read, not detected**, as PLIP's contacts are read:
11
+
12
+ - :func:`read_mmcif_pairs`: the PDB's own annotation of a deposited entry (``_ndb_struct_na_base_pair`` of
13
+ its mmCIF file). Its family is a number without the order of the edges for the asymmetric families, and
14
+ it covers the asymmetric unit: a pair with a crystal mate is marked and not drawn.
15
+ - :func:`read_fr3d_pairs`, :func:`read_fr3d_stacks`: the FR3D tables RNA 3D Hub serves for an entry
16
+ (``https://rna.bgsu.edu/rna3dhub/pdb/<ID>/interactions/fr3d/basepairs/csv``, and ``stacking``; licensed
17
+ CC BY 4.0, which the figure's source line credits). The family names the first nucleotide's edge first.
18
+ - :func:`read_rnapolis_pairs`, :func:`read_rnapolis_stacks`: the JSON that RNApolis's ``annotator`` writes
19
+ (``annotator -j pairs.json model.pdb``; RNApolis is MIT, run by the user in an environment of its own, and
20
+ never imported here). It annotates any model, a frame of a simulation or a prediction among them; the
21
+ family names the first nucleotide's edge first.
22
+ - :func:`pairs_from_dot_bracket`: a strand's secondary structure as the caller has it, with no family
23
+ unless the caller names one.
24
+ - :func:`pairs_from_contacts`: where there is no annotation (a frame of a simulation, a prediction), a
25
+ stand-in from bindview's plain distance table: two nucleotides with two or more hydrogen bonds from base
26
+ to base, and not stacked, are a pair *without a family*, drawn dashed and said so in the key.
27
+
28
+ The figure: each strand's own pairs of the
29
+ Watson–Crick family make stems and loops. Where those of both strands and the pairs across nest when the
30
+ second strand is written after the first (a duplex, a ribozyme on its substrate), the two are laid out as
31
+ one secondary structure with a nick between them; where they do not (a kissing complex is a pseudoknot of
32
+ the joined strands), each strand is laid out alone, the nucleotides of a loop that pair across on one
33
+ straight side of it, and the second strand is turned onto the first by its pairs across. A pair that does
34
+ not shape the layout (another family, a tertiary contact) is drawn pale. Under the drawing, a key of what
35
+ it draws and a line saying where its pairs came from.
36
+ """
37
+
38
+ from __future__ import annotations
39
+
40
+ import csv
41
+ import gzip
42
+ import io
43
+ import json
44
+ import math
45
+ from dataclasses import dataclass
46
+ from pathlib import Path
47
+ from typing import Any, Callable, Iterable, Sequence
48
+
49
+ import numpy as np
50
+
51
+ from .diagram import Quality, RenderResult
52
+ from .errors import BindviewError, RenderError
53
+ from .graph import Graph
54
+ from .interactive import hooks_of_links
55
+ from .near import pairs_within
56
+ from .scene import Circle, Group, Item, Line, Paint, Polygon, Polyline, Rect, Scene, Text, text_box
57
+ from .structure import Structure, _read_categories, read_structure
58
+ from .svg import to_svg
59
+ from .theme import Metrics, Palette, get_palette, scheme
60
+
61
+ __all__ = ["BasePair", "BaseStack", "BasePairs", "read_mmcif_pairs", "read_fr3d_pairs", "read_fr3d_stacks",
62
+ "read_rnapolis_pairs", "read_rnapolis_stacks", "pairs_from_dot_bracket", "pairs_from_contacts",
63
+ "pairs_within_from_table", "FAMILIES", "SOURCES"]
64
+
65
+ #: The twelve Leontis–Westhof families, in the numbering of the mmCIF item ``hbond_type_12``.
66
+ FAMILIES = ("cWW", "tWW", "cWH", "tWH", "cWS", "tWS", "cHH", "tHH", "cHS", "tHS", "cSS", "tSS")
67
+
68
+ #: What the source line of a figure says of a source tag (:attr:`BasePair.source`); another tag is
69
+ #: written as it is.
70
+ SOURCES = {
71
+ "pdb": "the PDB's annotation in the entry (_ndb_struct_na_base_pair)",
72
+ "fr3d": "FR3D, from RNA 3D Hub (rna.bgsu.edu/rna3dhub, CC BY 4.0)",
73
+ "rnapolis": "RNApolis's annotator (MIT), run on the model",
74
+ "dot-bracket": "a secondary structure given as a dot-bracket",
75
+ "plain-table": "bindview's plain distance table, without a family",
76
+ }
77
+
78
+ _ONE = {"A": "A", "C": "C", "G": "G", "U": "U", "DA": "A", "DC": "C", "DG": "G", "DT": "T", "RA": "A", "RC": "C",
79
+ "RG": "G", "RU": "U", "A5": "A", "A3": "A", "C5": "C", "C3": "C", "G5": "G", "G3": "G", "U5": "U", "U3": "U",
80
+ "RA5": "A", "RA3": "A", "RC5": "C", "RC3": "C", "RG5": "G", "RG3": "G", "RU5": "U", "RU3": "U",
81
+ "DA5": "A", "DA3": "A", "DC5": "C", "DC3": "C", "DG5": "G", "DG3": "G", "DT5": "T", "DT3": "T"}
82
+ #: Modified nucleotides, drawn by their parent's letter and marked as modified.
83
+ _PARENT = {"CBV": "C", "5BU": "U", "OMC": "C", "OMG": "G", "OMU": "U", "PSU": "U", "5MC": "C", "5MU": "U",
84
+ "1MA": "A", "1MG": "G", "2MG": "G", "M2G": "G", "7MG": "G", "H2U": "U", "4SU": "U", "GDP": "G",
85
+ "GTP": "G", "A2M": "A", "I": "G"}
86
+ _BACKBONE = {"P", "OP1", "OP2", "OP3", "O1P", "O2P", "O3P", "O5'", "C5'", "C4'", "O4'", "C3'", "O3'", "C2'",
87
+ "O2'", "C1'"}
88
+
89
+
90
+ def _letter(resname: str) -> tuple[str, bool]:
91
+ """One letter for a nucleotide, and whether it is modified."""
92
+ if resname in _ONE:
93
+ return _ONE[resname], False
94
+ return _PARENT.get(resname, "N"), True
95
+
96
+
97
+ # ---------------------------------------------------------------------------------------------------------
98
+ # Records
99
+ # ---------------------------------------------------------------------------------------------------------
100
+
101
+ @dataclass(frozen=True)
102
+ class BasePair:
103
+ """Two nucleotides whose bases pair, as a source says.
104
+
105
+ ``family`` is the Leontis–Westhof family (one of :data:`FAMILIES`, or the same with the edges the other
106
+ way round, ``"tHW"``), the edge of nucleotide ``a`` first; ``None`` where the source gives none.
107
+ ``ordered`` is false where the source names the family without saying which base uses which edge.
108
+ ``symmetry`` is the crystal operator of a partner that is a symmetry mate (``"6_555"``), empty for one
109
+ in the file. ``source`` is a tag of :data:`SOURCES` or the caller's own words.
110
+ """
111
+
112
+ chain_a: str
113
+ number_a: int
114
+ chain_b: str
115
+ number_b: int
116
+ family: str | None = None
117
+ icode_a: str = ""
118
+ icode_b: str = ""
119
+ ordered: bool = True
120
+ symmetry: str = ""
121
+ source: str = ""
122
+
123
+ @property
124
+ def key_a(self) -> tuple[str, int, str]:
125
+ """``(chain, number, insertion code)`` of the first nucleotide."""
126
+ return (self.chain_a, self.number_a, self.icode_a)
127
+
128
+ @property
129
+ def key_b(self) -> tuple[str, int, str]:
130
+ """``(chain, number, insertion code)`` of the second."""
131
+ return (self.chain_b, self.number_b, self.icode_b)
132
+
133
+
134
+ @dataclass(frozen=True)
135
+ class BaseStack:
136
+ """Two bases stacked on each other, as a source says."""
137
+
138
+ chain_a: str
139
+ number_a: int
140
+ chain_b: str
141
+ number_b: int
142
+ icode_a: str = ""
143
+ icode_b: str = ""
144
+ source: str = ""
145
+
146
+ @property
147
+ def key_a(self) -> tuple[str, int, str]:
148
+ """``(chain, number, insertion code)`` of the first nucleotide."""
149
+ return (self.chain_a, self.number_a, self.icode_a)
150
+
151
+ @property
152
+ def key_b(self) -> tuple[str, int, str]:
153
+ """``(chain, number, insertion code)`` of the second."""
154
+ return (self.chain_b, self.number_b, self.icode_b)
155
+
156
+
157
+ def _family(text: str) -> str | None:
158
+ t = text.strip()
159
+ if len(t) == 3 and t[0] in "ct" and t[1].upper() in "WHS" and t[2].upper() in "WHS":
160
+ return t[0] + t[1].upper() + t[2].upper()
161
+ return None
162
+
163
+
164
+ # ---------------------------------------------------------------------------------------------------------
165
+ # Readers
166
+ # ---------------------------------------------------------------------------------------------------------
167
+
168
+ def _text_of(path_or_text: "str | Path", is_text: "Callable[[str], bool]" = lambda text: False) -> str:
169
+ """What a reader was handed: the text of the file at a path, gzipped or not, or the text itself.
170
+ A ``str`` is the text where it has a line break, or where ``is_text`` says that it reads as what the
171
+ reader reads (a table of one row has no line break); any other names a file, which has to be there."""
172
+ if isinstance(path_or_text, str) and ("\n" in path_or_text or is_text(path_or_text)):
173
+ return path_or_text
174
+ p = Path(path_or_text)
175
+ try:
176
+ if p.suffix.lower() == ".gz":
177
+ with gzip.open(p, "rt", encoding="utf-8") as handle:
178
+ return handle.read()
179
+ return p.read_text(encoding="utf-8")
180
+ except (OSError, EOFError, UnicodeDecodeError) as exc:
181
+ raise BindviewError(f"cannot read {p}: {exc}") from exc
182
+
183
+
184
+ def read_mmcif_pairs(path_or_text: "str | Path") -> list[BasePair]:
185
+ """The base pairs the PDB annotated in a deposited entry: ``_ndb_struct_na_base_pair`` of its mmCIF
186
+ file (a path, gzipped or not, or the text). Chains and numbers are the authors', and the label ids
187
+ where the table has no others, as the atoms of such a file are named. Of an entry of several models,
188
+ the pairs of the first that the table lists. A pair whose partner is
189
+ a crystal mate keeps its operator in :attr:`BasePair.symmetry`. ``hbond_type_12`` gives the family;
190
+ for the asymmetric ones (cWH, tWH, cWS, tWS, cHS, tHS) the file does not say which base uses which
191
+ edge, and the pair says so (``ordered=False``). A file without the category gives no pairs."""
192
+ table = _read_categories(_text_of(path_or_text), {"_ndb_struct_na_base_pair"}).get("_ndb_struct_na_base_pair")
193
+ if not table:
194
+ return []
195
+ if len({len(values) for values in table.values()}) > 1:
196
+ raise BindviewError("_ndb_struct_na_base_pair: its columns do not have the same number of values (a row is "
197
+ "short)")
198
+ named = {end: tuple(next((f"{end}_{ids}_{what}" for ids in ("auth", "label") if f"{end}_{ids}_{what}" in table),
199
+ "") for what in ("asym_id", "seq_id")) for end in "ij"}
200
+ if not all(name for names in named.values() for name in names):
201
+ raise BindviewError("_ndb_struct_na_base_pair names no nucleotide: it has neither the authors' chain and "
202
+ "number of each (i_auth_asym_id, i_auth_seq_id, j_auth_asym_id, j_auth_seq_id) nor the "
203
+ "label ids")
204
+ (chain_i, seq_i), (chain_j, seq_j) = named["i"], named["j"]
205
+ models = table.get("model_number", [])
206
+ out = []
207
+ for k in range(len(table[seq_i])):
208
+ if models and models[k] != models[0]:
209
+ continue # the first model only, as the structure is read
210
+
211
+ def col(name: str) -> str:
212
+ v = table.get(name, ["?"] * (k + 1))[k]
213
+ return "" if v in ("?", ".") else v
214
+
215
+ def number(name: str) -> int:
216
+ try:
217
+ return int(col(name))
218
+ except ValueError:
219
+ raise BindviewError(f"_ndb_struct_na_base_pair, row {k + 1}: {name} is {table[name][k]!r}, which is "
220
+ f"no residue number") from None
221
+ code = col("hbond_type_12")
222
+ fam = FAMILIES[int(code) - 1] if code.isdigit() and 1 <= int(code) <= 12 else None
223
+ sym_i, sym_j = col("i_symmetry") or "1_555", col("j_symmetry") or "1_555"
224
+ sym = "" if sym_i == sym_j else (sym_j if sym_i == "1_555" else sym_i)
225
+ out.append(BasePair(col(chain_i), number(seq_i), col(chain_j),
226
+ number(seq_j), fam, col("i_pdb_ins_code"), col("j_pdb_ins_code"),
227
+ ordered=fam is None or fam[1] == fam[2], symmetry=sym, source="pdb"))
228
+ return out
229
+
230
+
231
+ def _unit(text: str) -> tuple[str, int, str, str]:
232
+ """An FR3D unit id, ``PDB|model|chain|component|number|atom|alt|icode|symmetry``: chain, number,
233
+ insertion code, symmetry operator."""
234
+ f = text.strip().split("|")
235
+ if len(f) < 5 or not f[4].lstrip("-").isdigit():
236
+ raise BindviewError(f"not an FR3D unit id: {text.strip()!r}")
237
+ icode = f[7] if len(f) > 7 else ""
238
+ sym = f[8] if len(f) > 8 else ""
239
+ return f[2], int(f[4]), icode, sym
240
+
241
+
242
+ def _fr3d_rows(path_or_text: "str | Path") -> Iterable[tuple[tuple[str, int, str, str], str, tuple[str, int, str, str]]]:
243
+ # A unit id has its fields between bars, and no file name has one.
244
+ table = csv.reader(io.StringIO(_text_of(path_or_text, lambda text: "|" in text)))
245
+ for row in table:
246
+ if len(row) < 3 or not row[0].strip():
247
+ continue
248
+ if row[0].split("|")[1:2] not in (["1"], []): # the first model only
249
+ continue
250
+ try:
251
+ units = _unit(row[0]), _unit(row[2])
252
+ except BindviewError as exc:
253
+ raise BindviewError(f"line {table.line_num} of the FR3D table: {exc}") from None
254
+ yield units[0], row[1].strip(), units[1]
255
+
256
+
257
+ def read_fr3d_pairs(path_or_text: "str | Path", source: str = "fr3d") -> list[BasePair]:
258
+ """The base pairs of an FR3D table as RNA 3D Hub serves it (CSV: unit id, family, unit id; a path or
259
+ the text). Each pair is listed once though the table lists it from both sides; near pairs (``ncWW``)
260
+ are left out. ``source`` is what the figure credits: the default credits RNA 3D Hub; give your own
261
+ words for a table made elsewhere."""
262
+ out: dict[frozenset, BasePair] = {}
263
+ for (c1, n1, i1, s1), fam, (c2, n2, i2, s2) in _fr3d_rows(path_or_text):
264
+ f = _family(fam)
265
+ if f is None:
266
+ continue
267
+ key = frozenset(((c1, n1, i1, s1), (c2, n2, i2, s2)))
268
+ if key not in out:
269
+ sym = s2 if s2 and s2 != "1_555" else (s1 if s1 and s1 != "1_555" else "")
270
+ out[key] = BasePair(c1, n1, c2, n2, f, i1, i2, symmetry=sym, source=source)
271
+ return list(out.values())
272
+
273
+
274
+ def read_fr3d_stacks(path_or_text: "str | Path", source: str = "fr3d") -> list[BaseStack]:
275
+ """The stacks of RNA 3D Hub's FR3D stacking table (``s33``, ``s35``, ``s53``, ``s55``), each once. A
276
+ stack with a crystal mate (a unit id with a symmetry operator other than the identity, ``1_555``) is
277
+ left out: a figure has the chains of the file."""
278
+ out: dict[frozenset, BaseStack] = {}
279
+ for (c1, n1, i1, s1), kind, (c2, n2, i2, s2) in _fr3d_rows(path_or_text):
280
+ if not kind.startswith("s") or s1 not in ("", "1_555") or s2 not in ("", "1_555"):
281
+ continue
282
+ key = frozenset(((c1, n1, i1), (c2, n2, i2)))
283
+ out.setdefault(key, BaseStack(c1, n1, c2, n2, i1, i2, source=source))
284
+ return list(out.values())
285
+
286
+
287
+ _RNAPOLIS_LISTS = ("base_pairs", "stackings")
288
+
289
+
290
+ def _rnapolis(path_or_json: "str | Path | dict") -> dict:
291
+ """What RNApolis's annotator wrote, as the object it is: one with a list of ``base_pairs``, of
292
+ ``stackings``, or of both. An object with neither is another program's, and is refused."""
293
+ data: Any = path_or_json
294
+ if not isinstance(data, dict):
295
+ try:
296
+ data = json.loads(_text_of(data, lambda text: text.lstrip().startswith(("{", "["))))
297
+ except ValueError as exc:
298
+ raise BindviewError(f"not the JSON of RNApolis's annotator: it is no JSON ({exc})") from exc
299
+ if not isinstance(data, dict):
300
+ raise BindviewError(f"not the JSON of RNApolis's annotator: an object is expected, not a JSON "
301
+ f"{type(data).__name__}")
302
+ if not any(key in data for key in _RNAPOLIS_LISTS):
303
+ raise BindviewError(f"not the JSON of RNApolis's annotator: it has neither 'base_pairs' nor 'stackings' "
304
+ f"(its keys: {', '.join(repr(k) for k in data) or 'none'})")
305
+ for key in _RNAPOLIS_LISTS:
306
+ if not isinstance(data.get(key, []), list):
307
+ raise BindviewError(f"not the JSON of RNApolis's annotator: its {key!r} is no list")
308
+ return data
309
+
310
+
311
+ def _rnapolis_entries(path_or_json: "str | Path | dict", key: str
312
+ ) -> Iterable[tuple[tuple[str, int, str], tuple[str, int, str], dict]]:
313
+ """The entries of one list of RNApolis's JSON, each with its two residues."""
314
+ for n, entry in enumerate(_rnapolis(path_or_json).get(key, []), start=1):
315
+ where = f"{key}, entry {n}, of RNApolis's JSON"
316
+ if not isinstance(entry, dict):
317
+ raise BindviewError(f"{where} is no object: {entry!r}")
318
+ for end in ("nt1", "nt2"):
319
+ if end not in entry:
320
+ raise BindviewError(f"{where} has no {end!r}")
321
+ yield _rnapolis_nt(entry["nt1"]), _rnapolis_nt(entry["nt2"]), entry
322
+
323
+
324
+ def _rnapolis_nt(entry: Any) -> tuple[str, int, str]:
325
+ """A residue of RNApolis's JSON: its author fields where it has them, else its label fields."""
326
+ try:
327
+ ids = entry.get("auth") or entry.get("label") or {}
328
+ return str(ids["chain"]), int(ids["number"]), str(ids.get("icode") or "")
329
+ except (AttributeError, KeyError, TypeError, ValueError):
330
+ raise BindviewError(f"a residue of RNApolis's JSON without a chain and a number: {entry!r}") from None
331
+
332
+
333
+ def read_rnapolis_pairs(path_or_json: "str | Path | dict", source: str = "rnapolis") -> list[BasePair]:
334
+ """The base pairs of the JSON that RNApolis's ``annotator`` writes (``annotator -j pairs.json model.pdb``),
335
+ a path, its text or the parsed object. The family (``lw``) names the first nucleotide's edge first; a pair
336
+ without one is read without a family. Each pair once."""
337
+ out: dict[frozenset, BasePair] = {}
338
+ for (c1, n1, i1), (c2, n2, i2), bp in _rnapolis_entries(path_or_json, "base_pairs"):
339
+ key = frozenset(((c1, n1, i1), (c2, n2, i2)))
340
+ if key not in out:
341
+ out[key] = BasePair(c1, n1, c2, n2, _family(str(bp.get("lw") or "")), i1, i2, source=source)
342
+ return list(out.values())
343
+
344
+
345
+ def read_rnapolis_stacks(path_or_json: "str | Path | dict", source: str = "rnapolis") -> list[BaseStack]:
346
+ """The stacks of RNApolis's JSON (``stackings``), each once; a figure draws those across its strands."""
347
+ out: dict[frozenset, BaseStack] = {}
348
+ for (c1, n1, i1), (c2, n2, i2), _ in _rnapolis_entries(path_or_json, "stackings"):
349
+ out.setdefault(frozenset(((c1, n1, i1), (c2, n2, i2))), BaseStack(c1, n1, c2, n2, i1, i2, source=source))
350
+ return list(out.values())
351
+
352
+
353
+ def pairs_from_dot_bracket(structure: "Structure | str | Path", chain: str, dot_bracket: str,
354
+ family: str | None = None, source: str = "dot-bracket") -> list[BasePair]:
355
+ """The pairs of one strand's secondary structure written as a dot-bracket, one character a nucleotide
356
+ of ``chain`` in the order of the chain: ``()``, ``[]``, ``{}``, ``<>`` for pairs, a dot (or any other
357
+ sign) for an unpaired nucleotide. A letter is refused: some notations write a further level of
358
+ pseudoknots with letters (``A`` closing with ``a``), which are not read here and would be pairs lost
359
+ without a word. No family unless the caller names one (``family="cWW"`` for a secondary structure of
360
+ Watson–Crick pairs)."""
361
+ st = structure if isinstance(structure, Structure) else read_structure(structure)
362
+ residues = st.polymer_residues(chain)
363
+ if len(residues) != len(dot_bracket):
364
+ raise BindviewError(f"the dot-bracket has {len(dot_bracket)} characters and chain {chain} has "
365
+ f"{len(residues)} nucleotides")
366
+ if family is not None and _family(family) is None:
367
+ raise BindviewError(f"{family!r} is not a Leontis–Westhof family (such as 'cWW')")
368
+ opening = {"(": ")", "[": "]", "{": "}", "<": ">"}
369
+ stacks: dict[str, list[int]] = {k: [] for k in opening.values()}
370
+ out = []
371
+ for i, ch in enumerate(dot_bracket):
372
+ if ch in opening:
373
+ stacks[opening[ch]].append(i)
374
+ elif ch in stacks:
375
+ if not stacks[ch]:
376
+ raise BindviewError(f"the dot-bracket closes a pair at {i + 1} that it did not open")
377
+ j = stacks[ch].pop()
378
+ a, b = residues[j], residues[i]
379
+ out.append(BasePair(chain, a.number, chain, b.number, _family(family) if family else None,
380
+ a.icode, b.icode, source=source))
381
+ elif ch.isalpha():
382
+ raise BindviewError(f"the dot-bracket has the letter {ch!r} at {i + 1}: a pair is written with one of "
383
+ f"the brackets () [] {{}} <>, and a letter, which some notations use for a further "
384
+ f"level of pseudoknots, is not read")
385
+ if any(stacks.values()):
386
+ raise BindviewError("the dot-bracket opens a pair that it does not close")
387
+ return out
388
+
389
+
390
+ def _bond_atoms(c: Any) -> tuple[str, str]:
391
+ """The atom at each end of a hydrogen bond of the plain table, an atom of the sugar under the name it
392
+ has today (``O2'`` for the ``O2*`` of old files). A row without them (a table written by hand may
393
+ leave them out) cannot be told to be from base to base or not, and is refused."""
394
+ if not c.atoms_a or not c.atoms_b:
395
+ raise BindviewError(f"the hydrogen bond of {c.chain_a}:{c.number_a}{c.icode_a} with "
396
+ f"{c.chain_b}:{c.number_b}{c.icode_b} names no atom on "
397
+ f"{'either side' if not c.atoms_a and not c.atoms_b else 'one side'}: whether it is from "
398
+ f"base to base cannot be told without its atoms")
399
+ return c.atoms_a[0].replace("*", "'"), c.atoms_b[0].replace("*", "'")
400
+
401
+
402
+ def pairs_from_contacts(contacts: Sequence[Any]) -> tuple[list[BasePair], list[BaseStack]]:
403
+ """A stand-in where no annotation is at hand: from bindview's plain distance table between two chains
404
+ (:func:`bindview.distance_table.interface_contacts`, with ``stacking=True`` for the stacks), two
405
+ nucleotides with two or more hydrogen bonds from base to base are a pair *without a family*, unless the
406
+ table also finds them stacked (a pair and a stack exclude each other); the stacks of the table are
407
+ stacks. A row may be written from either side: a bond is counted once, and a pair or a stack is named
408
+ from the side its first row is written from. Nothing here classifies a pair."""
409
+ bonds: dict[frozenset, set[frozenset]] = {}
410
+ ends: dict[frozenset, tuple] = {}
411
+ stacks: dict[frozenset, BaseStack] = {}
412
+ for c in contacts:
413
+ a, b = (c.chain_a, c.number_a, c.icode_a), (c.chain_b, c.number_b, c.icode_b)
414
+ two = frozenset((a, b))
415
+ if c.type.value == "pi_stacking":
416
+ stacks.setdefault(two, BaseStack(a[0], a[1], b[0], b[1], a[2], b[2], source="plain-table"))
417
+ elif c.type.value == "hbond":
418
+ atom_a, atom_b = _bond_atoms(c)
419
+ if atom_a not in _BACKBONE and atom_b not in _BACKBONE:
420
+ ends.setdefault(two, (a, b))
421
+ bonds.setdefault(two, set()).add(frozenset(((a, atom_a), (b, atom_b))))
422
+ pairs = [BasePair(a[0], a[1], b[0], b[1], None, a[2], b[2], source="plain-table")
423
+ for two, (a, b) in ends.items() if len(bonds[two]) >= 2 and two not in stacks]
424
+ return pairs, list(stacks.values())
425
+
426
+
427
+ def pairs_within_from_table(structure: "Structure | str | Path", chain: str) -> list[BasePair]:
428
+ """The stand-in of :func:`pairs_from_contacts` within one strand, where no annotation and no dot-bracket
429
+ is at hand: two nucleotides of the strand that are not neighbours, with two or more hydrogen bonds from
430
+ base to base by the plain distance table's rule (an N or O within
431
+ :data:`~bindview.distance_table.HBOND` of an N or O, one able to donate and the other to accept), are a
432
+ pair *without a family*. A nucleotide is in one pair at most: pairs are taken most bonds first, then
433
+ the shorter mean bond, and one whose nucleotide is taken is left out -- so a base triple shows as one
434
+ pair. Stacks within a strand are not looked for; nothing here classifies a pair.
435
+
436
+ The one-pair rule is needed because in a helix a base also makes two longer bonds (3.25 to 3.5 Å) to
437
+ the base diagonal to it, which would count as further pairs. It is fitted to one frame, of two
438
+ hairpins of a riboswitch, for which it gives the seven stem pairs of each that their dot-bracket
439
+ gives."""
440
+ from .distance_table import HBOND, _accepts, _donates
441
+
442
+ st = structure if isinstance(structure, Structure) else read_structure(structure)
443
+ keys = st.polymer_residues(chain)
444
+ atoms = [] # (position in the strand, key, resname, name, element, xyz)
445
+ for n, k in enumerate(keys):
446
+ name = st.residue_name(k)
447
+ for a in st.residue_atoms(k):
448
+ label = a.name.replace("*", "'")
449
+ if a.element in ("N", "O") and label not in _BACKBONE:
450
+ atoms.append((n, k, name, label, a.element, np.array(a.xyz, dtype=float)))
451
+ if not atoms:
452
+ return []
453
+ xyz = np.array([a[5] for a in atoms])
454
+ first, second, apart = pairs_within(xyz, xyz, HBOND)
455
+ bonds: dict[tuple[int, int], list[float]] = {}
456
+ for x, y, d in zip(first.tolist(), second.tolist(), apart.tolist()):
457
+ if y <= x: # (each pair once, in the order of the strand)
458
+ continue
459
+ (n1, _, r1, a1, e1, _), (n2, _, r2, a2, e2, _) = atoms[x], atoms[y]
460
+ if abs(n1 - n2) < 2:
461
+ continue
462
+ if (_donates(r1, a1) and _accepts(r2, a2, e2)) or (_donates(r2, a2) and _accepts(r1, a1, e1)):
463
+ bonds.setdefault((min(n1, n2), max(n1, n2)), []).append(d)
464
+ taken: set[int] = set()
465
+ kept = []
466
+ for (i, j), d in sorted(bonds.items(), key=lambda kv: (-len(kv[1]), sum(kv[1]) / len(kv[1]), kv[0])):
467
+ if len(d) >= 2 and i not in taken and j not in taken:
468
+ taken |= {i, j}
469
+ kept.append((i, j))
470
+ return [BasePair(chain, keys[i].number, chain, keys[j].number, None, keys[i].icode, keys[j].icode,
471
+ source="plain-table") for i, j in sorted(kept)]
472
+
473
+
474
+ # ---------------------------------------------------------------------------------------------------------
475
+ # Layout (in steps: one step between neighbours of a strand)
476
+ # ---------------------------------------------------------------------------------------------------------
477
+
478
+ B = 1.0 # backbone step
479
+ P = 1.7 # pair width, in steps
480
+
481
+
482
+ def _rot(v: np.ndarray) -> np.ndarray:
483
+ return np.array([-v[1], v[0]])
484
+
485
+
486
+ def _unit_vec(v: np.ndarray) -> np.ndarray:
487
+ n = float(np.linalg.norm(v))
488
+ return v / n if n > 1e-9 else np.array([1.0, 0.0])
489
+
490
+
491
+ def _circle_radius(lengths: list[float]) -> float:
492
+ lo, hi = max(lengths) / 2 + 1e-9, sum(lengths)
493
+
494
+ def total(r: float) -> float:
495
+ return sum(2 * math.asin(min(1.0, e / (2 * r))) for e in lengths)
496
+ if total(lo) < 2 * math.pi:
497
+ return lo
498
+ for _ in range(80):
499
+ mid = (lo + hi) / 2
500
+ if total(mid) > 2 * math.pi:
501
+ lo = mid
502
+ else:
503
+ hi = mid
504
+ return (lo + hi) / 2
505
+
506
+
507
+ def _radial(n: int, pairs: Sequence[tuple[int, int]], nick: int | None = None,
508
+ runs: "dict[int, int] | None" = None) -> np.ndarray:
509
+ """Coordinates for ``n`` nucleotides with nested ``pairs``: the exterior along the x axis, stems up,
510
+ each loop a polygon on a circle; the link ``nick -> nick + 1`` is no backbone; consecutive members of
511
+ one run (``runs``: nucleotide -> run) in a loop lie on one chord of its circle."""
512
+ run_of = runs or {}
513
+ pt = [-1] * n
514
+ for i, j in pairs:
515
+ pt[i], pt[j] = j, i
516
+ X = np.full((n, 2), np.nan)
517
+
518
+ def stem(i: int, j: int) -> None:
519
+ u = _rot(_unit_vec(X[j] - X[i]))
520
+ while i + 1 < j - 1 and pt[i + 1] == j - 1:
521
+ X[i + 1], X[j - 1] = X[i] + B * u, X[j] + B * u
522
+ i, j = i + 1, j - 1
523
+ loop(i, j, u)
524
+
525
+ def loop(k: int, l: int, u: np.ndarray) -> None:
526
+ V, t = [k], k + 1
527
+ while t < l:
528
+ if pt[t] == -1:
529
+ V.append(t)
530
+ t += 1
531
+ else:
532
+ V += [t, pt[t]]
533
+ t = pt[t] + 1
534
+ V.append(l)
535
+ children = [(V[a], V[a + 1]) for a in range(1, len(V) - 2) if pt[V[a]] == V[a + 1]]
536
+ e1 = _unit_vec(X[l] - X[k])
537
+ if nick is not None and k <= nick < l and not children:
538
+ for s, t in enumerate(range(k + 1, nick + 1), 1): # open ends: the strands run on
539
+ X[t] = X[k] + s * B * u
540
+ for s, t in enumerate(range(l - 1, nick, -1), 1):
541
+ X[t] = X[l] + s * B * u
542
+ return
543
+ corners: list[int] = []
544
+ lengths: list[float] = []
545
+ inner: dict[int, list[int]] = {}
546
+ a = 0
547
+ while True:
548
+ corners.append(V[a])
549
+ if a == len(V) - 1:
550
+ break
551
+ b = a
552
+ while (a >= 1 and b + 1 < len(V) - 1 and V[b + 1] == V[b] + 1 and pt[V[b]] != V[b + 1]
553
+ and V[b] in run_of and run_of.get(V[b + 1]) == run_of[V[b]]):
554
+ b += 1
555
+ if b > a + 1:
556
+ inner[V[a]] = V[a + 1:b]
557
+ lengths.append((b - a) * B)
558
+ a = b
559
+ else:
560
+ x, y = V[a], V[a + 1]
561
+ lengths.append(P if pt[x] == y else (2.5 * B if x == nick else B))
562
+ a += 1
563
+ lengths.append(P)
564
+ r = _circle_radius(lengths)
565
+ h = math.sqrt(max(r * r - P * P / 4, 0.0))
566
+ c = (X[k] + X[l]) / 2 + h * u
567
+ ang = math.atan2(-h, -P / 2)
568
+ for a in range(1, len(corners) - 1):
569
+ ang -= 2 * math.asin(min(1.0, lengths[a - 1] / (2 * r)))
570
+ X[corners[a]] = c + r * (math.cos(ang) * e1 + math.sin(ang) * u)
571
+ for a in range(len(corners) - 1):
572
+ mids = inner.get(corners[a], [])
573
+ s0, s1 = X[corners[a]], X[corners[a + 1]]
574
+ for q, m in enumerate(mids, 1):
575
+ X[m] = s0 + (s1 - s0) * q / (len(mids) + 1)
576
+ for x, y in children:
577
+ stem(x, y)
578
+
579
+ x, t = 0.0, 0
580
+ while t < n:
581
+ if pt[t] == -1 or pt[t] < t:
582
+ X[t] = (x, 0.0)
583
+ x += 2.5 * B if t == nick else B
584
+ t += 1
585
+ else:
586
+ j = pt[t]
587
+ X[t], X[j] = (x, 0.0), (x + P, 0.0)
588
+ stem(t, j)
589
+ x += P + (2.5 * B if j == nick else B)
590
+ t = j + 1
591
+ return X
592
+
593
+
594
+ def _crossing(p: tuple[int, int], q: tuple[int, int]) -> bool:
595
+ (i, j), (k, l) = sorted(p), sorted(q)
596
+ return i < k < j < l or k < i < l < j
597
+
598
+
599
+ def _nested(pairs: Sequence[tuple[int, int]]) -> list[tuple[int, int]]:
600
+ """The pairs that make the layout: runs of stacked pairs, longest first, each kept where it crosses
601
+ nothing kept before it and uses no nucleotide twice."""
602
+ ps = sorted({(min(p), max(p)) for p in pairs})
603
+ have = set(ps)
604
+ runs, seen = [], set()
605
+ for p in ps:
606
+ if p in seen:
607
+ continue
608
+ run, (i, j) = [p], p
609
+ while (i + 1, j - 1) in have and i + 1 < j - 1:
610
+ i, j = i + 1, j - 1
611
+ run.append((i, j))
612
+ seen.update(run)
613
+ runs.append(run)
614
+ runs.sort(key=lambda r: (-len(r), r[0]))
615
+ kept: list[tuple[int, int]] = []
616
+ used: set[int] = set()
617
+ for run in runs:
618
+ if any(i in used or j in used for i, j in run):
619
+ continue
620
+ if any(_crossing(p, q) for p in run for q in kept):
621
+ continue
622
+ kept += run
623
+ used.update(x for p in run for x in p)
624
+ return kept
625
+
626
+
627
+ def _runs(across: Sequence[tuple[int, int]]) -> list[list[tuple[int, int]]]:
628
+ have = set(across)
629
+ out, seen = [], set()
630
+ for p in sorted(across):
631
+ if p in seen:
632
+ continue
633
+ run, (i, j) = [p], p
634
+ while (i + 1, j - 1) in have:
635
+ i, j = i + 1, j - 1
636
+ run.append((i, j))
637
+ seen.update(run)
638
+ out.append(run)
639
+ return out
640
+
641
+
642
+ def _kabsch(src: np.ndarray, dst: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
643
+ cs, cd = src.mean(0), dst.mean(0)
644
+ u, _, vt = np.linalg.svd((src - cs).T @ (dst - cd))
645
+ d = np.sign(np.linalg.det(vt.T @ u.T)) or 1.0
646
+ r = vt.T @ np.diag([1.0, d]) @ u.T
647
+ return r, cd - r @ cs
648
+
649
+
650
+ def _relax(X: np.ndarray, springs: list[tuple[int, int, float, float]], iters: int = 2500,
651
+ d_min: float = 1.3) -> np.ndarray:
652
+ """Springs and a short-range push, each step scaled by a node's own stiffness."""
653
+ X = X.copy()
654
+ si = np.array([s[0] for s in springs], dtype=int)
655
+ sj = np.array([s[1] for s in springs], dtype=int)
656
+ rest = np.array([s[2] for s in springs])
657
+ w = np.array([s[3] for s in springs])
658
+ n = len(X)
659
+ stiff = np.full(n, 2.0)
660
+ np.add.at(stiff, si, w)
661
+ np.add.at(stiff, sj, w)
662
+ iu = np.triu_indices(n, 1)
663
+ for it in range(iters):
664
+ g = np.zeros_like(X)
665
+ d = X[si] - X[sj]
666
+ L = np.linalg.norm(d, axis=1) + 1e-9
667
+ f = (w * (L - rest) / L)[:, None] * d
668
+ np.add.at(g, si, f)
669
+ np.add.at(g, sj, -f)
670
+ D = X[iu[0]] - X[iu[1]]
671
+ Ld = np.linalg.norm(D, axis=1) + 1e-9
672
+ close = Ld < d_min
673
+ if close.any():
674
+ fr = (-(d_min - Ld[close]) / Ld[close])[:, None] * D[close] * 2.0
675
+ np.add.at(g, iu[0][close], fr)
676
+ np.add.at(g, iu[1][close], -fr)
677
+ X -= 0.45 * (1 - 0.8 * it / iters) * g / stiff[:, None]
678
+ return X
679
+
680
+
681
+ def _tidy(X: np.ndarray, side: np.ndarray, kept: Sequence[tuple[int, int]],
682
+ across: Sequence[tuple[int, int]]) -> np.ndarray:
683
+ """Push apart what overlaps, keeping each stretch's shape: backbone and pairs as they are, every
684
+ nucleotide at its distance from the next but one, and runs across as straight ladders."""
685
+ springs: list[tuple[int, int, float, float]] = []
686
+ n = len(X)
687
+ for i in range(n - 1):
688
+ if side[i] == side[i + 1]:
689
+ springs.append((i, i + 1, B, 8.0))
690
+ if i + 2 < n and side[i + 2] == side[i]:
691
+ springs.append((i, i + 2, float(np.linalg.norm(X[i] - X[i + 2])), 2.0))
692
+ have = set(kept)
693
+ for i, j in kept:
694
+ springs.append((i, j, P, 8.0))
695
+ if (i + 1, j - 1) in have:
696
+ springs += [(i, j - 1, math.hypot(B, P), 4.0), (i + 1, j, math.hypot(B, P), 4.0)]
697
+ for run in _runs(across):
698
+ for q, (i, j) in enumerate(run):
699
+ springs.append((i, j, P, 6.0))
700
+ if q + 1 < len(run):
701
+ i2, j2 = run[q + 1]
702
+ springs += [(i, j2, math.hypot(B, P), 4.0), (i2, j, math.hypot(B, P), 4.0)]
703
+ if q + 2 < len(run):
704
+ i3, j3 = run[q + 2]
705
+ springs += [(i, i3, 2 * B, 3.0), (j, j3, 2 * B, 3.0)]
706
+ return _relax(X, springs)
707
+
708
+
709
+ def _upright(X: np.ndarray, side: np.ndarray) -> np.ndarray:
710
+ """Turned so that the long axis is horizontal, the first strand left of or above the second; never
711
+ mirrored (a strand runs 5' to 3' the same way round in every figure)."""
712
+ c = X - X.mean(0)
713
+ _, _, vt = np.linalg.svd(c, full_matrices=False)
714
+ a = vt[0]
715
+ Y = c @ np.array([[a[0], a[1]], [-a[1], a[0]]]).T
716
+ m0, m1 = Y[side == 0].mean(0), Y[side == 1].mean(0)
717
+ dx, dy = m1 - m0
718
+ if (abs(dx) >= abs(dy) and dx < 0) or (abs(dx) < abs(dy) and dy > 0):
719
+ Y = -Y
720
+ return Y
721
+
722
+
723
+ def _shapes(p: BasePair) -> bool:
724
+ """May a pair shape the layout: one of the Watson–Crick family, or one of no known family."""
725
+ return p.family is None or p.family == "cWW"
726
+
727
+
728
+ @dataclass
729
+ class _Laid:
730
+ X: np.ndarray # steps, y up
731
+ side: np.ndarray
732
+ route: str
733
+ shaping: set[frozenset] # index pairs that shaped the layout
734
+
735
+
736
+ def _lay_out(n1: int, n2: int, pairs: Sequence[tuple[int, int, BasePair]]) -> _Laid:
737
+ side = np.array([0] * n1 + [1] * n2)
738
+ elig = [(i, j) for i, j, p in pairs if _shapes(p)]
739
+ across = [(i, j) if i < n1 else (j, i) for i, j, p in pairs if _shapes(p) and (i < n1) != (j < n1)]
740
+ kept = _nested(elig)
741
+ kept_set = {frozenset(k) for k in kept}
742
+ if across and all(frozenset(x) in kept_set for x in across):
743
+ X = _radial(n1 + n2, kept, nick=n1 - 1)
744
+ X = _tidy(X, side, kept, across)
745
+ return _Laid(_upright(X, side), side, "one structure of the joined strands", kept_set)
746
+ runs = _runs(across)
747
+ run_of: dict[int, int] = {}
748
+ for rn, run in enumerate(runs):
749
+ if len(run) >= 2:
750
+ for i, j in run:
751
+ run_of[i], run_of[j] = rn, rn
752
+ parts, own_all = [], []
753
+ for s, (base, size) in enumerate(((0, n1), (n1, n2))):
754
+ own = [(i - base, j - base) for i, j in elig if side[i] == s and side[j] == s]
755
+ k = _nested(own)
756
+ own_all += [(i + base, j + base) for i, j in k]
757
+ local = {i - base: r for i, r in run_of.items() if side[i] == s}
758
+ parts.append(_radial(size, k, runs=local))
759
+ X1, X2 = parts
760
+ if across:
761
+ n_out = _normals_of(X1)
762
+ src = np.array([X2[j - n1] for _, j in across])
763
+ dst = np.array([X1[i] + P * n_out[i] for i, _ in across])
764
+ if len(across) >= 2:
765
+ r, t = _kabsch(src, dst)
766
+ else:
767
+ r, t = np.eye(2), dst.mean(0) - src.mean(0)
768
+ else:
769
+ r, t = np.eye(2), np.array([X1[:, 0].max() + 4 * B - X2[:, 0].min(), 0.0])
770
+ X = np.vstack([X1, X2 @ r.T + t])
771
+ X = _tidy(X, side, own_all, across)
772
+ return _Laid(_upright(X, side), side, "each strand alone, placed by its pairs across",
773
+ {frozenset(k) for k in own_all} | {frozenset(k) for k in across})
774
+
775
+
776
+ def _normals_of(X: np.ndarray) -> np.ndarray:
777
+ """Outward directions: away from the neighbours within reach."""
778
+ N = np.zeros_like(X)
779
+ for i in range(len(X)):
780
+ d = np.linalg.norm(X - X[i], axis=1)
781
+ near = (d < 2.6) & (d > 0)
782
+ N[i] = _unit_vec(X[i] - X[near].mean(0)) if near.any() else np.array([0.0, 1.0])
783
+ return N
784
+
785
+
786
+ # ---------------------------------------------------------------------------------------------------------
787
+ # The figure
788
+ # ---------------------------------------------------------------------------------------------------------
789
+
790
+ #: The colours of the two strands and their fills, by palette name; a palette without them (one a caller
791
+ #: made) is given these of the light or the dark palette, by its background.
792
+ _STRAND_LIGHT = {"strand_1": "#2f63b0", "strand_1_fill": "#e2ebf8", "strand_2": "#c0561b", "strand_2_fill": "#f9e5d8"}
793
+ _STRAND_DARK = {"strand_1": "#7aa7e6", "strand_1_fill": "#1f3350", "strand_2": "#ea9a63", "strand_2_fill": "#4a2c19"}
794
+
795
+ _EDGE = {"W": "Watson–Crick", "H": "Hoogsteen", "S": "sugar"}
796
+
797
+ #: What each kind of mark means, in the key's words.
798
+ _KEY = {
799
+ "strands": "strand {a} and strand {b}; filled: paired across",
800
+ "across": "pair across the strands, cis Watson–Crick (G–C, A–U) where it has no symbol",
801
+ "across-none": "pair across, its family not annotated",
802
+ "within": "pair within a strand",
803
+ "within-none": "pair within a strand, its family not annotated",
804
+ "tertiary": "pale: a pair that does not shape the layout (another family, or a tertiary contact)",
805
+ "wobble": "G·U wobble",
806
+ "stack": "bases stacked across the strands",
807
+ "hbond": "other hydrogen bond across, with a sugar or phosphate atom",
808
+ "modified": "modified nucleotide, by its parent's letter",
809
+ }
810
+
811
+
812
+ def _family_name(f: str) -> str:
813
+ """One name for a family whichever base is named first: tHW is tWH (edges in the order W, H, S)."""
814
+ return f[0] + "".join(sorted(f[1:], key="WHS".index))
815
+
816
+
817
+ @dataclass(frozen=True)
818
+ class _Nt:
819
+ chain: str
820
+ number: int
821
+ icode: str
822
+ resname: str
823
+ letter: str
824
+ modified: bool
825
+
826
+ @property
827
+ def key(self) -> tuple[str, int, str]:
828
+ return (self.chain, self.number, self.icode)
829
+
830
+ @property
831
+ def name(self) -> str:
832
+ return f"{self.resname} {self.number}{self.icode}, chain {self.chain}"
833
+
834
+
835
+ class BasePairs:
836
+ """Two chains of RNA or DNA and the base pairs between them, as their secondary structures facing each
837
+ other (see the module's words).
838
+
839
+ ``structure`` is a :class:`~bindview.Structure` or a path; ``chains`` names the two strands. ``pairs``
840
+ are :class:`BasePair` records from any of the readers (or several, added together); the pairs of each
841
+ strand with itself shape its stems and loops, those between the two strands are the interface. Pairs
842
+ naming another chain, or a nucleotide the chains do not have, are left out and said in the result.
843
+ ``stacks``: :class:`BaseStack` records; left out, they are taken from ``contacts``. ``contacts``: the
844
+ plain distance table between the two chains (:func:`bindview.distance_table.interface_contacts`); its
845
+ hydrogen bonds with a sugar or phosphate atom between two nucleotides that are no pair are drawn as
846
+ other hydrogen bonds across, and with ``stacking=True`` its stacks are the stacks. ``source``: the line
847
+ under the key; left out, it is made from the sources the records name.
848
+
849
+ ``ligand``: a residue of the structure that is no part of the two chains (``"BGD"``, ``"C:1"``), drawn as a
850
+ box with its name between the nucleotides it touches, with a line for each kind of contact to each of
851
+ them. Its contacts are ``ligand_contacts`` -- interaction records, rows, or the path of a table, as a
852
+ :class:`~bindview.Diagram` takes them (PLIP's, say) -- and left out, those of bindview's plain distance
853
+ table (:func:`bindview.distance_table.ligand_contacts`, with ``ligand_smiles`` for the bond orders).
854
+ Contacts to anything but the nucleotides of the two chains are left out and said. ``ligand_name``: the
855
+ word in the box (the residue name, left out).
856
+ """
857
+
858
+ def __init__(self, structure: "Structure | str | Path", chains: Sequence[str], pairs: Iterable[BasePair],
859
+ *, stacks: "Iterable[BaseStack] | None" = None, contacts: Iterable[Any] = (),
860
+ source: str | None = None, ligand: "str | tuple[str, int] | Any | None" = None,
861
+ ligand_contacts: "Iterable[Any] | str | Path | None" = None, ligand_name: str | None = None,
862
+ ligand_smiles: str | None = None) -> None:
863
+ self.structure = structure if isinstance(structure, Structure) else read_structure(structure)
864
+ chains = list(chains)
865
+ if len(chains) != 2 or chains[0] == chains[1]:
866
+ raise BindviewError(f"BasePairs draws two chains; {chains!r} are not two")
867
+ self.chains = (chains[0], chains[1])
868
+ self.strands: list[list[_Nt]] = []
869
+ for chain in self.chains:
870
+ residues = self.structure.polymer_residues(chain)
871
+ if not residues:
872
+ where = self.structure.source or "the structure"
873
+ # A chain is nucleotides that are joined to one another: one alone, or several apart, is none.
874
+ apart = [k for k in self.structure.residues() if k.chain == chain and self._is_nucleotide(k)]
875
+ if apart:
876
+ named = ", ".join(f"{self.structure.residue_name(k)} {k.number}{k.icode}" for k in apart[:4])
877
+ raise BindviewError(
878
+ f"chain {chain!r} has {'one nucleotide' if len(apart) == 1 else f'{len(apart)} nucleotides'} "
879
+ f"in {where} ({named}{', ...' if len(apart) > 4 else ''}) and no two that are joined to each "
880
+ f"other: a strand is two or more nucleotides joined through a phosphate, and BasePairs "
881
+ f"draws two strands")
882
+ have = sorted({a.chain for a in self.structure.atoms})
883
+ raise BindviewError(f"chain {chain!r} has no nucleotides in {where}"
884
+ f" (its chains: {', '.join(have)})")
885
+ strand = []
886
+ for k in residues:
887
+ name = self.structure.residue_name(k)
888
+ letter, mod = _letter(name)
889
+ if letter == "N" and mod and not self._is_nucleotide(k):
890
+ raise BindviewError(f"chain {chain!r} is not a chain of nucleotides ({name} {k.number})")
891
+ strand.append(_Nt(chain, k.number, k.icode, name, letter, mod))
892
+ self.strands.append(strand)
893
+ self.warnings: list[str] = []
894
+ index = {n.key: i for i, n in enumerate(self.strands[0] + self.strands[1])}
895
+ self._index = index
896
+ self.pairs: list[BasePair] = []
897
+ seen: set[frozenset] = set()
898
+ foreign = missing = mates = 0
899
+ for p in pairs:
900
+ if p.chain_a not in self.chains or p.chain_b not in self.chains:
901
+ foreign += 1
902
+ continue
903
+ if p.symmetry:
904
+ mates += 1
905
+ continue
906
+ if p.key_a not in index or p.key_b not in index:
907
+ missing += 1
908
+ continue
909
+ pk = frozenset((p.key_a, p.key_b))
910
+ if pk in seen or p.key_a == p.key_b:
911
+ continue
912
+ seen.add(pk)
913
+ self.pairs.append(p)
914
+ if mates:
915
+ self.warnings.append(f"{mates} pair(s) with a crystal mate left out: the figure has the chains of the "
916
+ f"structure, not their symmetry mates")
917
+ if missing:
918
+ self.warnings.append(f"{missing} pair(s) naming a nucleotide that chains {self.chains[0]} and "
919
+ f"{self.chains[1]} do not have left out")
920
+ if foreign:
921
+ self.warnings.append(f"{foreign} pair(s) of other chains left out")
922
+ contacts = list(contacts)
923
+ if stacks is None:
924
+ stacks = pairs_from_contacts(contacts)[1] if contacts else []
925
+ self.stacks: list[BaseStack] = []
926
+ sseen: set[frozenset] = set()
927
+ for s in stacks:
928
+ if {s.chain_a, s.chain_b} != set(self.chains) or s.key_a not in index or s.key_b not in index:
929
+ continue
930
+ sk = frozenset((s.key_a, s.key_b))
931
+ if sk not in sseen:
932
+ sseen.add(sk)
933
+ self.stacks.append(s)
934
+ self.hbonds: list[tuple[tuple[str, int, str], tuple[str, int, str], int]] = []
935
+ bonds: dict[tuple, set[tuple[str, str]]] = {}
936
+ for c in contacts:
937
+ if c.type.value != "hbond":
938
+ continue
939
+ a, b = (c.chain_a, c.number_a, c.icode_a), (c.chain_b, c.number_b, c.icode_b)
940
+ if a not in index or b not in index or frozenset((a, b)) in seen or a[0] == b[0]:
941
+ continue
942
+ atom_a, atom_b = _bond_atoms(c)
943
+ if atom_a in _BACKBONE or atom_b in _BACKBONE:
944
+ if index[a] > index[b]: # a row written from the second strand: the same bond
945
+ a, b, atom_a, atom_b = b, a, atom_b, atom_a
946
+ bonds.setdefault((a, b), set()).add((atom_a, atom_b))
947
+ self.hbonds = [(a, b, len(atoms)) for (a, b), atoms in bonds.items()]
948
+ self.source = source
949
+ self._laid: tuple[tuple[BasePair, ...], _Laid] | None = None
950
+ #: The ligand beside the pairs, when one is named: its residue, its word, where its contacts came
951
+ #: from, and its contacts to each nucleotide (nucleotide -> the records).
952
+ self.ligand_key: Any = None
953
+ self.ligand_name: str | None = None
954
+ self.ligand_source: str | None = None
955
+ self.ligand_contacts: dict[tuple[str, int, str], list[Any]] = {}
956
+ if ligand is not None:
957
+ self._take_ligand(ligand, ligand_contacts, ligand_name, ligand_smiles)
958
+
959
+ def _take_ligand(self, ligand: Any, contacts: Any, name: str | None, smiles: str | None) -> None:
960
+ from .interactions import Interaction, load_interactions
961
+
962
+ key = self.structure.select_ligand(ligand)
963
+ if (key.chain, key.number, key.icode) in self._index:
964
+ raise BindviewError(f"the ligand {key} is a nucleotide of chain {key.chain}, one of the two strands")
965
+ self.ligand_key = key
966
+ self.ligand_name = name or self.structure.residue_name(key)
967
+ if contacts is None:
968
+ from .distance_table import ligand_contacts as plain_table
969
+
970
+ records = [Interaction.from_mapping(r) for r in plain_table(self.structure, key, smiles)]
971
+ self.ligand_source = "bindview's plain distance table"
972
+ elif isinstance(contacts, (str, Path)):
973
+ records = load_interactions(contacts)
974
+ self.ligand_source = Path(contacts).name
975
+ else:
976
+ records = [r if isinstance(r, Interaction) else Interaction.from_mapping(r) for r in contacts]
977
+ self.ligand_source = "as given"
978
+ outside = 0
979
+ for r in records:
980
+ k = (r.chain, int(r.residue_number), r.insertion_code or "")
981
+ if k in self._index:
982
+ self.ligand_contacts.setdefault(k, []).append(r)
983
+ else:
984
+ outside += 1
985
+ if outside:
986
+ self.warnings.append(f"{outside} contact(s) of the ligand {self.ligand_name} with residues outside "
987
+ f"chains {self.chains[0]} and {self.chains[1]} left out")
988
+ if not self.ligand_contacts:
989
+ self.warnings.append(f"the ligand {self.ligand_name} touches no nucleotide of chains {self.chains[0]} "
990
+ f"and {self.chains[1]}: it is not drawn")
991
+
992
+ def _is_nucleotide(self, key: Any) -> bool:
993
+ return any(a.name in ("C1'", "C1*") for a in self.structure.residue_atoms(key))
994
+
995
+ # -- what the figure says of itself ---------------------------------------------------------------
996
+ @property
997
+ def across(self) -> list[BasePair]:
998
+ """The pairs from one strand to the other."""
999
+ return [p for p in self.pairs if p.chain_a != p.chain_b]
1000
+
1001
+ @property
1002
+ def within(self) -> list[BasePair]:
1003
+ """The pairs within a strand."""
1004
+ return [p for p in self.pairs if p.chain_a == p.chain_b]
1005
+
1006
+ def source_line(self) -> str:
1007
+ """Where the pairs are from, in a sentence."""
1008
+ if self.source is not None:
1009
+ return self.source
1010
+ tags: list[str] = []
1011
+ for p in self.pairs:
1012
+ if p.source not in tags:
1013
+ tags.append(p.source)
1014
+ st: list[str] = []
1015
+ for s in self.stacks:
1016
+ if s.source not in st:
1017
+ st.append(s.source)
1018
+ both = bool(st) and st == tags # one source for both: said once
1019
+ head = "Pairs and stacks" if both else "Pairs"
1020
+
1021
+ def said(of: list[str]) -> str:
1022
+ """The sources in words; a record that names none (one made by hand) is said to have none."""
1023
+ named = [SOURCES.get(t, t) for t in of if t]
1024
+ if "" in of:
1025
+ named.append("some given without a source" if named else "given without a source")
1026
+ return "; ".join(named)
1027
+
1028
+ parts = [f"{head}: {said(tags)}." if tags else "No pairs given."]
1029
+ if st and not both:
1030
+ parts.append(f"Stacks: {said(st).replace(', without a family', '')}.")
1031
+ if self.hbonds:
1032
+ parts.append("Other hydrogen bonds across: bindview's plain distance table.")
1033
+ if self.ligand_contacts:
1034
+ parts.append(f"Contacts of {self.ligand_name}: {self.ligand_source}.")
1035
+ return " ".join(parts)
1036
+
1037
+ def _layout(self) -> _Laid:
1038
+ """The layout of the pairs the figure has now: laid out once, and again when they have changed."""
1039
+ pairs = tuple(self.pairs)
1040
+ if self._laid is None or self._laid[0] != pairs:
1041
+ ij = [(self._index[p.key_a], self._index[p.key_b], p) for p in pairs]
1042
+ self._laid = (pairs, _lay_out(len(self.strands[0]), len(self.strands[1]), ij))
1043
+ return self._laid[1]
1044
+
1045
+ # -- drawing ------------------------------------------------------------------------------------
1046
+ def render(self, theme: "str | Palette" = "light", *, metrics: Metrics | None = None, title: str | None = None,
1047
+ legend: bool = True, caption: bool = True, background: bool = True, colors: str = "standard",
1048
+ step: float = 24.0, figure_width_mm: float = 180.0, figure_height_mm: float = 240.0,
1049
+ min_font_pt: float = 5.0, interactive: bool = False, graph: "Graph | None" = None) -> RenderResult:
1050
+ """Draw the figure. ``theme``: ``"light"``, ``"dark"``, ``"auto"`` (both, following the reader) or a
1051
+ :class:`~bindview.Palette`; ``colors``: the colour scheme. ``step``: the distance of two neighbours
1052
+ of a strand, in px. ``legend``: the key under the drawing; ``caption``: the line of the source,
1053
+ which the result keeps in its ``notes`` also where it is left off the figure.
1054
+
1055
+ The figure is drawn whatever its size. Where its smallest text would be under ``min_font_pt`` on
1056
+ a page of ``figure_width_mm`` by ``figure_height_mm``, the result's status is ``"unreadable"``
1057
+ and its warnings say how wide the figure is at the least. A figure with no pair, stack or
1058
+ hydrogen bond between the two strands is ``"empty"``.
1059
+
1060
+ ``interactive``: the figure answers the pointer (:mod:`bindview.interactive`): pointing at a
1061
+ nucleotide, or at the ligand, keeps it, its pairs, stacks and contacts and the nucleotides at their
1062
+ other ends, and steps the rest back; a click keeps that. ``RenderResult.graph`` is the figure as
1063
+ nodes (a ``residue`` for each nucleotide, a ``ligand_group`` for the ligand) and contacts (each pair,
1064
+ stack, other hydrogen bond and contact of the ligand); ``graph``: such a graph, its nodes moved,
1065
+ to draw from instead of the layout."""
1066
+ css_vars = isinstance(theme, str) and theme.lower() == "auto"
1067
+ light, dark = scheme(colors)
1068
+ palette = light if css_vars else get_palette(theme, colors)
1069
+ palette = _with_strands(palette)
1070
+ dark_p = _with_strands(dark) if css_vars else None
1071
+ m = metrics or Metrics()
1072
+ laid = self._layout()
1073
+ fixed = None
1074
+ if graph is not None:
1075
+ laid, fixed = self._from_graph(laid, graph, step)
1076
+ scene, quality, data, live, drawn = self._scene(laid, m, step, title, legend, caption, figure_width_mm,
1077
+ figure_height_mm, min_font_pt, fixed)
1078
+ notes = list(self.warnings)
1079
+ if not quality.readable:
1080
+ notes.append(f"at {figure_width_mm:.0f} × {figure_height_mm:.0f} mm its smallest text would be "
1081
+ f"under {min_font_pt:g} pt: the figure is {quality.required_width_mm:.0f} mm wide at the "
1082
+ f"least")
1083
+ status = "ok" if self.across or self.stacks or self.hbonds else "empty"
1084
+ if status == "empty":
1085
+ notes.append(f"no pair, stack or hydrogen bond between chains {self.chains[0]} and {self.chains[1]}")
1086
+ elif not quality.readable:
1087
+ status = "unreadable" # drawn all the same: there is no smaller figure of two strands
1088
+ hooks = hooks_of_links(*live) if interactive else None
1089
+ svg = to_svg(scene, palette, background=background, css_vars=css_vars, dark_palette=dark_p,
1090
+ interactive=hooks if hooks is not None else False)
1091
+ return RenderResult(status=status, svg=svg, figure="diagram", warnings=notes, quality=quality,
1092
+ style="basepairs", scene=scene,
1093
+ theme="auto" if css_vars else palette.name if isinstance(theme, Palette) else str(theme).lower(),
1094
+ data=data, notes=[self.source_line()], graph=drawn)
1095
+
1096
+ def _from_graph(self, laid: _Laid, graph: "Graph", step: float) -> "tuple[_Laid, np.ndarray | None]":
1097
+ """The layout as a graph of this figure has it: each nucleotide where its node is, and the ligand."""
1098
+ X = laid.X.copy()
1099
+ for i, nt in enumerate(self.strands[0] + self.strands[1]):
1100
+ node = graph.find(_node_id(nt.key))
1101
+ if node is None or node.x is None or node.y is None:
1102
+ raise BindviewError(f"the graph is not one of this figure: it has no place for {nt.name}")
1103
+ X[i] = (node.x / step, -node.y / step)
1104
+ fixed = None
1105
+ if self.ligand_key is not None:
1106
+ node = graph.find(f"ligand:{self.ligand_key}")
1107
+ if node is not None and node.x is not None and node.y is not None:
1108
+ fixed = np.array([node.x / step, -node.y / step])
1109
+ return _Laid(X, laid.side, laid.route, laid.shaping), fixed
1110
+
1111
+ def render_svg(self, path: "str | Path | None" = None, theme: "str | Palette" = "light",
1112
+ **options: Any) -> RenderResult:
1113
+ """Render and, when ``path`` is given, write the figure there."""
1114
+ result = self.render(theme=theme, **options)
1115
+ if path is not None and result.svg is not None:
1116
+ p = Path(path)
1117
+ try:
1118
+ p.write_text(result.svg, encoding="utf-8")
1119
+ except OSError as exc:
1120
+ raise RenderError(f"cannot write {p}: {exc}") from exc
1121
+ result.path = p
1122
+ return result
1123
+
1124
+ def _scene(self, laid: _Laid, m: Metrics, step: float, title: str | None, legend: bool, caption: bool,
1125
+ width_mm: float, height_mm: float, min_pt: float, fixed: "np.ndarray | None" = None
1126
+ ) -> "tuple[Scene, Quality, dict[str, Any], tuple[dict[str, list[Group]], list], Graph]":
1127
+ nts = self.strands[0] + self.strands[1]
1128
+ side = laid.side
1129
+ r_nt = step * 0.42
1130
+ letter_font, number_font = m.residue_font, m.distance_font
1131
+ pad = step * 1.6
1132
+ lo, hi = laid.X.min(0), laid.X.max(0)
1133
+ lig = self._ligand_box(laid, nts, step, r_nt, letter_font, fixed)
1134
+ if lig is not None:
1135
+ lo = np.minimum(lo, lig[0] - lig[1])
1136
+ hi = np.maximum(hi, lig[0] + lig[1])
1137
+ top = pad + (m.title_font * 1.8 if title else 0.0)
1138
+ ox, oy = pad - lo[0] * step, top + hi[1] * step
1139
+
1140
+ def at(i: int) -> np.ndarray:
1141
+ return np.array([ox + laid.X[i][0] * step, oy - laid.X[i][1] * step])
1142
+ pos = [at(i) for i in range(len(nts))]
1143
+ draw_w = (hi[0] - lo[0]) * step + 2 * pad
1144
+ draw_h = top + (hi[1] - lo[1]) * step + pad
1145
+ pale = {frozenset((self._index[p.key_a], self._index[p.key_b])) for p in self.pairs} - laid.shaping
1146
+ across_ids = {self._index[k] for p in self.across for k in (p.key_a, p.key_b)}
1147
+ items: list[Item] = []
1148
+ lines: list[tuple[np.ndarray, np.ndarray, str, tuple[int, int]]] = []
1149
+ parts: dict[str, list[Group]] = {}
1150
+ links: list[tuple[Group, tuple[str, ...]]] = []
1151
+ if title:
1152
+ items.append(Text.plain(pad, pad + m.title_font, title, m.title_font, "text", anchor="start", bold=True))
1153
+
1154
+ def segment(i: int, j: int) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
1155
+ d = _unit_vec(pos[j] - pos[i])
1156
+ return pos[i] + d * r_nt, pos[j] - d * r_nt, d
1157
+
1158
+ for s in (0, 1):
1159
+ ids = [i for i in range(len(nts)) if side[i] == s]
1160
+ items.append(Group("strand", [Polyline(tuple((float(pos[i][0]), float(pos[i][1])) for i in ids),
1161
+ Paint(stroke=f"strand_{s + 1}", width=2.2, opacity=0.55))],
1162
+ data={"chain": self.chains[s]}))
1163
+ for a, b, n in self.hbonds:
1164
+ i, j = self._index[a], self._index[b]
1165
+ u, v, _ = segment(i, j)
1166
+ hb = Group("hbond", [_line(u, v, Paint(stroke="hbond", width=1.2, dash=(1.5, 2.5)))],
1167
+ title=f"{nts[i].name} – {nts[j].name}: {n} hydrogen bond(s) with a sugar or phosphate atom")
1168
+ items.append(hb)
1169
+ links.append((hb, (f"n{i}", f"n{j}")))
1170
+ lines.append((pos[i], pos[j], "hbond", (i, j)))
1171
+ for st in self.stacks:
1172
+ i, j = self._index[st.key_a], self._index[st.key_b]
1173
+ u, v, _ = segment(i, j)
1174
+ sg = Group("stack", [_line(u, v, Paint(stroke="pi_stacking", width=1.8, dash=(0.1, 3.4), opacity=0.7))],
1175
+ title=f"{nts[i].name} on {nts[j].name}: stacked")
1176
+ items.append(sg)
1177
+ links.append((sg, (f"n{i}", f"n{j}")))
1178
+ lines.append((pos[i], pos[j], "stack", (i, j)))
1179
+ kinds: set[str] = {"strands"}
1180
+ rungs = []
1181
+ for p in sorted(self.pairs, key=lambda q: q.chain_a != q.chain_b): # within first, across on top
1182
+ i, j = self._index[p.key_a], self._index[p.key_b]
1183
+ is_across = p.chain_a != p.chain_b
1184
+ is_pale = frozenset((i, j)) in pale
1185
+ colour = "text" if is_across else "protein_bond"
1186
+ width = (1.3 if is_pale else 2.4) if is_across else (1.1 if is_pale else 1.6)
1187
+ u, v, d = segment(i, j)
1188
+ dash = (4.0, 3.0) if p.family is None else ()
1189
+ paint = Paint(stroke=colour, width=width, dash=dash)
1190
+ mid = (u + v) / 2
1191
+ arc = abs(i - j) == 1 and side[i] == side[j]
1192
+ if arc:
1193
+ # Neighbours of a strand: no room for a symbol between them. A small arc out of the strand,
1194
+ # away from what lies around them, with the symbols at its top.
1195
+ e = _rot(_unit_vec(pos[j] - pos[i]))
1196
+ centre = (pos[i] + pos[j]) / 2
1197
+ near = [q for q in pos if 0 < float(np.linalg.norm(q - centre)) < 2.5 * step]
1198
+ if near and float(np.dot(np.mean(near, axis=0) - centre, e)) > 0:
1199
+ e = -e
1200
+ a0, a1 = pos[i] + e * r_nt, pos[j] + e * r_nt
1201
+ top = centre + e * (r_nt + step * 0.75)
1202
+ ctrl = 2 * top - (a0 + a1) / 2
1203
+ curve = [(1 - s) ** 2 * a0 + 2 * (1 - s) * s * ctrl + s ** 2 * a1 for s in np.linspace(0, 1, 13)]
1204
+ first: Item = Polyline(tuple((float(q[0]), float(q[1])) for q in curve), paint)
1205
+ mid = top
1206
+ lines.extend((curve[q], curve[q + 1], "within", (i, j)) for q in range(len(curve) - 1))
1207
+ else:
1208
+ first = _line(u, v, paint)
1209
+ g = Group("pair", [first],
1210
+ data={"family": p.family or "none", "across": "yes" if is_across else "no"},
1211
+ title=f"{nts[i].name} – {nts[j].name}: {p.family or 'family not annotated'}",
1212
+ opacity=0.55 if is_pale else 1.0)
1213
+ canonical = p.family == "cWW" and {nts[i].letter, nts[j].letter} in ({"G", "C"}, {"A", "U"}, {"A", "T"})
1214
+ wobble = p.family == "cWW" and {nts[i].letter, nts[j].letter} == {"G", "U"}
1215
+ drawn_as = p.family if p.ordered or p.family is None else _family_name(p.family)
1216
+ g.extend(_symbols(drawn_as, canonical, wobble, mid, d, colour, step * 0.42))
1217
+ items.append(g)
1218
+ links.append((g, (f"n{i}", f"n{j}")))
1219
+ if is_pale:
1220
+ kinds.add("tertiary")
1221
+ elif is_across:
1222
+ kinds.add("across-none" if p.family is None else "across")
1223
+ else:
1224
+ kinds.add("within-none" if p.family is None else "within")
1225
+ if p.family is not None and not canonical:
1226
+ kinds.add("wobble" if wobble else f"{'sym' if p.ordered else 'symu'}:{_family_name(p.family)}")
1227
+ if not arc:
1228
+ lines.append((pos[i], pos[j], "across" if is_across else "within", (i, j)))
1229
+ if is_across:
1230
+ rungs.append((pos[i], pos[j], (i, j)))
1231
+ if self.stacks:
1232
+ kinds.add("stack")
1233
+ if self.hbonds:
1234
+ kinds.add("hbond")
1235
+ obstacles: list[tuple[float, float, float, float]] = []
1236
+ lig_at: np.ndarray | None = None
1237
+ if lig is not None:
1238
+ lig_at = np.array([ox + lig[0][0] * step, oy - lig[0][1] * step])
1239
+ half = lig[1] * step
1240
+ obstacles.append((float(lig_at[0] - half[0]), float(lig_at[1] - half[1]), float(lig_at[0] + half[0]),
1241
+ float(lig_at[1] + half[1])))
1242
+ items.extend(self._ligand_items(nts, pos, lig_at, half, r_nt, letter_font, m, kinds, lines, parts,
1243
+ links))
1244
+ for i, nt in enumerate(nts):
1245
+ s = int(side[i])
1246
+ fill = f"strand_{s + 1}_fill" if i in across_ids else "background"
1247
+ dash = (2.0, 1.5) if nt.modified else ()
1248
+ if nt.modified:
1249
+ kinds.add("modified")
1250
+ mark = Group("nucleotide", [
1251
+ Circle(float(pos[i][0]), float(pos[i][1]), r_nt, Paint(stroke=f"strand_{s + 1}", fill=fill, width=1.5,
1252
+ dash=dash)),
1253
+ Text.plain(float(pos[i][0]), float(pos[i][1]) + letter_font * 0.36, nt.letter, letter_font, "text",
1254
+ bold=True)],
1255
+ data={"chain": nt.chain, "number": f"{nt.number}{nt.icode}", "resname": nt.resname},
1256
+ title=nt.name)
1257
+ items.append(mark)
1258
+ parts[f"n{i}"] = [mark]
1259
+ labels, label_boxes = self._labels(nts, pos, side, across_ids, lines, r_nt, number_font, obstacles)
1260
+ items.extend(labels)
1261
+
1262
+ # the counts the figure is judged by
1263
+ def seg_point(p: np.ndarray, a: np.ndarray, b: np.ndarray) -> float:
1264
+ ab = b - a
1265
+ t = float(np.clip(np.dot(p - a, ab) / max(float(np.dot(ab, ab)), 1e-9), 0, 1))
1266
+ return float(np.linalg.norm(p - (a + t * ab)))
1267
+ crossings = sum(1 for x in range(len(rungs)) for y in range(x + 1, len(rungs))
1268
+ if not set(rungs[x][2]) & set(rungs[y][2]) and _cross(rungs[x][0], rungs[x][1], rungs[y][0],
1269
+ rungs[y][1]))
1270
+ over = sum(1 for a, b, kind, ends in lines if kind in ("across", "within")
1271
+ for k in range(len(pos)) if k not in ends and seg_point(pos[k], a, b) < r_nt * 0.95)
1272
+ marks_on_marks = sum(1 for x in range(len(pos)) for y in range(x + 1, len(pos))
1273
+ if float(np.linalg.norm(pos[x] - pos[y])) < 2 * r_nt * 0.9)
1274
+ names_on = sum(1 for x in range(len(label_boxes)) for y in range(x + 1, len(label_boxes))
1275
+ if _boxes_overlap(label_boxes[x], label_boxes[y]))
1276
+ names_on += sum(1 for bx in label_boxes for q in pos if _box_circle(bx, q, r_nt))
1277
+ backbone = [float(np.linalg.norm(pos[i + 1] - pos[i])) / step for i in range(len(pos) - 1)
1278
+ if side[i] == side[i + 1]]
1279
+
1280
+ # key and source under the drawing
1281
+ y = draw_h
1282
+ key_w = 0.0
1283
+ if legend:
1284
+ group, kh, kw = self._key(kinds, m, y, step)
1285
+ items.append(group)
1286
+ y += kh
1287
+ key_w = kw
1288
+ source = self.source_line()
1289
+ if caption:
1290
+ src = source if "hbond" in kinds or self.source is not None else source.replace(
1291
+ " Other hydrogen bonds across: bindview's plain distance table.", "")
1292
+ width_for_text = max(draw_w, key_w, 360.0) - 2 * 14
1293
+ for line in _wrap(src, m.caption_font, width_for_text):
1294
+ y += m.caption_font * 1.35
1295
+ items.append(Text.plain(14, y, line, m.caption_font, "text_muted", anchor="start"))
1296
+ y += m.caption_font * 0.9
1297
+ width = max(draw_w, key_w + 28, 360.0 if caption else 0.0)
1298
+ height = y + 10
1299
+ scene = Scene(width, height, [Group("basepairs", items, data={"chains": " ".join(self.chains)})],
1300
+ title=title or f"Base pairs of chains {self.chains[0]} and {self.chains[1]}",
1301
+ description=source)
1302
+ smallest = min(number_font, letter_font, m.legend_font if legend else 99.0, m.caption_font if caption else 99.0)
1303
+ px_per_mm = 96 / 25.4
1304
+ fit = min(1.0, width_mm * px_per_mm / width, height_mm * px_per_mm / height)
1305
+ min_font = smallest * 0.75
1306
+ q = Quality(width=width, height=height, bond_length=step, n_residues=len(nts),
1307
+ n_interactions=len(self.across) + len(self.stacks) + len(self.hbonds), overlaps=marks_on_marks,
1308
+ unplaced=0, line_crossings=crossings, bond_crossings=0,
1309
+ max_stretch=max(backbone, default=1.0), min_font_pt=min_font,
1310
+ required_width_mm=width / px_per_mm * (min_pt / min_font),
1311
+ readable=min_font * fit >= min_pt - 1e-9, link_hits=over)
1312
+ data = {"layout": laid.route, "pairs_across": len(self.across), "pairs_within": len(self.within),
1313
+ "stacks": len(self.stacks), "hbonds": len(self.hbonds), "pale": len(pale),
1314
+ "names_on_names_or_marks": names_on,
1315
+ "kinds": sorted(kinds), "families": sorted({p.family or "none" for p in self.pairs})}
1316
+ if lig_at is not None:
1317
+ counts: dict[str, int] = {}
1318
+ for recs in self.ligand_contacts.values():
1319
+ for kind in dict.fromkeys(str(r.type) for r in recs):
1320
+ counts[kind] = counts.get(kind, 0) + 1
1321
+ data["ligand"] = {"residue": str(self.ligand_key), "name": self.ligand_name,
1322
+ "nucleotides": len(self.ligand_contacts), "lines": counts,
1323
+ "lines_over_marks": sum(1 for a, b, kind, ends in lines if kind == "ligand"
1324
+ for k in range(len(pos)) if k not in ends
1325
+ and seg_point(pos[k], a, b) < r_nt * 0.95),
1326
+ "at": [round(float(lig_at[0]), 2), round(float(lig_at[1]), 2)]}
1327
+ drawn = self._graph(nts, pos, lig_at, pale, step, scene, data)
1328
+ return scene, q, data, (parts, links), drawn
1329
+
1330
+ def _graph(self, nts: list[_Nt], pos: list[np.ndarray], lig_at: "np.ndarray | None", pale: set[frozenset],
1331
+ step: float, scene: Scene, data: dict[str, Any]) -> "Graph":
1332
+ """The figure as nodes and contacts (:mod:`bindview.graph`), in the page's frame."""
1333
+ from .graph import Contact, Graph, Node
1334
+
1335
+ across = {self._index[k] for p in self.across for k in (p.key_a, p.key_b)}
1336
+ found: dict[str, list[str]] = {}
1337
+ contacts: list[Contact] = []
1338
+
1339
+ def add(c: Contact) -> None:
1340
+ contacts.append(c)
1341
+ found.setdefault(c.residue, []).append(c.id)
1342
+ if c.ligand is not None:
1343
+ found.setdefault(c.ligand, []).append(c.id)
1344
+
1345
+ for n, p in enumerate(self.pairs):
1346
+ i, j = self._index[p.key_a], self._index[p.key_b]
1347
+ add(Contact(id=f"pair:{n}", type="base_pair", residue=_node_id(p.key_a), ligand=_node_id(p.key_b),
1348
+ label=p.family, attrs={"family": p.family, "ordered": p.ordered,
1349
+ "across": p.chain_a != p.chain_b, "source": p.source,
1350
+ "pale": frozenset((i, j)) in pale}))
1351
+ for n, st in enumerate(self.stacks):
1352
+ add(Contact(id=f"stack:{n}", type="base_stack", residue=_node_id(st.key_a), ligand=_node_id(st.key_b),
1353
+ attrs={"source": st.source}))
1354
+ for n, (a, b, count) in enumerate(self.hbonds):
1355
+ add(Contact(id=f"hbond:{n}", type="hbond", residue=_node_id(a), ligand=_node_id(b),
1356
+ attrs={"bonds": count, "with": "a sugar or phosphate atom"}))
1357
+ lig_id = f"ligand:{self.ligand_key}"
1358
+ if lig_at is not None:
1359
+ for key, recs in self.ligand_contacts.items():
1360
+ for n, r in enumerate(recs):
1361
+ add(Contact(id=f"{lig_id}:{_node_id(key)}:{n}", type=str(r.type), residue=_node_id(key),
1362
+ ligand=lig_id, distance=None if r.distance is None else float(r.distance),
1363
+ protein_atoms=tuple(a for a in (r.protein_atom,) if a),
1364
+ attrs={"ligand_atom": r.ligand_atom} if r.ligand_atom else {}))
1365
+ nodes = [Node(id=_node_id(nt.key), kind="residue", label=f"{nt.letter}{nt.number}{nt.icode}",
1366
+ x=float(pos[i][0]), y=float(pos[i][1]), contacts=tuple(found.get(_node_id(nt.key), ())),
1367
+ attrs={"chain": nt.chain, "number": f"{nt.number}{nt.icode}", "resname": nt.resname,
1368
+ "letter": nt.letter, "modified": nt.modified, "strand": int(nt.chain == self.chains[1]) + 1,
1369
+ "paired_across": i in across})
1370
+ for i, nt in enumerate(nts)]
1371
+ if lig_at is not None:
1372
+ nodes.append(Node(id=lig_id, kind="ligand_group", label=self.ligand_name or "", x=float(lig_at[0]),
1373
+ y=float(lig_at[1]), contacts=tuple(found.get(lig_id, ())),
1374
+ attrs={"residue": str(self.ligand_key), "contacts_from": self.ligand_source}))
1375
+ meta = {"basepairs": {"chains": list(self.chains), "layout": data["layout"], "source": self.source_line(),
1376
+ "pairs_across": data["pairs_across"], "pairs_within": data["pairs_within"],
1377
+ "stacks": data["stacks"], "hbonds": data["hbonds"]}}
1378
+ return Graph(view="basepairs", bond_length=step, nodes=nodes, contacts=contacts,
1379
+ size=(scene.width, scene.height), meta=meta).validate()
1380
+
1381
+ # -- the ligand beside the pairs ------------------------------------------------------------------
1382
+ def _ligand_box(self, laid: _Laid, nts: list[_Nt], step: float, r_nt: float, font: float,
1383
+ fixed: "np.ndarray | None" = None) -> "tuple[np.ndarray, np.ndarray] | None":
1384
+ """Where the ligand's box goes and its half size, in steps; ``None`` without a ligand to draw.
1385
+
1386
+ Near the nucleotides it touches and on none of them, its lines crossing as few lines of the figure
1387
+ and passing over as few nucleotides as there is room for: the first best of rings of places around
1388
+ the middle of those nucleotides, a quarter step apart, so that the same input gives the same place.
1389
+ """
1390
+ if not self.ligand_contacts:
1391
+ return None
1392
+ from .textmetrics import text_width
1393
+
1394
+ X = laid.X
1395
+ half = np.array([(text_width(self.ligand_name or "", font, bold=True) + font * 1.4) / 2,
1396
+ font * 0.95]) / step
1397
+ if fixed is not None:
1398
+ return fixed, half
1399
+ targets = [self._index[k] for k in self.ligand_contacts]
1400
+ segs = [(self._index[p.key_a], self._index[p.key_b]) for p in self.pairs]
1401
+ segs += [(self._index[st.key_a], self._index[st.key_b]) for st in self.stacks]
1402
+ segs += [(self._index[a], self._index[b]) for a, b, _ in self.hbonds]
1403
+ segs += [(i, i + 1) for i in range(len(nts) - 1) if laid.side[i] == laid.side[i + 1]]
1404
+ r = r_nt / step
1405
+ centre = X[targets].mean(0)
1406
+ best: tuple[float, np.ndarray] | None = None
1407
+ for ring in range(0, 25):
1408
+ n = 1 if ring == 0 else 8 * ring
1409
+ for k in range(n):
1410
+ ang = 2 * math.pi * k / n
1411
+ c = centre + ring * 0.25 * np.array([math.cos(ang), math.sin(ang)])
1412
+ gap = np.maximum(np.abs(X - c) - half, 0.0)
1413
+ if (np.hypot(gap[:, 0], gap[:, 1]) < r + 0.2).any():
1414
+ continue # on a nucleotide, or too close to one
1415
+ score = 0.0
1416
+ for t in targets:
1417
+ score += float(np.linalg.norm(X[t] - c))
1418
+ score += 2.0 * sum(1 for a, b in segs if t not in (a, b) and _cross(c, X[t], X[a], X[b]))
1419
+ ab = X[t] - c
1420
+ tt = np.clip(((X - c) @ ab) / max(float(ab @ ab), 1e-9), 0, 1)
1421
+ d = np.linalg.norm(X - (c + tt[:, None] * ab), axis=1)
1422
+ score += 2.0 * sum(1 for q in range(len(X)) if q != t and d[q] < r)
1423
+ if best is None or score < best[0] - 1e-9:
1424
+ best = (score, c)
1425
+ if best is None:
1426
+ best = (0.0, np.array([centre[0], X[:, 1].max() + 2.0]))
1427
+ return best[1], half
1428
+
1429
+ def _ligand_items(self, nts: list[_Nt], pos: list[np.ndarray], at: np.ndarray, half: np.ndarray, r_nt: float,
1430
+ font: float, m: Metrics, kinds: set[str],
1431
+ lines: list[tuple[np.ndarray, np.ndarray, str, tuple[int, int]]],
1432
+ parts: dict[str, list[Group]], links: list[tuple[Group, tuple[str, ...]]]) -> list[Item]:
1433
+ """The ligand's box and its lines: one for each kind of contact to each nucleotide, side by side, in
1434
+ the line style of that kind in the library's other figures; the records of each in its title."""
1435
+ from .interactions import InteractionType as T
1436
+ from .styles.base import LINK_STYLES
1437
+
1438
+ order = [T.SALTBRIDGE, T.HBOND, T.PI_CATION, T.PI_STACKING, T.METAL, T.HALOGEN, T.WATER_BRIDGE,
1439
+ T.HYDROPHOBIC, T.COVALENT]
1440
+ out: list[Item] = []
1441
+ for key, recs in self.ligand_contacts.items():
1442
+ i = self._index[key]
1443
+ d = _unit_vec(pos[i] - at)
1444
+ # where the line leaves the box
1445
+ tx = half[0] / abs(d[0]) if abs(d[0]) > 1e-9 else math.inf
1446
+ ty = half[1] / abs(d[1]) if abs(d[1]) > 1e-9 else math.inf
1447
+ start, end = at + d * (min(tx, ty) + 2.0), pos[i] - d * r_nt
1448
+ present = [k for k in order if any(r.type is k for r in recs)]
1449
+ e = _rot(d)
1450
+ strokes: list[Item] = []
1451
+ words = []
1452
+ for n, kind in enumerate(present):
1453
+ style = LINK_STYLES[kind]
1454
+ off = e * (n - (len(present) - 1) / 2) * 3.4
1455
+ strokes.append(_line(start + off, end + off, Paint(stroke=style.token, width=m.interaction_width
1456
+ * style.width, dash=style.dash, cap=style.cap)))
1457
+ kinds.add(f"lig:{kind.value}")
1458
+ dists = sorted(float(r.distance) for r in recs if r.type is kind and r.distance is not None)
1459
+ words.append(kind.label.lower() + (f" ({', '.join(f'{x:.2f}' for x in dists)} Å)" if dists else ""))
1460
+ lines.append((at, pos[i], "ligand", (i, i)))
1461
+ line = Group("ligand-contact", strokes, data={"chain": key[0], "number": f"{key[1]}{key[2]}",
1462
+ "kinds": " ".join(k.value for k in present)},
1463
+ title=f"{self.ligand_name} – {nts[i].name}: {'; '.join(words)}")
1464
+ out.append(line)
1465
+ links.append((line, (f"n{i}", "g0")))
1466
+ kinds.add("ligand")
1467
+ w, h = 2 * half
1468
+ box = Group("ligand", [
1469
+ Rect(float(at[0] - half[0]), float(at[1] - half[1]), float(w), float(h),
1470
+ Paint(stroke="ligand_bond", fill="background", width=1.6), rx=float(h / 2)),
1471
+ Text.plain(float(at[0]), float(at[1] + font * 0.36), self.ligand_name or "", font, "text", bold=True)],
1472
+ data={"residue": str(self.ligand_key)},
1473
+ title=f"{self.ligand_name} ({self.ligand_key}): touches {len(self.ligand_contacts)} nucleotide(s)")
1474
+ out.append(box)
1475
+ parts["g0"] = [box]
1476
+ return out
1477
+
1478
+ def _labels(self, nts: list[_Nt], pos: list[np.ndarray], side: np.ndarray, across_ids: set[int],
1479
+ lines: list[tuple[np.ndarray, np.ndarray, str, tuple[int, int]]], r_nt: float, font: float,
1480
+ obstacles: Sequence[tuple[float, float, float, float]] = ()
1481
+ ) -> tuple[list[Item], list[tuple[float, float, float, float]]]:
1482
+ """The ends (5', 3') and the numbers: every fifth, the ends of a strand, the ends of each stretch that
1483
+ pairs across; each where it covers no mark, no number and as few lines as there is room for."""
1484
+ items: list[Item] = []
1485
+ boxes: list[tuple[float, float, float, float]] = []
1486
+ X = np.array(pos)
1487
+ normals = np.zeros_like(X)
1488
+ for i in range(len(X)):
1489
+ d = np.linalg.norm(X - X[i], axis=1)
1490
+ near = (d < 2.6 * r_nt / 0.42) & (d > 0)
1491
+ normals[i] = _unit_vec(X[i] - X[near].mean(0)) if near.any() else np.array([0.0, -1.0])
1492
+ for s in (0, 1):
1493
+ ids = [i for i in range(len(nts)) if side[i] == s]
1494
+ for end, other, word in ((ids[0], ids[1] if len(ids) > 1 else None, "5′"),
1495
+ (ids[-1], ids[-2] if len(ids) > 1 else None, "3′")):
1496
+ away = _unit_vec(X[end] - X[other]) if other is not None else np.array([1.0, 0.0])
1497
+ c = X[end] + away * (r_nt + font * 0.9)
1498
+ t = Text.plain(float(c[0]), float(c[1] + font * 0.35), word, font, f"strand_{s + 1}", bold=True)
1499
+ items.append(t)
1500
+ boxes.append(text_box(t))
1501
+ run_ends = set()
1502
+ for s in (0, 1):
1503
+ ids = [i for i in range(len(nts)) if side[i] == s]
1504
+ for a, b in zip([-1] + ids[:-1], ids):
1505
+ if b in across_ids and a not in across_ids:
1506
+ run_ends.add(b)
1507
+ for a, b in zip(ids, ids[1:] + [-1]):
1508
+ if a in across_ids and b not in across_ids:
1509
+ run_ends.add(a)
1510
+
1511
+ def badness(box: tuple[float, float, float, float]) -> float:
1512
+ bad = 0.0
1513
+ centre = np.array([(box[0] + box[2]) / 2, (box[1] + box[3]) / 2])
1514
+ half = max(box[2] - box[0], box[3] - box[1]) / 2
1515
+ for q in X:
1516
+ if _box_circle(box, q, r_nt + 1.5):
1517
+ bad += 100
1518
+ for bx in boxes:
1519
+ if _boxes_overlap(bx, box):
1520
+ bad += 100
1521
+ for bx in obstacles:
1522
+ if _boxes_overlap(bx, box):
1523
+ bad += 100
1524
+ for a, b, _, _ in lines:
1525
+ ab = b - a
1526
+ t = float(np.clip(np.dot(centre - a, ab) / max(float(np.dot(ab, ab)), 1e-9), 0, 1))
1527
+ if float(np.linalg.norm(centre - (a + t * ab))) < half * 0.8:
1528
+ bad += 15
1529
+ return bad
1530
+
1531
+ for i, nt in enumerate(nts):
1532
+ ids = [k for k in range(len(nts)) if side[k] == side[i]]
1533
+ if not (nt.number % 5 == 0 or i == ids[0] or i == ids[-1] or i in run_ends):
1534
+ continue
1535
+ word = f"{nt.number}{nt.icode}"
1536
+ probe = Text.plain(0.0, 0.0, word, font, "text_muted")
1537
+ b0 = text_box(probe)
1538
+ w, h = b0[2] - b0[0], b0[3] - b0[1]
1539
+ best: tuple[float, np.ndarray] | None = None
1540
+ for extra in (0.0, 0.35, 0.8, 1.3):
1541
+ for k in range(24):
1542
+ ang = 2 * math.pi * k / 24
1543
+ d = np.array([math.cos(ang), math.sin(ang)])
1544
+ c = X[i] + d * (r_nt + 2 + extra * r_nt / 0.42 + abs(d[0]) * w / 2 + abs(d[1]) * h / 2)
1545
+ box = (c[0] - w / 2, c[1] - h / 2, c[0] + w / 2, c[1] + h / 2)
1546
+ score = badness(box) - 3 * float(np.dot(d, normals[i])) + 4 * extra
1547
+ if best is None or score < best[0]:
1548
+ best = (score, c)
1549
+ if best is not None and best[0] < 0:
1550
+ break
1551
+ assert best is not None
1552
+ c = best[1]
1553
+ t = Text.plain(float(c[0]), float(c[1] + h / 2 - (b0[3])), word, font, "text_muted")
1554
+ items.append(t)
1555
+ boxes.append(text_box(t))
1556
+ return items, boxes
1557
+
1558
+ def _key(self, kinds: set[str], m: Metrics, y0: float, step: float = 24.0) -> tuple[Group, float, float]:
1559
+ """The key under the drawing: a row for each kind of mark the figure has, its sample and its words.
1560
+ The symbol of a family is drawn at the size it has on a pair (``step``), and where that is more
1561
+ than a row and a sample hold at their usual size, the rows stand further apart and the samples
1562
+ are wider."""
1563
+ font = m.legend_font
1564
+ size = step * 0.42
1565
+ rows: list[str] = [k for k in ("strands", "across", "across-none", "within", "within-none", "tertiary",
1566
+ "wobble") if k in kinds]
1567
+ rows += sorted((k for k in kinds if k.startswith(("sym:", "symu:"))), key=lambda k: (k.split(":")[1], k))
1568
+ rows += [k for k in ("stack", "hbond", "modified") if k in kinds]
1569
+ rows += [k for k in ("ligand",) if k in kinds]
1570
+ rows += [f"lig:{t}" for t in ("saltbridge", "hbond", "pi_cation", "pi_stacking", "metal", "halogen",
1571
+ "water_bridge", "hydrophobic") if f"lig:{t}" in kinds]
1572
+ items: list[Item] = []
1573
+ y = y0 + font * 1.2
1574
+ x0, sample = 14.0, max(48.0, 2.4 * size)
1575
+ widest = 0.0
1576
+ for k in rows:
1577
+ mid = y - font * 0.35
1578
+ if k == "strands":
1579
+ items += [Circle(x0 + 10, mid, 8, Paint(stroke="strand_1", fill="strand_1_fill", width=1.5)),
1580
+ Circle(x0 + 34, mid, 8, Paint(stroke="strand_2", fill="strand_2_fill", width=1.5))]
1581
+ elif k in ("across", "across-none"):
1582
+ items.append(Line(x0, mid, x0 + sample, mid, Paint(stroke="text", width=2.4,
1583
+ dash=(4.0, 3.0) if k == "across-none" else ())))
1584
+ elif k in ("within", "within-none"):
1585
+ items.append(Line(x0, mid, x0 + sample, mid, Paint(stroke="protein_bond", width=1.6,
1586
+ dash=(4.0, 3.0) if k == "within-none" else ())))
1587
+ elif k == "tertiary":
1588
+ items.append(Line(x0, mid, x0 + sample, mid, Paint(stroke="text", width=1.3, opacity=0.55)))
1589
+ elif k == "wobble" or k.startswith(("sym:", "symu:")):
1590
+ items.append(Line(x0, mid, x0 + sample, mid, Paint(stroke="text", width=1.6)))
1591
+ fam = "cWW" if k == "wobble" else k.split(":")[1]
1592
+ items += _symbols(fam, False, k == "wobble", np.array([x0 + sample / 2, mid]), np.array([1.0, 0.0]),
1593
+ "text", size)
1594
+ elif k == "stack":
1595
+ items.append(Line(x0, mid, x0 + sample, mid, Paint(stroke="pi_stacking", width=1.8, dash=(0.1, 3.4),
1596
+ opacity=0.7)))
1597
+ elif k == "hbond":
1598
+ items.append(Line(x0, mid, x0 + sample, mid, Paint(stroke="hbond", width=1.2, dash=(1.5, 2.5))))
1599
+ elif k == "modified":
1600
+ items.append(Circle(x0 + sample / 2, mid, 8, Paint(stroke="text_muted", fill="background", width=1.5,
1601
+ dash=(2.0, 1.5))))
1602
+ elif k == "ligand":
1603
+ items.append(Rect(x0 + 4, mid - 8, sample - 8, 16, Paint(stroke="ligand_bond", fill="background",
1604
+ width=1.6), rx=8))
1605
+ elif k.startswith("lig:"):
1606
+ from .interactions import InteractionType
1607
+ from .styles.base import LINK_STYLES
1608
+
1609
+ style = LINK_STYLES[InteractionType(k[4:])]
1610
+ items.append(Line(x0, mid, x0 + sample, mid, Paint(stroke=style.token, width=m.interaction_width
1611
+ * style.width, dash=style.dash, cap=style.cap)))
1612
+ if k.startswith(("sym:", "symu:")):
1613
+ f = k.split(":")[1]
1614
+ text = (f"{f}: {'cis' if f[0] == 'c' else 'trans'}, {_EDGE[f[1]]} edge with {_EDGE[f[2]]} edge"
1615
+ + (" (not G–C, A–U or G·U)" if f == "cWW" else ""))
1616
+ if f[1] != f[2]:
1617
+ text += ("; each symbol at its own base" if k.startswith("sym:")
1618
+ else "; which base uses which edge, the source does not say")
1619
+ elif k == "ligand":
1620
+ text = (f"the ligand, {self.ligand_name}: a line for each kind of contact with a nucleotide "
1621
+ f"({self.ligand_source})")
1622
+ elif k.startswith("lig:"):
1623
+ from .interactions import InteractionType
1624
+
1625
+ text = f"{InteractionType(k[4:]).label.lower()} with the ligand"
1626
+ else:
1627
+ text = _KEY[k].format(a=self.chains[0], b=self.chains[1])
1628
+ t = Text.plain(x0 + sample + 14, y, text, font, "text", anchor="start")
1629
+ items.append(t)
1630
+ widest = max(widest, text_box(t)[2])
1631
+ y += max(font * 2.0, size + 4.0)
1632
+ return Group("key", items), y - y0, widest
1633
+
1634
+
1635
+ def _node_id(key: tuple[str, int, str]) -> str:
1636
+ """A nucleotide's id in the graph: ``A:8``, ``B:12A``."""
1637
+ return f"{key[0]}:{key[1]}{key[2]}"
1638
+
1639
+
1640
+ def _with_strands(p: Palette) -> Palette:
1641
+ """A palette with the strand colours: its own where it has them, else those of the light or the dark
1642
+ palette, by how dark its background is."""
1643
+ if all(k in p.extra for k in _STRAND_LIGHT):
1644
+ return p
1645
+ bg = p.background.lstrip("#")
1646
+ dark = len(bg) == 6 and sum(int(bg[i:i + 2], 16) for i in (0, 2, 4)) < 3 * 128
1647
+ return p.with_(extra={**(_STRAND_DARK if dark else _STRAND_LIGHT), **p.extra})
1648
+
1649
+
1650
+ def _symbols(family: str | None, canonical: bool, wobble: bool, m: np.ndarray, d: np.ndarray, colour: str,
1651
+ size: float) -> list[Item]:
1652
+ """The Leontis–Westhof symbol of a pair at ``m`` on its line (direction ``d``, from base a to base b):
1653
+ none for a canonical cis Watson–Crick pair or one without a family, a small dot for G·U, else the symbol
1654
+ of each base's edge (circle Watson–Crick, square Hoogsteen, triangle sugar edge), filled for cis, open
1655
+ for trans, one where both edges are the same."""
1656
+ if family is None or canonical:
1657
+ return []
1658
+ if wobble:
1659
+ return [Circle(float(m[0]), float(m[1]), 3.0, Paint(fill=colour))]
1660
+ cis, e1, e2 = family[0] == "c", family[1], family[2]
1661
+ fill = colour if cis else "background"
1662
+ if e1 == e2:
1663
+ return [_edge(e1, m, d, size, colour, fill)]
1664
+ return [_edge(e1, m - d * size * 0.55, d, size, colour, fill), _edge(e2, m + d * size * 0.55, d, size, colour, fill)]
1665
+
1666
+
1667
+ def _edge(edge: str, c: np.ndarray, d: np.ndarray, s: float, colour: str, fill: str) -> Item:
1668
+ paint = Paint(stroke=colour, fill=fill, width=1.3, join="miter", cap="butt")
1669
+ if edge == "W":
1670
+ return Circle(float(c[0]), float(c[1]), s * 0.5, paint)
1671
+ e = np.array([-d[1], d[0]])
1672
+ if edge == "H":
1673
+ h = s * 0.45
1674
+ pts = [c + h * (a * d + b * e) for a, b in ((-1, -1), (1, -1), (1, 1), (-1, 1))]
1675
+ else:
1676
+ pts = [c + s * 0.55 * v for v in (d, -0.5 * d + 0.87 * e, -0.5 * d - 0.87 * e)]
1677
+ return Polygon(tuple((float(p[0]), float(p[1])) for p in pts), paint)
1678
+
1679
+
1680
+ def _line(u: np.ndarray, v: np.ndarray, paint: Paint) -> Line:
1681
+ return Line(float(u[0]), float(u[1]), float(v[0]), float(v[1]), paint)
1682
+
1683
+
1684
+ def _cross(a: np.ndarray, b: np.ndarray, c: np.ndarray, d: np.ndarray) -> bool:
1685
+ def orient(p: np.ndarray, q: np.ndarray, r: np.ndarray) -> float:
1686
+ return float((q[0] - p[0]) * (r[1] - p[1]) - (q[1] - p[1]) * (r[0] - p[0]))
1687
+ return orient(a, b, c) * orient(a, b, d) < 0 and orient(c, d, a) * orient(c, d, b) < 0
1688
+
1689
+
1690
+ def _boxes_overlap(a: tuple[float, float, float, float], b: tuple[float, float, float, float]) -> bool:
1691
+ return a[0] < b[2] and b[0] < a[2] and a[1] < b[3] and b[1] < a[3]
1692
+
1693
+
1694
+ def _box_circle(bx: tuple[float, float, float, float], c: np.ndarray, r: float) -> bool:
1695
+ x = min(max(float(c[0]), bx[0]), bx[2])
1696
+ y = min(max(float(c[1]), bx[1]), bx[3])
1697
+ return math.hypot(float(c[0]) - x, float(c[1]) - y) < r
1698
+
1699
+
1700
+ def _wrap(text: str, size: float, width: float) -> list[str]:
1701
+ from .textmetrics import text_width
1702
+
1703
+ out, line = [], ""
1704
+ for word in text.split():
1705
+ trial = f"{line} {word}".strip()
1706
+ if line and text_width(trial, size) > width:
1707
+ out.append(line)
1708
+ line = word
1709
+ else:
1710
+ line = trial
1711
+ return out + ([line] if line else [])