bindview 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. bindview/__init__.py +88 -0
  2. bindview/__main__.py +6 -0
  3. bindview/align.py +493 -0
  4. bindview/arrange.js +347 -0
  5. bindview/arrange.py +248 -0
  6. bindview/backends.py +290 -0
  7. bindview/basepairs.py +1711 -0
  8. bindview/chains.py +264 -0
  9. bindview/chem.py +57 -0
  10. bindview/clearance.py +123 -0
  11. bindview/cli.py +990 -0
  12. bindview/compare.py +1854 -0
  13. bindview/confidence.py +531 -0
  14. bindview/consensus.py +303 -0
  15. bindview/covalent.py +220 -0
  16. bindview/depict.py +790 -0
  17. bindview/detect.py +378 -0
  18. bindview/diagram.py +1891 -0
  19. bindview/distance_table.py +589 -0
  20. bindview/ensemble.py +787 -0
  21. bindview/errors.py +47 -0
  22. bindview/exposure.py +207 -0
  23. bindview/features.py +179 -0
  24. bindview/fingerprint.py +469 -0
  25. bindview/fragments.py +304 -0
  26. bindview/geometry.py +482 -0
  27. bindview/graph.py +611 -0
  28. bindview/graphbuild.py +431 -0
  29. bindview/interactions.py +418 -0
  30. bindview/interactive.py +334 -0
  31. bindview/interface.py +1329 -0
  32. bindview/ions.py +155 -0
  33. bindview/layout/__init__.py +15 -0
  34. bindview/layout/body.py +421 -0
  35. bindview/layout/engine.py +1084 -0
  36. bindview/layout/field.py +261 -0
  37. bindview/ligand.py +583 -0
  38. bindview/near.py +67 -0
  39. bindview/options.py +92 -0
  40. bindview/pae.py +991 -0
  41. bindview/peptide.py +610 -0
  42. bindview/plane.py +320 -0
  43. bindview/polymer.py +678 -0
  44. bindview/py.typed +0 -0
  45. bindview/report.py +1407 -0
  46. bindview/residues.py +296 -0
  47. bindview/resolve.py +493 -0
  48. bindview/scene.py +239 -0
  49. bindview/solvent.py +254 -0
  50. bindview/structure.py +1145 -0
  51. bindview/styles/__init__.py +2 -0
  52. bindview/styles/absence.py +180 -0
  53. bindview/styles/base.py +2128 -0
  54. bindview/styles/closeup.py +146 -0
  55. bindview/styles/detailed.py +690 -0
  56. bindview/styles/ligand_draw.py +289 -0
  57. bindview/styles/mixed.py +70 -0
  58. bindview/styles/polymer_draw.py +354 -0
  59. bindview/styles/rings.py +75 -0
  60. bindview/styles/schematic.py +311 -0
  61. bindview/styles/summary.py +147 -0
  62. bindview/svg.py +310 -0
  63. bindview/textmetrics.py +64 -0
  64. bindview/theme.py +317 -0
  65. bindview-0.1.0.dist-info/METADATA +270 -0
  66. bindview-0.1.0.dist-info/RECORD +70 -0
  67. bindview-0.1.0.dist-info/WHEEL +4 -0
  68. bindview-0.1.0.dist-info/entry_points.txt +2 -0
  69. bindview-0.1.0.dist-info/licenses/LICENSE +21 -0
  70. bindview-0.1.0.dist-info/licenses/NOTICE +48 -0
