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/confidence.py ADDED
@@ -0,0 +1,531 @@
1
+ """How much of a predicted model to believe.
2
+
3
+ Every 2D interaction diagram tool was written for crystal structures and draws
4
+ each contact as equally real. A predicted complex is not that kind of evidence:
5
+ AlphaFold-style models say, atom by atom, how confident they are (pLDDT), and a
6
+ contact between a poorly placed ligand atom and a poorly placed side chain is a
7
+ different claim from one between two well placed ones.
8
+
9
+ What this module does, and where it stops:
10
+
11
+ * It **reads** confidence; it never computes one. Per-atom pLDDT comes from the
12
+ B-factor column of the model file, and only when the file *declares* that the
13
+ column is a pLDDT (``_ma_qa_metric``), or when the caller asserts it or hands
14
+ values in. The value range is never used as a hint: in a crystal structure
15
+ the same column is a temperature factor, where high means worse.
16
+ * A residue's confidence is the mean over its atom records -- the same atoms
17
+ the interactions are keyed on, so no second residue numbering is involved.
18
+ * A **contact** is as believable as its weaker end: the lower of the ligand
19
+ atom's pLDDT and the residue's. Not their mean.
20
+ * Values are binned with AlphaFold's own thresholds (90 / 70 / 50). The bins
21
+ decide how strongly something is drawn; they do not change which interactions
22
+ exist, how they are typed, or how long their lines are. Confidence qualifies
23
+ the evidence; it is not folded into the chemistry.
24
+ * Model-level numbers (ipTM, pTM, ranking score) and the verdict "do not trust
25
+ this model" belong to the caller. They are displayed, not derived.
26
+ * pLDDT is written on **two scales**: 0 to 100 (AlphaFold; the B-factor column
27
+ of a model file, Boltz's included) and 0 to 1 (Boltz's ``plddt_*.npz``, among
28
+ others). Everything here is on 0-100. The scale of what is handed in is never
29
+ guessed and never converted on the quiet, because the wrong guess is silent
30
+ both ways: 0-1 values read as 0-100 put every residue below 50, and a
31
+ hundredfold applied to values already on 0-100 puts every residue above 90.
32
+ Values that cannot be on the scale they are said to be on are refused
33
+ (:func:`plddt_factor`), and a caller can state the scale.
34
+ """
35
+
36
+ from __future__ import annotations
37
+
38
+ import json
39
+ from dataclasses import dataclass, field, replace
40
+ from pathlib import Path
41
+ from typing import Any, Iterable, Mapping, Sequence
42
+
43
+ import numpy as np
44
+
45
+ from .errors import BindviewError, StructureError
46
+ from .structure import ResidueKey, Structure
47
+
48
+ __all__ = ["Confidence", "ModelConfidence", "Look", "band_of", "look_of", "BANDS", "BAND_LABELS", "LOOKS",
49
+ "PLAIN", "POCKET_CUTOFF", "occupancy_factors", "OCCUPANCY_SAMPLES", "OCCUPANCY_STEPS",
50
+ "SHARE_WRITTEN_BELOW", "SCALES", "plddt_factor"]
51
+
52
+ #: Bands, best first, with their lower pLDDT bounds (AlphaFold's convention).
53
+ BANDS: tuple[tuple[str, float], ...] = (("very_high", 90.0), ("confident", 70.0), ("low", 50.0),
54
+ ("very_low", float("-inf")))
55
+ BAND_LABELS = {"very_high": "pLDDT ≥ 90", "confident": "pLDDT 70–90", "low": "pLDDT 50–70",
56
+ "very_low": "pLDDT < 50"}
57
+ #: Residues with a heavy atom this close (angstrom) to the ligand form the pocket.
58
+ POCKET_CUTOFF = 4.5
59
+
60
+
61
+ #: The scales a pLDDT can be stated to be on. bindview draws on the first.
62
+ SCALES = ("0-100", "0-1")
63
+ #: The atoms of a residue have values of their own when two of them differ by more than this (on 0-100).
64
+ #: A model that writes one value per residue writes it on every atom, to the last digit.
65
+ ATOM_SPREAD = 0.01
66
+
67
+
68
+ def gives_atoms(groups: "Iterable[Iterable[float]]") -> bool:
69
+ """Does a model give the atoms of a residue values of their own? ``groups`` are the values of the
70
+ atoms of each residue. Yes if in at least one residue two of them differ by more than
71
+ :data:`ATOM_SPREAD`; a residue of one atom says nothing either way."""
72
+ for group in groups:
73
+ values = list(group)
74
+ if len(values) > 1 and max(values) - min(values) > ATOM_SPREAD:
75
+ return True
76
+ return False
77
+
78
+
79
+ def plddt_factor(values: Iterable[float], what: str = "the pLDDT values handed in are", scale: "str | None" = None,
80
+ how: str = "scale='0-1' reads them as {lo} to {hi}; scale='0-100' takes them as they stand") -> float:
81
+ """What brings a set of pLDDT values to the 0-100 scale: 1 or 100. Or a refusal.
82
+
83
+ * ``scale=None``, not stated: the values are on 0-100, as documented. If none of them exceeds 1
84
+ (and they are not all zero) they cannot be -- on 0-100 a model has no residue below 1 -- and
85
+ are refused, with both scales named and how to state one.
86
+ * ``scale="0-100"``: stated, taken as they stand.
87
+ * ``scale="0-1"``: stated; the factor is 100. A value above 1 contradicts it and is refused.
88
+
89
+ On either scale a value below 0, or above the top of the scale, is refused. Nothing is
90
+ converted that the caller did not state.
91
+
92
+ ``what`` begins the error and ends with its verb (``"the B-factor column of model.cif holds"``);
93
+ ``how`` says how the scale is stated where the values came in (``{lo}`` and ``{hi}``: the values
94
+ times 100).
95
+ """
96
+ if scale is not None and scale not in SCALES:
97
+ raise ValueError(f"the scale of a pLDDT is {' or '.join(repr(s) for s in SCALES)}, not {scale!r}")
98
+ vals = [float(v) for v in values if v is not None and v == v] # (v == v: not NaN)
99
+ if not vals:
100
+ return 100.0 if scale == "0-1" else 1.0
101
+ lo, hi = min(vals), max(vals)
102
+ span = f"{lo:.3g}" if lo == hi else f"{lo:.3g} to {hi:.3g}"
103
+ if lo < 0.0:
104
+ raise BindviewError(f"{what} {span}: a pLDDT is not negative")
105
+ if scale == "0-1":
106
+ if hi > 1.0:
107
+ raise BindviewError(f"{what} {span}, and the scale stated is 0-1, on which nothing exceeds 1. Nothing is "
108
+ f"divided for you: if the values are on 0-100, state that, or state no scale")
109
+ return 100.0
110
+ if hi > 100.0:
111
+ raise BindviewError(f"{what} {span}: on the 0-100 scale of pLDDT nothing exceeds 100")
112
+ if scale is None and 0.0 < hi <= 1.0:
113
+ raise BindviewError(
114
+ f"{what} {span}: nothing above 1. bindview reads pLDDT on the 0-100 scale, where a model has no residue "
115
+ f"below 1, so these look like the 0-1 scale that Boltz writes into plddt_*.npz. The scale is not "
116
+ f"guessed and nothing is multiplied for you. State it: "
117
+ + how.format(lo=f"{100 * lo:.0f}", hi=f"{100 * hi:.0f}"))
118
+ return 1.0
119
+
120
+
121
+ def band_of(value: float) -> str:
122
+ """The pLDDT band of ``value`` (0-100 scale)."""
123
+ for name, lower in BANDS:
124
+ if value >= lower:
125
+ return name
126
+ return "very_low" # NaN
127
+
128
+
129
+ @dataclass(frozen=True)
130
+ class Look:
131
+ """How strongly to draw something.
132
+
133
+ Three channels, so that the message survives greyscale printing and colour
134
+ vision deficiency: stroke ``width`` (a factor on the normal width),
135
+ ``opacity``, and -- for the lowest band only -- a visible ``mark``.
136
+ ``level`` orders the looks: 0 is unqualified.
137
+ """
138
+
139
+ band: str | None
140
+ width: float = 1.0
141
+ opacity: float = 1.0
142
+ mark: bool = False
143
+ level: int = 0
144
+
145
+
146
+ #: Drawn as if nothing were known: used when there is no confidence information.
147
+ PLAIN = Look(None)
148
+ #: At or above 70 a contact is drawn at full strength: a confident prediction
149
+ #: should look like the unqualified figure, so that most figures end up barely
150
+ #: touched and the qualified ones stand out.
151
+ LOOKS: dict[str, Look] = {
152
+ "very_high": Look("very_high"),
153
+ "confident": Look("confident"),
154
+ "low": Look("low", width=0.7, opacity=0.62, level=1),
155
+ "very_low": Look("very_low", width=0.5, opacity=0.42, mark=True, level=2),
156
+ }
157
+ #: The mark that goes with the lowest band.
158
+ MARK = "?"
159
+
160
+
161
+ def look_of(value: float | None, by_colour: bool = False) -> Look:
162
+ """The look for a pLDDT value; :data:`PLAIN` when there is none.
163
+
164
+ ``by_colour``: the figure shows the bands by colour and not by weight. The
165
+ look is then the full-strength one and says only which band it is: nothing
166
+ is drawn thinner, paler or with a mark for its pLDDT.
167
+ """
168
+ if value is None:
169
+ return PLAIN
170
+ band = band_of(value)
171
+ return Look(band) if by_colour else LOOKS[band]
172
+
173
+
174
+ #: Occupancies shown as samples in the legend.
175
+ OCCUPANCY_SAMPLES = (1.0, 0.5, 0.1)
176
+
177
+
178
+ #: Occupancy in three steps (``RenderOptions.occupancy_style="steps"``, the default): from a share of
179
+ #: the first number on, a contact is drawn at the stroke-width and opacity factors after it. The top
180
+ #: step is a full line, so that a contact made in every model is drawn exactly like one that carries
181
+ #: no occupancy at all; the share written on the line tells 95 % from 100 %.
182
+ OCCUPANCY_STEPS = ((0.9, 1.0, 1.0), (0.5, 0.7, 0.8), (0.0, 0.38, 0.5))
183
+ #: A contact with a share below this is written on its line (rounded, it would not read 100 %).
184
+ SHARE_WRITTEN_BELOW = 0.995
185
+
186
+
187
+ def occupancy_factors(occupancy: float | None, steps: bool = False) -> tuple[float, float]:
188
+ """Stroke-width and opacity factors for a contact made in ``occupancy`` of an ensemble.
189
+
190
+ Occupancy uses the same visual channel as confidence -- weight and opacity
191
+ -- because it answers the same kind of question: how much of the evidence
192
+ stands behind this line. The mapping is continuous, or with ``steps`` in the
193
+ three steps of :data:`OCCUPANCY_STEPS`, and a contact that is always made (or
194
+ whose occupancy is unknown) is drawn exactly like one that carries no
195
+ occupancy at all, so a single structure is the limiting case of an ensemble.
196
+ The two factors scale the stroke; they are never combined with pLDDT into a
197
+ number.
198
+ """
199
+ if occupancy is None or occupancy >= 1.0:
200
+ return (1.0, 1.0)
201
+ o = max(0.0, occupancy)
202
+ if steps:
203
+ return next((width, opacity) for least, width, opacity in OCCUPANCY_STEPS if o >= least)
204
+ return (0.4 + 0.6 * o, 0.35 + 0.65 * o)
205
+
206
+
207
+ @dataclass(frozen=True)
208
+ class ModelConfidence:
209
+ """Model-level evidence, supplied by the caller and displayed as given.
210
+
211
+ ``trusted=False`` is the caller's verdict that the model should not be read
212
+ as a result; the figure is then *marked* (a banner and a frame), not merely
213
+ drawn faint. ``flag`` is that verdict in the caller's words, e.g.
214
+ ``"grade C"``. bindview applies no threshold of its own to decide this.
215
+ """
216
+
217
+ iptm: float | None = None
218
+ ptm: float | None = None
219
+ ranking_score: float | None = None
220
+ trusted: bool = True
221
+ flag: str | None = None
222
+
223
+ @classmethod
224
+ def from_mapping(cls, data: Mapping[str, Any], **overrides: Any) -> "ModelConfidence":
225
+ """From a mapping, such as AlphaFold 3's summary: ``iptm``, ``ptm`` and ``ranking_score`` as
226
+ numbers, or as text that is one (a table gives ``"0.83"``); ``trusted`` as true or false, or as
227
+ one of those words; ``flag``. A key that is not there, or holds nothing, is left out. A value
228
+ that is neither is refused by its key, not read as something else."""
229
+ def number(key: str) -> float | None:
230
+ value = data.get(key)
231
+ if value is None:
232
+ return None
233
+ try:
234
+ if isinstance(value, bool) or not isinstance(value, (int, float, str)):
235
+ raise ValueError
236
+ read = float(value)
237
+ if read != read: # nan: no number
238
+ raise ValueError
239
+ except ValueError:
240
+ raise BindviewError(f"model confidence: {key!r} is {value!r}, which is no number") from None
241
+ return read
242
+
243
+ def verdict(key: str) -> bool:
244
+ value = data.get(key)
245
+ if value is None:
246
+ return True
247
+ if isinstance(value, bool) or (isinstance(value, int) and value in (0, 1)):
248
+ return bool(value)
249
+ said = value.strip().lower() if isinstance(value, str) else None
250
+ if said in ("true", "yes"):
251
+ return True
252
+ if said in ("false", "no"):
253
+ return False
254
+ raise BindviewError(f"model confidence: {key!r} is {value!r}; it is true or false")
255
+
256
+ base = cls(iptm=number("iptm"), ptm=number("ptm"), ranking_score=number("ranking_score"),
257
+ trusted=verdict("trusted"), flag=data.get("flag") or None)
258
+ return replace(base, **overrides) if overrides else base
259
+
260
+ @classmethod
261
+ def from_json(cls, path: "str | Path", **overrides: Any) -> "ModelConfidence":
262
+ """Read an AlphaFold 3 ``summary_confidences.json`` (or any JSON with those keys)."""
263
+ try:
264
+ data = json.loads(Path(path).read_text())
265
+ except (OSError, ValueError) as exc:
266
+ raise StructureError(f"cannot read model confidence from {path}: {exc}") from exc
267
+ if not isinstance(data, Mapping):
268
+ raise StructureError(f"{path}: expected a JSON object with 'iptm' / 'ptm' / 'ranking_score'")
269
+ return cls.from_mapping(data, **overrides)
270
+
271
+ @staticmethod
272
+ def beside(structure_path: "str | Path") -> Path | None:
273
+ """The summary file AlphaFold 3 writes next to a model, if it is there.
274
+
275
+ The pairing is by name only -- ``model.cif`` with
276
+ ``summary_confidences.json``, ``<job>_model.cif`` with
277
+ ``<job>_summary_confidences.json`` -- never "whatever JSON is in the
278
+ directory", so a neighbouring model's numbers cannot be picked up.
279
+ """
280
+ p = Path(structure_path)
281
+ stem = p.stem
282
+ if stem == "model":
283
+ cand = p.with_name("summary_confidences.json")
284
+ elif stem.endswith("_model"):
285
+ cand = p.with_name(stem[: -len("model")] + "summary_confidences.json")
286
+ else:
287
+ return None
288
+ return cand if cand.is_file() else None
289
+
290
+ @classmethod
291
+ def coerce(cls, value: Any) -> "ModelConfidence | None":
292
+ """From whatever ``model_confidence`` was given."""
293
+ if value is None or isinstance(value, cls):
294
+ return value
295
+ if isinstance(value, Mapping):
296
+ return cls.from_mapping(value)
297
+ if isinstance(value, (str, Path)):
298
+ return cls.from_json(value)
299
+ raise TypeError("model confidence must be a ModelConfidence, a mapping or a path to a JSON file")
300
+
301
+
302
+ def _mean(values: Iterable[float]) -> float | None:
303
+ vals = [float(v) for v in values]
304
+ return sum(vals) / len(vals) if vals else None
305
+
306
+
307
+ @dataclass
308
+ class Confidence:
309
+ """Per-residue and per-ligand-atom pLDDT of one model, on the 0-100 scale.
310
+
311
+ ``origin`` records why the numbers may be read as confidence:
312
+ ``"declared"`` (the file's ``_ma_qa_metric`` says so), ``"asserted"`` (the
313
+ caller said the B-factor column is pLDDT) or ``"supplied"`` (the caller
314
+ passed the values).
315
+ """
316
+
317
+ residues: dict[tuple[str, int, str], float]
318
+ ligand_atoms: dict[str, float]
319
+ pocket_plddt: float | None = None
320
+ pocket_residues: int = 0
321
+ origin: str = "supplied"
322
+ model: ModelConfidence | None = None
323
+ #: The scale the values were *given* on, where the caller stated one that is not 0-100: they are
324
+ #: held on 0-100 like all others, and the result says that they were brought there.
325
+ given_on: str | None = None
326
+ #: pLDDT of the single atoms of every residue (not of the ligand), where the model was read from a
327
+ #: structure: ``(chain, number, icode) -> atom name -> value``. Empty where values were handed in.
328
+ atoms: dict[tuple[str, int, str], dict[str, float]] = field(default_factory=dict)
329
+ #: Does the model give the atoms of a residue values of their own (:func:`gives_atoms`)? What a
330
+ #: residue's atoms are drawn at where they are drawn, and what the figure then says they are drawn at.
331
+ per_atom: bool = False
332
+ _by_number: dict[tuple[int, str], list[tuple[str, int, str]]] = field(default_factory=dict, repr=False)
333
+
334
+ def __post_init__(self) -> None:
335
+ table: dict[tuple[int, str], list[tuple[str, int, str]]] = {}
336
+ for key in self.residues:
337
+ table.setdefault((key[1], key[2]), []).append(key)
338
+ self._by_number = table
339
+
340
+ # -- construction ------------------------------------------------------
341
+ @classmethod
342
+ def from_structure(cls, structure: Structure, ligand: ResidueKey, *, scale: float = 1.0,
343
+ origin: str = "declared", cutoff: float = POCKET_CUTOFF,
344
+ model: ModelConfidence | None = None) -> "Confidence | None":
345
+ """Read pLDDT from the B-factor column of ``structure``.
346
+
347
+ This does **not** check that the column is a pLDDT -- the caller of
348
+ this method has established that (see :meth:`Diagram.from_structure`).
349
+ Returns ``None`` when the column is absent. ``scale`` is what brings
350
+ the column to 0-100: 1, or 100 for a column on 0-1. A column that
351
+ cannot be on the scale it is said to be on is refused
352
+ (:func:`plddt_factor`): one read as 0-100 in which nothing exceeds 1,
353
+ one read as 0-1 in which something does.
354
+ """
355
+ said = {"declared": "declared a pLDDT", "asserted": "asserted to be pLDDT"}.get(origin, "read as pLDDT")
356
+ on_unit = scale == 100.0
357
+ plddt_factor((a.b_iso for a in structure.atoms if a.b_iso is not None),
358
+ f"the B-factor column of {structure.source or 'the structure'}, {said} on the "
359
+ f"{'0-1' if on_unit else '0-100'} scale, holds",
360
+ "0-1" if on_unit else None if scale == 1.0 else "0-100",
361
+ how="plddt='bfactor01' (--plddt bfactor01 on the command line) is the assertion that the "
362
+ "column is pLDDT on 0-1, and reads it as {lo} to {hi}")
363
+ residues: dict[tuple[str, int, str], float] = {}
364
+ single: dict[tuple[str, int, str], dict[str, float]] = {}
365
+ for key in structure.residues():
366
+ if key == ligand:
367
+ continue
368
+ vals = [a.b_iso * scale for a in structure.residue_atoms(key) if a.b_iso is not None]
369
+ if vals:
370
+ residues[(key.chain, key.number, key.icode)] = sum(vals) / len(vals)
371
+ single[(key.chain, key.number, key.icode)] = {
372
+ a.name: a.b_iso * scale for a in structure.residue_atoms(key)
373
+ if a.b_iso is not None and a.element not in ("H", "D")}
374
+ lig_atoms = {a.name: a.b_iso * scale for a in structure.residue_atoms(ligand) if a.b_iso is not None}
375
+ if not residues and not lig_atoms:
376
+ return None
377
+ pocket = pocket_atoms(structure, ligand, cutoff)
378
+ vals = [a.b_iso * scale for atoms in pocket.values() for a in atoms if a.b_iso is not None]
379
+ return cls(residues, lig_atoms, pocket_plddt=_mean(vals), pocket_residues=len(pocket), origin=origin,
380
+ model=model, atoms=single,
381
+ per_atom=gives_atoms([list(v.values()) for v in single.values()] + _chain_groups(lig_atoms)))
382
+
383
+ @classmethod
384
+ def from_values(cls, residues: Mapping[Any, float], ligand_atoms: Mapping[str, float] | None = None, *,
385
+ pocket_plddt: float | None = None, model: ModelConfidence | None = None,
386
+ scale: str | None = None) -> "Confidence":
387
+ """Confidence from values the caller already has.
388
+
389
+ ``residues`` is keyed by :class:`ResidueKey`, ``(chain, number)``,
390
+ ``(chain, number, icode)`` or ``"A:570"``; ``ligand_atoms`` by atom name.
391
+
392
+ The values are on the 0-100 scale unless ``scale="0-1"`` says
393
+ otherwise (Boltz's ``plddt_*.npz`` is on 0-1); they are then brought to
394
+ 0-100, and the result says so (``given_on``). Values that cannot be on
395
+ the scale they are said to be on are refused, and so are values without
396
+ a stated scale none of which exceeds 1 (:func:`plddt_factor`):
397
+ ``scale="0-100"`` states that they are meant as they stand.
398
+ """
399
+ every = [float(v) for v in residues.values()] + [float(v) for v in (ligand_atoms or {}).values()]
400
+ if pocket_plddt is not None:
401
+ every.append(float(pocket_plddt))
402
+ factor = plddt_factor(every, "the pLDDT values handed in are", scale)
403
+ table: dict[tuple[str, int, str], float] = {}
404
+ for key, value in residues.items():
405
+ table[_residue_key(key)] = float(value) * factor
406
+ given = {str(k): float(v) * factor for k, v in (ligand_atoms or {}).items()}
407
+ return cls(table, given,
408
+ pocket_plddt=None if pocket_plddt is None else float(pocket_plddt) * factor,
409
+ pocket_residues=0, origin="supplied", model=model,
410
+ given_on=scale if factor != 1.0 else None, per_atom=gives_atoms(_chain_groups(given)))
411
+
412
+ # -- lookups -----------------------------------------------------------
413
+ def residue(self, key: "ResidueKey | tuple[str, int, str] | None") -> float | None:
414
+ """pLDDT of a residue: the mean over its atom records."""
415
+ if key is None:
416
+ return None
417
+ k = (key.chain, key.number, key.icode) if isinstance(key, ResidueKey) else (key[0], key[1], key[2])
418
+ hit = self.residues.get(k)
419
+ if hit is None and not k[0]:
420
+ # A record without a chain id: unambiguous only if one chain has that number.
421
+ cands = self._by_number.get((k[1], k[2]), [])
422
+ if len(cands) == 1:
423
+ hit = self.residues[cands[0]]
424
+ return hit
425
+
426
+ def atom(self, key: "ResidueKey | tuple[str, int, str] | None", name: str) -> float | None:
427
+ """pLDDT of one atom of a residue: its own where the model gives the atoms of a residue values
428
+ of their own and this one has one, the residue's otherwise."""
429
+ if key is None:
430
+ return None
431
+ k = (key.chain, key.number, key.icode) if isinstance(key, ResidueKey) else (key[0], key[1], key[2])
432
+ if self.per_atom and name in self.atoms.get(k, {}):
433
+ return self.atoms[k][name]
434
+ return self.residue(key)
435
+
436
+ def ligand(self, names: Sequence[str]) -> float | None:
437
+ """pLDDT of a ligand site: the atom's own value, or the mean over the
438
+ atoms of a ring or charged group (whose centre is what the contact attaches to)."""
439
+ return _mean(self.ligand_atoms[n] for n in names if n in self.ligand_atoms)
440
+
441
+ def contact(self, residue: "ResidueKey | tuple[str, int, str] | None", names: Sequence[str]) -> float | None:
442
+ """Confidence of a contact: the **lower** of its two ends.
443
+
444
+ If only one end is known (values supplied for residues only), that end
445
+ is all that can be said and is returned.
446
+ """
447
+ ends = [v for v in (self.residue(residue), self.ligand(names)) if v is not None]
448
+ return min(ends) if ends else None
449
+
450
+ @property
451
+ def ligand_plddt(self) -> float | None:
452
+ """Mean pLDDT over the ligand's atoms."""
453
+ return _mean(self.ligand_atoms.values())
454
+
455
+ @property
456
+ def marked(self) -> bool:
457
+ """Has the caller flagged this model as not to be trusted?"""
458
+ return self.model is not None and not self.model.trusted
459
+
460
+ def with_model(self, model: ModelConfidence | None) -> "Confidence":
461
+ """The same with the numbers of the model as a whole."""
462
+ return replace(self, model=model)
463
+
464
+ def summary(self) -> dict[str, Any]:
465
+ """The figure-level numbers, as plain data."""
466
+ m = self.model
467
+ out = {
468
+ "origin": self.origin,
469
+ "iptm": m.iptm if m else None, "ptm": m.ptm if m else None,
470
+ "ranking_score": m.ranking_score if m else None,
471
+ "pocket_plddt": None if self.pocket_plddt is None else round(self.pocket_plddt, 2),
472
+ "pocket_residues": self.pocket_residues,
473
+ "ligand_plddt": None if self.ligand_plddt is None else round(self.ligand_plddt, 2),
474
+ "trusted": m.trusted if m else True, "flag": m.flag if m else None,
475
+ }
476
+ if self.given_on is not None:
477
+ # Said only where it happened: the summary of a model given on 0-100 has no such key.
478
+ out["given_on"] = f"the {self.given_on} scale, as stated; held and drawn on 0-100"
479
+ return out
480
+
481
+
482
+ def _chain_groups(ligand_atoms: Mapping[str, float]) -> list[list[float]]:
483
+ """The values of a chain taken as the ligand, residue by residue: its atoms are named
484
+ ``<residue>/<atom>`` (:meth:`bindview.structure.Structure.with_chain_as_ligand`). A ligand that is
485
+ one molecule is no residue, and says nothing of what a model gives the atoms of one."""
486
+ groups: dict[str, list[float]] = {}
487
+ for name, value in ligand_atoms.items():
488
+ if "/" in name:
489
+ groups.setdefault(name.split("/", 1)[0], []).append(value)
490
+ return list(groups.values())
491
+
492
+
493
+ def _residue_key(key: Any) -> tuple[str, int, str]:
494
+ if isinstance(key, ResidueKey):
495
+ return (key.chain, key.number, key.icode)
496
+ if isinstance(key, str):
497
+ chain, _, rest = key.rpartition(":")
498
+ digits = rest.rstrip("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz")
499
+ try:
500
+ return (chain, int(digits), rest[len(digits):])
501
+ except ValueError:
502
+ raise ValueError(f"cannot read residue key {key!r}; use 'A:570' or ('A', 570)") from None
503
+ if isinstance(key, int):
504
+ return ("", key, "")
505
+ parts = tuple(key)
506
+ if len(parts) == 2:
507
+ return (str(parts[0]), int(parts[1]), "")
508
+ if len(parts) == 3:
509
+ return (str(parts[0]), int(parts[1]), str(parts[2]))
510
+ raise ValueError(f"cannot read residue key {key!r}")
511
+
512
+
513
+ def pocket_atoms(structure: Structure, ligand: ResidueKey, cutoff: float = POCKET_CUTOFF
514
+ ) -> dict[ResidueKey, list]:
515
+ """Residues with a heavy atom within ``cutoff`` of a ligand heavy atom, with all their atoms."""
516
+ lig_xyz = np.array([a.xyz for a in structure.residue_atoms(ligand) if a.element not in ("H", "D")],
517
+ dtype=float).reshape(-1, 3)
518
+ if not len(lig_xyz):
519
+ return {}
520
+ coords = structure.coords
521
+ lo, hi = lig_xyz.min(axis=0) - cutoff, lig_xyz.max(axis=0) + cutoff
522
+ near = np.nonzero(((coords >= lo) & (coords <= hi)).all(axis=1))[0]
523
+ hits: dict[ResidueKey, list] = {}
524
+ for i in near:
525
+ atom = structure.atoms[int(i)]
526
+ key = atom.residue
527
+ if key == ligand or atom.element in ("H", "D") or key in hits:
528
+ continue
529
+ if float(np.linalg.norm(lig_xyz - coords[i], axis=1).min()) <= cutoff:
530
+ hits[key] = structure.residue_atoms(key)
531
+ return dict(sorted(hits.items()))