deeplc 4.3.0__tar.gz → 4.5.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 (56) hide show
  1. {deeplc-4.3.0/deeplc.egg-info → deeplc-4.5.0}/PKG-INFO +2 -1
  2. {deeplc-4.3.0 → deeplc-4.5.0}/deeplc/__init__.py +3 -0
  3. {deeplc-4.3.0 → deeplc-4.5.0}/deeplc/_architecture.py +54 -0
  4. deeplc-4.5.0/deeplc/_batch_features.py +218 -0
  5. deeplc-4.5.0/deeplc/_factored.py +181 -0
  6. {deeplc-4.3.0 → deeplc-4.5.0}/deeplc/_features.py +19 -1
  7. {deeplc-4.3.0 → deeplc-4.5.0}/deeplc/_model_ops.py +238 -17
  8. {deeplc-4.3.0 → deeplc-4.5.0}/deeplc/calibration/multihead.py +156 -24
  9. {deeplc-4.3.0 → deeplc-4.5.0}/deeplc/calibration/simple.py +13 -14
  10. {deeplc-4.3.0 → deeplc-4.5.0}/deeplc/core.py +122 -9
  11. {deeplc-4.3.0 → deeplc-4.5.0}/deeplc/data.py +118 -7
  12. deeplc-4.5.0/deeplc/report.py +505 -0
  13. {deeplc-4.3.0 → deeplc-4.5.0/deeplc.egg-info}/PKG-INFO +2 -1
  14. {deeplc-4.3.0 → deeplc-4.5.0}/deeplc.egg-info/SOURCES.txt +7 -1
  15. {deeplc-4.3.0 → deeplc-4.5.0}/deeplc.egg-info/requires.txt +1 -0
  16. {deeplc-4.3.0 → deeplc-4.5.0}/pyproject.toml +2 -1
  17. deeplc-4.5.0/tests/test_batch_features.py +247 -0
  18. deeplc-4.5.0/tests/test_factored.py +149 -0
  19. {deeplc-4.3.0 → deeplc-4.5.0}/tests/test_flexcnn.py +84 -0
  20. {deeplc-4.3.0 → deeplc-4.5.0}/tests/test_model_ops.py +42 -0
  21. {deeplc-4.3.0 → deeplc-4.5.0}/tests/test_multihead_calibration.py +128 -0
  22. deeplc-4.5.0/tests/test_report.py +355 -0
  23. {deeplc-4.3.0 → deeplc-4.5.0}/LICENSE +0 -0
  24. {deeplc-4.3.0 → deeplc-4.5.0}/MANIFEST.in +0 -0
  25. {deeplc-4.3.0 → deeplc-4.5.0}/README.md +0 -0
  26. {deeplc-4.3.0 → deeplc-4.5.0}/deeplc/__main__.py +0 -0
  27. {deeplc-4.3.0 → deeplc-4.5.0}/deeplc/_reference_selection.py +0 -0
  28. {deeplc-4.3.0 → deeplc-4.5.0}/deeplc/calibration/__init__.py +0 -0
  29. {deeplc-4.3.0 → deeplc-4.5.0}/deeplc/exceptions.py +0 -0
  30. {deeplc-4.3.0 → deeplc-4.5.0}/deeplc/gui.py +0 -0
  31. {deeplc-4.3.0 → deeplc-4.5.0}/deeplc/package_data/__init__.py +0 -0
  32. {deeplc-4.3.0 → deeplc-4.5.0}/deeplc/package_data/baseline_performance/__init__.py +0 -0
  33. {deeplc-4.3.0 → deeplc-4.5.0}/deeplc/package_data/baseline_performance/baseline_predictions.csv +0 -0
  34. {deeplc-4.3.0 → deeplc-4.5.0}/deeplc/package_data/examples/__init__.py +0 -0
  35. {deeplc-4.3.0 → deeplc-4.5.0}/deeplc/package_data/examples/example_psms.tsv.gz +0 -0
  36. {deeplc-4.3.0 → deeplc-4.5.0}/deeplc/package_data/gui_images/__init__.py +0 -0
  37. {deeplc-4.3.0 → deeplc-4.5.0}/deeplc/package_data/gui_images/config_icon.png +0 -0
  38. {deeplc-4.3.0 → deeplc-4.5.0}/deeplc/package_data/gui_images/deeplc_logo.png +0 -0
  39. {deeplc-4.3.0 → deeplc-4.5.0}/deeplc/package_data/gui_images/deeplc_logo.svg +0 -0
  40. {deeplc-4.3.0 → deeplc-4.5.0}/deeplc/package_data/gui_images/program_icon.png +0 -0
  41. {deeplc-4.3.0 → deeplc-4.5.0}/deeplc/package_data/models/__init__.py +0 -0
  42. {deeplc-4.3.0 → deeplc-4.5.0}/deeplc/package_data/models/full_hc_PXD005573_pub_1fd8363d9af9dcad3be7553c39396960.pt +0 -0
  43. {deeplc-4.3.0 → deeplc-4.5.0}/deeplc/package_data/models/full_hc_PXD005573_pub_8c22d89667368f2f02ad996469ba157e.pt +0 -0
  44. {deeplc-4.3.0 → deeplc-4.5.0}/deeplc/package_data/models/full_hc_PXD005573_pub_cb975cfdd4105f97efa0b3afffe075cc.pt +0 -0
  45. {deeplc-4.3.0 → deeplc-4.5.0}/deeplc/package_data/models/multitask_flexcnn_model.pt +0 -0
  46. {deeplc-4.3.0 → deeplc-4.5.0}/deeplc/package_data/models/multitask_model.pt +0 -0
  47. {deeplc-4.3.0 → deeplc-4.5.0}/deeplc/plot.py +0 -0
  48. {deeplc-4.3.0 → deeplc-4.5.0}/deeplc.egg-info/dependency_links.txt +0 -0
  49. {deeplc-4.3.0 → deeplc-4.5.0}/deeplc.egg-info/entry_points.txt +0 -0
  50. {deeplc-4.3.0 → deeplc-4.5.0}/deeplc.egg-info/top_level.txt +0 -0
  51. {deeplc-4.3.0 → deeplc-4.5.0}/setup.cfg +0 -0
  52. {deeplc-4.3.0 → deeplc-4.5.0}/tests/test_calibration.py +0 -0
  53. {deeplc-4.3.0 → deeplc-4.5.0}/tests/test_core.py +0 -0
  54. {deeplc-4.3.0 → deeplc-4.5.0}/tests/test_deduplication.py +0 -0
  55. {deeplc-4.3.0 → deeplc-4.5.0}/tests/test_features.py +0 -0
  56. {deeplc-4.3.0 → deeplc-4.5.0}/tests/test_reference_selection.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: deeplc
