simms-gpu 1.0.0__py3-none-any.whl

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.
@@ -0,0 +1,178 @@
1
+ """matchms score containers and tiled dense / coordinate-restricted sparse output."""
2
+
3
+ import inspect
4
+
5
+ import numpy as np
6
+ import torch
7
+ from matchms import Scores
8
+ from matchms.similarity.base_similarity import BaseSimilarityWithSparse
9
+
10
+
11
+ class CudaSimilarity(BaseSimilarityWithSparse):
12
+ score_datatype = np.dtype([("score", np.float64), ("matches", np.int_)])
13
+ score_fields = score_datatype.names
14
+
15
+ def to_dict(self):
16
+ params = {}
17
+ for name in inspect.signature(type(self)).parameters:
18
+ value = getattr(self, name)
19
+ params[name] = value.item() if isinstance(value, np.generic) else value
20
+ return {"__Similarity__": type(self).__name__, **params}
21
+
22
+ def _fields(self, score_fields):
23
+ if isinstance(score_fields, str):
24
+ score_fields = (score_fields,)
25
+ fields = self._resolve_score_fields(score_fields)
26
+ if len(set(fields)) != len(fields):
27
+ raise ValueError("score_fields must be unique")
28
+ return fields
29
+
30
+ def pair(self, spectrum_1, spectrum_2):
31
+ """Return the same zero-dimensional structured array as matchms."""
32
+ return self.matrix([spectrum_1], [spectrum_2], progress_bar=False, array_type="numpy").reshape(())
33
+
34
+ def matrix(self, spectra_1, spectra_2=None, score_fields=None, progress_bar=True, array_type="scores"):
35
+ """Return Scores, a structured NumPy array, or a device tensor.
36
+
37
+ Torch planes follow score_fields order, by default (score, matches), with
38
+ shape (2, rows, columns) and the requested floating-point precision.
39
+ """
40
+ fields = self._fields(score_fields)
41
+ if array_type not in ("scores", "numpy", "torch"):
42
+ raise ValueError("array_type must be 'scores', 'numpy' or 'torch'")
43
+ left, right, symmetric = self._inputs(spectra_1, spectra_2)
44
+ shape = (len(left), len(right))
45
+ if array_type == "torch":
46
+ result = torch.empty(
47
+ (len(fields), *shape), dtype=getattr(torch, self.precision), device=self.device
48
+ )
49
+ elif array_type == "numpy":
50
+ result = np.empty(shape, dtype=[(f, self.score_datatype[f]) for f in fields])
51
+ else:
52
+ result = self._create_dense_result(*shape, fields)
53
+
54
+ for rows, cols, _, tile in self._tiles(left, right, symmetric, None, progress_bar):
55
+ if array_type != "torch":
56
+ tile = tile.cpu().numpy()
57
+ for plane, field in enumerate(fields):
58
+ values = tile[self.score_fields.index(field)].reshape(
59
+ rows.stop - rows.start, cols.stop - cols.start
60
+ )
61
+ dest = result[plane] if array_type == "torch" else result[field]
62
+ dest[rows, cols] = values
63
+ if symmetric and rows.start != cols.start:
64
+ dest[cols, rows] = values.T
65
+ return Scores(result) if array_type == "scores" else result
66
+
67
+ def _coordinate_tiles(self, idx_row, idx_col, shape, symmetric):
68
+ if idx_row is None and idx_col is None:
69
+ return None
70
+ if idx_row is None or idx_col is None:
71
+ raise ValueError("idx_row and idx_col must be given together")
72
+ row, col = np.asarray(idx_row), np.asarray(idx_col)
73
+ if row.ndim != 1 or row.shape != col.shape:
74
+ raise ValueError("idx_row and idx_col must be aligned 1D arrays")
75
+ for index, size in zip((row, col), shape):
76
+ if index.size and index.dtype.kind not in "iu":
77
+ raise TypeError("sparse coordinates must be integers")
78
+ if np.any(index < 0) or np.any(index >= size):
79
+ raise ValueError("sparse coordinate out of bounds")
80
+ tiles = {}
81
+ for i, j in zip(row, col):
82
+ i, j = int(i), int(j)
83
+ if symmetric and i > j:
84
+ i, j = j, i
85
+ r, c = i - i % self.batch_size, j - j % self.batch_size
86
+ width = min(self.batch_size, shape[1] - c)
87
+ tiles.setdefault(r, {}).setdefault(c, []).append((i - r) * width + j - c)
88
+ for columns in tiles.values():
89
+ for c, positions in columns.items():
90
+ columns[c] = list(dict.fromkeys(positions))
91
+ return tiles
92
+
93
+ def _filtered_tiles(self, tiles, symmetric, min_score, min_matches, score_filter=None, diagonal=0):
94
+ """Yield retained upper-triangle or rectangular coordinates and full host records."""
95
+ predicate = score_filter
96
+ if predicate is None and getattr(self.keep_score, "__func__", None) is not BaseSimilarityWithSparse.keep_score:
97
+ predicate = self.keep_score
98
+ structured = self.is_structured_score
99
+ score_dtype = self.score_datatype["score"] if structured else self.score_datatype
100
+ for rs, cs, positions, tile in tiles:
101
+ score = tile[0] if structured else tile
102
+ keep = None
103
+ if min_score is not None:
104
+ # Compare at the precision of the public NumPy score and threshold.
105
+ dtype = np.result_type(score_dtype, min_score)
106
+ keep = score.to(getattr(torch, dtype.name)) >= min_score
107
+ if min_matches is not None:
108
+ enough = tile[1].double() >= min_matches
109
+ keep = enough if keep is None else keep & enough
110
+ if predicate is None and keep is None:
111
+ keep = score != 0
112
+ if structured:
113
+ keep &= tile[1] != 0
114
+
115
+ width = cs.stop - cs.start
116
+ if symmetric and rs == cs and positions is None:
117
+ # Explicit coordinates have already been canonicalized and deduplicated.
118
+ if keep is None:
119
+ keep = torch.ones_like(score, dtype=torch.bool)
120
+ keep.view(-1, width).triu_(diagonal)
121
+
122
+ if keep is None:
123
+ # An arbitrary Python predicate needs every remaining candidate.
124
+ local = np.arange(score.numel()) if positions is None else positions
125
+ else:
126
+ indices = torch.nonzero(keep).flatten()
127
+ if not indices.numel():
128
+ continue
129
+ tile = tile.index_select(-1, indices)
130
+ local = indices.cpu().numpy()
131
+ if positions is not None:
132
+ local = positions[local]
133
+ host = tile.cpu().numpy()
134
+ if structured:
135
+ values = np.empty(len(local), dtype=self.score_datatype)
136
+ values["score"], values["matches"] = host
137
+ else:
138
+ values = host
139
+ if predicate is not None:
140
+ keep = np.fromiter(map(predicate, self._predicate_values(values)), bool, count=len(local))
141
+ local, values = local[keep], values[keep]
142
+ if len(local):
143
+ i, j = np.divmod(local, width)
144
+ yield i + rs.start, j + cs.start, values
145
+
146
+ _predicate_values = staticmethod(iter)
147
+
148
+ def sparse_matrix(
149
+ self, spectra_1, spectra_2=None, idx_row=None, idx_col=None,
150
+ score_fields=None, score_filter=None, progress_bar=True, *, min_score=None, min_matches=None,
151
+ ):
152
+ """Apply inclusive device thresholds before any callable and field projection."""
153
+ fields = self._fields(score_fields)
154
+ left, right, symmetric = self._inputs(spectra_1, spectra_2)
155
+ # SciPy sparse fingerprint matrices expose their number of rows only via shape.
156
+ shape = tuple(data.shape[0] if hasattr(data, "shape") else len(data) for data in (left, right))
157
+ requested = self._coordinate_tiles(idx_row, idx_col, shape, symmetric)
158
+ tiles = self._tiles(left, right, symmetric, requested, progress_bar)
159
+ chunks = []
160
+ for i, j, values in self._filtered_tiles(tiles, symmetric, min_score, min_matches, score_filter):
161
+ chunks.append((i, j, values))
162
+ if symmetric:
163
+ off = i != j
164
+ chunks.append((j[off], i[off], values[off]))
165
+ if chunks:
166
+ rows, cols, values = map(np.concatenate, zip(*chunks))
167
+ else:
168
+ rows = cols = np.empty(0, dtype=np.intp)
169
+ values = np.empty(0, dtype=self.score_datatype)
170
+ return Scores(self._build_sparse_result(rows, cols, values, shape, fields))
171
+
172
+
173
+ class _ScalarCudaSimilarity(CudaSimilarity):
174
+ def sparse_matrix(self, spectra_1, spectra_2=None, idx_row=None, idx_col=None,
175
+ score_fields=None, score_filter=None, progress_bar=True, *, min_score=None):
176
+ """Apply an inclusive device score threshold before any callable."""
177
+ return super().sparse_matrix(spectra_1, spectra_2, idx_row, idx_col, score_fields,
178
+ score_filter, progress_bar, min_score=min_score)
@@ -0,0 +1,270 @@
1
+ # SPDX-License-Identifier: MIT
2
+ """Greedy peak evidence for retained edges and paths on the direct network."""
3
+
4
+ from functools import lru_cache
5
+ from math import sqrt
6
+
7
+ import numpy as np
8
+ from matchms.similarity.spectrum_similarity_functions import collect_peak_pairs
9
+ from numba import cuda, float32, float64, int32, uint8
10
+
11
+ from .CudaCosineGreedy import _scratch_size
12
+ from .spectrum_similarity_functions import _collect, _sift_down, peak_weights
13
+
14
+
15
+ @lru_cache(maxsize=32)
16
+ def _alignment_kernel(width, capacity, precision):
17
+ real = float64 if precision == "float64" else float32
18
+
19
+ @cuda.jit
20
+ def kernel(
21
+ mz,
22
+ weights,
23
+ norms,
24
+ lengths,
25
+ precursors,
26
+ endpoints,
27
+ tolerance,
28
+ limit,
29
+ starts,
30
+ steps,
31
+ maps,
32
+ scores,
33
+ counts,
34
+ assignment,
35
+ ):
36
+ k = cuda.grid(1)
37
+ if k >= len(endpoints):
38
+ return
39
+ u, v = endpoints[k]
40
+ nr, nq = lengths[u], lengths[v]
41
+ scores[k], counts[k] = 0, 0
42
+ if nr > mz.shape[1] or nq > mz.shape[1]:
43
+ counts[k] = -1
44
+ return
45
+ if norms[u] == 0 or norms[v] == 0:
46
+ return
47
+
48
+ left = cuda.local.array(capacity, int32)
49
+ right = cuda.local.array(capacity, int32)
50
+ order = cuda.local.array(capacity, int32)
51
+ values = cuda.local.array(capacity, real)
52
+ count = 0
53
+ delta = precursors[u] - precursors[v]
54
+ begin, end = starts[k], starts[k + 1]
55
+ if begin < end:
56
+ survived = False
57
+ for a in range(nr):
58
+ b = a
59
+ for hop in range(begin, end):
60
+ b = maps[steps[hop] + b]
61
+ if b == -1:
62
+ break
63
+ if b == -1:
64
+ continue
65
+ survived = True
66
+ low, high = float64(mz[u, a]) - tolerance, float64(mz[u, a]) + tolerance
67
+ mass = float64(mz[v, b])
68
+ if low <= mass <= high or (abs(delta) > tolerance and low <= mass + delta <= high):
69
+ continue # The later endpoint candidate supplies its tie order.
70
+ if count == limit:
71
+ counts[k] = -1
72
+ return
73
+ left[count], right[count], order[count] = a, b, count
74
+ values[count] = weights[u, a] * weights[v, b]
75
+ count += 1
76
+ if not survived:
77
+ return
78
+
79
+ bridge_count = count
80
+ count = _collect(
81
+ mz[u],
82
+ weights[u],
83
+ nr,
84
+ mz[v],
85
+ weights[v],
86
+ nq,
87
+ tolerance,
88
+ 0.0,
89
+ count,
90
+ limit,
91
+ left,
92
+ right,
93
+ order,
94
+ values,
95
+ False,
96
+ )
97
+ if count >= 0 and abs(delta) > tolerance:
98
+ unshifted_end = count
99
+ count = _collect(
100
+ mz[u],
101
+ weights[u],
102
+ nr,
103
+ mz[v],
104
+ weights[v],
105
+ nq,
106
+ tolerance,
107
+ delta,
108
+ count,
109
+ limit,
110
+ left,
111
+ right,
112
+ order,
113
+ values,
114
+ False,
115
+ )
116
+ if count > unshifted_end:
117
+ # Keep the later (shifted) occurrence when both windows cover
118
+ # the same pair. Heap priority still uses original candidate IDs.
119
+ size = bridge_count
120
+ for idx in range(bridge_count, count):
121
+ if idx < unshifted_end:
122
+ mass = float64(mz[u, left[idx]])
123
+ shifted = float64(mz[v, right[idx]]) + delta
124
+ if mass - tolerance <= shifted <= mass + tolerance:
125
+ continue
126
+ order[size] = idx
127
+ size += 1
128
+ count = size
129
+ if count < 0:
130
+ counts[k] = -1
131
+ return
132
+
133
+ used = cuda.local.array(width, uint8)
134
+ for b in range(nq):
135
+ used[b] = 0
136
+ for root in range(count // 2 - 1, -1, -1):
137
+ _sift_down(order, values, root, count)
138
+ total = real(0)
139
+ while count:
140
+ idx = order[0]
141
+ a, b = left[idx], right[idx]
142
+ if assignment[k, a] == -1 and not used[b]:
143
+ assignment[k, a] = b
144
+ used[b] = 1
145
+ total += values[idx]
146
+ counts[k] += 1
147
+ count -= 1
148
+ order[0] = order[count]
149
+ _sift_down(order, values, 0, count)
150
+ scores[k] = total / sqrt(norms[u] * norms[v])
151
+
152
+ return kernel
153
+
154
+
155
+ def _recover(peaks, method, u, v, steps, maps):
156
+ """Recover *both* evidence and score from uncapped, double precision rows."""
157
+
158
+ def row(i):
159
+ n = peaks.lengths[i]
160
+ return np.column_stack((peaks.mz[i, :n], peaks.intensities[i, :n]))
161
+
162
+ left, right = row(u), row(v)
163
+ products = {}
164
+ if len(steps):
165
+ for a in range(len(left)):
166
+ b = a
167
+ for offset in steps:
168
+ b = maps[offset + b]
169
+ if b == -1:
170
+ break
171
+ if b != -1:
172
+ products[a, int(b)] = None
173
+ if not products:
174
+ return 0.0, ()
175
+
176
+ delta = peaks.precursor_mz[u] - peaks.precursor_mz[v]
177
+ shifts = (0.0, delta) if abs(delta) > method.tolerance else (0.0,)
178
+ # Store the last occurrence, as in a reversed stable ascending product sort.
179
+ for shift in shifts:
180
+ pairs = collect_peak_pairs(
181
+ left, right, method.tolerance, shift, method.mz_power, method.intensity_power
182
+ )
183
+ if pairs is not None:
184
+ for a, b, _ in pairs:
185
+ key = int(a), int(b)
186
+ products.pop(key, None)
187
+ products[key] = None
188
+ if not products:
189
+ return 0.0, ()
190
+
191
+ def weighted(row):
192
+ weights, norms = peak_weights(
193
+ row[:, 0].reshape(1, -1),
194
+ row[:, 1].reshape(1, -1),
195
+ np.array([len(row)]),
196
+ method.mz_power,
197
+ method.intensity_power,
198
+ )
199
+ return weights[0], norms[0]
200
+
201
+ w1, n1 = weighted(left)
202
+ w2, n2 = weighted(right)
203
+ if n1 == 0 or n2 == 0:
204
+ return 0.0, ()
205
+ used_left, used_right, selected = set(), set(), []
206
+ total = 0.0
207
+ ordered = sorted(products, key=lambda p: w1[p[0]] * w2[p[1]])
208
+ for a, b in reversed(ordered):
209
+ if a not in used_left and b not in used_right:
210
+ used_left.add(a)
211
+ used_right.add(b)
212
+ selected.append((a, b))
213
+ total += w1[a] * w2[b]
214
+ return float(total / sqrt(n1 * n2)), tuple(sorted(selected))
215
+
216
+
217
+ class PeakAligner:
218
+ """Upload spectra once. Each path step addresses a ragged directed map by offset."""
219
+
220
+ def __init__(self, peaks, method):
221
+ self.peaks, self.method = peaks, method
222
+ self.width = min(peaks.width, method.n_max_peaks or 8192, 8192)
223
+ mz = np.ascontiguousarray(peaks.mz[:, : self.width], dtype=method.precision)
224
+ intensities = np.ascontiguousarray(peaks.intensities[:, : self.width], dtype=method.precision)
225
+ weights, norms = peak_weights(mz, intensities, peaks.lengths, method.mz_power, method.intensity_power)
226
+ self.device_rows = tuple(
227
+ cuda.to_device(a) for a in (mz, weights, norms, peaks.lengths, peaks.precursor_mz)
228
+ )
229
+ # Bound per-thread local memory even if the public candidate limit is large.
230
+ self.limit = min(method.match_limit, 512, max(1, 3 * self.width**2))
231
+ self.kernel = _alignment_kernel(
232
+ _scratch_size(self.width), _scratch_size(self.limit), method.precision
233
+ )
234
+ self.set_maps(np.empty(0, dtype=np.int32))
235
+
236
+ def set_maps(self, maps):
237
+ self.maps = maps
238
+ self.device_maps = cuda.to_device(maps)
239
+
240
+ def batch(self, endpoints, starts, steps, *, return_pairs=True):
241
+ n = len(endpoints)
242
+ assignments = cuda.to_device(np.full((n, self.width), -1, dtype=np.int32))
243
+ scores = cuda.device_array(n, dtype=self.method.precision)
244
+ counts = cuda.device_array(n, dtype=np.int32)
245
+ starts, steps = np.asarray(starts, dtype=np.int64), np.asarray(steps, dtype=np.int64)
246
+ self.kernel[(n + 63) // 64, min(n, 64)](
247
+ *self.device_rows,
248
+ cuda.to_device(np.asarray(endpoints, dtype=np.intp)),
249
+ self.method.tolerance,
250
+ self.limit,
251
+ cuda.to_device(starts),
252
+ cuda.to_device(steps),
253
+ self.device_maps,
254
+ scores,
255
+ counts,
256
+ assignments,
257
+ )
258
+ host_maps = assignments.copy_to_host() if return_pairs else None
259
+ for i, (score, count) in enumerate(zip(scores.copy_to_host(), counts.copy_to_host())):
260
+ if count < 0:
261
+ score, pairs = _recover(
262
+ self.peaks, self.method, *endpoints[i], steps[starts[i] : starts[i + 1]], self.maps
263
+ )
264
+ yield score, len(pairs), pairs if return_pairs else None
265
+ else:
266
+ pairs = None
267
+ if return_pairs:
268
+ active = np.flatnonzero(host_maps[i] >= 0)
269
+ pairs = tuple(zip(active.tolist(), host_maps[i, active].tolist()))
270
+ yield float(score), int(count), pairs