@@ -0,0 +1,354 @@
1
+ """Drawing a chain ligand: its residues as boxes on a backbone, the rest of it as atoms.
2
+
3
+ The counterpart of :mod:`bindview.styles.ligand_draw` for a depiction that has
4
+ ``units``. A residue is a rounded box with its three-letter code and, smaller
5
+ and paler, its position in the chain. The position is a count from the
6
+ ligand's own N-terminus and is set apart from the code on purpose: a protein
7
+ residue in the same figure reads ``Arg190``, and a chain residue must not look
8
+ as if it carried a number of that kind.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from dataclasses import replace
14
+ from typing import Mapping, Sequence
15
+
16
+ from ..confidence import PLAIN, Look, look_of
17
+ from ..depict import DepBond, Depiction, DepUnit
18
+ from ..geometry import Point, segment_box_entry
19
+ from ..polymer import BRACKET_OUT, BRACKET_STEP, INDEX_FONT, UNIT_FONT
20
+ from ..scene import Group, Line, Paint, Polyline, Rect, Span, Text
21
+ from ..textmetrics import CAP_HEIGHT
22
+ from ..theme import Metrics, Palette
23
+ from .ligand_draw import _atom_group, bond_items
24
+
25
+ __all__ = ["draw_polymer", "unit_looks", "bracket_points", "terminus_marks"]
26
+
27
+ _CORNER = 5.0
28
+ #: Outline of a box by confidence level: (dash, opacity), as for the residue bubbles.
29
+ _OUTLINE: dict[int, tuple[tuple[float, ...], float]] = {0: ((), 1.0), 1: ((3.6, 2.2), 0.85), 2: ((1.1, 2.3), 0.7)}
30
+ _TERMINUS_FONT = 8.5
31
+
32
+
33
+ def unit_looks(dep: Depiction, plddt: "dict[str, float] | None", by_colour: bool = False) -> list[Look]:
34
+ """The confidence look of every residue of the chain: that of the mean pLDDT of its atoms.
35
+ ``by_colour``: as in :func:`bindview.confidence.look_of`."""
36
+ looks = []
37
+ for unit in dep.units:
38
+ names = [dep.atoms[a].name for a in unit.atoms]
39
+ values = [plddt[n] for n in names if plddt and n is not None and n in plddt]
40
+ looks.append(look_of(sum(values) / len(values), by_colour) if values else PLAIN)
41
+ return looks
42
+
43
+
44
+ def bracket_points(dep: Depiction, bond: DepBond, lane: int) -> tuple[Point, ...]:
45
+ """The path of a link between two residues that are not neighbours: out to the left, along, and back."""
46
+ ua, ub = dep.unit_of(bond.a), dep.unit_of(bond.b)
47
+ assert ua is not None and ub is not None
48
+ x = min(ua.box[0], ub.box[0]) - BRACKET_OUT - lane * BRACKET_STEP
49
+ return ((ua.box[0], ua.y), (x, ua.y), (x, ub.y), (ub.box[0], ub.y))
50
+
51
+
52
+ def brackets(dep: Depiction) -> list[tuple[DepBond, tuple[Point, ...]]]:
53
+ """Every bracket of the depiction, each in a lane of its own where two would run along each other."""
54
+ out: list[tuple[DepBond, tuple[Point, ...]]] = []
55
+ spans: list[tuple[float, float, int]] = []
56
+ if dep.arranged == "plane":
57
+ return out # no column to stand beside: such a link is a straight line there
58
+ for bond in dep.bonds:
59
+ if bond.kind not in ("closure", "crosslink"):
60
+ continue
61
+ ua, ub = dep.unit_of(bond.a), dep.unit_of(bond.b)
62
+ if ua is None or ub is None:
63
+ continue
64
+ lo, hi = sorted((ua.y, ub.y))
65
+ lane = 0
66
+ while any(l == lane and not (hi < a or lo > b) for a, b, l in spans):
67
+ lane += 1
68
+ spans.append((lo, hi, lane))
69
+ out.append((bond, bracket_points(dep, bond, lane)))
70
+ return out
71
+
72
+
73
+ def terminus_marks(dep: Depiction) -> list[tuple[Point, str]]:
74
+ """Where "N" and "C" are printed: beyond the two ends of an open chain, unless something is attached there."""
75
+ if not dep.units or not dep.sequential or any(b.kind == "closure" for b in dep.bonds):
76
+ return []
77
+ if dep.arranged == "plane":
78
+ return [] # the first box is not the top of anything
79
+ first, last = dep.units[0], dep.units[-1]
80
+ used_top = used_bottom = False
81
+ for b in dep.bonds:
82
+ if b.kind != "covalent":
83
+ continue
84
+ for inside, outside in ((b.a, b.b), (b.b, b.a)):
85
+ unit = dep.unit_of(inside)
86
+ if unit is None or dep.unit_of(outside) is not None:
87
+ continue
88
+ y = dep.atoms[outside].y
89
+ used_top = used_top or (unit is first and y < first.box[1])
90
+ used_bottom = used_bottom or (unit is last and y > last.box[3])
91
+ cap = CAP_HEIGHT * _TERMINUS_FONT
92
+ marks = []
93
+ # A chain of nucleotides runs from its 5' end to its 3' end, as one of amino acids from N to C.
94
+ top, bottom = ("5\u2032", "3\u2032") if first.residue_class == "nucleotide" else ("N", "C")
95
+ if not used_top and not dep.open_ends[0]:
96
+ marks.append(((first.x, first.box[1] - 4.0), top))
97
+ if not used_bottom and not dep.open_ends[1]:
98
+ marks.append(((last.x, last.box[3] + 4.0 + cap), bottom))
99
+ return marks
100
+
101
+
102
+ def _unit_group(unit: DepUnit, look: Look, names: Sequence[str], deposited: bool = False,
103
+ called: str = "the ligand", beside: Sequence[str] = (), by_colour: bool = False) -> Group:
104
+ """One residue of the chain as its box. ``by_colour``: the box is filled with the colour of the
105
+ residue's pLDDT band, where it has one, and its name stands on it in the colour that reads there."""
106
+ dash, opacity = _OUTLINE[look.level]
107
+ coloured = by_colour and look.band is not None
108
+ fill = f"plddt_{look.band}" if coloured else "background"
109
+ ink = f"plddt_text_{look.band}" if coloured else "text"
110
+ counted = unit.number in ("", str(unit.position)) and not deposited
111
+ title = (f"{unit.text} {unit.number or unit.position} of {called} "
112
+ + ("(position counted from its N-terminus)" if counted else "(numbered as in the structure file)"))
113
+ g = Group("unit", data={"position": str(unit.position), "residue": unit.name, "class": unit.residue_class,
114
+ "atoms": ",".join(names)}, title=title)
115
+ if look.band is not None:
116
+ g.data["confidence"] = look.band
117
+ if beside:
118
+ # Those of its atoms that stand beside the box as atoms of their own.
119
+ g.data["beside"] = ",".join(beside)
120
+ x0, y0, x1, y1 = unit.box
121
+ g.add(Rect(x0, y0, x1 - x0, y1 - y0, Paint(fill=fill, stroke="ligand_bond", width=1.15, dash=dash,
122
+ opacity=opacity), rx=_CORNER))
123
+ baseline = unit.y + CAP_HEIGHT * UNIT_FONT / 2.0
124
+ g.add(Text(unit.x, baseline, (Span(unit.text, bold=True),
125
+ Span(" " + (unit.number or str(unit.position)), size=INDEX_FONT,
126
+ fill=ink if coloured else "text_muted")),
127
+ UNIT_FONT, ink, "middle", opacity=1.0 if look.level == 0 else 0.85))
128
+ return g
129
+
130
+
131
+ def draw_polymer(dep: Depiction, palette: Palette, metrics: Metrics,
132
+ looks: "Sequence[Look] | None" = None, units: "Sequence[Look] | None" = None,
133
+ deposited: bool = False, own: "Mapping[int, Look] | None" = None,
134
+ by_colour: bool = False) -> Group:
135
+ """The chain ligand as a group: backbone and bonds underneath, boxes and atom labels on top.
136
+
137
+ ``looks`` is one look per depicted atom (it styles the atoms outside the
138
+ chain), ``units`` one per residue of the chain. ``own`` is the look of every
139
+ atom that stands beside its residue's box as an atom of its own; without it
140
+ such atoms are drawn at full strength. ``by_colour``: the boxes are filled
141
+ with the colours of their pLDDT bands (:func:`_unit_group`).
142
+ """
143
+ g = Group("ligand", data={"drawn-as": "chain"})
144
+ line = Paint(stroke="ligand_bond", width=metrics.bond_width)
145
+ under = Group("backbone")
146
+ gap = Paint(stroke="ligand_bond", width=metrics.bond_width * 0.75, dash=(0.01, 3.2), cap="round", opacity=0.7)
147
+ beside = {i for u in dep.units for i in u.beside}
148
+ for bond in dep.bonds:
149
+ if bond.kind not in ("chain", "gap"):
150
+ continue
151
+ ua, ub = dep.unit_of(bond.a), dep.unit_of(bond.b)
152
+ if ua is None or ub is None:
153
+ continue
154
+ tail = ua.c if ua.c in ua.beside else None # the carbonyl carbon below the upper box, drawn
155
+ head = ub.n if ub.n in ub.beside else None # the nitrogen above the lower one
156
+ if tail is not None or head is not None:
157
+ if bond.kind == "chain":
158
+ continue # the bond between the two residues is drawn as what it is, at its atoms
159
+ # Residues are missing here: the dotted line runs between what is drawn of the two ends.
160
+ pa = dep.pos(tail) if tail is not None else segment_box_entry(ub.pos, ua.pos, ua.box)
161
+ pb = dep.pos(head) if head is not None else segment_box_entry(ua.pos, ub.pos, ub.box)
162
+ if tail is not None:
163
+ pa = (pa[0], pa[1] + 3.0)
164
+ if head is not None:
165
+ label = dep.atoms[head].label
166
+ pb = (pb[0], (label.box[1] if label is not None else pb[1]) - 2.0)
167
+ if pb[1] > pa[1]:
168
+ under.add(Line(pa[0], pa[1], pb[0], pb[1], gap))
169
+ continue
170
+ pa = segment_box_entry(ub.pos, ua.pos, ua.box)
171
+ pb = segment_box_entry(ua.pos, ub.pos, ub.box)
172
+ under.add(Line(pa[0], pa[1], pb[0], pb[1], line if bond.kind == "chain" else gap))
173
+ if dep.units:
174
+ # The chain goes on beyond what is drawn: a dotted stub where a terminus letter would stand.
175
+ first, last = dep.units[0], dep.units[-1]
176
+ if dep.open_ends[0]:
177
+ under.add(Line(first.x, first.box[1] - 9.0, first.x, first.box[1], gap))
178
+ if dep.open_ends[1]:
179
+ under.add(Line(last.x, last.box[3], last.x, last.box[3] + 9.0, gap))
180
+ for bond, points in brackets(dep):
181
+ paint = line if bond.kind == "closure" else Paint(stroke="ligand_bond", width=metrics.bond_width * 0.8,
182
+ dash=(3.2, 2.4))
183
+ under.add(Polyline(points, paint))
184
+ if dep.arranged == "plane":
185
+ # A link between two residues that are not neighbours in the chain (a disulfide): on a plane
186
+ # the two boxes are where their residues are, and the link is the straight line between them.
187
+ for bond in dep.bonds:
188
+ ua, ub = dep.unit_of(bond.a), dep.unit_of(bond.b)
189
+ if bond.kind not in ("closure", "crosslink") or ua is None or ub is None:
190
+ continue
191
+ pa = segment_box_entry(ub.pos, ua.pos, ua.box)
192
+ pb = segment_box_entry(ua.pos, ub.pos, ub.box)
193
+ under.add(Line(pa[0], pa[1], pb[0], pb[1],
194
+ Paint(stroke="ligand_bond", width=metrics.bond_width * 0.8, dash=(3.2, 2.4))))
195
+ g.add(under)
196
+
197
+ bonds = Group("bonds")
198
+ # Atoms outside the chain (an appendage: a lipid on a lysine) are drawn at their own looks where one of
199
+ # them is weaker than full strength; otherwise all of them at full strength, with the chain.
200
+ appendage = {a.idx for a in dep.atoms if dep.unit_of(a.idx) is None and a.idx not in beside}
201
+ faded = looks is not None and not by_colour and any(looks[i].level > 0 for i in appendage)
202
+ later: list[DepBond] = []
203
+ for bond in dep.bonds:
204
+ if bond.kind not in ("covalent", "coordination"):
205
+ continue
206
+ if bond.a in beside or bond.b in beside:
207
+ continue # of an atom beside its residue's box: drawn below, at its confidence
208
+ if faded and (bond.a in appendage or bond.b in appendage):
209
+ later.append(bond) # drawn below, at its confidence
210
+ continue
211
+ ua, ub = dep.unit_of(bond.a), dep.unit_of(bond.b)
212
+ if ua is None and ub is None:
213
+ bonds.extend(bond_items(dep, bond))
214
+ continue
215
+ if ua is not None and ub is not None:
216
+ continue
217
+ # The bond that holds an atom to the chain: from the edge of the residue's box to the atom.
218
+ unit, held = (ua, bond.b) if ua is not None else (ub, bond.a)
219
+ assert unit is not None
220
+ outside = dep.pos(held)
221
+ start = segment_box_entry(outside, unit.pos, unit.box)
222
+ end = outside
223
+ label = dep.atoms[held].label
224
+ if label is not None:
225
+ end = segment_box_entry(start, outside, label.box)
226
+ bonds.add(Line(start[0], start[1], end[0], end[1], line))
227
+ labels = Group("atoms")
228
+ if beside:
229
+ _draw_beside(dep, palette, metrics, beside, own or {}, bonds, labels)
230
+ if faded:
231
+ assert looks is not None
232
+ _draw_outside(dep, palette, metrics, appendage, looks, later, bonds, labels)
233
+ g.add(bonds)
234
+
235
+ boxes = Group("units")
236
+ for k, unit in enumerate(dep.units):
237
+ names = [dep.atoms[a].name or "" for a in unit.atoms]
238
+ boxes.add(_unit_group(unit, units[k] if units else PLAIN, names, deposited, dep.called,
239
+ [dep.atoms[a].name or "" for a in unit.beside], by_colour))
240
+ for point, letter in terminus_marks(dep):
241
+ boxes.add(Text.plain(point[0], point[1], letter, _TERMINUS_FONT, "text_muted"))
242
+ g.add(boxes)
243
+
244
+ for atom in dep.atoms:
245
+ if atom.label is not None and dep.unit_of(atom.idx) is None and atom.idx not in beside and not faded:
246
+ labels.add(_atom_group(atom, palette, metrics))
247
+ g.add(labels)
248
+ return g
249
+
250
+
251
+ def _draw_outside(dep: Depiction, palette: Palette, metrics: Metrics, outside: "set[int]",
252
+ looks: "Sequence[Look]", strokes: "Sequence[DepBond]", bonds: Group, labels: Group) -> None:
253
+ """The atoms outside the chain and their bonds, each at the look of its atom (a bond at the weaker of
254
+ its ends outside the chain), every level of confidence fading as one group, the weakest underneath."""
255
+ def weaker(bond: DepBond) -> Look:
256
+ return max((looks[i] for i in (bond.a, bond.b) if i in outside), key=lambda lk: lk.level)
257
+
258
+ levels = sorted({weaker(b).level for b in strokes} | {looks[i].level for i in outside}, reverse=True)
259
+ for level in levels:
260
+ mine = [b for b in strokes if weaker(b).level == level]
261
+ seen = weaker(mine[0]) if mine else next(looks[i] for i in sorted(outside) if looks[i].level == level)
262
+ fine = replace(dep, metrics=dep.metrics.with_(bond_width=metrics.bond_width * seen.width))
263
+ part = Group("bonds-outside" + ("-" + seen.band if seen.band else ""), opacity=seen.opacity)
264
+ paint = Paint(stroke="ligand_bond", width=metrics.bond_width * seen.width)
265
+ for bond in mine:
266
+ ua, ub = dep.unit_of(bond.a), dep.unit_of(bond.b)
267
+ if ua is None and ub is None:
268
+ part.extend(bond_items(fine, bond))
269
+ continue
270
+ # The bond that holds the appendage to the chain: from the edge of the residue's box to the atom.
271
+ unit, held = (ua, bond.b) if ua is not None else (ub, bond.a)
272
+ assert unit is not None
273
+ start = segment_box_entry(dep.pos(held), unit.pos, unit.box)
274
+ end = dep.pos(held)
275
+ label = dep.atoms[held].label
276
+ if label is not None:
277
+ end = segment_box_entry(start, dep.pos(held), label.box)
278
+ part.add(Line(start[0], start[1], end[0], end[1], paint))
279
+ if part.items:
280
+ bonds.add(part)
281
+ names = Group("atoms-outside" + ("-" + seen.band if seen.band else ""),
282
+ opacity=1.0 if level == 0 else max(0.6, seen.opacity + 0.15))
283
+ for i in sorted(outside):
284
+ atom = dep.atoms[i]
285
+ if atom.label is not None and looks[i].level == level:
286
+ names.add(_atom_group(atom, palette, metrics))
287
+ if names.items:
288
+ labels.add(names)
289
+
290
+
291
+ def _draw_beside(dep: Depiction, palette: Palette, metrics: Metrics, beside: "set[int]",
292
+ own: "Mapping[int, Look]", bonds: Group, labels: Group) -> None:
293
+ """The atoms that stand beside their residues' boxes: their bonds into ``bonds``, their names into
294
+ ``labels``, each at the look of its atom (a bond at the weaker of its two ends). Drawn at the scale
295
+ of the fragments around a chain, in the chain's colour; every level of confidence fades as one group."""
296
+ def look(i: int) -> Look:
297
+ return own.get(i, PLAIN)
298
+
299
+ def weaker(bond: DepBond) -> Look:
300
+ ends = [look(i) for i in (bond.a, bond.b) if i in beside]
301
+ return max(ends, key=lambda lk: lk.level)
302
+
303
+ mine = [b for b in dep.bonds if b.kind == "covalent" and (b.a in beside or b.b in beside)]
304
+ levels = sorted({weaker(b).level for b in mine} | {look(i).level for i in beside}, reverse=True)
305
+ for level in levels: # the weakest underneath
306
+ strokes = [b for b in mine if weaker(b).level == level]
307
+ seen = weaker(strokes[0]) if strokes else next(look(i) for i in sorted(beside) if look(i).level == level)
308
+ fine = replace(dep, metrics=dep.metrics.with_(bond_width=metrics.protein_bond_width * seen.width,
309
+ double_offset=metrics.double_offset * 0.8, label_gap=1.5))
310
+ part = Group("bonds-beside" + ("-" + seen.band if seen.band else ""), opacity=seen.opacity)
311
+ paint = Paint(stroke="ligand_bond", width=metrics.protein_bond_width * seen.width)
312
+ for bond in strokes:
313
+ ua, ub = dep.unit_of(bond.a), dep.unit_of(bond.b)
314
+ if ua is None and ub is None:
315
+ part.extend(bond_items(fine, bond))
316
+ continue
317
+ # From the edge of the residue's box (the alpha carbon, or a proline's nitrogen) to the atom.
318
+ unit, held = (ua, bond.b) if ua is not None else (ub, bond.a)
319
+ assert unit is not None
320
+ if unit.residue_class == "nucleotide" and held in unit.beside \
321
+ and unit.anchor not in (bond.a, bond.b):
322
+ # A nucleotide's box is its C4': a bond within it to an atom that is not drawn (O2', O3')
323
+ # is no line from the box. (A bond to the next residue's box is, as it is for a peptide.)
324
+ continue
325
+ outside = dep.pos(held)
326
+ start = segment_box_entry(outside, unit.pos, unit.box)
327
+ end = outside
328
+ label = dep.atoms[held].label
329
+ if label is not None:
330
+ end = segment_box_entry(start, outside, label.box)
331
+ part.add(Line(start[0], start[1], end[0], end[1], paint))
332
+ if part.items:
333
+ bonds.add(part)
334
+ names = Group("atoms-beside" + ("-" + seen.band if seen.band else ""),
335
+ opacity=1.0 if level == 0 else max(0.6, seen.opacity + 0.15))
336
+ for i in sorted(beside):
337
+ atom = dep.atoms[i]
338
+ if atom.label is not None and look(i).level == level:
339
+ names.add(_atom_group(atom, palette, metrics))
340
+ if names.items:
341
+ labels.add(names)
342
+
343
+
344
+ def chain_obstacles(dep: Depiction) -> list[tuple[float, float, float]]:
345
+ """Discs over the ink of a chain that is not an atom or a bond: brackets and the two terminus letters."""
346
+ out: list[tuple[float, float, float]] = []
347
+ for _bond, points in brackets(dep):
348
+ (_x0, y0), (x, _y1), (_x2, y2), _ = points
349
+ lo, hi = sorted((y0, y2))
350
+ steps = max(1, int((hi - lo) / 6.0))
351
+ out.extend((x, lo + (hi - lo) * k / steps, 2.5) for k in range(steps + 1))
352
+ for point, _letter in terminus_marks(dep):
353
+ out.append((point[0], point[1] - CAP_HEIGHT * _TERMINUS_FONT / 2.0, 6.0))
354
+ return out
@@ -0,0 +1,75 @@
1
+ """A residue in its ring: what share of the models of an ensemble contacts it (:mod:`bindview.consensus`).
2
+
3
+ A disc in the colour of the residue's class, with its name and the number of models, and around it a ring as long
4
+ as their share, clockwise from the top. Both styles draw a residue so where a figure counts by residue: in the
5
+ place of its bubble, or where the name of a residue stands that is drawn as atoms.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import math
11
+ from typing import TYPE_CHECKING
12
+
13
+ from ..scene import Circle, Item, Paint, Polyline, Text
14
+ from ..textmetrics import CAP_HEIGHT, text_width
15
+
16
+ if TYPE_CHECKING:
17
+ from ..consensus import ResidueShare
18
+
19
+ __all__ = ["ring_items", "ring_reach", "ring_title", "ring_sample", "BOLD_FROM"]
20
+
21
+ #: The letters of the name and, below it, of the number of models.
22
+ _NAME, _COUNT = 8.8, 7.6
23
+ #: From the edge of the disc to the middle of the ring, the width of the ring, and the room beyond it.
24
+ _GAP, _WIDTH, _PAD = 4.4, 3.4, 0.9
25
+ _LEAST_RADIUS = 15.0
26
+ #: From this share on the name is bold.
27
+ BOLD_FROM = 0.5
28
+
29
+
30
+ def _count(share: "ResidueShare") -> str:
31
+ return f"{share.n_models}/{share.n_total}"
32
+
33
+
34
+ def _radius(label: str, share: "ResidueShare") -> float:
35
+ wide = max(text_width(label, _NAME, bold=True), text_width(_count(share), _COUNT))
36
+ return max(_LEAST_RADIUS, math.hypot(wide / 2.0, CAP_HEIGHT * _NAME + 1.0) + 1.6)
37
+
38
+
39
+ def ring_reach(label: str, share: "ResidueShare") -> float:
40
+ """How far a residue in its ring reaches from its middle."""
41
+ return _radius(label, share) + _GAP + _WIDTH / 2.0 + _PAD
42
+
43
+
44
+ def ring_title(label: str, share: "ResidueShare") -> str:
45
+ return f"{label}: {share.said}"
46
+
47
+
48
+ def _arc(x: float, y: float, r: float, share: float) -> Item:
49
+ if share >= 1.0 - 1e-9:
50
+ return Circle(x, y, r, Paint(stroke="text", width=_WIDTH))
51
+ n = max(2, int(math.ceil(2.0 * math.pi * share * r / 2.0)))
52
+ turn = [-math.pi / 2.0 + 2.0 * math.pi * share * k / n for k in range(n + 1)]
53
+ return Polyline(tuple((x + r * math.cos(a), y + r * math.sin(a)) for a in turn),
54
+ Paint(stroke="text", width=_WIDTH, cap="butt"))
55
+
56
+
57
+ def ring_items(x: float, y: float, label: str, share: "ResidueShare", fill: str, ink: str = "bubble_text") -> list[Item]:
58
+ """A residue in its ring, at (x, y)."""
59
+ radius = _radius(label, share)
60
+ return [Circle(x, y, radius, Paint(fill=fill, stroke="bubble_line", width=0.8, opacity=0.55 + 0.45 * share.share)),
61
+ Circle(x, y, radius + _GAP, Paint(stroke="panel_border", width=0.8)),
62
+ _arc(x, y, radius + _GAP, share.share),
63
+ Text.plain(x, y - 0.6, label, _NAME, ink, bold=share.share >= BOLD_FROM),
64
+ Text.plain(x, y + CAP_HEIGHT * _COUNT + 2.0, _count(share), _COUNT, ink)]
65
+
66
+
67
+ def ring_sample(x: float, y: float, radius: float) -> list[Item]:
68
+ """The ring of the key: that of a residue that three of four models contact."""
69
+ return [Circle(x, y, radius - 1.2, Paint(stroke="panel_border", width=0.8)),
70
+ *_thin(_arc(x, y, radius - 1.2, 0.75))]
71
+
72
+
73
+ def _thin(arc: Item) -> list[Item]:
74
+ assert isinstance(arc, Polyline)
75
+ return [Polyline(arc.points, Paint(stroke="text", width=2.2, cap="butt"))]