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/fingerprint.py
ADDED
|
@@ -0,0 +1,469 @@
|
|
|
1
|
+
"""Interaction fingerprints: which residue makes which kind of contact.
|
|
2
|
+
|
|
3
|
+
A fingerprint is the per-(residue, interaction type) vector of one complex. It
|
|
4
|
+
is what a comparison of ligands is computed from, it is the form in which the
|
|
5
|
+
content of a figure becomes a number, and it is useful on its own to anyone who
|
|
6
|
+
wants a table instead of a drawing.
|
|
7
|
+
|
|
8
|
+
Three things are fixed so that fingerprints from different runs, machines and
|
|
9
|
+
ligands can be compared:
|
|
10
|
+
|
|
11
|
+
* a **bit** is ``(chain, residue number, insertion code, residue name, type)``
|
|
12
|
+
-- the residue numbering of the structure file, the same one the interaction
|
|
13
|
+
records use;
|
|
14
|
+
* bits are **ordered** by chain, residue number, insertion code and then by
|
|
15
|
+
interaction type in the order of :class:`~bindview.interactions.InteractionType`
|
|
16
|
+
-- never by the order records happened to arrive in;
|
|
17
|
+
* both the long form (one row per set bit, lossless) and the wide form (one row
|
|
18
|
+
per ligand, one column per bit) **round-trip through CSV**.
|
|
19
|
+
|
|
20
|
+
A bit carries how many records set it, the shortest reported distance, which
|
|
21
|
+
ligand atoms make the contact and, for predicted models, the confidence of its
|
|
22
|
+
best-supported record (see :mod:`bindview.confidence`): presence and evidence are
|
|
23
|
+
kept as separate numbers and never multiplied into one score.
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
from __future__ import annotations
|
|
27
|
+
|
|
28
|
+
import csv
|
|
29
|
+
import io
|
|
30
|
+
from dataclasses import dataclass, field
|
|
31
|
+
from pathlib import Path
|
|
32
|
+
from typing import TYPE_CHECKING, Any, Iterable, Iterator, Mapping, Sequence
|
|
33
|
+
|
|
34
|
+
from .confidence import look_of
|
|
35
|
+
from .errors import InteractionError
|
|
36
|
+
from .interactions import Interaction, InteractionType
|
|
37
|
+
from .residues import format_residue_label
|
|
38
|
+
|
|
39
|
+
if TYPE_CHECKING: # pragma: no cover
|
|
40
|
+
from .diagram import Diagram
|
|
41
|
+
|
|
42
|
+
__all__ = ["Bit", "BitValue", "Fingerprint", "FingerprintTable", "ConsensusRow", "TYPE_ORDER", "LONG_COLUMNS"]
|
|
43
|
+
|
|
44
|
+
#: Interaction types in column order.
|
|
45
|
+
TYPE_ORDER: tuple[InteractionType, ...] = tuple(InteractionType)
|
|
46
|
+
_TYPE_RANK = {t: i for i, t in enumerate(TYPE_ORDER)}
|
|
47
|
+
|
|
48
|
+
#: Columns of the long CSV form, in order.
|
|
49
|
+
LONG_COLUMNS = ("ligand", "chain", "residue_number", "insertion_code", "residue_name", "interaction_type",
|
|
50
|
+
"count", "min_distance", "plddt", "occupancy", "ligand_atoms")
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
@dataclass(frozen=True)
|
|
54
|
+
class Bit:
|
|
55
|
+
"""One fingerprint column: a residue and an interaction type."""
|
|
56
|
+
|
|
57
|
+
chain: str
|
|
58
|
+
number: int
|
|
59
|
+
icode: str
|
|
60
|
+
resname: str
|
|
61
|
+
type: InteractionType
|
|
62
|
+
|
|
63
|
+
@property
|
|
64
|
+
def residue(self) -> tuple[str, int, str]:
|
|
65
|
+
return (self.chain, self.number, self.icode)
|
|
66
|
+
|
|
67
|
+
@property
|
|
68
|
+
def sort_key(self) -> tuple[str, int, str, int]:
|
|
69
|
+
return (self.chain, self.number, self.icode, _TYPE_RANK[self.type])
|
|
70
|
+
|
|
71
|
+
def __lt__(self, other: "Bit") -> bool:
|
|
72
|
+
return self.sort_key < other.sort_key
|
|
73
|
+
|
|
74
|
+
@property
|
|
75
|
+
def column(self) -> str:
|
|
76
|
+
"""The column name of this bit: ``A:GLN570:hbond``. Where the name of the residue is not letters alone
|
|
77
|
+
(``CA2``, ``H2U``, ``5MC``), or its insertion code is not, the name, the number and the code stand
|
|
78
|
+
apart, so that one cannot be read into the other: ``A:CA2:7::metal``."""
|
|
79
|
+
name = self.resname.upper()
|
|
80
|
+
if _letters(name) and (not self.icode or _letters(self.icode)):
|
|
81
|
+
return f"{self.chain}:{name}{self.number}{self.icode}:{self.type.value}"
|
|
82
|
+
return f"{self.chain}:{name}:{self.number}:{self.icode}:{self.type.value}"
|
|
83
|
+
|
|
84
|
+
@property
|
|
85
|
+
def residue_label(self) -> str:
|
|
86
|
+
return format_residue_label(self.resname, self.number, self.icode, None)
|
|
87
|
+
|
|
88
|
+
@classmethod
|
|
89
|
+
def from_column(cls, text: str) -> "Bit":
|
|
90
|
+
"""The bit that a column name stands for (:attr:`column`, in either of its two forms)."""
|
|
91
|
+
parts = text.split(":")
|
|
92
|
+
try:
|
|
93
|
+
if len(parts) == 5:
|
|
94
|
+
chain, resname, number, icode, kind = parts
|
|
95
|
+
return cls(chain, int(number), icode, resname, InteractionType(kind))
|
|
96
|
+
chain, residue, kind = parts
|
|
97
|
+
split = next(i for i, ch in enumerate(residue) if ch.isdigit() or ch == "-")
|
|
98
|
+
digits = residue[split:].rstrip("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz")
|
|
99
|
+
return cls(chain, int(digits), residue[split + len(digits):], residue[:split], InteractionType(kind))
|
|
100
|
+
except (ValueError, StopIteration):
|
|
101
|
+
raise InteractionError(f"cannot read fingerprint column {text!r}; expected 'A:GLN570:hbond', or "
|
|
102
|
+
"'A:CA2:7::metal' for a residue whose name is not letters alone") from None
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
@dataclass(frozen=True)
|
|
106
|
+
class BitValue:
|
|
107
|
+
"""What is known about one set bit."""
|
|
108
|
+
|
|
109
|
+
count: int = 1 # interaction records behind the bit
|
|
110
|
+
distance: float | None = None # shortest reported distance, angstrom
|
|
111
|
+
plddt: float | None = None # confidence of the best-supported record
|
|
112
|
+
ligand_atoms: tuple[str, ...] = () # names of the ligand atoms that make the contact, sorted
|
|
113
|
+
occupancy: float | None = None # share of an ensemble in which the contact is made
|
|
114
|
+
|
|
115
|
+
def merged(self, other: "BitValue") -> "BitValue":
|
|
116
|
+
ds = [d for d in (self.distance, other.distance) if d is not None]
|
|
117
|
+
ps = [p for p in (self.plddt, other.plddt) if p is not None]
|
|
118
|
+
occ = [o for o in (self.occupancy, other.occupancy) if o is not None]
|
|
119
|
+
return BitValue(self.count + other.count, min(ds) if ds else None, max(ps) if ps else None,
|
|
120
|
+
tuple(sorted(set(self.ligand_atoms) | set(other.ligand_atoms))), max(occ) if occ else None)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _letters(text: str) -> bool:
|
|
124
|
+
"""Is it letters of the alphabet and nothing else?"""
|
|
125
|
+
return text.isascii() and text.isalpha()
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _num(value: float | None, digits: int) -> str:
|
|
129
|
+
return "" if value is None else f"{value:.{digits}f}"
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _opt_float(text: str) -> float | None:
|
|
133
|
+
text = text.strip()
|
|
134
|
+
return float(text) if text else None
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
@dataclass
|
|
138
|
+
class Fingerprint:
|
|
139
|
+
"""The set bits of one ligand, with what is known about each."""
|
|
140
|
+
|
|
141
|
+
name: str
|
|
142
|
+
bits: dict[Bit, BitValue] = field(default_factory=dict)
|
|
143
|
+
|
|
144
|
+
# -- construction ------------------------------------------------------
|
|
145
|
+
@classmethod
|
|
146
|
+
def from_diagram(cls, diagram: "Diagram", name: str | None = None) -> "Fingerprint":
|
|
147
|
+
"""The fingerprint of a built :class:`~bindview.diagram.Diagram`.
|
|
148
|
+
|
|
149
|
+
Every supplied record counts, including one that could not be attached
|
|
150
|
+
to a ligand atom (it is still a reported contact with that residue).
|
|
151
|
+
"""
|
|
152
|
+
conf = diagram.confidence
|
|
153
|
+
bits: dict[Bit, BitValue] = {}
|
|
154
|
+
for r in diagram.interactions:
|
|
155
|
+
rec = r.record
|
|
156
|
+
chain = r.residue.chain if r.residue is not None else rec.chain
|
|
157
|
+
bit = Bit(chain, rec.residue_number, rec.insertion_code, rec.residue_name.upper(), rec.type)
|
|
158
|
+
atoms = tuple(sorted(diagram.ligand.names[i] for i in r.ligand.atoms)) if r.ligand is not None else ()
|
|
159
|
+
plddt = rec.confidence # a record may carry its own number
|
|
160
|
+
if plddt is None and conf is not None and atoms:
|
|
161
|
+
plddt = conf.contact(r.residue if r.residue is not None else rec.residue_id, atoms)
|
|
162
|
+
# Stored at the precision the CSV carries, so that a fingerprint equals its round trip.
|
|
163
|
+
one = BitValue(1, None if rec.distance is None else round(rec.distance, 2),
|
|
164
|
+
None if plddt is None else round(plddt, 1), atoms,
|
|
165
|
+
None if rec.occupancy is None else round(rec.occupancy, 4))
|
|
166
|
+
bits[bit] = bits[bit].merged(one) if bit in bits else one
|
|
167
|
+
return cls(name or diagram.name or "ligand", dict(sorted(bits.items(), key=lambda kv: kv[0].sort_key)))
|
|
168
|
+
|
|
169
|
+
# -- reading -----------------------------------------------------------
|
|
170
|
+
@property
|
|
171
|
+
def columns(self) -> list[Bit]:
|
|
172
|
+
"""The set bits, in the fixed order."""
|
|
173
|
+
return sorted(self.bits, key=lambda b: b.sort_key)
|
|
174
|
+
|
|
175
|
+
def __len__(self) -> int:
|
|
176
|
+
return len(self.bits)
|
|
177
|
+
|
|
178
|
+
def __iter__(self) -> Iterator[Bit]:
|
|
179
|
+
return iter(self.columns)
|
|
180
|
+
|
|
181
|
+
def __contains__(self, bit: object) -> bool:
|
|
182
|
+
return bit in self.bits
|
|
183
|
+
|
|
184
|
+
def vector(self, columns: Sequence[Bit] | None = None, counts: bool = False) -> list[int]:
|
|
185
|
+
"""The fingerprint over ``columns`` (default: its own bits): 1/0, or record counts."""
|
|
186
|
+
cols = self.columns if columns is None else list(columns)
|
|
187
|
+
return [(self.bits[b].count if counts else 1) if b in self.bits else 0 for b in cols]
|
|
188
|
+
|
|
189
|
+
def residues(self) -> dict[tuple[str, int, str], list[InteractionType]]:
|
|
190
|
+
"""Interaction types per contacted residue, both in the fixed order."""
|
|
191
|
+
out: dict[tuple[str, int, str], list[InteractionType]] = {}
|
|
192
|
+
for b in self.columns:
|
|
193
|
+
out.setdefault(b.residue, []).append(b.type)
|
|
194
|
+
return out
|
|
195
|
+
|
|
196
|
+
def tanimoto(self, other: "Fingerprint") -> float:
|
|
197
|
+
"""Shared bits over all bits set in either fingerprint (1.0 for two empty ones)."""
|
|
198
|
+
a, b = set(self.bits), set(other.bits)
|
|
199
|
+
return len(a & b) / len(a | b) if (a or b) else 1.0
|
|
200
|
+
|
|
201
|
+
def difference(self, other: "Fingerprint") -> tuple[list[Bit], list[Bit], list[Bit]]:
|
|
202
|
+
"""``(shared, only in self, only in other)``, each in the fixed order."""
|
|
203
|
+
a, b = set(self.bits), set(other.bits)
|
|
204
|
+
|
|
205
|
+
def ordered(bits: Iterable[Bit]) -> list[Bit]:
|
|
206
|
+
return sorted(bits, key=lambda x: x.sort_key)
|
|
207
|
+
return ordered(a & b), ordered(a - b), ordered(b - a)
|
|
208
|
+
|
|
209
|
+
# -- CSV (long form) ---------------------------------------------------
|
|
210
|
+
def rows(self) -> list[dict[str, str]]:
|
|
211
|
+
"""One row for each bit, as plain data."""
|
|
212
|
+
out = []
|
|
213
|
+
for b in self.columns:
|
|
214
|
+
c = self.bits[b]
|
|
215
|
+
out.append({
|
|
216
|
+
"ligand": self.name, "chain": b.chain, "residue_number": str(b.number), "insertion_code": b.icode,
|
|
217
|
+
"residue_name": b.resname, "interaction_type": b.type.value, "count": str(c.count),
|
|
218
|
+
"min_distance": _num(c.distance, 2), "plddt": _num(c.plddt, 1),
|
|
219
|
+
"occupancy": _num(c.occupancy, 4), "ligand_atoms": " ".join(c.ligand_atoms),
|
|
220
|
+
})
|
|
221
|
+
return out
|
|
222
|
+
|
|
223
|
+
def to_csv(self, path: "str | Path | None" = None) -> str:
|
|
224
|
+
"""Long-form CSV: one row per set bit. Written to ``path`` when given; always returned."""
|
|
225
|
+
return _write_rows(LONG_COLUMNS, self.rows(), path)
|
|
226
|
+
|
|
227
|
+
@classmethod
|
|
228
|
+
def from_csv(cls, source: "str | Path") -> "Fingerprint":
|
|
229
|
+
"""Read one fingerprint back from :meth:`to_csv` output (text or a path)."""
|
|
230
|
+
table = FingerprintTable.from_csv(source)
|
|
231
|
+
if len(table.fingerprints) != 1:
|
|
232
|
+
raise InteractionError(f"expected one fingerprint, found {len(table.fingerprints)}; "
|
|
233
|
+
"use FingerprintTable.from_csv")
|
|
234
|
+
return table.fingerprints[0]
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
@dataclass(frozen=True)
|
|
238
|
+
class ConsensusRow:
|
|
239
|
+
"""One residue of a set: how many ligands contact it, and how.
|
|
240
|
+
|
|
241
|
+
The numbers live on contact records. ``contacts`` holds one
|
|
242
|
+
:class:`~bindview.interactions.Interaction` per interaction type made with
|
|
243
|
+
the residue, and its ``occupancy`` is the share of the set's ligands that
|
|
244
|
+
make it: the same field, drawn through the same channel, that carries the
|
|
245
|
+
share of frames when the ensemble is a trajectory. ``occupancy`` of the row
|
|
246
|
+
itself is the share of ligands that contact the residue in any way, which
|
|
247
|
+
the per-type numbers cannot give (one ligand can make several types).
|
|
248
|
+
"""
|
|
249
|
+
|
|
250
|
+
chain: str
|
|
251
|
+
number: int
|
|
252
|
+
icode: str
|
|
253
|
+
resname: str
|
|
254
|
+
n_ligands: int # ligands with any contact to the residue
|
|
255
|
+
n_total: int # ligands in the set
|
|
256
|
+
contacts: tuple[Interaction, ...] # one per interaction type, in the fixed order
|
|
257
|
+
ligands: tuple[str, ...] # names of the contacting ligands, in set order
|
|
258
|
+
#: Contacting ligands by the confidence of their contact with the residue:
|
|
259
|
+
#: unqualified or pLDDT >= 70, 50-70, below 50. ``None``: the set carries no confidence.
|
|
260
|
+
levels: tuple[int, int, int] | None = None
|
|
261
|
+
|
|
262
|
+
@property
|
|
263
|
+
def residue(self) -> tuple[str, int, str]:
|
|
264
|
+
return (self.chain, self.number, self.icode)
|
|
265
|
+
|
|
266
|
+
@property
|
|
267
|
+
def label(self) -> str:
|
|
268
|
+
return format_residue_label(self.resname, self.number, self.icode, None)
|
|
269
|
+
|
|
270
|
+
@property
|
|
271
|
+
def occupancy(self) -> float:
|
|
272
|
+
"""Share of the set's ligands that contact the residue in any way."""
|
|
273
|
+
return self.n_ligands / self.n_total if self.n_total else 0.0
|
|
274
|
+
|
|
275
|
+
@property
|
|
276
|
+
def fraction(self) -> float:
|
|
277
|
+
return self.occupancy
|
|
278
|
+
|
|
279
|
+
@property
|
|
280
|
+
def types(self) -> tuple[tuple[InteractionType, int], ...]:
|
|
281
|
+
"""``(type, ligands making it)`` in the fixed order -- read off the contact records."""
|
|
282
|
+
return tuple((c.type, int(round((c.occupancy or 0.0) * self.n_total))) for c in self.contacts)
|
|
283
|
+
|
|
284
|
+
@property
|
|
285
|
+
def n_confident(self) -> int | None:
|
|
286
|
+
return self.levels[0] if self.levels is not None else None
|
|
287
|
+
|
|
288
|
+
def as_dict(self) -> dict[str, Any]:
|
|
289
|
+
return {"residue": self.label, "chain": self.chain, "residue_number": self.number,
|
|
290
|
+
"n_ligands": self.n_ligands, "frac": round(self.fraction, 3),
|
|
291
|
+
"types": sorted(t.value for t, _ in self.types),
|
|
292
|
+
"type_counts": {t.value: n for t, n in self.types}, "ligands": list(self.ligands),
|
|
293
|
+
"n_confident": self.n_confident,
|
|
294
|
+
"contacts": [{"type": c.type.value, "occupancy": round(c.occupancy or 0.0, 4),
|
|
295
|
+
"confidence": c.confidence, "distance": c.distance} for c in self.contacts]}
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
@dataclass
|
|
299
|
+
class FingerprintTable:
|
|
300
|
+
"""The fingerprints of a set of ligands over one residue numbering."""
|
|
301
|
+
|
|
302
|
+
fingerprints: list[Fingerprint]
|
|
303
|
+
|
|
304
|
+
def __post_init__(self) -> None:
|
|
305
|
+
names = [f.name for f in self.fingerprints]
|
|
306
|
+
if len(set(names)) != len(names):
|
|
307
|
+
raise InteractionError(f"ligand names must be unique in a fingerprint table: {names}")
|
|
308
|
+
|
|
309
|
+
@property
|
|
310
|
+
def names(self) -> list[str]:
|
|
311
|
+
"""The names of the ligands, in order."""
|
|
312
|
+
return [f.name for f in self.fingerprints]
|
|
313
|
+
|
|
314
|
+
@property
|
|
315
|
+
def columns(self) -> list[Bit]:
|
|
316
|
+
"""The union of all set bits, in the fixed order."""
|
|
317
|
+
union: set[Bit] = set()
|
|
318
|
+
for f in self.fingerprints:
|
|
319
|
+
union |= set(f.bits)
|
|
320
|
+
return sorted(union, key=lambda b: b.sort_key)
|
|
321
|
+
|
|
322
|
+
def matrix(self, counts: bool = False) -> list[list[int]]:
|
|
323
|
+
"""The bits as a matrix, one row a ligand; with ``counts`` the number of records."""
|
|
324
|
+
cols = self.columns
|
|
325
|
+
return [f.vector(cols, counts) for f in self.fingerprints]
|
|
326
|
+
|
|
327
|
+
def consensus(self) -> list[ConsensusRow]:
|
|
328
|
+
"""Per residue: how many ligands contact it and with which types.
|
|
329
|
+
|
|
330
|
+
Rows are ordered by the number of ligands (most first), then by chain
|
|
331
|
+
and residue number. Each row's contact records carry, per interaction
|
|
332
|
+
type, the share of ligands that make it (``occupancy``), the shortest
|
|
333
|
+
distance over the set, and the confidence of the best-supported ligand.
|
|
334
|
+
"""
|
|
335
|
+
n = len(self.fingerprints)
|
|
336
|
+
has_conf = any(v.plddt is not None for f in self.fingerprints for v in f.bits.values())
|
|
337
|
+
slots: dict[tuple[str, int, str], dict[str, Any]] = {}
|
|
338
|
+
for f in self.fingerprints:
|
|
339
|
+
best: dict[tuple[str, int, str], float | None] = {}
|
|
340
|
+
for b in f.columns:
|
|
341
|
+
value = f.bits[b]
|
|
342
|
+
slot = slots.setdefault(b.residue, {"resname": b.resname, "types": {}, "ligands": [],
|
|
343
|
+
"levels": [0, 0, 0]})
|
|
344
|
+
kind = slot["types"].setdefault(b.type, {"n": 0, "distance": None, "plddt": None})
|
|
345
|
+
kind["n"] += 1
|
|
346
|
+
if value.distance is not None:
|
|
347
|
+
kind["distance"] = value.distance if kind["distance"] is None else min(kind["distance"],
|
|
348
|
+
value.distance)
|
|
349
|
+
if value.plddt is not None:
|
|
350
|
+
kind["plddt"] = value.plddt if kind["plddt"] is None else max(kind["plddt"], value.plddt)
|
|
351
|
+
if f.name not in slot["ligands"]:
|
|
352
|
+
slot["ligands"].append(f.name)
|
|
353
|
+
if b.residue not in best:
|
|
354
|
+
best[b.residue] = value.plddt
|
|
355
|
+
elif value.plddt is not None:
|
|
356
|
+
current = best[b.residue]
|
|
357
|
+
best[b.residue] = value.plddt if current is None else max(current, value.plddt)
|
|
358
|
+
for res, top in best.items():
|
|
359
|
+
slots[res]["levels"][look_of(top).level] += 1
|
|
360
|
+
rows = []
|
|
361
|
+
for res, slot in slots.items():
|
|
362
|
+
contacts = tuple(
|
|
363
|
+
Interaction(type=t, residue_number=res[1], residue_name=slot["resname"], chain=res[0],
|
|
364
|
+
insertion_code=res[2], distance=slot["types"][t]["distance"],
|
|
365
|
+
occupancy=slot["types"][t]["n"] / n, confidence=slot["types"][t]["plddt"])
|
|
366
|
+
for t in TYPE_ORDER if t in slot["types"])
|
|
367
|
+
levels = (slot["levels"][0], slot["levels"][1], slot["levels"][2]) if has_conf else None
|
|
368
|
+
rows.append(ConsensusRow(res[0], res[1], res[2], slot["resname"], len(slot["ligands"]), n, contacts,
|
|
369
|
+
tuple(slot["ligands"]), levels))
|
|
370
|
+
rows.sort(key=lambda r: (-r.n_ligands, r.chain, r.number, r.icode))
|
|
371
|
+
return rows
|
|
372
|
+
|
|
373
|
+
def contacts(self) -> list[Interaction]:
|
|
374
|
+
"""The set as contact records: one per (residue, interaction type), in the fixed column
|
|
375
|
+
order, with ``occupancy`` the share of ligands that make the contact."""
|
|
376
|
+
rows = {r.residue: r for r in self.consensus()}
|
|
377
|
+
return [c for res in sorted(rows) for c in rows[res].contacts]
|
|
378
|
+
|
|
379
|
+
# -- CSV ---------------------------------------------------------------
|
|
380
|
+
def to_csv(self, path: "str | Path | None" = None, form: str = "long", counts: bool = False) -> str:
|
|
381
|
+
"""``form="long"``: one row per (ligand, set bit), lossless. ``form="wide"``: one row per
|
|
382
|
+
ligand and one column per bit of the union, holding 1/0 (or record counts)."""
|
|
383
|
+
if form == "long":
|
|
384
|
+
rows = [row for f in self.fingerprints for row in f.rows()]
|
|
385
|
+
# A ligand with no contacts still belongs to the set: keep it as a row with no bit.
|
|
386
|
+
for f in self.fingerprints:
|
|
387
|
+
if not f.bits:
|
|
388
|
+
rows.append({**{k: "" for k in LONG_COLUMNS}, "ligand": f.name})
|
|
389
|
+
return _write_rows(LONG_COLUMNS, rows, path)
|
|
390
|
+
if form != "wide":
|
|
391
|
+
raise ValueError("form must be 'long' or 'wide'")
|
|
392
|
+
cols = self.columns
|
|
393
|
+
header = ["ligand"] + [b.column for b in cols]
|
|
394
|
+
rows = [dict(zip(header, [f.name] + [str(v) for v in f.vector(cols, counts)])) for f in self.fingerprints]
|
|
395
|
+
return _write_rows(header, rows, path)
|
|
396
|
+
|
|
397
|
+
@classmethod
|
|
398
|
+
def from_csv(cls, source: "str | Path") -> "FingerprintTable":
|
|
399
|
+
"""Read either CSV form back (text or a path). The wide form carries presence
|
|
400
|
+
(or counts) only; distances, confidence and atoms are in the long form."""
|
|
401
|
+
text = _read_text(source)
|
|
402
|
+
reader = csv.DictReader(io.StringIO(text))
|
|
403
|
+
header = reader.fieldnames or []
|
|
404
|
+
if not header or header[0] != "ligand":
|
|
405
|
+
one_line = isinstance(source, str) and "\n" not in source.strip() and len(source) <= 200
|
|
406
|
+
raise InteractionError("not a fingerprint CSV: the first column must be 'ligand'"
|
|
407
|
+
+ (f" (and {source!r} is not the name of a file that is there)" if one_line else ""))
|
|
408
|
+
fps: dict[str, Fingerprint] = {}
|
|
409
|
+
if "interaction_type" in header:
|
|
410
|
+
for row in reader:
|
|
411
|
+
fp = fps.setdefault(row["ligand"], Fingerprint(row["ligand"]))
|
|
412
|
+
if not row.get("interaction_type"):
|
|
413
|
+
continue
|
|
414
|
+
try:
|
|
415
|
+
bit = Bit(row["chain"], int(row["residue_number"]), row["insertion_code"], row["residue_name"],
|
|
416
|
+
InteractionType(row["interaction_type"]))
|
|
417
|
+
fp.bits[bit] = BitValue(int(row["count"] or 1), _opt_float(row.get("min_distance", "")),
|
|
418
|
+
_opt_float(row.get("plddt", "")),
|
|
419
|
+
tuple((row.get("ligand_atoms") or "").split()),
|
|
420
|
+
_opt_float(row.get("occupancy") or ""))
|
|
421
|
+
except (KeyError, ValueError) as exc:
|
|
422
|
+
raise InteractionError(f"bad fingerprint row {row!r}: {exc}") from exc
|
|
423
|
+
else:
|
|
424
|
+
bits = [Bit.from_column(c) for c in header[1:]]
|
|
425
|
+
for row in reader:
|
|
426
|
+
fp = fps.setdefault(row["ligand"], Fingerprint(row["ligand"]))
|
|
427
|
+
for name, b in zip(header[1:], bits):
|
|
428
|
+
cell = (row[name] or "").strip() # (a row that ends early has none)
|
|
429
|
+
if not cell.isdecimal():
|
|
430
|
+
if cell:
|
|
431
|
+
raise InteractionError(f"{cell!r} in column {name!r} of ligand {row['ligand']!r} is not a "
|
|
432
|
+
"count: a cell of the wide form holds 0, 1 or how many records")
|
|
433
|
+
continue
|
|
434
|
+
if int(cell):
|
|
435
|
+
fp.bits[b] = BitValue(int(cell))
|
|
436
|
+
return cls(list(fps.values()))
|
|
437
|
+
|
|
438
|
+
|
|
439
|
+
def _read_text(source: "str | Path") -> str:
|
|
440
|
+
"""The text of a table. A ``Path`` is a file; a string is one where it is the name of a file that is there,
|
|
441
|
+
whatever it is called, and the table itself where it is not."""
|
|
442
|
+
if isinstance(source, Path) or _names_a_file(str(source)):
|
|
443
|
+
try:
|
|
444
|
+
return Path(source).read_text(encoding="utf-8").removeprefix("\ufeff")
|
|
445
|
+
except (OSError, ValueError) as exc: # (ValueError: it is not text)
|
|
446
|
+
raise InteractionError(f"cannot read {source}: {exc}") from exc
|
|
447
|
+
return str(source).removeprefix("\ufeff")
|
|
448
|
+
|
|
449
|
+
|
|
450
|
+
def _names_a_file(text: str) -> bool:
|
|
451
|
+
"""Is it the name of a file that is there? No table is: a name has no line break in it."""
|
|
452
|
+
try:
|
|
453
|
+
return "\n" not in text and Path(text).is_file()
|
|
454
|
+
except (OSError, ValueError): # too long for a name, or with a character no name has
|
|
455
|
+
return False
|
|
456
|
+
|
|
457
|
+
|
|
458
|
+
def _write_rows(header: Sequence[str], rows: Sequence[Mapping[str, str]], path: "str | Path | None") -> str:
|
|
459
|
+
buf = io.StringIO()
|
|
460
|
+
writer = csv.DictWriter(buf, fieldnames=list(header), lineterminator="\n")
|
|
461
|
+
writer.writeheader()
|
|
462
|
+
writer.writerows(rows)
|
|
463
|
+
text = buf.getvalue()
|
|
464
|
+
if path is not None:
|
|
465
|
+
try:
|
|
466
|
+
Path(path).write_text(text, encoding="utf-8")
|
|
467
|
+
except OSError as exc:
|
|
468
|
+
raise InteractionError(f"cannot write {path}: {exc}") from exc
|
|
469
|
+
return text
|