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,334 @@
1
+ """A figure that answers the pointer, with a style sheet and no script.
2
+
3
+ ``render(interactive=True)`` asks for it. Pointing at a residue, or at one of its contacts, keeps the
4
+ residue, its contacts and what they reach, steps the rest of the residues and contacts far back, and draws
5
+ the lines of the contacts heavier, so that what is pointed at is what the figure shows. A click keeps that
6
+ until a click elsewhere, and the tab key goes from one residue to the next.
7
+
8
+ Nothing is added to what a figure draws. A figure already says of every residue which one it is, of every
9
+ contact which residue makes it, and of every residue of a chain ligand which atoms are its own
10
+ (``data-residue``, ``data-ligand-atoms``, ``data-atoms``). From that this module gives each of those groups
11
+ a few classes and lets it take the focus, and writes one rule per residue. A browser that shows the file
12
+ as a document or as part of a page follows the rules; everything else (an ``<img>``, a PDF, a drawing
13
+ program) shows the figure as it is without them.
14
+
15
+ A figure of a ligand that is drawn as atoms has two things beside, in a group of their own at its end
16
+ (:mod:`bindview.styles.closeup`). The atoms of every residue that is drawn without them, which take its place
17
+ while it is pointed at and are not shown otherwise (``display="none"``, which every reader of the file
18
+ honours). And a place to point at on every atom of the ligand, which is no ink: pointing at an atom that makes
19
+ contacts keeps those and the residues they are with.
20
+
21
+ A page around the figure can ask for the same, with one attribute on its root: ``<svg data-active="712">`` is
22
+ what pointing at residue 712 is, until the attribute is taken off or says another. The number is the one that
23
+ ``data-residue-number`` says of the residue and its contacts (with its insertion code, ``60A``). A number that
24
+ the figure does not have changes nothing; one that two chains have lights both, and there ``A:712`` lights one.
25
+ Whoever points into the figure, or has clicked in it, is followed first.
26
+
27
+ The classes, where ``X`` is a residue of the protein (``r712``: its number; where two have the same, each is
28
+ ``r712_A`` with its chain and ``r712`` as well), of a chain ligand (``u0``, ...), or an atom of the ligand that makes a
29
+ contact (``a0``, ...). What is no letter, digit or hyphen in a number or in the name of a chain is in a class by
30
+ its code (``'`` is ``__27_``); ``data-active`` says it as it is:
31
+
32
+ ``lf-part`` a residue, a residue of the chain, a contact, or such an atom: what can step back
33
+ ``lf-t-X`` pointing at this is pointing at ``X`` (``X`` itself, and the contacts of a protein residue)
34
+ ``lf-o-X`` this is ``X`` or one of its contacts
35
+ ``lf-p-X`` this is in contact with ``X``
36
+ ``lf-m-X`` the atoms of ``X``, shown while it is pointed at
37
+ """
38
+
39
+ from __future__ import annotations
40
+
41
+ import re
42
+ from dataclasses import dataclass, field
43
+ from typing import Sequence
44
+
45
+ from .scene import Group, Line, Scene
46
+
47
+ __all__ = ["Hooks", "hooks", "hooks_of_links", "ROOT_CLASS", "DIMMED", "HEAVY", "NOTHING_TO_POINT_AT", "OVER",
48
+ "ACTIVE", "NUMBER", "UNDER"]
49
+
50
+ #: On the root of a figure that answers the pointer.
51
+ ROOT_CLASS = "lf-live"
52
+ #: How much is left of what steps back.
53
+ DIMMED = 0.12
54
+ #: The group at the end of a figure that holds what is not drawn until it is pointed at.
55
+ OVER = "lf-over"
56
+ #: The attribute of the root by which a page says which residue it means.
57
+ ACTIVE = "data-active"
58
+ #: What a group says of its residue's number (``data-residue-number``). Written with the hooks or not at all.
59
+ NUMBER = "residue-number"
60
+ #: The ring around an atom of the ligand that is pointed at.
61
+ _RING = "#b45309"
62
+ #: How heavy the line of a contact is drawn while a residue is pointed at (what stepped back is faint all the same).
63
+ HEAVY = 2.6
64
+ #: The class of a line in the group of a contact that is wider than ``HEAVY``: it lies under the contact's line (the
65
+ #: glow of a PAE, the highlight of a covalent bond, whole or in the pieces left around a word) and keeps its width.
66
+ UNDER = "lf-under"
67
+ #: The lines of a contact that are drawn heavier.
68
+ _LINES = f":is(line,polyline,path):not(.{UNDER})"
69
+ #: What a result says where the option was asked for and changes nothing.
70
+ NOTHING_TO_POINT_AT = ("interactive was asked for, and this figure has no residue to point at: it is the figure it "
71
+ "would be without")
72
+
73
+
74
+ @dataclass
75
+ class Hooks:
76
+ """What is added to a figure: classes for some of its groups (by the group's ``id``), the groups
77
+ that take the focus (0: in the order of the tab key; -1: by a click only), and the rules."""
78
+
79
+ classes: dict[int, str] = field(default_factory=dict)
80
+ focus: dict[int, int] = field(default_factory=dict)
81
+ css: str = ""
82
+ #: The same, rule by rule, where each says the same in every figure that has it.
83
+ shared: list[str] = field(default_factory=list)
84
+ #: The groups that are written hidden.
85
+ hidden: set[int] = field(default_factory=set)
86
+ #: The lines that are written with the class ``UNDER`` (by their ``id``).
87
+ under: set[int] = field(default_factory=set)
88
+
89
+
90
+ def _kind(group: Group) -> str:
91
+ return group.cls.split(" ", 1)[0]
92
+
93
+
94
+ def _names(text: str) -> set[str]:
95
+ return {n for n in text.split(",") if n}
96
+
97
+
98
+ def hooks(scene: Scene, over: "Sequence[Group]" = ()) -> Hooks | None:
99
+ """The hooks of a figure, or ``None`` for one with nothing to point at (a table, an empty figure).
100
+ ``over``: what is written after the figure (:mod:`bindview.styles.closeup`)."""
101
+ residues: dict[str, list[Group]] = {} # which residue: its groups (a large one is drawn in parts)
102
+ units: list[Group] = []
103
+ contacts: list[Group] = []
104
+ marks: list[Group] = [] # what is marked of a residue (bindview.styles.absence)
105
+
106
+ def collect(items: list) -> None:
107
+ for it in items:
108
+ if not isinstance(it, Group):
109
+ continue
110
+ kind = _kind(it)
111
+ if kind == "residue" and it.data.get("residue") and it.items:
112
+ residues.setdefault(it.data["residue"], []).append(it)
113
+ elif kind == "unit" and it.items:
114
+ units.append(it)
115
+ elif kind == "absence" and it.data.get("residue") and it.items:
116
+ marks.append(it)
117
+ elif kind in ("interaction", "contact") and it.data.get("residue") and it.items:
118
+ contacts.append(it)
119
+ else:
120
+ collect(it.items)
121
+
122
+ collect(scene.items)
123
+ if not residues and not units:
124
+ return None
125
+ token, numbered, also = _tokens(residues)
126
+ atoms = [(_names(u.data.get("atoms", "")), f"u{n}") for n, u in enumerate(units)]
127
+
128
+ # The atoms of the ligand that make a contact, by name: a contact that is not drawn as a line counts too.
129
+ hits = [g for g in over if _kind(g) == "hit" and any(r in token for r in _names(g.data.get("residues", "")))]
130
+ spot = {g.data["atom"]: f"a{n}" for n, g in enumerate(hits)}
131
+
132
+ own: dict[int, list[str]] = {} # a group: whose it is
133
+ target: dict[int, str] = {} # a group: pointing at it is pointing at whom
134
+ near: dict[str, set[str]] = {} # who: in contact with whom
135
+ for c in contacts:
136
+ mine = [token[c.data["residue"]]] if c.data["residue"] in token else []
137
+ reached = _names(c.data.get("ligand-atoms", ""))
138
+ theirs = [t for names, t in atoms if names & reached]
139
+ if not mine and not theirs:
140
+ continue
141
+ own[id(c)] = mine + theirs
142
+ target[id(c)] = (mine or theirs)[0]
143
+ for a in mine:
144
+ for b in theirs:
145
+ near.setdefault(a, set()).add(b)
146
+ near.setdefault(b, set()).add(a)
147
+
148
+ out = Hooks()
149
+ at_atoms: dict[int, list[str]] = {} # a contact: the atoms of the ligand that make it
150
+ for c in contacts:
151
+ if id(c) not in own:
152
+ continue
153
+ there = [spot[n] for n in sorted(_names(c.data.get("ligand-atoms", ""))) if n in spot]
154
+ at_atoms[id(c)] = there
155
+ for g in hits:
156
+ for ident in _names(g.data["residues"]):
157
+ if ident in token:
158
+ near.setdefault(token[ident], set()).add(spot[g.data["atom"]])
159
+
160
+ rank = {t: n for n, t in enumerate([*(t for _, t in atoms), *spot.values(), *token.values()])}
161
+
162
+ def named(prefix: str, whos: "Sequence[str]") -> list[str]:
163
+ # (A residue whose number another has is called by the number alone as well: _tokens.)
164
+ return [f"lf-{prefix}-{t}" for t in dict.fromkeys(t for w in whos for t in (w, *also.get(w, ())))]
165
+
166
+ def classes(group: Group, who: str, owners: list[str], partners: bool) -> None:
167
+ parts = ["lf-part"] + named("t", [who]) + named("o", owners)
168
+ if partners:
169
+ parts += named("p", sorted(near.get(who, ()), key=rank.__getitem__))
170
+ out.classes[id(group)] = " ".join(parts)
171
+
172
+ for ident, groups in residues.items():
173
+ for g in groups:
174
+ classes(g, token[ident], [token[ident]], True)
175
+ out.focus[id(g)] = 0
176
+ for g in marks:
177
+ if g.data["residue"] in token: # it stays with its residue, and steps back with it
178
+ classes(g, token[g.data["residue"]], [token[g.data["residue"]]], True)
179
+ for n, u in enumerate(units):
180
+ classes(u, f"u{n}", [f"u{n}"], True)
181
+ out.focus[id(u)] = 0
182
+ for c in contacts:
183
+ if id(c) in own:
184
+ classes(c, target[id(c)], own[id(c)] + at_atoms[id(c)], False)
185
+ out.focus[id(c)] = -1
186
+ out.under.update(_wide(c))
187
+ shown: list[str] = [] # the residues that have atoms to show
188
+ for g in over:
189
+ if _kind(g) == "more" and g.data.get("residue") in token:
190
+ who = token[g.data["residue"]]
191
+ shown.append(who)
192
+ out.classes[id(g)] = f"lf-m-{who}"
193
+ out.hidden.add(id(g))
194
+ elif _kind(g) == "hit" and g.data["atom"] in spot:
195
+ classes(g, spot[g.data["atom"]], [spot[g.data["atom"]]], False)
196
+ out.focus[id(g)] = -1
197
+
198
+ root = f"svg.bindview.{ROOT_CLASS}"
199
+ rules = [f"{root} .lf-part{{transition:opacity .12s;cursor:pointer}}",
200
+ f"{root} .lf-part:focus:not(:focus-visible){{outline:none}}",
201
+ f"{root}:has(.lf-part:is(:hover,:focus)) .lf-part:is(.interaction,.contact) {_LINES}"
202
+ f"{{stroke-width:{HEAVY:g}px}}"]
203
+ if over:
204
+ rules.append(f"{root} .more{{pointer-events:none}}{root} .hit{{cursor:pointer}}"
205
+ f"{root} .hit circle{{pointer-events:all}}{root} .hit:is(:hover,:focus) circle"
206
+ f"{{stroke:{_RING};stroke-width:1.6px}}")
207
+ for who in list(dict.fromkeys(token.values())) + [t for _, t in atoms] + list(spot.values()):
208
+ # A residue that has the focus is kept; pointing counts where nothing has the focus.
209
+ at = f":is(:has(.lf-t-{who}:focus),:not(:has(.lf-part:focus)):has(.lf-t-{who}:hover))"
210
+ rules.append(f"{root}{at} .lf-part:not(.lf-o-{who},.lf-p-{who}){{opacity:{DIMMED:g}}}")
211
+ if who in shown:
212
+ # Its atoms take its place: it steps back with the rest, and its lines go with it. (Said of a figure
213
+ # that has them: a page with several figures in it reads the rules of each for all.)
214
+ rules.append(f"{root}:has(.lf-m-{who}){at} .lf-part.lf-o-{who}{{opacity:{DIMMED:g}}}"
215
+ f"{root}{at} .lf-m-{who}{{display:inline}}")
216
+ out.css = "".join(rules) + _asked_for(numbered, set(shown))
217
+ out.shared = _RULE.findall("".join(rules) + _asked_for(numbered, set(shown), each=True))
218
+ return out
219
+
220
+
221
+ _RULE = re.compile(r"[^{}]+\{[^{}]*\}")
222
+
223
+
224
+ def _wide(group: Group) -> "list[int]":
225
+ """The lines of a contact's group that drawing it heavier would make thinner."""
226
+ out: list[int] = []
227
+ for it in group.items:
228
+ if isinstance(it, Group):
229
+ out += _wide(it)
230
+ elif isinstance(it, Line) and it.paint.stroke is not None and it.paint.width > HEAVY:
231
+ out.append(id(it))
232
+ return out
233
+
234
+
235
+ def _name(text: str) -> str:
236
+ """``text`` as part of a class name: a letter, a digit and a hyphen as they are, anything else by its code
237
+ (``'`` is ``__27_``). The name is then one word of a ``class`` attribute and needs no escape in a selector."""
238
+ return "".join(c if (c.isascii() and c.isalnum()) or c == "-" else f"__{ord(c):x}_" for c in text)
239
+
240
+
241
+ def _quoted(text: str) -> str:
242
+ """``text`` as a string in a selector. The style sheet is written into the file as it is, so what would end
243
+ the string (a quote, a backslash) and what is markup in XML is said by its code, as CSS has it."""
244
+ return '"' + "".join(c if c.isprintable() and c not in '"\\<>&' else f"\\{ord(c):x} " for c in text) + '"'
245
+
246
+
247
+ def _tokens(residues: "dict[str, list[Group]]"
248
+ ) -> "tuple[dict[str, str], dict[str, tuple[str, list[str]]], dict[str, tuple[str, ...]]]":
249
+ """What each residue is called in the classes; for everything that ``data-active`` can say (a number, and
250
+ ``chain:number`` where more than one residue has the number), the name that it keeps and the residues that
251
+ are meant; and what a residue whose number another has is called as well.
252
+
253
+ A name follows from the residue alone, never from what else the figure holds: a page reads the rules of each
254
+ of its figures for all of them. So a residue whose number another has is named with its chain (``r25_A``), and
255
+ by the number alone too (``r25``), which is what every residue of that number answers to in any figure.
256
+ """
257
+ numbers: dict[str, list[str]] = {}
258
+ for n, (ident, groups) in enumerate(residues.items()):
259
+ numbers.setdefault(str(groups[0].data.get(NUMBER) or f"x{n}"), []).append(ident)
260
+ token: dict[str, str] = {}
261
+ numbered: dict[str, tuple[str, list[str]]] = {}
262
+ also: dict[str, tuple[str, ...]] = {}
263
+ for number, idents in numbers.items():
264
+ name = f"r{_name(number)}"
265
+ for ident in idents:
266
+ if len(idents) == 1:
267
+ token[ident] = name
268
+ continue
269
+ chain, colon, _ = ident.partition(":")
270
+ chain = chain if colon else ""
271
+ token[ident] = f"{name}_{_name(chain)}"
272
+ also[token[ident]] = (name,)
273
+ numbered[f"{chain}:{number}"] = (token[ident], [token[ident]])
274
+ numbered[number] = (name, list(dict.fromkeys(token[ident] for ident in idents)))
275
+ return token, numbered, also
276
+
277
+
278
+ def _asked_for(numbered: "dict[str, tuple[str, list[str]]]", shown: "set[str]", each: bool = False) -> str:
279
+ """The rules by which the page around a figure asks for what pointing at a residue is (``data-active``).
280
+
281
+ Each is said of a figure that has the residue: a page with several figures in it reads the rules of each for
282
+ all, and a figure without the residue is left as it is. ``each``: no rule is of more than one residue.
283
+ """
284
+ if not numbered:
285
+ return ""
286
+ root = f"svg.{ROOT_CLASS}"
287
+ # Said once, of a figure in which nothing is pointed at and nothing has the focus; what is asked for follows it.
288
+ # (The rules of pointing are the more specific ones, so where they speak of a group they win.)
289
+ rules = [f"{root}:not(:has(.lf-part:is(:hover,:focus))){{--lf-faint:{DIMMED:g};--lf-shown:inline}}"]
290
+ any_of = []
291
+ for said, (kept, whos) in numbered.items():
292
+ asked = f"{root}[{ACTIVE}={_quoted(said)}]"
293
+ here = f":has(.lf-t-{kept})"
294
+ any_of.append(f"[{ACTIVE}={_quoted(said)}]{here}")
295
+ rules.append(f"{asked}{here} .lf-part:not(.lf-o-{kept},.lf-p-{kept}){{opacity:var(--lf-faint,1)}}")
296
+ for w in whos:
297
+ if w in shown:
298
+ rules.append(f"{asked}:has(.lf-m-{w}) .lf-part.lf-o-{w}{{opacity:var(--lf-faint,1)}}"
299
+ f"{asked} .lf-m-{w}{{display:var(--lf-shown,none)}}")
300
+ heavy = f" .lf-part:is(.interaction,.contact) {_LINES}{{stroke-width:{HEAVY:g}px}}"
301
+ rules += [f"{root}{a}{heavy}" for a in any_of] if each else [f"{root}:is({','.join(any_of)}){heavy}"]
302
+ return "".join(rules)
303
+
304
+
305
+ def hooks_of_links(parts: "dict[str, list[Group]]", links: "list[tuple[Group, tuple[str, ...]]]") -> Hooks | None:
306
+ """The hooks of a figure that says itself what its parts and the links between them are, as
307
+ :class:`~bindview.BasePairs` does: ``parts`` maps a token (a nucleotide, the ligand) to its groups,
308
+ ``links`` gives each line its group and the tokens it joins. Pointing at a part keeps it, its links and
309
+ what they reach; pointing at a link (a click, as for a contact) keeps the link and its ends."""
310
+ if not parts:
311
+ return None
312
+ near: dict[str, set[str]] = {}
313
+ for _, ends in links:
314
+ for a in ends:
315
+ for b in ends:
316
+ if a != b:
317
+ near.setdefault(a, set()).add(b)
318
+ out = Hooks()
319
+ for who, groups in parts.items():
320
+ for g in groups:
321
+ out.classes[id(g)] = " ".join(["lf-part", f"lf-t-{who}", f"lf-o-{who}"]
322
+ + [f"lf-p-{t}" for t in sorted(near.get(who, ()))])
323
+ out.focus[id(g)] = 0
324
+ for g, ends in links:
325
+ out.classes[id(g)] = " ".join(["lf-part", f"lf-t-{ends[0]}"] + [f"lf-o-{t}" for t in ends])
326
+ out.focus[id(g)] = -1
327
+ root = f"svg.bindview.{ROOT_CLASS}"
328
+ rules = [f"{root} .lf-part{{transition:opacity .12s;cursor:pointer}}",
329
+ f"{root} .lf-part:focus:not(:focus-visible){{outline:none}}"]
330
+ for who in parts:
331
+ rules.append(f"{root}:is(:has(.lf-t-{who}:focus),:not(:has(.lf-part:focus)):has(.lf-t-{who}:hover)) "
332
+ f".lf-part:not(.lf-o-{who},.lf-p-{who}){{opacity:{DIMMED:g}}}")
333
+ out.css = "".join(rules)
334
+ return out