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/backends.py ADDED
@@ -0,0 +1,290 @@
1
+ """How a ligand is drawn: as atoms, or as a chain of residues.
2
+
3
+ A :class:`~bindview.ligand.Ligand` is the molecule as it was built from the
4
+ structure file: atoms with their names, bonds, coordinates. A *backend* decides
5
+ what a reader is shown of it and what a contact attaches to:
6
+
7
+ * :class:`SmallMolecule` -- every atom and bond, as a chemist draws a
8
+ structure.
9
+ * :class:`Polymer` -- the ligand as a chain of its residues, each a box on a
10
+ backbone; whatever is not a residue (a fatty acid, a cap) stays atoms and is
11
+ shown attached. A contact lands on the residue whose atom makes it.
12
+
13
+ Which one a ligand gets is decided by **what the molecule is, not by how big it
14
+ is** (:func:`bindview.peptide.decide`): a cobalamin of ninety atoms has no chain
15
+ of amino acids and is drawn as atoms; a peptide of twenty residues is drawn as
16
+ a chain. A caller can overrule the decision either way.
17
+
18
+ The layout engine, the audit, the graph and the two styles see a
19
+ :class:`~bindview.depict.Depiction` and do not know which backend made it.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ from typing import TYPE_CHECKING, Any, Protocol, Sequence, runtime_checkable
25
+
26
+ from rdkit import Chem
27
+
28
+ from .chem import quiet_rdkit
29
+ from .confidence import Confidence, Look
30
+ from .depict import Depiction, depict_ligand
31
+ from .ligand import Ligand
32
+ from .peptide import Decision, Peptide, decide, decide_given, perceive_peptide
33
+ from .polymer import depict_polymer
34
+ from .scene import Group
35
+ from .theme import Metrics, Palette
36
+
37
+ if TYPE_CHECKING: # pragma: no cover
38
+ from .graph import Graph
39
+
40
+ __all__ = ["LigandBackend", "SmallMolecule", "Polymer", "choose_backend", "BACKENDS"]
41
+
42
+ #: What ``ligand_as`` accepts.
43
+ BACKENDS = ("auto", "atoms", "chain")
44
+
45
+ NUMBERING_NOTE = ("Residues of the ligand are numbered by their position in its own chain, counted from its "
46
+ "N-terminus as read from its bonds; these are not positions in any sequence database.")
47
+
48
+
49
+ @runtime_checkable
50
+ class LigandBackend(Protocol):
51
+ """What the diagram needs from the way a ligand is drawn."""
52
+
53
+ kind: str # "atoms" | "chain"
54
+ ligand: Ligand
55
+ decision: Decision # why this backend, in a sentence a figure's notes can quote
56
+
57
+ def depict(self, metrics: Metrics, method: str = "auto") -> Depiction:
58
+ """Geometry of the ligand, laid out afresh."""
59
+
60
+ def depict_from(self, metrics: Metrics, graph: "Graph") -> Depiction:
61
+ """Geometry of the ligand where a graph has it."""
62
+
63
+ def draw(self, dep: Depiction, palette: Palette, metrics: Metrics,
64
+ confidence: "Confidence | None" = None, by_colour: bool = False, by_bond: bool = False
65
+ ) -> tuple[Group, set[int]]:
66
+ """The ligand as a scene group, and the confidence levels that occur in it. ``by_colour``: the
67
+ figure shows pLDDT by colour, so nothing of the ligand is drawn weaker for it; ``by_bond``: the
68
+ bonds of a ligand that is drawn as atoms have the colour."""
69
+
70
+ def bands(self, dep: Depiction, confidence: "Confidence") -> "list[str | None]":
71
+ """The pLDDT band of every depicted atom, for a figure that colours by it."""
72
+
73
+ def obstacles(self, dep: Depiction) -> list[tuple[float, float, float]]:
74
+ """Discs over ink of the ligand that is neither an atom label nor a bond."""
75
+
76
+ def footnotes(self, dep: "Depiction | None" = None) -> list[str]:
77
+ """Sentences the figure must carry because of how the ligand is drawn (``dep``: as it was drawn)."""
78
+
79
+
80
+ class SmallMolecule:
81
+ """The ligand as atoms and bonds, as a chemist draws a structure."""
82
+
83
+ kind = "atoms"
84
+
85
+ def __init__(self, ligand: Ligand, decision: Decision | None = None) -> None:
86
+ self.ligand = ligand
87
+ self.decision = decision or Decision(False, "it is drawn as atoms")
88
+
89
+ def depict(self, metrics: Metrics, method: str = "auto") -> Depiction:
90
+ return depict_ligand(self.ligand, metrics, method=method)
91
+
92
+ def depict_from(self, metrics: Metrics, graph: "Graph") -> Depiction:
93
+ from .graphbuild import depiction_from
94
+
95
+ return depiction_from(self.ligand, metrics, graph)
96
+
97
+ def draw(self, dep: Depiction, palette: Palette, metrics: Metrics,
98
+ confidence: "Confidence | None" = None, by_colour: bool = False, by_bond: bool = False
99
+ ) -> tuple[Group, set[int]]:
100
+ from .styles.ligand_draw import atom_looks, draw_ligand
101
+
102
+ looks: "Sequence[Look] | None" = (atom_looks(dep, confidence.ligand_atoms, by_colour)
103
+ if confidence is not None else None)
104
+ bands = [lk.band for lk in looks] if by_bond and looks else None
105
+ return draw_ligand(dep, palette, metrics, looks, bands), ({lk.level for lk in looks} if looks else set())
106
+
107
+ def bands(self, dep: Depiction, confidence: "Confidence") -> "list[str | None]":
108
+ """The pLDDT band of every depicted atom, for a figure that colours by it; ``None`` where the
109
+ model gives the atom no value."""
110
+ from .styles.ligand_draw import atom_looks
111
+
112
+ return [lk.band for lk in atom_looks(dep, confidence.ligand_atoms, True)]
113
+
114
+ def obstacles(self, dep: Depiction) -> list[tuple[float, float, float]]:
115
+ return []
116
+
117
+ def footnotes(self, dep: "Depiction | None" = None) -> list[str]:
118
+ return []
119
+
120
+
121
+ class Polymer:
122
+ """The ligand as a chain of residues, with what is not a residue drawn as atoms."""
123
+
124
+ kind = "chain"
125
+
126
+ def __init__(self, ligand: Ligand, peptide: Peptide, decision: Decision | None = None) -> None:
127
+ self.ligand = ligand
128
+ self.peptide = peptide
129
+ self.decision = decision or decide(peptide)
130
+ #: Set when the chain is the spine of an interface figure (:mod:`bindview.interface`): what the
131
+ #: legend and the footnotes say then (``legend``, ``notes``) and what goes into the graph (``meta``).
132
+ self.interface: Any = None
133
+ #: Set when the residues are not drawn in a column but where they lie on the plane through
134
+ #: them (:class:`bindview.plane.Arrangement`).
135
+ self.arrangement: Any = None
136
+ #: Which atoms of which residue stand beside its box as atoms (position -> atoms), and on
137
+ #: which side its side chain does (position -> +1 or -1). The diagram sets both from the
138
+ #: contacts it draws and from ``peptide.detail`` before the chain is depicted
139
+ #: (:func:`bindview.polymer.shown_atoms`, :func:`bindview.polymer.piece_sides`).
140
+ self.shown: dict[int, tuple[int, ...]] = {}
141
+ self.sides: dict[int, int] = {}
142
+ #: What is written on them (``RenderOptions.atom_labels``).
143
+ self.atom_labels = "names"
144
+
145
+ def depict(self, metrics: Metrics, method: str = "auto") -> Depiction:
146
+ return depict_polymer(self.ligand, self.peptide, metrics, method=method, plane=self.arrangement,
147
+ shown=self.shown, sides=self.sides, labels=self.atom_labels)
148
+
149
+ def depict_from(self, metrics: Metrics, graph: "Graph") -> Depiction:
150
+ from .graphbuild import polymer_positions
151
+
152
+ units, atoms = polymer_positions(graph)
153
+ scale = None
154
+ if self.arrangement is not None:
155
+ stored = (graph.meta.get("interface") or {}).get("plane") or {}
156
+ scale = stored.get("px_per_angstrom")
157
+ return depict_polymer(self.ligand, self.peptide, metrics, unit_xy=units, exact=atoms,
158
+ plane=self.arrangement, scale=scale, shown=self.shown, sides=self.sides, labels=self.atom_labels)
159
+
160
+ def draw(self, dep: Depiction, palette: Palette, metrics: Metrics,
161
+ confidence: "Confidence | None" = None, by_colour: bool = False, by_bond: bool = False
162
+ ) -> tuple[Group, set[int]]:
163
+ from .styles.ligand_draw import atom_looks
164
+ from .styles.polymer_draw import draw_polymer, unit_looks
165
+
166
+ if confidence is None:
167
+ return draw_polymer(dep, palette, metrics, deposited=self.deposited), set()
168
+ looks = atom_looks(dep, confidence.ligand_atoms, by_colour)
169
+ units = unit_looks(dep, confidence.ligand_atoms, by_colour)
170
+ if by_colour:
171
+ # Nothing is drawn weaker for its pLDDT: the boxes are filled, and the atoms stand on colour.
172
+ return draw_polymer(dep, palette, metrics, looks, units, deposited=self.deposited,
173
+ by_colour=True), {0}
174
+ outside = {looks[a.idx].level for a in dep.atoms if dep.unit_of(a.idx) is None}
175
+ # An atom that stands beside its residue's box: at its own value where the model gives the atoms
176
+ # of a residue values of their own, at its residue's where it gives one for the residue.
177
+ own = {i: (looks[i] if confidence.per_atom else units[u.index]) for u in dep.units for i in u.beside}
178
+ return (draw_polymer(dep, palette, metrics, looks, units, deposited=self.deposited, own=own),
179
+ outside | {u.level for u in units} | {lk.level for lk in own.values()})
180
+
181
+ def bands(self, dep: Depiction, confidence: "Confidence") -> "list[str | None]":
182
+ """The pLDDT band of every depicted atom, for a figure that colours by it: an atom's own, and
183
+ for an atom beside its residue's box the residue's where the model gives one value for a residue."""
184
+ from .styles.ligand_draw import atom_looks
185
+ from .styles.polymer_draw import unit_looks
186
+
187
+ bands = [lk.band for lk in atom_looks(dep, confidence.ligand_atoms, True)]
188
+ if not confidence.per_atom:
189
+ units = unit_looks(dep, confidence.ligand_atoms, True)
190
+ for u in dep.units:
191
+ for i in u.beside:
192
+ bands[i] = units[u.index].band
193
+ return bands
194
+
195
+ def obstacles(self, dep: Depiction) -> list[tuple[float, float, float]]:
196
+ from .styles.polymer_draw import chain_obstacles
197
+
198
+ return chain_obstacles(dep)
199
+
200
+ @property
201
+ def deposited(self) -> bool:
202
+ """Are the residues' numbers those of the structure file (and not a count made here)?"""
203
+ return self.peptide.numbering == "deposited"
204
+
205
+ def footnotes(self, dep: "Depiction | None" = None) -> list[str]:
206
+ if self.interface is not None:
207
+ return list(self.interface.said(dep))
208
+ if self.deposited:
209
+ chain = f" (chain {self.ligand.chain})" if self.ligand.chain else ""
210
+ return [f"Residues of the ligand carry the names and numbers of the structure file{chain}."]
211
+ return [NUMBERING_NOTE]
212
+
213
+ def legend_text(self) -> str:
214
+ """What the legend says a box is, and whose its number is."""
215
+ if self.interface is not None:
216
+ return str(self.interface.legend)
217
+ return ("Residue of the ligand, numbered as in the structure file" if self.deposited
218
+ else "Residue of the ligand, numbered from its own N-terminus")
219
+
220
+ def residue_label(self, atom: int) -> str | None:
221
+ """``Lys20`` for an atom of the chain, ``None`` for one outside it."""
222
+ res = self.peptide.residue_of(atom)
223
+ return None if res is None else f"{res.code3}{res.shown}"
224
+
225
+ def part_of(self, atoms: Sequence[int]) -> str:
226
+ """``backbone``, ``side chain`` or ``outside the chain``: where in the ligand these atoms are.
227
+ Of a nucleotide the base is what a side chain is of an amino acid, and is called ``base``."""
228
+ residues = [self.peptide.residue_of(a) for a in atoms]
229
+ if any(r is None for r in residues):
230
+ return "outside the chain"
231
+ if all(r.is_backbone(a) for r, a in zip(residues, atoms) if r is not None):
232
+ return "backbone"
233
+ return "base" if all(r is not None and r.kind == "nucleotide" for r in residues) else "side chain"
234
+
235
+
236
+ def _reference(ligand: Ligand) -> Chem.Mol | None:
237
+ """The molecule the ligand was specified as, for its stereochemistry: a model can invert a centre."""
238
+ if not ligand.smiles or ligand.bond_source != "template":
239
+ return None
240
+ with quiet_rdkit():
241
+ return Chem.MolFromSmiles(ligand.smiles)
242
+
243
+
244
+ def choose_backend(ligand: Ligand, ligand_as: str = "auto") -> "SmallMolecule | Polymer":
245
+ """The backend for a ligand: by what it is (``auto``), or as the caller says.
246
+
247
+ ``chain`` for a ligand that has no chain of residues at all is an error:
248
+ there is nothing to draw as one.
249
+ """
250
+ if ligand_as not in BACKENDS:
251
+ raise ValueError(f"ligand_as must be one of {', '.join(BACKENDS)}, not {ligand_as!r}")
252
+ if ligand_as == "atoms" and ligand.n_atoms < 2:
253
+ return SmallMolecule(ligand)
254
+ peptide: Peptide | None = None
255
+ if ligand.given:
256
+ # A chain of its own in the structure file: its residues are given, not perceived.
257
+ from .chains import given_peptide
258
+
259
+ with quiet_rdkit():
260
+ peptide = given_peptide(ligand.mol, ligand.names, ligand.given)
261
+ decision = decide_given(peptide)
262
+ else:
263
+ if ligand.bond_source != "single-atom":
264
+ with quiet_rdkit():
265
+ peptide = perceive_peptide(ligand.mol, stereo_from=_reference(ligand))
266
+ decision = decide(peptide)
267
+ if ligand_as == "atoms":
268
+ return SmallMolecule(ligand, Decision(False, "it was asked to be drawn as atoms", decision.longest_run,
269
+ decision.recognised, found=decision.polymer))
270
+ if ligand_as == "chain":
271
+ if peptide is None:
272
+ raise ValueError("this ligand cannot be drawn as a chain: " + decision.reason)
273
+ return Polymer(ligand, peptide, Decision(True, "it was asked to be drawn as a chain", decision.longest_run,
274
+ decision.recognised, found=decision.polymer))
275
+ if decision.polymer and peptide is not None:
276
+ return Polymer(ligand, peptide, decision)
277
+ return SmallMolecule(ligand, decision)
278
+
279
+
280
+ def describe(backend: Any) -> dict[str, Any]:
281
+ """The backend as plain data, for a result or a graph."""
282
+ out: dict[str, Any] = {"drawn_as": backend.kind, "why": backend.decision.reason}
283
+ if isinstance(backend, Polymer):
284
+ pep = backend.peptide
285
+ out.update({"residues": len(pep), "sequence": pep.sequence, "cyclic": pep.cyclic,
286
+ "numbering": ("as deposited in the structure file" if backend.deposited
287
+ else "position in the ligand's own chain, from its N-terminus"),
288
+ "numbering_origin": pep.numbering,
289
+ "atoms_outside_the_chain": pep.n_atoms - pep.in_chain})
290
+ return out