deeplc 4.1.0__tar.gz → 4.2.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 (48) hide show
  1. {deeplc-4.1.0/deeplc.egg-info → deeplc-4.2.0}/PKG-INFO +3 -3
  2. {deeplc-4.1.0 → deeplc-4.2.0}/README.md +2 -2
  3. {deeplc-4.1.0 → deeplc-4.2.0}/deeplc/__main__.py +8 -1
  4. deeplc-4.2.0/deeplc/_reference_selection.py +235 -0
  5. {deeplc-4.1.0 → deeplc-4.2.0}/deeplc/core.py +52 -10
  6. {deeplc-4.1.0 → deeplc-4.2.0/deeplc.egg-info}/PKG-INFO +3 -3
  7. {deeplc-4.1.0 → deeplc-4.2.0}/deeplc.egg-info/SOURCES.txt +1 -0
  8. {deeplc-4.1.0 → deeplc-4.2.0}/pyproject.toml +1 -1
  9. {deeplc-4.1.0 → deeplc-4.2.0}/tests/test_core.py +39 -0
  10. deeplc-4.2.0/tests/test_deduplication.py +211 -0
  11. {deeplc-4.1.0 → deeplc-4.2.0}/tests/test_flexcnn.py +3 -1
  12. {deeplc-4.1.0 → deeplc-4.2.0}/tests/test_model_ops.py +3 -3
  13. deeplc-4.1.0/deeplc/_reference_selection.py +0 -130
  14. {deeplc-4.1.0 → deeplc-4.2.0}/LICENSE +0 -0
  15. {deeplc-4.1.0 → deeplc-4.2.0}/MANIFEST.in +0 -0
  16. {deeplc-4.1.0 → deeplc-4.2.0}/deeplc/__init__.py +0 -0
  17. {deeplc-4.1.0 → deeplc-4.2.0}/deeplc/_architecture.py +0 -0
  18. {deeplc-4.1.0 → deeplc-4.2.0}/deeplc/_features.py +0 -0
  19. {deeplc-4.1.0 → deeplc-4.2.0}/deeplc/_model_ops.py +0 -0
  20. {deeplc-4.1.0 → deeplc-4.2.0}/deeplc/calibration.py +0 -0
  21. {deeplc-4.1.0 → deeplc-4.2.0}/deeplc/data.py +0 -0
  22. {deeplc-4.1.0 → deeplc-4.2.0}/deeplc/exceptions.py +0 -0
  23. {deeplc-4.1.0 → deeplc-4.2.0}/deeplc/gui.py +0 -0
  24. {deeplc-4.1.0 → deeplc-4.2.0}/deeplc/package_data/__init__.py +0 -0
  25. {deeplc-4.1.0 → deeplc-4.2.0}/deeplc/package_data/baseline_performance/__init__.py +0 -0
  26. {deeplc-4.1.0 → deeplc-4.2.0}/deeplc/package_data/baseline_performance/baseline_predictions.csv +0 -0
  27. {deeplc-4.1.0 → deeplc-4.2.0}/deeplc/package_data/examples/__init__.py +0 -0
  28. {deeplc-4.1.0 → deeplc-4.2.0}/deeplc/package_data/examples/example_psms.tsv.gz +0 -0
  29. {deeplc-4.1.0 → deeplc-4.2.0}/deeplc/package_data/gui_images/__init__.py +0 -0
  30. {deeplc-4.1.0 → deeplc-4.2.0}/deeplc/package_data/gui_images/config_icon.png +0 -0
  31. {deeplc-4.1.0 → deeplc-4.2.0}/deeplc/package_data/gui_images/deeplc_logo.png +0 -0
  32. {deeplc-4.1.0 → deeplc-4.2.0}/deeplc/package_data/gui_images/deeplc_logo.svg +0 -0
  33. {deeplc-4.1.0 → deeplc-4.2.0}/deeplc/package_data/gui_images/program_icon.png +0 -0
  34. {deeplc-4.1.0 → deeplc-4.2.0}/deeplc/package_data/models/__init__.py +0 -0
  35. {deeplc-4.1.0 → deeplc-4.2.0}/deeplc/package_data/models/full_hc_PXD005573_pub_1fd8363d9af9dcad3be7553c39396960.pt +0 -0
  36. {deeplc-4.1.0 → deeplc-4.2.0}/deeplc/package_data/models/full_hc_PXD005573_pub_8c22d89667368f2f02ad996469ba157e.pt +0 -0
  37. {deeplc-4.1.0 → deeplc-4.2.0}/deeplc/package_data/models/full_hc_PXD005573_pub_cb975cfdd4105f97efa0b3afffe075cc.pt +0 -0
  38. {deeplc-4.1.0 → deeplc-4.2.0}/deeplc/package_data/models/multitask_flexcnn_model.pt +0 -0
  39. {deeplc-4.1.0 → deeplc-4.2.0}/deeplc/package_data/models/multitask_model.pt +0 -0
  40. {deeplc-4.1.0 → deeplc-4.2.0}/deeplc/plot.py +0 -0
  41. {deeplc-4.1.0 → deeplc-4.2.0}/deeplc.egg-info/dependency_links.txt +0 -0
  42. {deeplc-4.1.0 → deeplc-4.2.0}/deeplc.egg-info/entry_points.txt +0 -0
  43. {deeplc-4.1.0 → deeplc-4.2.0}/deeplc.egg-info/requires.txt +0 -0
  44. {deeplc-4.1.0 → deeplc-4.2.0}/deeplc.egg-info/top_level.txt +0 -0
  45. {deeplc-4.1.0 → deeplc-4.2.0}/setup.cfg +0 -0
  46. {deeplc-4.1.0 → deeplc-4.2.0}/tests/test_calibration.py +0 -0
  47. {deeplc-4.1.0 → deeplc-4.2.0}/tests/test_features.py +0 -0
  48. {deeplc-4.1.0 → deeplc-4.2.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.0
3
+ Version: 4.2.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>
@@ -252,8 +252,8 @@ Dynamic: license-file
252
252
 
253
253
  DeepLC predicts retention times for peptides carrying any modification. It does this by leveraging
254
254
  a deep learning model based on atomic composition features. Starting with v4, DeepLC comes with a
255
- multitask pretrained model covering multiple LC setups, enabling accurate predictions out of the
256
- box. For best results on a specific dataset, predictions can be calibrated or fine-tuned
255
+ multitask pretrained model covering multiple LC setups (6,543 setups since v4.1.1), enabling
256
+ accurate predictions out of the box. For best results on a specific dataset, predictions can be calibrated or fine-tuned
257
257
  using a small reference set of identified PSMs.
258
258
 
259
259
  ## Citation
@@ -16,8 +16,8 @@
16
16
 
17
17
  DeepLC predicts retention times for peptides carrying any modification. It does this by leveraging
18
18
  a deep learning model based on atomic composition features. Starting with v4, DeepLC comes with a
19
- multitask pretrained model covering multiple LC setups, enabling accurate predictions out of the
20
- box. For best results on a specific dataset, predictions can be calibrated or fine-tuned
19
+ multitask pretrained model covering multiple LC setups (6,543 setups since v4.1.1), enabling
20
+ accurate predictions out of the box. For best results on a specific dataset, predictions can be calibrated or fine-tuned
21
21
  using a small reference set of identified PSMs.
22
22
 
23
23
  ## Citation
@@ -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
+ )
@@ -12,7 +12,7 @@ from psm_utils import PSM, Peptidoform, PSMList
12
12
  from torch.utils.data import DataLoader
