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.
- bindview/__init__.py +88 -0
- bindview/__main__.py +6 -0
- bindview/align.py +493 -0
- bindview/arrange.js +347 -0
- bindview/arrange.py +248 -0
- bindview/backends.py +290 -0
- bindview/basepairs.py +1711 -0
- bindview/chains.py +264 -0
- bindview/chem.py +57 -0
- bindview/clearance.py +123 -0
- bindview/cli.py +990 -0
- bindview/compare.py +1854 -0
- bindview/confidence.py +531 -0
- bindview/consensus.py +303 -0
- bindview/covalent.py +220 -0
- bindview/depict.py +790 -0
- bindview/detect.py +378 -0
- bindview/diagram.py +1891 -0
- bindview/distance_table.py +589 -0
- bindview/ensemble.py +787 -0
- bindview/errors.py +47 -0
- bindview/exposure.py +207 -0
- bindview/features.py +179 -0
- bindview/fingerprint.py +469 -0
- bindview/fragments.py +304 -0
- bindview/geometry.py +482 -0
- bindview/graph.py +611 -0
- bindview/graphbuild.py +431 -0
- bindview/interactions.py +418 -0
- bindview/interactive.py +334 -0
- bindview/interface.py +1329 -0
- bindview/ions.py +155 -0
- bindview/layout/__init__.py +15 -0
- bindview/layout/body.py +421 -0
- bindview/layout/engine.py +1084 -0
- bindview/layout/field.py +261 -0
- bindview/ligand.py +583 -0
- bindview/near.py +67 -0
- bindview/options.py +92 -0
- bindview/pae.py +991 -0
- bindview/peptide.py +610 -0
- bindview/plane.py +320 -0
- bindview/polymer.py +678 -0
- bindview/py.typed +0 -0
- bindview/report.py +1407 -0
- bindview/residues.py +296 -0
- bindview/resolve.py +493 -0
- bindview/scene.py +239 -0
- bindview/solvent.py +254 -0
- bindview/structure.py +1145 -0
- bindview/styles/__init__.py +2 -0
- bindview/styles/absence.py +180 -0
- bindview/styles/base.py +2128 -0
- bindview/styles/closeup.py +146 -0
- bindview/styles/detailed.py +690 -0
- bindview/styles/ligand_draw.py +289 -0
- bindview/styles/mixed.py +70 -0
- bindview/styles/polymer_draw.py +354 -0
- bindview/styles/rings.py +75 -0
- bindview/styles/schematic.py +311 -0
- bindview/styles/summary.py +147 -0
- bindview/svg.py +310 -0
- bindview/textmetrics.py +64 -0
- bindview/theme.py +317 -0
- bindview-0.1.0.dist-info/METADATA +270 -0
- bindview-0.1.0.dist-info/RECORD +70 -0
- bindview-0.1.0.dist-info/WHEEL +4 -0
- bindview-0.1.0.dist-info/entry_points.txt +2 -0
- bindview-0.1.0.dist-info/licenses/LICENSE +21 -0
- bindview-0.1.0.dist-info/licenses/NOTICE +48 -0
bindview/pae.py
ADDED
|
@@ -0,0 +1,991 @@
|
|
|
1
|
+
"""Predicted aligned error: what a model says about the placement of one residue against another.
|
|
2
|
+
|
|
3
|
+
pLDDT is a claim about a residue's own surroundings. The predicted aligned
|
|
4
|
+
error (PAE) is a claim about a *pair*: the expected error, in ångström, in the
|
|
5
|
+
position of residue ``j`` when the model is aligned on residue ``i``. For a
|
|
6
|
+
contact across an interface it is the number that says whether the two sides
|
|
7
|
+
are placed against each other at all; a model can have confident residues on
|
|
8
|
+
both sides and no idea how they sit together. Low is confident. AlphaFold 3
|
|
9
|
+
caps the scale near 31.75 Å, which means "no idea".
|
|
10
|
+
|
|
11
|
+
This module reads the matrix (AlphaFold 3's ``confidences.json``, the PAE file
|
|
12
|
+
of the AlphaFold database, each plain or gzipped, or the ``pae_*.npz`` Boltz
|
|
13
|
+
writes) and answers for two residues. The
|
|
14
|
+
value of a pair is **the smaller of the two directions** of the matrix.
|
|
15
|
+
Nothing here draws; a contact carries the value
|
|
16
|
+
(:attr:`bindview.interactions.Interaction.pae`) and the styles write it on the
|
|
17
|
+
contact's line as a tag that says what it is, ``PAE 11`` -- never by stroke
|
|
18
|
+
weight, opacity or dash, which belong to pLDDT. Or, where it is asked for
|
|
19
|
+
(``render(pae_colors=True)``) and in the diagram of a ligand, as a glow behind
|
|
20
|
+
the line in the colour of its band (:data:`PAE_BANDS`).
|
|
21
|
+
|
|
22
|
+
A model that is run several times gives several matrices
|
|
23
|
+
(:class:`PaeDraws`). They become one number per pair by their **median**: the
|
|
24
|
+
largest of n draws rises with n and the smallest falls with it, so either
|
|
25
|
+
would make a figure of five draws say something else than a figure of one for
|
|
26
|
+
no reason in the model. The value of each draw is kept beside it.
|
|
27
|
+
|
|
28
|
+
Draws of a model with several copies of one chain need one more step. The
|
|
29
|
+
copies are interchangeable to the model, and it is free to name them in another
|
|
30
|
+
order in every draw: "chain A, residue 94 and chain B, residue 151" is a
|
|
31
|
+
contact in one draw and two residues on opposite sides of the assembly in the
|
|
32
|
+
next. Before a pair is looked up in a draw, the chains of that draw are
|
|
33
|
+
therefore matched to those of the structure that is drawn, by superposition
|
|
34
|
+
(:func:`match_chains`), which needs the model file of every draw. Without them
|
|
35
|
+
such draws are refused, not read by name.
|
|
36
|
+
|
|
37
|
+
Two neighbours of PAE are **not** read here, and are refused where a PAE is
|
|
38
|
+
expected rather than taken for one. The predicted distance error (PDE, Boltz's
|
|
39
|
+
``pde_*.npz``) is the expected error of the *distance* between two residues:
|
|
40
|
+
it has no frame of reference, and is not a second opinion on PAE. pLDDT
|
|
41
|
+
(``plddt_*.npz``) is about one residue.
|
|
42
|
+
|
|
43
|
+
One number is worked out from the matrix here and is not a model's own: **ipSAE**
|
|
44
|
+
(:func:`ipsae`), a score of how well two sides of a complex are placed against
|
|
45
|
+
each other. It is computed only where a caller asks for it.
|
|
46
|
+
"""
|
|
47
|
+
|
|
48
|
+
from __future__ import annotations
|
|
49
|
+
|
|
50
|
+
import gzip
|
|
51
|
+
import json
|
|
52
|
+
import zipfile
|
|
53
|
+
from dataclasses import dataclass, field, replace
|
|
54
|
+
from itertools import permutations, product
|
|
55
|
+
from pathlib import Path
|
|
56
|
+
from typing import TYPE_CHECKING, Any, Iterable, Sequence
|
|
57
|
+
|
|
58
|
+
import numpy as np
|
|
59
|
+
|
|
60
|
+
from .errors import BindviewError
|
|
61
|
+
from .structure import ResidueKey
|
|
62
|
+
|
|
63
|
+
if TYPE_CHECKING: # pragma: no cover
|
|
64
|
+
from .structure import Structure
|
|
65
|
+
|
|
66
|
+
__all__ = ["Pae", "PaeDraws", "PAE_SHOWN", "PAE_STRONG", "PAE_BANDS", "pae_band", "pae_tag", "pae_shown", "tokens_of",
|
|
67
|
+
"read_pae",
|
|
68
|
+
"match_chains", "model_beside", "SAME_FIT", "Ipsae", "OneWay", "IPSAE_CUTOFF", "ipsae", "ipsae_d0",
|
|
69
|
+
"ipsae_of"]
|
|
70
|
+
|
|
71
|
+
#: A contact whose PAE, rounded to a whole ångström, is below this carries no tag: below it the
|
|
72
|
+
#: relative placement of two residues is customarily read as confident.
|
|
73
|
+
PAE_SHOWN = 5
|
|
74
|
+
#: ... and from here on the tag is bold, and a figure all of whose contacts are here says so in words.
|
|
75
|
+
PAE_STRONG = 10
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
#: The bands of a PAE that is drawn as a glow, best first: the name of the colour (those that pLDDT is drawn in,
|
|
79
|
+
#: with the same meaning: blue is sure, orange is not) and the PAE, in ångström, from which it is this one.
|
|
80
|
+
PAE_BANDS: "tuple[tuple[str, float], ...]" = (("very_high", 0.0), ("confident", 5.0), ("low", 10.0), ("very_low", 15.0))
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _a_pae(value: float) -> float:
|
|
84
|
+
"""A PAE as the number it has to be: of ångström, from 0. Not a number, below 0 and without end are refused."""
|
|
85
|
+
if not 0.0 <= float(value) < float("inf"):
|
|
86
|
+
raise BindviewError(f"a PAE is a number of ångström from 0, not {value!r}")
|
|
87
|
+
return float(value)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def pae_band(value: float) -> str:
|
|
91
|
+
"""The band of a PAE (:data:`PAE_BANDS`)."""
|
|
92
|
+
value = _a_pae(value)
|
|
93
|
+
return next(name for name, least in reversed(PAE_BANDS) if value >= least)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
#: The residues a co-folding model of the AlphaFold 3 kind (Boltz among them) takes as one token
|
|
97
|
+
#: each: the standard amino acids and nucleotides, and the unknown ones. Any other residue (a ligand,
|
|
98
|
+
#: a modified residue) is one token for each of its heavy atoms.
|
|
99
|
+
ONE_TOKEN = frozenset("ALA ARG ASN ASP CYS GLN GLU GLY HIS ILE LEU LYS MET PHE PRO SER THR TRP TYR VAL UNK "
|
|
100
|
+
"A C G U N DA DC DG DT DN".split())
|
|
101
|
+
#: What an ``.npz`` that is not a PAE says of itself, by the name of its array.
|
|
102
|
+
_NOT_PAE = {
|
|
103
|
+
"pde": ("a predicted distance error (PDE)",
|
|
104
|
+
"PDE is another quantity: the expected error of the distance between two residues, with no frame "
|
|
105
|
+
"of reference. bindview writes PAE on a contact and does not draw PDE; give the pae_*.npz of the "
|
|
106
|
+
"same model"),
|
|
107
|
+
"plddt": ("per-residue pLDDT",
|
|
108
|
+
"pLDDT is about one residue and PAE about two. bindview reads pLDDT from the model file, where "
|
|
109
|
+
"Boltz writes it on the 0-100 scale and declares it; give the pae_*.npz of the same model"),
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
#: Two assignments of the copies of a chain whose fits differ by no more than this (CA RMSD, ångström)
|
|
114
|
+
#: fit equally well: a symmetric oligomer does in each of its rotations.
|
|
115
|
+
SAME_FIT = 0.5
|
|
116
|
+
#: Assignments of copies that are tried one by one; beyond this many a model is not matched.
|
|
117
|
+
MAX_ASSIGNMENTS = 5040
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def tokens_of(structure: "Structure") -> tuple[tuple[str, ...], tuple[int, ...]]:
|
|
121
|
+
"""Chain and residue number of every token of a model, in the order of its file.
|
|
122
|
+
|
|
123
|
+
A matrix that comes without the names of its rows (Boltz's ``pae_*.npz``)
|
|
124
|
+
has one row per token, in the order in which the model's file lists its
|
|
125
|
+
residues: one for a standard residue of a polymer, one per heavy atom for
|
|
126
|
+
anything else (:data:`ONE_TOKEN`), as the published tokenisation has it.
|
|
127
|
+
A matrix is only ever taken if its size is exactly the number of tokens
|
|
128
|
+
counted this way.
|
|
129
|
+
"""
|
|
130
|
+
chains, numbers, _, _, _ = _tokens(structure)
|
|
131
|
+
return chains, numbers
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _tokens(structure: "Structure"
|
|
135
|
+
) -> tuple[tuple[str, ...], tuple[int, ...], tuple[str, ...], np.ndarray, tuple[str, ...]]:
|
|
136
|
+
""":func:`tokens_of`, and with every token the name of its residue, a place for it (its CA, or
|
|
137
|
+
the centre of its heavy atoms where it has none) and the insertion code of its residue."""
|
|
138
|
+
chains: list[str] = []
|
|
139
|
+
numbers: list[int] = []
|
|
140
|
+
names: list[str] = []
|
|
141
|
+
places: list[tuple[float, float, float]] = []
|
|
142
|
+
icodes: list[str] = []
|
|
143
|
+
for key in structure.residues():
|
|
144
|
+
atoms = [a for a in structure.residue_atoms(key) if a.element not in ("H", "D")]
|
|
145
|
+
name = structure.residue_name(key)
|
|
146
|
+
n = 1 if name in ONE_TOKEN else len(atoms)
|
|
147
|
+
ca = [a.xyz for a in atoms if a.name == "CA"]
|
|
148
|
+
place = ca[0] if ca else tuple(np.mean([a.xyz for a in atoms], axis=0)) if atoms else (0.0, 0.0, 0.0)
|
|
149
|
+
chains.extend([key.chain] * n)
|
|
150
|
+
numbers.extend([key.number] * n)
|
|
151
|
+
names.extend([name] * n)
|
|
152
|
+
places.extend([place] * n)
|
|
153
|
+
icodes.extend([key.icode] * n)
|
|
154
|
+
return tuple(chains), tuple(numbers), tuple(names), np.array(places, dtype=float).reshape(-1, 3), tuple(icodes)
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def _per_chain(chains: Sequence[str]) -> str:
|
|
158
|
+
"""How many tokens each chain has, in words: ``chain A: 157, chain B: 157``."""
|
|
159
|
+
per: dict[str, int] = {}
|
|
160
|
+
for c in chains:
|
|
161
|
+
per[c] = per.get(c, 0) + 1
|
|
162
|
+
return ", ".join(f"chain {c}: {n}" for c, n in per.items())
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def _afdb_matrix(data: Any, source: str = "") -> "np.ndarray | None":
|
|
166
|
+
"""The matrix of the AlphaFold database's PAE file, or ``None`` where ``data`` is not what such a file holds.
|
|
167
|
+
|
|
168
|
+
The database writes a list with one object, ``[{"predicted_aligned_error": [[...], ...],
|
|
169
|
+
"max_predicted_aligned_error": 31.75}]``. Some older files are that object without the list, and
|
|
170
|
+
the first ones hold three flat lists instead of the matrix: ``residue1``, ``residue2`` and
|
|
171
|
+
``distance``, the two residues counted from 1. In every form the matrix is n × n, in ångström,
|
|
172
|
+
for the n residues of the one chain of the model, in the model's order, and ``[i][j]`` (in the
|
|
173
|
+
flat lists: ``residue1`` i + 1 with ``residue2`` j + 1) is the error of residue j when the model
|
|
174
|
+
is aligned on residue i: rows are aligned residues, as in :class:`Pae`. The file of a model of
|
|
175
|
+
several chains declares them beside the matrix (:func:`_afdb_chains`).
|
|
176
|
+
"""
|
|
177
|
+
held = data[0] if isinstance(data, list) and len(data) == 1 else data
|
|
178
|
+
if not isinstance(held, dict) or "pae" in held:
|
|
179
|
+
return None
|
|
180
|
+
flat = ("residue1", "residue2", "distance")
|
|
181
|
+
if "predicted_aligned_error" not in held and not all(k in held for k in flat):
|
|
182
|
+
return None
|
|
183
|
+
what = source or "the PAE file"
|
|
184
|
+
try:
|
|
185
|
+
if "predicted_aligned_error" in held:
|
|
186
|
+
matrix = np.array(held["predicted_aligned_error"], dtype=float)
|
|
187
|
+
else:
|
|
188
|
+
first, second = (np.array(held[k], dtype=int) for k in flat[:2])
|
|
189
|
+
values = np.array(held["distance"], dtype=float)
|
|
190
|
+
if not (first.ndim == second.ndim == values.ndim == 1 and len(first) == len(second) == len(values)):
|
|
191
|
+
raise ValueError(f"'residue1', 'residue2' and 'distance' are lists of {first.size}, {second.size} "
|
|
192
|
+
f"and {values.size} values")
|
|
193
|
+
if not len(first) or min(first.min(), second.min()) < 1:
|
|
194
|
+
raise ValueError("'residue1' and 'residue2' count the residues from 1")
|
|
195
|
+
n = int(max(first.max(), second.max()))
|
|
196
|
+
matrix = np.full((n, n), np.nan)
|
|
197
|
+
matrix[first - 1, second - 1] = values
|
|
198
|
+
except (TypeError, ValueError) as exc:
|
|
199
|
+
raise BindviewError(f"{what} is written as the PAE file of the AlphaFold database, and its predicted aligned "
|
|
200
|
+
f"errors are not a matrix of numbers: {exc}") from exc
|
|
201
|
+
if matrix.ndim != 2 or matrix.shape[0] != matrix.shape[1] or not matrix.size:
|
|
202
|
+
raise BindviewError(f"{what} is written as the PAE file of the AlphaFold database, and its "
|
|
203
|
+
f"'predicted_aligned_error' is not a square matrix "
|
|
204
|
+
f"({' x '.join(str(n) for n in matrix.shape) or 'no rows'})")
|
|
205
|
+
return matrix
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def _afdb_chains(data: Any, size: int, source: str = "") -> "list[tuple[str, int]] | None":
|
|
209
|
+
"""The chains that the AlphaFold database's PAE file declares, each as its ``label_asym_id`` and its
|
|
210
|
+
number of residues, in the order of the rows; ``None`` where the file declares none.
|
|
211
|
+
|
|
212
|
+
The file of a model of several chains holds, beside the matrix, ``"chains": [{"label_asym_id": "A",
|
|
213
|
+
"sequenceStart": 1, "sequenceEnd": 246}, ...]``: its rows are those chains one after the other, each
|
|
214
|
+
over its residues from the first to the last. The residues declared have to be as many as the matrix
|
|
215
|
+
has rows. A file that holds fewer rows than it declares is not read: every row after the missing ones
|
|
216
|
+
would be taken for another residue, and nothing on a figure would show it.
|
|
217
|
+
"""
|
|
218
|
+
held = data[0] if isinstance(data, list) and len(data) == 1 else data
|
|
219
|
+
if not isinstance(held, dict) or not held.get("chains"):
|
|
220
|
+
return None
|
|
221
|
+
what = source or "the PAE file"
|
|
222
|
+
try:
|
|
223
|
+
declared = [(str(c["label_asym_id"]), int(c["sequenceStart"]), int(c["sequenceEnd"])) for c in held["chains"]]
|
|
224
|
+
except (KeyError, TypeError, ValueError) as exc:
|
|
225
|
+
raise BindviewError(f"{what} declares the chains of its matrix ('chains') in a form that is not read here: "
|
|
226
|
+
f"each needs 'label_asym_id', 'sequenceStart' and 'sequenceEnd' ({exc!r})") from exc
|
|
227
|
+
names = [name for name, _, _ in declared]
|
|
228
|
+
if len(set(names)) != len(names) or any(last < first for _, first, last in declared):
|
|
229
|
+
raise BindviewError(f"{what} declares the chains of its matrix as "
|
|
230
|
+
f"{', '.join(f'{name} {first}-{last}' for name, first, last in declared)}: a chain is "
|
|
231
|
+
f"declared once, from its first residue to its last")
|
|
232
|
+
counted = [(name, last - first + 1) for name, first, last in declared]
|
|
233
|
+
if sum(n for _, n in counted) != size:
|
|
234
|
+
raise BindviewError(f"{what} declares {sum(n for _, n in counted)} residues in its chains "
|
|
235
|
+
f"({', '.join(f'chain {name}: {n}' for name, n in counted)}), and its matrix is {size} x "
|
|
236
|
+
f"{size}: the file does not hold the rows it declares (is it whole?)")
|
|
237
|
+
return counted
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def _named_places(structure: "Structure", keys: Sequence[ResidueKey]) -> tuple[tuple[str, ...], np.ndarray]:
|
|
241
|
+
"""The name of each residue and a place for it: its CA, or the centre of its heavy atoms where it has none."""
|
|
242
|
+
names, places = [], []
|
|
243
|
+
for k in keys:
|
|
244
|
+
atoms = [a for a in structure.residue_atoms(k) if a.element not in ("H", "D")]
|
|
245
|
+
ca = [a.xyz for a in atoms if a.name == "CA"]
|
|
246
|
+
names.append(structure.residue_name(k))
|
|
247
|
+
places.append(ca[0] if ca else tuple(np.mean([a.xyz for a in atoms], axis=0)))
|
|
248
|
+
return tuple(names), np.array(places, dtype=float).reshape(-1, 3)
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def model_beside(path: "str | Path") -> "Path | None":
|
|
252
|
+
"""The model file a matrix belongs to, where it sits beside it under the name Boltz gives the
|
|
253
|
+
two: ``pae_<name>.npz`` with ``<name>.cif`` (or ``.pdb``). By name only, never "whatever
|
|
254
|
+
structure is in the folder"."""
|
|
255
|
+
p = Path(path)
|
|
256
|
+
if p.suffix != ".npz" or not p.name.startswith("pae_"):
|
|
257
|
+
return None
|
|
258
|
+
for suffix in (".cif", ".pdb"):
|
|
259
|
+
cand = p.with_name(p.name[len("pae_"):-len(".npz")] + suffix)
|
|
260
|
+
if cand.is_file():
|
|
261
|
+
return cand
|
|
262
|
+
return None
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def _fit(a: np.ndarray, b: np.ndarray) -> float:
|
|
266
|
+
"""Root mean square distance between two sets of points after the best superposition of one on the other."""
|
|
267
|
+
a0, b0 = a - a.mean(axis=0), b - b.mean(axis=0)
|
|
268
|
+
u, sv, vt = np.linalg.svd(a0.T @ b0)
|
|
269
|
+
sign = 1.0 if np.linalg.det(u @ vt) >= 0.0 else -1.0
|
|
270
|
+
rest = float((a0 ** 2).sum() + (b0 ** 2).sum() - 2.0 * (sv[0] + sv[1] + sign * sv[2]))
|
|
271
|
+
return float(np.sqrt(max(rest, 0.0) / len(a)))
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
def _copies(chains: Sequence[str], numbers: Sequence[int], names: Sequence[str]) -> list[list[str]]:
|
|
275
|
+
"""The chains that are copies of one another: the same residues, by number and by name, in the
|
|
276
|
+
same order. Each group in the order of the file. Without ``names`` (a matrix that came without
|
|
277
|
+
its model) these are the chains with the same residue numbers, which may or may not be copies."""
|
|
278
|
+
made: dict[str, list[tuple[int, str]]] = {}
|
|
279
|
+
for i, c in enumerate(chains):
|
|
280
|
+
made.setdefault(c, []).append((numbers[i], names[i] if names else ""))
|
|
281
|
+
groups: dict[tuple, list[str]] = {}
|
|
282
|
+
for c, residues in made.items():
|
|
283
|
+
groups.setdefault(tuple(residues), []).append(c)
|
|
284
|
+
return [g for g in groups.values() if len(g) > 1]
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
def match_chains(reference: "Pae", draw: "Pae") -> tuple[dict[str, str], float, float]:
|
|
288
|
+
"""Which chain of ``draw`` is which chain of ``reference``, where a model has copies of a chain.
|
|
289
|
+
|
|
290
|
+
Returns the assignment (chain of the reference: chain of the draw), its CA RMSD after
|
|
291
|
+
superposition, and the RMSD with the chains as they are named. Chains that are not copies of
|
|
292
|
+
another keep their names. Every assignment of the copies is tried; the one that fits best wins,
|
|
293
|
+
and among those within :data:`SAME_FIT` of the best (a symmetric oligomer fits equally well in
|
|
294
|
+
each of its rotations) the one that renames the fewest chains, then the first in alphabetical
|
|
295
|
+
order. A model with copies and no coordinates for one of the two is refused: a matrix cannot say
|
|
296
|
+
which of two identical chains is which. So are chains with the same residue numbers where the
|
|
297
|
+
names of their residues are not known either: they may be copies.
|
|
298
|
+
"""
|
|
299
|
+
if draw.chains != reference.chains or draw.numbers != reference.numbers:
|
|
300
|
+
raise BindviewError(f"{draw.source or 'a draw'} and {reference.source or 'the reference'} do not have the "
|
|
301
|
+
f"same residues in the same order: they are not of one model")
|
|
302
|
+
order = list(dict.fromkeys(reference.chains))
|
|
303
|
+
same = {c: c for c in order}
|
|
304
|
+
copies = _copies(reference.chains, reference.numbers, reference.resnames)
|
|
305
|
+
if not copies:
|
|
306
|
+
return same, 0.0, 0.0
|
|
307
|
+
if reference.places is None or draw.places is None:
|
|
308
|
+
named = " and ".join(", ".join(g) for g in copies)
|
|
309
|
+
# What their residues are is known from the model alone: without it, equal numbers are all there is.
|
|
310
|
+
what = ("are copies of one another, and a model" if reference.resnames else
|
|
311
|
+
"have the same residue numbers and may be copies of one another (which residues they are is not "
|
|
312
|
+
"known without the model). A model")
|
|
313
|
+
raise BindviewError(
|
|
314
|
+
f"chains {named} {what} is free to name its copies in another order "
|
|
315
|
+
f"in every draw: the values of {draw.source or 'a draw'} cannot be read by chain name. Give the model "
|
|
316
|
+
f"file of every draw with its matrix (a pair of matrix and structure; Boltz's pae_<name>.npz is "
|
|
317
|
+
f"paired with <name>.cif beside it by itself)")
|
|
318
|
+
count = 1
|
|
319
|
+
for g in copies:
|
|
320
|
+
for k in range(2, len(g) + 1):
|
|
321
|
+
count *= k
|
|
322
|
+
if count > MAX_ASSIGNMENTS:
|
|
323
|
+
raise BindviewError(f"{count} ways to assign the copies of this model's chains to each other: more than "
|
|
324
|
+
f"are tried ({MAX_ASSIGNMENTS})")
|
|
325
|
+
rows = {c: [i for i, x in enumerate(draw.chains) if x == c] for c in order}
|
|
326
|
+
mine = np.concatenate([[i for i, x in enumerate(reference.chains) if x == c] for c in order])
|
|
327
|
+
tried = []
|
|
328
|
+
for choice in product(*(permutations(g) for g in copies)):
|
|
329
|
+
assignment = dict(same)
|
|
330
|
+
for g, chosen in zip(copies, choice):
|
|
331
|
+
assignment.update(zip(g, chosen))
|
|
332
|
+
theirs = np.concatenate([rows[assignment[c]] for c in order])
|
|
333
|
+
changed = sum(1 for c in order if assignment[c] != c)
|
|
334
|
+
tried.append((_fit(reference.places[mine], draw.places[theirs]), changed, tuple(assignment[c] for c in order)))
|
|
335
|
+
best = min(t[0] for t in tried)
|
|
336
|
+
fit, _, names = min((t for t in tried if t[0] <= best + SAME_FIT), key=lambda t: (t[1], t[2]))
|
|
337
|
+
as_named = next(t[0] for t in tried if t[1] == 0)
|
|
338
|
+
return dict(zip(order, names)), fit, as_named
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
def pae_shown(value: "float | None") -> "int | None":
|
|
342
|
+
"""The PAE of a contact as it is printed: whole ångström, half rounded up; ``None`` when there is none."""
|
|
343
|
+
return None if value is None else int(_a_pae(value) + 0.5)
|
|
344
|
+
|
|
345
|
+
|
|
346
|
+
def pae_tag(value: "float | None") -> "tuple[str, bool] | None":
|
|
347
|
+
"""What is written on a contact's line for its PAE: ``("PAE 11", bold)``, or ``None`` below the threshold."""
|
|
348
|
+
shown = pae_shown(value)
|
|
349
|
+
if shown is None or shown < PAE_SHOWN:
|
|
350
|
+
return None
|
|
351
|
+
return f"PAE {shown}", shown >= PAE_STRONG
|
|
352
|
+
|
|
353
|
+
|
|
354
|
+
def pae_key(bold: "Iterable[bool]") -> "tuple[tuple[str, bool], ...]":
|
|
355
|
+
"""The legend's sample of a PAE tag, for a figure whose tags are written as ``bold`` says (one entry
|
|
356
|
+
for each tag: is it bold?).
|
|
357
|
+
|
|
358
|
+
A key shows a thing the way the figure draws it. Where every tag is bold the key is a bold tag, where
|
|
359
|
+
none is a plain one, and where both occur one of each, the plain one first. The samples are tags as
|
|
360
|
+
:func:`pae_tag` writes them (of 7 and of 11 Å), not values of the figure: a key that is bold in a
|
|
361
|
+
figure whose tags are all plain reads as a value, the largest one, that no contact has.
|
|
362
|
+
"""
|
|
363
|
+
written = set(bold)
|
|
364
|
+
plain, strong = pae_tag(PAE_SHOWN + 2.0), pae_tag(PAE_STRONG + 1.0)
|
|
365
|
+
assert plain is not None and strong is not None
|
|
366
|
+
return tuple(key for key in (plain, strong) if key[1] in written) or (strong,)
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
@dataclass(frozen=True)
|
|
370
|
+
class Pae:
|
|
371
|
+
"""A PAE matrix with the residue each row stands for."""
|
|
372
|
+
|
|
373
|
+
matrix: np.ndarray # (n, n); [i, j]: expected error of token j when aligned on token i
|
|
374
|
+
chains: tuple[str, ...]
|
|
375
|
+
numbers: tuple[int, ...]
|
|
376
|
+
source: str = ""
|
|
377
|
+
#: The name of every row's residue and a place for it (its CA), where the model the matrix belongs
|
|
378
|
+
#: to was read with it. Needed to tell the copies of a chain apart from one draw to the next
|
|
379
|
+
#: (:func:`match_chains`), and for nothing else.
|
|
380
|
+
resnames: tuple[str, ...] = ()
|
|
381
|
+
places: "np.ndarray | None" = field(default=None, repr=False, compare=False)
|
|
382
|
+
#: The insertion code of every row's residue, where the rows are those of a model file (Boltz's
|
|
383
|
+
#: ``pae_*.npz``): ``H:100`` and ``H:100A`` are then two residues. Empty where the matrix names its
|
|
384
|
+
#: rows itself, by chain and number.
|
|
385
|
+
icodes: tuple[str, ...] = ()
|
|
386
|
+
#: Is a residue that the matrix does not have under its chain name looked up by its number alone?
|
|
387
|
+
#: Settled where the matrix was read with its model: ``True`` for a matrix of one chain whose model
|
|
388
|
+
#: has that chain cut into participants, under other names; ``False`` where the rows are named as
|
|
389
|
+
#: the model names its residues. ``None``, read without a model: where the matrix has one chain.
|
|
390
|
+
by_number: "bool | None" = None
|
|
391
|
+
|
|
392
|
+
@classmethod
|
|
393
|
+
def read(cls, path: "str | Path", structure: "Structure | None" = None, placed: bool = True) -> "Pae":
|
|
394
|
+
"""Read a PAE matrix from a model's own file.
|
|
395
|
+
|
|
396
|
+
AlphaFold 3's ``confidences.json`` (or ``.json.gz``) names its rows
|
|
397
|
+
itself (keys ``pae``, ``token_res_ids``, ``token_chain_ids``). Boltz's
|
|
398
|
+
``pae_*.npz`` is the matrix and nothing else: the rows are then those of
|
|
399
|
+
``structure``, the model the matrix belongs to (:func:`tokens_of`), and
|
|
400
|
+
without it the file cannot be read. Either file is refused where it is
|
|
401
|
+
not the matrix of ``structure``: where its rows are not the tokens of
|
|
402
|
+
that model (:meth:`at`).
|
|
403
|
+
|
|
404
|
+
The PAE file of the AlphaFold database
|
|
405
|
+
(``AF-<accession>-F1-predicted_aligned_error_v4.json``, or ``.json.gz``;
|
|
406
|
+
a list with one object that holds ``predicted_aligned_error``, and the
|
|
407
|
+
two older forms of it) is a matrix without the names of its rows too:
|
|
408
|
+
n × n for the n residues of the one chain of its model, in the model's
|
|
409
|
+
order. Its rows are the residues of the polymer chain of ``structure``,
|
|
410
|
+
by their chain name and numbers there, and it is refused, with both
|
|
411
|
+
sizes, where that chain has another number of residues or the model has
|
|
412
|
+
several chains. One chain that was cut into participants
|
|
413
|
+
(:meth:`bindview.structure.Structure.split`) is still one chain: its
|
|
414
|
+
parts keep their residue numbers, which run on from one part to the
|
|
415
|
+
next. The file of a model of several chains (a complex of the
|
|
416
|
+
database) declares its chains beside the matrix (``chains``, each by
|
|
417
|
+
its ``label_asym_id`` with its first and last residue): its rows are
|
|
418
|
+
those chains of ``structure``, one after the other. It is refused where
|
|
419
|
+
it holds fewer or more rows than it declares, and where ``structure``
|
|
420
|
+
has another number of residues in one of them or a polymer chain that
|
|
421
|
+
it does not declare.
|
|
422
|
+
|
|
423
|
+
In every file, and in :attr:`matrix`, row i and column j hold the error
|
|
424
|
+
of residue j when the model is aligned on residue i.
|
|
425
|
+
|
|
426
|
+
``placed``: the structure is the matrix's own model (and not another
|
|
427
|
+
draw's, lent for the names of the rows), so its coordinates may be kept
|
|
428
|
+
with the rows.
|
|
429
|
+
"""
|
|
430
|
+
p = Path(path)
|
|
431
|
+
if p.suffix == ".npz":
|
|
432
|
+
return cls._read_npz(p, structure, placed)
|
|
433
|
+
try:
|
|
434
|
+
raw = gzip.open(p, "rt", encoding="utf-8") if p.suffix == ".gz" else open(p, encoding="utf-8")
|
|
435
|
+
with raw as fh:
|
|
436
|
+
data: Any = json.load(fh)
|
|
437
|
+
except (OSError, ValueError) as exc:
|
|
438
|
+
raise BindviewError(f"cannot read a PAE matrix from {p}: {exc}") from exc
|
|
439
|
+
return cls.from_mapping(data, p.name, structure, placed)
|
|
440
|
+
|
|
441
|
+
def at(self, structure: "Structure", placed: bool = True) -> "Pae":
|
|
442
|
+
"""The same matrix with the residue names and places of its rows from the model it belongs to.
|
|
443
|
+
|
|
444
|
+
The rows have to be the tokens of that model (:func:`tokens_of`), chain by chain and number
|
|
445
|
+
by number, in whatever order. A matrix of one chain is also taken for a model that has its
|
|
446
|
+
residues, number for number, under other chain names: a chain that was cut into participants
|
|
447
|
+
keeps its numbers and not its name. Its rows are then found by number alone
|
|
448
|
+
(:attr:`by_number`), and it is given no names and places. Any other matrix is not of this
|
|
449
|
+
model and is refused, with the tokens of both. ``placed=False`` checks, and gives no names
|
|
450
|
+
and places either.
|
|
451
|
+
"""
|
|
452
|
+
chains, numbers, _, _, _ = _tokens(structure)
|
|
453
|
+
if sorted(zip(self.chains, self.numbers)) != sorted(zip(chains, numbers)):
|
|
454
|
+
if len(set(self.chains)) == 1 and sorted(self.numbers) == sorted(numbers):
|
|
455
|
+
return replace(self, by_number=True)
|
|
456
|
+
raise BindviewError(
|
|
457
|
+
f"{self.source or 'the PAE matrix'} has {len(self.numbers)} tokens ({_per_chain(self.chains)}), and "
|
|
458
|
+
f"{structure.source or 'the structure'} has {len(numbers)} ({_per_chain(chains)}): the two are not "
|
|
459
|
+
f"of the same model, or its residues are not tokens the way bindview counts them")
|
|
460
|
+
if not placed:
|
|
461
|
+
return replace(self, by_number=False)
|
|
462
|
+
where = {}
|
|
463
|
+
for key in structure.residues():
|
|
464
|
+
atoms = [a for a in structure.residue_atoms(key) if a.element not in ("H", "D")]
|
|
465
|
+
ca = [a.xyz for a in atoms if a.name == "CA"]
|
|
466
|
+
if atoms:
|
|
467
|
+
where[(key.chain, key.number)] = (structure.residue_name(key),
|
|
468
|
+
ca[0] if ca else tuple(np.mean([a.xyz for a in atoms], axis=0)))
|
|
469
|
+
try:
|
|
470
|
+
found = [where[(c, n)] for c, n in zip(self.chains, self.numbers)]
|
|
471
|
+
except KeyError:
|
|
472
|
+
return replace(self, by_number=False)
|
|
473
|
+
return replace(self, resnames=tuple(f[0] for f in found), by_number=False,
|
|
474
|
+
places=np.array([f[1] for f in found], dtype=float).reshape(-1, 3))
|
|
475
|
+
|
|
476
|
+
@classmethod
|
|
477
|
+
def from_mapping(cls, data: Any, source: str = "", structure: "Structure | None" = None,
|
|
478
|
+
placed: bool = True) -> "Pae":
|
|
479
|
+
"""A matrix from what a model's JSON file holds, as :meth:`read` reads it from the file.
|
|
480
|
+
|
|
481
|
+
AlphaFold 3's mapping (``pae``, ``token_res_ids`` and ``token_chain_ids``) names its rows
|
|
482
|
+
itself, and is checked against ``structure`` where one is given (:meth:`at`). What the PAE
|
|
483
|
+
file of the AlphaFold database holds does not: its rows are the residues of ``structure``,
|
|
484
|
+
which it cannot be read without. ``source`` is what an error calls the file.
|
|
485
|
+
"""
|
|
486
|
+
held = _afdb_matrix(data, source)
|
|
487
|
+
if held is not None:
|
|
488
|
+
declared = _afdb_chains(data, held.shape[0], source)
|
|
489
|
+
if declared is not None and len(declared) > 1:
|
|
490
|
+
return cls._of_chains(held, declared, source, structure, placed)
|
|
491
|
+
return cls._of_one_chain(held, source, structure, placed)
|
|
492
|
+
if not isinstance(data, dict):
|
|
493
|
+
raise BindviewError(
|
|
494
|
+
f"{source or 'the PAE file'} is no PAE file that is read here: neither AlphaFold 3's (an object "
|
|
495
|
+
f"with 'pae' and 'token_res_ids') nor the AlphaFold database's (a list with one object that has "
|
|
496
|
+
f"'predicted_aligned_error'), but a JSON {type(data).__name__}")
|
|
497
|
+
try:
|
|
498
|
+
matrix = np.array(data["pae"], dtype=float)
|
|
499
|
+
numbers = tuple(int(n) for n in data["token_res_ids"])
|
|
500
|
+
chains = tuple(str(c) for c in data.get("token_chain_ids") or [""] * len(numbers))
|
|
501
|
+
except (KeyError, TypeError, ValueError) as exc:
|
|
502
|
+
raise BindviewError(f"{source or 'the PAE file'} has no 'pae' with 'token_res_ids': {exc}") from exc
|
|
503
|
+
if matrix.ndim != 2 or matrix.shape[0] != matrix.shape[1] or matrix.shape[0] != len(numbers) \
|
|
504
|
+
or len(chains) != len(numbers):
|
|
505
|
+
raise BindviewError(f"{source or 'the PAE file'}: the matrix and its residue numbers do not fit "
|
|
506
|
+
f"({matrix.shape}, {len(numbers)} residues)")
|
|
507
|
+
made = cls(matrix, chains, numbers, source)
|
|
508
|
+
return made.at(structure, placed) if structure is not None else made
|
|
509
|
+
|
|
510
|
+
@classmethod
|
|
511
|
+
def _of_one_chain(cls, matrix: np.ndarray, source: str, structure: "Structure | None",
|
|
512
|
+
placed: bool = True) -> "Pae":
|
|
513
|
+
"""The matrix of the AlphaFold database's file with the residues of its model as its rows.
|
|
514
|
+
|
|
515
|
+
The rows are the residues of the polymer chain of ``structure``
|
|
516
|
+
(:meth:`bindview.structure.Structure.polymer_residues`), in the order of the file; what else
|
|
517
|
+
the file holds (water, a ligand that was put into the model) has no row. A model of several
|
|
518
|
+
polymer chains is not the model of such a matrix, unless they are one chain that was cut into
|
|
519
|
+
participants: their residue numbers then run on from one to the next and none comes twice.
|
|
520
|
+
The rows of that chain go under no chain name and are found by number alone.
|
|
521
|
+
"""
|
|
522
|
+
what, size = source or "the PAE file", " x ".join(str(n) for n in matrix.shape)
|
|
523
|
+
if structure is None:
|
|
524
|
+
raise BindviewError(f"{what} is the PAE file of the AlphaFold database, a matrix without the names of "
|
|
525
|
+
f"its rows: the model it belongs to has to be given with it, to say which row is "
|
|
526
|
+
f"which residue")
|
|
527
|
+
model = structure.source or "the structure"
|
|
528
|
+
parts = {c: structure.polymer_residues(c) for c in dict.fromkeys(a.chain for a in structure.atoms)}
|
|
529
|
+
parts = {c: keys for c, keys in parts.items() if keys}
|
|
530
|
+
inside = {k for keys in parts.values() for k in keys}
|
|
531
|
+
keys = [k for k in structure.residues() if k in inside]
|
|
532
|
+
counted = ", ".join(f"chain {c}: {len(ks)}" for c, ks in parts.items()) or "no polymer chain"
|
|
533
|
+
cut = len(parts) > 1 and all(a.number < b.number for a, b in zip(keys, keys[1:]))
|
|
534
|
+
if len(parts) > 1 and not cut:
|
|
535
|
+
raise BindviewError(
|
|
536
|
+
f"{what} is a matrix of {size}, for the residues of one chain as the AlphaFold database predicts "
|
|
537
|
+
f"it, and {model} has {len(parts)} polymer chains ({counted}), which are not one chain cut into "
|
|
538
|
+
f"parts either (their residue numbers do not run on from one to the next): the two are not of the "
|
|
539
|
+
f"same model")
|
|
540
|
+
if len(keys) != matrix.shape[0]:
|
|
541
|
+
raise BindviewError(f"{what} is a matrix of {size}, and {model} has {len(keys)} residues ({counted}): "
|
|
542
|
+
f"the two are not of the same model")
|
|
543
|
+
names, places = _named_places(structure, keys)
|
|
544
|
+
return cls(matrix, tuple("" if cut else k.chain for k in keys), tuple(k.number for k in keys), source,
|
|
545
|
+
names, places if placed else None, tuple(k.icode for k in keys), by_number=cut)
|
|
546
|
+
|
|
547
|
+
@classmethod
|
|
548
|
+
def _of_chains(cls, matrix: np.ndarray, declared: "list[tuple[str, int]]", source: str,
|
|
549
|
+
structure: "Structure | None", placed: bool = True) -> "Pae":
|
|
550
|
+
"""The matrix of the AlphaFold database's file of a complex with the residues of its model as its rows.
|
|
551
|
+
|
|
552
|
+
The file names its chains by their ``label_asym_id`` (:func:`_afdb_chains`). A chain of the file is
|
|
553
|
+
the chain of the model whose polymer atoms have that label, or, where no polymer atom has it, the
|
|
554
|
+
chain of that name. Its rows are its polymer residues
|
|
555
|
+
(:meth:`bindview.structure.Structure.polymer_residues`) in the order of the model's file, named as
|
|
556
|
+
the model names them. A chain that was cut into participants
|
|
557
|
+
(:meth:`bindview.structure.Structure.split`) keeps its label: its rows are the residues of its parts.
|
|
558
|
+
The model has to have every chain the file declares, each with as many residues, and no other
|
|
559
|
+
polymer chain.
|
|
560
|
+
"""
|
|
561
|
+
what = source or "the PAE file"
|
|
562
|
+
listed = ", ".join(f"chain {name}: {n}" for name, n in declared)
|
|
563
|
+
if structure is None:
|
|
564
|
+
raise BindviewError(f"{what} is the PAE file of a complex of the AlphaFold database ({listed}): the model "
|
|
565
|
+
f"it belongs to has to be given with it, to say which of its chains each row is in")
|
|
566
|
+
model = structure.source or "the structure"
|
|
567
|
+
parts = {c: structure.polymer_residues(c) for c in dict.fromkeys(a.chain for a in structure.atoms)}
|
|
568
|
+
parts = {c: keys for c, keys in parts.items() if keys}
|
|
569
|
+
counted = ", ".join(f"chain {c}: {len(ks)}" for c, ks in parts.items()) or "no polymer chain"
|
|
570
|
+
keys: list[ResidueKey] = []
|
|
571
|
+
taken: list[str] = []
|
|
572
|
+
for label, n in declared:
|
|
573
|
+
chains = [c for c in structure._by_label(label) if c in parts] or ([label] if label in parts else [])
|
|
574
|
+
if not chains or set(chains) & set(taken):
|
|
575
|
+
raise BindviewError(f"{what} declares chain {label} ({listed}), and {model} has no polymer chain of "
|
|
576
|
+
f"that name that is not another's ({counted}): the two are not of the same model")
|
|
577
|
+
taken.extend(chains)
|
|
578
|
+
inside = {k for c in chains for k in parts[c]}
|
|
579
|
+
mine = [k for k in structure.residues() if k in inside]
|
|
580
|
+
if len(mine) != n:
|
|
581
|
+
said = f"chain {label}" + (f" (in the model {', '.join(chains)})" if chains != [label] else "")
|
|
582
|
+
raise BindviewError(f"{what} declares {n} residues in {said} ({listed}), and {model} has {len(mine)} "
|
|
583
|
+
f"there ({counted}): the two are not of the same model")
|
|
584
|
+
keys.extend(mine)
|
|
585
|
+
rest = [c for c in parts if c not in taken]
|
|
586
|
+
if rest:
|
|
587
|
+
raise BindviewError(f"{what} declares {listed}, and {model} has polymer chains besides "
|
|
588
|
+
f"({', '.join(rest)}): the two are not of the same model")
|
|
589
|
+
names, places = _named_places(structure, keys)
|
|
590
|
+
return cls(matrix, tuple(k.chain for k in keys), tuple(k.number for k in keys), source,
|
|
591
|
+
names, places if placed else None, tuple(k.icode for k in keys), by_number=False)
|
|
592
|
+
|
|
593
|
+
@classmethod
|
|
594
|
+
def _read_npz(cls, p: Path, structure: "Structure | None", placed: bool = True) -> "Pae":
|
|
595
|
+
"""Boltz's ``pae_*.npz``: one array, named ``pae``. An array of another name is another quantity."""
|
|
596
|
+
try:
|
|
597
|
+
with np.load(p, allow_pickle=False) as held:
|
|
598
|
+
arrays = list(held.files)
|
|
599
|
+
matrix = np.array(held["pae"], dtype=float) if "pae" in arrays else None
|
|
600
|
+
except (OSError, ValueError, EOFError, KeyError, zipfile.BadZipFile) as exc:
|
|
601
|
+
raise BindviewError(f"cannot read a PAE matrix from {p}: {exc}") from exc
|
|
602
|
+
if matrix is None:
|
|
603
|
+
for name, (what, why) in _NOT_PAE.items():
|
|
604
|
+
if name in arrays:
|
|
605
|
+
raise BindviewError(f"{p.name} holds {what}, not a predicted aligned error (its array is named "
|
|
606
|
+
f"{name!r}). {why}")
|
|
607
|
+
raise BindviewError(f"{p.name} has no array named 'pae' (it has {', '.join(map(repr, arrays)) or 'none'})")
|
|
608
|
+
if structure is None:
|
|
609
|
+
raise BindviewError(f"{p.name} is a matrix without the names of its rows: the model it belongs to has to "
|
|
610
|
+
f"be given with it, to say which row is which residue")
|
|
611
|
+
chains, numbers, names, places, icodes = _tokens(structure)
|
|
612
|
+
if matrix.ndim != 2 or matrix.shape[0] != matrix.shape[1] or matrix.shape[0] != len(numbers):
|
|
613
|
+
raise BindviewError(
|
|
614
|
+
f"{p.name} is a matrix of {' x '.join(str(n) for n in matrix.shape)}, and "
|
|
615
|
+
f"{structure.source or 'the structure'} has {len(numbers)} tokens "
|
|
616
|
+
f"({_per_chain(chains)}): the two are not of the same model, or "
|
|
617
|
+
f"its residues are not tokens the way bindview counts them")
|
|
618
|
+
return cls(matrix, chains, numbers, p.name, names, places if placed else None, icodes, by_number=False)
|
|
619
|
+
|
|
620
|
+
def _rows(self, key: ResidueKey) -> list[int]:
|
|
621
|
+
"""The rows of a residue: by chain and number, and by number alone where the matrix has one chain
|
|
622
|
+
and its model has that chain under other names (a chain that was cut into participants keeps
|
|
623
|
+
its numbers and not its name; :attr:`by_number`). Where the insertion codes of the rows are
|
|
624
|
+
known (:attr:`icodes`), a row is the residue's only with its own."""
|
|
625
|
+
mine = [i for i, n in enumerate(self.numbers)
|
|
626
|
+
if n == key.number and (not self.icodes or self.icodes[i] == key.icode)]
|
|
627
|
+
rows = [i for i in mine if self.chains[i] == key.chain]
|
|
628
|
+
if not rows and self._number_alone:
|
|
629
|
+
rows = mine
|
|
630
|
+
return rows
|
|
631
|
+
|
|
632
|
+
@property
|
|
633
|
+
def _number_alone(self) -> bool:
|
|
634
|
+
return len(set(self.chains)) == 1 if self.by_number is None else self.by_number
|
|
635
|
+
|
|
636
|
+
def between(self, a: ResidueKey, b: ResidueKey, atoms: "tuple[Sequence[int], int] | None" = None
|
|
637
|
+
) -> "float | None":
|
|
638
|
+
"""The PAE of a pair of residues: the smaller of the two directions; ``None`` if either is not in the file.
|
|
639
|
+
|
|
640
|
+
``atoms``: which of the heavy atoms of ``b`` are meant, by their order in the file, and how many it has.
|
|
641
|
+
A residue that is one token for each of its atoms (a ligand) is then read at those, and the smallest of
|
|
642
|
+
their values is the pair's."""
|
|
643
|
+
ra, rb = self._rows(a), self._rows(b)
|
|
644
|
+
if atoms is not None and len(rb) == atoms[1]:
|
|
645
|
+
rb = [rb[i] for i in atoms[0]]
|
|
646
|
+
if not ra or not rb:
|
|
647
|
+
return None
|
|
648
|
+
# The smaller of the two directions, and of a value and a missing one the value.
|
|
649
|
+
block = np.fmin(self.matrix[np.ix_(ra, rb)], self.matrix[np.ix_(rb, ra)].T)
|
|
650
|
+
if np.isnan(block).all():
|
|
651
|
+
return None
|
|
652
|
+
return float(np.nanmin(block))
|
|
653
|
+
|
|
654
|
+
def summary(self, values: Sequence[float]) -> dict[str, float]:
|
|
655
|
+
"""Smallest, median and largest of some contact values, for a figure-level statement."""
|
|
656
|
+
ordered = sorted(values)
|
|
657
|
+
return {"min": round(ordered[0], 1), "median": round(float(np.median(ordered)), 1), "max": round(ordered[-1], 1)}
|
|
658
|
+
|
|
659
|
+
|
|
660
|
+
@dataclass(frozen=True)
|
|
661
|
+
class PaeDraws:
|
|
662
|
+
"""The PAE matrices of several draws of one model of the same complex, read as one.
|
|
663
|
+
|
|
664
|
+
The value of a pair of residues is the **median** of its values in the
|
|
665
|
+
draws (each the smaller of the two directions of that draw's matrix).
|
|
666
|
+
Not the largest: the largest of n draws rises with n whatever the model
|
|
667
|
+
knows, and a figure of five draws would look worse than a figure of one.
|
|
668
|
+
Not the smallest, which falls with n. :meth:`each` gives the values draw
|
|
669
|
+
by draw; they travel with the contact (``pae_draws``). A draw is given
|
|
670
|
+
once: the same matrix twice is refused.
|
|
671
|
+
|
|
672
|
+
A pair is named by the chains of ``reference``: the structure that is
|
|
673
|
+
drawn (the first draw, if none is given). Where the model has copies of a
|
|
674
|
+
chain, every draw's chains are matched to the reference's first
|
|
675
|
+
(:func:`match_chains`); :attr:`renamed` lists the draws in which a chain is
|
|
676
|
+
another's by name.
|
|
677
|
+
"""
|
|
678
|
+
|
|
679
|
+
draws: tuple[Pae, ...]
|
|
680
|
+
reference: "Pae | None" = None
|
|
681
|
+
#: For every draw, which of its chains is which chain of the reference; and how well it fits.
|
|
682
|
+
assignments: tuple[dict[str, str], ...] = field(default=(), init=False)
|
|
683
|
+
fits: tuple[tuple[float, float], ...] = field(default=(), init=False)
|
|
684
|
+
|
|
685
|
+
def __post_init__(self) -> None:
|
|
686
|
+
object.__setattr__(self, "draws", tuple(self.draws))
|
|
687
|
+
if not self.draws:
|
|
688
|
+
raise BindviewError("no PAE matrix was given")
|
|
689
|
+
first = self.draws[0]
|
|
690
|
+
for other in self.draws[1:]:
|
|
691
|
+
if other.chains != first.chains or other.numbers != first.numbers:
|
|
692
|
+
raise BindviewError(f"{other.source or 'a PAE matrix'} and {first.source or 'the first'} do not have "
|
|
693
|
+
f"the same residues in the same order: they are not draws of one model")
|
|
694
|
+
for k, later in enumerate(self.draws):
|
|
695
|
+
for j, earlier in enumerate(self.draws[:k]):
|
|
696
|
+
# (The first row first: two draws of a model differ there, and whole matrices are large.)
|
|
697
|
+
if later.matrix.size and np.array_equal(later.matrix[0], earlier.matrix[0], equal_nan=True) \
|
|
698
|
+
and np.array_equal(later.matrix, earlier.matrix, equal_nan=True):
|
|
699
|
+
raise BindviewError(
|
|
700
|
+
f"draws {j + 1} and {k + 1} ({earlier.source or 'unnamed'} and {later.source or 'unnamed'}) "
|
|
701
|
+
f"are the same matrix: a draw is given once, or the median over the draws is not that of "
|
|
702
|
+
f"as many samples of the model as there are draws")
|
|
703
|
+
reference = self.reference if self.reference is not None else first
|
|
704
|
+
if reference.chains != first.chains or reference.numbers != first.numbers:
|
|
705
|
+
raise BindviewError(f"the structure that is drawn and {first.source or 'the draws'} do not have the same "
|
|
706
|
+
f"residues in the same order: the draws are not of this model")
|
|
707
|
+
matched = [match_chains(reference, d) for d in self.draws]
|
|
708
|
+
object.__setattr__(self, "assignments", tuple(m[0] for m in matched))
|
|
709
|
+
object.__setattr__(self, "fits", tuple((m[1], m[2]) for m in matched))
|
|
710
|
+
|
|
711
|
+
@property
|
|
712
|
+
def chains(self) -> tuple[str, ...]:
|
|
713
|
+
return self.draws[0].chains
|
|
714
|
+
|
|
715
|
+
@property
|
|
716
|
+
def numbers(self) -> tuple[int, ...]:
|
|
717
|
+
return self.draws[0].numbers
|
|
718
|
+
|
|
719
|
+
@property
|
|
720
|
+
def source(self) -> str:
|
|
721
|
+
return f"{len(self.draws)} draws ({self.draws[0].source} to {self.draws[-1].source})" \
|
|
722
|
+
if self.draws[0].source else f"{len(self.draws)} draws"
|
|
723
|
+
|
|
724
|
+
@property
|
|
725
|
+
def copies(self) -> list[list[str]]:
|
|
726
|
+
"""The chains of the model that are copies of one another, group by group: the same residues,
|
|
727
|
+
by number and by name."""
|
|
728
|
+
ref = self.reference if self.reference is not None else self.draws[0]
|
|
729
|
+
return _copies(ref.chains, ref.numbers, ref.resnames)
|
|
730
|
+
|
|
731
|
+
@property
|
|
732
|
+
def renamed(self) -> list[dict[str, Any]]:
|
|
733
|
+
"""The draws whose chains were matched under other names than their own: which draw (counted
|
|
734
|
+
from 0, in the order given), which chain of it stands for which of the reference, and the CA
|
|
735
|
+
RMSD of the draw on the reference with that assignment and with the chains as they are named."""
|
|
736
|
+
return [{"draw": k, "source": d.source, "chains": dict(a), "rmsd": round(fit, 2),
|
|
737
|
+
"rmsd_as_named": round(named, 2)}
|
|
738
|
+
for k, (d, a, (fit, named)) in enumerate(zip(self.draws, self.assignments, self.fits))
|
|
739
|
+
if any(mine != theirs for mine, theirs in a.items())]
|
|
740
|
+
|
|
741
|
+
def each(self, a: ResidueKey, b: ResidueKey, atoms: "tuple[Sequence[int], int] | None" = None
|
|
742
|
+
) -> tuple["float | None", ...]:
|
|
743
|
+
"""The PAE of a pair of residues in every draw, in the order the draws were given: of the
|
|
744
|
+
residues that are ``a`` and ``b`` once the draw's chains are matched to the reference's."""
|
|
745
|
+
return tuple(d.between(ResidueKey(names.get(a.chain, a.chain), a.number, a.icode),
|
|
746
|
+
ResidueKey(names.get(b.chain, b.chain), b.number, b.icode), atoms)
|
|
747
|
+
for d, names in zip(self.draws, self.assignments))
|
|
748
|
+
|
|
749
|
+
def between(self, a: ResidueKey, b: ResidueKey, atoms: "tuple[Sequence[int], int] | None" = None
|
|
750
|
+
) -> "float | None":
|
|
751
|
+
"""The PAE of a pair of residues: the median over the draws; ``None`` if no draw has a value."""
|
|
752
|
+
values = [v for v in self.each(a, b, atoms) if v is not None]
|
|
753
|
+
return float(np.median(values)) if values else None
|
|
754
|
+
|
|
755
|
+
|
|
756
|
+
def _for_model(pae: Pae, structure: "Structure | None") -> Pae:
|
|
757
|
+
"""A matrix that was made without a model, for the model it is used with: whether a residue under
|
|
758
|
+
another chain name is found by its number alone (:attr:`Pae.by_number`) is settled for that model.
|
|
759
|
+
Only where the matrix has one chain and the model has its residues, number for number."""
|
|
760
|
+
if structure is None or pae.by_number is not None:
|
|
761
|
+
return pae
|
|
762
|
+
numbers = _tokens(structure)[1]
|
|
763
|
+
return replace(pae, by_number=len(set(pae.chains)) == 1 and sorted(pae.numbers) == sorted(numbers))
|
|
764
|
+
|
|
765
|
+
|
|
766
|
+
def read_pae(given: Any, structure: "Structure | None" = None) -> "Pae | PaeDraws | None":
|
|
767
|
+
"""A PAE as a caller hands it in.
|
|
768
|
+
|
|
769
|
+
A :class:`Pae` or :class:`PaeDraws`; the path of one file, which is then the matrix of
|
|
770
|
+
``structure``; or several, which are the draws of one model. A draw is a :class:`Pae`, a pair
|
|
771
|
+
``(matrix file, its model: a path or a Structure)``, or the path of a matrix alone, whose model
|
|
772
|
+
is then looked for beside it (:func:`model_beside`). A draw that comes without its model lends
|
|
773
|
+
the names of its rows from ``structure`` and has no coordinates of its own, which is enough
|
|
774
|
+
unless the model has copies of a chain (:func:`match_chains`). One of several is not a set of
|
|
775
|
+
draws: a figure of one draw says nothing of a median. A :class:`Pae` that was made without a
|
|
776
|
+
model is not checked against ``structure``; a residue is found in it by its number alone only
|
|
777
|
+
where it has one chain and ``structure`` has its residues, number for number.
|
|
778
|
+
"""
|
|
779
|
+
from .structure import Structure, read_structure
|
|
780
|
+
|
|
781
|
+
if isinstance(given, Pae):
|
|
782
|
+
return _for_model(given, structure)
|
|
783
|
+
if given is None or isinstance(given, PaeDraws):
|
|
784
|
+
return given
|
|
785
|
+
if isinstance(given, (str, Path)):
|
|
786
|
+
return Pae.read(given, structure)
|
|
787
|
+
if not isinstance(given, Iterable):
|
|
788
|
+
raise BindviewError(f"a PAE is a file, a Pae, or several of them, not {type(given).__name__}")
|
|
789
|
+
draws = []
|
|
790
|
+
for item in given:
|
|
791
|
+
if isinstance(item, Pae):
|
|
792
|
+
draws.append(_for_model(item, structure))
|
|
793
|
+
elif isinstance(item, (str, Path)):
|
|
794
|
+
beside = model_beside(item)
|
|
795
|
+
draws.append(Pae.read(item, read_structure(beside)) if beside is not None
|
|
796
|
+
else Pae.read(item, structure, placed=False))
|
|
797
|
+
elif isinstance(item, Sequence) and len(item) == 2:
|
|
798
|
+
matrix, model = item
|
|
799
|
+
draws.append(Pae.read(matrix, model if isinstance(model, Structure) else read_structure(model)))
|
|
800
|
+
else:
|
|
801
|
+
raise BindviewError(f"a draw is a matrix file, a Pae, or a pair of matrix file and model, not {item!r}")
|
|
802
|
+
if not draws:
|
|
803
|
+
return None
|
|
804
|
+
if len(draws) == 1:
|
|
805
|
+
return draws[0]
|
|
806
|
+
reference = None
|
|
807
|
+
if structure is not None:
|
|
808
|
+
chains, numbers, names, places, icodes = _tokens(structure)
|
|
809
|
+
if chains == draws[0].chains and numbers == draws[0].numbers:
|
|
810
|
+
reference = Pae(np.zeros((0, 0)), chains, numbers, structure.source or "the structure", names, places,
|
|
811
|
+
icodes)
|
|
812
|
+
return PaeDraws(tuple(draws), reference)
|
|
813
|
+
|
|
814
|
+
|
|
815
|
+
# ---------------------------------------------------------------------------
|
|
816
|
+
# ipSAE: a score of an interface as a whole, from the matrix
|
|
817
|
+
# ---------------------------------------------------------------------------
|
|
818
|
+
|
|
819
|
+
#: The PAE, in ångström, below which a pair of residues counts for ipSAE: the value its authors use for
|
|
820
|
+
#: models of AlphaFold 3 and of Boltz, which are the ones whose matrices are read here. (They name 10
|
|
821
|
+
#: or 15 Å; a caller can give another.)
|
|
822
|
+
IPSAE_CUTOFF = 10.0
|
|
823
|
+
|
|
824
|
+
|
|
825
|
+
def _d0(n: np.ndarray) -> np.ndarray:
|
|
826
|
+
return np.maximum(1.0, 1.24 * np.cbrt(n - 15.0) - 1.8)
|
|
827
|
+
|
|
828
|
+
|
|
829
|
+
def ipsae_d0(n: float) -> float:
|
|
830
|
+
"""The length scale of a TM-score over ``n`` residues, in ångström (Yang and Skolnick's d0), as
|
|
831
|
+
ipSAE takes it for one aligned residue: never below 1, which it is for fewer than 27 residues."""
|
|
832
|
+
return float(_d0(np.asarray(float(n))))
|
|
833
|
+
|
|
834
|
+
|
|
835
|
+
@dataclass(frozen=True)
|
|
836
|
+
class OneWay:
|
|
837
|
+
"""ipSAE in one direction: the model aligned on a residue of one side, scored over the other side."""
|
|
838
|
+
|
|
839
|
+
value: float
|
|
840
|
+
#: The aligned residue that gives the value, as chain and number in the matrix; ``None`` where no
|
|
841
|
+
#: pair of residues is below the cut-off, and the value is 0.
|
|
842
|
+
aligned: "tuple[str, int] | None" = None
|
|
843
|
+
#: How many residues of the scored side have a PAE below the cut-off to that residue, and the d0
|
|
844
|
+
#: of that many.
|
|
845
|
+
n0: int = 0
|
|
846
|
+
d0: float = 1.0
|
|
847
|
+
|
|
848
|
+
|
|
849
|
+
@dataclass(frozen=True)
|
|
850
|
+
class Ipsae:
|
|
851
|
+
"""ipSAE between two sides of a predicted complex, in its two directions (:func:`ipsae`).
|
|
852
|
+
|
|
853
|
+
The score has a direction and the two values differ. The reference script also gives the larger
|
|
854
|
+
of the two, and work on designed binders usually quotes the smaller; neither is chosen here.
|
|
855
|
+
"""
|
|
856
|
+
|
|
857
|
+
forward: OneWay # aligned on the first side, scored over the second
|
|
858
|
+
backward: OneWay # aligned on the second, scored over the first
|
|
859
|
+
cutoff: float = IPSAE_CUTOFF
|
|
860
|
+
residues: tuple[int, int] = (0, 0) # of each side: those that entered
|
|
861
|
+
#: Residues of the two sides that did not enter: those without an alpha carbon (a ligand, an ion, a
|
|
862
|
+
#: nucleotide) and, where no structure was given, every residue the model takes atom by atom.
|
|
863
|
+
left_out: int = 0
|
|
864
|
+
same_chain: bool = False # the matrix has both sides in one chain of the model
|
|
865
|
+
#: Of the residues that entered, those the model takes atom by atom (modified residues): each
|
|
866
|
+
#: entered by the row of its alpha carbon.
|
|
867
|
+
by_alpha_carbon: int = 0
|
|
868
|
+
|
|
869
|
+
@property
|
|
870
|
+
def values(self) -> tuple[float, float]:
|
|
871
|
+
return self.forward.value, self.backward.value
|
|
872
|
+
|
|
873
|
+
|
|
874
|
+
def _residue_rows(pae: Pae, residues: "Iterable[ResidueKey]", structure: "Structure | None" = None,
|
|
875
|
+
names: "dict[str, str] | None" = None) -> tuple[list[int], int, int]:
|
|
876
|
+
"""The row of every residue that enters ipSAE: the one that stands for its alpha carbon.
|
|
877
|
+
|
|
878
|
+
A standard residue is one row of the matrix. A residue that the model takes atom by atom (a
|
|
879
|
+
modified residue) is one row for each of its heavy atoms, in the order of the model file, and
|
|
880
|
+
enters by the row at the place of its CA among them; that needs ``structure``, the model with the
|
|
881
|
+
residues as they are named here. What has no alpha carbon does not enter: a ligand, and, where the
|
|
882
|
+
structure says so, a residue of one row without one (an ion, a nucleotide). Rows are found as
|
|
883
|
+
:meth:`Pae._rows` finds them; ``names`` says under which chain a chain goes in this matrix (a draw
|
|
884
|
+
that names the copies of a chain otherwise).
|
|
885
|
+
|
|
886
|
+
Returns the rows, how many of them are of residues taken atom by atom, and how many residues did
|
|
887
|
+
not enter.
|
|
888
|
+
"""
|
|
889
|
+
index: dict[tuple[str, int, str], list[int]] = {}
|
|
890
|
+
for i, (chain, number) in enumerate(zip(pae.chains, pae.numbers)):
|
|
891
|
+
index.setdefault((chain, number, pae.icodes[i] if pae.icodes else ""), []).append(i)
|
|
892
|
+
by_number: dict[tuple[int, str], list[int]] = {}
|
|
893
|
+
if pae._number_alone:
|
|
894
|
+
# A chain that was cut into participants keeps its numbers and not its name.
|
|
895
|
+
by_number = {(number, icode): rows for (_, number, icode), rows in index.items()}
|
|
896
|
+
rows: list[int] = []
|
|
897
|
+
by_alpha_carbon = left_out = 0
|
|
898
|
+
for key in residues:
|
|
899
|
+
chain = names.get(key.chain, key.chain) if names else key.chain
|
|
900
|
+
icode = key.icode if pae.icodes else ""
|
|
901
|
+
found = index.get((chain, key.number, icode)) or by_number.get((key.number, icode)) or []
|
|
902
|
+
if not found:
|
|
903
|
+
continue
|
|
904
|
+
heavy = ([a.name for a in structure.residue_atoms(key) if a.element not in ("H", "D")]
|
|
905
|
+
if structure is not None else [])
|
|
906
|
+
if len(found) == 1:
|
|
907
|
+
if heavy and "CA" not in heavy:
|
|
908
|
+
left_out += 1
|
|
909
|
+
else:
|
|
910
|
+
rows.append(found[0])
|
|
911
|
+
elif "CA" in heavy and len(heavy) == len(found):
|
|
912
|
+
rows.append(found[heavy.index("CA")])
|
|
913
|
+
by_alpha_carbon += 1
|
|
914
|
+
else:
|
|
915
|
+
left_out += 1
|
|
916
|
+
return rows, by_alpha_carbon, left_out
|
|
917
|
+
|
|
918
|
+
|
|
919
|
+
def _one_way(pae: Pae, aligned: list[int], scored: list[int], cutoff: float,
|
|
920
|
+
chain_of: "dict[int, str] | None" = None) -> OneWay:
|
|
921
|
+
"""One direction of ipSAE. ``chain_of`` names the chain of a row where the matrix names none (a chain
|
|
922
|
+
cut into parts is read by number): the chain of the residue that row was asked for."""
|
|
923
|
+
block = pae.matrix[np.ix_(aligned, scored)]
|
|
924
|
+
with np.errstate(invalid="ignore"):
|
|
925
|
+
below = block < cutoff # a value that is missing is below nothing
|
|
926
|
+
n = below.sum(axis=1)
|
|
927
|
+
d0 = _d0(n.astype(float))
|
|
928
|
+
with np.errstate(invalid="ignore"):
|
|
929
|
+
terms = np.where(below, 1.0 / (1.0 + (block / d0[:, None]) ** 2), 0.0)
|
|
930
|
+
values = np.divide(terms.sum(axis=1), n, out=np.zeros(len(aligned)), where=n > 0)
|
|
931
|
+
if not (n > 0).any():
|
|
932
|
+
return OneWay(0.0)
|
|
933
|
+
best = int(np.argmax(values))
|
|
934
|
+
row = aligned[best]
|
|
935
|
+
chain = pae.chains[row] or (chain_of or {}).get(row, "")
|
|
936
|
+
return OneWay(float(values[best]), (chain, pae.numbers[row]), int(n[best]), float(d0[best]))
|
|
937
|
+
|
|
938
|
+
|
|
939
|
+
def _ipsae(pae: Pae, first: "list[ResidueKey]", second: "list[ResidueKey]", cutoff: float,
|
|
940
|
+
structure: "Structure | None", names: "dict[str, str] | None" = None) -> Ipsae:
|
|
941
|
+
if not cutoff > 0.0:
|
|
942
|
+
raise BindviewError(f"the PAE cut-off of ipSAE is a positive number of ångström, not {cutoff!r}")
|
|
943
|
+
a, ca_a, out_a = _residue_rows(pae, first, structure, names)
|
|
944
|
+
b, ca_b, out_b = _residue_rows(pae, second, structure, names)
|
|
945
|
+
if not a or not b:
|
|
946
|
+
raise BindviewError(f"{pae.source or 'the PAE matrix'} has no row for a residue with an alpha carbon on "
|
|
947
|
+
f"{'either side' if not a and not b else 'one side'} of the interface: ipSAE is "
|
|
948
|
+
f"computed between protein chains and cannot be computed here")
|
|
949
|
+
if set(a) & set(b):
|
|
950
|
+
raise BindviewError("the two sides of an ipSAE share residues: it is a score between two sides")
|
|
951
|
+
same = bool({pae.chains[i] for i in a} & {pae.chains[i] for i in b})
|
|
952
|
+
chain_of = {row: key.chain for key in first + second for row in _residue_rows(pae, [key], structure, names)[0]}
|
|
953
|
+
return Ipsae(_one_way(pae, a, b, cutoff, chain_of), _one_way(pae, b, a, cutoff, chain_of), float(cutoff),
|
|
954
|
+
(len(a), len(b)),
|
|
955
|
+
out_a + out_b, same, ca_a + ca_b)
|
|
956
|
+
|
|
957
|
+
|
|
958
|
+
def ipsae(pae: Pae, first: "Iterable[ResidueKey]", second: "Iterable[ResidueKey]",
|
|
959
|
+
cutoff: float = IPSAE_CUTOFF, structure: "Structure | None" = None) -> Ipsae:
|
|
960
|
+
"""ipSAE between the residues ``first`` and the residues ``second``, from one PAE matrix.
|
|
961
|
+
|
|
962
|
+
The score is Dunbrack's (2025, "Rēs ipSAE loquunt: What's wrong with AlphaFold's ipTM score and how
|
|
963
|
+
to fix it"), in the variant his script reports as plain ipSAE. For one direction, ``first`` to
|
|
964
|
+
``second``: the model is aligned on a residue i of the first side, and the residues j of the second
|
|
965
|
+
whose PAE to it is below ``cutoff`` (rows of the matrix are aligned residues, columns scored ones)
|
|
966
|
+
are averaged as ``1 / (1 + (PAE[i][j] / d0)**2)``, with d0 from how many they are
|
|
967
|
+
(:func:`ipsae_d0`). The score is the largest such average over the residues i, and 0 where no pair
|
|
968
|
+
is below the cut-off. It runs from 0 to 1. The other direction is another number.
|
|
969
|
+
|
|
970
|
+
What enters is every pair of residues of the two sides, not the contacts of a figure, and a residue
|
|
971
|
+
enters by its alpha carbon. A standard residue is one row of the matrix. A modified residue is one
|
|
972
|
+
row for each of its atoms and enters by that of its CA, as in the reference script; ``structure``,
|
|
973
|
+
the model the matrix belongs to, is needed to tell which row that is, and without it such a residue
|
|
974
|
+
is left out. What has no alpha carbon (a ligand, an ion, a nucleotide) does not enter. Residues
|
|
975
|
+
that did not enter are counted in ``left_out``. A side may be several chains, which are then scored
|
|
976
|
+
as one; the published score is of two chains of protein or nucleic acid, and only protein is scored
|
|
977
|
+
here.
|
|
978
|
+
"""
|
|
979
|
+
return _ipsae(pae, list(first), list(second), cutoff, structure)
|
|
980
|
+
|
|
981
|
+
|
|
982
|
+
def ipsae_of(pae: "Pae | PaeDraws", first: "Iterable[ResidueKey]", second: "Iterable[ResidueKey]",
|
|
983
|
+
cutoff: float = IPSAE_CUTOFF, structure: "Structure | None" = None) -> tuple[Ipsae, ...]:
|
|
984
|
+
""":func:`ipsae` of one matrix, or of every draw of a model in the order the draws were given:
|
|
985
|
+
the residues are named by the chains of the structure that is drawn, and looked up in each draw
|
|
986
|
+
under the chains that are theirs there (:class:`PaeDraws`)."""
|
|
987
|
+
first, second = list(first), list(second)
|
|
988
|
+
if isinstance(pae, Pae):
|
|
989
|
+
return (_ipsae(pae, first, second, cutoff, structure),)
|
|
990
|
+
return tuple(_ipsae(draw, first, second, cutoff, structure, names)
|
|
991
|
+
for draw, names in zip(pae.draws, pae.assignments))
|