deeplc 4.1.1__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.
Files changed (51) hide show
  1. {deeplc-4.1.1/deeplc.egg-info → deeplc-4.3.0}/PKG-INFO +1 -1
  2. {deeplc-4.1.1 → deeplc-4.3.0}/deeplc/__main__.py +8 -1
  3. deeplc-4.3.0/deeplc/_reference_selection.py +235 -0
  4. deeplc-4.3.0/deeplc/calibration/__init__.py +29 -0
  5. deeplc-4.3.0/deeplc/calibration/multihead.py +365 -0
  6. deeplc-4.1.1/deeplc/calibration.py → deeplc-4.3.0/deeplc/calibration/simple.py +13 -4
  7. {deeplc-4.1.1 → deeplc-4.3.0}/deeplc/core.py +50 -66
  8. {deeplc-4.1.1 → deeplc-4.3.0/deeplc.egg-info}/PKG-INFO +1 -1
  9. {deeplc-4.1.1 → deeplc-4.3.0}/deeplc.egg-info/SOURCES.txt +5 -1
  10. {deeplc-4.1.1 → deeplc-4.3.0}/pyproject.toml +1 -1
  11. deeplc-4.3.0/tests/test_deduplication.py +210 -0
  12. deeplc-4.3.0/tests/test_multihead_calibration.py +351 -0
  13. deeplc-4.1.1/deeplc/_reference_selection.py +0 -130
  14. {deeplc-4.1.1 → deeplc-4.3.0}/LICENSE +0 -0
  15. {deeplc-4.1.1 → deeplc-4.3.0}/MANIFEST.in +0 -0
  16. {deeplc-4.1.1 → deeplc-4.3.0}/README.md +0 -0
  17. {deeplc-4.1.1 → deeplc-4.3.0}/deeplc/__init__.py +0 -0
  18. {deeplc-4.1.1 → deeplc-4.3.0}/deeplc/_architecture.py +0 -0
  19. {deeplc-4.1.1 → deeplc-4.3.0}/deeplc/_features.py +0 -0
  20. {deeplc-4.1.1 → deeplc-4.3.0}/deeplc/_model_ops.py +0 -0
  21. {deeplc-4.1.1 → deeplc-4.3.0}/deeplc/data.py +0 -0
  22. {deeplc-4.1.1 → deeplc-4.3.0}/deeplc/exceptions.py +0 -0
  23. {deeplc-4.1.1 → deeplc-4.3.0}/deeplc/gui.py +0 -0
  24. {deeplc-4.1.1 → deeplc-4.3.0}/deeplc/package_data/__init__.py +0 -0
  25. {deeplc-4.1.1 → deeplc-4.3.0}/deeplc/package_data/baseline_performance/__init__.py +0 -0
  26. {deeplc-4.1.1 → deeplc-4.3.0}/deeplc/package_data/baseline_performance/baseline_predictions.csv +0 -0
  27. {deeplc-4.1.1 → deeplc-4.3.0}/deeplc/package_data/examples/__init__.py +0 -0
  28. {deeplc-4.1.1 → deeplc-4.3.0}/deeplc/package_data/examples/example_psms.tsv.gz +0 -0
  29. {deeplc-4.1.1 → deeplc-4.3.0}/deeplc/package_data/gui_images/__init__.py +0 -0
  30. {deeplc-4.1.1 → deeplc-4.3.0}/deeplc/package_data/gui_images/config_icon.png +0 -0
  31. {deeplc-4.1.1 → deeplc-4.3.0}/deeplc/package_data/gui_images/deeplc_logo.png +0 -0
  32. {deeplc-4.1.1 → deeplc-4.3.0}/deeplc/package_data/gui_images/deeplc_logo.svg +0 -0
  33. {deeplc-4.1.1 → deeplc-4.3.0}/deeplc/package_data/gui_images/program_icon.png +0 -0
  34. {deeplc-4.1.1 → deeplc-4.3.0}/deeplc/package_data/models/__init__.py +0 -0
  35. {deeplc-4.1.1 → deeplc-4.3.0}/deeplc/package_data/models/full_hc_PXD005573_pub_1fd8363d9af9dcad3be7553c39396960.pt +0 -0
  36. {deeplc-4.1.1 → deeplc-4.3.0}/deeplc/package_data/models/full_hc_PXD005573_pub_8c22d89667368f2f02ad996469ba157e.pt +0 -0
  37. {deeplc-4.1.1 → deeplc-4.3.0}/deeplc/package_data/models/full_hc_PXD005573_pub_cb975cfdd4105f97efa0b3afffe075cc.pt +0 -0
  38. {deeplc-4.1.1 → deeplc-4.3.0}/deeplc/package_data/models/multitask_flexcnn_model.pt +0 -0
  39. {deeplc-4.1.1 → deeplc-4.3.0}/deeplc/package_data/models/multitask_model.pt +0 -0
  40. {deeplc-4.1.1 → deeplc-4.3.0}/deeplc/plot.py +0 -0
  41. {deeplc-4.1.1 → deeplc-4.3.0}/deeplc.egg-info/dependency_links.txt +0 -0
  42. {deeplc-4.1.1 → deeplc-4.3.0}/deeplc.egg-info/entry_points.txt +0 -0
  43. {deeplc-4.1.1 → deeplc-4.3.0}/deeplc.egg-info/requires.txt +0 -0
  44. {deeplc-4.1.1 → deeplc-4.3.0}/deeplc.egg-info/top_level.txt +0 -0
  45. {deeplc-4.1.1 → deeplc-4.3.0}/setup.cfg +0 -0
  46. {deeplc-4.1.1 → deeplc-4.3.0}/tests/test_calibration.py +0 -0
  47. {deeplc-4.1.1 → deeplc-4.3.0}/tests/test_core.py +0 -0
  48. {deeplc-4.1.1 → deeplc-4.3.0}/tests/test_features.py +0 -0
  49. {deeplc-4.1.1 → deeplc-4.3.0}/tests/test_flexcnn.py +0 -0
  50. {deeplc-4.1.1 → deeplc-4.3.0}/tests/test_model_ops.py +0 -0
  51. {deeplc-4.1.1 → 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.1.1
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>
@@ -135,7 +135,14 @@ def _validate_finetune(ctx, param, value):
135
135
  help="Path to a model file. Uses the built-in default model if not provided.",
136
136
  )