13
13
 
14
14
  from deeplc import _model_ops
15
- from deeplc._reference_selection import select_reference_psms
15
+ from deeplc._reference_selection import deduplicate_psms, select_reference_psms
16
16
  from deeplc.calibration import (
17
17
  Calibration,
18
18
  SplineTransformerCalibration,
@@ -22,7 +22,20 @@ from deeplc.data import DeepLCDataset, split_datasets
22
22
  LOGGER = logging.getLogger(__name__)
23
23
 
24
24
  DEEPLC_DIR = Path(__file__).resolve().parent
25
- DEFAULT_MODEL = DEEPLC_DIR / "package_data" / "models" / "multitask_model.pt"
25
+ #: The model every core function uses when none is given: the fused-trunk multitask
26
+ #: model trained across 6,543 LC setups (see :data:`FLEXCNN_MULTITASK_MODEL`).
27
+ DEFAULT_MODEL = DEEPLC_DIR / "package_data" / "models" / "multitask_flexcnn_model.pt"
28
+
29
+ #: The 4.0 default, a shared-trunk model with one head per LC setup, kept so that
30
+ #: existing workflows can pin it: ``predict(psms, model=LEGACY_MULTITASK_MODEL)``.
31
+ LEGACY_MULTITASK_MODEL = DEEPLC_DIR / "package_data" / "models" / "multitask_model.pt"
32
+
33
+ #: The LC setup an uncalibrated ``predict()`` reports for a multitask model. The
34
+ #: default model has 6,543 setups and no reference to choose between them, so the
35
+ #: setup of the DeepLC 1.x to 3.x training data (PXD005573, 200-minute gradient) is
36
+ #: used, which keeps uncalibrated output on the gradient earlier versions reported.
37
+ #: Calibration and fine-tuning pick or fit the setup from the reference instead.
38
+ DEFAULT_TASK_NAME = "PXD005573_mcp"
26
39
 
27
40
  #: Below this many reference PSMs, fine-tuning measured worse than calibration on
28
41
  #: every held-out setup tried, so it is warned about rather than silently attempted.
@@ -40,10 +53,9 @@ MIN_FINETUNE_REFERENCE = 500
40
53
  #: near 1 %.
41
54
  MAX_FINETUNE_ERROR_FRACTION = 0.15
42
55
 
43
- #: Fused-trunk multitask model, trained across 6,543 LC setups. Not the default:
44
- #: switching would change every prediction, so the choice is left to the caller
45
- #: until the calibration path is adapted to its low-rank head.
46
- FLEXCNN_MULTITASK_MODEL = DEEPLC_DIR / "package_data" / "models" / "multitask_flexcnn_model.pt"
56
+ #: Fused-trunk multitask model, trained across 6,543 LC setups. The default since
57
+ #: 4.1.1; the name is kept for callers that pass it explicitly.
58
+ FLEXCNN_MULTITASK_MODEL = DEFAULT_MODEL
47
59
 
48
60
 
49
61
  def predict(
@@ -65,8 +77,10 @@ def predict(
65
77
  Additional keyword arguments to pass to the prediction function.
66
78
  return_matrix
67
79
  If True, return the full prediction matrix of shape ``(n, n_heads)`` when using a
68
- multitask model. If False (default), return a 1D array of shape ``(n,)`` using
69
- head 0 when model output is 2D.
80
+ multitask model. If False (default), return a 1D array of shape ``(n,)`` for the
81
+ setup named by :data:`DEFAULT_TASK_NAME` when the model knows its setups, and head
82
+ 0 otherwise. Uncalibrated output is on that setup's gradient; use
83
+ :func:`predict_and_calibrate` to map it onto your own.
70
84
 
71
85
  Returns
72
86
  -------
@@ -96,7 +110,7 @@ def predict(
96
110
  and "task_idx" not in kwargs
97
111
  and _model_ops.supports_task_subset(loaded_model)
98
112
  ):
99
- kwargs["task_idx"] = [0]
113
+ kwargs["task_idx"] = [_default_task_idx(loaded_model)]
100
114
 
101
115
  result = _model_ops.predict(
102
116
  model=loaded_model,
@@ -106,10 +120,24 @@ def predict(
106
120
  **kwargs,
107
121
  ).numpy()
108
122
  if not return_matrix:
109
- return result[:, 0]
123
+ return result[:, 0 if "task_idx" in kwargs else _default_task_idx(loaded_model)]
110
124
  return result
111
125
 
112
126
 
127
+ def _default_task_idx(model: torch.nn.Module) -> int:
128
+ """
129
+ Index of the setup an uncalibrated prediction reports.
130
+
131
+ :data:`DEFAULT_TASK_NAME` when the model carries setup names and lists it, else 0.
132
+ A model without names, or a model of a single setup, has nothing to choose from.
133
+ """
134
+ names = getattr(model, "task_names", None) or []
135
+ try:
136
+ return list(names).index(DEFAULT_TASK_NAME)
137
+ except ValueError:
138
+ return 0
139
+
140
+
113
141
  def calibrate(
114
142
  psm_list_reference: PSMList,
115
143
  model: torch.nn.Module | PathLike | str | None = None,
@@ -136,6 +164,13 @@ def calibrate(
136
164
  Fitted calibration instance.
137
165
 
138
166
  """
167
+ # One point per peptidoform: a reference taken from a search result repeats a
168
+ # peptidoform once per spectrum it was identified in, each time with a different observed
169
+ # retention time, which gives the fit conflicting targets and weighs peptidoforms by how
170
+ # often they happened to be identified. A caller who wants the repeats to count fits a
171
+ # Calibration itself and passes it in already fitted.
172
+ psm_list_reference = deduplicate_psms(psm_list_reference)
173
+
139
174
  # Get calibration
140
175
  if calibration is None:
141
176
  LOGGER.debug("No calibration provided, using SplineTransformerCalibration by default.")
@@ -204,6 +239,7 @@ def predict_and_calibrate(
204
239
  predict_kwargs
205
240
  Additional keyword arguments to pass to the prediction function.
206
241
 
242
+
207
243
  Returns
208
244
  -------
209
245
  np.ndarray
@@ -285,6 +321,7 @@ def finetune_and_predict(
285
321
  predict_kwargs
286
322
  Additional keyword arguments to pass to the prediction function.
287
323
 
324
+
288
325
  Returns
289
326
  -------
290
327
  np.ndarray
@@ -415,6 +452,11 @@ def finetune(
415
452
  """
416
453
  LOGGER.info("Fine-tuning model...")
417
454
 
455
+ # One point per peptidoform, as in calibrate(): training on the same peptidoform several
456
+ # times with contradictory retention times teaches the model the average of a
457
+ # disagreement. Use deeplc.train() for full control over the training set.
458
+ psm_list_reference = deduplicate_psms(psm_list_reference)
459
+
418
460
  # Fine-tuning needs enough reference data to both fit and validate on. The
419
461
  # default validation split leaves too few PSMs to early-stop against on a small
420
462
  # reference set, which is how a fit ends up worse than the model it started
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: deeplc
3
- Version: 4.1.0
3
+ Version: 4.2.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>
@@ -252,8 +252,8 @@ Dynamic: license-file
252
252
 
253
253
  DeepLC predicts retention times for peptides carrying any modification. It does this by leveraging
254
254
  a deep learning model based on atomic composition features. Starting with v4, DeepLC comes with a
255
- multitask pretrained model covering multiple LC setups, enabling accurate predictions out of the
256
- box. For best results on a specific dataset, predictions can be calibrated or fine-tuned
255
+ multitask pretrained model covering multiple LC setups (6,543 setups since v4.1.1), enabling
256
+ accurate predictions out of the box. For best results on a specific dataset, predictions can be calibrated or fine-tuned
257
257
  using a small reference set of identified PSMs.
258
258
 
259
259
  ## Citation
@@ -38,6 +38,7 @@ deeplc/package_data/models/multitask_flexcnn_model.pt
38
38
  deeplc/package_data/models/multitask_model.pt
39
39
  tests/test_calibration.py
40
40
  tests/test_core.py
41
+ tests/test_deduplication.py
41
42
  tests/test_features.py
42
43
  tests/test_flexcnn.py
43
44
  tests/test_model_ops.py
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "deeplc"
3
- version = "4.1.0"
3
+ version = "4.2.0"
4
4
  description = "DeepLC: Retention time prediction for (modified) peptides using Deep Learning."
5
5
  readme = "README.md"
6
6
  license = { file = "LICENSE" }
@@ -71,6 +71,45 @@ def test_predict_returns_matrix_when_flag_set():
71
71
  assert result.shape[1] > 1
72
72
 
73
73
 
74
+ def test_default_model_is_the_flexcnn_multitask_model():
75
+ """Since 4.1.1 the fused-trunk model of 6,543 setups is what a bare call loads."""
76
+ assert deeplc.core.DEFAULT_MODEL == deeplc.core.FLEXCNN_MULTITASK_MODEL
77
+ assert deeplc.core.DEFAULT_MODEL.name == "multitask_flexcnn_model.pt"
78
+ assert deeplc.core.LEGACY_MULTITASK_MODEL.name == "multitask_model.pt"
79
+ assert deeplc.core.LEGACY_MULTITASK_MODEL.exists()
80
+
81
+
82
+ def test_uncalibrated_predict_reports_the_default_setup():
83
+ """
84
+ A bare ``predict`` returns the column of :data:`DEFAULT_TASK_NAME`, not head 0.
85
+
86
+ The default model lists thousands of setups, and head 0 is whichever sorted first.
87
+ The PXD005573 setup keeps uncalibrated output on the gradient DeepLC 1.x to 3.x
88
+ reported, so downstream code that never calibrated sees comparable numbers.
89
+ """
90
+ model = deeplc.core._model_ops.load_model(deeplc.core.DEFAULT_MODEL, device="cpu")
91
+ idx = list(model.task_names).index(deeplc.core.DEFAULT_TASK_NAME)
92
+ assert idx != 0
93
+
94
+ psm_list = _make_psm_list(_PEPTIDES)
95
+ single = deeplc.core.predict(psm_list, predict_kwargs={"device": "cpu"})
96
+ matrix = deeplc.core.predict(psm_list, return_matrix=True, predict_kwargs={"device": "cpu"})
97
+ np.testing.assert_allclose(single, matrix[:, idx], rtol=1e-5, atol=1e-4)
98
+ assert not np.allclose(single, matrix[:, 0])
99
+ assert np.isfinite(single).all()
100
+
101
+
102
+ def test_legacy_multitask_model_still_loads_and_predicts():
103
+ """The 4.0 default remains bundled and usable when pinned explicitly."""
104
+ result = deeplc.core.predict(
105
+ _make_psm_list(_PEPTIDES),
106
+ model=deeplc.core.LEGACY_MULTITASK_MODEL,
107
+ predict_kwargs={"device": "cpu"},
108
+ )
109
+ assert result.shape == (len(_PEPTIDES),)
110
+ assert np.isfinite(result).all()
111
+
112
+
74
113
  def test_predict_and_calibrate_auto_selects_reference():
75
114
  # 200 PSMs cycling through _PEPTIDES; 100 with qvalue<=0.01, 100 with qvalue=1.0.
76
115
  # auto-selection picks the 100 low-qvalue PSMs as reference.
@@ -0,0 +1,211 @@
1
+ """Reference deduplication: one PSM per peptidoform, the first observation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+
7
+ import numpy as np
8
+ from psm_utils import PSM, PSMList
9
+
10
+ from deeplc import core
11
+ from deeplc._reference_selection import deduplicate_psms
12
+ from deeplc.calibration import SplineTransformerCalibration
13
+
14
+ _PEPTIDES = [
15
+ "AAGPSLSHTSGGTQSK",
16
+ "AGFAGDDAPR",
17
+ "AIQEYNQDK",
18
+ "AAYFGILEK",
19
+ "ADTQLDESSEQIDEEELTSK",
20
+ "AHQVVEDGYEFFAK",
21
+ "ALDQFVNFSEQK",
22
+ "AAPFSPAEK",
23
+ "VGAHAGEYGAEALER",
24
+ "LNLSPLGEEMR",
25
+ ]
26
+
27
+
28
+ def _psms(pairs: list[tuple[str, float | None]], charge: int = 2) -> PSMList:
29
+ """Build a PSMList from (peptide, retention time) pairs."""
30
+ return PSMList(
31
+ psm_list=[
32
+ PSM(spectrum_id=str(i), peptidoform=f"{seq}/{charge}", retention_time=rt)
33
+ for i, (seq, rt) in enumerate(pairs)
34
+ ]
35
+ )
36
+
37
+
38
+ def test_keeps_the_first_observation_of_each_peptidoform():
39
+ """Repeats are dropped and the retention time of the first one survives."""
40
+ psm_list = _psms([("PEPTIDEK", 10.0), ("PEPTIDEK", 40.0), ("ACDEFGHIK", 20.0)])
41
+
42
+ deduplicated = deduplicate_psms(psm_list)
43
+
44
+ assert [str(p.peptidoform) for p in deduplicated] == ["PEPTIDEK/2", "ACDEFGHIK/2"]
45
+ assert [p.retention_time for p in deduplicated] == [10.0, 20.0]
46
+
47
+
48
+ def test_order_is_preserved():
49
+ """The kept PSMs stay in the order they were given in."""
50
+ psm_list = _psms([(s, float(i)) for i, s in enumerate(_PEPTIDES)])
51
+ assert [str(p.peptidoform) for p in deduplicate_psms(psm_list)] == [
52
+ str(p.peptidoform) for p in psm_list
53
+ ]
54
+
55
+
56
+ def test_idempotent():
57
+ """Deduplicating an already deduplicated list changes nothing."""
58
+ psm_list = _psms([("PEPTIDEK", 10.0), ("PEPTIDEK", 40.0), ("ACDEFGHIK", 20.0)])
59
+ once = deduplicate_psms(psm_list)
60
+ assert len(deduplicate_psms(once)) == len(once)
61
+
62
+
63
+ def test_charge_states_are_duplicates_by_default():
64
+ """Retention time does not depend on charge, so charge states are repeats."""
65
+ psm_list = PSMList(
66
+ psm_list=[
67
+ PSM(spectrum_id="1", peptidoform="PEPTIDEK/2", retention_time=10.0),
68
+ PSM(spectrum_id="2", peptidoform="PEPTIDEK/3", retention_time=11.0),
69
+ ]
70
+ )
71
+
72
+ assert len(deduplicate_psms(psm_list)) == 1
73
+ assert len(deduplicate_psms(psm_list, ignore_charge=False)) == 2
74
+
75
+
76
+ def test_modified_peptidoforms_are_not_duplicates():
77
+ """A modification makes a different peptidoform, which elutes at a different time."""
78
+ psm_list = PSMList(
79
+ psm_list=[
80
+ PSM(spectrum_id="1", peptidoform="PEPTM[Oxidation]IDEK/2", retention_time=10.0),
81
+ PSM(spectrum_id="2", peptidoform="PEPTMIDEK/2", retention_time=12.0),
82
+ ]
83
+ )
84
+ assert len(deduplicate_psms(psm_list)) == 2
85
+
86
+
87
+ def test_exotic_peptidoforms_keep_their_identity():
88
+ """
89
+ The key is ``Peptidoform.modified_sequence``, so nothing but charge is ignored.
90
+
91
+ Terminal, global and labile modifications all distinguish two peptidoforms, and a
92
+ modification label may itself contain a slash, which is why the charge is not cut off the
93
+ ProForma string by hand.
94
+ """
95
+ distinct = [
96
+ "PEPTIDEK/2",
97
+ "[Acetyl]-PEPTIDEK/2",
98
+ "PEPTIDEK-[Amidated]/2",
99
+ "PEPTM[Oxidation]IDEK/2",
100
+ "PEPT[Phospho]IDEK/2",
101
+ "<[Carbamidomethyl]@C>PEPCTIDEK/2",
102
+ "PROT[Phospho|+79.966]EIN/2",
103
+ ]
104
+ psm_list = PSMList(
105
+ psm_list=[
106
+ PSM(spectrum_id=str(i), peptidoform=pf, retention_time=10.0 + i)
107
+ for i, pf in enumerate(distinct)
108
+ ]
109
+ )
110
+
111
+ assert len(deduplicate_psms(psm_list)) == len(distinct)
112
+
113
+
114
+ def test_charge_adducts_do_not_create_a_second_peptidoform():
115
+ """``/2`` and ``/2[+2H]`` are the same peptidoform measured twice."""
116
+ psm_list = PSMList(
117
+ psm_list=[
118
+ PSM(spectrum_id="1", peptidoform="PEPTIDEK/2", retention_time=10.0),
119
+ PSM(spectrum_id="2", peptidoform="PEPTIDEK/2[+2H]", retention_time=11.0),
120
+ ]
121
+ )
122
+ assert len(deduplicate_psms(psm_list)) == 1
123
+
124
+
125
+ def test_warns_when_repeats_disagree_on_the_retention_time(caplog):
126
+ """
127
+ A disagreement of the order of the gradient is a data problem, not jitter.
128
+
129
+ Deduplication silently fixes the fit, so the case a user needs to hear about is when the
130
+ repeated peptidoform was not the same elution event at all.
131
+ """
132
+ pairs = [(s, float(i)) for i, s in enumerate(_PEPTIDES)]
133
+ pairs.append((_PEPTIDES[0], 500.0)) # same peptidoform, 500 minutes later
134
+
135
+ with caplog.at_level(logging.WARNING, logger="deeplc._reference_selection"):
136
+ deduplicate_psms(_psms(pairs))
137
+
138
+ assert any("disagreed on the observed retention time" in r.message for r in caplog.records)
139
+
140
+
141
+ def test_missing_retention_times_do_not_break_the_report(caplog):
142
+ """PSMs without an observed retention time are deduplicated like any other."""
143
+ psm_list = _psms([("PEPTIDEK", None), ("PEPTIDEK", None), ("ACDEFGHIK", 20.0)])
144
+ with caplog.at_level(logging.INFO, logger="deeplc._reference_selection"):
145
+ assert len(deduplicate_psms(psm_list)) == 2
146
+
147
+
148
+ def _reference_with_duplicates() -> PSMList:
149
+ """Ten peptidoforms on a clean gradient, each repeated once at a wrong retention time."""
150
+ pairs = [(s, 5.0 + 3.0 * i) for i, s in enumerate(_PEPTIDES)]
151
+ pairs += [(s, 100.0 - 2.0 * i) for i, s in enumerate(_PEPTIDES)]
152
+ return _psms(pairs)
153
+
154
+
155
+ def test_calibrate_always_uses_the_first_observations():
156
+ """
157
+ ``calibrate`` fits one point per peptidoform; there is no switch to turn that off.
158
+
159
+ The reference holds each peptidoform twice: once on a clean 5 to 32 minute gradient and
160
+ once at a contradictory 82 to 100 minutes. The fit must reproduce the clean gradient.
161
+ """
162
+ reference = _reference_with_duplicates()
163
+ targets = _psms([(s, None) for s in _PEPTIDES])
164
+
165
+ calibration = core.calibrate(reference, predict_kwargs={"device": "cpu"})
166
+ predicted = core.predict(targets, return_matrix=True)
167
+ calibrated = calibration.transform(predicted[:, calibration.selected_model_head or 0])
168
+
169
+ assert np.isfinite(calibrated).all()
170
+ clean_low, clean_high = 5.0, 5.0 + 3.0 * (len(_PEPTIDES) - 1)
171
+ mean = float(calibrated.mean())
172
+ assert clean_low <= mean <= clean_high, f"fit at {mean:.1f} left the clean gradient"
173
+
174
+
175
+ def test_a_prefitted_calibration_is_the_way_to_keep_the_repeats():
176
+ """
177
+ The escape hatch for the rare caller who wants every reference PSM to count.
178
+
179
+ ``calibrate`` deduplicates unconditionally, so a caller who wants the repeats weighed fits
180
+ a ``Calibration`` on its own targets and passes it in; ``predict_and_calibrate`` then uses
181
+ it as given instead of fitting one.
182
+ """
183
+ reference = _reference_with_duplicates()
184
+ psm_list = _psms([(s, None) for s in _PEPTIDES])
185
+
186
+ source = core.predict(reference, predict_kwargs={"device": "cpu"}, return_matrix=True)
187
+ own = SplineTransformerCalibration()
188
+ own.selected_model_head = 0
189
+ own.fit(target=np.array(reference["retention_time"], dtype=np.float32), source=source[:, 0])
190
+
191
+ kept = core.predict_and_calibrate(
192
+ psm_list, psm_list_reference=reference, calibration=own, predict_kwargs={"device": "cpu"}
193
+ )
194
+ deduplicated = core.predict_and_calibrate(
195
+ psm_list, psm_list_reference=reference, predict_kwargs={"device": "cpu"}
196
+ )
197
+
198
+ assert kept.shape == deduplicated.shape == (len(_PEPTIDES),)
199
+ assert not np.allclose(kept, deduplicated)
200
+
201
+
202
+ def test_predict_and_calibrate_runs_on_a_duplicated_reference():
203
+ """One prediction per input PSM, in the input order, whatever the reference looks like."""
204
+ psm_list = _psms([(s, None) for s in _PEPTIDES])
205
+ result = core.predict_and_calibrate(
206
+ psm_list,
207
+ psm_list_reference=_reference_with_duplicates(),
208
+ predict_kwargs={"device": "cpu"},
209
+ )
210
+ assert result.shape == (len(_PEPTIDES),)
211
+ assert np.isfinite(result).all()
@@ -549,8 +549,10 @@ def test_bundled_model_predicts_in_minutes():
549
549
  assert -100.0 < out.min() < 60.0
550
550
  assert 20.0 < out.max() < 1000.0
551
551
 
552
+ # Uncalibrated output reports the DeepLC 1.x to 3.x setup, not whichever sorted first.
553
+ default_idx = list(model.task_names).index(core.DEFAULT_TASK_NAME)
552
554
  single = core.predict(peptides, model=path)
553
- np.testing.assert_allclose(single, out[:, 0], rtol=1e-5)
555
+ np.testing.assert_allclose(single, out[:, default_idx], rtol=1e-5)
554
556
 
555
557
 
556
558
  def test_small_reference_set_warns_and_widens_validation(tmp_path, caplog):
@@ -9,7 +9,7 @@ from deeplc import _model_ops
9
9
  from torch.utils.data import Dataset
10
10
 
11
11
  from deeplc._architecture import DeepLCModel
12
- from deeplc.core import DEFAULT_MODEL
12
+ from deeplc.core import LEGACY_MULTITASK_MODEL
13
13
  from deeplc.data import split_datasets
14
14
 
15
15
 
@@ -59,7 +59,7 @@ def test_train_rejects_empty_validation_loader():
59
59
 
60
60
 
61
61
  @pytest.mark.skipif(
62
- not DEFAULT_MODEL.exists(),
62
+ not LEGACY_MULTITASK_MODEL.exists(),
63
63
  reason="multitask model not bundled",
64
64
  )
65
65
  def test_load_multitask_model_without_prior_shim():
@@ -67,7 +67,7 @@ def test_load_multitask_model_without_prior_shim():
67
67
  # Remove any previously registered shim so the test is self-contained.
68
68
  sys.modules.pop("multitask_model", None)
69
69
 
70
- model = _model_ops.load_model(DEFAULT_MODEL, device="cpu")
70
+ model = _model_ops.load_model(LEGACY_MULTITASK_MODEL, device="cpu")
71
71
 
72
72
  assert isinstance(model, DeepLCModel)
73
73
 
@@ -1,130 +0,0 @@
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]
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