deeplc 4.3.0__tar.gz → 4.4.0__tar.gz
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.
- {deeplc-4.3.0/deeplc.egg-info → deeplc-4.4.0}/PKG-INFO +2 -1
- {deeplc-4.3.0 → deeplc-4.4.0}/deeplc/__init__.py +3 -0
- {deeplc-4.3.0 → deeplc-4.4.0}/deeplc/_architecture.py +31 -0
- deeplc-4.4.0/deeplc/_batch_features.py +218 -0
- {deeplc-4.3.0 → deeplc-4.4.0}/deeplc/_features.py +19 -1
- {deeplc-4.3.0 → deeplc-4.4.0}/deeplc/_model_ops.py +143 -9
- {deeplc-4.3.0 → deeplc-4.4.0}/deeplc/calibration/multihead.py +106 -18
- {deeplc-4.3.0 → deeplc-4.4.0}/deeplc/calibration/simple.py +13 -14
- {deeplc-4.3.0 → deeplc-4.4.0}/deeplc/core.py +105 -7
- {deeplc-4.3.0 → deeplc-4.4.0}/deeplc/data.py +118 -7
- deeplc-4.4.0/deeplc/report.py +505 -0
- {deeplc-4.3.0 → deeplc-4.4.0/deeplc.egg-info}/PKG-INFO +2 -1
- {deeplc-4.3.0 → deeplc-4.4.0}/deeplc.egg-info/SOURCES.txt +5 -1
- {deeplc-4.3.0 → deeplc-4.4.0}/deeplc.egg-info/requires.txt +1 -0
- {deeplc-4.3.0 → deeplc-4.4.0}/pyproject.toml +2 -1
- deeplc-4.4.0/tests/test_batch_features.py +247 -0
- {deeplc-4.3.0 → deeplc-4.4.0}/tests/test_flexcnn.py +84 -0
- {deeplc-4.3.0 → deeplc-4.4.0}/tests/test_multihead_calibration.py +128 -0
- deeplc-4.4.0/tests/test_report.py +355 -0
- {deeplc-4.3.0 → deeplc-4.4.0}/LICENSE +0 -0
- {deeplc-4.3.0 → deeplc-4.4.0}/MANIFEST.in +0 -0
- {deeplc-4.3.0 → deeplc-4.4.0}/README.md +0 -0
- {deeplc-4.3.0 → deeplc-4.4.0}/deeplc/__main__.py +0 -0
- {deeplc-4.3.0 → deeplc-4.4.0}/deeplc/_reference_selection.py +0 -0
- {deeplc-4.3.0 → deeplc-4.4.0}/deeplc/calibration/__init__.py +0 -0
- {deeplc-4.3.0 → deeplc-4.4.0}/deeplc/exceptions.py +0 -0
- {deeplc-4.3.0 → deeplc-4.4.0}/deeplc/gui.py +0 -0
- {deeplc-4.3.0 → deeplc-4.4.0}/deeplc/package_data/__init__.py +0 -0
- {deeplc-4.3.0 → deeplc-4.4.0}/deeplc/package_data/baseline_performance/__init__.py +0 -0
- {deeplc-4.3.0 → deeplc-4.4.0}/deeplc/package_data/baseline_performance/baseline_predictions.csv +0 -0
- {deeplc-4.3.0 → deeplc-4.4.0}/deeplc/package_data/examples/__init__.py +0 -0
- {deeplc-4.3.0 → deeplc-4.4.0}/deeplc/package_data/examples/example_psms.tsv.gz +0 -0
- {deeplc-4.3.0 → deeplc-4.4.0}/deeplc/package_data/gui_images/__init__.py +0 -0
- {deeplc-4.3.0 → deeplc-4.4.0}/deeplc/package_data/gui_images/config_icon.png +0 -0
- {deeplc-4.3.0 → deeplc-4.4.0}/deeplc/package_data/gui_images/deeplc_logo.png +0 -0
- {deeplc-4.3.0 → deeplc-4.4.0}/deeplc/package_data/gui_images/deeplc_logo.svg +0 -0
- {deeplc-4.3.0 → deeplc-4.4.0}/deeplc/package_data/gui_images/program_icon.png +0 -0
- {deeplc-4.3.0 → deeplc-4.4.0}/deeplc/package_data/models/__init__.py +0 -0
- {deeplc-4.3.0 → deeplc-4.4.0}/deeplc/package_data/models/full_hc_PXD005573_pub_1fd8363d9af9dcad3be7553c39396960.pt +0 -0
- {deeplc-4.3.0 → deeplc-4.4.0}/deeplc/package_data/models/full_hc_PXD005573_pub_8c22d89667368f2f02ad996469ba157e.pt +0 -0
- {deeplc-4.3.0 → deeplc-4.4.0}/deeplc/package_data/models/full_hc_PXD005573_pub_cb975cfdd4105f97efa0b3afffe075cc.pt +0 -0
- {deeplc-4.3.0 → deeplc-4.4.0}/deeplc/package_data/models/multitask_flexcnn_model.pt +0 -0
- {deeplc-4.3.0 → deeplc-4.4.0}/deeplc/package_data/models/multitask_model.pt +0 -0
- {deeplc-4.3.0 → deeplc-4.4.0}/deeplc/plot.py +0 -0
- {deeplc-4.3.0 → deeplc-4.4.0}/deeplc.egg-info/dependency_links.txt +0 -0
- {deeplc-4.3.0 → deeplc-4.4.0}/deeplc.egg-info/entry_points.txt +0 -0
- {deeplc-4.3.0 → deeplc-4.4.0}/deeplc.egg-info/top_level.txt +0 -0
- {deeplc-4.3.0 → deeplc-4.4.0}/setup.cfg +0 -0
- {deeplc-4.3.0 → deeplc-4.4.0}/tests/test_calibration.py +0 -0
- {deeplc-4.3.0 → deeplc-4.4.0}/tests/test_core.py +0 -0
- {deeplc-4.3.0 → deeplc-4.4.0}/tests/test_deduplication.py +0 -0
- {deeplc-4.3.0 → deeplc-4.4.0}/tests/test_features.py +0 -0
- {deeplc-4.3.0 → deeplc-4.4.0}/tests/test_model_ops.py +0 -0
- {deeplc-4.3.0 → deeplc-4.4.0}/tests/test_reference_selection.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: deeplc
|
|
3
|
-
Version: 4.
|
|
3
|
+
Version: 4.4.0
|
|
4
4
|
Summary: DeepLC: Retention time prediction for (modified) peptides using Deep Learning.
|
|
5
5
|
Author: Ralf Gabriels, Kevin Velghe, Robbe Devreese, Arthur Declercq, Alireza Nameni, Ralf Gabriels, Niels Hulstaert, Sven Degroeve, Lennart Martens
|
|
6
6
|
Author-email: Robbin Bouwmeester <robbin.bouwmeester@ugent.be>
|
|
@@ -223,6 +223,7 @@ Requires-Dist: numpy<3,>=1.17
|
|
|
223
223
|
Requires-Dist: pandas<3,>=0.25
|
|
224
224
|
Requires-Dist: scikit-learn<2,>=1.2.0
|
|
225
225
|
Requires-Dist: psm-utils<2,>=1.5
|
|
226
|
+
Requires-Dist: rapidfuzz<4,>=3
|
|
226
227
|
Requires-Dist: click<9,>=8
|
|
227
228
|
Requires-Dist: rich<15,>=13
|
|
228
229
|
Provides-Extra: gui
|
|
@@ -11,9 +11,12 @@ from deeplc.core import (
|
|
|
11
11
|
save_model,
|
|
12
12
|
train,
|
|
13
13
|
)
|
|
14
|
+
from deeplc.report import TrainingIndex, prediction_report
|
|
14
15
|
|
|
15
16
|
__version__: str = version("deeplc")
|
|
16
17
|
__all__: list[str] = [
|
|
18
|
+
"TrainingIndex",
|
|
19
|
+
"prediction_report",
|
|
17
20
|
"calibrate",
|
|
18
21
|
"predict",
|
|
19
22
|
"predict_and_calibrate",
|
|
@@ -844,6 +844,10 @@ class FlexCNNMultitaskModel(nn.Module):
|
|
|
844
844
|
#: Index reserved for padding positions in the residue encoding.
|
|
845
845
|
PAD_INDEX = 20
|
|
846
846
|
|
|
847
|
+
#: The fused trunk reads the per-position matrix directly, so the rolling-sum array is
|
|
848
|
+
#: redundant and its ``forward`` deletes it. Encoding can skip building it.
|
|
849
|
+
uses_rolling_sum = False
|
|
850
|
+
|
|
847
851
|
def __init__(
|
|
848
852
|
self,
|
|
849
853
|
n_tasks: int,
|
|
@@ -934,6 +938,33 @@ class FlexCNNMultitaskModel(nn.Module):
|
|
|
934
938
|
del x_atom_sum # the fused trunk reads x_atom directly
|
|
935
939
|
return self.head(self.encoder(x_atom, x_global, x_one_hot), task_idx)
|
|
936
940
|
|
|
941
|
+
@property
|
|
942
|
+
def padding_reach(self) -> int | None:
|
|
943
|
+
"""
|
|
944
|
+
How far a valid position can see across the right edge of the encoding window.
|
|
945
|
+
|
|
946
|
+
The trunk masks its output by the true residue count and pools over that mask, and
|
|
947
|
+
the features themselves do not depend on the window, so the only way padding can
|
|
948
|
+
reach a valid position is through the convolutions. Each convolution of width ``k``
|
|
949
|
+
and dilation ``d`` reaches ``(k - 1) // 2 * d`` positions, and the reaches add up.
|
|
950
|
+
A batch encoded in a window of its longest peptide plus this many positions
|
|
951
|
+
therefore predicts exactly what the full window predicts, which for a median
|
|
952
|
+
peptide of sixteen residues is a fraction of the sixty positions used otherwise.
|
|
953
|
+
|
|
954
|
+
Returns None when the trunk pools or strides across positions, because then the
|
|
955
|
+
mask no longer lines up position by position and the argument does not hold.
|
|
956
|
+
|
|
957
|
+
"""
|
|
958
|
+
reach = 0
|
|
959
|
+
for module in self.encoder.modules():
|
|
960
|
+
if isinstance(module, (nn.MaxPool1d, nn.AvgPool1d)):
|
|
961
|
+
return None
|
|
962
|
+
if isinstance(module, nn.Conv1d):
|
|
963
|
+
if module.stride[0] != 1:
|
|
964
|
+
return None
|
|
965
|
+
reach += ((module.kernel_size[0] - 1) // 2) * module.dilation[0]
|
|
966
|
+
return reach
|
|
967
|
+
|
|
937
968
|
def add_task_head(
|
|
938
969
|
self, targets: torch.Tensor | None = None, init_from: int | None = None
|
|
939
970
|
) -> int:
|
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Batched feature encoding: the residue-only base for a whole batch in one pass.
|
|
3
|
+
|
|
4
|
+
:func:`deeplc._features.encode_peptidoform` stays the definition of what a feature is. What
|
|
5
|
+
this module adds is a faster route to the same numbers for a batch of peptidoforms, and it
|
|
6
|
+
only accelerates the part that depends on residue identity alone:
|
|
7
|
+
|
|
8
|
+
* the per-position atom composition matrix and the one-hot residue matrix are a table gather
|
|
9
|
+
and a scatter over the batch;
|
|
10
|
+
* the positional atom block reads the first few and last few residues of each peptide, which
|
|
11
|
+
is the same gather with different rows;
|
|
12
|
+
* the global vector is a sum along the batch's position axis.
|
|
13
|
+
|
|
14
|
+
Modifications are not reimplemented here. They occur on a quarter of a typical peptide list,
|
|
15
|
+
and their placement has a legacy quirk that a shipped model was trained against, so they are
|
|
16
|
+
applied by calling :func:`deeplc._features._apply_modifications` and its terminal counterpart
|
|
17
|
+
on **views into the batch arrays**. The exactness therefore comes from reusing that code
|
|
18
|
+
rather than from matching it.
|
|
19
|
+
|
|
20
|
+
Anything the batched route is not verified for falls back to
|
|
21
|
+
:func:`~deeplc._features.encode_peptidoform` per peptide, which keeps its warnings and its
|
|
22
|
+
exceptions rather than approximating them: peptides shorter than four residues, whose
|
|
23
|
+
negative positional indices wrap around the sequence in the reference encoder, and peptides
|
|
24
|
+
carrying a residue the one-hot block has no slot for, such as selenocysteine. Feature layouts
|
|
25
|
+
the route does not cover at all are rejected by :func:`supports`, and the caller keeps the
|
|
26
|
+
per-peptide path for those.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
from __future__ import annotations
|
|
30
|
+
|
|
31
|
+
from collections.abc import Sequence
|
|
32
|
+
|
|
33
|
+
import numpy as np
|
|
34
|
+
from psm_utils import Peptidoform
|
|
35
|
+
from pyteomics import mass
|
|
36
|
+
|
|
37
|
+
from deeplc._features import (
|
|
38
|
+
DEFAULT_DICT_AA,
|
|
39
|
+
DEFAULT_DICT_INDEX,
|
|
40
|
+
DEFAULT_DICT_INDEX_POS,
|
|
41
|
+
DEFAULT_POSITIONS,
|
|
42
|
+
DEFAULT_POSITIONS_NEG,
|
|
43
|
+
DEFAULT_POSITIONS_POS,
|
|
44
|
+
_apply_modifications,
|
|
45
|
+
_apply_terminal_modifications,
|
|
46
|
+
_terminal_composition,
|
|
47
|
+
encode_peptidoform,
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
#: Residues the one-hot block has a slot for, in its own order.
|
|
51
|
+
RESIDUES: tuple[str, ...] = tuple(sorted(DEFAULT_DICT_AA, key=lambda key: DEFAULT_DICT_AA[key]))
|
|
52
|
+
CODE: dict[str, int] = {residue: index for index, residue in enumerate(RESIDUES)}
|
|
53
|
+
#: Row reserved for padding in the gather tables, holding zeros.
|
|
54
|
+
PAD = len(RESIDUES)
|
|
55
|
+
N_ATOMS = len(DEFAULT_DICT_INDEX)
|
|
56
|
+
_POSITIONS = DEFAULT_POSITIONS_POS | DEFAULT_POSITIONS_NEG
|
|
57
|
+
POS_ROWS = max(_POSITIONS) - min(_POSITIONS) + 1
|
|
58
|
+
POS_OFFSET = min(_POSITIONS)
|
|
59
|
+
|
|
60
|
+
#: Shortest peptide the batched route takes. Below four residues the reference encoder's
|
|
61
|
+
#: negative positional indices wrap around the sequence - with a single residue,
|
|
62
|
+
#: ``seq[seq_len - 2]`` is ``seq[-1]``, that same residue - and such peptides are rare enough
|
|
63
|
+
#: that reproducing the wrap in vectorised form is not worth the risk of getting it wrong.
|
|
64
|
+
MIN_LENGTH = 4
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _gather_table(atom_index: dict[str, int]) -> np.ndarray:
|
|
68
|
+
"""Atom counts per residue under one atom ordering, with a zero row for padding."""
|
|
69
|
+
table = np.zeros((PAD + 1, N_ATOMS), dtype=np.float16)
|
|
70
|
+
for residue, row in CODE.items():
|
|
71
|
+
for atom, count in mass.std_aa_comp[residue].items():
|
|
72
|
+
column = atom_index.get(atom)
|
|
73
|
+
if column is not None:
|
|
74
|
+
table[row, column] = count
|
|
75
|
+
return table
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
COMPOSITION = _gather_table(DEFAULT_DICT_INDEX)
|
|
79
|
+
POSITIONAL = _gather_table(DEFAULT_DICT_INDEX_POS)
|
|
80
|
+
#: An unmodified peptidoform contributes nothing to the terminal block: the reference reads
|
|
81
|
+
#: the ``n_term`` and ``c_term`` properties, which are empty, and returns zeros. The backbone
|
|
82
|
+
#: termini are already inside the residue compositions.
|
|
83
|
+
TERMINI = np.zeros((2, N_ATOMS), dtype=np.float16)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def supports(add_ccs_features: bool, include_rolling_sum: bool) -> bool:
|
|
87
|
+
"""
|
|
88
|
+
Whether the batched route covers a feature layout.
|
|
89
|
+
|
|
90
|
+
It does not build the rolling-sum matrix, which the four-branch model reads, and it does
|
|
91
|
+
not build the collision cross section extras, which need the precursor charge and a
|
|
92
|
+
handful of residue fractions. A caller asking for either keeps the per-peptide path.
|
|
93
|
+
"""
|
|
94
|
+
return not add_ccs_features and not include_rolling_sum
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _as_peptidoform(peptidoform: Peptidoform | str) -> Peptidoform:
|
|
98
|
+
"""Parse a ProForma string if that is what a dataset holds, else pass it through."""
|
|
99
|
+
return peptidoform if hasattr(peptidoform, "sequence") else Peptidoform(str(peptidoform))
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def encode_batch_features(
|
|
103
|
+
peptidoforms: Sequence[Peptidoform | str],
|
|
104
|
+
padding_length: int = 60,
|
|
105
|
+
add_terminal_composition: bool = True,
|
|
106
|
+
legacy_positional_deltas: bool = True,
|
|
107
|
+
) -> dict[str, np.ndarray]:
|
|
108
|
+
"""
|
|
109
|
+
Encode a batch of peptidoforms, gathering the base and patching the modified ones.
|
|
110
|
+
|
|
111
|
+
Parameters
|
|
112
|
+
----------
|
|
113
|
+
peptidoforms
|
|
114
|
+
The peptidoforms to encode, parsed or as ProForma strings.
|
|
115
|
+
padding_length
|
|
116
|
+
Window the per-position matrices are padded or truncated to.
|
|
117
|
+
add_terminal_composition
|
|
118
|
+
Whether to append the N- and C-terminal group compositions to the global vector.
|
|
119
|
+
legacy_positional_deltas
|
|
120
|
+
Whether modification deltas go into the positional block the way versions before
|
|
121
|
+
4.0.1 placed them, which every released model was trained against.
|
|
122
|
+
|
|
123
|
+
Returns
|
|
124
|
+
-------
|
|
125
|
+
dict of str to numpy.ndarray
|
|
126
|
+
``matrix``, ``matrix_global`` and ``matrix_hc``, batched along the first axis and
|
|
127
|
+
equal value for value, dtype included, to stacking what
|
|
128
|
+
:func:`~deeplc._features.encode_peptidoform` returns for each peptidoform.
|
|
129
|
+
|
|
130
|
+
"""
|
|
131
|
+
parsed = [_as_peptidoform(p) for p in peptidoforms]
|
|
132
|
+
n = len(parsed)
|
|
133
|
+
sequences = [p.sequence for p in parsed]
|
|
134
|
+
lengths = np.fromiter(
|
|
135
|
+
(min(len(sequence), padding_length) for sequence in sequences), dtype=np.int64, count=n
|
|
136
|
+
)
|
|
137
|
+
reference_rows = {
|
|
138
|
+
row
|
|
139
|
+
for row, sequence in enumerate(sequences)
|
|
140
|
+
if len(sequence) < MIN_LENGTH or any(residue not in CODE for residue in sequence)
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
residues = np.full((n, padding_length), PAD, dtype=np.int64)
|
|
144
|
+
for row, (sequence, length) in enumerate(zip(sequences, lengths, strict=True)):
|
|
145
|
+
if row not in reference_rows:
|
|
146
|
+
residues[row, :length] = [CODE[residue] for residue in sequence[:length]]
|
|
147
|
+
|
|
148
|
+
matrix = COMPOSITION[residues]
|
|
149
|
+
one_hot = np.zeros((n, padding_length, len(DEFAULT_DICT_AA)), dtype=np.float16)
|
|
150
|
+
rows, columns = np.nonzero(residues != PAD)
|
|
151
|
+
one_hot[rows, columns, residues[rows, columns]] = 1.0
|
|
152
|
+
|
|
153
|
+
positional = np.zeros((n, POS_ROWS, N_ATOMS), dtype=np.float16)
|
|
154
|
+
for position in sorted(DEFAULT_POSITIONS_POS):
|
|
155
|
+
taken = lengths > position
|
|
156
|
+
positional[taken, position - POS_OFFSET] = POSITIONAL[residues[taken, position]]
|
|
157
|
+
for position in sorted(DEFAULT_POSITIONS_NEG):
|
|
158
|
+
taken = lengths + position >= 0
|
|
159
|
+
positional[taken, position - POS_OFFSET] = POSITIONAL[
|
|
160
|
+
residues[np.nonzero(taken)[0], (lengths + position)[taken]]
|
|
161
|
+
]
|
|
162
|
+
|
|
163
|
+
terminal = np.repeat(TERMINI[None, :, :], n, axis=0) if add_terminal_composition else None
|
|
164
|
+
|
|
165
|
+
for row, peptidoform in enumerate(parsed):
|
|
166
|
+
if row in reference_rows:
|
|
167
|
+
continue
|
|
168
|
+
tokens = peptidoform.parsed_sequence
|
|
169
|
+
if any(token[1] is not None for token in tokens):
|
|
170
|
+
_apply_modifications(
|
|
171
|
+
matrix[row],
|
|
172
|
+
positional[row],
|
|
173
|
+
tokens,
|
|
174
|
+
int(lengths[row]),
|
|
175
|
+
DEFAULT_DICT_INDEX,
|
|
176
|
+
DEFAULT_DICT_INDEX_POS,
|
|
177
|
+
DEFAULT_POSITIONS,
|
|
178
|
+
legacy_positional_deltas,
|
|
179
|
+
)
|
|
180
|
+
properties = peptidoform.properties
|
|
181
|
+
if properties.get("n_term") or properties.get("c_term"):
|
|
182
|
+
_apply_terminal_modifications(
|
|
183
|
+
matrix[row],
|
|
184
|
+
positional[row],
|
|
185
|
+
peptidoform,
|
|
186
|
+
int(lengths[row]),
|
|
187
|
+
DEFAULT_DICT_INDEX,
|
|
188
|
+
DEFAULT_DICT_INDEX_POS,
|
|
189
|
+
DEFAULT_POSITIONS,
|
|
190
|
+
legacy_positional_deltas,
|
|
191
|
+
)
|
|
192
|
+
if terminal is not None:
|
|
193
|
+
terminal[row] = _terminal_composition(peptidoform, DEFAULT_DICT_INDEX)
|
|
194
|
+
|
|
195
|
+
# float64, because the reference promotes when it appends the integer length to a float16
|
|
196
|
+
# sum. The dataset casts to float32 afterwards either way, but the dtype is observable.
|
|
197
|
+
blocks = [
|
|
198
|
+
matrix.sum(axis=1).astype(np.float64),
|
|
199
|
+
lengths[:, None].astype(np.float64),
|
|
200
|
+
positional.reshape(n, -1).astype(np.float64),
|
|
201
|
+
]
|
|
202
|
+
if terminal is not None:
|
|
203
|
+
blocks.append(terminal.reshape(n, -1).astype(np.float64))
|
|
204
|
+
matrix_global = np.concatenate(blocks, axis=1)
|
|
205
|
+
|
|
206
|
+
for row in sorted(reference_rows):
|
|
207
|
+
features = encode_peptidoform(
|
|
208
|
+
parsed[row],
|
|
209
|
+
add_terminal_composition=add_terminal_composition,
|
|
210
|
+
padding_length=padding_length,
|
|
211
|
+
legacy_positional_deltas=legacy_positional_deltas,
|
|
212
|
+
include_rolling_sum=False,
|
|
213
|
+
)
|
|
214
|
+
matrix[row] = features["matrix"]
|
|
215
|
+
one_hot[row] = features["matrix_hc"]
|
|
216
|
+
matrix_global[row] = features["matrix_global"]
|
|
217
|
+
|
|
218
|
+
return {"matrix": matrix, "matrix_global": matrix_global, "matrix_hc": one_hot}
|
|
@@ -40,6 +40,7 @@ def encode_peptidoform(
|
|
|
40
40
|
dict_index_pos: dict[str, int] | None = None,
|
|
41
41
|
dict_index: dict[str, int] | None = None,
|
|
42
42
|
legacy_positional_deltas: bool = False,
|
|
43
|
+
include_rolling_sum: bool = True,
|
|
43
44
|
) -> dict[str, np.ndarray]:
|
|
44
45
|
"""
|
|
45
46
|
Extract features from a single peptidoform.
|
|
@@ -58,6 +59,10 @@ def encode_peptidoform(
|
|
|
58
59
|
modification on the same residue are indistinguishable.
|
|
59
60
|
padding_length
|
|
60
61
|
The maximum length of the sequence after padding. Default is 60.
|
|
62
|
+
include_rolling_sum
|
|
63
|
+
Whether to build ``matrix_sum``, the rolling sum over pairs of positions. Models
|
|
64
|
+
with a convolutional trunk ignore it; False returns an empty array in its place.
|
|
65
|
+
Default is True.
|
|
61
66
|
legacy_positional_deltas
|
|
62
67
|
Whether to place modification deltas in the positional block the way versions
|
|
63
68
|
before 4.0.1 did, which was to index ``pos_mat`` without the sorted-layout
|
|
@@ -139,7 +144,14 @@ def encode_peptidoform(
|
|
|
139
144
|
matrix_all = np.append(matrix_all, (seq.count("K") + seq.count("R")) / seq_len)
|
|
140
145
|
matrix_all = np.append(matrix_all, charge)
|
|
141
146
|
|
|
142
|
-
|
|
147
|
+
# The fused trunk reads the per-position matrix directly and deletes this one on the
|
|
148
|
+
# first line of its forward, so building it is pure cost for those models: the cumulative
|
|
149
|
+
# sum and its slicing are about a tenth of the encoding work.
|
|
150
|
+
matrix_sum = (
|
|
151
|
+
_compute_rolling_sum(std_matrix.T, n=2)[:, ::2].T
|
|
152
|
+
if include_rolling_sum
|
|
153
|
+
else np.zeros((0, len(dict_index)), dtype=np.float16)
|
|
154
|
+
)
|
|
143
155
|
|
|
144
156
|
matrix_global = np.concatenate([matrix_all, pos_matrix.flatten()])
|
|
145
157
|
if add_terminal_composition:
|
|
@@ -337,6 +349,12 @@ def _apply_composition_to_matrices(
|
|
|
337
349
|
except KeyError:
|
|
338
350
|
warnings.warn(f"Ignoring atom {atom_comp} at pos {i}", stacklevel=2)
|
|
339
351
|
continue
|
|
352
|
+
except IndexError:
|
|
353
|
+
# Same guard as the branch below, which this one was missing: a modification
|
|
354
|
+
# placed beyond the padding window has no row to add itself to. Reachable
|
|
355
|
+
# with an isotope-labelled modification, so a TMT or SILAC label, on a
|
|
356
|
+
# peptide longer than the window, where it raised instead of warning.
|
|
357
|
+
warnings.warn(f"Index error for atom {atom_comp} at pos {i}", stacklevel=2)
|
|
340
358
|
except IndexError:
|
|
341
359
|
warnings.warn(f"Index error for atom {atom_comp} at pos {i}", stacklevel=2)
|
|
342
360
|
|
|
@@ -3,10 +3,11 @@
|
|
|
3
3
|
import copy
|
|
4
4
|
import inspect
|
|
5
5
|
import logging
|
|
6
|
-
from collections.abc import Callable, Sequence
|
|
6
|
+
from collections.abc import Callable, Iterator, Sequence
|
|
7
7
|
from os import PathLike
|
|
8
8
|
from pathlib import Path
|
|
9
9
|
|
|
10
|
+
import numpy as np
|
|
10
11
|
import torch
|
|
11
12
|
from rich.progress import (
|
|
12
13
|
BarColumn,
|
|
@@ -250,8 +251,16 @@ def predict(
|
|
|
250
251
|
num_threads: int | None = None,
|
|
251
252
|
show_progress: bool = True,
|
|
252
253
|
task_idx: Sequence[int] | None = None,
|
|
254
|
+
length_buckets: bool = True,
|
|
253
255
|
) -> torch.Tensor:
|
|
254
|
-
"""
|
|
256
|
+
"""
|
|
257
|
+
Predict using the model for the given dataset.
|
|
258
|
+
|
|
259
|
+
``length_buckets`` runs length-sorted chunks in a window that fits them rather than
|
|
260
|
+
padding every peptide to the model's full window; see :func:`_length_buckets`. It is
|
|
261
|
+
exact for models that report a ``padding_reach`` and ignored for those that do not.
|
|
262
|
+
Set it to False to force one pass over the data in the dataset's own window.
|
|
263
|
+
"""
|
|
255
264
|
# ``task_idx`` selects which LC setups a multitask model evaluates. Without
|
|
256
265
|
# it a model trained on thousands of setups returns a column per setup: at
|
|
257
266
|
# 6,543 setups and a million peptides that output alone is tens of gigabytes,
|
|
@@ -260,11 +269,111 @@ def predict(
|
|
|
260
269
|
torch.set_num_threads(num_threads or torch.get_num_threads())
|
|
261
270
|
device = device or ("cuda" if torch.cuda.is_available() else "cpu")
|
|
262
271
|
model = load_model(model, device)
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
272
|
+
|
|
273
|
+
buckets = _length_buckets(model, data, batch_size) if length_buckets else None
|
|
274
|
+
if buckets is None:
|
|
275
|
+
predictions = _predict_epoch(
|
|
276
|
+
model,
|
|
277
|
+
data,
|
|
278
|
+
device,
|
|
279
|
+
batch_size=batch_size,
|
|
280
|
+
num_workers=num_workers,
|
|
281
|
+
show_progress=show_progress,
|
|
282
|
+
task_idx=task_idx,
|
|
283
|
+
)
|
|
284
|
+
return predictions.cpu().detach()
|
|
285
|
+
|
|
286
|
+
out: torch.Tensor | None = None
|
|
287
|
+
for indices, subset in buckets:
|
|
288
|
+
part = _predict_epoch(
|
|
289
|
+
model,
|
|
290
|
+
subset,
|
|
291
|
+
device,
|
|
292
|
+
batch_size=batch_size,
|
|
293
|
+
num_workers=num_workers,
|
|
294
|
+
show_progress=show_progress,
|
|
295
|
+
task_idx=task_idx,
|
|
296
|
+
).cpu()
|
|
297
|
+
if out is None:
|
|
298
|
+
out = torch.empty((len(data), part.shape[1]), dtype=part.dtype)
|
|
299
|
+
out[indices] = part
|
|
300
|
+
if out is None:
|
|
301
|
+
raise ValueError("Dataset is empty — nothing to predict.")
|
|
302
|
+
return out.detach()
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
#: Widest spread of peptide lengths allowed inside one prediction chunk. Small enough that
|
|
306
|
+
#: no peptide carries much padding, large enough that the dense middle of a length
|
|
307
|
+
#: distribution still fills a batch.
|
|
308
|
+
#: A tight window is worth more than a full batch: enforcing a minimum chunk size, so that the
|
|
309
|
+
#: sparse long tail rides along in a wider window, was measured slower (1,546 against 1,503
|
|
310
|
+
#: peptidoforms/s at a floor of 512 and 1,449 at 2,048).
|
|
311
|
+
_LENGTH_BAND = 4
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
def _residue_count(peptidoform: object) -> int:
|
|
315
|
+
"""
|
|
316
|
+
Residues in a peptidoform, whether it arrives parsed or as a ProForma string.
|
|
317
|
+
|
|
318
|
+
A dataset may hold either. The string form cannot be counted by its length, since
|
|
319
|
+
modifications and the charge state are part of it, so it is parsed once here rather
|
|
320
|
+
than per encoded item.
|
|
321
|
+
"""
|
|
322
|
+
sequence = getattr(peptidoform, "sequence", None)
|
|
323
|
+
if sequence is None:
|
|
324
|
+
from psm_utils import Peptidoform
|
|
325
|
+
|
|
326
|
+
sequence = Peptidoform(str(peptidoform)).sequence
|
|
327
|
+
return len(sequence)
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
def _length_buckets(
|
|
331
|
+
model: torch.nn.Module, data: Dataset, batch_size: int
|
|
332
|
+
) -> list[tuple[torch.Tensor, Dataset]] | None:
|
|
333
|
+
"""
|
|
334
|
+
Split the dataset into length-sorted chunks, each encoded in a window that fits it.
|
|
335
|
+
|
|
336
|
+
Padding every peptide to the model's full window makes the convolutions work on
|
|
337
|
+
padding: at a 60-position window and a median peptide of 16 residues most of the
|
|
338
|
+
trunk's arithmetic is spent on positions that are masked out again before pooling.
|
|
339
|
+
Sorting by length and giving each chunk a window of its own longest peptide plus the
|
|
340
|
+
trunk's reach is exact - it was measured identical to the full window over 50,000
|
|
341
|
+
peptides - and about three times faster on CPU.
|
|
342
|
+
|
|
343
|
+
Returns None when the model does not report a reach, when the data is not a
|
|
344
|
+
DeepLCDataset, or when there is nothing to gain, so the caller falls back to one pass.
|
|
345
|
+
"""
|
|
346
|
+
reach = getattr(model, "padding_reach", None)
|
|
347
|
+
if reach is None or not isinstance(data, DeepLCDataset) or len(data) == 0:
|
|
348
|
+
return None
|
|
349
|
+
|
|
350
|
+
lengths = np.fromiter(
|
|
351
|
+
(_residue_count(p) for p in data.peptidoforms), dtype=np.int64, count=len(data)
|
|
266
352
|
)
|
|
267
|
-
|
|
353
|
+
window = data.padding_length
|
|
354
|
+
order = np.argsort(lengths, kind="stable")
|
|
355
|
+
sorted_lengths = lengths[order]
|
|
356
|
+
|
|
357
|
+
# A chunk is cut either at the batch size or as soon as its longest peptide would exceed
|
|
358
|
+
# the shortest by more than _LENGTH_BAND, so no peptide is padded much beyond its own
|
|
359
|
+
# length. Fixed-size chunks are not enough: the longest chunk of a length-sorted set holds
|
|
360
|
+
# thousands of ordinary peptides alongside the few long ones and inherits their window,
|
|
361
|
+
# which on a 20,000-peptide set cost 43 % of the throughput.
|
|
362
|
+
buckets: list[tuple[torch.Tensor, Dataset]] = []
|
|
363
|
+
start = 0
|
|
364
|
+
while start < len(order):
|
|
365
|
+
stop = min(start + batch_size, len(order))
|
|
366
|
+
band = sorted_lengths[start] + _LENGTH_BAND
|
|
367
|
+
within = int(np.searchsorted(sorted_lengths[start:stop], band, side="right"))
|
|
368
|
+
stop = start + max(within, 1)
|
|
369
|
+
padding = int(min(window, sorted_lengths[stop - 1] + reach))
|
|
370
|
+
chunk = order[start:stop]
|
|
371
|
+
buckets.append((torch.as_tensor(chunk), data.variant(chunk.tolist(), padding)))
|
|
372
|
+
start = stop
|
|
373
|
+
|
|
374
|
+
if len(buckets) == 1 and buckets[0][1].padding_length >= window:
|
|
375
|
+
return None # one chunk at the full window is what the plain path already does
|
|
376
|
+
return buckets
|
|
268
377
|
|
|
269
378
|
|
|
270
379
|
def supports_task_subset(model: torch.nn.Module) -> bool:
|
|
@@ -340,10 +449,30 @@ def _validate_epoch(
|
|
|
340
449
|
return float(val_loss / len(data_loader))
|
|
341
450
|
|
|
342
451
|
|
|
452
|
+
def _feature_batches(data: Dataset, batch_size: int, num_workers: int) -> Iterator[list]:
|
|
453
|
+
"""
|
|
454
|
+
Yield feature batches, assembled by the dataset itself where it can be.
|
|
455
|
+
|
|
456
|
+
A DeepLCDataset encodes a whole batch into one buffer per feature, which skips the
|
|
457
|
+
per-peptide tensors and the collate step a DataLoader needs. Worker processes and other
|
|
458
|
+
dataset types keep the DataLoader.
|
|
459
|
+
"""
|
|
460
|
+
if isinstance(data, DeepLCDataset) and num_workers == 0:
|
|
461
|
+
for start in range(0, len(data), batch_size):
|
|
462
|
+
stop = min(start + batch_size, len(data))
|
|
463
|
+
yield list(data.encode_batch(range(start, stop)))
|
|
464
|
+
else:
|
|
465
|
+
loader = DataLoader(data, batch_size=batch_size, shuffle=False, num_workers=num_workers)
|
|
466
|
+
for features, _ in loader:
|
|
467
|
+
yield list(features)
|
|
468
|
+
|
|
469
|
+
|
|
343
470
|
def _predict_epoch(
|
|
344
471
|
model: torch.nn.Module,
|
|
345
|
-
|
|
472
|
+
data: Dataset,
|
|
346
473
|
device: str,
|
|
474
|
+
batch_size: int = 512,
|
|
475
|
+
num_workers: int = 0,
|
|
347
476
|
show_progress: bool = False,
|
|
348
477
|
task_idx: Sequence[int] | None = None,
|
|
349
478
|
) -> torch.Tensor:
|
|
@@ -353,9 +482,14 @@ def _predict_epoch(
|
|
|
353
482
|
if task_idx is not None and supports_task_subset(model):
|
|
354
483
|
selected = torch.as_tensor(list(task_idx), dtype=torch.long, device=device)
|
|
355
484
|
predictions = []
|
|
485
|
+
total = int(np.ceil(len(data) / batch_size)) if hasattr(data, "__len__") else None
|
|
356
486
|
with torch.no_grad():
|
|
357
|
-
for features
|
|
358
|
-
|
|
487
|
+
for features in track(
|
|
488
|
+
_feature_batches(data, batch_size, num_workers),
|
|
489
|
+
description="Predicting...",
|
|
490
|
+
transient=True,
|
|
491
|
+
disable=not show_progress,
|
|
492
|
+
total=total,
|
|
359
493
|
):
|
|
360
494
|
features = [feature_tensor.to(device) for feature_tensor in features]
|
|
361
495
|
outputs = model(*features) if selected is None else model(*features, task_idx=selected)
|