3
- Version: 4.3.0
3
+ Version: 4.5.0
4
4
  Summary: DeepLC: Retention time prediction for (modified) peptides using Deep Learning.
5
5
  Author: Ralf Gabriels, Kevin Velghe, Robbe Devreese, Arthur Declercq, Alireza Nameni, Ralf Gabriels, Niels Hulstaert, Sven Degroeve, Lennart Martens
6
6
  Author-email: Robbin Bouwmeester <robbin.bouwmeester@ugent.be>
@@ -223,6 +223,7 @@ Requires-Dist: numpy<3,>=1.17
223
223
  Requires-Dist: pandas<3,>=0.25
224
224
  Requires-Dist: scikit-learn<2,>=1.2.0
225
225
  Requires-Dist: psm-utils<2,>=1.5
226
+ Requires-Dist: rapidfuzz<4,>=3
226
227
  Requires-Dist: click<9,>=8
227
228
  Requires-Dist: rich<15,>=13
228
229
  Provides-Extra: gui
@@ -11,9 +11,12 @@ from deeplc.core import (
11
11
  save_model,
12
12
  train,
13
13
  )
14
+ from deeplc.report import TrainingIndex, prediction_report
14
15
 
15
16
  __version__: str = version("deeplc")
16
17
  __all__: list[str] = [
18
+ "TrainingIndex",
19
+ "prediction_report",
17
20
  "calibrate",
18
21
  "predict",
19
22
  "predict_and_calibrate",
@@ -844,6 +844,10 @@ class FlexCNNMultitaskModel(nn.Module):
844
844
  #: Index reserved for padding positions in the residue encoding.
845
845
  PAD_INDEX = 20
846
846
 
847
+ #: The fused trunk reads the per-position matrix directly, so the rolling-sum array is
848
+ #: redundant and its ``forward`` deletes it. Encoding can skip building it.
849
+ uses_rolling_sum = False
850
+
847
851
  def __init__(
848
852
  self,
849
853
  n_tasks: int,
@@ -934,6 +938,56 @@ class FlexCNNMultitaskModel(nn.Module):
934
938
  del x_atom_sum # the fused trunk reads x_atom directly
935
939
  return self.head(self.encoder(x_atom, x_global, x_one_hot), task_idx)
936
940
 
941
+ def project(
942
+ self,
943
+ x_atom: torch.Tensor,
944
+ x_atom_sum: torch.Tensor,
945
+ x_global: torch.Tensor,
946
+ x_one_hot: torch.Tensor,
947
+ ) -> torch.Tensor:
948
+ """
949
+ Map the trunk into the head's low-rank space, stopping before the per-setup step.
950
+
951
+ ``FactorHead`` finishes with ``projected @ embedding.T * scale + shift``, so this is
952
+ everything the setups share. Keeping it, rather than the ``(batch, n_tasks)`` matrix
953
+ it expands to, is what lets a whole run be held in ``(n_peptides, rank)``.
954
+
955
+ Returns
956
+ -------
957
+ torch.Tensor
958
+ Shape ``(batch, rank)``.
959
+
960
+ """
961
+ del x_atom_sum # the fused trunk reads x_atom directly
962
+ return self.head.proj(self.encoder(x_atom, x_global, x_one_hot))
963
+
964
+ @property
965
+ def padding_reach(self) -> int | None:
966
+ """
967
+ How far a valid position can see across the right edge of the encoding window.
968
+
969
+ The trunk masks its output by the true residue count and pools over that mask, and
970
+ the features themselves do not depend on the window, so the only way padding can
971
+ reach a valid position is through the convolutions. Each convolution of width ``k``
972
+ and dilation ``d`` reaches ``(k - 1) // 2 * d`` positions, and the reaches add up.
973
+ A batch encoded in a window of its longest peptide plus this many positions
974
+ therefore predicts exactly what the full window predicts, which for a median
975
+ peptide of sixteen residues is a fraction of the sixty positions used otherwise.
976
+
977
+ Returns None when the trunk pools or strides across positions, because then the
978
+ mask no longer lines up position by position and the argument does not hold.
979
+
980
+ """
981
+ reach = 0
982
+ for module in self.encoder.modules():
983
+ if isinstance(module, (nn.MaxPool1d, nn.AvgPool1d)):
984
+ return None
985
+ if isinstance(module, nn.Conv1d):
986
+ if module.stride[0] != 1:
987
+ return None
988
+ reach += ((module.kernel_size[0] - 1) // 2) * module.dilation[0]
989
+ return reach
990
+
937
991
  def add_task_head(
938
992
  self, targets: torch.Tensor | None = None, init_from: int | None = None
939
993
  ) -> int:
@@ -0,0 +1,218 @@
1
+ """
2
+ Batched feature encoding: the residue-only base for a whole batch in one pass.
3
+
4
+ :func:`deeplc._features.encode_peptidoform` stays the definition of what a feature is. What
5
+ this module adds is a faster route to the same numbers for a batch of peptidoforms, and it
6
+ only accelerates the part that depends on residue identity alone:
7
+
8
+ * the per-position atom composition matrix and the one-hot residue matrix are a table gather
9
+ and a scatter over the batch;
10
+ * the positional atom block reads the first few and last few residues of each peptide, which
11
+ is the same gather with different rows;
12
+ * the global vector is a sum along the batch's position axis.
13
+
14
+ Modifications are not reimplemented here. They occur on a quarter of a typical peptide list,
15
+ and their placement has a legacy quirk that a shipped model was trained against, so they are
16
+ applied by calling :func:`deeplc._features._apply_modifications` and its terminal counterpart
17
+ on **views into the batch arrays**. The exactness therefore comes from reusing that code
18
+ rather than from matching it.
19
+
20
+ Anything the batched route is not verified for falls back to
21
+ :func:`~deeplc._features.encode_peptidoform` per peptide, which keeps its warnings and its
22
+ exceptions rather than approximating them: peptides shorter than four residues, whose
23
+ negative positional indices wrap around the sequence in the reference encoder, and peptides
24
+ carrying a residue the one-hot block has no slot for, such as selenocysteine. Feature layouts
25
+ the route does not cover at all are rejected by :func:`supports`, and the caller keeps the
26
+ per-peptide path for those.
27
+ """
28
+
29
+ from __future__ import annotations
30
+
31
+ from collections.abc import Sequence
32
+
33
+ import numpy as np
34
+ from psm_utils import Peptidoform
35
+ from pyteomics import mass
36
+
37
+ from deeplc._features import (
38
+ DEFAULT_DICT_AA,
39
+ DEFAULT_DICT_INDEX,
40
+ DEFAULT_DICT_INDEX_POS,
41
+ DEFAULT_POSITIONS,
42
+ DEFAULT_POSITIONS_NEG,
43
+ DEFAULT_POSITIONS_POS,
44
+ _apply_modifications,
45
+ _apply_terminal_modifications,
46
+ _terminal_composition,
47
+ encode_peptidoform,
48
+ )
49
+
50
+ #: Residues the one-hot block has a slot for, in its own order.
51
+ RESIDUES: tuple[str, ...] = tuple(sorted(DEFAULT_DICT_AA, key=lambda key: DEFAULT_DICT_AA[key]))
52
+ CODE: dict[str, int] = {residue: index for index, residue in enumerate(RESIDUES)}
53
+ #: Row reserved for padding in the gather tables, holding zeros.
54
+ PAD = len(RESIDUES)
55
+ N_ATOMS = len(DEFAULT_DICT_INDEX)
56
+ _POSITIONS = DEFAULT_POSITIONS_POS | DEFAULT_POSITIONS_NEG
57
+ POS_ROWS = max(_POSITIONS) - min(_POSITIONS) + 1
58
+ POS_OFFSET = min(_POSITIONS)
59
+
60
+ #: Shortest peptide the batched route takes. Below four residues the reference encoder's
61
+ #: negative positional indices wrap around the sequence - with a single residue,
62
+ #: ``seq[seq_len - 2]`` is ``seq[-1]``, that same residue - and such peptides are rare enough
63
+ #: that reproducing the wrap in vectorised form is not worth the risk of getting it wrong.
64
+ MIN_LENGTH = 4
65
+
66
+
67
+ def _gather_table(atom_index: dict[str, int]) -> np.ndarray:
68
+ """Atom counts per residue under one atom ordering, with a zero row for padding."""
69
+ table = np.zeros((PAD + 1, N_ATOMS), dtype=np.float16)
70
+ for residue, row in CODE.items():
71
+ for atom, count in mass.std_aa_comp[residue].items():
72
+ column = atom_index.get(atom)
73
+ if column is not None:
74
+ table[row, column] = count
75
+ return table
76
+
77
+
78
+ COMPOSITION = _gather_table(DEFAULT_DICT_INDEX)
79
+ POSITIONAL = _gather_table(DEFAULT_DICT_INDEX_POS)
80
+ #: An unmodified peptidoform contributes nothing to the terminal block: the reference reads
81
+ #: the ``n_term`` and ``c_term`` properties, which are empty, and returns zeros. The backbone
82
+ #: termini are already inside the residue compositions.
83
+ TERMINI = np.zeros((2, N_ATOMS), dtype=np.float16)
84
+
85
+
86
+ def supports(add_ccs_features: bool, include_rolling_sum: bool) -> bool:
87
+ """
88
+ Whether the batched route covers a feature layout.
89
+
90
+ It does not build the rolling-sum matrix, which the four-branch model reads, and it does
91
+ not build the collision cross section extras, which need the precursor charge and a
92
+ handful of residue fractions. A caller asking for either keeps the per-peptide path.
93
+ """
94
+ return not add_ccs_features and not include_rolling_sum
95
+
96
+
97
+ def _as_peptidoform(peptidoform: Peptidoform | str) -> Peptidoform:
98
+ """Parse a ProForma string if that is what a dataset holds, else pass it through."""
99
+ return peptidoform if hasattr(peptidoform, "sequence") else Peptidoform(str(peptidoform))
100
+
101
+
102
+ def encode_batch_features(
103
+ peptidoforms: Sequence[Peptidoform | str],
104
+ padding_length: int = 60,
105
+ add_terminal_composition: bool = True,
106
+ legacy_positional_deltas: bool = True,
107
+ ) -> dict[str, np.ndarray]:
108
+ """
109
+ Encode a batch of peptidoforms, gathering the base and patching the modified ones.
110
+
111
+ Parameters
112
+ ----------
113
+ peptidoforms
114
+ The peptidoforms to encode, parsed or as ProForma strings.
115
+ padding_length
116
+ Window the per-position matrices are padded or truncated to.
117
+ add_terminal_composition
118
+ Whether to append the N- and C-terminal group compositions to the global vector.
119
+ legacy_positional_deltas
120
+ Whether modification deltas go into the positional block the way versions before
121
+ 4.0.1 placed them, which every released model was trained against.
122
+
123
+ Returns
124
+ -------
125
+ dict of str to numpy.ndarray
126
+ ``matrix``, ``matrix_global`` and ``matrix_hc``, batched along the first axis and
127
+ equal value for value, dtype included, to stacking what
128
+ :func:`~deeplc._features.encode_peptidoform` returns for each peptidoform.
129
+
130
+ """
131
+ parsed = [_as_peptidoform(p) for p in peptidoforms]
132
+ n = len(parsed)
133
+ sequences = [p.sequence for p in parsed]
134
+ lengths = np.fromiter(
135
+ (min(len(sequence), padding_length) for sequence in sequences), dtype=np.int64, count=n
136
+ )
137
+ reference_rows = {
138
+ row
139
+ for row, sequence in enumerate(sequences)
140
+ if len(sequence) < MIN_LENGTH or any(residue not in CODE for residue in sequence)
141
+ }
142
+
143
+ residues = np.full((n, padding_length), PAD, dtype=np.int64)
144
+ for row, (sequence, length) in enumerate(zip(sequences, lengths, strict=True)):
145
+ if row not in reference_rows:
146
+ residues[row, :length] = [CODE[residue] for residue in sequence[:length]]
147
+
148
+ matrix = COMPOSITION[residues]
149
+ one_hot = np.zeros((n, padding_length, len(DEFAULT_DICT_AA)), dtype=np.float16)
150
+ rows, columns = np.nonzero(residues != PAD)
151
+ one_hot[rows, columns, residues[rows, columns]] = 1.0
152
+
153
+ positional = np.zeros((n, POS_ROWS, N_ATOMS), dtype=np.float16)
154
+ for position in sorted(DEFAULT_POSITIONS_POS):
155
+ taken = lengths > position
156
+ positional[taken, position - POS_OFFSET] = POSITIONAL[residues[taken, position]]
157
+ for position in sorted(DEFAULT_POSITIONS_NEG):
158
+ taken = lengths + position >= 0
159
+ positional[taken, position - POS_OFFSET] = POSITIONAL[
160
+ residues[np.nonzero(taken)[0], (lengths + position)[taken]]
161
+ ]
162
+
163
+ terminal = np.repeat(TERMINI[None, :, :], n, axis=0) if add_terminal_composition else None
164
+
165
+ for row, peptidoform in enumerate(parsed):
166
+ if row in reference_rows:
167
+ continue
168
+ tokens = peptidoform.parsed_sequence
169
+ if any(token[1] is not None for token in tokens):
170
+ _apply_modifications(
171
+ matrix[row],
172
+ positional[row],
173
+ tokens,
174
+ int(lengths[row]),
175
+ DEFAULT_DICT_INDEX,
176
+ DEFAULT_DICT_INDEX_POS,
177
+ DEFAULT_POSITIONS,
178
+ legacy_positional_deltas,
179
+ )
180
+ properties = peptidoform.properties
181
+ if properties.get("n_term") or properties.get("c_term"):
182
+ _apply_terminal_modifications(
183
+ matrix[row],
184
+ positional[row],
185
+ peptidoform,
186
+ int(lengths[row]),
187
+ DEFAULT_DICT_INDEX,
188
+ DEFAULT_DICT_INDEX_POS,
189
+ DEFAULT_POSITIONS,
190
+ legacy_positional_deltas,
191
+ )
192
+ if terminal is not None:
193
+ terminal[row] = _terminal_composition(peptidoform, DEFAULT_DICT_INDEX)
194
+
195
+ # float64, because the reference promotes when it appends the integer length to a float16
196
+ # sum. The dataset casts to float32 afterwards either way, but the dtype is observable.
197
+ blocks = [
198
+ matrix.sum(axis=1).astype(np.float64),
199
+ lengths[:, None].astype(np.float64),
200
+ positional.reshape(n, -1).astype(np.float64),
201
+ ]
202
+ if terminal is not None:
203
+ blocks.append(terminal.reshape(n, -1).astype(np.float64))
204
+ matrix_global = np.concatenate(blocks, axis=1)
205
+
206
+ for row in sorted(reference_rows):
207
+ features = encode_peptidoform(
208
+ parsed[row],
209
+ add_terminal_composition=add_terminal_composition,
210
+ padding_length=padding_length,
211
+ legacy_positional_deltas=legacy_positional_deltas,
212
+ include_rolling_sum=False,
213
+ )
214
+ matrix[row] = features["matrix"]
215
+ one_hot[row] = features["matrix_hc"]
216
+ matrix_global[row] = features["matrix_global"]
217
+
218
+ return {"matrix": matrix, "matrix_global": matrix_global, "matrix_hc": one_hot}
@@ -0,0 +1,181 @@
1
+ """A prediction matrix held as its low-rank factors rather than materialised."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import numpy as np
6
+
7
+ __all__ = ["FactoredPredictionMatrix"]
8
+
9
+
10
+ class FactoredPredictionMatrix:
11
+ """
12
+ A prediction matrix kept as its low-rank factors.
13
+
14
+ Holds the ``(n_peptides, n_tasks)`` output of a
15
+ :class:`~deeplc._architecture.FactorHead` as the factors it is computed from.
16
+
17
+ That head is low rank by construction::
18
+
19
+ pred[:, j] = (proj(trunk).embedding[j]) * scale[j] + shift[j]
20
+
21
+ so the whole matrix is determined by ``proj(trunk)``, which is ``(n_peptides, rank)``,
22
+ together with the head's own parameters. At rank 64 and 6,543 setups that is 102 times
23
+ smaller than the matrix it stands for: 2.6 M peptides need 0.6 GiB of factors instead of
24
+ 63 GiB of predictions.
25
+
26
+ It indexes like the matrix. ``m[rows]``, ``m[:, heads]`` and ``m[rows, head]`` each
27
+ evaluate only what was asked for, so a caller that reads a few thousand rows to choose a
28
+ head and then one column per run never builds the rest. ``np.asarray(m)`` still gives the
29
+ dense matrix for code that genuinely needs it, at its full size.
30
+
31
+ Parameters
32
+ ----------
33
+ projections
34
+ ``proj(trunk)`` for every peptide, shape ``(n_peptides, rank)``.
35
+ embedding
36
+ Per-setup embedding, shape ``(n_tasks, rank)``.
37
+ scale, shift
38
+ Per-setup affine map, shape ``(n_tasks,)``.
39
+
40
+ """
41
+
42
+ #: Marks this as a source a calibration may index instead of a materialised matrix.
43
+ is_head_source = True
44
+
45
+ def __init__(
46
+ self,
47
+ projections: np.ndarray,
48
+ embedding: np.ndarray,
49
+ scale: np.ndarray,
50
+ shift: np.ndarray,
51
+ ) -> None:
52
+ self._projections = np.asarray(projections)
53
+ self._embedding = np.asarray(embedding, dtype=self._projections.dtype)
54
+ self._scale = np.asarray(scale, dtype=self._projections.dtype)
55
+ self._shift = np.asarray(shift, dtype=self._projections.dtype)
56
+ if self._embedding.shape[1] != self._projections.shape[1]:
57
+ raise ValueError(
58
+ f"embedding rank {self._embedding.shape[1]} does not match projection rank "
59
+ f"{self._projections.shape[1]}"
60
+ )
61
+
62
+ @property
63
+ def shape(self) -> tuple[int, int]:
64
+ """Rows and task count, without evaluating anything."""
65
+ return (self._projections.shape[0], self._embedding.shape[0])
66
+
67
+ @property
68
+ def ndim(self) -> int:
69
+ """Always two: this stands in for a matrix."""
70
+ return 2
71
+
72
+ @property
73
+ def dtype(self) -> np.dtype:
74
+ """Element type of the matrix it stands for."""
75
+ return self._projections.dtype
76
+
77
+ @property
78
+ def rank(self) -> int:
79
+ """Width of the factorisation."""
80
+ return self._projections.shape[1]
81
+
82
+ @property
83
+ def nbytes(self) -> int:
84
+ """What the factors occupy."""
85
+ return int(
86
+ self._projections.nbytes
87
+ + self._embedding.nbytes
88
+ + self._scale.nbytes
89
+ + self._shift.nbytes
90
+ )
91
+
92
+ @property
93
+ def dense_nbytes(self) -> int:
94
+ """What the matrix would occupy if it were materialised."""
95
+ rows, columns = self.shape
96
+ return int(rows * columns * self._projections.itemsize)
97
+
98
+ def __len__(self) -> int:
99
+ """Return the number of peptides."""
100
+ return self.shape[0]
101
+
102
+ def _evaluate(self, rows, columns) -> np.ndarray:
103
+ """Compute just the requested block from the factors."""
104
+ projections = self._projections if rows is None else self._projections[rows]
105
+ if projections.ndim == 1:
106
+ projections = projections[None, :]
107
+ if columns is None:
108
+ embedding, scale, shift = self._embedding, self._scale, self._shift
109
+ else:
110
+ embedding = np.atleast_2d(self._embedding[columns])
111
+ scale = np.atleast_1d(self._scale[columns])
112
+ shift = np.atleast_1d(self._shift[columns])
113
+ return (projections @ embedding.T) * scale + shift
114
+
115
+ def _select_rows(self, rows) -> FactoredPredictionMatrix:
116
+ """Narrow to a subset of peptides, still as factors."""
117
+ return FactoredPredictionMatrix(
118
+ self._projections[rows], self._embedding, self._scale, self._shift
119
+ )
120
+
121
+ def __getitem__(self, key):
122
+ """
123
+ Index as the dense matrix would, evaluating only the block that is asked for.
124
+
125
+ Selecting rows alone gives another factored matrix rather than a dense one. That is
126
+ what lets a caller narrow to one run's peptides and still hand the result to a
127
+ calibration, which reads a few dozen of the thousands of heads: nothing in that path
128
+ ever builds the wide matrix. A scalar in either position drops that axis, as numpy
129
+ does, so ``m[rows, head]`` is one dimensional and ``m[i, j]`` is a scalar.
130
+ """
131
+ rows, columns = key if isinstance(key, tuple) else (key, None)
132
+ if isinstance(rows, slice) and rows == slice(None):
133
+ rows = None
134
+ if columns is None and rows is not None and not _is_scalar(rows):
135
+ return self._select_rows(rows)
136
+ row_scalar = _is_scalar(rows)
137
+ column_scalar = columns is not None and _is_scalar(columns)
138
+ block = self._evaluate(rows, columns)
139
+ if row_scalar:
140
+ block = block[0]
141
+ return block[0] if column_scalar else block
142
+ return block[:, 0] if column_scalar else block
143
+
144
+ def __array__(self, dtype=None, copy=None) -> np.ndarray:
145
+ """Return the whole matrix, for callers that really need it, at its full size."""
146
+ dense = self._evaluate(None, None)
147
+ return dense if dtype is None else dense.astype(dtype)
148
+
149
+ def __getattr__(self, name: str):
150
+ """
151
+ Fall back to the dense matrix for anything not answered from the factors.
152
+
153
+ Reductions such as ``.min()`` and ``.mean()`` have no cheap factored form, so code
154
+ that calls them gets the same answer it always did, at the same cost it always had.
155
+ Only indexing, which is the path that matters for a wide matrix, stays lazy.
156
+ """
157
+ if name.startswith("_"):
158
+ raise AttributeError(name)
159
+ return getattr(np.asarray(self), name)
160
+
161
+ def __repr__(self) -> str:
162
+ """Show the shape it stands for and what it actually costs."""
163
+ rows, columns = self.shape
164
+ return (
165
+ f"{type(self).__name__}(shape=({rows}, {columns}), rank={self.rank}, "
166
+ f"{_human(self.nbytes)} held for a {_human(self.dense_nbytes)} matrix)"
167
+ )
168
+
169
+
170
+ def _is_scalar(index) -> bool:
171
+ """Whether an index selects one element rather than a subset."""
172
+ return np.isscalar(index) or (isinstance(index, np.generic) and np.ndim(index) == 0)
173
+
174
+
175
+ def _human(n: int) -> str:
176
+ """Format a byte count in the largest unit that keeps it above one."""
177
+ for unit in ("B", "KiB", "MiB", "GiB"):
178
+ if n < 1024 or unit == "GiB":
179
+ return f"{n:.1f} {unit}" if unit != "B" else f"{n} B"
180
+ n /= 1024
181
+ return f"{n:.1f} GiB"
@@ -40,6 +40,7 @@ def encode_peptidoform(
40
40
  dict_index_pos: dict[str, int] | None = None,
41
41
  dict_index: dict[str, int] | None = None,
42
42
  legacy_positional_deltas: bool = False,
43
+ include_rolling_sum: bool = True,
43
44
  ) -> dict[str, np.ndarray]:
44
45
  """
45
46
  Extract features from a single peptidoform.
@@ -58,6 +59,10 @@ def encode_peptidoform(
58
59
  modification on the same residue are indistinguishable.
59
60
  padding_length
60
61
  The maximum length of the sequence after padding. Default is 60.
62
+ include_rolling_sum
63
+ Whether to build ``matrix_sum``, the rolling sum over pairs of positions. Models
64
+ with a convolutional trunk ignore it; False returns an empty array in its place.
65
+ Default is True.
61
66
  legacy_positional_deltas
62
67
  Whether to place modification deltas in the positional block the way versions
63
68
  before 4.0.1 did, which was to index ``pos_mat`` without the sorted-layout
@@ -139,7 +144,14 @@ def encode_peptidoform(
139
144
  matrix_all = np.append(matrix_all, (seq.count("K") + seq.count("R")) / seq_len)
140
145
  matrix_all = np.append(matrix_all, charge)
141
146
 
142
- matrix_sum = _compute_rolling_sum(std_matrix.T, n=2)[:, ::2].T
147
+ # The fused trunk reads the per-position matrix directly and deletes this one on the
148
+ # first line of its forward, so building it is pure cost for those models: the cumulative
149
+ # sum and its slicing are about a tenth of the encoding work.
150
+ matrix_sum = (
151
+ _compute_rolling_sum(std_matrix.T, n=2)[:, ::2].T
152
+ if include_rolling_sum
153
+ else np.zeros((0, len(dict_index)), dtype=np.float16)
154
+ )
143
155
 
144
156
  matrix_global = np.concatenate([matrix_all, pos_matrix.flatten()])
145
157
  if add_terminal_composition:
@@ -337,6 +349,12 @@ def _apply_composition_to_matrices(
337
349
  except KeyError:
338
350
  warnings.warn(f"Ignoring atom {atom_comp} at pos {i}", stacklevel=2)
339
351
  continue
352
+ except IndexError:
353
+ # Same guard as the branch below, which this one was missing: a modification
354
+ # placed beyond the padding window has no row to add itself to. Reachable
355
+ # with an isotope-labelled modification, so a TMT or SILAC label, on a
356
+ # peptide longer than the window, where it raised instead of warning.
357
+ warnings.warn(f"Index error for atom {atom_comp} at pos {i}", stacklevel=2)
340
358
  except IndexError:
341
359
  warnings.warn(f"Index error for atom {atom_comp} at pos {i}", stacklevel=2)
342
360