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/interactions.py
ADDED
|
@@ -0,0 +1,418 @@
|
|
|
1
|
+
"""The interaction record: the one data structure callers hand to this library.
|
|
2
|
+
|
|
3
|
+
A caller that already has interactions (from PLIP, from a database, from any
|
|
4
|
+
other detector) passes a list of :class:`Interaction` and never touches
|
|
5
|
+
detection. The record is deliberately small and flat so it maps one-to-one onto
|
|
6
|
+
a table row; ``testdata/*/interactions.tsv`` is exactly this shape.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import csv
|
|
12
|
+
import io
|
|
13
|
+
from dataclasses import dataclass, replace
|
|
14
|
+
from enum import Enum
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
from typing import Any, Iterable, Mapping
|
|
17
|
+
|
|
18
|
+
from .errors import InteractionError
|
|
19
|
+
|
|
20
|
+
__all__ = ["InteractionType", "Interaction", "load_interactions", "parse_interactions", "coerce_interactions",
|
|
21
|
+
"check_confidence_scale"]
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class InteractionType(str, Enum):
|
|
25
|
+
"""The interaction classes the diagram knows how to draw."""
|
|
26
|
+
|
|
27
|
+
HYDROPHOBIC = "hydrophobic"
|
|
28
|
+
HBOND = "hbond"
|
|
29
|
+
SALTBRIDGE = "saltbridge"
|
|
30
|
+
PI_STACKING = "pi_stacking"
|
|
31
|
+
PI_CATION = "pi_cation"
|
|
32
|
+
HALOGEN = "halogen"
|
|
33
|
+
METAL = "metal"
|
|
34
|
+
WATER_BRIDGE = "water_bridge"
|
|
35
|
+
#: A bond, and no contact: the ligand is bound to the residue (:mod:`bindview.covalent`).
|
|
36
|
+
COVALENT = "covalent"
|
|
37
|
+
|
|
38
|
+
def __str__(self) -> str:
|
|
39
|
+
return self.value
|
|
40
|
+
|
|
41
|
+
@property
|
|
42
|
+
def label(self) -> str:
|
|
43
|
+
"""The kind in words, as the key of a figure has it."""
|
|
44
|
+
return _LABELS[self]
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
_LABELS = {
|
|
48
|
+
InteractionType.HYDROPHOBIC: "Hydrophobic contact",
|
|
49
|
+
InteractionType.HBOND: "Hydrogen bond",
|
|
50
|
+
InteractionType.SALTBRIDGE: "Salt bridge",
|
|
51
|
+
InteractionType.PI_STACKING: "π–π stacking",
|
|
52
|
+
InteractionType.PI_CATION: "π–cation",
|
|
53
|
+
InteractionType.HALOGEN: "Halogen bond",
|
|
54
|
+
InteractionType.METAL: "Metal coordination",
|
|
55
|
+
InteractionType.WATER_BRIDGE: "Water bridge",
|
|
56
|
+
InteractionType.COVALENT: "Covalent bond",
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
# Spellings seen in the wild, normalised to the canonical value.
|
|
60
|
+
_ALIASES = {
|
|
61
|
+
"hydrophobic": "hydrophobic", "hydrophobic_contact": "hydrophobic", "hydroph": "hydrophobic",
|
|
62
|
+
"hbond": "hbond", "h_bond": "hbond", "hydrogen_bond": "hbond", "hydrogenbond": "hbond",
|
|
63
|
+
"saltbridge": "saltbridge", "salt_bridge": "saltbridge", "ionic": "saltbridge",
|
|
64
|
+
"pi_stacking": "pi_stacking", "pistacking": "pi_stacking", "pi_stack": "pi_stacking", "pistack": "pi_stacking",
|
|
65
|
+
"pi_pi": "pi_stacking",
|
|
66
|
+
"pi_cation": "pi_cation", "pication": "pi_cation", "cation_pi": "pi_cation",
|
|
67
|
+
"halogen": "halogen", "halogen_bond": "halogen", "halogenbond": "halogen", "xbond": "halogen",
|
|
68
|
+
"metal": "metal", "metal_complex": "metal", "metal_coordination": "metal",
|
|
69
|
+
"water_bridge": "water_bridge", "waterbridge": "water_bridge", "water": "water_bridge",
|
|
70
|
+
"covalent": "covalent", "covalent_bond": "covalent", "covale": "covalent",
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _as_type(value: Any) -> InteractionType:
|
|
75
|
+
if isinstance(value, InteractionType):
|
|
76
|
+
return value
|
|
77
|
+
key = str(value).strip().lower().replace("-", "_").replace(" ", "_")
|
|
78
|
+
canon = _ALIASES.get(key)
|
|
79
|
+
if canon is None:
|
|
80
|
+
raise InteractionError(
|
|
81
|
+
f"unknown interaction type {value!r}; expected one of {', '.join(t.value for t in InteractionType)}")
|
|
82
|
+
return InteractionType(canon)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
#: The one word a table writes for a value that is not given that is also a name: of an atom (a heme has
|
|
86
|
+
#: a nitrogen called so), of a residue (sodium) and of a chain.
|
|
87
|
+
NOT_GIVEN_OR_A_NAME = "NA"
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _opt_str(value: Any) -> str | None:
|
|
91
|
+
if value is None:
|
|
92
|
+
return None
|
|
93
|
+
s = str(value).strip()
|
|
94
|
+
return s if s and s not in ("?", ".", "None", "none", "NA", "nan", "NaN") else None
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _opt_name(value: Any) -> str | None:
|
|
98
|
+
"""The name of an atom, a residue or a chain, or None where none is given. ``NA`` is kept: a heme has a
|
|
99
|
+
nitrogen of that name, sodium is called so, and a large structure has a chain of that name. A table can also
|
|
100
|
+
write it for a name that is not given; whether the molecule has an atom, or the structure a chain, called so
|
|
101
|
+
says which it is (:func:`bindview.resolve.resolve_interactions`)."""
|
|
102
|
+
s = None if value is None else str(value).strip()
|
|
103
|
+
return s if s == NOT_GIVEN_OR_A_NAME else _opt_str(value)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _opt_float(value: Any, field_name: str) -> float | None:
|
|
107
|
+
s = _opt_str(value)
|
|
108
|
+
if s is None:
|
|
109
|
+
return None
|
|
110
|
+
try:
|
|
111
|
+
return float(s)
|
|
112
|
+
except ValueError:
|
|
113
|
+
raise InteractionError(f"{field_name} is not a number: {value!r}") from None
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _opt_bool(value: Any, field_name: str) -> bool | None:
|
|
117
|
+
if isinstance(value, bool):
|
|
118
|
+
return value
|
|
119
|
+
s = _opt_str(value)
|
|
120
|
+
if s is None:
|
|
121
|
+
return None
|
|
122
|
+
low = s.lower()
|
|
123
|
+
if low in ("true", "t", "1", "yes", "y"):
|
|
124
|
+
return True
|
|
125
|
+
if low in ("false", "f", "0", "no", "n"):
|
|
126
|
+
return False
|
|
127
|
+
raise InteractionError(f"{field_name} is not a boolean: {value!r}")
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _names(value: Any) -> tuple[str, ...]:
|
|
131
|
+
"""Several names: a sequence of them, or text with commas or semicolons between them. What stands for a
|
|
132
|
+
value that is not given in any other column does so here: an empty cell, ``?``, ``.``, the ``nan`` of a
|
|
133
|
+
data frame. ``NA`` alone is kept, as it is for one name (:func:`_opt_name`)."""
|
|
134
|
+
if isinstance(value, (str, float)) or value is None:
|
|
135
|
+
text = _opt_name(value)
|
|
136
|
+
return tuple(p for p in (part.strip() for part in text.replace(";", ",").split(",")) if p) if text else ()
|
|
137
|
+
return tuple(str(v) for v in value)
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def _floats(value: Any, field_name: str) -> tuple[float, ...]:
|
|
141
|
+
"""Several numbers: a sequence, or text with commas, semicolons or blanks between them."""
|
|
142
|
+
if value is None:
|
|
143
|
+
return ()
|
|
144
|
+
parts = value.replace(";", ",").replace(" ", ",").split(",") if isinstance(value, str) else list(value)
|
|
145
|
+
try:
|
|
146
|
+
return tuple(float(v) for v in parts if str(v).strip())
|
|
147
|
+
except (TypeError, ValueError):
|
|
148
|
+
raise InteractionError(f"{field_name} are not numbers: {value!r}") from None
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
@dataclass(frozen=True)
|
|
152
|
+
class Interaction:
|
|
153
|
+
"""One protein-ligand interaction.
|
|
154
|
+
|
|
155
|
+
In every field an empty value, ``?``, ``.``, ``None`` and ``nan`` say that
|
|
156
|
+
the value is not given, and so does ``NA``, which is what R writes. Where
|
|
157
|
+
``NA`` can also be a name (of an atom, of a chain) it is that name if the
|
|
158
|
+
structure has an atom or a chain called so, and a value that is not given
|
|
159
|
+
otherwise.
|
|
160
|
+
|
|
161
|
+
Parameters
|
|
162
|
+
----------
|
|
163
|
+
type:
|
|
164
|
+
One of :class:`InteractionType` (a plain string such as ``"hbond"`` is accepted).
|
|
165
|
+
residue_number, residue_name, chain:
|
|
166
|
+
The protein residue. ``chain`` may be empty when the structure has a
|
|
167
|
+
single chain carrying that residue number.
|
|
168
|
+
protein_atom, ligand_atom:
|
|
169
|
+
Atom names as they appear in the structure file. Leave ``None`` for
|
|
170
|
+
interactions made by a *group* -- an aromatic ring (pi-stacking,
|
|
171
|
+
pi-cation), a charged group (salt bridge) -- or when the detector did
|
|
172
|
+
not report one (PLIP's metal rows). The group is then resolved from the
|
|
173
|
+
structure geometry using ``distance``; see :mod:`bindview.resolve`.
|
|
174
|
+
ligand_atoms, protein_atoms:
|
|
175
|
+
Optional explicit group membership (ring atoms, the atoms of a charged
|
|
176
|
+
group). When given, nothing is inferred for that side.
|
|
177
|
+
distance:
|
|
178
|
+
In angstrom. Atom-atom for hydrophobic, H-bond, halogen and metal
|
|
179
|
+
contacts; centre-centre for ring and charge interactions.
|
|
180
|
+
angle:
|
|
181
|
+
In degrees, as reported by the detector (donor angle, ring-plane angle, ...).
|
|
182
|
+
ligand_is_donor:
|
|
183
|
+
Direction of an H-bond or water bridge: ``True`` when the ligand atom
|
|
184
|
+
donates. ``None`` when not applicable or unknown.
|
|
185
|
+
beyond_contact_set:
|
|
186
|
+
``True`` when the residue lies outside the caller's contact definition
|
|
187
|
+
(e.g. a pi interaction measured centroid-to-centroid to a residue with
|
|
188
|
+
no heavy atom within the pocket cut-off). Such contacts are drawn in a
|
|
189
|
+
visibly different, muted way.
|
|
190
|
+
water:
|
|
191
|
+
For water bridges, ``"chain:number"`` of the bridging water, if known.
|
|
192
|
+
occupancy:
|
|
193
|
+
The share of an *ensemble* in which this contact is made, from 0 to 1:
|
|
194
|
+
the fraction of frames of a trajectory, of the ligands of a series, of
|
|
195
|
+
the models of an NMR bundle, of the poses of a docking run. The number
|
|
196
|
+
does not say which; the caller names the ensemble (``ensemble=`` on
|
|
197
|
+
the diagram) and the legend prints that name. ``None`` for a contact
|
|
198
|
+
observed in one structure. bindview reads no trajectories: occupancy
|
|
199
|
+
arrives as data, like every other field here.
|
|
200
|
+
confidence:
|
|
201
|
+
How much the model is to be believed about *this contact*, on the scale
|
|
202
|
+
of pLDDT (0 to 100, higher is better). ``None`` leaves it to be derived
|
|
203
|
+
where the model allows: the lower of the ligand atom's pLDDT and the
|
|
204
|
+
residue's (see :mod:`bindview.confidence`). A value given here is used
|
|
205
|
+
as it stands, so a caller can let a contact carry a number of its own.
|
|
206
|
+
predicted:
|
|
207
|
+
``True`` for a contact that was neither observed nor detected in the
|
|
208
|
+
structure but inferred: a water bridge through a *predicted*
|
|
209
|
+
solvent site. Such a record is drawn in a visibly different way and
|
|
210
|
+
labelled as predicted wherever it appears.
|
|
211
|
+
"""
|
|
212
|
+
|
|
213
|
+
type: InteractionType
|
|
214
|
+
residue_number: int
|
|
215
|
+
residue_name: str
|
|
216
|
+
chain: str = ""
|
|
217
|
+
protein_atom: str | None = None
|
|
218
|
+
ligand_atom: str | None = None
|
|
219
|
+
distance: float | None = None
|
|
220
|
+
angle: float | None = None
|
|
221
|
+
ligand_is_donor: bool | None = None
|
|
222
|
+
beyond_contact_set: bool = False
|
|
223
|
+
ligand_atoms: tuple[str, ...] = ()
|
|
224
|
+
protein_atoms: tuple[str, ...] = ()
|
|
225
|
+
insertion_code: str = ""
|
|
226
|
+
water: str | None = None
|
|
227
|
+
occupancy: float | None = None
|
|
228
|
+
confidence: float | None = None
|
|
229
|
+
predicted: bool = False
|
|
230
|
+
#: Predicted aligned error between the two residues of the contact, in ångström: what a
|
|
231
|
+
#: structure-prediction model says about how well it places one relative to the other, which
|
|
232
|
+
#: is what the reliability of a contact across an interface means. Carried into the graph, and
|
|
233
|
+
#: drawn with the contact: as a glow behind its line or as a number on it (``pae_colors``).
|
|
234
|
+
pae: float | None = None
|
|
235
|
+
#: Where ``pae`` is the median over several draws of a model: the value of each draw, in the
|
|
236
|
+
#: order the draws were given. Empty for a contact with one value and no draws behind it.
|
|
237
|
+
pae_draws: tuple[float, ...] = ()
|
|
238
|
+
|
|
239
|
+
def __post_init__(self) -> None:
|
|
240
|
+
object.__setattr__(self, "type", _as_type(self.type))
|
|
241
|
+
try:
|
|
242
|
+
object.__setattr__(self, "residue_number", int(self.residue_number))
|
|
243
|
+
except (TypeError, ValueError):
|
|
244
|
+
raise InteractionError(f"residue_number is not an integer: {self.residue_number!r}") from None
|
|
245
|
+
name = _opt_name(self.residue_name) # (it has to be given: sodium's is NA)
|
|
246
|
+
if name is None:
|
|
247
|
+
raise InteractionError("residue_name is required")
|
|
248
|
+
object.__setattr__(self, "residue_name", name.upper())
|
|
249
|
+
object.__setattr__(self, "chain", _opt_name(self.chain) or "")
|
|
250
|
+
object.__setattr__(self, "protein_atom", _opt_name(self.protein_atom))
|
|
251
|
+
object.__setattr__(self, "ligand_atom", _opt_name(self.ligand_atom))
|
|
252
|
+
object.__setattr__(self, "distance", _opt_float(self.distance, "distance"))
|
|
253
|
+
object.__setattr__(self, "angle", _opt_float(self.angle, "angle"))
|
|
254
|
+
object.__setattr__(self, "ligand_is_donor", _opt_bool(self.ligand_is_donor, "ligand_is_donor"))
|
|
255
|
+
object.__setattr__(self, "beyond_contact_set", bool(_opt_bool(self.beyond_contact_set, "beyond_contact_set")))
|
|
256
|
+
object.__setattr__(self, "ligand_atoms", _names(self.ligand_atoms))
|
|
257
|
+
object.__setattr__(self, "protein_atoms", _names(self.protein_atoms))
|
|
258
|
+
object.__setattr__(self, "insertion_code", _opt_str(self.insertion_code) or "")
|
|
259
|
+
object.__setattr__(self, "water", _opt_str(self.water))
|
|
260
|
+
if self.distance is not None and self.distance < 0:
|
|
261
|
+
raise InteractionError(f"distance must not be negative: {self.distance}")
|
|
262
|
+
object.__setattr__(self, "predicted", bool(_opt_bool(self.predicted, "predicted")))
|
|
263
|
+
object.__setattr__(self, "occupancy", _opt_float(self.occupancy, "occupancy"))
|
|
264
|
+
object.__setattr__(self, "confidence", _opt_float(self.confidence, "confidence"))
|
|
265
|
+
object.__setattr__(self, "pae", _opt_float(self.pae, "pae"))
|
|
266
|
+
if self.pae is not None and self.pae < 0:
|
|
267
|
+
raise InteractionError(f"pae is an error in ångström and cannot be negative: {self.pae:g}")
|
|
268
|
+
object.__setattr__(self, "pae_draws", _floats(self.pae_draws, "pae_draws"))
|
|
269
|
+
if any(v < 0 for v in self.pae_draws):
|
|
270
|
+
raise InteractionError("pae_draws are errors in ångström and cannot be negative")
|
|
271
|
+
if self.occupancy is not None and not 0.0 <= self.occupancy <= 1.0:
|
|
272
|
+
raise InteractionError(f"occupancy is a fraction between 0 and 1, not {self.occupancy:g} "
|
|
273
|
+
"(divide a percentage by 100)")
|
|
274
|
+
if self.confidence is not None and not 0.0 <= self.confidence <= 100.0:
|
|
275
|
+
raise InteractionError(f"confidence is on the pLDDT scale, 0 to 100, not {self.confidence:g}")
|
|
276
|
+
|
|
277
|
+
# -- construction ------------------------------------------------------
|
|
278
|
+
@classmethod
|
|
279
|
+
def from_mapping(cls, row: Mapping[str, Any]) -> "Interaction":
|
|
280
|
+
"""Build a record from a dict-like row (a TSV line, a database row)."""
|
|
281
|
+
def pick(*keys: str) -> Any:
|
|
282
|
+
for k in keys:
|
|
283
|
+
if k in row and row[k] is not None:
|
|
284
|
+
return row[k]
|
|
285
|
+
return None
|
|
286
|
+
|
|
287
|
+
typ = pick("type", "interaction_type")
|
|
288
|
+
if typ is None:
|
|
289
|
+
raise InteractionError("row has no 'type' / 'interaction_type'")
|
|
290
|
+
number = pick("residue_number", "resnr", "resnum", "residue_id")
|
|
291
|
+
if number is None or str(number).strip() == "":
|
|
292
|
+
raise InteractionError("row has no 'residue_number'")
|
|
293
|
+
return cls(
|
|
294
|
+
type=typ,
|
|
295
|
+
residue_number=number,
|
|
296
|
+
residue_name=pick("residue_name", "restype", "resname") or "",
|
|
297
|
+
chain=pick("chain", "reschain", "chain_id") or "",
|
|
298
|
+
protein_atom=pick("protein_atom", "protein_atom_name"),
|
|
299
|
+
ligand_atom=pick("ligand_atom", "ligand_atom_name"),
|
|
300
|
+
distance=pick("distance", "dist"),
|
|
301
|
+
angle=pick("angle"),
|
|
302
|
+
ligand_is_donor=pick("ligand_is_donor"),
|
|
303
|
+
beyond_contact_set=pick("beyond_contact_set") or False,
|
|
304
|
+
ligand_atoms=pick("ligand_atoms") or (),
|
|
305
|
+
protein_atoms=pick("protein_atoms") or (),
|
|
306
|
+
insertion_code=pick("insertion_code", "icode") or "",
|
|
307
|
+
water=pick("water"),
|
|
308
|
+
occupancy=pick("occupancy", "frequency", "persistence"),
|
|
309
|
+
confidence=pick("confidence", "contact_confidence"),
|
|
310
|
+
predicted=pick("predicted") or False,
|
|
311
|
+
pae=pick("pae", "predicted_aligned_error"),
|
|
312
|
+
pae_draws=pick("pae_draws") or (),
|
|
313
|
+
)
|
|
314
|
+
|
|
315
|
+
def with_(self, **changes: Any) -> "Interaction":
|
|
316
|
+
"""The same record with some of its fields changed."""
|
|
317
|
+
return replace(self, **changes)
|
|
318
|
+
|
|
319
|
+
# -- convenience -------------------------------------------------------
|
|
320
|
+
@property
|
|
321
|
+
def residue_label(self) -> str:
|
|
322
|
+
"""``Gln712`` -- three-letter name in title case plus number."""
|
|
323
|
+
return f"{self.residue_name.capitalize()}{self.residue_number}{self.insertion_code}"
|
|
324
|
+
|
|
325
|
+
@property
|
|
326
|
+
def residue_id(self) -> tuple[str, int, str]:
|
|
327
|
+
"""``(chain, number, insertion code)`` of the residue."""
|
|
328
|
+
return (self.chain, self.residue_number, self.insertion_code)
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
def check_confidence_scale(values: Iterable["float | None"], what: str = "The contacts") -> None:
|
|
332
|
+
"""Refuse a set of contact confidences that cannot be on the 0-100 scale they are documented on.
|
|
333
|
+
|
|
334
|
+
A record's ``confidence`` is on the scale of pLDDT, 0 to 100, and is used as it stands. One
|
|
335
|
+
value says nothing about its scale; a whole set none of which exceeds 1 does: on 0-100 a model
|
|
336
|
+
has no value below 1, so these are on 0-1 (what Boltz writes into ``plddt_*.npz``), and drawn
|
|
337
|
+
as they stand every contact would look unreliable, in a figure that still looks like a result.
|
|
338
|
+
Nothing is converted: the scale is the caller's to put right.
|
|
339
|
+
"""
|
|
340
|
+
vals = [float(v) for v in values if v is not None]
|
|
341
|
+
if not vals or max(vals) > 1.0 or max(vals) <= 0.0:
|
|
342
|
+
return
|
|
343
|
+
lo, hi = min(vals), max(vals)
|
|
344
|
+
raise InteractionError(
|
|
345
|
+
f"{what} carry a confidence of {lo:.3g}{'' if lo == hi else f' to {hi:.3g}'}: nothing above 1. "
|
|
346
|
+
f"'confidence' is on the scale of pLDDT, 0 to 100, on which a model has no value below 1, so these "
|
|
347
|
+
f"look like the 0-1 scale that Boltz writes into plddt_*.npz. The scale is not guessed and nothing is "
|
|
348
|
+
f"multiplied for you: give them times 100, or leave them out and let the model file speak (bindview reads "
|
|
349
|
+
f"pLDDT from a file that declares it, and Boltz's does, on 0-100)")
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
def coerce_interactions(items: Iterable[Interaction | Mapping[str, Any]]) -> list[Interaction]:
|
|
353
|
+
"""Accept records or dict-like rows and return records."""
|
|
354
|
+
out: list[Interaction] = []
|
|
355
|
+
for n, item in enumerate(items):
|
|
356
|
+
if isinstance(item, Interaction):
|
|
357
|
+
out.append(item)
|
|
358
|
+
elif isinstance(item, Mapping):
|
|
359
|
+
try:
|
|
360
|
+
out.append(Interaction.from_mapping(item))
|
|
361
|
+
except InteractionError as exc:
|
|
362
|
+
raise InteractionError(f"interaction #{n + 1}: {exc}") from None
|
|
363
|
+
else:
|
|
364
|
+
raise InteractionError(f"interaction #{n + 1}: expected Interaction or mapping, got {type(item).__name__}")
|
|
365
|
+
return out
|
|
366
|
+
|
|
367
|
+
|
|
368
|
+
#: What may stand between two fields of a table. Where none is named, it is the one the header row has most of,
|
|
369
|
+
#: and the earlier of two that are as frequent. A spreadsheet program writes semicolons where its list separator is one.
|
|
370
|
+
_DELIMITERS = ("\t", ",", ";")
|
|
371
|
+
|
|
372
|
+
|
|
373
|
+
def parse_interactions(text: str, delimiter: str | None = None) -> list[Interaction]:
|
|
374
|
+
"""Parse delimited text with a header row.
|
|
375
|
+
|
|
376
|
+
``delimiter`` is the character between two fields. Left out, it is found in the header row: a tab, a comma
|
|
377
|
+
or a semicolon. Numbers are written with a decimal point.
|
|
378
|
+
|
|
379
|
+
A file with a header and no rows is a valid, *empty* result: it means the
|
|
380
|
+
complex was analysed and nothing was found.
|
|
381
|
+
"""
|
|
382
|
+
text = text.removeprefix("\ufeff") # the byte-order mark a spreadsheet program puts before the header
|
|
383
|
+
if not text.strip():
|
|
384
|
+
raise InteractionError("interaction table is empty (no header row)")
|
|
385
|
+
if delimiter is None:
|
|
386
|
+
head = text.splitlines()[0]
|
|
387
|
+
delimiter = max(_DELIMITERS, key=head.count) # max keeps the first of equals
|
|
388
|
+
elif len(delimiter) != 1:
|
|
389
|
+
raise InteractionError(f"delimiter is one character, not {delimiter!r}")
|
|
390
|
+
reader = csv.DictReader(io.StringIO(text), delimiter=delimiter)
|
|
391
|
+
if not reader.fieldnames or not ({"type", "interaction_type"} & {f.strip() for f in reader.fieldnames}):
|
|
392
|
+
raise InteractionError("interaction table needs a 'type' or 'interaction_type' column")
|
|
393
|
+
out: list[Interaction] = []
|
|
394
|
+
for n, row in enumerate(reader, start=2):
|
|
395
|
+
clean = {(k or "").strip(): v for k, v in row.items()}
|
|
396
|
+
if not any((v or "").strip() for v in clean.values()):
|
|
397
|
+
continue
|
|
398
|
+
try:
|
|
399
|
+
out.append(Interaction.from_mapping(clean))
|
|
400
|
+
except InteractionError as exc:
|
|
401
|
+
raise InteractionError(f"line {n}: {exc}") from None
|
|
402
|
+
return out
|
|
403
|
+
|
|
404
|
+
|
|
405
|
+
def load_interactions(path: str | Path) -> list[Interaction]:
|
|
406
|
+
"""Read an interaction table (``.tsv`` / ``.csv``) from disk."""
|
|
407
|
+
p = Path(path)
|
|
408
|
+
try:
|
|
409
|
+
text = p.read_text(encoding="utf-8-sig")
|
|
410
|
+
except UnicodeDecodeError as exc:
|
|
411
|
+
raise InteractionError(f"cannot read {p}: it is not UTF-8 text (it has the byte "
|
|
412
|
+
f"0x{exc.object[exc.start]:02x}); save it as UTF-8") from exc
|
|
413
|
+
except OSError as exc:
|
|
414
|
+
raise InteractionError(f"cannot read {p}: {exc}") from exc
|
|
415
|
+
try:
|
|
416
|
+
return parse_interactions(text)
|
|
417
|
+
except InteractionError as exc:
|
|
418
|
+
raise InteractionError(f"{p}: {exc}") from None
|