137
137
  def predict(
138
- psms, psm_filetype, reference, reference_filetype, auto_calibrate, finetune, output, model
138
+ psms,
139
+ psm_filetype,
140
+ reference,
141
+ reference_filetype,
142
+ auto_calibrate,
143
+ finetune,
144
+ output,
145
+ model,
139
146
  ):
140
147
  """Predict retention times for a list of peptide-spectrum matches."""
141
148
  if auto_calibrate and reference:
@@ -0,0 +1,235 @@
1
+ """Automatic reference PSM selection for auto-calibration."""
2
+
3
+ import logging
4
+
5
+ import numpy as np
6
+ from psm_utils import PSMList
7
+
8
+ from deeplc.exceptions import ReferenceSelectionError
9
+
10
+ LOGGER = logging.getLogger(__name__)
11
+
12
+ Q_VALUE_THRESHOLD = 0.01
13
+ MIN_REFERENCE_PSMS = 50
14
+ MAX_REFERENCE_PSMS = 500
15
+ TOP_SCORE_FRACTION = 0.2
16
+
17
+
18
+ def select_reference_psms(psm_list: PSMList) -> PSMList:
19
+ """
20
+ Select the best PSMs from a PSMList to use as calibration reference.
21
+
22
+ Selection strategy (in priority order):
23
+
24
+ 1. q-values already present: filter targets with observed RT by q-value threshold.
25
+ 2. Target-decoy labels and scores present: compute q-values, then filter by threshold.
26
+ 3. Scores only: take top fraction by score, clamped to [MIN, MAX] count.
27
+ 4. None of the above: raise ReferenceSelectionError.
28
+
29
+ Parameters
30
+ ----------
31
+ psm_list
32
+ PSMList to select reference PSMs from. Must contain PSMs with observed retention
33
+ times and either q-values, scores + target-decoy labels, or scores.
34
+
35
+ Returns
36
+ -------
37
+ PSMList
38
+ Subset of target PSMs with observed RT suitable for calibration.
39
+
40
+ Raises
41
+ ------
42
+ ReferenceSelectionError
43
+ If the PSMList lacks the required fields for any selection strategy.
44
+
45
+ """
46
+ # Filter to targets with observed RT
47
+ candidates = _filter_targets_with_rt(psm_list)
48
+ if len(candidates) == 0:
49
+ raise ReferenceSelectionError(
50
+ "No target PSMs with observed retention times found. "
51
+ "Auto-calibration requires PSMs with retention times."
52
+ )
53
+
54
+ # Determine strategy
55
+ has_qvalues = any(psm.qvalue is not None for psm in psm_list.psm_list)
56
+ has_scores = any(psm.score is not None for psm in psm_list.psm_list)
57
+ has_decoy_labels = any(psm.is_decoy is not None for psm in psm_list.psm_list)
58
+
59
+ if has_qvalues:
60
+ LOGGER.info("Selecting reference PSMs by pre-computed q-values.")
61
+ reference = _select_by_qvalue(candidates)
62
+ elif has_decoy_labels and has_scores:
63
+ LOGGER.info("Computing q-values from target-decoy competition.")
64
+ reference = _select_by_computed_qvalue(psm_list)
65
+ elif has_scores:
66
+ LOGGER.info("Selecting reference PSMs by top scores.")
67
+ reference = _select_by_score(candidates)
68
+ else:
69
+ raise ReferenceSelectionError(
70
+ "Cannot auto-select reference PSMs: input lacks q-values, scores, and "
71
+ "target-decoy labels. Provide a separate reference file instead."
72
+ )
73
+
74
+ if len(reference) < MIN_REFERENCE_PSMS:
75
+ raise ReferenceSelectionError(
76
+ f"Only {len(reference)} reference PSMs selected, but at least "
77
+ f"{MIN_REFERENCE_PSMS} are required for calibration."
78
+ )
79
+
80
+ LOGGER.info("Selected %d reference PSMs.", len(reference))
81
+ return reference
82
+
83
+
84
+ def _filter_targets_with_rt(psm_list: PSMList) -> PSMList:
85
+ """Filter to non-decoy PSMs with observed retention times."""
86
+ is_decoy = np.array(
87
+ [psm.is_decoy if psm.is_decoy is not None else False for psm in psm_list.psm_list]
88
+ )
89
+ has_rt = np.array(
90
+ [
91
+ psm.retention_time is not None and not np.isnan(psm.retention_time)
92
+ for psm in psm_list.psm_list
93
+ ]
94
+ )
95
+ mask = ~is_decoy & has_rt
96
+ return psm_list[mask]
97
+
98
+
99
+ def _select_by_qvalue(candidates: PSMList) -> PSMList:
100
+ """Select PSMs with q-value below threshold."""
101
+ qvalues = np.array(
102
+ [psm.qvalue if psm.qvalue is not None else np.inf for psm in candidates.psm_list]
103
+ )
104
+ mask = qvalues <= Q_VALUE_THRESHOLD
105
+ return candidates[mask]
106
+
107
+
108
+ def _select_by_computed_qvalue(psm_list: PSMList) -> PSMList:
109
+ """
110
+ Compute q-values from target-decoy competition, then select by threshold.
111
+
112
+ Note: this modifies ``psm_list`` in-place by assigning computed q-values.
113
+ """
114
+ psm_list.calculate_qvalues(reverse=True)
115
+ candidates = _filter_targets_with_rt(psm_list)
116
+ return _select_by_qvalue(candidates)
117
+
118
+
119
+ def _select_by_score(candidates: PSMList) -> PSMList:
120
+ """Select top fraction of PSMs by score, clamped to [MIN, MAX] count."""
121
+ scores = np.array(
122
+ [psm.score if psm.score is not None else -np.inf for psm in candidates.psm_list]
123
+ )
124
+ n_total = len(candidates)
125
+ n_select = int(n_total * TOP_SCORE_FRACTION)
126
+ n_select = max(MIN_REFERENCE_PSMS, min(MAX_REFERENCE_PSMS, n_select))
127
+ n_select = min(n_select, n_total)
128
+
129
+ top_indices = np.argsort(scores)[::-1][:n_select]
130
+ return candidates[top_indices]
131
+
132
+
133
+ def deduplicate_psms(psm_list: PSMList, ignore_charge: bool = True) -> PSMList:
134
+ """
135
+ Keep one PSM per peptidoform, the first occurrence in the list.
136
+
137
+ A reference set built from a search result usually contains the same peptidoform
138
+ identified in many spectra, with a different observed retention time each time. Those
139
+ repeats do not add information about the gradient: they give the calibration one x value
140
+ with several conflicting y values, and their number is what a spline fit weighs, so a
141
+ peptidoform seen 261 times counts 261 times while one seen once counts once. On a
142
+ reported MS2Rescore case, 6,331 reference PSMs collapsed to 2,623 peptidoforms, and the
143
+ observed retention times of one repeated peptidoform differed by two thirds of the whole
144
+ observed range.
145
+
146
+ Only the first observation is kept, which is what a caller who has already sorted or
147
+ filtered its PSMs expects, and it makes the result independent of how many times a
148
+ peptidoform happened to be identified.
149
+
150
+ Parameters
151
+ ----------
152
+ psm_list
153
+ PSMs to deduplicate.
154
+ ignore_charge
155
+ Treat charge states of the same peptidoform as duplicates (default). Retention time
156
+ does not depend on precursor charge, so the charge states of one peptidoform are
157
+ repeats of the same measurement. Set to False to keep one PSM per peptidoform *and*
158
+ charge.
159
+
160
+ Returns
161
+ -------
162
+ PSMList
163
+ The first PSM of every peptidoform, in the original order.
164
+
165
+ """
166
+ seen: set[str] = set()
167
+ keep = np.zeros(len(psm_list), dtype=bool)
168
+ for i, psm in enumerate(psm_list.psm_list):
169
+ # modified_sequence is the ProForma string without the charge state, so it keeps the
170
+ # terminal and global modifications that distinguish two peptidoforms while ignoring
171
+ # charge. Taking it from psm_utils also avoids cutting the string ourselves, which a
172
+ # modification label containing a slash would break.
173
+ key = psm.peptidoform.modified_sequence
174
+ if not ignore_charge:
175
+ key = f"{key}/{psm.peptidoform.precursor_charge}"
176
+ if key not in seen:
177
+ seen.add(key)
178
+ keep[i] = True
179
+
180
+ n_dropped = int((~keep).sum())
181
+ if n_dropped:
182
+ LOGGER.info(
183
+ "Deduplicated the reference: %d of %d PSMs are repeats of a peptidoform already "
184
+ "in the set and were dropped, leaving %d. Pass deduplicate_reference=False to "
185
+ "keep them.",
186
+ n_dropped,
187
+ len(psm_list),
188
+ int(keep.sum()),
189
+ )
190
+ _warn_on_conflicting_retention_times(psm_list, keep, ignore_charge)
191
+ return psm_list[keep]
192
+
193
+
194
+ def _warn_on_conflicting_retention_times(
195
+ psm_list: PSMList, keep: np.ndarray, ignore_charge: bool
196
+ ) -> None:
197
+ """
198
+ Report the largest retention-time disagreement among the dropped repeats.
199
+
200
+ A small spread is ordinary chromatographic jitter; a spread of the order of the gradient
201
+ means the repeats are not the same elution event, so the reference was built from PSMs
202
+ that a search would normally not put in one calibration set (decoys, low-scoring hits, or
203
+ several runs pooled into one file). Worth saying out loud, because deduplication then
204
+ hides a data problem rather than solving it.
205
+ """
206
+ by_key: dict[str, list[float]] = {}
207
+ for psm in psm_list.psm_list:
208
+ rt = psm.retention_time
209
+ if rt is None or np.isnan(rt):
210
+ continue
211
+ key = psm.peptidoform.modified_sequence
212
+ if not ignore_charge:
213
+ key = f"{key}/{psm.peptidoform.precursor_charge}"
214
+ by_key.setdefault(key, []).append(float(rt))
215
+
216
+ spreads = [max(v) - min(v) for v in by_key.values() if len(v) > 1]
217
+ if not spreads:
218
+ return
219
+ worst = max(spreads)
220
+ observed = [
221
+ float(psm.retention_time)
222
+ for psm in psm_list.psm_list
223
+ if psm.retention_time is not None and not np.isnan(psm.retention_time)
224
+ ]
225
+ span = (max(observed) - min(observed)) if observed else 0.0
226
+ LOGGER.log(
227
+ logging.WARNING if span and worst > 0.25 * span else logging.INFO,
228
+ "Repeated peptidoforms disagreed on the observed retention time by up to %.2f "
229
+ "(median %.2f) against an observed range of %.2f. A large disagreement means the "
230
+ "repeats are not the same elution event: check whether the reference mixes runs or "
231
+ "includes low-confidence PSMs.",
232
+ worst,
233
+ float(np.median(spreads)),
234
+ span,
235
+ )
@@ -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
- """Calibration utilities."""
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."""