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/report.py ADDED
@@ -0,0 +1,1407 @@
1
+ """What an input holds, and the figures that go with it: ``bindview report``.
2
+
3
+ Nobody says whether the input is a small molecule in a pocket, a peptide, an interface or an ensemble:
4
+ the report looks, draws the figure for what it finds, and prints the call that drew it. That call is the
5
+ manual mode: copy it and change it.
6
+
7
+ bindview report INPUT [-o report.html] [--smiles NAME=SMILES ...] [--domain NAME=CHAIN:FROM-TO ...]
8
+ [--each] [--one-view] [--look]
9
+
10
+ from bindview.report import survey
11
+
12
+ found = survey("model.cif") # what the input holds, and the figures that follow: nothing drawn
13
+ found.draw() # runs the call of every figure
14
+ page = found.html() # one page, each figure under its call
15
+
16
+ INPUT is a model (mmCIF or PDB, gzipped or not) or a folder that holds one. What lies beside the model is
17
+ used: a table of contacts, a file of predicted aligned errors, a ``meta.json``. A small molecule is drawn
18
+ from a table beside the model, else with PLIP where it is installed, else from the table of heavy atoms
19
+ (:func:`bindview.distance_table.ligand_contacts`), which is cruder than PLIP and says so. A peptide chain
20
+ and an interface are drawn from the plain distance table of the same module. A call names its files from
21
+ the folder of the input and is run there, so a page is the same wherever the report is run.
22
+
23
+ The rules:
24
+
25
+ R1 A folder's models are the mmCIF and PDB files directly in it. One: that is the complex. Several: they
26
+ are a set (R1b, R1c).
27
+ R1b A folder that holds no model of its own and subfolders that hold one model each: the subfolders are the
28
+ members of a set. A subfolder with several models is no member, and the page names it.
29
+ R1c A set of one composition is an ensemble: the first member by name is read as the complex, and all of
30
+ them are counted (R9). A composition is the chains with their names, kinds and residue counts, and every
31
+ other residue with its name, its number of copies, its heavy-atom formula and the file's own SMILES. Else,
32
+ where the first protein chain of every member has the same sequence but for a tenth and every member
33
+ has exactly one small molecule, the set is a series of ligands on one protein and is drawn as a
34
+ comparison. Else it is refused, and the refusal names ``--each`` (R16).
35
+ R2 A residue is of a protein chain when it has N, CA and C and is bonded through them to a neighbour
36
+ (N and C within 1.6 A), or when it is written as ATOM and named as an amino acid, however much of it
37
+ is modelled. A peptide is a protein chain of 2 to 50 residues.
38
+ R2b A protein chain of 2 to 50 residues with a heavy atom within bonding distance of another protein
39
+ chain (a disulfide, say) is a part of that protein and no peptide: listed, not drawn as a ligand.
40
+ R2c A nucleic chain is what the library takes for one: a chain without a residue of R2 and with two or
41
+ more nucleotides joined to one another. A residue of such a chain that is written as ATOM and named as
42
+ a nucleotide belongs to it, however much of it is modelled. From 3 to 50 nucleotides it is an
43
+ oligonucleotide.
44
+ R3 Every other residue that is not water is a candidate ligand: a cap (ACE, NH2, NME, FOR within bonding
45
+ distance of a chain), an ion (one heavy atom), an additive (a fixed list of what crystals and buffers
46
+ bring), a sugar (a fixed list, bonded to the chain), or a small molecule (the rest). Residues of one
47
+ name are copies of one ligand; the copy with the most heavy atoms stands for them.
48
+ R4 Drawn: every small molecule, the largest first, six at most; ions only where there is no small
49
+ molecule and no chain that is drawn as a ligand (R7, R7b), three at most. The others are listed with
50
+ the selection that would draw them.
51
+ R5 A table beside the model belongs to a candidate when every ligand atom it names is an atom of the
52
+ candidate; of several copies it is the one within 6 A of the first residue the table names. The table
53
+ that is named after the model (``<model>.interactions.tsv``) comes first, and one that is named after
54
+ another model of the folder is not read. A table that names no ligand atom comes last and is taken
55
+ where the model has one ligand only. Without a table, PLIP where it can be imported, with the nucleic
56
+ acid as the receptor when no protein atom and a nucleotide lie within 6 A. Without either, the table
57
+ of heavy atoms. A file beside the model that cannot be read as a table is named on the page.
58
+ R6 The SMILES: as handed in, else the file's own, else a ``meta.json`` beside the model that names the
59
+ candidate, else none (the library then draws the connectivity and says so).
60
+ R7 A peptide is drawn as the ligand with the plain distance table, unless a table beside the model
61
+ names atoms the way a chain ligand's are named (``63/OE1``): the first such table by name is taken,
62
+ for every chain that is drawn as a ligand. Three at most, the shortest first.
63
+ R7b An oligonucleotide is drawn as the ligand, like a peptide, where the complex has a protein chain of
64
+ more than 50 residues. Peptides and oligonucleotides together: three at most, the shortest first.
65
+ Its partners are the residues of the protein chains: what it pairs with in another nucleic chain
66
+ is in the interface of the two (R8b).
67
+ R8 An interface is drawn for every pair of protein chains of more than 50 residues for which the plain
68
+ distance table has a row; three at most, those with the most rows first. A file of predicted
69
+ aligned errors beside the model goes in: ``*confidences.json`` (not the summary), the AlphaFold database's
70
+ ``*predicted_aligned_error*.json``, each gzipped or not, or ``pae_<model>.npz``.
71
+ R8b Interfaces are between chains of more than 50 residues, protein or nucleic, and between any two
72
+ nucleic chains that touch, whatever their length. Three at most.
73
+ R9 An ensemble is the models of one file, or the members of a set of one composition (R1c). It is drawn
74
+ for the largest small molecule from a table for every model (``model_NN.interactions.tsv`` by the
75
+ model's number; for files of one folder ``<file>.interactions.tsv``; for members in folders of their
76
+ own the table beside each, R5), else with PLIP for 25 models at most, else from the table of heavy
77
+ atoms, model by model.
78
+ R10 Confidence is the library's business. The report says what it saw (a declared pLDDT, a file of
79
+ predicted aligned errors, a summary of the model's scores) and hands on two things: the file of
80
+ predicted aligned errors to an interface (R8, R12), and ``plddt_colors=True`` to one view (R15).
81
+ R11 The page has what the input holds first, then the figures in the order of these rules (small
82
+ molecules or ions, chains as ligands, interfaces, each pair of nucleic chains followed by its base
83
+ pairs, parts, the ensemble), then what was found and has no figure, with the reason.
84
+ R12 Where a ``meta.json`` beside the model names the parts of one chain (``chain``, and
85
+ ``participants`` with ``name`` and ``residues``), or the caller does (``--domain
86
+ NAME=CHAIN:FROM-TO``, at least two), each part gets a chain name of its own and the interface of
87
+ every pair of parts that touches is drawn, with the PAE file where there is one. Three at most.
88
+ A part that cannot be cut out of its chain is refused where the caller named it, and is a line of
89
+ the page where a ``meta.json`` did.
90
+ R13 What is drawn from the plain distance table (a peptide, an oligonucleotide, an interface, two
91
+ parts) asks for ring stacking (``stacking=True``), and the rows a pair is ranked by are counted
92
+ with it.
93
+ R14 A figure whose call asks for the detailed style and comes back unreadable is drawn again by the
94
+ same call in the schematic style. Where that one is drawn (ok or degraded), it is shown, its call is
95
+ printed, and the page says what the detailed style said; else the detailed figure stays, with the
96
+ library's summary in its place. A call that names no style (an ensemble, a series, base pairs) is
97
+ left as it is.
98
+ R15 Views. Where a figure's call names a style and its figure is ok or degraded, the same object is drawn
99
+ again, each time by a last line of its own that the page prints above it: in the other style (not
100
+ where R14 left the detailed style for being unreadable); with pLDDT in AlphaFold's colours
101
+ (``plddt_colors=True``), where the file declares a pLDDT; and as a figure that answers the pointer
102
+ (``interactive=True``). The first figure is what it was. A view that comes back unreadable, empty
103
+ or refused is not shown: the page names it and what the library said. ``views=False``
104
+ (``--one-view``) draws the first figure alone. A call that names no style (an ensemble, a series)
105
+ has no views.
106
+ R16 Each, for a set to screen. With ``--each`` (:func:`write_each`) the members of a folder (R1, R1b) are
107
+ not read as one input: each is surveyed and drawn as an input of its own (R2 to R15, R17) and gets a
108
+ page of its own, and an index lists them, one row a member, in the order of their names: its name and
109
+ a link to its page; its figures, each with its status; for its first figure that is drawn, the
110
+ contacts by kind, ipTM, pocket and ligand pLDDT where the model gives them, the buried fraction, and
111
+ how many warnings the library gave. A member that cannot be read, that the library refuses, or that
112
+ holds nothing to draw, is a row that says so, and so is a subfolder that is no member (R1b). The index
113
+ is written as a page and as a CSV of the same rows. Without ``--each`` a folder whose members are
114
+ neither one complex nor one series is refused, and the refusal names ``--each``.
115
+ R17 Base pairs. After each interface of two nucleic chains that R8b draws, the two chains are drawn again
116
+ as their base pairs (:class:`~bindview.BasePairs`). The pairs: the PDB's own annotation where the model
117
+ is an mmCIF that has pairs of these chains; else RNApolis's JSON beside the model
118
+ (``<model>.rnapolis.json``, or ``basepairs.rnapolis.json``), with its stacks; else the stand-in of the
119
+ plain distance table, across and within each strand, without a family, which the page says. The other
120
+ hydrogen bonds across, and the stacks where the annotation has none, come from the plain table. The
121
+ first small molecule of R4 with a heavy atom within 4.0 A of either chain stands beside the pairs, its
122
+ contacts from the table R5 gives it, else from the plain table. Its one view (R15) is the figure that
123
+ answers the pointer: it has no style to change and no pLDDT to colour.
124
+
125
+ Limits: a short subunit that is not bonded to its protein is taken for a peptide; two ligands of one
126
+ formula without a SMILES in their files are taken for one; the copies of one complex in a crystal touch
127
+ one another, and those contacts are drawn as interfaces like any other; a model named ``.mmcif.gz`` is
128
+ not asked for the PDB's own base pairs (R17).
129
+ """
130
+
131
+ from __future__ import annotations
132
+
133
+ import contextlib
134
+ import csv
135
+ import difflib
136
+ import html
137
+ import importlib.util
138
+ import io
139
+ import json
140
+ import os
141
+ import urllib.parse
142
+ from collections import Counter
143
+ from contextvars import ContextVar
144
+ from dataclasses import dataclass, field
145
+ from pathlib import Path
146
+ from typing import Any, Iterator, Mapping, Sequence
147
+
148
+ import numpy as np
149
+
150
+ from . import __version__
151
+ from .distance_table import interface_contacts
152
+ from .errors import BindviewError, StructureError
153
+ from .exposure import WATER_NAMES
154
+ from .interactions import NOT_GIVEN_OR_A_NAME, Interaction, load_interactions
155
+ from .near import pairs_within
156
+ from .residues import is_nucleotide, template_for
157
+ from .structure import Structure, read_models, read_structure
158
+
159
+ __all__ = ["survey", "write_each", "Survey", "Track", "View", "Row", "Found", "Chain", "Candidate", "Beside",
160
+ "Member"]
161
+
162
+ MODEL_SUFFIXES = (".cif", ".mmcif", ".pdb", ".ent")
163
+ ADDITIVES = frozenset("GOL EDO PEG PGE PG4 1PE P6G 2PE MPD DMS ACT ACY FMT SO4 PO4 NO3 CIT TRS MES EPE BME DTT "
164
+ "IPA EOH IMD NH4 SCN BU3 TLA MLI".split())
165
+ SUGARS = frozenset("NAG NDG MAN BMA FUC FUL GAL GLA GLC BGC XYP SIA".split())
166
+ CAPS = frozenset({"ACE", "NH2", "NME", "FOR"})
167
+ PEPTIDE = (2, 50) # R2: residues of a chain that is a peptide
168
+ OLIGO = (3, 50) # R2c: nucleotides of a chain that is an oligonucleotide
169
+ SAME_PROTEIN = 0.9 # R1c: the share of two sequences that has to agree
170
+ NEAR = 6.0 # R5: angstrom
171
+ BESIDE_PAIRS = 4.0 # R17: angstrom from a strand for a small molecule to stand beside the pairs
172
+ PEPTIDE_BOND = 1.6 # R2: angstrom between N and C of two residues that are one chain
173
+ BOND, BOND_HEAVY = 1.9, 2.3 # R3: bonded to the chain; the longer where S, P or Se is one of the two
174
+ #: R16: the kinds of contact an index counts, in its order, and what it calls them.
175
+ KINDS = ("hbond", "saltbridge", "pi_stacking", "pi_cation", "halogen", "metal", "water_bridge", "hydrophobic")
176
+ KIND_NAMES = {"hbond": "H-bond", "saltbridge": "salt bridge", "pi_stacking": "\u03c0-stacking",
177
+ "pi_cation": "\u03c0-cation", "halogen": "halogen bond", "metal": "metal", "water_bridge": "water bridge",
178
+ "hydrophobic": "hydrophobic"}
179
+ MOST: Mapping[str, int] = {"small molecule": 6, "ion": 3, "peptide": 3, "interface": 3, "models": 25}
180
+ DETAILED, SCHEMATIC = 'style="detailed"', 'style="schematic"' # R14: in the last line of a call
181
+ SUMMARY = "; a per-residue summary was drawn instead" # R14: the library's words for what it replaces
182
+
183
+
184
+ # ---------------------------------------------------------------------------
185
+ # What the input holds
186
+ # ---------------------------------------------------------------------------
187
+
188
+ @dataclass
189
+ class Chain:
190
+ name: str
191
+ kind: str # protein | nucleic | "" (no polymer: it only carries other residues)
192
+ residues: int
193
+ sequence: tuple[str, ...] = () # the names of its residues, in the order of the file
194
+ joined: str = "" # R2b: the protein chain a short protein chain is bonded to
195
+
196
+ @property
197
+ def peptide(self) -> bool:
198
+ return self.kind == "protein" and PEPTIDE[0] <= self.residues <= PEPTIDE[1] and not self.joined
199
+
200
+ @property
201
+ def oligo(self) -> bool:
202
+ return self.kind == "nucleic" and OLIGO[0] <= self.residues <= OLIGO[1]
203
+
204
+ @property
205
+ def what(self) -> str:
206
+ """The chain in words, for the page."""
207
+ if self.peptide:
208
+ return "a peptide"
209
+ if self.joined:
210
+ return f"protein, joined to chain {self.joined}"
211
+ if self.oligo:
212
+ return "an oligonucleotide"
213
+ return self.kind or "no polymer: it carries other residues"
214
+
215
+
216
+ @dataclass
217
+ class Candidate:
218
+ """A residue outside the chains that could be the ligand."""
219
+
220
+ name: str
221
+ chain: str
222
+ number: int
223
+ heavy: int
224
+ kind: str # ion | cap | additive | sugar | small molecule
225
+ bonded: bool # an atom of it lies within bonding distance of a chain
226
+ atoms: frozenset[str]
227
+ xyz: np.ndarray
228
+ copies: int = 1
229
+ formula: str = "" # its heavy atoms by element: C25F3N7O2
230
+
231
+ @property
232
+ def spec(self) -> str:
233
+ """The residue as ``Diagram.from_structure(ligand=...)`` takes it."""
234
+ return f"{self.chain}:{self.name}:{self.number}"
235
+
236
+
237
+ @dataclass
238
+ class Found:
239
+ """What one model holds."""
240
+
241
+ chains: list[Chain]
242
+ candidates: list[Candidate] # one for each name, the largest first
243
+ copies: dict[str, list[Candidate]] # name -> every copy
244
+ waters: int
245
+ plddt: bool
246
+ smiles_in_file: dict[str, str]
247
+
248
+
249
+ @dataclass
250
+ class Beside:
251
+ """What lies beside a model."""
252
+
253
+ #: ``(path, rows, the ligand atoms it names, whether those are a chain ligand's names)``
254
+ tables: list[tuple[Path, list[Interaction], set[str], bool]] = field(default_factory=list)
255
+ #: The ``.tsv`` and ``.csv`` files that are no table of contacts, each with the reason: the page names them.
256
+ not_tables: list[tuple[Path, str]] = field(default_factory=list)
257
+ pae: Path | None = None
258
+ summary: Path | None = None
259
+ meta: dict[str, Any] | None = None
260
+
261
+
262
+ @dataclass
263
+ class Member:
264
+ """One complex of a set: a ligand of a series."""
265
+
266
+ name: str
267
+ model: Path
268
+ ligand: Candidate
269
+ table: Path | None # the table of contacts beside the model that is the ligand's
270
+ smiles: str | None # to hand in; None where the file has its own, or there is none
271
+ smiles_from: str
272
+
273
+
274
+ @dataclass
275
+ class View:
276
+ """R15: the object of a figure drawn once more, by a last line of its own."""
277
+
278
+ title: str
279
+ line: str # the last line that draws it, run where the figure's call ran
280
+ svg: str = ""
281
+ status: str = ""
282
+ said: list[str] = field(default_factory=list)
283
+
284
+
285
+ @dataclass
286
+ class Track:
287
+ """One figure of the report: what was seen, and the call that draws it."""
288
+
289
+ kind: str # ligand | ion | peptide | oligonucleotide | interface | basepairs | ensemble | series | parts
290
+ title: str
291
+ why: str # what was seen that makes it this figure
292
+ code: str # the call, as source: it is run, and printed
293
+ svg: str = ""
294
+ status: str = ""
295
+ said: list[str] = field(default_factory=list)
296
+ schematic: bool = False # R14: drawn in the schematic style because the detailed one is unreadable
297
+ views: list[View] = field(default_factory=list) # R15
298
+ #: R16: what an index says of the figure: contacts by kind, confidence, buried fraction, warnings.
299
+ facts: dict[str, Any] = field(default_factory=dict)
300
+
301
+
302
+ def _stem(model: Path) -> str:
303
+ name = model.name[:-3] if model.name.endswith(".gz") else model.name
304
+ return name.rsplit(".", 1)[0]
305
+
306
+
307
+ def look(st: Structure) -> Found:
308
+ """R2 and R3: the chains of a structure, and what else it holds."""
309
+ keys = st.residues()
310
+ names_of = {k: {a.name for a in st.residue_atoms(k)} for k in keys}
311
+ whole = [k for k in keys if {"N", "CA", "C"} <= names_of[k]]
312
+ backbone = set()
313
+ if len(whole) > 1:
314
+ def at(k: Any, name: str) -> tuple[float, float, float]:
315
+ atom = st.atom_by_name(k, name)
316
+ assert atom is not None # a residue of ``whole`` has N, CA and C
317
+ return atom.xyz
318
+
319
+ n_at = np.array([at(k, "N") for k in whole], dtype=float)
320
+ c_at = np.array([at(k, "C") for k in whole], dtype=float)
321
+ of_n, of_c, _ = pairs_within(n_at, c_at, PEPTIDE_BOND)
322
+ joined = of_n != of_c # (a residue's own N and C are no peptide bond)
323
+ backbone = {whole[i] for i in set(of_n[joined].tolist()) | set(of_c[joined].tolist())}
324
+ for k in keys:
325
+ named = template_for(st.residue_name(k))
326
+ if named is not None and named.kind == "amino" and not any(a.hetero for a in st.residue_atoms(k)):
327
+ backbone.add(k)
328
+ order = list(dict.fromkeys(k.chain for k in keys))
329
+ chains: list[Chain] = []
330
+ in_chain: set[Any] = set()
331
+ of_chain: dict[str, list[Any]] = {}
332
+ for c in order:
333
+ own = [k for k in keys if k.chain == c]
334
+ protein = [k for k in own if k in backbone]
335
+ nucleic = [] if protein else st._nucleotides(c) # R2c: nucleotides joined to one another
336
+ if len(nucleic) >= 2: # and those of which little is modelled
337
+ joined = set(nucleic)
338
+ nucleic = [k for k in own if k in joined or (is_nucleotide(st.residue_name(k))
339
+ and not any(a.hetero for a in st.residue_atoms(k)))]
340
+ if protein:
341
+ chains.append(Chain(c, "protein", len(protein), tuple(st.residue_name(k) for k in protein)))
342
+ in_chain.update(protein)
343
+ of_chain[c] = protein
344
+ elif len(nucleic) >= 2:
345
+ chains.append(Chain(c, "nucleic", len(nucleic), tuple(st.residue_name(k) for k in nucleic)))
346
+ in_chain.update(nucleic)
347
+ else:
348
+ chains.append(Chain(c, "", 0))
349
+
350
+ def heavy_of(k: Any) -> list[Any]:
351
+ return [a for a in st.residue_atoms(k) if a.element not in ("H", "D")]
352
+
353
+ # R2b: a short protein chain that is bonded to another protein chain is a part of that protein.
354
+ for chain in chains:
355
+ if chain.kind != "protein" or not PEPTIDE[0] <= chain.residues <= PEPTIDE[1]:
356
+ continue
357
+ mine = [a for k in of_chain[chain.name] for a in heavy_of(k)]
358
+ here = np.array([a.xyz for a in mine], dtype=float)
359
+ big = np.array([a.element.upper() in ("S", "P", "SE") for a in mine], dtype=bool)
360
+ low, high = here.min(axis=0) - BOND_HEAVY, here.max(axis=0) + BOND_HEAVY
361
+ for other in chains:
362
+ if other.kind != "protein" or other.name == chain.name:
363
+ continue
364
+ theirs = [a for k in of_chain[other.name] for a in heavy_of(k)
365
+ if low[0] <= a.x <= high[0] and low[1] <= a.y <= high[1] and low[2] <= a.z <= high[2]]
366
+ if not theirs:
367
+ continue
368
+ d = np.linalg.norm(here[:, None, :] - np.array([a.xyz for a in theirs], dtype=float)[None, :, :], axis=2)
369
+ big2 = np.array([a.element.upper() in ("S", "P", "SE") for a in theirs], dtype=bool)
370
+ if (d < np.where(big[:, None] | big2[None, :], BOND_HEAVY, BOND)).any():
371
+ chain.joined = other.name
372
+ break
373
+
374
+ chain_atoms = [a for k in keys if k in in_chain for a in heavy_of(k)]
375
+ chain_xyz = np.array([a.xyz for a in chain_atoms], dtype=float).reshape(-1, 3)
376
+ chain_big = np.array([a.element.upper() in ("S", "P", "SE") for a in chain_atoms], dtype=bool)
377
+
378
+ def is_bonded(atoms: list[Any]) -> bool:
379
+ if not len(chain_xyz):
380
+ return False
381
+ d = np.linalg.norm(np.array([a.xyz for a in atoms], dtype=float)[:, None, :] - chain_xyz[None, :, :], axis=2)
382
+ big = np.array([a.element.upper() in ("S", "P", "SE") for a in atoms], dtype=bool)
383
+ return bool((d < np.where(big[:, None] | chain_big[None, :], BOND_HEAVY, BOND)).any())
384
+
385
+ copies: dict[str, list[Candidate]] = {}
386
+ waters = 0
387
+ for k in keys:
388
+ name = st.residue_name(k)
389
+ if name.upper() in WATER_NAMES:
390
+ waters += 1
391
+ continue
392
+ if k in in_chain:
393
+ continue
394
+ heavy = heavy_of(k)
395
+ if not heavy:
396
+ continue
397
+ bonded = is_bonded(heavy)
398
+ kind = ("cap" if name in CAPS and bonded else "ion" if len(heavy) == 1 # (the cap NH2 is one atom too)
399
+ else "additive" if name in ADDITIVES else "sugar" if name in SUGARS and bonded
400
+ else "small molecule")
401
+ elements = Counter(a.element.capitalize() for a in heavy)
402
+ copies.setdefault(name, []).append(Candidate(
403
+ name, k.chain, k.number, len(heavy), kind, bonded, frozenset(a.name for a in heavy),
404
+ np.array([a.xyz for a in heavy], dtype=float),
405
+ formula="".join(f"{e}{n if n > 1 else ''}" for e, n in sorted(elements.items()))))
406
+ candidates = []
407
+ for group in copies.values():
408
+ first = max(group, key=lambda c: c.heavy) # the first in the file among equals
409
+ first.copies = len(group)
410
+ candidates.append(first)
411
+ candidates.sort(key=lambda c: -c.heavy)
412
+ return Found(chains, candidates, copies, waters, bool(st.declares_plddt), dict(st.chem_comp_smiles))
413
+
414
+
415
+ def _composition(found: Found) -> tuple[Any, ...]:
416
+ """R1c: what a model is made of. Two co-folds name every ligand alike, so a residue outside the chains
417
+ counts with its formula and with the SMILES its file gives it."""
418
+ return (tuple((c.name, c.kind, c.residues) for c in found.chains),
419
+ tuple(sorted((name, len(group), group[0].formula, found.smiles_in_file.get(name, ""))
420
+ for name, group in found.copies.items())))
421
+
422
+
423
+ def _is_model(p: Path) -> bool:
424
+ name = p.name[:-3] if p.name.endswith(".gz") else p.name
425
+ return p.is_file() and name.lower().endswith(MODEL_SUFFIXES)
426
+
427
+
428
+ def _members(path: Path) -> list[tuple[str, Path]]:
429
+ """R1 and R1b: the models of an input, each with the name it has in a set."""
430
+ if not path.is_dir():
431
+ return [(_stem(path), path)] if _is_model(path) else []
432
+ own = sorted(p for p in path.iterdir() if _is_model(p))
433
+ if own:
434
+ return [(_stem(p), p) for p in own]
435
+ out = []
436
+ for sub in sorted(p for p in path.iterdir() if p.is_dir()):
437
+ models = sorted(p for p in sub.iterdir() if _is_model(p))
438
+ if len(models) == 1:
439
+ out.append((sub.name, models[0]))
440
+ return out
441
+
442
+
443
+ def _passed_over(path: Path) -> list[tuple[Path, list[str]]]:
444
+ """R1b: the subfolders of a set that are no member of it, each with the models it holds: more than one."""
445
+ if not path.is_dir() or any(_is_model(p) for p in path.iterdir()):
446
+ return []
447
+ out = []
448
+ for sub in sorted(p for p in path.iterdir() if p.is_dir()):
449
+ models = sorted(p.name for p in sub.iterdir() if _is_model(p))
450
+ if len(models) > 1:
451
+ out.append((sub, models))
452
+ return out
453
+
454
+
455
+ _ONE_MODEL = "a member of a set is a folder with one model: name this folder by itself to have it read"
456
+
457
+
458
+ def _named(models: Sequence[str]) -> str:
459
+ return ", ".join(models[:4]) + (" and more" if len(models) > 4 else "")
460
+
461
+
462
+ def _one_protein(looks: Sequence[Found]) -> bool:
463
+ """R1c: do the first protein chains of all members have one sequence, but for a tenth?"""
464
+ firsts = [next((c for c in f.chains if c.kind == "protein"), None) for f in looks]
465
+ if any(c is None for c in firsts):
466
+ return False
467
+ ref = firsts[0].sequence if firsts[0] is not None else ()
468
+ return all(c is not None and difflib.SequenceMatcher(None, ref, c.sequence, autojunk=False).ratio() >= SAME_PROTEIN
469
+ for c in firsts[1:])
470
+
471
+
472
+ def _beside(model: Path) -> Beside:
473
+ out = Beside()
474
+ # R5: a table that is named after a model is that model's: its own comes first, another model's is not read.
475
+ own = f"{_stem(model)}.interactions.tsv"
476
+ others = {f"{_stem(p)}.interactions.tsv" for p in model.parent.iterdir() if p != model and _is_model(p)} - {own}
477
+ for p in sorted(model.parent.iterdir(), key=lambda p: (p.name != own, p)):
478
+ low = p.name.lower()
479
+ if low.endswith((".tsv", ".csv")):
480
+ if p.name in others:
481
+ continue
482
+ try:
483
+ rows = load_interactions(p)
484
+ except BindviewError as exc: # (a spreadsheet's export in another encoding, say)
485
+ why = str(exc)
486
+ for lead in (f"cannot read {p}: ", f"{p}: "): # the reader names the file: so does the page
487
+ why = why.removeprefix(lead)
488
+ out.not_tables.append((p, why.replace(str(p), p.name)))
489
+ continue
490
+ # (NA can stand for a name that is not given: it does not tell whose table this is.)
491
+ named = {n for r in rows for n in ([r.ligand_atom] if r.ligand_atom not in (None, NOT_GIVEN_OR_A_NAME) else [])
492
+ + list(r.ligand_atoms or ())}
493
+ out.tables.append((p, rows, named, any("/" in n for n in named)))
494
+ elif low.endswith(("summary_confidences.json", "summary_confidences.json.gz")):
495
+ out.summary = out.summary or p
496
+ elif (low.endswith(("confidences.json", "confidences.json.gz")) or low == f"pae_{_stem(model).lower()}.npz"
497
+ or ("predicted_aligned_error" in low and low.endswith((".json", ".json.gz")))):
498
+ out.pae = out.pae or p # R8
499
+ elif low == "meta.json":
500
+ try:
501
+ meta = json.loads(p.read_text(encoding="utf-8"))
502
+ except (OSError, ValueError):
503
+ continue
504
+ if isinstance(meta, dict):
505
+ out.meta = meta
506
+ return out
507
+
508
+
509
+ def plip_here() -> bool:
510
+ """Can PLIP be imported where this runs? It is asked, and not imported."""
511
+ return importlib.util.find_spec("plip") is not None
512
+
513
+
514
+ # ---------------------------------------------------------------------------
515
+ # The figures that follow
516
+ # ---------------------------------------------------------------------------
517
+
518
+ #: The folder of the input that is being surveyed: the printed calls name their files from it, and are run in it.
519
+ _FOLDER: "ContextVar[Path | None]" = ContextVar("the folder of the input", default=None)
520
+
521
+
522
+ def _shown(path: Path) -> str:
523
+ """A path as a printed call names it: from the folder of the input, in which the call is run, and never
524
+ from above it (a file that does not lie in that folder has its bare name)."""
525
+ full, folder = Path(os.path.abspath(path)), _FOLDER.get()
526
+ if folder is not None and (full == folder or folder in full.parents):
527
+ return full.relative_to(folder).as_posix()
528
+ return full.name
529
+
530
+
531
+ @contextlib.contextmanager
532
+ def _run_in(folder: Path) -> "Iterator[None]":
533
+ """Inside, the working directory is ``folder``; after, it is what it was."""
534
+ before = os.getcwd()
535
+ os.chdir(folder)
536
+ try:
537
+ yield
538
+ finally:
539
+ os.chdir(before)
540
+
541
+
542
+ def _q(text: object) -> str:
543
+ """Words as a Python string in a printed call. Whatever a file calls a chain or a residue, and
544
+ whatever a path or a SMILES holds, it stays inside the quotes."""
545
+ return json.dumps(str(text), ensure_ascii=False)
546
+
547
+
548
+ def _table_of(cand: Candidate, found: Found, st: Structure, by: Beside) -> tuple[Candidate, Path | None]:
549
+ """R5: the table beside the model that is this candidate's, and the copy it is about. A table that names no
550
+ atom of a ligand says nothing of whose it is: it comes after those that do, and is taken where the model has
551
+ one ligand only."""
552
+ alone = sum(c.kind in ("small molecule", "ion") for c in found.candidates) == 1
553
+ for path, rows, named, chain_names in sorted(by.tables, key=lambda table: not table[2]):
554
+ if chain_names or not named <= cand.atoms or not (named or alone):
555
+ continue
556
+ if rows and len(found.copies[cand.name]) > 1:
557
+ first = rows[0]
558
+ # (NA for the chain is a chain of that name where the model has one, and no chain given where not.)
559
+ chain = first.chain if any(k.chain == first.chain for k in st.residues()) else None
560
+ key = st.find_residue(chain, first.residue_number, first.insertion_code)
561
+ if key is not None:
562
+ at = np.array([a.xyz for a in st.residue_atoms(key)], dtype=float)
563
+ for copy in found.copies[cand.name]:
564
+ if np.linalg.norm(copy.xyz[:, None, :] - at[None, :, :], axis=2).min() <= NEAR:
565
+ copy.copies = cand.copies
566
+ return copy, path
567
+ return cand, path
568
+ return cand, None
569
+
570
+
571
+ def _receptor(cand: Candidate, st: Structure, found: Found) -> str:
572
+ """R5: what PLIP is to take for the receptor of a candidate."""
573
+ kinds = {c.name: c.kind for c in found.chains}
574
+ near = set()
575
+ for a in st.atoms:
576
+ if a.element in ("H", "D") or a.resname.upper() in WATER_NAMES or kinds.get(a.chain) not in ("protein", "nucleic"):
577
+ continue
578
+ if (a.chain, a.resnum) == (cand.chain, cand.number):
579
+ continue
580
+ if np.linalg.norm(cand.xyz - np.array(a.xyz), axis=1).min() <= NEAR:
581
+ near.add(kinds[a.chain])
582
+ return "nucleic" if near == {"nucleic"} else "protein"
583
+
584
+
585
+ def _smiles(cand: Candidate, found: Found, by: Beside, given: Mapping[str, str]) -> tuple[str | None, str]:
586
+ """R6: the SMILES to hand in (None: nothing to hand in), and where it is from, in words."""
587
+ if cand.name in given:
588
+ return given[cand.name], "handed in"
589
+ if cand.name in found.smiles_in_file:
590
+ return None, "in the file itself"
591
+ ligand = (by.meta or {}).get("ligand")
592
+ named = {cand.name, f"{cand.chain}:{cand.number}", f"{cand.chain}:{cand.name}:{cand.number}"}
593
+ if isinstance(ligand, dict) and ligand.get("residue_name_in_cif") in named and ligand.get("smiles"):
594
+ return str(ligand["smiles"]), "from meta.json beside the model"
595
+ return None, "none: the library draws the connectivity and says so"
596
+
597
+
598
+ def _ligand_track(cand: Candidate, model: Path, st: Structure, found: Found, by: Beside,
599
+ given: Mapping[str, str]) -> Track:
600
+ cand, table = _table_of(cand, found, st, by)
601
+ smiles, where = _smiles(cand, found, by, given)
602
+ kind = "ion" if cand.kind == "ion" else "ligand"
603
+ what = "an ion" if cand.kind == "ion" else f"a {cand.kind}"
604
+ seen = (f"{cand.name} on chain {cand.chain}: {what} of {cand.heavy} heavy atom{'s' if cand.heavy != 1 else ''}"
605
+ + (f", {cand.copies} copies in the file" if cand.copies > 1 else "")
606
+ + (", within bonding distance of the chain" if cand.bonded else "") + f". SMILES: {where}.")
607
+ extra = f",\n smiles={_q(smiles)}" if smiles else ""
608
+ if table is not None:
609
+ names_atoms = any(named for path, _, named, _ in by.tables if path == table)
610
+ seen += (f" Contacts: the table {table.name} beside the model, which names its atoms." if names_atoms else
611
+ f" Contacts: the table {table.name} beside the model, which names no atom of a ligand: it is taken "
612
+ "for this one's, the only ligand of the model.")
613
+ code = ("from bindview import Diagram, load_interactions\n\n"
614
+ f"dia = Diagram.from_structure({_q(_shown(model))}, ligand={_q(cand.spec)}{extra},\n"
615
+ f" interactions=load_interactions({_q(_shown(table))}))\n"
616
+ 'figure = dia.render(style="detailed")')
617
+ return Track(kind, f"{cand.name} in its pocket", seen, code)
618
+ receptor = _receptor(cand, st, found)
619
+ said = "" if receptor == "protein" else ', receptor="nucleic"'
620
+ code = ("from bindview import Diagram\n"
621
+ "from bindview.detect import detect_interactions # PLIP, which is optional and GPL\n\n"
622
+ f"model = {_q(_shown(model))}\n"
623
+ f"dia = Diagram.from_structure(model, ligand={_q(cand.spec)}{extra},\n"
624
+ f" interactions=detect_interactions(model, {_q(cand.spec)}{said}))\n"
625
+ 'figure = dia.render(style="detailed")')
626
+ if plip_here():
627
+ seen += (" Contacts: no table beside the model, so PLIP finds them"
628
+ + (", with the nucleic acid as the receptor." if said else "."))
629
+ return Track(kind, f"{cand.name} in its pocket", seen, code)
630
+ seen += (" Contacts: no table beside the model and no PLIP where this ran, so they are the table of heavy "
631
+ "atoms: no hydrogen is placed, a hydrogen bond has no angle, and there is no water bridge.")
632
+ first = f"smiles = {_q(smiles)}\n" if smiles else ""
633
+ hand = ", smiles=smiles" if smiles else ""
634
+ code = ("from bindview import Diagram, read_structure\n"
635
+ "from bindview.distance_table import ligand_contacts # heavy atoms only: cruder than PLIP\n\n"
636
+ f"model = read_structure({_q(_shown(model))})\n" + first
637
+ + f"dia = Diagram.from_structure(model, ligand={_q(cand.spec)}{hand},\n"
638
+ f" interactions=ligand_contacts(model, {_q(cand.spec)}{', smiles' if smiles else ''}))\n"
639
+ 'figure = dia.render(style="detailed")')
640
+ return Track(kind, f"{cand.name} in its pocket", seen, code)
641
+
642
+
643
+ def _peptide_track(chain: Chain, model: Path, by: Beside, proteins: Sequence[str] = ()) -> Track:
644
+ table = next((path for path, _, _, chain_names in by.tables if chain_names), None)
645
+ if chain.kind == "nucleic":
646
+ seen = (f"Chain {chain.name} is a nucleic chain of {chain.residues} nucleotides beside a protein: an "
647
+ "oligonucleotide, drawn as the ligand.")
648
+ else:
649
+ seen = f"Chain {chain.name} is a protein chain of {chain.residues} residues: a peptide, drawn as the ligand."
650
+ if table is not None:
651
+ seen += f" Contacts: the table {table.name} beside the model, which names atoms residue by residue."
652
+ code = ("from bindview import Diagram, load_interactions\n\n"
653
+ f"dia = Diagram.from_structure({_q(_shown(model))}, {_q('chain:' + chain.name)},\n"
654
+ f" interactions=load_interactions({_q(_shown(table))}))\n"
655
+ 'figure = dia.render(style="detailed")')
656
+ else:
657
+ seen += " Contacts: the plain distance table with ring stacking, which is no interaction analysis."
658
+ partners = ""
659
+ if chain.kind == "nucleic" and proteins: # R7b
660
+ seen += (" Its partners are the residues of the protein: what the chain pairs with in another "
661
+ "nucleic chain is in their interface.")
662
+ partners = f", partners=[{', '.join(_q(p) for p in proteins)}]"
663
+ code = ("from bindview import Diagram, read_structure\n"
664
+ "from bindview.distance_table import contact_table # distances only: no interaction analysis\n\n"
665
+ f"model = read_structure({_q(_shown(model))})\n"
666
+ f"dia = Diagram.from_structure(model, {_q('chain:' + chain.name)},\n"
667
+ f" interactions=contact_table(model, {_q(chain.name)}{partners}, stacking=True))\n"
668
+ 'figure = dia.render(style="detailed")')
669
+ if chain.kind == "nucleic":
670
+ return Track("oligonucleotide", f"The oligonucleotide of chain {chain.name}", seen, code)
671
+ return Track("peptide", f"The peptide of chain {chain.name}", seen, code)
672
+
673
+
674
+ def _interface_track(a: Chain, b: Chain, rows: int, model: Path, by: Beside) -> Track:
675
+ unit = {"protein": "residues", "nucleic": "nucleotides"}
676
+ seen = (f"Chains {a.name} ({a.kind}, {a.residues} {unit[a.kind]}) and {b.name} ({b.kind}, {b.residues} "
677
+ f"{unit[b.kind]}) touch: the plain distance table, with ring stacking, has {rows} rows for the pair.")
678
+ pae = ""
679
+ if by.pae is not None:
680
+ seen += f" Predicted aligned errors: {by.pae.name} beside the model."
681
+ pae = f",\n pae={_q(_shown(by.pae))}"
682
+ code = ("from bindview import Interface, read_structure\n"
683
+ "from bindview.distance_table import interface_contacts # distances only: no interaction analysis\n\n"
684
+ f"model = read_structure({_q(_shown(model))})\n"
685
+ f"face = Interface(model, [{_q(a.name)}, {_q(b.name)}], "
686
+ f"interface_contacts(model, [{_q(a.name)}], [{_q(b.name)}], stacking=True){pae})\n"
687
+ 'figure = face.render(style="detailed")')
688
+ return Track("interface", f"The interface of chains {a.name} and {b.name}", seen, code)
689
+
690
+
691
+ def _basepairs_track(a: Chain, b: Chain, model: Path, st: Structure, found: Found, by: Beside,
692
+ small: Sequence[Candidate], given: Mapping[str, str]) -> Track:
693
+ """R17: two nucleic chains as their base pairs, with a small molecule beside them where one is."""
694
+ from .basepairs import read_mmcif_pairs
695
+
696
+ pair = f"[{_q(a.name)}, {_q(b.name)}]"
697
+ head = ["BasePairs", "read_structure"]
698
+ lines = [f"model = read_structure({_q(_shown(model))})",
699
+ f"contacts = interface_contacts(model, [{_q(a.name)}], [{_q(b.name)}], stacking=True)"]
700
+ own = ([p for p in read_mmcif_pairs(model) if {p.chain_a, p.chain_b} <= {a.name, b.name}]
701
+ if model.name.lower().endswith((".cif", ".cif.gz", ".mmcif")) else [])
702
+ beside = [f for f in (model.parent / f"{_stem(model)}.rnapolis.json", model.parent / "basepairs.rnapolis.json")
703
+ if f.exists()]
704
+ stacks = ""
705
+ if own:
706
+ head.append("read_mmcif_pairs")
707
+ lines.append(f"found = read_mmcif_pairs({_q(_shown(model))})")
708
+ seen = f"Pairs: the PDB's own annotation in {model.name} ({len(own)} pairs of these chains)."
709
+ elif beside:
710
+ head += ["read_rnapolis_pairs", "read_rnapolis_stacks"]
711
+ lines += [f"annotation = {_q(_shown(beside[0]))}", "found = read_rnapolis_pairs(annotation)"]
712
+ stacks = ", stacks=read_rnapolis_stacks(annotation)"
713
+ seen = f"Pairs and stacks: RNApolis's annotation {beside[0].name} beside the model."
714
+ else:
715
+ head += ["pairs_from_contacts", "pairs_within_from_table"]
716
+ lines.append(f"found = (pairs_from_contacts(contacts)[0] + pairs_within_from_table(model, {_q(a.name)})\n"
717
+ f" + pairs_within_from_table(model, {_q(b.name)}))")
718
+ seen = ("No annotation of the pairs beside the model (an mmCIF with the PDB's, or RNApolis's JSON): the "
719
+ "pairs are the plain distance table's stand-in, two or more hydrogen bonds from base to base, "
720
+ "without a family.")
721
+ lig = ""
722
+ strands = np.array([x.xyz for x in st.atoms if x.chain in (a.name, b.name) and x.element not in ("H", "D")],
723
+ dtype=float).reshape(-1, 3)
724
+ for cand in small:
725
+ if len(strands) and np.linalg.norm(cand.xyz[:, None, :] - strands[None, :, :], axis=2).min() <= BESIDE_PAIRS:
726
+ cand, table = _table_of(cand, found, st, by)
727
+ if table is not None:
728
+ lig = f", ligand={_q(cand.spec)},\n ligand_contacts={_q(_shown(table))}"
729
+ seen += f" {cand.name} lies beside them, with its contacts from {table.name}."
730
+ else:
731
+ smiles, _ = _smiles(cand, found, by, given)
732
+ lig = f", ligand={_q(cand.spec)}" + (f",\n ligand_smiles={_q(smiles)}" if smiles else "")
733
+ seen += f" {cand.name} lies beside them, with its contacts from the plain distance table."
734
+ break
735
+ code = (f"from bindview import {', '.join(head)}\n"
736
+ "from bindview.distance_table import interface_contacts # distances only: no interaction analysis\n\n"
737
+ + "\n".join(lines) + "\n"
738
+ + f"pairs = BasePairs(model, {pair}, found, contacts=contacts{stacks}{lig})\n"
739
+ "figure = pairs.render()")
740
+ return Track("basepairs", f"The base pairs of chains {a.name} and {b.name}", seen, code)
741
+
742
+
743
+ def _ensemble_track(cand: Candidate, models: Sequence[Path], numbers: Sequence[int | None], by: Beside, found: Found,
744
+ given: Mapping[str, str], own: "Sequence[Path | None] | None" = None) -> Track:
745
+ """``own``: for the members of a set that lie in folders of their own, the table beside each."""
746
+ smiles, where = _smiles(cand, found, by, given)
747
+ many = len(numbers) if len(models) == 1 else len(models)
748
+ of = f"the {many} models of {models[0].name}" if len(models) == 1 else f"{many} models of one complex"
749
+ seen = f"{of[:1].upper() + of[1:]}: an ensemble, counted for {cand.name}. SMILES: {where}."
750
+ folder = models[0].parent
751
+ wanted: list[Path]
752
+ if len(models) == 1:
753
+ wanted = [folder / f"model_{n:02d}.interactions.tsv" for n in numbers if n is not None]
754
+ reads = (f"models = read_models({_q(_shown(models[0]))})\n"
755
+ f'tables = [{_q(_shown(folder))} + f"/model_{{m.model:02d}}.interactions.tsv" for m in models]\n')
756
+ else:
757
+ wanted = ([t for t in own if t is not None] if own is not None
758
+ else [m.parent / f"{_stem(m)}.interactions.tsv" for m in models])
759
+ reads = ("models = [" + ", ".join(_q(_shown(m)) for m in models) + "]\n"
760
+ "tables = [" + ", ".join(_q(_shown(t)) for t in wanted) + "]\n")
761
+ have = len(wanted) == many and all(t.exists() for t in wanted)
762
+ smi = _q(smiles) if smiles else "None"
763
+ head = "from bindview import Ensemble" + (", read_models" if len(models) == 1 else "") + "\n\n"
764
+ if have:
765
+ seen += " Contacts: a table for every model beside it."
766
+ code = (head + reads + f"ens = Ensemble.from_structures(models, {_q(cand.spec)}, {smi}, tables,\n"
767
+ f" ensemble={_q(of)})\nfigure = ens.diagram().render()")
768
+ return Track("ensemble", f"{cand.name} over {many} models", seen, code)
769
+ code = (head + reads.split("\n")[0] + "\n"
770
+ + f"ens = Ensemble.from_structures(models, {_q(cand.spec)}, {smi}, # no tables: PLIP finds the contacts\n"
771
+ f" ensemble={_q(of)})\nfigure = ens.diagram().render()")
772
+ if plip_here() and many <= MOST["models"]:
773
+ seen += " Contacts: no table for every model, so PLIP finds them model by model."
774
+ return Track("ensemble", f"{cand.name} over {many} models", seen, code)
775
+ seen += (" Contacts: no table for every model"
776
+ + (f" and more models than the {MOST['models']} this report has PLIP go through"
777
+ if plip_here() else " and no PLIP where this ran")
778
+ + ", so they are the table of heavy atoms, model by model.")
779
+ loads = (f"models = read_models({_q(_shown(models[0]))})\n" if len(models) == 1 else
780
+ "models = [read_structure(p) for p in (" + ", ".join(_q(_shown(m)) for m in models) + ")]\n")
781
+ code = ("from bindview import Ensemble, " + ("read_models" if len(models) == 1 else "read_structure") + "\n"
782
+ "from bindview.distance_table import ligand_contacts # heavy atoms only: cruder than PLIP\n\n"
783
+ + loads + f"tables = [ligand_contacts(m, {_q(cand.spec)}, {smi}) for m in models]\n"
784
+ f"ens = Ensemble.from_structures(models, {_q(cand.spec)}, {smi}, tables,\n"
785
+ f" ensemble={_q(of)})\nfigure = ens.diagram().render()")
786
+ return Track("ensemble", f"{cand.name} over {many} models", seen, code)
787
+
788
+
789
+ # ---------------------------------------------------------------------------
790
+ # The survey, and its page
791
+ # ---------------------------------------------------------------------------
792
+
793
+ @dataclass
794
+ class Survey:
795
+ """What an input holds and the figures that follow from it. Nothing is drawn until :meth:`draw`."""
796
+
797
+ path: Path
798
+ models: list[Path] # R1: one, or the models of a set
799
+ found: Found # what the first model holds
800
+ models_in_file: int
801
+ beside: Beside
802
+ tracks: list[Track]
803
+ left: list[tuple[str, str]] # what was found and has no figure, and why
804
+ plip: bool
805
+ #: ``"complex"``, ``"ensemble"`` (one complex in several models) or ``"series"`` (R1c).
806
+ kind: str = "complex"
807
+ #: The complexes of a series, one ligand each.
808
+ members: list[Member] = field(default_factory=list)
809
+ #: The folder of the input: the calls of the figures name their files from it, and are run in it.
810
+ folder: Path = field(default_factory=Path.cwd)
811
+
812
+ @property
813
+ def model(self) -> Path:
814
+ return self.models[0]
815
+
816
+ def draw(self, views: bool = True) -> None:
817
+ """Run the call of every figure, and draw its views (R15) unless ``views=False``. What the library
818
+ refuses is said on the page, in its words."""
819
+ for track in self.tracks:
820
+ if track.status:
821
+ continue
822
+ track.svg, track.status, track.said, names = _run(track.code, track.title, self.folder)
823
+ head, _, last = track.code.rpartition("\n")
824
+ if track.status == "unreadable" and DETAILED in last:
825
+ code = f"{head}\n{last.replace(DETAILED, SCHEMATIC)}" # R14
826
+ svg, status, said, again = _run(code, track.title, self.folder)
827
+ if status not in ("ok", "degraded"): # not drawn: the detailed figure stays
828
+ track.said.append("the schematic style was tried and is not readable either"
829
+ if status == "unreadable" else
830
+ f"the schematic style was tried and came back {status}")
831
+ else:
832
+ told = [s.removesuffix(SUMMARY) for s in track.said if "not readable" in s] or ["it is not readable"]
833
+ track.code, track.svg, track.status, track.schematic = code, svg, status, True
834
+ track.said = [f"drawn in the schematic style: in the detailed style, {s}" for s in told] + said
835
+ names = again
836
+ if track.status in ("ok", "degraded"):
837
+ track.facts = _facts(names.get("figure"))
838
+ if views and track.status in ("ok", "degraded"):
839
+ with _run_in(self.folder):
840
+ track.views = _views(track, names, self.found.plddt)
841
+
842
+ def html(self) -> str:
843
+ """The report as one page. It holds no date, no timing and no path from above the input's folder: the
844
+ same input gives the same page, wherever the report is run."""
845
+ return _page(self)
846
+
847
+
848
+ def _views(track: Track, names: dict[str, Any], plddt: bool) -> list[View]:
849
+ """R15: the figure's object drawn again, each by a last line of its own, where the figure's call ran."""
850
+ last = track.code.rpartition("\n")[2]
851
+ style = DETAILED if DETAILED in last else SCHEMATIC if SCHEMATIC in last else None
852
+ out = []
853
+ if track.kind == "basepairs" and last.endswith("()"): # R17: its one view
854
+ out.append(View("a figure that answers the pointer: point at a nucleotide, or click it",
855
+ last[:-1] + "interactive=True)"))
856
+ elif style is None or not last.endswith(")"):
857
+ return []
858
+ else:
859
+ if not track.schematic:
860
+ other = SCHEMATIC if style == DETAILED else DETAILED
861
+ out.append(View(f"in the {'schematic' if other == SCHEMATIC else 'detailed'} style",
862
+ last.replace(style, other)))
863
+ if plddt:
864
+ out.append(View("pLDDT in AlphaFold's colours", last[:-1] + ", plddt_colors=True)"))
865
+ out.append(View("a figure that answers the pointer: point at a residue, or click it",
866
+ last[:-1] + ", interactive=True)"))
867
+ for view in out:
868
+ try:
869
+ exec(compile(view.line, f"<{track.title}: {view.title}>", "exec"), names) # noqa: S102 - as printed
870
+ except BindviewError as exc:
871
+ view.status, view.said = "refused", [str(exc)]
872
+ continue
873
+ figure = names["figure"]
874
+ view.status, view.said = figure.status, list(figure.warnings)
875
+ if figure.status in ("ok", "degraded"):
876
+ view.svg = figure.svg
877
+ return out
878
+
879
+
880
+ def _facts(figure: Any) -> dict[str, Any]:
881
+ """R16: what an index says of a figure, read off the result that drew it."""
882
+ graph = getattr(figure, "graph", None)
883
+ kinds = Counter(c.type for c in graph.contacts) if graph is not None else Counter()
884
+ conf = getattr(figure, "confidence", None) or {}
885
+ burial = getattr(figure, "burial", None) or {}
886
+ return {"contacts": {k: kinds[k] for k in KINDS if kinds[k]}, "iptm": conf.get("iptm"),
887
+ "pocket_plddt": conf.get("pocket_plddt"), "ligand_plddt": conf.get("ligand_plddt"),
888
+ "buried_fraction": burial.get("buried_fraction"), "warnings": len(getattr(figure, "warnings", []))}
889
+
890
+
891
+ def _run(code: str, title: str, folder: Path) -> tuple[str, str, list[str], dict[str, Any]]:
892
+ """Run the call of a figure in the folder it is written for: its picture, its status, what the library
893
+ said, and the names the call made (its diagram, for the views)."""
894
+ names: dict[str, Any] = {}
895
+ try:
896
+ with _run_in(folder):
897
+ exec(compile(code, f"<{title}>", "exec"), names) # noqa: S102 - the call the page prints
898
+ except BindviewError as exc:
899
+ return "", "refused", [str(exc)], names
900
+ figure = names["figure"]
901
+ said = list(figure.warnings)
902
+ peptide = getattr(getattr(names.get("dia"), "backend", None), "peptide", None)
903
+ if peptide is not None:
904
+ said.insert(0, f"read as a chain of {len(peptide.residues)} residues")
905
+ return figure.svg, figure.status, said, names
906
+
907
+
908
+ def _member_table(model: Path, cand: Candidate, found: Found, st: Structure, alone: bool) -> "Path | None":
909
+ """The table of contacts of a member of a set: the one named after its model, or, where the model
910
+ lies in a folder of its own, the table beside it that names the ligand's atoms (R5)."""
911
+ named = model.parent / f"{_stem(model)}.interactions.tsv"
912
+ if named.exists():
913
+ return named
914
+ return _table_of(cand, found, st, _beside(model))[1] if alone else None
915
+
916
+
917
+ def _series_track(members: Sequence[Member]) -> Track:
918
+ """R1c: several ligands on one protein, as the library's comparison of them."""
919
+ n = len(members)
920
+ tables = sum(1 for m in members if m.table is not None)
921
+ seen = (f"{n} complexes of one protein, each with one small molecule: a series of ligands, drawn as a "
922
+ f"comparison ({'what the two do differently' if n == 2 else 'what they have in common'}). Contacts: "
923
+ + ("the table beside each model." if tables == n else
924
+ f"the table beside the model for {tables} of them, the table of heavy atoms for the others."))
925
+
926
+ def line(m: Member) -> str:
927
+ smiles = f", smiles={_q(m.smiles)}" if m.smiles else ""
928
+ if tables == n:
929
+ return (f" Diagram.from_structure({_q(_shown(m.model))}, ligand={_q(m.ligand.spec)}{smiles}, "
930
+ f"name={_q(m.name)},\n "
931
+ f"interactions=load_interactions({_q(_shown(m.table or m.model))})),\n")
932
+ table = f", table={_q(_shown(m.table))}" if m.table else ""
933
+ return f" member({_q(_shown(m.model))}, {_q(m.ligand.spec)}, {_q(m.name)}{table}{smiles}),\n"
934
+
935
+ if tables == n:
936
+ head = "from bindview import Comparison, Diagram, load_interactions\n\n"
937
+ else:
938
+ head = ("from bindview import Comparison, Diagram, load_interactions, read_structure\n"
939
+ "from bindview.distance_table import ligand_contacts # heavy atoms only: where a member has no table\n\n\n"
940
+ "def member(path, ligand, name, table=None, smiles=None):\n"
941
+ " model = read_structure(path)\n"
942
+ " contacts = load_interactions(table) if table else ligand_contacts(model, ligand, smiles)\n"
943
+ " return Diagram.from_structure(model, ligand=ligand, smiles=smiles, name=name, interactions=contacts)\n\n\n")
944
+ code = head + "diagrams = [\n" + "".join(line(m) for m in members) + "]\nfigure = Comparison(diagrams).render()"
945
+ return Track("series", f"{n} ligands of one pocket", seen, code)
946
+
947
+
948
+ def _parts(by: Beside, given: "Sequence[tuple[str, str, int, int]] | None"
949
+ ) -> tuple[list[tuple[str, str, int, int]], list[tuple[str, str]]]:
950
+ """R12: the parts of a chain that somebody named, as ``(name, chain, first, last)``; and what a
951
+ ``meta.json`` names as a part without saying where it is, each with the reason it has no figure."""
952
+ if given:
953
+ if len(given) == 1:
954
+ raise BindviewError(f"one part was named ({given[0][0]!r}): an interface is between two, so name both")
955
+ return list(given), []
956
+ meta = by.meta or {}
957
+ chain, parts = meta.get("chain"), meta.get("participants")
958
+ out, unread = [], []
959
+ if isinstance(chain, str) and isinstance(parts, list):
960
+ for part in parts:
961
+ span = part.get("residues") if isinstance(part, dict) else None
962
+ if isinstance(span, list) and len(span) == 2 and isinstance(part.get("name"), str):
963
+ try:
964
+ out.append((str(part["name"]), chain, int(span[0]), int(span[1])))
965
+ except (TypeError, ValueError):
966
+ unread.append((f"part {part['name']!r} of meta.json",
967
+ f"its residues are {span!r}, not two residue numbers"))
968
+ return (out if len(out) >= 2 else []), unread
969
+
970
+
971
+ def _part_tracks(parts: Sequence[tuple[str, str, int, int]], model: Path, st: Structure, by: Beside,
972
+ named_by: str) -> tuple[list[Track], list[tuple[str, str]]]:
973
+ """R12: the interface of every pair of named parts that touches. A part that cannot be cut out of its
974
+ chain is refused here, under the name it was given: for the cut it has a chain name of the report's."""
975
+ numbers: dict[str, list[int]] = {}
976
+ for key in st.residues():
977
+ numbers.setdefault(key.chain, []).append(key.number)
978
+ for name, chain, first, last in parts:
979
+ if first > last:
980
+ raise BindviewError(f"part {name!r} runs from {first} to {last}: the first number comes first")
981
+ if not any(first <= number <= last for number in numbers.get(chain, ())):
982
+ raise BindviewError(f"part {name!r}: chain {chain!r} has no residue from {first} to {last}")
983
+ for i, a in enumerate(parts):
984
+ for b in parts[i + 1:]:
985
+ if a[1] == b[1] and a[2] <= b[3] and b[2] <= a[3]:
986
+ raise BindviewError(f"parts {a[0]!r} ({a[2]} to {a[3]}) and {b[0]!r} ({b[2]} to {b[3]}) overlap on "
987
+ f"chain {a[1]!r}")
988
+ taken = {a.chain for a in st.atoms}
989
+ free = [c for c in "XYZWVUTSRQPONMLKJIHGFEDCBA" if c not in taken]
990
+ if len(free) < len(parts):
991
+ raise BindviewError(f"{len(parts)} parts were named and only {len(free)} chain names are free")
992
+ letter = {part: free[k] for k, part in enumerate(parts)}
993
+ cut = st
994
+ for chain in dict.fromkeys(p[1] for p in parts):
995
+ cut = cut.split(chain, {letter[p]: (p[2], p[3]) for p in parts if p[1] == chain})
996
+ pairs = []
997
+ for i, a in enumerate(parts):
998
+ for b in parts[i + 1:]:
999
+ rows = len(interface_contacts(cut, [letter[a]], [letter[b]], stacking=True))
1000
+ if rows:
1001
+ pairs.append((rows, a, b))
1002
+ pairs.sort(key=lambda x: -x[0])
1003
+ tracks: list[Track] = []
1004
+ left: list[tuple[str, str]] = []
1005
+
1006
+ def said(name: str) -> str:
1007
+ return name.replace("=", " ").replace("+", " ")
1008
+
1009
+ for rows, a, b in pairs:
1010
+ if len(tracks) == MOST["interface"]:
1011
+ left.append((f"the interface of {a[0]} and {b[0]} ({rows} rows)", "more interfaces than the report draws"))
1012
+ continue
1013
+ seen = (f"{a[0]} (chain {a[1]}, {a[2]} to {a[3]}) and {b[0]} (chain {b[1]}, {b[2]} to {b[3]}), named "
1014
+ f"{named_by}, touch: the plain distance table, with ring stacking, has {rows} rows for the pair.")
1015
+ pae = ""
1016
+ if by.pae is not None:
1017
+ seen += f" Predicted aligned errors: {by.pae.name} beside the model."
1018
+ pae = f",\n pae={_q(_shown(by.pae))}"
1019
+ splits = "".join(f".split({_q(chain)}, {{" + ", ".join(f"{_q(letter[p])}: ({p[2]}, {p[3]})" for p in (a, b) if p[1] == chain)
1020
+ + "})" for chain in dict.fromkeys(p[1] for p in (a, b)))
1021
+ code = ("from bindview import Interface, read_structure\n"
1022
+ "from bindview.distance_table import interface_contacts # distances only: no interaction analysis\n\n"
1023
+ f"model = read_structure({_q(_shown(model))}){splits} # each part a chain of its own\n"
1024
+ f"face = Interface(model, [{_q(said(a[0]) + '=' + letter[a])}, {_q(said(b[0]) + '=' + letter[b])}],\n"
1025
+ f" interface_contacts(model, [{_q(letter[a])}], [{_q(letter[b])}], stacking=True){pae})\n"
1026
+ 'figure = face.render(style="detailed")')
1027
+ tracks.append(Track("parts", f"The interface of {a[0]} and {b[0]}", seen, code))
1028
+ if not pairs:
1029
+ left.append((", ".join(p[0] for p in parts), "the parts that were named do not touch"))
1030
+ return tracks, left
1031
+
1032
+
1033
+ def survey(path: "str | Path", smiles: "Mapping[str, str] | None" = None,
1034
+ domains: "Sequence[tuple[str, str, int, int]] | None" = None) -> Survey:
1035
+ """Look at a model, or at a folder that holds one or a set of them: what it holds, and the figures
1036
+ that follow.
1037
+
1038
+ ``smiles`` hands in the SMILES of a residue by its name, for the bond orders that a deposited
1039
+ structure does not carry. ``domains`` names parts of a chain as ``(name, chain, first, last)``: the
1040
+ interface between them is drawn (R12). Nothing is drawn here: :meth:`Survey.draw` does that.
1041
+ """
1042
+ path = Path(path)
1043
+ if not path.exists():
1044
+ raise BindviewError(f"{path}: no such file or folder")
1045
+ folder = Path(os.path.abspath(path if path.is_dir() else path.parent))
1046
+ naming = _FOLDER.set(folder)
1047
+ try:
1048
+ found = _survey(path, dict(smiles or {}), domains)
1049
+ finally:
1050
+ _FOLDER.reset(naming)
1051
+ found.folder = folder
1052
+ return found
1053
+
1054
+
1055
+ def _survey(path: Path, given: "dict[str, str]", domains: "Sequence[tuple[str, str, int, int]] | None") -> Survey:
1056
+ members = _members(path)
1057
+ passed = [(f"folder {sub.name} ({len(names)} models: {_named(names)})", _ONE_MODEL) # R1b
1058
+ for sub, names in _passed_over(path)]
1059
+ if not members:
1060
+ raise BindviewError(f"{path}: no model here (an mmCIF or PDB file, or a folder that holds one)"
1061
+ + (f"; {'; '.join(what for what, _ in passed)}: {_ONE_MODEL}" if passed else ""))
1062
+ models = [m for _, m in members]
1063
+ alone = len({m.parent for m in models}) == len(models) and len(models) > 1 # each in a folder of its own
1064
+ structures = [read_structure(m) for m in models]
1065
+ looks = [look(s) for s in structures]
1066
+ if len({_composition(f) for f in looks}) > 1: # R1c
1067
+ ligands = [[c for c in f.candidates if c.kind == "small molecule"] for f in looks]
1068
+ if not (_one_protein(looks) and all(len(found) == 1 for found in ligands)):
1069
+ raise BindviewError(f"{path} holds {len(models)} models that are neither one complex nor a series of "
1070
+ f"ligands on one protein ({', '.join(m.name if not alone else m.parent.name for m in models)}): "
1071
+ "name one of them, or ask for a page of each (--each)")
1072
+ series = []
1073
+ for (name, model), st_m, found_m, (cand,) in zip(members, structures, looks, ligands):
1074
+ by_m = _beside(model)
1075
+ handed, where = _smiles(cand, found_m, by_m if alone or len(models) == 1 else Beside(), given)
1076
+ series.append(Member(name, model, cand, _member_table(model, cand, found_m, st_m, alone), handed, where))
1077
+ return Survey(path, models, looks[0], 1, _beside(models[0]), [_series_track(series)], passed, plip_here(),
1078
+ kind="series", members=series)
1079
+ model, found, st = models[0], looks[0], structures[0]
1080
+ numbers = [m.model for m in read_models(model)]
1081
+ by = _beside(model)
1082
+ tracks: list[Track] = []
1083
+ left: list[tuple[str, str]] = list(passed)
1084
+ small = [c for c in found.candidates if c.kind == "small molecule"]
1085
+ ions = [c for c in found.candidates if c.kind == "ion"]
1086
+ long_protein = any(c.kind == "protein" and c.residues > PEPTIDE[1] for c in found.chains)
1087
+ short = sorted((c for c in found.chains if c.peptide or (c.oligo and long_protein)), key=lambda c: c.residues) # R7, R7b
1088
+ for cand in small[:MOST["small molecule"]]:
1089
+ tracks.append(_ligand_track(cand, model, st, found, by, given))
1090
+ if not small and not short:
1091
+ for cand in ions[:MOST["ion"]]:
1092
+ tracks.append(_ligand_track(cand, model, st, found, by, given))
1093
+ for chain in short[:MOST["peptide"]]:
1094
+ tracks.append(_peptide_track(chain, model, by, [c.name for c in found.chains if c.kind == "protein"]))
1095
+ # R8, R8b: two chains of more than 50, or two nucleic chains of any length
1096
+ polymers = [c for c in found.chains if c.kind in ("protein", "nucleic")]
1097
+ pairs = []
1098
+ for i, a in enumerate(polymers):
1099
+ for b in polymers[i + 1:]:
1100
+ both_long = a.residues > PEPTIDE[1] and b.residues > PEPTIDE[1]
1101
+ if not (both_long or (a.kind == "nucleic" and b.kind == "nucleic")):
1102
+ continue
1103
+ rows = len(interface_contacts(st, [a.name], [b.name], stacking=True))
1104
+ if rows:
1105
+ pairs.append((rows, a, b))
1106
+ pairs.sort(key=lambda x: -x[0])
1107
+ for rows, a, b in pairs[:MOST["interface"]]:
1108
+ tracks.append(_interface_track(a, b, rows, model, by))
1109
+ if a.kind == "nucleic" and b.kind == "nucleic": # R17
1110
+ tracks.append(_basepairs_track(a, b, model, st, found, by, small[:MOST["small molecule"]], given))
1111
+ parts, unread = _parts(by, domains) # R12
1112
+ left.extend(unread)
1113
+ if parts:
1114
+ try:
1115
+ more, missing = _part_tracks(parts, model, st, by, "by the caller" if domains else "in meta.json")
1116
+ except BindviewError as exc:
1117
+ if domains:
1118
+ raise
1119
+ # A file beside the model was found, not handed in: what is wrong in it does not end the report.
1120
+ more, missing = [], [(", ".join(p[0] for p in parts) + " (parts that meta.json names)",
1121
+ f"no interface of them is drawn: {exc}")]
1122
+ tracks.extend(more)
1123
+ left.extend(missing)
1124
+ many = len(numbers) if len(models) == 1 else len(models)
1125
+ if many >= 2 and small:
1126
+ own = None
1127
+ if alone:
1128
+ own = [_member_table(m, small[0], f, s, True) for m, f, s in zip(models, looks, structures)]
1129
+ tracks.append(_ensemble_track(small[0], models, numbers, by, found, given, own))
1130
+ # What was found and has no figure, with the reason (R4, R7, R8, R9)
1131
+ for cand in found.candidates:
1132
+ if cand.kind in ("cap", "additive", "sugar") or (cand.kind == "ion" and (small or short)):
1133
+ why = {"cap": "the end of a chain", "additive": "on the list of what crystals and buffers bring",
1134
+ "sugar": "a sugar bonded to the chain", "ion": "an ion beside a ligand"}[cand.kind]
1135
+ left.append((f"{cand.name} ({cand.kind}, {cand.heavy} heavy atom{'s' if cand.heavy != 1 else ''}, "
1136
+ f"{cand.copies} cop{'ies' if cand.copies != 1 else 'y'})",
1137
+ f"{why}; ligand={_q(cand.spec)} draws it"))
1138
+ for cand in small[MOST["small molecule"]:] + ([] if small or short else ions[MOST["ion"]:]):
1139
+ left.append((f"{cand.name} ({cand.kind})", f"more than the report draws; ligand={_q(cand.spec)} draws it"))
1140
+ for chain in short[MOST["peptide"]:]:
1141
+ left.append((f"chain {chain.name} ({chain.what} of {chain.residues})", "more chains as ligands than the report draws"))
1142
+ for rows, a, b in pairs[MOST["interface"]:]:
1143
+ left.append((f"the interface of chains {a.name} and {b.name} ({rows} rows)", "more interfaces than the report draws"))
1144
+ for chain in found.chains:
1145
+ if chain.joined: # R2b
1146
+ left.append((f"chain {chain.name} (protein, {chain.residues} residues)",
1147
+ f"bonded to chain {chain.joined}: a part of that protein, and no peptide; "
1148
+ f"ligand={_q('chain:' + chain.name)} draws it as one all the same"))
1149
+ elif chain.kind == "nucleic" and not any(chain.name in (a.name, b.name) for _, a, b in pairs) \
1150
+ and chain not in short:
1151
+ left.append((f"chain {chain.name} (nucleic, {chain.residues} nucleotides)",
1152
+ "it touches no other nucleic chain, and no protein chain of more than 50 residues is "
1153
+ "here for it to be the ligand of"))
1154
+ if many >= 2 and not small:
1155
+ left.append((f"{many} models", "an ensemble is counted for a small molecule, and there is none"))
1156
+ proteins = [c for c in found.chains if c.kind == "protein"]
1157
+ if not tracks and len(proteins) == 1 and not found.candidates:
1158
+ left.append((f"chain {proteins[0].name} alone",
1159
+ "one protein chain and nothing beside it. An interface between two domains of one chain "
1160
+ "can be drawn, but somebody has to say which residues the domains are (--domain)"))
1161
+ return Survey(path, models, found, len(numbers), by, tracks, left, plip_here(),
1162
+ kind="ensemble" if many >= 2 else "complex")
1163
+
1164
+
1165
+ @dataclass
1166
+ class Row:
1167
+ """R16: a member of a set in its index."""
1168
+
1169
+ name: str
1170
+ model: Path
1171
+ page: str = "" # the member's page, from the index
1172
+ tracks: list[Track] = field(default_factory=list)
1173
+ refused: str = "" # what the library said, where the member has no page
1174
+ why: str = "refused" # and what that was: it refused the member, or could not read its model
1175
+ left: list[tuple[str, str]] = field(default_factory=list)
1176
+
1177
+ @property
1178
+ def note(self) -> str:
1179
+ """The library's words where the member has no page, or why it has no figure."""
1180
+ if self.refused:
1181
+ return f"{self.why}: {self.refused}"
1182
+ if not self.tracks:
1183
+ return "nothing to draw" + (f": {self.left[0][0]}, {self.left[0][1]}" if self.left else "")
1184
+ return ""
1185
+
1186
+ @property
1187
+ def first(self) -> "Track | None":
1188
+ """The member's first figure that is drawn."""
1189
+ return next((t for t in self.tracks if t.status in ("ok", "degraded")), None)
1190
+
1191
+
1192
+ def write_each(path: "str | Path", out: "str | Path | None" = None, smiles: "Mapping[str, str] | None" = None,
1193
+ views: bool = True, say: Any = None) -> tuple[list[Row], Path]:
1194
+ """R16: a page for each member of a folder, and an index of them as a page and a CSV.
1195
+
1196
+ The index is ``<folder>.report.html`` beside the folder unless ``out`` says where; the members' pages
1197
+ are in the folder of the same name without ``.html``, and the CSV beside the index. ``say`` is told of
1198
+ each member as it is done."""
1199
+ source = Path(path)
1200
+ if not source.is_dir():
1201
+ raise BindviewError(f"{source}: --each takes a folder of models, or of folders that hold one")
1202
+ members = _members(source)
1203
+ passed = _passed_over(source)
1204
+ if not members and not passed:
1205
+ raise BindviewError(f"{source}: no model here (an mmCIF or PDB file, or a folder that holds one)")
1206
+ index = Path(out) if out else source.parent / f"{source.name}.report.html"
1207
+ pages = index.with_name(index.name.removesuffix(".html"))
1208
+ pages.mkdir(parents=True, exist_ok=True)
1209
+ rows: list[Row] = []
1210
+ # A page is named after its member, and a name is one page: the second member of a name gets a number that
1211
+ # no member has (letters in either case are one name where a file system takes them for one).
1212
+ taken = {name.casefold() for name, _ in members}
1213
+ seen: Counter[str] = Counter()
1214
+ for k, (name, model) in enumerate(members, 1):
1215
+ seen[name.casefold()] += 1
1216
+ if seen[name.casefold()] > 1:
1217
+ number = seen[name.casefold()]
1218
+ while f"{name}-{number}".casefold() in taken:
1219
+ number += 1
1220
+ name = f"{name}-{number}"
1221
+ taken.add(name.casefold())
1222
+ row = Row(name, model)
1223
+ try:
1224
+ found = survey(model, smiles)
1225
+ found.draw(views=views)
1226
+ except BindviewError as exc:
1227
+ # Named within the folder: the index is read beside it, not on the machine that wrote it.
1228
+ row.refused = str(exc).replace(str(model), str(model.relative_to(source)))
1229
+ if isinstance(exc, StructureError):
1230
+ row.why = "could not be read"
1231
+ else:
1232
+ row.tracks, row.left = found.tracks, found.left
1233
+ target = pages / f"{name}.html"
1234
+ target.write_text(found.html(), encoding="utf-8")
1235
+ row.page = f"{pages.name}/{target.name}"
1236
+ rows.append(row)
1237
+ if say is not None:
1238
+ done = ", ".join(f"{t.title}: {t.status}" for t in row.tracks) or row.refused or "nothing drawn"
1239
+ say(f" [{k}/{len(members)}] {name}: {done}")
1240
+ for sub, names in passed: # R1b: no member, and a row that says so
1241
+ rows.append(Row(sub.name, sub, why="not read",
1242
+ refused=f"{len(names)} models in one folder ({_named(names)}), and {_ONE_MODEL}"))
1243
+ if say is not None:
1244
+ say(f" {sub.name}: {rows[-1].note}")
1245
+ if passed:
1246
+ rows.sort(key=lambda row: row.name)
1247
+ index.write_text(_index_page(source, rows), encoding="utf-8")
1248
+ index.with_suffix(".csv").write_text(_index_csv(rows), encoding="utf-8")
1249
+ return rows, index
1250
+
1251
+
1252
+ def _number(value: Any, digits: int = 0, percent: bool = False) -> str:
1253
+ if value is None:
1254
+ return ""
1255
+ return f"{100 * value:.{digits}f} %" if percent else f"{value:.{digits}f}"
1256
+
1257
+
1258
+ def _index_csv(rows: Sequence[Row]) -> str:
1259
+ """R16: the rows of the index, one a member, with a column for each kind of contact."""
1260
+ buf = io.StringIO()
1261
+ out = csv.writer(buf, lineterminator="\n")
1262
+ out.writerow(["member", "page", "figures", "status", *KINDS, "iptm", "pocket_plddt", "ligand_plddt",
1263
+ "buried_fraction", "warnings", "note"])
1264
+ for row in rows:
1265
+ first = row.first
1266
+ facts = first.facts if first is not None else {}
1267
+ kinds = facts.get("contacts", {})
1268
+ out.writerow([row.name, row.page, " | ".join(t.title for t in row.tracks),
1269
+ " | ".join(t.status for t in row.tracks),
1270
+ *[kinds.get(k, 0) if first is not None else "" for k in KINDS],
1271
+ _number(facts.get("iptm"), 2), _number(facts.get("pocket_plddt"), 1),
1272
+ _number(facts.get("ligand_plddt"), 1), _number(facts.get("buried_fraction"), 3),
1273
+ facts["warnings"] if first is not None else "", row.note])
1274
+ return buf.getvalue()
1275
+
1276
+
1277
+ def _index_page(source: Path, rows: Sequence[Row]) -> str:
1278
+ """R16: the index of a set's pages. It holds no date and no timing, as a report does not."""
1279
+ esc = html.escape
1280
+ drawn = sum(1 for r in rows if r.first is not None)
1281
+ out = ["<!doctype html><html lang='en'><head><meta charset='utf-8'>"
1282
+ f"<title>bindview report: {esc(source.name)}, each</title><style>{_CSS}</style></head><body><main>",
1283
+ f"<h1>{esc(source.name)}: {len(rows)} inputs, a page each</h1>",
1284
+ f"<p>Each input of the folder was looked at and drawn as an input of its own; its page has its "
1285
+ f"figures, each under the call that drew it. {drawn} of {len(rows)} have a figure. The numbers are "
1286
+ f"those of each input's first figure. bindview {esc(__version__)}; PLIP is "
1287
+ f"{'installed' if plip_here() else 'not installed'} where this ran. The same rows are in the CSV "
1288
+ "beside this page.</p>",
1289
+ "<table><tr><th>input</th><th>figures</th><th>contacts of the first</th><th>ipTM</th>"
1290
+ "<th>pocket pLDDT</th><th>ligand pLDDT</th><th>buried</th><th>warnings</th></tr>"]
1291
+ for row in rows:
1292
+ # (A link is an address: a name with #, ? or % in it is quoted, or a browser asks for another page.)
1293
+ name = f"<a href='{esc(urllib.parse.quote(row.page))}'>{esc(row.name)}</a>" if row.page else esc(row.name)
1294
+ if row.refused:
1295
+ out.append(f"<tr><td>{name}</td><td colspan='7'><span class='badge refused'>{esc(row.why)}</span> "
1296
+ f"{esc(row.refused)}</td></tr>")
1297
+ continue
1298
+ figures = "<br>".join(f"{esc(t.title)} <span class='badge {esc(t.status.split()[0] if t.status else 'not')}'>"
1299
+ f"{esc(t.status or 'not run')}</span>" for t in row.tracks)
1300
+ if not figures:
1301
+ figures = esc(row.note)
1302
+ first = row.first
1303
+ facts = first.facts if first is not None else {}
1304
+ kinds = ", ".join(f"<span class='k'>{n} {esc(KIND_NAMES[k])}</span>" for k, n in facts.get("contacts", {}).items())
1305
+ out.append(f"<tr><td>{name}</td><td>{figures}</td><td>{kinds}</td>"
1306
+ f"<td>{_number(facts.get('iptm'), 2)}</td><td>{_number(facts.get('pocket_plddt'))}</td>"
1307
+ f"<td>{_number(facts.get('ligand_plddt'))}</td>"
1308
+ f"<td>{_number(facts.get('buried_fraction'), percent=True)}</td>"
1309
+ f"<td>{facts.get('warnings', '') if first is not None else ''}</td></tr>")
1310
+ out.append("</table></main></body></html>\n")
1311
+ return "".join(out)
1312
+
1313
+ _CSS = ("body{font:15px/1.5 -apple-system,'Segoe UI',Helvetica,Arial,sans-serif;color:#1f2933;margin:0;"
1314
+ "background:#f8fafc}main{max-width:1080px;margin:0 auto;padding:28px 24px 80px}"
1315
+ "h1{font-size:24px;margin:0 0 4px}h2{font-size:18px;margin:40px 0 6px}h3{font-size:15px;margin:0 0 4px}"
1316
+ "p{max-width:84ch;margin:6px 0}.quiet{color:#52606d}"
1317
+ "table{border-collapse:collapse;margin:8px 0;font-size:14px}td,th{border:1px solid #d9e2ec;"
1318
+ "padding:4px 10px;text-align:left;vertical-align:top}th{background:#eef2f6;font-weight:600}"
1319
+ "article{background:#fff;border:1px solid #d9e2ec;border-radius:8px;padding:16px 18px;margin:14px 0}"
1320
+ "pre{background:#f1f5f9;border-radius:6px;padding:10px 12px;overflow-x:auto;font-size:12.5px;"
1321
+ "line-height:1.45}.fig{overflow-x:auto;margin:10px 0}.fig svg{display:block;max-width:100%;height:auto}"
1322
+ ".badge{display:inline-block;border-radius:10px;padding:1px 9px;font-size:12px;font-weight:600;"
1323
+ "color:#fff;background:#2f855a;margin-right:8px}.badge.degraded{background:#b7791f}"
1324
+ ".badge.refused,.badge.unreadable{background:#c53030}.badge.empty,.badge.not{background:#718096}"
1325
+ "ul{margin:6px 0;padding-left:22px}li{margin:2px 0}code{font-size:13px}"
1326
+ "h4{font-size:14px;margin:18px 0 4px}.views{display:grid;grid-template-columns:repeat(auto-fit,"
1327
+ "minmax(320px,1fr));gap:14px}.views figure{margin:0;min-width:0}.views pre{white-space:pre-wrap}"
1328
+ "figcaption{font-size:13px}.k{white-space:nowrap}")
1329
+
1330
+
1331
+ def _page(result: Survey) -> str:
1332
+ esc = html.escape
1333
+ found, by, models = result.found, result.beside, result.models
1334
+ out = ["<!doctype html><html lang='en'><head><meta charset='utf-8'>"
1335
+ f"<title>bindview report: {esc(result.path.name)}</title><style>{_CSS}</style></head><body><main>",
1336
+ f"<h1>What {esc(result.path.name)} holds, and its figures</h1>",
1337
+ "<p>Nobody said what kind of input this is: the report looked. Each figure is drawn by the call "
1338
+ "printed above it; copy a call and change it. A call names its files from the folder of the input: "
1339
+ "run it there. Under a figure, its views: the same object drawn again by the line printed above each. "
1340
+ f"bindview {esc(__version__)}; PLIP is {'installed' if result.plip else 'not installed'} "
1341
+ "where this ran.</p>",
1342
+ "<h2>What the input holds</h2>"]
1343
+ if result.kind == "series":
1344
+ out.append(f"<p>{len(result.members)} complexes of one protein, each with one small molecule: a series of "
1345
+ "ligands. The chains below are those of the first.</p>")
1346
+ out.append("<table><tr><th>member</th><th>ligand</th><th>heavy atoms</th><th>SMILES</th><th>contacts from</th></tr>"
1347
+ + "".join(f"<tr><td>{esc(m.name)}</td><td>{esc(m.ligand.name)} ({esc(m.ligand.formula)})</td>"
1348
+ f"<td>{m.ligand.heavy}</td><td>{esc(m.smiles_from)}</td>"
1349
+ f"<td>{esc(m.table.name) if m.table else 'the table of heavy atoms'}</td></tr>"
1350
+ for m in result.members) + "</table>")
1351
+ elif len(models) > 1:
1352
+ out.append(f"<p>{len(models)} models of one composition: {esc(', '.join(m.name for m in models[:8]))}"
1353
+ f"{' and more' if len(models) > 8 else ''}. What follows is read from the first.</p>")
1354
+ elif result.models_in_file > 1:
1355
+ out.append(f"<p>{esc(models[0].name)} holds {result.models_in_file} models. "
1356
+ "What follows is read from the first.</p>")
1357
+ else:
1358
+ out.append(f"<p>One model: {esc(models[0].name)}.</p>")
1359
+ out.append("<table><tr><th>chain</th><th>what it is</th><th>residues</th></tr>" + "".join(
1360
+ f"<tr><td>{esc(c.name)}</td><td>{esc(c.what)}</td><td>{c.residues or ''}</td></tr>"
1361
+ for c in found.chains) + "</table>")
1362
+ if result.kind == "series":
1363
+ pass # the ligands of a series stand in the table above
1364
+ elif found.candidates:
1365
+ out.append("<table><tr><th>other residue</th><th>copies</th><th>heavy atoms</th><th>taken for</th>"
1366
+ "<th>within bonding distance of a chain</th></tr>" + "".join(
1367
+ f"<tr><td>{esc(c.name)}</td><td>{c.copies}</td><td>{c.heavy}</td><td>{c.kind}</td>"
1368
+ f"<td>{'yes' if c.bonded else ''}</td></tr>" for c in found.candidates) + "</table>")
1369
+ else:
1370
+ out.append("<p>No residue outside the chains but water.</p>")
1371
+ seen = [f"{found.waters} water{'s' if found.waters != 1 else ''}",
1372
+ "the file declares a per-atom pLDDT, which the figures draw" if found.plddt
1373
+ else "the file declares no pLDDT",
1374
+ f"predicted aligned errors beside the model ({by.pae.name})" if by.pae
1375
+ else "no file of predicted aligned errors beside the model"]
1376
+ if by.summary:
1377
+ seen.append(f"a summary of the model's own scores beside it ({by.summary.name})")
1378
+ seen.append("tables of contacts beside the model: " + ", ".join(t[0].name for t in by.tables[:6])
1379
+ + (f" and {len(by.tables) - 6} more" if len(by.tables) > 6 else "") if by.tables
1380
+ else "no table of contacts beside the model")
1381
+ if by.not_tables:
1382
+ seen.append("not read as a table of contacts: " + "; ".join(f"{p.name} ({why})" for p, why in by.not_tables[:6])
1383
+ + (f"; and {len(by.not_tables) - 6} more" if len(by.not_tables) > 6 else ""))
1384
+ out.append("<ul>" + "".join(f"<li>{esc(s)}</li>" for s in seen) + "</ul>")
1385
+ drawn = result.tracks
1386
+ out.append(f"<h2>The figures ({len(drawn)})</h2>")
1387
+ if not drawn:
1388
+ out.append("<p>None. What was found is listed below, with what is missing.</p>")
1389
+ for t in drawn:
1390
+ notes = "".join(f"<li>{esc(s)}</li>" for s in t.said)
1391
+ status = t.status or "not run"
1392
+ shown = [v for v in t.views if v.svg]
1393
+ views = "".join(f"<figure><pre><code>{esc(v.line)}</code></pre><div class='fig'>{v.svg}</div>"
1394
+ f"<figcaption class='quiet'>{esc(v.title)}</figcaption></figure>" for v in shown)
1395
+ unshown = "".join(f"<li>{esc(v.title)} (<code>{esc(v.line)}</code>): {esc(v.status)}"
1396
+ + (f": {esc(v.said[0])}" if v.said else "") + "</li>" for v in t.views if not v.svg)
1397
+ out.append(f"<article><h3>{esc(t.title)}</h3><p class='quiet'>{esc(t.why)}</p><pre><code>{esc(t.code)}"
1398
+ f"</code></pre><div class='fig'>{t.svg}</div><p><span class='badge {esc(status.split()[0])}'>"
1399
+ f"{esc(status)}</span></p>" + (f"<ul class='quiet'>{notes}</ul>" if notes else "")
1400
+ + (f"<h4>Views ({len(shown)})</h4><div class='views'>{views}</div>" if shown else "")
1401
+ + (f"<ul class='quiet'>{unshown}</ul>" if unshown else "") + "</article>")
1402
+ if result.left:
1403
+ out.append("<h2>Found, and not drawn</h2>")
1404
+ out.append("<table><tr><th>found</th><th>why it has no figure</th></tr>" + "".join(
1405
+ f"<tr><td>{esc(what)}</td><td>{esc(why)}</td></tr>" for what, why in result.left) + "</table>")
1406
+ out.append("</main></body></html>\n")
1407
+ return "".join(out)