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/structure.py ADDED
@@ -0,0 +1,1145 @@
1
+ """Reading atoms out of structure files.
2
+
3
+ Only what a 2D diagram needs is read: atom names, elements, residue identity,
4
+ coordinates and the B-factor column. mmCIF is parsed with a small tokenizer of
5
+ our own so the core has no dependency beyond RDKit and NumPy; legacy PDB files
6
+ are supported too.
7
+
8
+ The B-factor column is kept as the number it is. Whether it may be read as a
9
+ *confidence* (pLDDT) is a separate question that the file answers itself: a
10
+ predicted model declares a local pLDDT metric in ``_ma_qa_metric``, a crystal
11
+ structure does not, and in a crystal structure the same column is a
12
+ temperature factor where high means worse. :attr:`Structure.plddt_scale` records
13
+ the declaration; nothing in this package guesses from the value range.
14
+
15
+ The file is opened read-only and never written to.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import gzip
21
+ import re
22
+ from dataclasses import dataclass, field, replace
23
+ from pathlib import Path
24
+ from typing import Iterable, Iterator, Mapping, Sequence
25
+
26
+ import numpy as np
27
+
28
+ from .chem import is_metal
29
+ from .errors import LigandNotFoundError, StructureError
30
+ from .exposure import WATER_NAMES
31
+ from .near import pairs_within
32
+
33
+ __all__ = ["Atom", "ResidueKey", "ChainResidue", "Link", "Structure", "read_structure", "read_models", "parse_mmcif",
34
+ "parse_pdb", "MAX_LIGAND_RESIDUES"]
35
+
36
+ #: A chain with more residues than this is not drawn as a ligand, whole: no page holds it at a
37
+ #: legible size (54 boxes is what the default page takes). It is then one side of an interface,
38
+ #: of which :mod:`bindview.interface` draws the residues that touch the other side.
39
+ MAX_LIGAND_RESIDUES = 54
40
+ #: Two heavy atoms closer than this (ångström) are not two atoms.
41
+ _TOO_CLOSE = 1.05
42
+
43
+
44
+ @dataclass(frozen=True, order=True)
45
+ class ResidueKey:
46
+ """Identity of one residue: chain, residue number and insertion code."""
47
+
48
+ chain: str
49
+ number: int
50
+ icode: str = ""
51
+
52
+ def __str__(self) -> str:
53
+ return f"{self.chain}:{self.number}{self.icode}"
54
+
55
+
56
+ @dataclass(frozen=True)
57
+ class ChainResidue:
58
+ """One residue of a polymer chain that is taken as the ligand, as the file has it.
59
+
60
+ When a whole chain is the ligand its atoms become one lump, like the single
61
+ component a co-folding model writes for a peptide, and every atom gets a
62
+ name that is unique in it: ``63/OE1`` is atom ``OE1`` of residue 63. This
63
+ record keeps what the file said about the residue those atoms came from.
64
+ """
65
+
66
+ name: str # component name: "GLU", "TYS", "ACE"
67
+ number: str # residue number as deposited, with its insertion code: "63", "63A"
68
+ atoms: tuple[str, ...] # the names its heavy atoms have in the ligand
69
+
70
+
71
+ @dataclass(frozen=True)
72
+ class Link:
73
+ """A bond between two residues that the file declares: a ``_struct_conn`` row of a covalent kind, a
74
+ ``LINK`` record."""
75
+
76
+ a: ResidueKey
77
+ a_atom: str
78
+ b: ResidueKey
79
+ b_atom: str
80
+
81
+
82
+ @dataclass(frozen=True)
83
+ class Atom:
84
+ """One atom record."""
85
+
86
+ index: int
87
+ name: str
88
+ element: str
89
+ resname: str
90
+ chain: str
91
+ resnum: int
92
+ icode: str
93
+ x: float
94
+ y: float
95
+ z: float
96
+ hetero: bool
97
+ #: ``_atom_site.B_iso_or_equiv`` / the PDB B-factor column, as written.
98
+ b_iso: float | None = None
99
+ #: ``_atom_site.label_asym_id`` where the file has it beside the author's chain name (``chain``):
100
+ #: the two differ in many deposited structures, and a caller may know a chain by either.
101
+ label_chain: str = ""
102
+
103
+ @property
104
+ def residue(self) -> ResidueKey:
105
+ return ResidueKey(self.chain, self.resnum, self.icode)
106
+
107
+ @property
108
+ def xyz(self) -> tuple[float, float, float]:
109
+ return (self.x, self.y, self.z)
110
+
111
+
112
+ @dataclass
113
+ class Structure:
114
+ """A parsed structure: a flat atom list plus lookup tables.
115
+
116
+ ``chem_comp_smiles`` carries ``_chem_comp.pdbx_smiles`` when the file has it
117
+ (AlphaFold 3 writes the input SMILES there), keyed by component id.
118
+
119
+ ``plddt_scale`` is ``None`` unless the file *declares* that its B-factor
120
+ column holds a per-atom pLDDT (a ``_ma_qa_metric`` row with mode ``local``
121
+ and a pLDDT type); it is then the factor that brings the column to the
122
+ usual 0-100 scale (1, or 100 for the ``in [0,1]`` variants).
123
+ ``qa_metrics`` lists every declared metric as ``(mode, name, type)``.
124
+ """
125
+
126
+ atoms: list[Atom]
127
+ source: str = ""
128
+ chem_comp_smiles: dict[str, str] = field(default_factory=dict)
129
+ plddt_scale: float | None = None
130
+ qa_metrics: tuple[tuple[str, str, str], ...] = ()
131
+ #: The bonds between residues that the file declares (:class:`Link`), metal coordination left out.
132
+ links: tuple[Link, ...] = ()
133
+ _by_residue: dict[ResidueKey, list[int]] = field(default_factory=dict, repr=False)
134
+ _coords: np.ndarray | None = field(default=None, repr=False)
135
+ #: The number of this model in its file, where it was read as one of the file's models
136
+ #: (``read_structure(path, model=n)``, :func:`read_models`). ``None`` for a structure that was read
137
+ #: without naming a model: the first model of its file, whatever number that has.
138
+ model: int | None = None
139
+ #: The accessions of the entries of sequence databases that the file assigns to each chain, by the
140
+ #: chain's author name (``_struct_ref`` with ``_struct_ref_seq`` of an mmCIF file; :meth:`chains_of`).
141
+ accessions: dict[str, tuple[str, ...]] = field(default_factory=dict)
142
+
143
+ def __post_init__(self) -> None:
144
+ if not self._by_residue:
145
+ table: dict[ResidueKey, list[int]] = {}
146
+ for a in self.atoms:
147
+ table.setdefault(a.residue, []).append(a.index)
148
+ self._by_residue = table
149
+
150
+ # -- lookups -----------------------------------------------------------
151
+ @property
152
+ def coords(self) -> np.ndarray:
153
+ """``(n_atoms, 3)`` array of coordinates."""
154
+ if self._coords is None:
155
+ self._coords = np.array([a.xyz for a in self.atoms], dtype=float).reshape(-1, 3)
156
+ return self._coords
157
+
158
+ def residues(self) -> list[ResidueKey]:
159
+ """All residues, in file order."""
160
+ return list(self._by_residue)
161
+
162
+ def residue_atoms(self, key: ResidueKey) -> list[Atom]:
163
+ """The atoms of a residue."""
164
+ return [self.atoms[i] for i in self._by_residue.get(key, [])]
165
+
166
+ def residue_name(self, key: ResidueKey) -> str:
167
+ """The name of a residue, as the file gives it."""
168
+ idx = self._by_residue.get(key)
169
+ return self.atoms[idx[0]].resname if idx else ""
170
+
171
+ def find_residue(self, chain: str | None, number: int, icode: str = "") -> ResidueKey | None:
172
+ """Locate a residue by number; ``chain=None`` matches any chain if unique."""
173
+ if chain:
174
+ key = ResidueKey(chain, number, icode)
175
+ return key if key in self._by_residue else None
176
+ hits = [k for k in self._by_residue if k.number == number and k.icode == icode]
177
+ return hits[0] if len(hits) == 1 else None
178
+
179
+ @property
180
+ def declares_plddt(self) -> bool:
181
+ """Does the file itself say that its B-factor column is a per-atom pLDDT?"""
182
+ return self.plddt_scale is not None
183
+
184
+ # -- a chain by the protein it is ----------------------------------------
185
+ def chains_of(self, accession: str) -> list[str]:
186
+ """The chains that the file assigns to an entry of a sequence database, by their author names, in
187
+ the order of the file: a UniProt accession (``"P69905"``), or that of an isoform (``"P27348-2"``)
188
+ where the file names the isoform.
189
+
190
+ Read from ``_struct_ref`` and ``_struct_ref_seq`` of an mmCIF file, which the entries of the PDB
191
+ and the models of the AlphaFold database have. A file without them assigns no chain to anything: a
192
+ PDB file, a model of AlphaFold 3 or of Boltz. The copies of one protein (the two chains of a
193
+ homodimer) are all its chains; a chain that was cut into parts (:meth:`split`) is its parts. A
194
+ chain that the file names and that has no atom is not among them.
195
+ """
196
+ wanted = accession.strip().upper()
197
+ present = {a.chain for a in self.atoms}
198
+ return [c for c, names in self.accessions.items() if wanted in names and c in present]
199
+
200
+ def chain_of(self, accession: str) -> str:
201
+ """The one chain that the file assigns to an entry of a sequence database (:meth:`chains_of`): for
202
+ a caller who knows a protein by its accession and not by the name of its chain in this file.
203
+
204
+ Where the file assigns the entry to no chain, or to several (the copies of a homodimer), that is an
205
+ error which says what the file assigns. A chain is never chosen for the caller: a figure of the
206
+ wrong chain names real residues at real places and shows no sign of the mistake.
207
+ """
208
+ found = self.chains_of(accession)
209
+ if len(found) == 1:
210
+ return found[0]
211
+ what = self.source or "the structure"
212
+ if found:
213
+ raise StructureError(f"{what} assigns {accession} to {len(found)} chains ({', '.join(found)}): which "
214
+ f"of them is meant has to be said by its name")
215
+ assigned = "; ".join(f"chain {c}: {', '.join(names)}" for c, names in self.accessions.items())
216
+ raise StructureError(f"{what} assigns {accession} to no chain"
217
+ + (f" ({assigned})" if assigned else
218
+ ": it assigns no entry of a sequence database to any chain (no _struct_ref)"))
219
+
220
+ # -- a polymer chain as the ligand ---------------------------------------
221
+ def polymer_residues(self, chain: str) -> list[ResidueKey]:
222
+ """The residues of ``chain`` that make up its polymer, in file order.
223
+
224
+ Those with a backbone of their own (atoms ``N``, ``CA`` and ``C``) and
225
+ whatever is covalently bound to one of them: a cap such as ``ACE``, a
226
+ modified residue. Waters are never part of it, and neither is anything
227
+ else that merely carries the chain's name -- a deposited structure
228
+ files an ion or a solvent molecule under the chain it lies next to.
229
+ """
230
+ keys = [k for k in self._by_residue if k.chain == chain and self.residue_name(k).upper() not in WATER_NAMES]
231
+ heavy = {k: [a for a in self.residue_atoms(k) if a.element not in ("H", "D")] for k in keys}
232
+ inside = [k for k in keys if {"N", "CA", "C"} <= {a.name for a in heavy[k]}]
233
+ if not inside:
234
+ inside = self._nucleotides(chain) # a chain of RNA or DNA has no such residue
235
+ if not inside:
236
+ return []
237
+ rest = [k for k in keys if k not in inside and heavy[k]]
238
+ grew = True
239
+ while grew and rest:
240
+ grew = False
241
+ have = np.array([a.xyz for k in inside for a in heavy[k]], dtype=float)
242
+ big = np.array([a.element in ("S", "P", "SE", "Se") for k in inside for a in heavy[k]])
243
+ for k in list(rest):
244
+ pts = np.array([a.xyz for a in heavy[k]], dtype=float)
245
+ own = np.array([a.element in ("S", "P", "SE", "Se") for a in heavy[k]])
246
+ d = np.linalg.norm(pts[:, None, :] - have[None, :, :], axis=2)
247
+ limit = np.where(own[:, None] | big[None, :], 2.3, 1.9)
248
+ if (d < limit).any():
249
+ inside.append(k)
250
+ rest.remove(k)
251
+ grew = True
252
+ order = {k: i for i, k in enumerate(keys)}
253
+ return sorted(inside, key=lambda k: order[k])
254
+
255
+ def split(self, chain: str, parts: "Mapping[str, tuple[int, int]]") -> "Structure":
256
+ """The structure with stretches of ``chain`` under chain names of their own.
257
+
258
+ ``parts`` maps a new chain name to the first and the last residue number of a stretch: the
259
+ domains of one chain, which an :class:`~bindview.interface.Interface` then takes as two
260
+ participants (a participant is whole chains). Residues of the chain outside every stretch
261
+ keep its name, and so does everything else. A name that a chain already has, a stretch that
262
+ holds no residue, and two stretches that overlap are errors.
263
+ """
264
+ taken = {a.chain for a in self.atoms}
265
+ spans = {name: (int(lo), int(hi)) for name, (lo, hi) in parts.items()}
266
+ for name, (lo, hi) in spans.items():
267
+ if name in taken:
268
+ raise StructureError(f"a part cannot be called {name!r}: the structure has a chain of that name")
269
+ if lo > hi:
270
+ raise StructureError(f"part {name!r} runs from {lo} to {hi}: the first number comes first")
271
+ if any(other != name and lo <= b and a <= hi for other, (a, b) in spans.items()):
272
+ raise StructureError(f"part {name!r} ({lo} to {hi}) overlaps another part of chain {chain!r}")
273
+ if not any(a.chain == chain and lo <= a.resnum <= hi for a in self.atoms):
274
+ raise StructureError(f"chain {chain!r} has no residue from {lo} to {hi} (part {name!r})")
275
+
276
+ def named(atom: Atom) -> str:
277
+ if atom.chain != chain:
278
+ return atom.chain
279
+ return next((name for name, (lo, hi) in spans.items() if lo <= atom.resnum <= hi), chain)
280
+
281
+ accessions = dict(self.accessions)
282
+ if chain in accessions:
283
+ accessions.update({name: accessions[chain] for name in spans})
284
+ return replace(self, atoms=[replace(a, chain=named(a)) for a in self.atoms], _by_residue={}, _coords=None,
285
+ accessions=accessions)
286
+
287
+ def with_chain_as_ligand(self, chain: str
288
+ ) -> tuple["Structure", ResidueKey, tuple[ChainResidue, ...], list[str]]:
289
+ """The structure with the polymer of ``chain`` turned into one ligand residue.
290
+
291
+ Returns the new structure, the key of that residue, what the file said
292
+ about the residues it was made of, and notes on anything that was not
293
+ taken as it stood. Nothing else in the structure changes, so every
294
+ other chain is environment as before.
295
+
296
+ One thing is not taken as it stands: a heavy atom less than
297
+ :data:`_TOO_CLOSE` ångström from another one. No two heavy atoms are
298
+ that close; in a deposited structure it is a mislabelled hydrogen or a
299
+ duplicate. Of such a pair the atom that is bonded to nothing else is
300
+ left out of the structure altogether, and a note says so.
301
+ """
302
+ keys = self.polymer_residues(chain)
303
+ if not keys:
304
+ raise LigandNotFoundError(f"chain {chain!r} of {self.source or 'the structure'} has no polymer residues")
305
+ if len(keys) > MAX_LIGAND_RESIDUES:
306
+ raise LigandNotFoundError(
307
+ f"chain {chain!r} has {len(keys)} residues. A chain of more than {MAX_LIGAND_RESIDUES} is not "
308
+ f"drawn as a ligand: it is one side of an interface. Draw the interface between it and its "
309
+ f"partner instead (bindview interface, or bindview.Interface), which shows the residues of each "
310
+ f"side that touch the other")
311
+ return self.with_residues_as_ligand(keys)
312
+
313
+ def with_residues_as_ligand(self, keys: Sequence[ResidueKey]
314
+ ) -> tuple["Structure", ResidueKey, tuple[ChainResidue, ...], list[str]]:
315
+ """The structure with these residues of one chain turned into one ligand residue.
316
+
317
+ What :meth:`with_chain_as_ligand` does for a whole chain, for any
318
+ residues of a chain: the interface residues of one participant, which
319
+ are the *spine* of an interface figure (:mod:`bindview.interface`). The
320
+ residues that are not named stay what they were.
321
+ """
322
+ keys = list(keys)
323
+ if not keys or len({k.chain for k in keys}) != 1:
324
+ raise LigandNotFoundError("the residues that are drawn as one chain have to be of one chain")
325
+ chain = keys[0].chain
326
+ notes: list[str] = []
327
+ heavy = [a for k in keys for a in self.residue_atoms(k) if a.element not in ("H", "D")]
328
+ xyz = np.array([a.xyz for a in heavy], dtype=float)
329
+ # The pairs within bonding distance (each twice, and each atom with itself), never the array of all pairs.
330
+ first, second, apart = pairs_within(xyz, xyz, 1.9)
331
+ bonded = np.bincount(first[(apart < 1.9) & (apart > _TOO_CLOSE)], minlength=len(heavy))
332
+ clash = (apart < _TOO_CLOSE) & (first < second)
333
+ dropped: set[int] = set()
334
+ for i, j, d in zip(first[clash].tolist(), second[clash].tolist(), apart[clash].tolist()):
335
+ if heavy[i].index in dropped or heavy[j].index in dropped:
336
+ continue # (an atom too close to two others goes once, with one note)
337
+ # Of the two the one that is bonded to fewer other atoms goes, and of two that are bonded alike
338
+ # the one that comes later in the file.
339
+ out = i if bonded[i] < bonded[j] else j
340
+ keep = j if out == i else i
341
+ a, b = heavy[out], heavy[keep]
342
+ dropped.add(a.index)
343
+ notes.append(f"atom {a.name} of {a.resname} {a.resnum}{a.icode} lies {d:.2f} \u00c5 from "
344
+ f"{b.name} of {b.resname} {b.resnum}{b.icode} and was left out: no two heavy atoms "
345
+ f"are that close")
346
+ merged = ResidueKey(chain, keys[0].number, keys[0].icode)
347
+ wanted = set(keys)
348
+ atoms: list[Atom] = []
349
+ residues: dict[ResidueKey, list[str]] = {k: [] for k in keys}
350
+ for a in self.atoms:
351
+ if a.index in dropped:
352
+ continue
353
+ if a.residue in wanted:
354
+ name = f"{a.resnum}{a.icode}/{a.name}"
355
+ if a.element not in ("H", "D"):
356
+ residues[a.residue].append(name)
357
+ a = replace(a, name=name, resname=f"CHAIN_{chain}", resnum=merged.number, icode=merged.icode,
358
+ hetero=True)
359
+ atoms.append(replace(a, index=len(atoms)))
360
+ given = tuple(ChainResidue(self.residue_name(k), f"{k.number}{k.icode}", tuple(residues[k]))
361
+ for k in keys if residues[k])
362
+ return replace(self, atoms=atoms, _by_residue={}, _coords=None), merged, given, notes
363
+
364
+ def resolve_ligand(self, spec: "str | ResidueKey | tuple[str, int | str]"
365
+ ) -> tuple["Structure", ResidueKey, tuple[ChainResidue, ...], list[str]]:
366
+ """Resolve a ligand selection that may also name a whole polymer chain.
367
+
368
+ Everything :meth:`select_ligand` accepts, and in addition::
369
+
370
+ "C" chain C, when no residue is named ``C`` and the chain is a polymer
371
+ "chain:C" chain C, said outright
372
+
373
+ A chain is looked up by the name its authors gave it
374
+ (``auth_asym_id``, what every other part of this package and a PDB
375
+ file call the chain). Only if there is no such chain, the name is tried
376
+ as the mmCIF ``label_asym_id``, and a note says which chain that is.
377
+
378
+ A chain that is the ligand comes back as one residue of a new
379
+ structure, together with the residues the file gave it (see
380
+ :meth:`with_chain_as_ligand`); for any other selection the structure is
381
+ returned as it is and the third element is empty. Which chain is the
382
+ ligand is never guessed: the caller names it.
383
+ """
384
+ if isinstance(spec, str):
385
+ text = spec.strip()
386
+ head, _, tail = text.partition(":")
387
+ said = head.lower() == "chain" and bool(tail) and ":" not in tail
388
+ name = tail if said else text
389
+ if said or (":" not in text and not any(self.residue_name(k) == text for k in self._by_residue)):
390
+ if said or len(self._backbone(name)) >= 2:
391
+ if self._backbone(name) or not self._by_label(name):
392
+ return self.with_chain_as_ligand(name)
393
+ by_label = self._by_label(name)
394
+ if len(by_label) == 1 and len(self._backbone(by_label[0])) >= (1 if said else 2):
395
+ st, key, given, notes = self.with_chain_as_ligand(by_label[0])
396
+ return st, key, given, [f"chain {name!r} is the file's label_asym_id; its authors call the "
397
+ f"chain {by_label[0]!r}, and so does the figure"] + notes
398
+ return self, self.select_ligand(spec), (), []
399
+
400
+ def _backbone(self, chain: str) -> list[ResidueKey]:
401
+ return [k for k in self._by_residue if k.chain == chain
402
+ and {"N", "CA", "C"} <= {a.name for a in self.residue_atoms(k)}] or self._nucleotides(chain)
403
+
404
+ def _nucleotides(self, chain: str) -> list[ResidueKey]:
405
+ """The nucleotides of ``chain`` that are joined to one another, in file order: residues with a
406
+ sugar (``C1'``, ``C3'``, ``C4'``, ``O4'``) whose ``O3'`` is bound to the phosphorus of another.
407
+ By their atoms and not by their names, so a modified nucleotide is one. Two nucleotides that
408
+ merely lie in one chain, two copies of a cofactor, are no chain."""
409
+ found: dict[ResidueKey, dict[str, Atom]] = {}
410
+ for k in self._by_residue:
411
+ if k.chain != chain or self.residue_name(k).upper() in WATER_NAMES:
412
+ continue
413
+ atoms = {a.name.replace("*", "'"): a for a in self.residue_atoms(k)}
414
+ if {"C1'", "C3'", "C4'", "O4'"} <= set(atoms):
415
+ found[k] = atoms
416
+ ends = [(k, atoms["O3'"]) for k, atoms in found.items() if "O3'" in atoms]
417
+ heads = [(k, atoms["P"]) for k, atoms in found.items() if "P" in atoms]
418
+ joined: set[ResidueKey] = set()
419
+ for k, o3 in ends:
420
+ for other, p in heads:
421
+ if other != k and (o3.x - p.x) ** 2 + (o3.y - p.y) ** 2 + (o3.z - p.z) ** 2 < 2.0 ** 2:
422
+ joined.update((k, other))
423
+ return [k for k in found if k in joined]
424
+
425
+ def _by_label(self, label: str) -> list[str]:
426
+ """The author chain names of the polymer atoms whose ``label_asym_id`` is ``label``."""
427
+ return sorted({a.chain for a in self.atoms if a.label_chain == label and a.resname.upper() not in WATER_NAMES
428
+ and a.name in ("N", "CA", "C", "C4'", "C4*")})
429
+
430
+ def atom_by_name(self, key: ResidueKey, name: str) -> Atom | None:
431
+ """An atom of a residue by its name, or None."""
432
+ for i in self._by_residue.get(key, []):
433
+ if self.atoms[i].name == name:
434
+ return self.atoms[i]
435
+ return None
436
+
437
+ # -- ligand selection --------------------------------------------------
438
+ def select_ligand(self, spec: "str | ResidueKey | tuple[str, int | str]") -> ResidueKey:
439
+ """Resolve a ligand selection to exactly one residue.
440
+
441
+ Accepted forms::
442
+
443
+ "LIG_B" residue (component) name
444
+ "B:1" chain and residue number
445
+ "B:LIG_B:1" chain, residue name and number
446
+ ("B", 1) chain and residue number
447
+ ("B", "1A") chain and residue number with its insertion code
448
+ ResidueKey used as is
449
+
450
+ A bare name that matches several residues is an error rather than a
451
+ silent pick of the first: the caller has to say which copy is meant.
452
+ """
453
+ if isinstance(spec, ResidueKey):
454
+ if spec not in self._by_residue:
455
+ raise LigandNotFoundError(f"no residue {spec} in {self.source or 'structure'}")
456
+ return spec
457
+ if isinstance(spec, tuple):
458
+ try:
459
+ chain, given = spec
460
+ m = re.fullmatch(r"(-?\d+)([A-Za-z]?)", given.strip() if isinstance(given, str) else str(int(given)))
461
+ if m is None:
462
+ raise ValueError(given)
463
+ except (TypeError, ValueError):
464
+ raise LigandNotFoundError(
465
+ f"cannot parse ligand selection {spec!r}; a pair is (chain, number), the number with its "
466
+ f"insertion code where it has one: ('A', 698) or ('A', '698A')") from None
467
+ number, icode = int(m.group(1)), m.group(2)
468
+ key = self.find_residue(str(chain), number, icode)
469
+ if key is None:
470
+ raise LigandNotFoundError(f"no residue {chain}:{number}{icode} in {self.source or 'structure'}")
471
+ return key
472
+ text = str(spec).strip()
473
+ if not text:
474
+ raise LigandNotFoundError("empty ligand selection")
475
+ parts = text.split(":")
476
+ if len(parts) == 1:
477
+ hits = [k for k in self._by_residue if self.residue_name(k) == text]
478
+ if not hits:
479
+ # Convenience: a bare chain id whose chain holds a single hetero residue.
480
+ chain_hits = [k for k in self._by_residue if k.chain == text]
481
+ het = [k for k in chain_hits if all(a.hetero for a in self.residue_atoms(k))]
482
+ if len(het) == 1:
483
+ return het[0]
484
+ names = sorted({self.residue_name(k) for k in self._by_residue
485
+ if any(a.hetero for a in self.residue_atoms(k))})
486
+ raise LigandNotFoundError(
487
+ f"no residue named {text!r}; hetero residues present: {', '.join(names) or 'none'}")
488
+ if len(hits) > 1:
489
+ listed = ", ".join(str(k) for k in hits[:8])
490
+ raise LigandNotFoundError(
491
+ f"{len(hits)} residues are named {text!r} ({listed}); select one as 'chain:number'")
492
+ return hits[0]
493
+ try:
494
+ if len(parts) == 2:
495
+ chain, numtxt, name = parts[0], parts[1], None
496
+ elif len(parts) == 3:
497
+ chain, name, numtxt = parts
498
+ else:
499
+ raise ValueError(text)
500
+ m = re.fullmatch(r"(-?\d+)([A-Za-z]?)", numtxt)
501
+ if not m:
502
+ raise ValueError(text)
503
+ number, icode = int(m.group(1)), m.group(2)
504
+ except ValueError:
505
+ raise LigandNotFoundError(
506
+ f"cannot parse ligand selection {text!r}; use 'NAME', 'chain:number' or 'chain:NAME:number'"
507
+ ) from None
508
+ key = self.find_residue(chain, number, icode)
509
+ if key is None or (name is not None and self.residue_name(key) != name):
510
+ raise LigandNotFoundError(f"no residue matching {text!r} in {self.source or 'structure'}")
511
+ return key
512
+
513
+
514
+ # ---------------------------------------------------------------------------
515
+ # mmCIF
516
+ # ---------------------------------------------------------------------------
517
+
518
+ _TOKEN = re.compile(
519
+ r"""
520
+ '((?:[^']|'(?=\S))*)'(?=\s|$) # single-quoted (a quote only closes before whitespace)
521
+ | "((?:[^"]|"(?=\S))*)"(?=\s|$) # double-quoted
522
+ | (\#.*) # comment to end of line
523
+ | (\S+) # bare word
524
+ """,
525
+ re.VERBOSE,
526
+ )
527
+
528
+
529
+ def _tokens(lines: Sequence[str]) -> Iterator[tuple[str, bool]]:
530
+ """Yield ``(token, quoted)`` pairs from mmCIF text.
531
+
532
+ ``quoted`` distinguishes the literal string ``"loop_"`` from the keyword.
533
+ """
534
+ i, n = 0, len(lines)
535
+ while i < n:
536
+ line = lines[i]
537
+ if line.startswith(";"):
538
+ # Multi-line text field: runs until a line that starts with ';'.
539
+ buf = [line[1:].rstrip("\n")]
540
+ i += 1
541
+ while i < n and not lines[i].startswith(";"):
542
+ buf.append(lines[i].rstrip("\n"))
543
+ i += 1
544
+ yield "\n".join(buf).strip(), True
545
+ if i >= n:
546
+ break
547
+ line = lines[i][1:] # what follows the closing ';' on its line are values like any other
548
+ for m in _TOKEN.finditer(line):
549
+ if m.group(3) is not None:
550
+ break
551
+ if m.group(1) is not None:
552
+ yield m.group(1), True
553
+ elif m.group(2) is not None:
554
+ yield m.group(2), True
555
+ else:
556
+ yield m.group(4), False
557
+ i += 1
558
+
559
+
560
+ def _read_categories(text: str, wanted: set[str]) -> dict[str, dict[str, list[str]]]:
561
+ """Read the requested categories of the first data block as column tables."""
562
+ out: dict[str, dict[str, list[str]]] = {}
563
+ toks = _tokens(text.splitlines())
564
+ pending: tuple[str, bool] | None = None
565
+ seen_block = False
566
+
567
+ def nxt() -> tuple[str, bool] | None:
568
+ nonlocal pending
569
+ if pending is not None:
570
+ t, pending = pending, None
571
+ return t
572
+ return next(toks, None)
573
+
574
+ while True:
575
+ tok = nxt()
576
+ if tok is None:
577
+ break
578
+ word, quoted = tok
579
+ if quoted:
580
+ continue
581
+ low = word.lower()
582
+ if low.startswith("data_"):
583
+ if seen_block:
584
+ break # only the first data block
585
+ seen_block = True
586
+ continue
587
+ if low == "loop_":
588
+ names: list[str] = []
589
+ while True:
590
+ t = nxt()
591
+ if t is None:
592
+ break
593
+ if not t[1] and t[0].startswith("_"):
594
+ names.append(t[0])
595
+ else:
596
+ pending = t
597
+ break
598
+ if not names:
599
+ continue
600
+ cat = names[0].split(".", 1)[0].lower()
601
+ keep = cat in wanted
602
+ cols: list[list[str]] = [[] for _ in names]
603
+ k = 0
604
+ while True:
605
+ t = nxt()
606
+ if t is None:
607
+ break
608
+ w, q = t
609
+ if not q and (w.startswith("_") or w.lower() == "loop_" or w.lower().startswith("data_")):
610
+ pending = t
611
+ break
612
+ if keep:
613
+ cols[k].append(w)
614
+ k = (k + 1) % len(names)
615
+ if keep:
616
+ table = out.setdefault(cat, {})
617
+ for nm, col in zip(names, cols):
618
+ table[nm.split(".", 1)[1].lower() if "." in nm else nm.lower()] = col
619
+ continue
620
+ if word.startswith("_"):
621
+ val = nxt()
622
+ cat, _, item = word.partition(".")
623
+ if cat.lower() in wanted and val is not None:
624
+ out.setdefault(cat.lower(), {})[item.lower()] = [val[0]]
625
+ return out
626
+
627
+
628
+ def _int(text: str, default: int = 0) -> int:
629
+ try:
630
+ return int(text)
631
+ except ValueError:
632
+ return default
633
+
634
+
635
+ def _norm_element(symbol: str) -> str:
636
+ s = symbol.strip()
637
+ return s[:1].upper() + s[1:].lower() if s else ""
638
+
639
+
640
+ def _of_another_type(records: "Sequence[tuple[tuple[str, int, str], str, str]]") -> set[int]:
641
+ """The atom records that are not read because their position holds residues of two types.
642
+
643
+ ``records`` are the atom records of one model in the order of the file, each as its position (chain,
644
+ number, insertion code), its residue name and its alternate-location id (empty where it has none). A
645
+ file writes two residue types at one position as alternate locations of each other: serine as ``A``,
646
+ threonine as ``B``. Such a position is read as one residue, of the type of its first record and of that
647
+ type's first alternate location; a record of that type without an alternate-location id belongs to it
648
+ too. What is returned are the places in ``records`` of the others. A position with one residue type has
649
+ none among them, however many conformations it has. Nor has one where a second residue name stands
650
+ without an alternate-location id: that is no alternate location, but a number given twice (a ligand
651
+ that a docking program numbers like a residue of the protein), and nothing of it is left out.
652
+ """
653
+ types: dict[tuple[str, int, str], str] = {}
654
+ mixed: set[tuple[str, int, str]] = set()
655
+ for place, resname, alt in records:
656
+ if types.setdefault(place, resname) != resname and alt:
657
+ mixed.add(place)
658
+ out: set[int] = set()
659
+ if not mixed:
660
+ return out
661
+ location: dict[tuple[str, int, str], str] = {}
662
+ for k, (place, resname, alt) in enumerate(records):
663
+ if place in mixed and alt and (resname != types[place] or location.setdefault(place, alt) != alt):
664
+ out.add(k)
665
+ return out
666
+
667
+
668
+ def parse_mmcif(text: str, source: str = "", model: "int | None" = None) -> Structure:
669
+ """Parse mmCIF text into a :class:`Structure`.
670
+
671
+ Of the atoms that have one name in one residue, as the alternate locations of an atom have, the
672
+ first in the file is read. Where one position (chain, number, insertion code) holds residues of two
673
+ types, as alternate locations of each other, the residue is the one that comes first in the file, in
674
+ its first alternate location: the atoms of the other type are not read.
675
+
676
+ ``model``: the model to read, by the number the file gives it
677
+ (``_atom_site.pdbx_PDB_model_num``). ``None`` is the first model of the file.
678
+
679
+ A residue is numbered by ``auth_seq_id`` and, where the file has none, by ``label_seq_id``. A ligand
680
+ or a water has no ``label_seq_id`` (it is a dot): in a file without the author's numbers such a
681
+ residue is numbered after the last numbered residue of its chain, in the order of the file. The rows
682
+ of one such residue are those that follow one another with one chain and component name, until an
683
+ atom name comes a second time.
684
+ """
685
+ return _mmcif_models(text, source, _model_asked(model, source or "mmCIF"))[0]
686
+
687
+
688
+ def _mmcif_models(text: str, source: str, model: "int | None | str") -> list[Structure]:
689
+ """The models of mmCIF text: the first (``None``), the one numbered ``model``, or all of them
690
+ (``"all"``), each a structure of its own. The text is read once."""
691
+ cats = _read_categories(text, {"_atom_site", "_chem_comp", "_ma_qa_metric", "_struct_conn", "_struct_ref",
692
+ "_struct_ref_seq"})
693
+ site = cats.get("_atom_site")
694
+ if not site or "cartn_x" not in site:
695
+ raise StructureError(f"{source or 'mmCIF'}: no _atom_site coordinates found")
696
+ lacking = [written for written in ("Cartn_y", "Cartn_z") if written.lower() not in site]
697
+ if lacking:
698
+ raise StructureError(f"{source or 'mmCIF'}: _atom_site has no {', '.join(lacking)}")
699
+ lengths = [len(column) for column in site.values()]
700
+ if min(lengths) != max(lengths):
701
+ # The values of a loop are dealt to its columns in turn: columns of unequal length are a last row
702
+ # that is not whole. Read on, its atom would have no place, and the columns after the cut none at all.
703
+ raise StructureError(f"{source or 'mmCIF'}: the _atom_site loop ends inside a row: its last row has "
704
+ f"{lengths.count(max(lengths))} of {len(lengths)} values (a file that was cut short?)")
705
+ n = len(site["cartn_x"])
706
+
707
+ def col(*names: str) -> list[str] | None:
708
+ for nm in names:
709
+ c = site.get(nm)
710
+ if c is not None and len(c) == n:
711
+ return c
712
+ return None
713
+
714
+ xs, ys, zs = site["cartn_x"], site["cartn_y"], site["cartn_z"]
715
+ group = col("group_pdb")
716
+ element = col("type_symbol")
717
+ name = col("auth_atom_id", "label_atom_id")
718
+ comp = col("auth_comp_id", "label_comp_id")
719
+ chain = col("auth_asym_id", "label_asym_id")
720
+ label_chain = col("label_asym_id")
721
+ seq = col("auth_seq_id", "label_seq_id")
722
+ seq_alt = col("label_seq_id")
723
+ icode = col("pdbx_pdb_ins_code")
724
+ alt = col("label_alt_id")
725
+ numbers = col("pdbx_pdb_model_num")
726
+ b_iso = col("b_iso_or_equiv")
727
+ if name is None or comp is None or chain is None or seq is None:
728
+ raise StructureError(f"{source or 'mmCIF'}: _atom_site lacks atom/residue identifiers")
729
+
730
+ smiles: dict[str, str] = {}
731
+ cc = cats.get("_chem_comp")
732
+ if cc and "id" in cc and "pdbx_smiles" in cc:
733
+ for cid, smi in zip(cc["id"], cc["pdbx_smiles"]):
734
+ if smi not in ("?", "."):
735
+ smiles[cid] = smi
736
+ metrics, scale = _qa_metrics(cats.get("_ma_qa_metric"))
737
+ links = _mmcif_links(cats.get("_struct_conn"))
738
+ accessions = _accessions(cats.get("_struct_ref"), cats.get("_struct_ref_seq"))
739
+
740
+ def number_of(i: int) -> "int | None":
741
+ """The number the file gives the residue of row ``i``: the author's, else the label's, else none."""
742
+ for column in (seq, seq_alt):
743
+ if column is not None:
744
+ try:
745
+ return int(column[i])
746
+ except ValueError:
747
+ pass
748
+ return None
749
+
750
+ def build(rows: Sequence[int], number: "int | None") -> Structure:
751
+ atoms: list[Atom] = []
752
+ seen: set[tuple[str, int, str, str]] = set()
753
+ # A residue without a number (see parse_mmcif): the highest number of each chain, counted up for
754
+ # each such residue, and the one the rows are in, with the atoms it has so far and its number.
755
+ highest: "dict[str, int] | None" = None
756
+ within: "tuple[tuple[str, str, str], set[tuple[str, str]], int] | None" = None
757
+ places: list[tuple[tuple[str, int, str], str, str]] = []
758
+ for i in rows:
759
+ given = number_of(i)
760
+ if given is None:
761
+ if highest is None:
762
+ highest = {}
763
+ for j in rows:
764
+ other = number_of(j)
765
+ if other is not None and other > highest.get(chain[j], 0):
766
+ highest[chain[j]] = other
767
+ part = (chain[i], label_chain[i] if label_chain is not None else "", comp[i])
768
+ atom = (name[i], alt[i] if alt is not None else "")
769
+ if within is None or within[0] != part or atom in within[1]:
770
+ highest[chain[i]] = highest.get(chain[i], 0) + 1
771
+ within = (part, set(), highest[chain[i]])
772
+ within[1].add(atom)
773
+ num = within[2]
774
+ else:
775
+ num = given
776
+ ic = icode[i] if icode is not None and icode[i] not in (".", "?") else ""
777
+ location = alt[i] if alt is not None and alt[i] not in (".", "?") else ""
778
+ places.append(((chain[i], num, ic), comp[i], location))
779
+ left_out = _of_another_type(places)
780
+ for k, i in enumerate(rows):
781
+ if k in left_out:
782
+ continue # of another residue type than the one its position is read as
783
+ (_, num, ic), _, _ = places[k]
784
+ ident = (chain[i], num, ic, name[i])
785
+ if ident in seen:
786
+ continue # a second atom of that name in the residue: the first one is kept
787
+ seen.add(ident)
788
+ try:
789
+ x, y, z = float(xs[i]), float(ys[i]), float(zs[i])
790
+ except ValueError as exc:
791
+ raise StructureError(f"{source or 'mmCIF'}: bad coordinate in _atom_site row {i + 1}") from exc
792
+ el = _norm_element(element[i]) if element is not None else _guess_element(name[i])
793
+ atoms.append(Atom(
794
+ index=len(atoms), name=name[i], element=el, resname=comp[i], chain=chain[i],
795
+ resnum=num, icode=ic, x=x, y=y, z=z,
796
+ hetero=(group[i].upper() == "HETATM") if group is not None else False,
797
+ b_iso=_float_or_none(b_iso[i]) if b_iso is not None else None,
798
+ label_chain=label_chain[i] if label_chain is not None else "",
799
+ ))
800
+ if not atoms:
801
+ raise StructureError(f"{source or 'mmCIF'}: no atoms"
802
+ + (f" in model {number}" if number is not None else ""))
803
+ return Structure(atoms=atoms, source=source, chem_comp_smiles=dict(smiles), plddt_scale=scale,
804
+ qa_metrics=metrics, links=links, model=number, accessions=dict(accessions))
805
+
806
+ if model is None:
807
+ # The first model: the rows down to the first that belongs to another one.
808
+ first = numbers[0] if numbers else None
809
+ stop = next((i for i in range(n) if numbers is not None and numbers[i] != first), n)
810
+ return [build(range(stop), None)]
811
+ by_model: dict[str, list[int]] = {}
812
+ for i in range(n):
813
+ by_model.setdefault(numbers[i] if numbers is not None else "1", []).append(i)
814
+ numbered = _model_numbers(list(by_model))
815
+ if model == "all":
816
+ return [build(rows, number) for rows, number in zip(by_model.values(), numbered)]
817
+ if model not in numbered:
818
+ raise StructureError(_no_such_model(source or "mmCIF", model, numbered))
819
+ return [build(list(by_model.values())[numbered.index(model)], int(model))]
820
+
821
+
822
+ def _model_asked(model: "int | float | str | None", source: str) -> "int | None":
823
+ """The model that is asked for, as the number it is: also where it comes as text (``"2"``) or as a
824
+ whole number of another kind (``2.0``)."""
825
+ if model is None:
826
+ return None
827
+ try:
828
+ if isinstance(model, bool) or (isinstance(model, str) and not re.fullmatch(r"\s*[+-]?\d+\s*", model)):
829
+ raise ValueError(model)
830
+ number = int(model)
831
+ if not isinstance(model, str) and number != model:
832
+ raise ValueError(model)
833
+ except (TypeError, ValueError):
834
+ raise StructureError(f"{source}: model is the number of one model of the file, not {model!r} "
835
+ f"(read_models gives every model of a file)") from None
836
+ return number
837
+
838
+
839
+ def _model_numbers(written: "Sequence[str | None]") -> list[int]:
840
+ """The numbers of a file's models: those it writes, where they are numbers and no two are alike;
841
+ otherwise their order, from 1 (some programs write every frame as model 1, or with no number)."""
842
+ try:
843
+ numbers = [int(str(w)) for w in written]
844
+ except (TypeError, ValueError):
845
+ numbers = []
846
+ if len(numbers) != len(written) or len(set(numbers)) != len(numbers):
847
+ return list(range(1, len(written) + 1))
848
+ return numbers
849
+
850
+
851
+ def _no_such_model(source: str, model: object, numbered: "Sequence[int]") -> str:
852
+ if len(numbered) == 1:
853
+ return f"{source}: there is no model {model}: the file has one model, number {numbered[0]}"
854
+ listed = (", ".join(str(k) for k in numbered) if len(numbered) <= 12
855
+ else f"{numbered[0]} to {numbered[-1]}" if numbered == list(range(numbered[0], numbered[-1] + 1))
856
+ else ", ".join(str(k) for k in numbered[:12]) + ", ...")
857
+ return f"{source}: there is no model {model}: the file has {len(numbered)} models, numbered {listed}"
858
+
859
+
860
+ def _mmcif_links(table: "dict[str, list[str]] | None") -> tuple[Link, ...]:
861
+ """The covalent bonds of ``_struct_conn`` within one copy of the molecules."""
862
+ if not table or "conn_type_id" not in table:
863
+ return ()
864
+ n = len(table["conn_type_id"])
865
+
866
+ def column(*names: str) -> "list[str] | None":
867
+ return next((table[c] for c in names if len(table.get(c, ())) == n), None)
868
+
869
+ ends = []
870
+ for k in "12":
871
+ ends.append((column(f"ptnr{k}_auth_asym_id", f"ptnr{k}_label_asym_id"),
872
+ column(f"ptnr{k}_auth_seq_id", f"ptnr{k}_label_seq_id"),
873
+ column(f"pdbx_ptnr{k}_pdb_ins_code"), column(f"ptnr{k}_label_atom_id"),
874
+ column(f"ptnr{k}_symmetry")))
875
+ if any(e[0] is None or e[1] is None or e[3] is None for e in ends):
876
+ return ()
877
+ out = []
878
+ for i, kind in enumerate(table["conn_type_id"]):
879
+ if not kind.lower().startswith("covale"):
880
+ continue
881
+ if len({e[4][i] for e in ends if e[4] is not None}) > 1:
882
+ continue # to another copy of the molecule
883
+ keys = []
884
+ for chain, number, icode, _, _ in ends:
885
+ assert chain is not None and number is not None
886
+ ic = icode[i] if icode is not None and icode[i] not in (".", "?") else ""
887
+ keys.append(ResidueKey(chain[i], _int(number[i]), ic))
888
+ out.append(Link(keys[0], ends[0][3][i], keys[1], ends[1][3][i])) # type: ignore[index]
889
+ return tuple(out)
890
+
891
+
892
+ def _accessions(ref: "dict[str, list[str]] | None", seq: "dict[str, list[str]] | None"
893
+ ) -> dict[str, tuple[str, ...]]:
894
+ """The accessions of the entries of sequence databases that the file assigns to each chain.
895
+
896
+ ``_struct_ref`` names an entry (``pdbx_db_accession``, and ``pdbx_db_isoform`` where it is an
897
+ isoform); each row of ``_struct_ref_seq`` aligns a stretch of one of them (``ref_id``) to a chain
898
+ (``pdbx_strand_id``, the author's name). The rows are joined by ``ref_id`` and not by their places in
899
+ the two lists: one entry may serve several chains (the copies of a homodimer: one row of the first,
900
+ two of the second), and one chain several entries (a fused protein).
901
+ """
902
+ def column(table: "dict[str, list[str]]", key: str) -> "list[str] | None":
903
+ values = table.get(key)
904
+ return values if values is not None and len(values) == max(len(v) for v in table.values()) else None
905
+
906
+ def written(value: str) -> bool:
907
+ return value not in ("?", ".", "")
908
+
909
+ if not ref or not seq:
910
+ return {}
911
+ entries: dict[str, list[str]] = {}
912
+ ids, accessions, isoforms = column(ref, "id"), column(ref, "pdbx_db_accession"), column(ref, "pdbx_db_isoform")
913
+ if ids is not None and accessions is not None:
914
+ for k, ident in enumerate(ids):
915
+ names = [accessions[k]] + ([isoforms[k]] if isoforms is not None else [])
916
+ entries[ident] = [n.upper() for n in names if written(n)]
917
+ refs, strands, own = column(seq, "ref_id"), column(seq, "pdbx_strand_id"), column(seq, "pdbx_db_accession")
918
+ out: dict[str, list[str]] = {}
919
+ for k, strand in enumerate(strands or []):
920
+ names = entries.get(refs[k], []) if refs is not None else []
921
+ if not names and own is not None and written(own[k]):
922
+ names = [own[k].upper()]
923
+ for chain in (c.strip() for c in strand.split(",")):
924
+ if written(chain) and names:
925
+ have = out.setdefault(chain, [])
926
+ have.extend(n for n in names if n not in have)
927
+ return {c: tuple(names) for c, names in out.items()}
928
+
929
+
930
+ def _pdb_links(lines: Iterable[str]) -> tuple[Link, ...]:
931
+ """The ``LINK`` records of a PDB file between atoms of one copy of the molecules, metals left out."""
932
+ out = []
933
+ for line in lines:
934
+ if line[:6] != "LINK " or len(line) < 57:
935
+ continue
936
+ if line[59:65].strip() != line[66:72].strip():
937
+ continue # to another copy of the molecule
938
+ try:
939
+ ends = [(ResidueKey(line[c].strip() or "A", int(line[c + 1:c + 5]), line[c + 5:c + 6].strip()),
940
+ line[n:n + 4]) for c, n in ((21, 12), (51, 42))]
941
+ except (ValueError, IndexError):
942
+ continue
943
+ if any(is_metal(_guess_element(name)) for _, name in ends):
944
+ continue
945
+ out.append(Link(ends[0][0], ends[0][1].strip(), ends[1][0], ends[1][1].strip()))
946
+ return tuple(out)
947
+
948
+
949
+ def _float_or_none(text: str) -> float | None:
950
+ try:
951
+ return float(text)
952
+ except ValueError:
953
+ return None
954
+
955
+
956
+ def _qa_metrics(table: dict[str, list[str]] | None) -> tuple[tuple[tuple[str, str, str], ...], float | None]:
957
+ """The ``_ma_qa_metric`` declarations, and the pLDDT scale if a *local* pLDDT is among them.
958
+
959
+ ModelCIF names the metric in ``type`` (``pLDDT``, ``pLDDT all-atom``, and
960
+ the same ``in [0,1]``); writers also repeat it in ``name``. A global-only
961
+ declaration is not enough: it says nothing about the per-atom column.
962
+ """
963
+ if not table:
964
+ return (), None
965
+ n = max((len(v) for v in table.values()), default=0)
966
+
967
+ def column(key: str) -> list[str]:
968
+ col = table.get(key)
969
+ return col if col is not None and len(col) == n else [""] * n
970
+
971
+ rows = tuple(zip(column("mode"), column("name"), column("type")))
972
+ scale: float | None = None
973
+ for mode, name, kind in rows:
974
+ if mode.strip().lower() != "local":
975
+ continue
976
+ described = f"{kind} {name}".lower()
977
+ if "plddt" in described:
978
+ scale = 100.0 if "[0,1]" in described.replace(" ", "") else 1.0
979
+ break
980
+ return rows, scale
981
+
982
+
983
+ # ---------------------------------------------------------------------------
984
+ # PDB
985
+ # ---------------------------------------------------------------------------
986
+
987
+ _TWO_LETTER = {"CL", "BR", "FE", "ZN", "MG", "MN", "CA", "NA", "CU", "CO", "NI", "SE", "HG", "CD", "LI", "SI"}
988
+
989
+
990
+ def _guess_element(atom_name: str) -> str:
991
+ """Element from an atom name when the element column is blank.
992
+
993
+ Given the raw four-character PDB field, alignment decides: a two-letter
994
+ element starts in the first column (``"CA "`` is calcium, ``"FE "`` iron)
995
+ while a one-letter element is preceded by a space or digit (``" CA "`` is an
996
+ alpha carbon). Without alignment only the first letter is trusted.
997
+
998
+ A hydrogen whose name fills the four columns begins in the first one too: ``HG11`` to ``HG23`` are the
999
+ hydrogens on the gamma carbons of valine, isoleucine and threonine, and no mercury. An ``H`` that two
1000
+ digits follow after its second letter is therefore a hydrogen.
1001
+ """
1002
+ if len(atom_name) == 4 and atom_name[:1].isalpha() and atom_name[:2].upper() in _TWO_LETTER \
1003
+ and not atom_name[2:].strip(" 0123456789'\"*") \
1004
+ and not (atom_name[:1].upper() == "H" and atom_name[2:].isdigit()):
1005
+ return atom_name[:2].capitalize()
1006
+ letters = re.sub(r"[^A-Za-z]", "", atom_name)
1007
+ return letters[0].upper() if letters else ""
1008
+
1009
+
1010
+ def parse_pdb(text: str, source: str = "", model: "int | None" = None) -> Structure:
1011
+ """Parse legacy PDB text into a :class:`Structure`.
1012
+
1013
+ Of the atoms that have one name in one residue, as the alternate locations of an atom have, the
1014
+ first in the file is read. Where one position (chain, number, insertion code) holds residues of two
1015
+ types, as alternate locations of each other, the residue is the one that comes first in the file, in
1016
+ its first alternate location: the atoms of the other type are not read.
1017
+
1018
+ ``model``: the model to read, by the number of its ``MODEL`` record. ``None`` is the first model
1019
+ of the file.
1020
+ """
1021
+ return _pdb_models(text, source, _model_asked(model, source or "PDB"))[0]
1022
+
1023
+
1024
+ def _pdb_models(text: str, source: str, model: "int | None | str") -> list[Structure]:
1025
+ """The models of PDB text: the first (``None``), the one numbered ``model``, or all (``"all"``)."""
1026
+ links = _pdb_links(text.splitlines())
1027
+
1028
+ def build(lines: Sequence[str], number: "int | None") -> Structure:
1029
+ atoms: list[Atom] = []
1030
+ seen: set[tuple[str, int, str, str]] = set()
1031
+ places: list[tuple[tuple[str, int, str], str, str]] = []
1032
+ placed: list[tuple[str, float, float, float]] = []
1033
+ for line in lines:
1034
+ try:
1035
+ name = line[12:16].strip()
1036
+ resname = line[17:20].strip()
1037
+ chain = line[21].strip() or "A"
1038
+ num = int(line[22:26])
1039
+ ic = line[26].strip()
1040
+ x, y, z = float(line[30:38]), float(line[38:46]), float(line[46:54])
1041
+ except (ValueError, IndexError) as exc:
1042
+ raise StructureError(f"{source or 'PDB'}: malformed atom record: {line[:30]!r}") from exc
1043
+ places.append(((chain, num, ic), resname, line[16].strip()))
1044
+ placed.append((name, x, y, z))
1045
+ left_out = _of_another_type(places)
1046
+ for k, line in enumerate(lines):
1047
+ if k in left_out:
1048
+ continue # of another residue type than the one its position is read as
1049
+ rec = line[:6]
1050
+ (chain, num, ic), resname, _ = places[k]
1051
+ name, x, y, z = placed[k]
1052
+ b_iso = _float_or_none(line[60:66]) if len(line) >= 66 else None
1053
+ ident = (chain, num, ic, name)
1054
+ if ident in seen:
1055
+ continue
1056
+ seen.add(ident)
1057
+ el = _norm_element(line[76:78]) if len(line) >= 78 and line[76:78].strip() else _guess_element(line[12:16])
1058
+ atoms.append(Atom(index=len(atoms), name=name, element=el, resname=resname, chain=chain,
1059
+ resnum=num, icode=ic, x=x, y=y, z=z, hetero=(rec == "HETATM"), b_iso=b_iso))
1060
+ if not atoms:
1061
+ raise StructureError(f"{source or 'PDB'}: no ATOM/HETATM records"
1062
+ + (f" in model {number}" if number is not None else ""))
1063
+ return Structure(atoms=atoms, source=source, links=links, model=number)
1064
+
1065
+ if model is None:
1066
+ # The first model: every atom record down to the first ENDMDL.
1067
+ first: list[str] = []
1068
+ for line in text.splitlines():
1069
+ if line[:6].startswith("ENDMDL"):
1070
+ break
1071
+ if line[:6] in ("ATOM ", "HETATM"):
1072
+ first.append(line)
1073
+ return [build(first, None)]
1074
+ # The atom records of every model, with the number its MODEL record writes (none without one).
1075
+ blocks: list[tuple[str | None, list[str]]] = []
1076
+ written: str | None = None
1077
+ current: list[str] = []
1078
+ opened = False
1079
+ for line in text.splitlines():
1080
+ rec = line[:6]
1081
+ if rec == "MODEL ":
1082
+ if current: # atoms before a MODEL record: a model of their own
1083
+ blocks.append((written, current))
1084
+ fields = line[6:].split()
1085
+ written, current, opened = (fields[0] if fields else None), [], True
1086
+ elif rec.startswith("ENDMDL"):
1087
+ blocks.append((written, current))
1088
+ written, current, opened = None, [], False
1089
+ elif rec in ("ATOM ", "HETATM"):
1090
+ current.append(line)
1091
+ if current or opened or not blocks:
1092
+ blocks.append((written, current))
1093
+ numbered = _model_numbers([w for w, _ in blocks]) if len(blocks) > 1 or blocks[0][0] is not None else [1]
1094
+ if model == "all":
1095
+ return [build(lines, number) for (_, lines), number in zip(blocks, numbered)]
1096
+ if model not in numbered:
1097
+ raise StructureError(_no_such_model(source or "PDB", model, numbered))
1098
+ return [build(blocks[numbered.index(model)][1], int(model))]
1099
+
1100
+
1101
+ def _read(path: "str | Path", model: "int | None | str") -> list[Structure]:
1102
+ p = Path(path)
1103
+ try:
1104
+ if p.suffix.lower() == ".gz":
1105
+ with gzip.open(p, "rt", encoding="utf-8") as handle:
1106
+ text = handle.read()
1107
+ else:
1108
+ text = p.read_text(encoding="utf-8")
1109
+ except UnicodeDecodeError as exc:
1110
+ raise StructureError(f"cannot read {p}: it is not UTF-8 text (it has the byte 0x{exc.object[exc.start]:02x}); "
1111
+ f"save it as UTF-8") from exc
1112
+ except (OSError, EOFError) as exc:
1113
+ raise StructureError(f"cannot read {p}: {exc}") from exc
1114
+ suffixes = [x.lower() for x in p.suffixes]
1115
+ suffix = suffixes[-2] if suffixes and suffixes[-1] == ".gz" and len(suffixes) > 1 else p.suffix.lower()
1116
+ if suffix in (".pdb", ".ent"):
1117
+ return _pdb_models(text, str(p), model)
1118
+ if suffix in (".cif", ".mmcif"):
1119
+ return _mmcif_models(text, str(p), model)
1120
+ # Unknown extension: sniff.
1121
+ if re.search(r"^data_", text, re.MULTILINE) and "_atom_site." in text:
1122
+ return _mmcif_models(text, str(p), model)
1123
+ return _pdb_models(text, str(p), model)
1124
+
1125
+
1126
+ def read_structure(path: "str | Path", model: "int | None" = None) -> Structure:
1127
+ """Read an mmCIF (``.cif``/``.mmcif``) or PDB (``.pdb``/``.ent``) file, gzipped (``.gz``) or not.
1128
+
1129
+ ``model``: which model of the file, by the number the file gives it
1130
+ (``_atom_site.pdbx_PDB_model_num``, the serial of ``MODEL``). ``None`` is the first model; a
1131
+ number the file does not have is refused. :func:`read_models` gives them all.
1132
+ """
1133
+ return _read(path, _model_asked(model, str(path)))[0]
1134
+
1135
+
1136
+ def read_models(path: "str | Path") -> list[Structure]:
1137
+ """Every model of a structure file as a structure of its own, in the order of the file.
1138
+
1139
+ The models of an NMR bundle, or frames that were written into one PDB file. Each structure
1140
+ knows its number in the file (:attr:`Structure.model`); a file that numbers no model is one
1141
+ model, numbered 1, and models that a PDB file does not tell apart by number are numbered by
1142
+ their order. This is the structure file :func:`read_structure` reads, all of it: no
1143
+ trajectory format is read.
1144
+ """
1145
+ return _read(path, "all")