deeplc 4.1.1__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.1/deeplc.egg-info → deeplc-4.2.0}/PKG-INFO +1 -1
  2. {deeplc-4.1.1 → deeplc-4.2.0}/deeplc/__main__.py +8 -1
  3. deeplc-4.2.0/deeplc/_reference_selection.py +235 -0
  4. {deeplc-4.1.1 → deeplc-4.2.0}/deeplc/core.py +15 -1
  5. {deeplc-4.1.1 → deeplc-4.2.0/deeplc.egg-info}/PKG-INFO +1 -1
  6. {deeplc-4.1.1 → deeplc-4.2.0}/deeplc.egg-info/SOURCES.txt +1 -0
  7. {deeplc-4.1.1 → deeplc-4.2.0}/pyproject.toml +1 -1
  8. deeplc-4.2.0/tests/test_deduplication.py +211 -0
  9. deeplc-4.1.1/deeplc/_reference_selection.py +0 -130
  10. {deeplc-4.1.1 → deeplc-4.2.0}/LICENSE +0 -0
  11. {deeplc-4.1.1 → deeplc-4.2.0}/MANIFEST.in +0 -0
  12. {deeplc-4.1.1 → deeplc-4.2.0}/README.md +0 -0
  13. {deeplc-4.1.1 → deeplc-4.2.0}/deeplc/__init__.py +0 -0
  14. {deeplc-4.1.1 → deeplc-4.2.0}/deeplc/_architecture.py +0 -0
  15. {deeplc-4.1.1 → deeplc-4.2.0}/deeplc/_features.py +0 -0
  16. {deeplc-4.1.1 → deeplc-4.2.0}/deeplc/_model_ops.py +0 -0
  17. {deeplc-4.1.1 → deeplc-4.2.0}/deeplc/calibration.py +0 -0
  18. {deeplc-4.1.1 → deeplc-4.2.0}/deeplc/data.py +0 -0
  19. {deeplc-4.1.1 → deeplc-4.2.0}/deeplc/exceptions.py +0 -0
  20. {deeplc-4.1.1 → deeplc-4.2.0}/deeplc/gui.py +0 -0
  21. {deeplc-4.1.1 → deeplc-4.2.0}/deeplc/package_data/__init__.py +0 -0
  22. {deeplc-4.1.1 → deeplc-4.2.0}/deeplc/package_data/baseline_performance/__init__.py +0 -0
  23. {deeplc-4.1.1 → deeplc-4.2.0}/deeplc/package_data/baseline_performance/baseline_predictions.csv +0 -0
  24. {deeplc-4.1.1 → deeplc-4.2.0}/deeplc/package_data/examples/__init__.py +0 -0
  25. {deeplc-4.1.1 → deeplc-4.2.0}/deeplc/package_data/examples/example_psms.tsv.gz +0 -0
  26. {deeplc-4.1.1 → deeplc-4.2.0}/deeplc/package_data/gui_images/__init__.py +0 -0
  27. {deeplc-4.1.1 → deeplc-4.2.0}/deeplc/package_data/gui_images/config_icon.png +0 -0
  28. {deeplc-4.1.1 → deeplc-4.2.0}/deeplc/package_data/gui_images/deeplc_logo.png +0 -0
  29. {deeplc-4.1.1 → deeplc-4.2.0}/deeplc/package_data/gui_images/deeplc_logo.svg +0 -0
  30. {deeplc-4.1.1 → deeplc-4.2.0}/deeplc/package_data/gui_images/program_icon.png +0 -0
  31. {deeplc-4.1.1 → deeplc-4.2.0}/deeplc/package_data/models/__init__.py +0 -0
  32. {deeplc-4.1.1 → deeplc-4.2.0}/deeplc/package_data/models/full_hc_PXD005573_pub_1fd8363d9af9dcad3be7553c39396960.pt +0 -0
  33. {deeplc-4.1.1 → deeplc-4.2.0}/deeplc/package_data/models/full_hc_PXD005573_pub_8c22d89667368f2f02ad996469ba157e.pt +0 -0
  34. {deeplc-4.1.1 → deeplc-4.2.0}/deeplc/package_data/models/full_hc_PXD005573_pub_cb975cfdd4105f97efa0b3afffe075cc.pt +0 -0
  35. {deeplc-4.1.1 → deeplc-4.2.0}/deeplc/package_data/models/multitask_flexcnn_model.pt +0 -0
  36. {deeplc-4.1.1 → deeplc-4.2.0}/deeplc/package_data/models/multitask_model.pt +0 -0
  37. {deeplc-4.1.1 → deeplc-4.2.0}/deeplc/plot.py +0 -0
  38. {deeplc-4.1.1 → deeplc-4.2.0}/deeplc.egg-info/dependency_links.txt +0 -0
  39. {deeplc-4.1.1 → deeplc-4.2.0}/deeplc.egg-info/entry_points.txt +0 -0
  40. {deeplc-4.1.1 → deeplc-4.2.0}/deeplc.egg-info/requires.txt +0 -0
  41. {deeplc-4.1.1 → deeplc-4.2.0}/deeplc.egg-info/top_level.txt +0 -0
  42. {deeplc-4.1.1 → deeplc-4.2.0}/setup.cfg +0 -0
  43. {deeplc-4.1.1 → deeplc-4.2.0}/tests/test_calibration.py +0 -0
  44. {deeplc-4.1.1 → deeplc-4.2.0}/tests/test_core.py +0 -0
  45. {deeplc-4.1.1 → deeplc-4.2.0}/tests/test_features.py +0 -0
  46. {deeplc-4.1.1 → deeplc-4.2.0}/tests/test_flexcnn.py +0 -0
  47. {deeplc-4.1.1 → deeplc-4.2.0}/tests/test_model_ops.py +0 -0
  48. {deeplc-4.1.1 → 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.1
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>
@@ -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,
@@ -164,6 +164,13 @@ def calibrate(
164
164
  Fitted calibration instance.
165
165
 
166
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
+
167
174
  # Get calibration
168
175
  if calibration is None:
169
176
  LOGGER.debug("No calibration provided, using SplineTransformerCalibration by default.")
@@ -232,6 +239,7 @@ def predict_and_calibrate(
232
239
  predict_kwargs
233
240
  Additional keyword arguments to pass to the prediction function.
234
241
 
242
+
235
243
  Returns
236
244
  -------
237
245
  np.ndarray
@@ -313,6 +321,7 @@ def finetune_and_predict(
313
321
  predict_kwargs
314
322
  Additional keyword arguments to pass to the prediction function.
315
323
 
324
+
316
325
  Returns
317
326
  -------
318
327
  np.ndarray
@@ -443,6 +452,11 @@ def finetune(
443
452
  """
444
453
  LOGGER.info("Fine-tuning model...")
445
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
+
446
460
  # Fine-tuning needs enough reference data to both fit and validate on. The
447
461
  # default validation split leaves too few PSMs to early-stop against on a small
448
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.1
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>
@@ -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.1"
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" }
@@ -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()
@@ -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
File without changes
File without changes
File without changes
File without changes