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,289 @@
1
+ """Drawing the ligand skeleton: bonds, wedges, atom labels. Shared by all styles."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import replace
6
+ from typing import Sequence
7
+
8
+ from ..confidence import PLAIN, Look
9
+ from ..depict import AtomLabel, DepBond, Depiction, clip_to_labels
10
+ from ..geometry import Point, add, cross, dist, lerp, mul, perp, sub, unit
11
+ from ..scene import Circle, Group, Item, Line, Paint, Polygon, Text
12
+ from ..theme import Metrics, Palette
13
+
14
+ __all__ = ["draw_ligand", "bond_items", "coloured_bond_items", "label_items", "double_bond_side", "plddt_underlay"]
15
+
16
+
17
+ def _ring_for(dep: Depiction, bond: DepBond) -> tuple[int, ...] | None:
18
+ """The ring a double bond should be drawn inside of."""
19
+ rings = [r for r in dep.rings if bond.a in r and bond.b in r]
20
+ if not rings:
21
+ return None
22
+
23
+ def n_double(ring: tuple[int, ...]) -> int:
24
+ members = set(ring)
25
+ return sum(1 for b in dep.bonds if b.order == 2 and b.a in members and b.b in members)
26
+
27
+ # Aromatic first, then six-membered, then the ring with more double bonds.
28
+ rings.sort(key=lambda r: (
29
+ 0 if all(dep.atoms[i].aromatic for i in r) else 1,
30
+ 0 if len(r) == 6 else 1,
31
+ -n_double(r), len(r), r))
32
+ return rings[0]
33
+
34
+
35
+ def double_bond_side(dep: Depiction, bond: DepBond) -> int:
36
+ """``+1`` / ``-1``: the side of ``a->b`` the second line goes on; ``0`` = centred."""
37
+ pa, pb = dep.pos(bond.a), dep.pos(bond.b)
38
+ axis = sub(pb, pa)
39
+ ring = _ring_for(dep, bond)
40
+ if ring is not None:
41
+ c = dep.centroid(ring)
42
+ return 1 if cross(axis, sub(c, pa)) > 0 else -1
43
+ na = [j for j in dep.neighbours(bond.a) if j != bond.b]
44
+ nb = [j for j in dep.neighbours(bond.b) if j != bond.a]
45
+ if not na or not nb:
46
+ return 0 # terminal: centre the pair of lines
47
+ score = 0
48
+ for j in na + nb:
49
+ score += 1 if cross(axis, sub(dep.pos(j), pa)) > 0 else -1
50
+ return 1 if score >= 0 else -1
51
+
52
+
53
+ def _clipped(dep: Depiction, bond: DepBond, pa: Point, pb: Point) -> tuple[Point, Point] | None:
54
+ return clip_to_labels(pa, pb, dep.atoms[bond.a].label, dep.atoms[bond.b].label, dep.metrics.label_gap)
55
+
56
+
57
+ def bond_items(dep: Depiction, bond: DepBond, stroke: str = "ligand_bond") -> list[Item]:
58
+ m = dep.metrics
59
+ pa, pb = dep.pos(bond.a), dep.pos(bond.b)
60
+ if bond.kind == "coordination":
61
+ seg = _clipped(dep, bond, pa, pb)
62
+ if seg is None:
63
+ return []
64
+ return [Line(*seg[0], *seg[1], Paint(stroke="coordination", width=m.bond_width * 0.75,
65
+ dash=(1.2, 3.2)))]
66
+ seg = _clipped(dep, bond, pa, pb)
67
+ if seg is None:
68
+ return []
69
+ a, b = seg
70
+ paint = Paint(stroke=stroke, width=m.bond_width)
71
+ n = perp(unit(sub(pb, pa)))
72
+
73
+ if bond.stereo == "wedge":
74
+ hw0, hw1 = m.bond_width * 0.35, m.wedge_width / 2.0
75
+ pts = (add(a, mul(n, hw0)), add(b, mul(n, hw1)), add(b, mul(n, -hw1)), add(a, mul(n, -hw0)))
76
+ return [Polygon(pts, Paint(fill=stroke, stroke=stroke, width=0.5, join="round"))]
77
+ if bond.stereo == "hash":
78
+ length = dist(a, b)
79
+ count = max(3, int(round(length / m.hash_spacing)))
80
+ thin = Paint(stroke=stroke, width=max(0.9, m.bond_width * 0.62), cap="butt")
81
+ out: list[Item] = []
82
+ for k in range(count):
83
+ t = (k + 0.5) / count
84
+ p = lerp(a, b, t)
85
+ hw = 0.5 + (m.wedge_width / 2.0 - 0.5) * t
86
+ out.append(Line(*add(p, mul(n, hw)), *add(p, mul(n, -hw)), thin))
87
+ return out
88
+
89
+ if bond.order == 1 and not bond.aromatic:
90
+ return [Line(*a, *b, paint)]
91
+
92
+ off = m.double_offset
93
+ if bond.order == 3:
94
+ out = [Line(*a, *b, paint)]
95
+ for sgn in (1.0, -1.0):
96
+ s2 = _clipped(dep, bond, add(pa, mul(n, sgn * off * 0.85)), add(pb, mul(n, sgn * off * 0.85)))
97
+ if s2:
98
+ out.append(Line(*s2[0], *s2[1], paint))
99
+ return out
100
+
101
+ side = double_bond_side(dep, bond)
102
+ if side == 0 and not bond.aromatic:
103
+ out = []
104
+ for sgn in (0.5, -0.5):
105
+ s2 = _clipped(dep, bond, add(pa, mul(n, sgn * off)), add(pb, mul(n, sgn * off)))
106
+ if s2:
107
+ out.append(Line(*s2[0], *s2[1], paint))
108
+ return out
109
+
110
+ side = side or 1
111
+ out = [Line(*a, *b, paint)]
112
+ length = dist(pa, pb)
113
+ trim = min(off * 0.95, length * 0.2)
114
+ ia = add(pa, mul(n, side * off))
115
+ ib = add(pb, mul(n, side * off))
116
+ ax = unit(sub(pb, pa))
117
+ # Pull the inner line in at ends that are bare junctions, so it meets the
118
+ # neighbouring bonds like a mitre instead of poking past them.
119
+ if dep.atoms[bond.a].label is None and len(dep.neighbours(bond.a)) > 1:
120
+ ia = add(ia, mul(ax, trim))
121
+ if dep.atoms[bond.b].label is None and len(dep.neighbours(bond.b)) > 1:
122
+ ib = add(ib, mul(ax, -trim))
123
+ s2 = _clipped(dep, bond, ia, ib)
124
+ if s2:
125
+ inner = Paint(stroke=stroke, width=m.bond_width, dash=(2.6, 2.2)) if bond.aromatic else paint
126
+ out.append(Line(*s2[0], *s2[1], inner))
127
+ return out
128
+
129
+
130
+ def coloured_bond_items(dep: Depiction, bond: DepBond, bands: "Sequence[str | None]", stroke: str = "ligand_bond"
131
+ ) -> list[Item]:
132
+ """A bond in the colours of its atoms' pLDDT bands, each half in that of the atom it leaves: ``bands`` has
133
+ one entry for each depicted atom, and an atom without a value has the bond in its own colour (``stroke``)."""
134
+ items = bond_items(dep, bond, stroke)
135
+ if bond.kind == "coordination":
136
+ return items
137
+ of = [f"plddt_{bands[i]}" if bands[i] is not None else stroke for i in (bond.a, bond.b)]
138
+ if of[0] == of[1]:
139
+ return [_painted(it, of[0]) for it in items]
140
+ pa, pb = dep.pos(bond.a), dep.pos(bond.b)
141
+ axis, length = unit(sub(pb, pa)), dist(pa, pb) or 1.0
142
+
143
+ def along(p: Point) -> float:
144
+ return (sub(p, pa)[0] * axis[0] + sub(p, pa)[1] * axis[1]) / length
145
+
146
+ out: list[Item] = []
147
+ for it in items:
148
+ if isinstance(it, Line):
149
+ p, q = (it.x1, it.y1), (it.x2, it.y2)
150
+ t0, t1 = along(p), along(q)
151
+ if abs(t1 - t0) < 0.2: # a rung of a hashed bond lies across it
152
+ out.append(_painted(it, of[0] if (t0 + t1) / 2.0 < 0.5 else of[1]))
153
+ continue
154
+ mid = lerp(p, q, min(max((0.5 - t0) / (t1 - t0), 0.0), 1.0))
155
+ first, second = (of[0], of[1]) if t0 < t1 else (of[1], of[0])
156
+ butt = replace(it.paint, cap="butt") if not it.paint.dash else it.paint
157
+ out.append(Line(*p, *mid, replace(butt, stroke=first)))
158
+ out.append(Line(*mid, *q, replace(butt, stroke=second)))
159
+ # A round end where the bond meets others, as a bond of one colour has.
160
+ out.extend(Circle(*end, it.paint.width / 2.0, Paint(fill=token)) for end, token in ((p, first), (q, second))
161
+ if not it.paint.dash)
162
+ elif isinstance(it, Polygon) and len(it.points) == 4:
163
+ a0, b0, b1, a1 = it.points # a wedge, from its narrow end to its wide one
164
+ m0, m1 = lerp(a0, b0, 0.5), lerp(a1, b1, 0.5)
165
+ out.append(Polygon((a0, m0, m1, a1), replace(it.paint, fill=of[0], stroke=of[0])))
166
+ out.append(Polygon((m0, b0, b1, m1), replace(it.paint, fill=of[1], stroke=of[1])))
167
+ else:
168
+ out.append(_painted(it, of[0]))
169
+ return out
170
+
171
+
172
+ def _painted(it: Item, token: str) -> Item:
173
+ if isinstance(it, Polygon):
174
+ return Polygon(it.points, replace(it.paint, fill=token, stroke=token))
175
+ assert isinstance(it, Line)
176
+ return Line(it.x1, it.y1, it.x2, it.y2, replace(it.paint, stroke=token))
177
+
178
+
179
+ def label_items(label: AtomLabel, size: float, fill: str) -> list[Item]:
180
+ return [Text(run.x, run.y, run.spans, size, fill, run.anchor) for run in label.runs]
181
+
182
+
183
+ def atom_looks(dep: Depiction, plddt: "dict[str, float] | None", by_colour: bool = False) -> list[Look]:
184
+ """The confidence look of every depicted atom.
185
+
186
+ A depiction-only hydrogen takes the look of the atom it is drawn on; an atom
187
+ without a value is drawn plainly. ``by_colour``: as in
188
+ :func:`bindview.confidence.look_of`.
189
+ """
190
+ from ..confidence import look_of
191
+
192
+ looks = [look_of(plddt.get(a.name), by_colour) if (plddt and a.name) else PLAIN for a in dep.atoms]
193
+ if plddt:
194
+ for a in dep.atoms:
195
+ if a.name is None:
196
+ nbrs = dep.neighbours(a.idx)
197
+ if nbrs:
198
+ looks[a.idx] = looks[nbrs[0]]
199
+ return looks
200
+
201
+
202
+ #: A figure that colours by pLDDT sets the atoms on a band of colour: how wide it is, in bond lengths,
203
+ #: and how strong. Wide enough to read as a colour, and pale enough for a bond to stand on it.
204
+ UNDERLAY_WIDTH = 0.5
205
+ UNDERLAY_OPACITY = 0.5
206
+
207
+
208
+ def plddt_underlay(dep: Depiction, bands: "Sequence[str | None]") -> "Group | None":
209
+ """What stands behind atoms that are coloured by pLDDT.
210
+
211
+ Under every atom that is drawn as an atom a disc in the colour of its band, and under every bond
212
+ between two such atoms a stroke as wide as the disc, each half in the colour of the atom it leaves.
213
+ ``bands`` has one entry for each depicted atom: its band, or ``None`` where the model gives it no
214
+ value, and nothing stands behind that atom. The whole is one group and is made paler as one, so
215
+ that where two shapes meet nothing adds up. ``None`` where there is nothing to draw.
216
+ """
217
+ width = UNDERLAY_WIDTH * dep.metrics.bond_length
218
+ items: list[Item] = []
219
+ for bond in dep.bonds:
220
+ if bond.kind not in ("covalent", "coordination"):
221
+ continue
222
+ if dep.unit_of(bond.a) is not None or dep.unit_of(bond.b) is not None:
223
+ continue # an atom inside a residue's box: the box is coloured, not the atom
224
+ a, b = dep.atoms[bond.a], dep.atoms[bond.b]
225
+ mx, my = (a.x + b.x) / 2.0, (a.y + b.y) / 2.0
226
+ for atom in (a, b):
227
+ band = bands[atom.idx]
228
+ if band is not None:
229
+ items.append(Line(atom.x, atom.y, mx, my, Paint(stroke=f"plddt_{band}", width=width, cap="butt")))
230
+ for atom in dep.atoms:
231
+ band = bands[atom.idx]
232
+ if band is not None and dep.unit_of(atom.idx) is None:
233
+ items.append(Circle(atom.x, atom.y, width / 2.0, Paint(fill=f"plddt_{band}")))
234
+ return Group("plddt", items, opacity=UNDERLAY_OPACITY) if items else None
235
+
236
+
237
+ def draw_ligand(dep: Depiction, palette: Palette, metrics: Metrics,
238
+ looks: "Sequence[Look] | None" = None, bands: "Sequence[str | None] | None" = None) -> Group:
239
+ """The ligand as a group: bonds underneath, labels on top. ``bands``, one for each depicted atom: its bonds
240
+ are drawn in the colours of these pLDDT bands.
241
+
242
+ With ``looks`` (one per depicted atom) the drawing carries the model's
243
+ confidence: a bond is drawn at the weaker of its two atoms, thinner and
244
+ paler below pLDDT 70. Each confidence level fades as one group, so the
245
+ strokes that meet at an atom do not add up to a darker joint.
246
+ """
247
+ g = Group("ligand")
248
+ if looks is None or all(lk.level == 0 for lk in looks):
249
+ bonds = Group("bonds")
250
+ for bond in dep.bonds:
251
+ bonds.extend(bond_items(dep, bond) if bands is None else coloured_bond_items(dep, bond, bands))
252
+ labels = Group("atoms")
253
+ for atom in dep.atoms:
254
+ if atom.label is not None:
255
+ labels.add(_atom_group(atom, palette, metrics))
256
+ g.add(bonds, labels)
257
+ return g
258
+
259
+ bonds = Group("bonds")
260
+ labels = Group("atoms")
261
+ by_level: dict[int, Look] = {}
262
+ for lk in looks:
263
+ by_level.setdefault(lk.level, lk)
264
+ for level in sorted(by_level, reverse=True): # weakest underneath
265
+ look = by_level[level]
266
+ thin = replace(dep, metrics=dep.metrics.with_(bond_width=dep.metrics.bond_width * look.width))
267
+ part = Group("bonds-" + (look.band or "plain"), opacity=look.opacity)
268
+ for bond in dep.bonds:
269
+ if max(looks[bond.a].level, looks[bond.b].level) == level:
270
+ part.extend(bond_items(thin, bond))
271
+ if part.items:
272
+ bonds.add(part)
273
+ text = Group("atoms-" + (look.band or "plain"), opacity=1.0 if level == 0 else max(0.6, look.opacity + 0.15))
274
+ for atom in dep.atoms:
275
+ if atom.label is not None and looks[atom.idx].level == level:
276
+ text.add(_atom_group(atom, palette, metrics))
277
+ if text.items:
278
+ labels.add(text)
279
+ g.add(bonds, labels)
280
+ return g
281
+
282
+
283
+ def _atom_group(atom, palette: Palette, metrics: Metrics) -> Group:
284
+ token = palette.element_token(atom.element)
285
+ if atom.name is None:
286
+ token = "ligand_carbon" # depiction-only stereo hydrogens
287
+ ag = Group("atom", data={"atom": atom.name} if atom.name else {})
288
+ ag.extend(label_items(atom.label, metrics.atom_font, token))
289
+ return ag
@@ -0,0 +1,70 @@
1
+ """A figure whose residues are not all drawn alike (``residues={...}``).
2
+
3
+ Each residue is drawn by the style that draws its form: with atoms, or as its
4
+ name, by the detailed one, and as a bubble by the schematic one. What the two
5
+ share -- the lines, the lining, the halos, the key -- is the figure's and is
6
+ drawn once, from the one set of settings.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from dataclasses import replace
12
+ from typing import Sequence
13
+
14
+ from ..layout import Body
15
+ from .base import (STYLE_SETTINGS, Context, Drawn, RenderOptions, ResidueGroup, Settings, StyleDrawing,
16
+ finish_drawing, residue_names)
17
+ from .detailed import DetailedStyle
18
+ from .schematic import SchematicStyle, _Bubble
19
+
20
+ __all__ = ["MixedStyle", "style_for", "unknown_residues"]
21
+
22
+
23
+ class MixedStyle:
24
+ """``name``: the style whose settings are the figure's where a residue is not named."""
25
+
26
+ def __init__(self, name: str, settings: Settings) -> None:
27
+ self.name, self.settings = name, settings
28
+ self._atoms, self._bubbles = DetailedStyle(settings), SchematicStyle(settings)
29
+
30
+ def _of(self, grp: ResidueGroup) -> "DetailedStyle | SchematicStyle":
31
+ return self._bubbles if self.settings.form_of(grp) == "bubbles" else self._atoms
32
+
33
+ def ligand_obstacles(self, ctx: Context) -> list[tuple[float, float, float]]:
34
+ return self._atoms.ligand_obstacles(ctx, [g for g in ctx.groups if self._of(g) is self._atoms])
35
+
36
+ def bodies(self, ctx: Context) -> list[Body]:
37
+ return [self._of(grp).body(ctx, grp) for grp in ctx.groups]
38
+
39
+ def draw(self, ctx: Context, bodies: Sequence[Body], poses: dict, label_ts: dict | None = None) -> StyleDrawing:
40
+ d = Drawn({"backdrop": [], "halos": [], "interactions": [], "contacts": [], "residues": []})
41
+ bubbles = [b for b in bodies if isinstance(b.payload, _Bubble)]
42
+ others = [b for b in bodies if not isinstance(b.payload, _Bubble)]
43
+ self._atoms.draw_bodies(ctx, others, poses, label_ts or {}, d)
44
+ self._bubbles.draw_bodies(ctx, bubbles, poses, label_ts or {}, d)
45
+ return finish_drawing(ctx, self.settings, d)
46
+
47
+
48
+ def style_for(name: str, options: RenderOptions) -> "DetailedStyle | SchematicStyle | MixedStyle":
49
+ """The style called ``name`` with what the options set by hand."""
50
+ try:
51
+ own = STYLE_SETTINGS[name]
52
+ except KeyError:
53
+ raise ValueError(f"unknown style {name!r}; choose from {', '.join(sorted(STYLE_SETTINGS))}") from None
54
+ settings = own.with_options(options)
55
+ if not isinstance(settings.residues, str):
56
+ if "*" not in dict(settings.residues):
57
+ # A residue that is not named is drawn as the style draws it.
58
+ settings = replace(settings, residues=settings.residues + (("*", own.residues),))
59
+ return MixedStyle(name, settings)
60
+ drawn = SchematicStyle(settings) if settings.residues == "bubbles" else DetailedStyle(settings)
61
+ drawn.name = name
62
+ return drawn
63
+
64
+
65
+ def unknown_residues(options: RenderOptions, groups: Sequence[ResidueGroup]) -> list[str]:
66
+ """The names in ``residues={...}`` that no residue of the figure answers to."""
67
+ if options.residues is None or isinstance(options.residues, str):
68
+ return []
69
+ known = {n.lower() for g in groups for n in residue_names(g)}
70
+ return [name for name, _ in options.residues if name != "*" and name.lower() not in known]