deeplc 4.2.0__tar.gz → 4.3.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.2.0/deeplc.egg-info → deeplc-4.3.0}/PKG-INFO +1 -1
- deeplc-4.3.0/deeplc/calibration/__init__.py +29 -0
- deeplc-4.3.0/deeplc/calibration/multihead.py +365 -0
- deeplc-4.2.0/deeplc/calibration.py → deeplc-4.3.0/deeplc/calibration/simple.py +13 -4
- {deeplc-4.2.0 → deeplc-4.3.0}/deeplc/core.py +36 -66
- {deeplc-4.2.0 → deeplc-4.3.0/deeplc.egg-info}/PKG-INFO +1 -1
- {deeplc-4.2.0 → deeplc-4.3.0}/deeplc.egg-info/SOURCES.txt +4 -1
- {deeplc-4.2.0 → deeplc-4.3.0}/pyproject.toml +1 -1
- {deeplc-4.2.0 → deeplc-4.3.0}/tests/test_deduplication.py +6 -7
- deeplc-4.3.0/tests/test_multihead_calibration.py +351 -0
- {deeplc-4.2.0 → deeplc-4.3.0}/LICENSE +0 -0
- {deeplc-4.2.0 → deeplc-4.3.0}/MANIFEST.in +0 -0
- {deeplc-4.2.0 → deeplc-4.3.0}/README.md +0 -0
- {deeplc-4.2.0 → deeplc-4.3.0}/deeplc/__init__.py +0 -0
- {deeplc-4.2.0 → deeplc-4.3.0}/deeplc/__main__.py +0 -0
- {deeplc-4.2.0 → deeplc-4.3.0}/deeplc/_architecture.py +0 -0
- {deeplc-4.2.0 → deeplc-4.3.0}/deeplc/_features.py +0 -0
- {deeplc-4.2.0 → deeplc-4.3.0}/deeplc/_model_ops.py +0 -0
- {deeplc-4.2.0 → deeplc-4.3.0}/deeplc/_reference_selection.py +0 -0
- {deeplc-4.2.0 → deeplc-4.3.0}/deeplc/data.py +0 -0
- {deeplc-4.2.0 → deeplc-4.3.0}/deeplc/exceptions.py +0 -0
- {deeplc-4.2.0 → deeplc-4.3.0}/deeplc/gui.py +0 -0
- {deeplc-4.2.0 → deeplc-4.3.0}/deeplc/package_data/__init__.py +0 -0
- {deeplc-4.2.0 → deeplc-4.3.0}/deeplc/package_data/baseline_performance/__init__.py +0 -0
- {deeplc-4.2.0 → deeplc-4.3.0}/deeplc/package_data/baseline_performance/baseline_predictions.csv +0 -0
- {deeplc-4.2.0 → deeplc-4.3.0}/deeplc/package_data/examples/__init__.py +0 -0
- {deeplc-4.2.0 → deeplc-4.3.0}/deeplc/package_data/examples/example_psms.tsv.gz +0 -0
- {deeplc-4.2.0 → deeplc-4.3.0}/deeplc/package_data/gui_images/__init__.py +0 -0
- {deeplc-4.2.0 → deeplc-4.3.0}/deeplc/package_data/gui_images/config_icon.png +0 -0
- {deeplc-4.2.0 → deeplc-4.3.0}/deeplc/package_data/gui_images/deeplc_logo.png +0 -0
- {deeplc-4.2.0 → deeplc-4.3.0}/deeplc/package_data/gui_images/deeplc_logo.svg +0 -0
- {deeplc-4.2.0 → deeplc-4.3.0}/deeplc/package_data/gui_images/program_icon.png +0 -0
- {deeplc-4.2.0 → deeplc-4.3.0}/deeplc/package_data/models/__init__.py +0 -0
- {deeplc-4.2.0 → deeplc-4.3.0}/deeplc/package_data/models/full_hc_PXD005573_pub_1fd8363d9af9dcad3be7553c39396960.pt +0 -0
- {deeplc-4.2.0 → deeplc-4.3.0}/deeplc/package_data/models/full_hc_PXD005573_pub_8c22d89667368f2f02ad996469ba157e.pt +0 -0
- {deeplc-4.2.0 → deeplc-4.3.0}/deeplc/package_data/models/full_hc_PXD005573_pub_cb975cfdd4105f97efa0b3afffe075cc.pt +0 -0
- {deeplc-4.2.0 → deeplc-4.3.0}/deeplc/package_data/models/multitask_flexcnn_model.pt +0 -0
- {deeplc-4.2.0 → deeplc-4.3.0}/deeplc/package_data/models/multitask_model.pt +0 -0
- {deeplc-4.2.0 → deeplc-4.3.0}/deeplc/plot.py +0 -0
- {deeplc-4.2.0 → deeplc-4.3.0}/deeplc.egg-info/dependency_links.txt +0 -0
- {deeplc-4.2.0 → deeplc-4.3.0}/deeplc.egg-info/entry_points.txt +0 -0
- {deeplc-4.2.0 → deeplc-4.3.0}/deeplc.egg-info/requires.txt +0 -0
- {deeplc-4.2.0 → deeplc-4.3.0}/deeplc.egg-info/top_level.txt +0 -0
- {deeplc-4.2.0 → deeplc-4.3.0}/setup.cfg +0 -0
- {deeplc-4.2.0 → deeplc-4.3.0}/tests/test_calibration.py +0 -0
- {deeplc-4.2.0 → deeplc-4.3.0}/tests/test_core.py +0 -0
- {deeplc-4.2.0 → deeplc-4.3.0}/tests/test_features.py +0 -0
- {deeplc-4.2.0 → deeplc-4.3.0}/tests/test_flexcnn.py +0 -0
- {deeplc-4.2.0 → deeplc-4.3.0}/tests/test_model_ops.py +0 -0
- {deeplc-4.2.0 → deeplc-4.3.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.3.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>
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"""Calibration utilities."""
|
|
2
|
+
|
|
3
|
+
from deeplc.calibration.multihead import (
|
|
4
|
+
MultiHeadCalibration,
|
|
5
|
+
MultiHeadPiecewiseLinearCalibration,
|
|
6
|
+
MultiHeadRidgeCalibration,
|
|
7
|
+
MultiHeadSplineCalibration,
|
|
8
|
+
upgrade_calibration,
|
|
9
|
+
)
|
|
10
|
+
from deeplc.calibration.simple import (
|
|
11
|
+
Calibration,
|
|
12
|
+
IdentityCalibration,
|
|
13
|
+
PiecewiseLinearCalibration,
|
|
14
|
+
SplineTransformerCalibration,
|
|
15
|
+
)
|
|
16
|
+
from deeplc.exceptions import CalibrationError
|
|
17
|
+
|
|
18
|
+
__all__ = [
|
|
19
|
+
"Calibration",
|
|
20
|
+
"CalibrationError",
|
|
21
|
+
"IdentityCalibration",
|
|
22
|
+
"MultiHeadCalibration",
|
|
23
|
+
"MultiHeadPiecewiseLinearCalibration",
|
|
24
|
+
"MultiHeadRidgeCalibration",
|
|
25
|
+
"MultiHeadSplineCalibration",
|
|
26
|
+
"PiecewiseLinearCalibration",
|
|
27
|
+
"SplineTransformerCalibration",
|
|
28
|
+
"upgrade_calibration",
|
|
29
|
+
]
|
|
@@ -0,0 +1,365 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Multitask-aware calibration utilities.
|
|
3
|
+
|
|
4
|
+
Every class here maps the full ``(n, n_heads)`` prediction matrix of a multitask model onto a
|
|
5
|
+
single series of observed values, and is responsible for picking which head(s) to use itself:
|
|
6
|
+
``fit(target: (n,), source: (n, n_heads))`` / ``transform(source: (n, n_heads)) -> (n,)``. A
|
|
7
|
+
single-setup model still produces a matrix, just with ``n_heads=1``, so these classes are the
|
|
8
|
+
default way to calibrate any DeepLC model. See :mod:`deeplc.calibration.simple` for the naive,
|
|
9
|
+
single-series calibrations these delegate to.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import logging
|
|
15
|
+
from abc import ABC, abstractmethod
|
|
16
|
+
from typing import cast
|
|
17
|
+
|
|
18
|
+
import numpy as np
|
|
19
|
+
from sklearn.linear_model import RidgeCV # type: ignore[import]
|
|
20
|
+
|
|
21
|
+
from deeplc.calibration.simple import (
|
|
22
|
+
Calibration,
|
|
23
|
+
PiecewiseLinearCalibration,
|
|
24
|
+
SplineTransformerCalibration,
|
|
25
|
+
)
|
|
26
|
+
from deeplc.exceptions import CalibrationError
|
|
27
|
+
|
|
28
|
+
LOGGER = logging.getLogger(__name__)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class MultiHeadCalibration(ABC):
|
|
32
|
+
"""Abstract base class for a calibration that selects its own head(s) from a matrix."""
|
|
33
|
+
|
|
34
|
+
#: The best-correlating head, set by ``fit``. Meaningful for every implementer, including
|
|
35
|
+
#: :class:`MultiHeadRidgeCalibration`, which reports the single best head even though it
|
|
36
|
+
#: fits on several.
|
|
37
|
+
selected_model_head: int
|
|
38
|
+
|
|
39
|
+
@abstractmethod
|
|
40
|
+
def __init__(self, *args, **kwargs):
|
|
41
|
+
"""Initialize the calibration model."""
|
|
42
|
+
super().__init__()
|
|
43
|
+
|
|
44
|
+
@property
|
|
45
|
+
@abstractmethod
|
|
46
|
+
def is_fitted(self) -> bool:
|
|
47
|
+
"""Indicates whether the calibration model has been fitted."""
|
|
48
|
+
...
|
|
49
|
+
|
|
50
|
+
@abstractmethod
|
|
51
|
+
def fit(self, target: np.ndarray, source: np.ndarray) -> None:
|
|
52
|
+
"""Fit the calibration from the source matrix to target."""
|
|
53
|
+
...
|
|
54
|
+
|
|
55
|
+
@abstractmethod
|
|
56
|
+
def transform(self, source: np.ndarray) -> np.ndarray:
|
|
57
|
+
"""Transform the source matrix into the calibrated target space."""
|
|
58
|
+
...
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class _SingleHeadCalibration(MultiHeadCalibration):
|
|
62
|
+
"""
|
|
63
|
+
Shared logic for wrapping one naive, single-series :class:`Calibration`.
|
|
64
|
+
|
|
65
|
+
Ranks the heads of the matrix by Pearson correlation to the target, fits ``self._inner`` on
|
|
66
|
+
the winner, and transforms by picking that same column. Subclasses only need to construct
|
|
67
|
+
``self._inner``.
|
|
68
|
+
"""
|
|
69
|
+
|
|
70
|
+
_inner: Calibration
|
|
71
|
+
|
|
72
|
+
@property
|
|
73
|
+
def is_fitted(self) -> bool:
|
|
74
|
+
"""True if the wrapped calibration has been fitted."""
|
|
75
|
+
return self._inner.is_fitted
|
|
76
|
+
|
|
77
|
+
def fit(self, target: np.ndarray, source: np.ndarray) -> None:
|
|
78
|
+
"""
|
|
79
|
+
Select the best-correlating head and fit the wrapped calibration on it.
|
|
80
|
+
|
|
81
|
+
Parameters
|
|
82
|
+
----------
|
|
83
|
+
target
|
|
84
|
+
Observed retention times of the reference, shape ``(n,)``.
|
|
85
|
+
source
|
|
86
|
+
Reference predictions for every head, shape ``(n, n_heads_total)``. A 1-D array is
|
|
87
|
+
accepted and treated as a single head, so a single-task model still works.
|
|
88
|
+
|
|
89
|
+
"""
|
|
90
|
+
source = np.asarray(source, dtype=np.float64)
|
|
91
|
+
if source.ndim == 1:
|
|
92
|
+
source = source[:, None]
|
|
93
|
+
target = np.asarray(target, dtype=np.float64).ravel()
|
|
94
|
+
if source.shape[0] != target.shape[0]:
|
|
95
|
+
raise CalibrationError(
|
|
96
|
+
f"source has {source.shape[0]} rows and target {target.shape[0]}"
|
|
97
|
+
)
|
|
98
|
+
finite = np.isfinite(target) & np.isfinite(source).all(axis=1)
|
|
99
|
+
if int(finite.sum()) < 3:
|
|
100
|
+
raise CalibrationError("Fewer than three reference points with finite values.")
|
|
101
|
+
source, target = source[finite], target[finite]
|
|
102
|
+
|
|
103
|
+
order = _rank_heads_by_correlation(source, target)
|
|
104
|
+
self.selected_model_head = int(order[0])
|
|
105
|
+
self._inner.fit(
|
|
106
|
+
target=target.astype(np.float32),
|
|
107
|
+
source=source[:, self.selected_model_head].astype(np.float32),
|
|
108
|
+
)
|
|
109
|
+
|
|
110
|
+
def transform(self, source: np.ndarray) -> np.ndarray:
|
|
111
|
+
"""
|
|
112
|
+
Select the fitted head from the matrix and transform it.
|
|
113
|
+
|
|
114
|
+
Parameters
|
|
115
|
+
----------
|
|
116
|
+
source
|
|
117
|
+
Predictions for every head, shape ``(n, n_heads_total)``, as returned by
|
|
118
|
+
``predict(..., return_matrix=True)``.
|
|
119
|
+
|
|
120
|
+
"""
|
|
121
|
+
if not self.is_fitted:
|
|
122
|
+
raise CalibrationError("The model has not been fitted yet. Call fit() first.")
|
|
123
|
+
source = np.asarray(source, dtype=np.float64)
|
|
124
|
+
if source.ndim == 1:
|
|
125
|
+
source = source[:, None]
|
|
126
|
+
head = self.selected_model_head
|
|
127
|
+
if source.shape[1] <= head:
|
|
128
|
+
raise CalibrationError(
|
|
129
|
+
f"source has {source.shape[1]} heads, but the calibration was fitted on a model "
|
|
130
|
+
f"with at least {head + 1}."
|
|
131
|
+
)
|
|
132
|
+
if source.shape[0] == 0:
|
|
133
|
+
return np.array([])
|
|
134
|
+
return np.asarray(
|
|
135
|
+
self._inner.transform(source[:, head].astype(np.float32)), dtype=np.float64
|
|
136
|
+
)
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
class MultiHeadPiecewiseLinearCalibration(_SingleHeadCalibration):
|
|
140
|
+
"""Piece-wise linear calibration on whichever head correlates best with the reference."""
|
|
141
|
+
|
|
142
|
+
def __init__(
|
|
143
|
+
self,
|
|
144
|
+
number_of_splits: int = 10,
|
|
145
|
+
extrapolate: bool = True,
|
|
146
|
+
use_median: bool = False,
|
|
147
|
+
min_samples_per_segment: int = 20,
|
|
148
|
+
) -> None:
|
|
149
|
+
"""
|
|
150
|
+
Piece-wise linear calibration on whichever head correlates best with the reference.
|
|
151
|
+
|
|
152
|
+
Parameters
|
|
153
|
+
----------
|
|
154
|
+
number_of_splits : int
|
|
155
|
+
Number of segments to split the source value range into.
|
|
156
|
+
More segments allow more flexibility but may lead to overfitting.
|
|
157
|
+
extrapolate : bool
|
|
158
|
+
If True, allows extrapolation outside the fitted source value range.
|
|
159
|
+
If False, clips input values to the fitted range.
|
|
160
|
+
use_median : bool
|
|
161
|
+
If True, uses the median of each segment to define anchors. If False, uses the mean.
|
|
162
|
+
min_samples_per_segment : int
|
|
163
|
+
Minimum number of samples required for a segment to contribute an anchor.
|
|
164
|
+
Segments with fewer samples are skipped, which helps avoid unstable anchors in
|
|
165
|
+
sparse regions when using many splits.
|
|
166
|
+
|
|
167
|
+
"""
|
|
168
|
+
super().__init__()
|
|
169
|
+
self._inner = PiecewiseLinearCalibration(
|
|
170
|
+
number_of_splits=number_of_splits,
|
|
171
|
+
extrapolate=extrapolate,
|
|
172
|
+
use_median=use_median,
|
|
173
|
+
min_samples_per_segment=min_samples_per_segment,
|
|
174
|
+
)
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
class MultiHeadSplineCalibration(_SingleHeadCalibration):
|
|
178
|
+
"""Spline-based calibration on whichever head correlates best with the reference."""
|
|
179
|
+
|
|
180
|
+
def __init__(self) -> None:
|
|
181
|
+
"""Initialize MultiHeadSplineCalibration."""
|
|
182
|
+
super().__init__()
|
|
183
|
+
self._inner = SplineTransformerCalibration()
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
class MultiHeadRidgeCalibration(MultiHeadCalibration):
|
|
187
|
+
"""
|
|
188
|
+
Calibrate a multitask model against several of its LC-setup heads at once.
|
|
189
|
+
|
|
190
|
+
Heads are ranked by Pearson correlation to the reference, the ``n_heads`` best are each
|
|
191
|
+
calibrated with :class:`~deeplc.calibration.simple.SplineTransformerCalibration`, and a ridge
|
|
192
|
+
regression maps the calibrated estimates onto the observed retention times. Never fits more
|
|
193
|
+
head weights than half the reference size. For a single-task model (one head) this reduces to
|
|
194
|
+
a spline followed by a linear rescaling.
|
|
195
|
+
|
|
196
|
+
Parameters
|
|
197
|
+
----------
|
|
198
|
+
n_heads
|
|
199
|
+
How many of the best-correlating heads to combine.
|
|
200
|
+
alphas
|
|
201
|
+
Ridge strengths offered to the internal cross-validation.
|
|
202
|
+
|
|
203
|
+
"""
|
|
204
|
+
|
|
205
|
+
def __init__(self, n_heads: int = 80, alphas: np.ndarray | None = None) -> None:
|
|
206
|
+
"""Initialize MultiHeadRidgeCalibration."""
|
|
207
|
+
super().__init__()
|
|
208
|
+
if n_heads < 1:
|
|
209
|
+
raise ValueError(f"n_heads must be at least 1, got {n_heads}")
|
|
210
|
+
self.n_heads = n_heads
|
|
211
|
+
self.alphas = np.logspace(-3, 6, 19) if alphas is None else np.asarray(alphas)
|
|
212
|
+
self._head_idx: np.ndarray | None = None
|
|
213
|
+
self._head_calibrations: list[SplineTransformerCalibration] = []
|
|
214
|
+
self._ridge = None
|
|
215
|
+
|
|
216
|
+
@property
|
|
217
|
+
def is_fitted(self) -> bool:
|
|
218
|
+
"""True once the heads are selected, calibrated and weighted."""
|
|
219
|
+
return self._head_idx is not None and self._ridge is not None
|
|
220
|
+
|
|
221
|
+
def fit(self, target: np.ndarray, source: np.ndarray) -> None:
|
|
222
|
+
"""
|
|
223
|
+
Select, calibrate and weight the heads.
|
|
224
|
+
|
|
225
|
+
Parameters
|
|
226
|
+
----------
|
|
227
|
+
target
|
|
228
|
+
Observed retention times of the reference, shape ``(n,)``.
|
|
229
|
+
source
|
|
230
|
+
Reference predictions for every head, shape ``(n, n_heads_total)``. A 1-D array is
|
|
231
|
+
accepted and treated as a single head, so a single-task model still works.
|
|
232
|
+
|
|
233
|
+
"""
|
|
234
|
+
source = np.asarray(source, dtype=np.float64)
|
|
235
|
+
if source.ndim == 1:
|
|
236
|
+
source = source[:, None]
|
|
237
|
+
target = np.asarray(target, dtype=np.float64).ravel()
|
|
238
|
+
if source.shape[0] != target.shape[0]:
|
|
239
|
+
raise CalibrationError(
|
|
240
|
+
f"source has {source.shape[0]} rows and target {target.shape[0]}"
|
|
241
|
+
)
|
|
242
|
+
finite = np.isfinite(target) & np.isfinite(source).all(axis=1)
|
|
243
|
+
if int(finite.sum()) < 3:
|
|
244
|
+
raise CalibrationError("Fewer than three reference points with finite values.")
|
|
245
|
+
source, target = source[finite], target[finite]
|
|
246
|
+
|
|
247
|
+
order = _rank_heads_by_correlation(source, target)
|
|
248
|
+
# never fit more weights than half the reference: a 230-peptide reference cannot support
|
|
249
|
+
# eighty of them, and the ridge would be extrapolating its own regularisation
|
|
250
|
+
n_heads = int(min(self.n_heads, source.shape[1], max(1, len(target) // 2)))
|
|
251
|
+
self._head_idx = order[:n_heads]
|
|
252
|
+
self.selected_model_head = int(order[0])
|
|
253
|
+
|
|
254
|
+
calibrated = np.empty((len(target), n_heads), dtype=np.float64)
|
|
255
|
+
self._head_calibrations = []
|
|
256
|
+
for position, head in enumerate(self._head_idx):
|
|
257
|
+
head_calibration = SplineTransformerCalibration()
|
|
258
|
+
column = source[:, head].astype(np.float32)
|
|
259
|
+
head_calibration.fit(target=target.astype(np.float32), source=column)
|
|
260
|
+
calibrated[:, position] = np.asarray(
|
|
261
|
+
head_calibration.transform(column), dtype=np.float64
|
|
262
|
+
)
|
|
263
|
+
self._head_calibrations.append(head_calibration)
|
|
264
|
+
|
|
265
|
+
n_splits = int(min(5, max(2, len(target) // 20)))
|
|
266
|
+
self._ridge = RidgeCV(alphas=self.alphas, cv=n_splits).fit(calibrated, target)
|
|
267
|
+
LOGGER.info(
|
|
268
|
+
"Calibrated on %d of %d heads with ridge strength %.4g; head %d correlates best.",
|
|
269
|
+
n_heads,
|
|
270
|
+
source.shape[1],
|
|
271
|
+
float(getattr(self._ridge, "alpha_", float("nan"))),
|
|
272
|
+
self.selected_model_head,
|
|
273
|
+
)
|
|
274
|
+
|
|
275
|
+
def transform(self, source: np.ndarray) -> np.ndarray:
|
|
276
|
+
"""
|
|
277
|
+
Calibrate predictions of the model this calibration was fitted with.
|
|
278
|
+
|
|
279
|
+
Parameters
|
|
280
|
+
----------
|
|
281
|
+
source
|
|
282
|
+
Predictions for every head, shape ``(n, n_heads_total)``, as returned by
|
|
283
|
+
``predict(..., return_matrix=True)``.
|
|
284
|
+
|
|
285
|
+
"""
|
|
286
|
+
if not self.is_fitted:
|
|
287
|
+
raise CalibrationError("The model has not been fitted yet. Call fit() first.")
|
|
288
|
+
source = np.asarray(source, dtype=np.float64)
|
|
289
|
+
if source.ndim == 1:
|
|
290
|
+
source = source[:, None]
|
|
291
|
+
head_idx = cast(np.ndarray, self._head_idx)
|
|
292
|
+
if source.shape[1] <= int(head_idx.max()):
|
|
293
|
+
raise CalibrationError(
|
|
294
|
+
f"source has {source.shape[1]} heads, but the calibration was fitted on a model "
|
|
295
|
+
f"with at least {int(head_idx.max()) + 1}."
|
|
296
|
+
)
|
|
297
|
+
if source.shape[0] == 0:
|
|
298
|
+
return np.array([])
|
|
299
|
+
calibrated = np.column_stack(
|
|
300
|
+
[
|
|
301
|
+
np.asarray(cal.transform(source[:, head].astype(np.float32)), dtype=np.float64)
|
|
302
|
+
for cal, head in zip(self._head_calibrations, head_idx, strict=True)
|
|
303
|
+
]
|
|
304
|
+
)
|
|
305
|
+
return np.asarray(self._ridge.predict(calibrated), dtype=np.float64)
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def upgrade_calibration(calibration: Calibration | MultiHeadCalibration) -> MultiHeadCalibration:
|
|
309
|
+
"""
|
|
310
|
+
Wrap a naive, single-series calibration in its matching ``MultiHeadCalibration``.
|
|
311
|
+
|
|
312
|
+
A ``MultiHeadCalibration`` instance is returned unchanged. A naive
|
|
313
|
+
:class:`~deeplc.calibration.simple.Calibration` must not be fitted yet: a fitted instance
|
|
314
|
+
carries no record of which head it was fit on, so there is nothing to wrap it around.
|
|
315
|
+
|
|
316
|
+
Parameters
|
|
317
|
+
----------
|
|
318
|
+
calibration
|
|
319
|
+
The calibration to wrap, naive or already multi-head.
|
|
320
|
+
|
|
321
|
+
Returns
|
|
322
|
+
-------
|
|
323
|
+
MultiHeadCalibration
|
|
324
|
+
``calibration`` itself if it already is one, otherwise a new wrapper around it.
|
|
325
|
+
|
|
326
|
+
"""
|
|
327
|
+
if isinstance(calibration, MultiHeadCalibration):
|
|
328
|
+
return calibration
|
|
329
|
+
if not isinstance(calibration, Calibration):
|
|
330
|
+
raise ValueError(
|
|
331
|
+
f"Expected calibration to be of type `Calibration` or `MultiHeadCalibration`, got "
|
|
332
|
+
f"{type(calibration)}"
|
|
333
|
+
)
|
|
334
|
+
if not isinstance(calibration, (PiecewiseLinearCalibration, SplineTransformerCalibration)):
|
|
335
|
+
raise ValueError(
|
|
336
|
+
f"No MultiHeadCalibration counterpart is known for {type(calibration).__name__}."
|
|
337
|
+
)
|
|
338
|
+
if calibration.is_fitted:
|
|
339
|
+
raise CalibrationError(
|
|
340
|
+
"A fitted, naive Calibration cannot be upgraded to a MultiHeadCalibration: it "
|
|
341
|
+
"carries no record of which head it was fit on. Fit a MultiHead*Calibration instead."
|
|
342
|
+
)
|
|
343
|
+
if isinstance(calibration, PiecewiseLinearCalibration):
|
|
344
|
+
return MultiHeadPiecewiseLinearCalibration(
|
|
345
|
+
number_of_splits=calibration.number_of_splits,
|
|
346
|
+
extrapolate=calibration.extrapolate,
|
|
347
|
+
use_median=calibration.use_median,
|
|
348
|
+
min_samples_per_segment=calibration.min_samples_per_segment,
|
|
349
|
+
)
|
|
350
|
+
return MultiHeadSplineCalibration()
|
|
351
|
+
|
|
352
|
+
|
|
353
|
+
def _rank_heads_by_correlation(source: np.ndarray, target: np.ndarray) -> np.ndarray:
|
|
354
|
+
"""
|
|
355
|
+
Head indices by decreasing Pearson correlation with the target, in one pass.
|
|
356
|
+
|
|
357
|
+
Vectorised because a fused-trunk multitask model can have thousands of heads to rank at once.
|
|
358
|
+
"""
|
|
359
|
+
centred = source - source.mean(axis=0)
|
|
360
|
+
target_centred = target - target.mean()
|
|
361
|
+
with np.errstate(invalid="ignore", divide="ignore"):
|
|
362
|
+
denominator = np.sqrt((centred**2).sum(axis=0) * (target_centred**2).sum())
|
|
363
|
+
correlation = (centred * target_centred[:, None]).sum(axis=0) / denominator
|
|
364
|
+
correlation = np.where(np.isfinite(correlation), correlation, -np.inf)
|
|
365
|
+
return np.argsort(-correlation)
|
|
@@ -1,4 +1,11 @@
|
|
|
1
|
-
"""
|
|
1
|
+
"""
|
|
2
|
+
Naive calibration utilities.
|
|
3
|
+
|
|
4
|
+
Every class here maps a single series of raw predictions onto a single series of observed
|
|
5
|
+
values: ``fit(target: (n,), source: (n,))`` / ``transform(source: (n,)) -> (n,)``. None of them
|
|
6
|
+
know about multitask models or LC-setup heads; see :mod:`deeplc.calibration.multihead` for the
|
|
7
|
+
classes that select a head from a ``(n, n_heads)`` prediction matrix and delegate to one of these.
|
|
8
|
+
"""
|
|
2
9
|
|
|
3
10
|
from __future__ import annotations
|
|
4
11
|
|
|
@@ -17,9 +24,7 @@ LOGGER = logging.getLogger(__name__)
|
|
|
17
24
|
|
|
18
25
|
|
|
19
26
|
class Calibration(ABC):
|
|
20
|
-
"""Abstract base class for calibration."""
|
|
21
|
-
|
|
22
|
-
selected_model_head: int | None = None
|
|
27
|
+
"""Abstract base class for a single-series calibration."""
|
|
23
28
|
|
|
24
29
|
@abstractmethod
|
|
25
30
|
def __init__(self, *args, **kwargs):
|
|
@@ -46,6 +51,10 @@ class Calibration(ABC):
|
|
|
46
51
|
class IdentityCalibration(Calibration):
|
|
47
52
|
"""No calibration; returns inputs unchanged."""
|
|
48
53
|
|
|
54
|
+
def __init__(self) -> None:
|
|
55
|
+
"""Initialize IdentityCalibration."""
|
|
56
|
+
super().__init__()
|
|
57
|
+
|
|
49
58
|
@property
|
|
50
59
|
def is_fitted(self) -> bool:
|
|
51
60
|
"""Always fitted; identity calibration requires no fitting."""
|
|
@@ -15,7 +15,9 @@ from deeplc import _model_ops
|
|
|
15
15
|
from deeplc._reference_selection import deduplicate_psms, select_reference_psms
|
|
16
16
|
from deeplc.calibration import (
|
|
17
17
|
Calibration,
|
|
18
|
-
|
|
18
|
+
MultiHeadCalibration,
|
|
19
|
+
MultiHeadRidgeCalibration,
|
|
20
|
+
upgrade_calibration,
|
|
19
21
|
)
|
|
20
22
|
from deeplc.data import DeepLCDataset, split_datasets
|
|
21
23
|
|
|
@@ -141,11 +143,11 @@ def _default_task_idx(model: torch.nn.Module) -> int:
|
|
|
141
143
|
def calibrate(
|
|
142
144
|
psm_list_reference: PSMList,
|
|
143
145
|
model: torch.nn.Module | PathLike | str | None = None,
|
|
144
|
-
calibration: Calibration | None = None,
|
|
146
|
+
calibration: Calibration | MultiHeadCalibration | None = None,
|
|
145
147
|
predict_kwargs: dict | None = None,
|
|
146
|
-
) ->
|
|
148
|
+
) -> MultiHeadCalibration:
|
|
147
149
|
"""
|
|
148
|
-
Return a `
|
|
150
|
+
Return a `MultiHeadCalibration` instance fitted to the reference dataset.
|
|
149
151
|
|
|
150
152
|
Parameters
|
|
151
153
|
----------
|
|
@@ -154,13 +156,19 @@ def calibrate(
|
|
|
154
156
|
model
|
|
155
157
|
Trained model or path to model file.
|
|
156
158
|
calibration
|
|
157
|
-
Calibration instance to use. If None,
|
|
159
|
+
Calibration instance to use. If None, MultiHeadRidgeCalibration is used. A model with a
|
|
160
|
+
single LC setup still predicts a one-column matrix, so this default also covers
|
|
161
|
+
single-task models. See ``deeplc.calibration.multihead`` for lighter alternatives (e.g.
|
|
162
|
+
``MultiHeadSplineCalibration``) when the ridge over many heads isn't the right fit, for
|
|
163
|
+
example for a custom, non-multitask model. An unfitted naive
|
|
164
|
+
:class:`~deeplc.calibration.simple.Calibration` is accepted too and upgraded to its
|
|
165
|
+
``MultiHead*Calibration`` counterpart; see :func:`deeplc.calibration.upgrade_calibration`.
|
|
158
166
|
predict_kwargs
|
|
159
167
|
Additional keyword arguments to pass to the prediction function.
|
|
160
168
|
|
|
161
169
|
Returns
|
|
162
170
|
-------
|
|
163
|
-
|
|
171
|
+
MultiHeadCalibration
|
|
164
172
|
Fitted calibration instance.
|
|
165
173
|
|
|
166
174
|
"""
|
|
@@ -168,20 +176,17 @@ def calibrate(
|
|
|
168
176
|
# peptidoform once per spectrum it was identified in, each time with a different observed
|
|
169
177
|
# retention time, which gives the fit conflicting targets and weighs peptidoforms by how
|
|
170
178
|
# often they happened to be identified. A caller who wants the repeats to count fits a
|
|
171
|
-
#
|
|
179
|
+
# MultiHeadCalibration itself and passes it in already fitted.
|
|
172
180
|
psm_list_reference = deduplicate_psms(psm_list_reference)
|
|
173
181
|
|
|
174
|
-
# Get calibration
|
|
175
182
|
if calibration is None:
|
|
176
|
-
LOGGER.debug("No calibration provided, using
|
|
177
|
-
calibration =
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
f"Expected calibration to be of type `Calibration`, got {type(calibration)}"
|
|
181
|
-
)
|
|
183
|
+
LOGGER.debug("No calibration provided, using MultiHeadRidgeCalibration by default.")
|
|
184
|
+
calibration = MultiHeadRidgeCalibration()
|
|
185
|
+
else:
|
|
186
|
+
calibration = upgrade_calibration(calibration)
|
|
182
187
|
if calibration.is_fitted:
|
|
183
188
|
LOGGER.warning(
|
|
184
|
-
"Provided
|
|
189
|
+
"Provided calibration is already fitted. Refitting will overwrite existing fit."
|
|
185
190
|
)
|
|
186
191
|
|
|
187
192
|
if any(psm_list_reference["is_decoy"]):
|
|
@@ -199,15 +204,11 @@ def calibrate(
|
|
|
199
204
|
return_matrix=True,
|
|
200
205
|
)
|
|
201
206
|
|
|
202
|
-
# Fit calibration
|
|
207
|
+
# Fit calibration; every MultiHeadCalibration takes the whole matrix and selects its own
|
|
208
|
+
# head(s), setting selected_model_head itself for callers that want to know which setup came
|
|
209
|
+
# out on top.
|
|
203
210
|
LOGGER.debug("Fitting calibration...")
|
|
204
211
|
target_rt_cal = np.array(psm_list_reference["retention_time"], dtype=np.float32)
|
|
205
|
-
|
|
206
|
-
# Select the best head for calibration if the model predicts for multiple LC setups
|
|
207
|
-
if source_rt_cal.shape[1] > 1:
|
|
208
|
-
calibration.selected_model_head = _best_correlating_head(source_rt_cal, target_rt_cal)
|
|
209
|
-
source_rt_cal = source_rt_cal[:, calibration.selected_model_head or 0]
|
|
210
|
-
|
|
211
212
|
calibration.fit(target=target_rt_cal, source=source_rt_cal)
|
|
212
213
|
|
|
213
214
|
return calibration
|
|
@@ -217,7 +218,7 @@ def predict_and_calibrate(
|
|
|
217
218
|
psm_list: PSMList | list[PSM | Peptidoform | str],
|
|
218
219
|
psm_list_reference: PSMList | list[PSM | Peptidoform | str] | None = None,
|
|
219
220
|
model: torch.nn.Module | PathLike | str | None = None,
|
|
220
|
-
calibration: Calibration | None = None,
|
|
221
|
+
calibration: Calibration | MultiHeadCalibration | None = None,
|
|
221
222
|
predict_kwargs: dict | None = None,
|
|
222
223
|
) -> np.ndarray:
|
|
223
224
|
"""
|
|
@@ -235,7 +236,12 @@ def predict_and_calibrate(
|
|
|
235
236
|
model
|
|
236
237
|
Trained model or path to model file.
|
|
237
238
|
calibration
|
|
238
|
-
Calibration instance to use. If None,
|
|
239
|
+
Calibration instance to use. If None, MultiHeadRidgeCalibration is used. See
|
|
240
|
+
``deeplc.calibration.multihead`` for lighter alternatives. An unfitted naive
|
|
241
|
+
:class:`~deeplc.calibration.simple.Calibration` is accepted too and upgraded to its
|
|
242
|
+
``MultiHead*Calibration`` counterpart; see :func:`deeplc.calibration.upgrade_calibration`.
|
|
243
|
+
A fitted one is not, since it carries no record of which head it was fit on: fit a
|
|
244
|
+
``MultiHead*Calibration`` instead to pass in an already fitted calibration.
|
|
239
245
|
predict_kwargs
|
|
240
246
|
Additional keyword arguments to pass to the prediction function.
|
|
241
247
|
|
|
@@ -262,10 +268,8 @@ def predict_and_calibrate(
|
|
|
262
268
|
return_matrix=True,
|
|
263
269
|
)
|
|
264
270
|
|
|
265
|
-
if calibration is not None
|
|
266
|
-
|
|
267
|
-
f"Expected calibration to be of type `Calibration`, got {type(calibration)}"
|
|
268
|
-
)
|
|
271
|
+
if calibration is not None:
|
|
272
|
+
calibration = upgrade_calibration(calibration)
|
|
269
273
|
|
|
270
274
|
# Fit calibration if not already fitted
|
|
271
275
|
if calibration is None or not calibration.is_fitted:
|
|
@@ -278,21 +282,8 @@ def predict_and_calibrate(
|
|
|
278
282
|
else:
|
|
279
283
|
LOGGER.info("Calibration is already fitted, skipping fitting step.")
|
|
280
284
|
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
raise ValueError(
|
|
284
|
-
"Calibration has no selected_model_head. Either use calibrate() to fit it, "
|
|
285
|
-
"or set calibration.selected_model_head manually before calling "
|
|
286
|
-
"predict_and_calibrate() with a multitask model."
|
|
287
|
-
)
|
|
288
|
-
predicted_rt = predicted_rt[:, calibration.selected_model_head]
|
|
289
|
-
else:
|
|
290
|
-
predicted_rt = predicted_rt[:, 0]
|
|
291
|
-
|
|
292
|
-
# Apply calibration to predictions
|
|
293
|
-
calibrated_rt = calibration.transform(predicted_rt)
|
|
294
|
-
|
|
295
|
-
return calibrated_rt
|
|
285
|
+
# Every MultiHeadCalibration selects its own head(s), so it takes the matrix as it is.
|
|
286
|
+
return calibration.transform(predicted_rt)
|
|
296
287
|
|
|
297
288
|
|
|
298
289
|
def finetune_and_predict(
|
|
@@ -348,9 +339,10 @@ def finetune_and_predict(
|
|
|
348
339
|
psm_list=parsed_psm_list,
|
|
349
340
|
model=finetuned_model,
|
|
350
341
|
predict_kwargs=predict_kwargs,
|
|
342
|
+
return_matrix=True,
|
|
351
343
|
)
|
|
352
344
|
|
|
353
|
-
# Fit calibration
|
|
345
|
+
# Fit calibration to the fine-tuned model predictions
|
|
354
346
|
LOGGER.info("Fitting calibration with fine-tuned model predictions...")
|
|
355
347
|
calibration = calibrate(
|
|
356
348
|
psm_list_reference=parsed_psm_list_ref,
|
|
@@ -716,25 +708,3 @@ def _parse_psms(psm_list: PSMList | list[PSM | Peptidoform | str]) -> PSMList:
|
|
|
716
708
|
raise ValueError("List must contain either PSMs, Peptidoforms, or strings.")
|
|
717
709
|
else:
|
|
718
710
|
raise ValueError("Input must be a PSMList or a list of PSMs, Peptidoforms, or strings.")
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
def _best_correlating_head(predictions: np.ndarray, targets: np.ndarray) -> int:
|
|
722
|
-
"""Return the head index with highest valid Pearson correlation to targets."""
|
|
723
|
-
best_idx = 0
|
|
724
|
-
best_corr = float("-inf")
|
|
725
|
-
|
|
726
|
-
for idx in range(predictions.shape[1]):
|
|
727
|
-
pred_col = predictions[:, idx]
|
|
728
|
-
mask = np.isfinite(pred_col) & np.isfinite(targets)
|
|
729
|
-
if mask.sum() < 3:
|
|
730
|
-
continue
|
|
731
|
-
pred_masked = pred_col[mask]
|
|
732
|
-
target_masked = targets[mask]
|
|
733
|
-
if np.std(pred_masked) < 1e-8 or np.std(target_masked) < 1e-8:
|
|
734
|
-
continue
|
|
735
|
-
corr = np.corrcoef(pred_masked, target_masked)[0, 1]
|
|
736
|
-
if np.isfinite(corr) and corr > best_corr:
|
|
737
|
-
best_corr = corr
|
|
738
|
-
best_idx = idx
|
|
739
|
-
|
|
740
|
-
return best_idx
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: deeplc
|
|
3
|
-
Version: 4.
|
|
3
|
+
Version: 4.3.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>
|
|
@@ -8,7 +8,6 @@ deeplc/_architecture.py
|
|
|
8
8
|
deeplc/_features.py
|
|
9
9
|
deeplc/_model_ops.py
|
|
10
10
|
deeplc/_reference_selection.py
|
|
11
|
-
deeplc/calibration.py
|
|
12
11
|
deeplc/core.py
|
|
13
12
|
deeplc/data.py
|
|
14
13
|
deeplc/exceptions.py
|
|
@@ -20,6 +19,9 @@ deeplc.egg-info/dependency_links.txt
|
|
|
20
19
|
deeplc.egg-info/entry_points.txt
|
|
21
20
|
deeplc.egg-info/requires.txt
|
|
22
21
|
deeplc.egg-info/top_level.txt
|
|
22
|
+
deeplc/calibration/__init__.py
|
|
23
|
+
deeplc/calibration/multihead.py
|
|
24
|
+
deeplc/calibration/simple.py
|
|
23
25
|
deeplc/package_data/__init__.py
|
|
24
26
|
deeplc/package_data/baseline_performance/__init__.py
|
|
25
27
|
deeplc/package_data/baseline_performance/baseline_predictions.csv
|
|
@@ -42,4 +44,5 @@ tests/test_deduplication.py
|
|
|
42
44
|
tests/test_features.py
|
|
43
45
|
tests/test_flexcnn.py
|
|
44
46
|
tests/test_model_ops.py
|
|
47
|
+
tests/test_multihead_calibration.py
|
|
45
48
|
tests/test_reference_selection.py
|
|
@@ -9,7 +9,7 @@ from psm_utils import PSM, PSMList
|
|
|
9
9
|
|
|
10
10
|
from deeplc import core
|
|
11
11
|
from deeplc._reference_selection import deduplicate_psms
|
|
12
|
-
from deeplc.calibration import
|
|
12
|
+
from deeplc.calibration import MultiHeadSplineCalibration
|
|
13
13
|
|
|
14
14
|
_PEPTIDES = [
|
|
15
15
|
"AAGPSLSHTSGGTQSK",
|
|
@@ -164,7 +164,7 @@ def test_calibrate_always_uses_the_first_observations():
|
|
|
164
164
|
|
|
165
165
|
calibration = core.calibrate(reference, predict_kwargs={"device": "cpu"})
|
|
166
166
|
predicted = core.predict(targets, return_matrix=True)
|
|
167
|
-
calibrated = calibration.transform(predicted
|
|
167
|
+
calibrated = calibration.transform(predicted)
|
|
168
168
|
|
|
169
169
|
assert np.isfinite(calibrated).all()
|
|
170
170
|
clean_low, clean_high = 5.0, 5.0 + 3.0 * (len(_PEPTIDES) - 1)
|
|
@@ -177,16 +177,15 @@ def test_a_prefitted_calibration_is_the_way_to_keep_the_repeats():
|
|
|
177
177
|
The escape hatch for the rare caller who wants every reference PSM to count.
|
|
178
178
|
|
|
179
179
|
``calibrate`` deduplicates unconditionally, so a caller who wants the repeats weighed fits
|
|
180
|
-
a ``
|
|
181
|
-
it as given instead of fitting one.
|
|
180
|
+
a ``MultiHeadCalibration`` on its own targets and passes it in; ``predict_and_calibrate`` then
|
|
181
|
+
uses it as given instead of fitting one.
|
|
182
182
|
"""
|
|
183
183
|
reference = _reference_with_duplicates()
|
|
184
184
|
psm_list = _psms([(s, None) for s in _PEPTIDES])
|
|
185
185
|
|
|
186
186
|
source = core.predict(reference, predict_kwargs={"device": "cpu"}, return_matrix=True)
|
|
187
|
-
own =
|
|
188
|
-
own.
|
|
189
|
-
own.fit(target=np.array(reference["retention_time"], dtype=np.float32), source=source[:, 0])
|
|
187
|
+
own = MultiHeadSplineCalibration()
|
|
188
|
+
own.fit(target=np.array(reference["retention_time"], dtype=np.float32), source=source)
|
|
190
189
|
|
|
191
190
|
kept = core.predict_and_calibrate(
|
|
192
191
|
psm_list, psm_list_reference=reference, calibration=own, predict_kwargs={"device": "cpu"}
|
|
@@ -0,0 +1,351 @@
|
|
|
1
|
+
"""Calibrating against several LC setups at once instead of the single best one."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import numpy as np
|
|
6
|
+
import pytest
|
|
7
|
+
from psm_utils import PSM, PSMList
|
|
8
|
+
|
|
9
|
+
from deeplc import core
|
|
10
|
+
from deeplc.calibration import (
|
|
11
|
+
Calibration,
|
|
12
|
+
IdentityCalibration,
|
|
13
|
+
MultiHeadCalibration,
|
|
14
|
+
MultiHeadPiecewiseLinearCalibration,
|
|
15
|
+
MultiHeadRidgeCalibration,
|
|
16
|
+
MultiHeadSplineCalibration,
|
|
17
|
+
PiecewiseLinearCalibration,
|
|
18
|
+
SplineTransformerCalibration,
|
|
19
|
+
upgrade_calibration,
|
|
20
|
+
)
|
|
21
|
+
from deeplc.exceptions import CalibrationError
|
|
22
|
+
|
|
23
|
+
_PEPTIDES = [
|
|
24
|
+
"AAGPSLSHTSGGTQSK",
|
|
25
|
+
"AGFAGDDAPR",
|
|
26
|
+
"AIQEYNQDK",
|
|
27
|
+
"AAYFGILEK",
|
|
28
|
+
"ADTQLDESSEQIDEEELTSK",
|
|
29
|
+
"AHQVVEDGYEFFAK",
|
|
30
|
+
"ALDQFVNFSEQK",
|
|
31
|
+
"AAPFSPAEK",
|
|
32
|
+
"VGAHAGEYGAEALER",
|
|
33
|
+
"LNLSPLGEEMR",
|
|
34
|
+
]
|
|
35
|
+
|
|
36
|
+
#: (multi-head class, plain single-series class it wraps), for the shared behavioral tests below.
|
|
37
|
+
_SELECTOR_CLASSES = [
|
|
38
|
+
(MultiHeadPiecewiseLinearCalibration, PiecewiseLinearCalibration),
|
|
39
|
+
(MultiHeadSplineCalibration, SplineTransformerCalibration),
|
|
40
|
+
]
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _synthetic(n: int = 200, n_heads: int = 12, seed: int = 0):
|
|
44
|
+
"""
|
|
45
|
+
Build a target that mixes two heads, which no single head can reproduce.
|
|
46
|
+
|
|
47
|
+
Head 0 tracks the first half of the gradient and head 1 the second, both with noise; the
|
|
48
|
+
remaining heads are unrelated. A single-head calibration has to pick one and lose the other,
|
|
49
|
+
while a combination can use both.
|
|
50
|
+
"""
|
|
51
|
+
rng = np.random.default_rng(seed)
|
|
52
|
+
latent = rng.uniform(0, 100, n)
|
|
53
|
+
target = latent
|
|
54
|
+
source = rng.normal(size=(n, n_heads)) * 20 + 50
|
|
55
|
+
source[:, 0] = latent + rng.normal(0, 8, n) + np.where(latent > 50, 30, 0)
|
|
56
|
+
if n_heads > 1:
|
|
57
|
+
source[:, 1] = latent + rng.normal(0, 8, n) - np.where(latent <= 50, 30, 0)
|
|
58
|
+
return target, source
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def test_multihead_calibrations_share_a_common_type():
|
|
62
|
+
"""`core` dispatches on this type; every head-selecting calibration must be one."""
|
|
63
|
+
assert isinstance(MultiHeadRidgeCalibration(), MultiHeadCalibration)
|
|
64
|
+
assert isinstance(MultiHeadPiecewiseLinearCalibration(), MultiHeadCalibration)
|
|
65
|
+
assert isinstance(MultiHeadSplineCalibration(), MultiHeadCalibration)
|
|
66
|
+
assert not isinstance(SplineTransformerCalibration(), MultiHeadCalibration)
|
|
67
|
+
assert not isinstance(PiecewiseLinearCalibration(), MultiHeadCalibration)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def test_beats_a_single_head_when_the_target_mixes_two():
|
|
71
|
+
"""A combination wins when the gradient sits between two setups."""
|
|
72
|
+
target, source = _synthetic()
|
|
73
|
+
train, test = slice(0, 150), slice(150, None)
|
|
74
|
+
|
|
75
|
+
multi = MultiHeadRidgeCalibration(n_heads=5)
|
|
76
|
+
multi.fit(target=target[train], source=source[train])
|
|
77
|
+
multi_mae = float(np.mean(np.abs(multi.transform(source[test]) - target[test])))
|
|
78
|
+
|
|
79
|
+
single = SplineTransformerCalibration()
|
|
80
|
+
best = multi.selected_model_head
|
|
81
|
+
single.fit(target=target[train], source=source[train][:, best])
|
|
82
|
+
single_mae = float(np.mean(np.abs(single.transform(source[test][:, best]) - target[test])))
|
|
83
|
+
|
|
84
|
+
assert multi_mae < single_mae
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def test_records_the_best_head():
|
|
88
|
+
"""selected_model_head still reports the top-correlating setup, for callers that ask."""
|
|
89
|
+
target, source = _synthetic()
|
|
90
|
+
calibration = MultiHeadRidgeCalibration(n_heads=3)
|
|
91
|
+
calibration.fit(target=target, source=source)
|
|
92
|
+
assert calibration.selected_model_head in (0, 1)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def test_is_fitted_and_transform_guard():
|
|
96
|
+
"""Transforming before fitting is an error, not silent nonsense."""
|
|
97
|
+
calibration = MultiHeadRidgeCalibration()
|
|
98
|
+
assert not calibration.is_fitted
|
|
99
|
+
with pytest.raises(CalibrationError, match="not been fitted"):
|
|
100
|
+
calibration.transform(np.zeros((3, 5)))
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def test_rejects_a_model_with_fewer_heads_than_it_was_fitted_on():
|
|
104
|
+
"""A calibration is tied to the model it was fitted on."""
|
|
105
|
+
target, source = _synthetic(n_heads=12)
|
|
106
|
+
calibration = MultiHeadRidgeCalibration(n_heads=6)
|
|
107
|
+
calibration.fit(target=target, source=source)
|
|
108
|
+
with pytest.raises(CalibrationError, match="heads"):
|
|
109
|
+
calibration.transform(source[:, :2])
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def test_single_head_input_is_accepted():
|
|
113
|
+
"""A single-task model gives a 1-D series; the calibration degrades to one spline."""
|
|
114
|
+
target, source = _synthetic(n_heads=1)
|
|
115
|
+
calibration = MultiHeadRidgeCalibration()
|
|
116
|
+
calibration.fit(target=target, source=source[:, 0])
|
|
117
|
+
out = calibration.transform(source[:, 0])
|
|
118
|
+
assert out.shape == target.shape
|
|
119
|
+
assert np.isfinite(out).all()
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def test_never_fits_more_weights_than_half_the_reference():
|
|
123
|
+
"""A ten-point reference must not be asked to support eighty weights."""
|
|
124
|
+
target, source = _synthetic(n=10, n_heads=40)
|
|
125
|
+
calibration = MultiHeadRidgeCalibration(n_heads=80)
|
|
126
|
+
calibration.fit(target=target, source=source)
|
|
127
|
+
assert len(calibration._head_calibrations) <= 5
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def test_rejects_a_nonsensical_head_count():
|
|
131
|
+
"""Zero heads cannot calibrate anything."""
|
|
132
|
+
with pytest.raises(ValueError, match="at least 1"):
|
|
133
|
+
MultiHeadRidgeCalibration(n_heads=0)
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def test_too_few_finite_points():
|
|
137
|
+
"""Two points cannot support a spline and a ridge."""
|
|
138
|
+
calibration = MultiHeadRidgeCalibration()
|
|
139
|
+
with pytest.raises(CalibrationError, match="three reference points"):
|
|
140
|
+
calibration.fit(target=np.array([1.0, np.nan]), source=np.zeros((2, 4)))
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def test_empty_source_returns_empty():
|
|
144
|
+
"""No PSMs in, no predictions out."""
|
|
145
|
+
target, source = _synthetic()
|
|
146
|
+
calibration = MultiHeadRidgeCalibration(n_heads=4)
|
|
147
|
+
calibration.fit(target=target, source=source)
|
|
148
|
+
assert calibration.transform(np.zeros((0, source.shape[1]))).shape == (0,)
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
@pytest.mark.parametrize(("selector_cls", "inner_cls"), _SELECTOR_CLASSES)
|
|
152
|
+
def test_selector_matches_a_manual_fit_of_its_inner_calibration(
|
|
153
|
+
selector_cls: type[MultiHeadCalibration], inner_cls: type[Calibration]
|
|
154
|
+
):
|
|
155
|
+
"""The wrapper picks a head and defers to its inner calibration, nothing more."""
|
|
156
|
+
target, source = _synthetic()
|
|
157
|
+
selector = selector_cls()
|
|
158
|
+
selector.fit(target=target, source=source)
|
|
159
|
+
assert selector.selected_model_head in (0, 1)
|
|
160
|
+
|
|
161
|
+
inner = inner_cls()
|
|
162
|
+
head_column = source[:, selector.selected_model_head]
|
|
163
|
+
inner.fit(target=target, source=head_column)
|
|
164
|
+
|
|
165
|
+
# Exclude the exact extreme points: SplineTransformerCalibration switches between the spline
|
|
166
|
+
# and its linear trail model right at the fitted min/max, so a sub-ULP float32 rounding
|
|
167
|
+
# difference there can flip the branch and jump the output. That instability is inherent to
|
|
168
|
+
# the wrapped calibration, not something the selector introduces.
|
|
169
|
+
not_extreme = (head_column != head_column.min()) & (head_column != head_column.max())
|
|
170
|
+
np.testing.assert_allclose(
|
|
171
|
+
selector.transform(source)[not_extreme],
|
|
172
|
+
inner.transform(head_column)[not_extreme],
|
|
173
|
+
rtol=1e-4,
|
|
174
|
+
atol=1e-4,
|
|
175
|
+
)
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
@pytest.mark.parametrize(("selector_cls", "_inner_cls"), _SELECTOR_CLASSES)
|
|
179
|
+
def test_selector_is_fitted_and_transform_guard(selector_cls, _inner_cls):
|
|
180
|
+
"""Transforming before fitting is an error, not silent nonsense."""
|
|
181
|
+
calibration = selector_cls()
|
|
182
|
+
assert not calibration.is_fitted
|
|
183
|
+
with pytest.raises(CalibrationError, match="not been fitted"):
|
|
184
|
+
calibration.transform(np.zeros((3, 5)))
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
@pytest.mark.parametrize(("selector_cls", "_inner_cls"), _SELECTOR_CLASSES)
|
|
188
|
+
def test_selector_rejects_a_model_with_fewer_heads_than_it_was_fitted_on(selector_cls, _inner_cls):
|
|
189
|
+
"""A calibration is tied to the model it was fitted on."""
|
|
190
|
+
target, source = _synthetic(n_heads=12)
|
|
191
|
+
calibration = selector_cls()
|
|
192
|
+
calibration.fit(target=target, source=source)
|
|
193
|
+
with pytest.raises(CalibrationError, match="heads"):
|
|
194
|
+
# 0 columns is fewer than the fitted head's index whichever head that turned out to be.
|
|
195
|
+
calibration.transform(source[:, :0])
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
@pytest.mark.parametrize(("selector_cls", "_inner_cls"), _SELECTOR_CLASSES)
|
|
199
|
+
def test_selector_single_head_input_is_accepted(selector_cls, _inner_cls):
|
|
200
|
+
"""A single-task model gives a 1-D series; the calibration still works."""
|
|
201
|
+
target, source = _synthetic(n_heads=1)
|
|
202
|
+
calibration = selector_cls()
|
|
203
|
+
calibration.fit(target=target, source=source[:, 0])
|
|
204
|
+
out = calibration.transform(source[:, 0])
|
|
205
|
+
assert out.shape == target.shape
|
|
206
|
+
assert np.isfinite(out).all()
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
@pytest.mark.parametrize(("selector_cls", "_inner_cls"), _SELECTOR_CLASSES)
|
|
210
|
+
def test_selector_too_few_finite_points(selector_cls, _inner_cls):
|
|
211
|
+
"""Two points cannot support a fit."""
|
|
212
|
+
calibration = selector_cls()
|
|
213
|
+
with pytest.raises(CalibrationError, match="three reference points"):
|
|
214
|
+
calibration.fit(target=np.array([1.0, np.nan]), source=np.zeros((2, 4)))
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
@pytest.mark.parametrize(("selector_cls", "_inner_cls"), _SELECTOR_CLASSES)
|
|
218
|
+
def test_selector_empty_source_returns_empty(selector_cls, _inner_cls):
|
|
219
|
+
"""No PSMs in, no predictions out."""
|
|
220
|
+
target, source = _synthetic()
|
|
221
|
+
calibration = selector_cls()
|
|
222
|
+
calibration.fit(target=target, source=source)
|
|
223
|
+
assert calibration.transform(np.zeros((0, source.shape[1]))).shape == (0,)
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def _psm_list(rts: list[float] | None = None) -> PSMList:
|
|
227
|
+
return PSMList(
|
|
228
|
+
psm_list=[
|
|
229
|
+
PSM(
|
|
230
|
+
spectrum_id=str(i),
|
|
231
|
+
peptidoform=f"{seq}/2",
|
|
232
|
+
retention_time=None if rts is None else rts[i],
|
|
233
|
+
)
|
|
234
|
+
for i, seq in enumerate(_PEPTIDES)
|
|
235
|
+
]
|
|
236
|
+
)
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def test_core_hands_the_matrix_over_and_predicts_end_to_end():
|
|
240
|
+
"""
|
|
241
|
+
``calibrate`` and ``predict_and_calibrate`` accept it with the bundled multitask model.
|
|
242
|
+
|
|
243
|
+
This is the integration path a user takes: pass the calibration in, get one prediction per
|
|
244
|
+
PSM back.
|
|
245
|
+
"""
|
|
246
|
+
reference = _psm_list([5.0 + 3.0 * i for i in range(len(_PEPTIDES))])
|
|
247
|
+
calibration = core.calibrate(
|
|
248
|
+
reference,
|
|
249
|
+
calibration=MultiHeadRidgeCalibration(n_heads=4),
|
|
250
|
+
predict_kwargs={"device": "cpu"},
|
|
251
|
+
)
|
|
252
|
+
assert calibration.is_fitted
|
|
253
|
+
assert calibration.selected_model_head is not None
|
|
254
|
+
|
|
255
|
+
predicted = core.predict_and_calibrate(
|
|
256
|
+
_psm_list(),
|
|
257
|
+
psm_list_reference=reference,
|
|
258
|
+
calibration=calibration,
|
|
259
|
+
predict_kwargs={"device": "cpu"},
|
|
260
|
+
)
|
|
261
|
+
assert predicted.shape == (len(_PEPTIDES),)
|
|
262
|
+
assert np.isfinite(predicted).all()
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def test_default_calibration_combines_heads_for_the_multitask_model():
|
|
266
|
+
"""With no calibration given, the bundled multitask model is calibrated on several heads."""
|
|
267
|
+
reference = _psm_list([5.0 + 3.0 * i for i in range(len(_PEPTIDES))])
|
|
268
|
+
calibration = core.calibrate(reference, predict_kwargs={"device": "cpu"})
|
|
269
|
+
assert isinstance(calibration, MultiHeadRidgeCalibration)
|
|
270
|
+
assert calibration.is_fitted
|
|
271
|
+
assert calibration.selected_model_head is not None
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
def test_lighter_calibration_can_be_passed_explicitly():
|
|
275
|
+
"""Passing MultiHeadSplineCalibration opts out of the ridge combination."""
|
|
276
|
+
reference = _psm_list([5.0 + 3.0 * i for i in range(len(_PEPTIDES))])
|
|
277
|
+
calibration = core.calibrate(
|
|
278
|
+
reference,
|
|
279
|
+
calibration=MultiHeadSplineCalibration(),
|
|
280
|
+
predict_kwargs={"device": "cpu"},
|
|
281
|
+
)
|
|
282
|
+
assert isinstance(calibration, MultiHeadSplineCalibration)
|
|
283
|
+
assert calibration.selected_model_head is not None
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
def test_upgrade_calibration_returns_a_multihead_instance_unchanged():
|
|
287
|
+
"""A MultiHeadCalibration is not touched: nothing to upgrade."""
|
|
288
|
+
calibration = MultiHeadRidgeCalibration(n_heads=3)
|
|
289
|
+
assert upgrade_calibration(calibration) is calibration
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def test_upgrade_calibration_wraps_a_naive_spline_calibration():
|
|
293
|
+
"""A naive SplineTransformerCalibration becomes a MultiHeadSplineCalibration."""
|
|
294
|
+
upgraded = upgrade_calibration(SplineTransformerCalibration())
|
|
295
|
+
assert isinstance(upgraded, MultiHeadSplineCalibration)
|
|
296
|
+
assert not upgraded.is_fitted
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
def test_upgrade_calibration_carries_over_piecewise_linear_parameters():
|
|
300
|
+
"""The wrapped PiecewiseLinearCalibration keeps the constructor arguments it was given."""
|
|
301
|
+
naive = PiecewiseLinearCalibration(number_of_splits=25, use_median=True)
|
|
302
|
+
upgraded = upgrade_calibration(naive)
|
|
303
|
+
assert isinstance(upgraded, MultiHeadPiecewiseLinearCalibration)
|
|
304
|
+
assert upgraded._inner.number_of_splits == 25
|
|
305
|
+
assert upgraded._inner.use_median is True
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def test_upgrade_calibration_rejects_an_already_fitted_naive_calibration():
|
|
309
|
+
"""A fitted naive calibration carries no record of which head it was fit on."""
|
|
310
|
+
naive = SplineTransformerCalibration()
|
|
311
|
+
naive.fit(target=np.linspace(0, 10, 50), source=np.linspace(0, 10, 50))
|
|
312
|
+
with pytest.raises(CalibrationError, match="fitted, naive Calibration"):
|
|
313
|
+
upgrade_calibration(naive)
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
def test_upgrade_calibration_rejects_a_calibration_with_no_multihead_counterpart():
|
|
317
|
+
"""IdentityCalibration has no MultiHead* counterpart; upgrading it is a clear error."""
|
|
318
|
+
with pytest.raises(ValueError, match="No MultiHeadCalibration counterpart"):
|
|
319
|
+
upgrade_calibration(IdentityCalibration())
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
def test_upgrade_calibration_rejects_a_nonsensical_type():
|
|
323
|
+
"""Neither a Calibration nor a MultiHeadCalibration cannot be upgraded."""
|
|
324
|
+
with pytest.raises(ValueError, match="Expected calibration to be of type"):
|
|
325
|
+
upgrade_calibration(object())
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
def test_core_accepts_an_unfitted_naive_calibration_for_backward_compatibility():
|
|
329
|
+
"""`calibrate()` upgrades a plain SplineTransformerCalibration instead of rejecting it."""
|
|
330
|
+
reference = _psm_list([5.0 + 3.0 * i for i in range(len(_PEPTIDES))])
|
|
331
|
+
calibration = core.calibrate(
|
|
332
|
+
reference,
|
|
333
|
+
calibration=SplineTransformerCalibration(),
|
|
334
|
+
predict_kwargs={"device": "cpu"},
|
|
335
|
+
)
|
|
336
|
+
assert isinstance(calibration, MultiHeadSplineCalibration)
|
|
337
|
+
assert calibration.is_fitted
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
def test_core_rejects_a_fitted_naive_calibration():
|
|
341
|
+
"""predict_and_calibrate() cannot recover the head a naive calibration was fit on."""
|
|
342
|
+
reference = _psm_list([5.0 + 3.0 * i for i in range(len(_PEPTIDES))])
|
|
343
|
+
naive = SplineTransformerCalibration()
|
|
344
|
+
naive.fit(target=np.array([5.0 + 3.0 * i for i in range(len(_PEPTIDES))]), source=np.zeros(10))
|
|
345
|
+
with pytest.raises(CalibrationError, match="fitted, naive Calibration"):
|
|
346
|
+
core.predict_and_calibrate(
|
|
347
|
+
_psm_list(),
|
|
348
|
+
psm_list_reference=reference,
|
|
349
|
+
calibration=naive,
|
|
350
|
+
predict_kwargs={"device": "cpu"},
|
|
351
|
+
)
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{deeplc-4.2.0 → deeplc-4.3.0}/deeplc/package_data/baseline_performance/baseline_predictions.csv
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|