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.
- simms/__init__.py +6 -0
- simms/__version__.py +1 -0
- simms/peaks.py +174 -0
- simms/similarity/CudaBinnedEmbeddingSimilarity.py +103 -0
- simms/similarity/CudaCosineGreedy.py +230 -0
- simms/similarity/CudaCosineLinear.py +382 -0
- simms/similarity/CudaEntropyGreedy.py +184 -0
- simms/similarity/CudaFingerprintSimilarity.py +207 -0
- simms/similarity/CudaModifiedCosine.py +10 -0
- simms/similarity/CudaNeutralLossesCosine.py +23 -0
- simms/similarity/CudaTransitiveAlignment.py +295 -0
- simms/similarity/__init__.py +24 -0
- simms/similarity/_base.py +178 -0
- simms/similarity/_transitive_peaks.py +270 -0
- simms/similarity/spectrum_similarity_functions.py +312 -0
- simms/similarity/vector_similarity_functions.py +202 -0
- simms/utils.py +126 -0
- simms_gpu-1.0.0.dist-info/METADATA +225 -0
- simms_gpu-1.0.0.dist-info/RECORD +21 -0
- simms_gpu-1.0.0.dist-info/WHEEL +4 -0
- simms_gpu-1.0.0.dist-info/licenses/LICENSE +20 -0
|
@@ -0,0 +1,382 @@
|
|
|
1
|
+
"""CUDA linear cosine scoring on SIRIUS-merged peaks."""
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
from operator import mul
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from functools import lru_cache
|
|
7
|
+
|
|
8
|
+
import numpy as np
|
|
9
|
+
import torch
|
|
10
|
+
from matchms.similarity._precursor_validation import get_valid_precursor_mz
|
|
11
|
+
from matchms.similarity.cosine_linear_functions import _weighted_products, sirius_merge_close_peaks
|
|
12
|
+
from matchms.similarity.spectrum_similarity_functions import _preprocess_peak_array
|
|
13
|
+
from numba import cuda, int16, njit
|
|
14
|
+
from numba.cuda import libdevice
|
|
15
|
+
|
|
16
|
+
from ..peaks import PeakArrays, _spectrum_rows
|
|
17
|
+
from ..utils import get_device
|
|
18
|
+
from ._base import CudaSimilarity
|
|
19
|
+
from .vector_similarity_functions import kernel_stream, kernel_view, tile_slices
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
_LOGGER = logging.getLogger("matchms")
|
|
23
|
+
_WORKSPACE_WIDTH = 2048
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@dataclass
|
|
27
|
+
class _Prepared:
|
|
28
|
+
mz: np.ndarray
|
|
29
|
+
weights: np.ndarray
|
|
30
|
+
offsets: np.ndarray
|
|
31
|
+
norms: np.ndarray
|
|
32
|
+
precursors: np.ndarray
|
|
33
|
+
|
|
34
|
+
def __len__(self):
|
|
35
|
+
return len(self.norms)
|
|
36
|
+
|
|
37
|
+
def batch(self, rows, device, width_limit):
|
|
38
|
+
offsets = self.offsets[rows.start : rows.stop + 1]
|
|
39
|
+
peaks = slice(offsets[0], offsets[-1])
|
|
40
|
+
mz, weights = self.mz[peaks], self.weights[peaks]
|
|
41
|
+
offsets = offsets - offsets[0]
|
|
42
|
+
lengths = np.diff(offsets)
|
|
43
|
+
if width_limit is not None and np.any(lengths > width_limit):
|
|
44
|
+
# Oversized rows are scored exclusively on the CPU. Keep empty
|
|
45
|
+
# slots for their row indices without staging their peaks on CUDA.
|
|
46
|
+
keep = lengths <= width_limit
|
|
47
|
+
active = np.repeat(keep, lengths)
|
|
48
|
+
mz, weights = mz[active], weights[active]
|
|
49
|
+
offsets = np.r_[0, np.cumsum(np.where(keep, lengths, 0))]
|
|
50
|
+
arrays = (mz, weights, offsets, self.norms[rows], self.precursors[rows])
|
|
51
|
+
return tuple(torch.as_tensor(a, device=device) for a in arrays)
|
|
52
|
+
|
|
53
|
+
def peak_slice(self, index):
|
|
54
|
+
return slice(self.offsets[index], self.offsets[index + 1])
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
# matchms rounds each product before adding it. Prevent CUDA from fusing
|
|
58
|
+
# that multiplication into the sum or into a modified-cosine DP comparison.
|
|
59
|
+
_device_product = mul if cuda.config.ENABLE_CUDASIM else libdevice.dmul_rn
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
@cuda.jit(device=True)
|
|
63
|
+
def _direct_score(mz1, w1, mz2, w2, tolerance):
|
|
64
|
+
i = j = matches = 0
|
|
65
|
+
total = 0.0
|
|
66
|
+
while i < mz1.size and j < mz2.size:
|
|
67
|
+
diff = mz1[i] - mz2[j]
|
|
68
|
+
if abs(diff) <= tolerance:
|
|
69
|
+
total += _device_product(w1[i], w2[j])
|
|
70
|
+
matches += 1
|
|
71
|
+
i += 1
|
|
72
|
+
j += 1
|
|
73
|
+
elif diff < 0:
|
|
74
|
+
i += 1
|
|
75
|
+
else:
|
|
76
|
+
j += 1
|
|
77
|
+
return total, matches
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _make_modified_score(product):
|
|
81
|
+
def _modified_score(mz1, w1, mz2, w2, precursor1, precursor2, tolerance, partners):
|
|
82
|
+
"""Return unnormalized weight and count. Both GPU and CPU use this traversal."""
|
|
83
|
+
n1, n2 = mz1.size, mz2.size
|
|
84
|
+
for node in range(n1 + n2):
|
|
85
|
+
partners[0, node] = -1
|
|
86
|
+
partners[1, node] = -1
|
|
87
|
+
|
|
88
|
+
for kind in range(2):
|
|
89
|
+
if kind == 1 and abs(precursor1 - precursor2) <= tolerance:
|
|
90
|
+
break
|
|
91
|
+
offset1 = precursor1 if kind else 0.0
|
|
92
|
+
offset2 = precursor2 if kind else 0.0
|
|
93
|
+
j = 0
|
|
94
|
+
for i in range(n1):
|
|
95
|
+
center = mz1[i] - offset1
|
|
96
|
+
while j < n2 and mz2[j] - offset2 < center - tolerance:
|
|
97
|
+
j += 1
|
|
98
|
+
if j < n2 and mz2[j] - offset2 <= center + tolerance:
|
|
99
|
+
other = n1 + j
|
|
100
|
+
if kind == 0 or partners[0, i] != other:
|
|
101
|
+
partners[kind, i] = other
|
|
102
|
+
partners[kind, other] = i
|
|
103
|
+
j += 1
|
|
104
|
+
|
|
105
|
+
total = 0.0
|
|
106
|
+
matches = 0
|
|
107
|
+
for start in range(n1 + n2):
|
|
108
|
+
if (partners[0, start] >= 0) == (partners[1, start] >= 0):
|
|
109
|
+
continue
|
|
110
|
+
# Only endpoints have degree one. Removing each traversed edge leaves
|
|
111
|
+
# the next edge unambiguous and consumes the whole component.
|
|
112
|
+
node = start
|
|
113
|
+
prev2 = prev = 0.0
|
|
114
|
+
sum2 = accumulated = total
|
|
115
|
+
count2 = count = 0
|
|
116
|
+
while True:
|
|
117
|
+
kind = 0 if partners[0, node] >= 0 else 1
|
|
118
|
+
other = partners[kind, node]
|
|
119
|
+
if other < 0:
|
|
120
|
+
break
|
|
121
|
+
partners[kind, node] = -1
|
|
122
|
+
partners[kind, other] = -1
|
|
123
|
+
if node < n1:
|
|
124
|
+
benefit = product(w1[node], w2[other - n1])
|
|
125
|
+
else:
|
|
126
|
+
benefit = product(w1[other], w2[node - n1])
|
|
127
|
+
# Upstream backtracking takes the last edge on ties. Carrying the
|
|
128
|
+
# winning count alongside its weight avoids storing the DP table.
|
|
129
|
+
take = prev2 + benefit
|
|
130
|
+
if node == start or take >= prev:
|
|
131
|
+
best, best_count = take, count2 + (benefit != 0.0)
|
|
132
|
+
# Keep the global summation order of matchms backtracking.
|
|
133
|
+
best_sum = sum2 + benefit
|
|
134
|
+
else:
|
|
135
|
+
best, best_count = prev, count
|
|
136
|
+
best_sum = accumulated
|
|
137
|
+
prev2, prev = prev, best
|
|
138
|
+
count2, count = count, best_count
|
|
139
|
+
sum2, accumulated = accumulated, best_sum
|
|
140
|
+
node = other
|
|
141
|
+
total = accumulated
|
|
142
|
+
matches += count
|
|
143
|
+
return total, matches
|
|
144
|
+
|
|
145
|
+
return _modified_score
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
_modified_device = cuda.jit(device=True)(_make_modified_score(_device_product))
|
|
149
|
+
_modified_host = njit(_make_modified_score(mul))
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
@lru_cache(maxsize=None)
|
|
153
|
+
def _kernel(modified, width):
|
|
154
|
+
workspace_shape = (2, 2 * width)
|
|
155
|
+
|
|
156
|
+
# Specialize local storage to the merged batch width. The direct kernel
|
|
157
|
+
# needs only its two cursors regardless of spectrum length.
|
|
158
|
+
@cuda.jit
|
|
159
|
+
def run(
|
|
160
|
+
mz1,
|
|
161
|
+
w1,
|
|
162
|
+
offsets1,
|
|
163
|
+
norms1,
|
|
164
|
+
pre1,
|
|
165
|
+
mz2,
|
|
166
|
+
w2,
|
|
167
|
+
offsets2,
|
|
168
|
+
norms2,
|
|
169
|
+
pre2,
|
|
170
|
+
tolerance,
|
|
171
|
+
positions,
|
|
172
|
+
diagonal,
|
|
173
|
+
result,
|
|
174
|
+
):
|
|
175
|
+
k = cuda.grid(1)
|
|
176
|
+
if k >= result.shape[1]:
|
|
177
|
+
return
|
|
178
|
+
pos = positions[k] if positions.size else k
|
|
179
|
+
i, j = pos // norms2.size, pos % norms2.size
|
|
180
|
+
if diagonal and i > j:
|
|
181
|
+
return
|
|
182
|
+
a, b = offsets1[i], offsets1[i + 1]
|
|
183
|
+
c, d = offsets2[j], offsets2[j + 1]
|
|
184
|
+
score = 0.0
|
|
185
|
+
matches = 0
|
|
186
|
+
if a < b and c < d and not (norms1[i] <= 1e-12 or norms2[j] <= 1e-12):
|
|
187
|
+
if modified:
|
|
188
|
+
partners = cuda.local.array(workspace_shape, int16)
|
|
189
|
+
score, matches = _modified_device(
|
|
190
|
+
mz1[a:b], w1[a:b], mz2[c:d], w2[c:d], pre1[i], pre2[j], tolerance, partners
|
|
191
|
+
)
|
|
192
|
+
else:
|
|
193
|
+
score, matches = _direct_score(mz1[a:b], w1[a:b], mz2[c:d], w2[c:d], tolerance)
|
|
194
|
+
score /= norms1[i] * norms2[j]
|
|
195
|
+
result[0, k], result[1, k] = score, matches
|
|
196
|
+
if diagonal and i != j:
|
|
197
|
+
mirror = j * norms2.size + i
|
|
198
|
+
result[0, mirror], result[1, mirror] = score, matches
|
|
199
|
+
|
|
200
|
+
return run
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
class CudaCosineLinear(CudaSimilarity):
|
|
204
|
+
"""Linear-time direct cosine. Merge and weight each input spectrum once per call."""
|
|
205
|
+
|
|
206
|
+
is_commutative = True
|
|
207
|
+
modified = False
|
|
208
|
+
|
|
209
|
+
def __init__(
|
|
210
|
+
self,
|
|
211
|
+
tolerance=0.01,
|
|
212
|
+
mz_power=0.0,
|
|
213
|
+
intensity_power=1.0,
|
|
214
|
+
noise_cutoff=0.01,
|
|
215
|
+
remove_precursor=False,
|
|
216
|
+
offset_to_precursor=-1.6,
|
|
217
|
+
*,
|
|
218
|
+
batch_size=2048,
|
|
219
|
+
precision="float64",
|
|
220
|
+
):
|
|
221
|
+
self.tolerance = tolerance
|
|
222
|
+
self.mz_power = mz_power
|
|
223
|
+
self.intensity_power = intensity_power
|
|
224
|
+
self.noise_cutoff = noise_cutoff
|
|
225
|
+
self.remove_precursor = remove_precursor
|
|
226
|
+
self.offset_to_precursor = offset_to_precursor
|
|
227
|
+
if isinstance(batch_size, bool) or not isinstance(batch_size, (int, np.integer)) or batch_size < 1:
|
|
228
|
+
raise ValueError("batch_size must be a positive integer")
|
|
229
|
+
if precision not in ("float32", "float64"):
|
|
230
|
+
raise ValueError("precision must be 'float32' or 'float64'")
|
|
231
|
+
self.batch_size = int(batch_size)
|
|
232
|
+
self.precision = precision
|
|
233
|
+
|
|
234
|
+
@property
|
|
235
|
+
def device(self):
|
|
236
|
+
return get_device(require_cuda=True)
|
|
237
|
+
|
|
238
|
+
def _prepare(self, data):
|
|
239
|
+
masses, weights, norms, precursors = [], [], [], []
|
|
240
|
+
offsets = [0]
|
|
241
|
+
for mz, intensity, precursor in _spectrum_rows(data):
|
|
242
|
+
if self.modified or self.remove_precursor:
|
|
243
|
+
precursor = get_valid_precursor_mz({"precursor_mz": precursor}, _LOGGER)
|
|
244
|
+
else:
|
|
245
|
+
precursor = 0.0
|
|
246
|
+
peaks = _preprocess_peak_array(
|
|
247
|
+
np.column_stack((mz, intensity)),
|
|
248
|
+
precursor_mz=precursor,
|
|
249
|
+
remove_precursor=self.remove_precursor,
|
|
250
|
+
offset_to_precursor=self.offset_to_precursor,
|
|
251
|
+
noise_cutoff=self.noise_cutoff,
|
|
252
|
+
)
|
|
253
|
+
merged = sirius_merge_close_peaks(peaks.astype(np.float64, copy=False), self.tolerance)
|
|
254
|
+
products, norm = _weighted_products(merged, self.mz_power, self.intensity_power)
|
|
255
|
+
masses.append(merged[:, 0])
|
|
256
|
+
weights.append(products)
|
|
257
|
+
norms.append(norm)
|
|
258
|
+
precursors.append(precursor)
|
|
259
|
+
offsets.append(offsets[-1] + len(products))
|
|
260
|
+
return _Prepared(
|
|
261
|
+
np.concatenate(masses) if masses else np.empty(0),
|
|
262
|
+
np.concatenate(weights) if weights else np.empty(0),
|
|
263
|
+
np.asarray(offsets),
|
|
264
|
+
np.asarray(norms),
|
|
265
|
+
np.asarray(precursors, dtype=np.float64),
|
|
266
|
+
)
|
|
267
|
+
|
|
268
|
+
def _inputs(self, spectra_1, spectra_2):
|
|
269
|
+
left = self._prepare(spectra_1)
|
|
270
|
+
right = left if spectra_2 is None or spectra_1 is spectra_2 else self._prepare(spectra_2)
|
|
271
|
+
return left, right, spectra_2 is None
|
|
272
|
+
|
|
273
|
+
def pair(self, spectrum_1, spectrum_2):
|
|
274
|
+
a = spectrum_1 if isinstance(spectrum_1, PeakArrays) else [spectrum_1]
|
|
275
|
+
b = spectrum_2 if isinstance(spectrum_2, PeakArrays) else [spectrum_2]
|
|
276
|
+
if len(a) != 1 or len(b) != 1:
|
|
277
|
+
raise ValueError("pair expects one spectrum per input")
|
|
278
|
+
return self.matrix(a, b, array_type="numpy", progress_bar=False).reshape(())
|
|
279
|
+
|
|
280
|
+
def _recover(self, left, right, i, j):
|
|
281
|
+
if left.norms[i] <= 1e-12 or right.norms[j] <= 1e-12:
|
|
282
|
+
return 0.0, 0
|
|
283
|
+
a, b = left.peak_slice(i), right.peak_slice(j)
|
|
284
|
+
partners = np.empty((2, a.stop - a.start + b.stop - b.start), dtype=np.intp)
|
|
285
|
+
total, matches = _modified_host(
|
|
286
|
+
left.mz[a],
|
|
287
|
+
left.weights[a],
|
|
288
|
+
right.mz[b],
|
|
289
|
+
right.weights[b],
|
|
290
|
+
left.precursors[i],
|
|
291
|
+
right.precursors[j],
|
|
292
|
+
self.tolerance,
|
|
293
|
+
partners,
|
|
294
|
+
)
|
|
295
|
+
return total / (left.norms[i] * right.norms[j]), matches
|
|
296
|
+
|
|
297
|
+
def _tiles(self, left, right, symmetric, requested, progress_bar):
|
|
298
|
+
previous = None
|
|
299
|
+
limit = _WORKSPACE_WIDTH if self.modified else None
|
|
300
|
+
lengths1, lengths2 = np.diff(left.offsets), np.diff(right.offsets)
|
|
301
|
+
for rows, cols, positions in tile_slices(
|
|
302
|
+
(len(left), len(right)), self.batch_size, symmetric, requested, progress_bar
|
|
303
|
+
):
|
|
304
|
+
if previous != rows:
|
|
305
|
+
a = left.batch(rows, self.device, limit)
|
|
306
|
+
previous = rows
|
|
307
|
+
b = a if left is right and rows == cols else right.batch(cols, self.device, limit)
|
|
308
|
+
nr, nc = rows.stop - rows.start, cols.stop - cols.start
|
|
309
|
+
count = nr * nc if positions is None else len(positions)
|
|
310
|
+
indices = torch.as_tensor(
|
|
311
|
+
[] if positions is None else positions, device=self.device, dtype=torch.int64
|
|
312
|
+
)
|
|
313
|
+
diagonal = symmetric and rows == cols and positions is None
|
|
314
|
+
width = 1
|
|
315
|
+
oversized = None
|
|
316
|
+
if self.modified:
|
|
317
|
+
lens1, lens2 = lengths1[rows], lengths2[cols]
|
|
318
|
+
largest = max(
|
|
319
|
+
lens1[lens1 <= _WORKSPACE_WIDTH].max(initial=1),
|
|
320
|
+
lens2[lens2 <= _WORKSPACE_WIDTH].max(initial=1),
|
|
321
|
+
)
|
|
322
|
+
width = 1 << (int(largest) - 1).bit_length()
|
|
323
|
+
if lens1.max() > width or lens2.max() > width:
|
|
324
|
+
if positions is None:
|
|
325
|
+
oversized = np.flatnonzero((lens1[:, None] > width) | (lens2 > width))
|
|
326
|
+
else:
|
|
327
|
+
oversized = np.flatnonzero(
|
|
328
|
+
(lens1[positions // nc] > width) | (lens2[positions % nc] > width)
|
|
329
|
+
)
|
|
330
|
+
result = torch.empty((2, count), dtype=getattr(torch, self.precision), device=self.device)
|
|
331
|
+
threads = min(count, 64)
|
|
332
|
+
_kernel(self.modified, width)[
|
|
333
|
+
(count + threads - 1) // threads, threads, kernel_stream(a[0].device)
|
|
334
|
+
](
|
|
335
|
+
*map(kernel_view, a),
|
|
336
|
+
*map(kernel_view, b),
|
|
337
|
+
self.tolerance,
|
|
338
|
+
kernel_view(indices),
|
|
339
|
+
diagonal,
|
|
340
|
+
kernel_view(result),
|
|
341
|
+
)
|
|
342
|
+
if oversized is not None and oversized.size:
|
|
343
|
+
pos = oversized if positions is None else positions[oversized]
|
|
344
|
+
i, j = np.divmod(pos, nc)
|
|
345
|
+
if diagonal:
|
|
346
|
+
upper = i <= j
|
|
347
|
+
oversized, i, j = oversized[upper], i[upper], j[upper]
|
|
348
|
+
repaired = [self._recover(left, right, rows.start + x, cols.start + y) for x, y in zip(i, j)]
|
|
349
|
+
values = torch.tensor(repaired, device=self.device, dtype=result.dtype).T
|
|
350
|
+
result[:, oversized] = values
|
|
351
|
+
if diagonal:
|
|
352
|
+
result[:, j * nc + i] = values
|
|
353
|
+
yield rows, cols, positions, result
|
|
354
|
+
|
|
355
|
+
|
|
356
|
+
class CudaModifiedCosineLinear(CudaCosineLinear):
|
|
357
|
+
"""Exact direct and shifted path matching, with CPU workspace for rows over 2048 merged peaks."""
|
|
358
|
+
|
|
359
|
+
modified = True
|
|
360
|
+
|
|
361
|
+
def __init__(
|
|
362
|
+
self,
|
|
363
|
+
tolerance=0.01,
|
|
364
|
+
mz_power=0.0,
|
|
365
|
+
intensity_power=1.0,
|
|
366
|
+
noise_cutoff=0.01,
|
|
367
|
+
remove_precursor=True,
|
|
368
|
+
offset_to_precursor=-1.6,
|
|
369
|
+
*,
|
|
370
|
+
batch_size=2048,
|
|
371
|
+
precision="float64",
|
|
372
|
+
):
|
|
373
|
+
super().__init__(
|
|
374
|
+
tolerance,
|
|
375
|
+
mz_power,
|
|
376
|
+
intensity_power,
|
|
377
|
+
noise_cutoff,
|
|
378
|
+
remove_precursor,
|
|
379
|
+
offset_to_precursor,
|
|
380
|
+
batch_size=batch_size,
|
|
381
|
+
precision=precision,
|
|
382
|
+
)
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
"""Tile-streamed, one-to-one spectral entropy similarity on CUDA."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
|
|
5
|
+
import numpy as np
|
|
6
|
+
import pandas as pd
|
|
7
|
+
import torch
|
|
8
|
+
from matchms import Scores, SpectraCollection
|
|
9
|
+
from matchms.similarity.entropy_greedy import (
|
|
10
|
+
EntropyGreedy,
|
|
11
|
+
_entropy_fragment_similarity_greedy,
|
|
12
|
+
_entropy_neutral_loss_similarity_greedy,
|
|
13
|
+
)
|
|
14
|
+
from matchms.similarity.flash_utils import _clean_and_weight
|
|
15
|
+
from numba import cuda
|
|
16
|
+
from tqdm import tqdm
|
|
17
|
+
|
|
18
|
+
from ..peaks import _spectrum_rows
|
|
19
|
+
from ..utils import get_device
|
|
20
|
+
from ._base import _ScalarCudaSimilarity
|
|
21
|
+
from .CudaCosineGreedy import _positive_int, _scratch_size
|
|
22
|
+
from .spectrum_similarity_functions import ENTROPY_HYBRID_CAP, entropy_kernel
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass
|
|
26
|
+
class _Prepared:
|
|
27
|
+
# Each packed peak holds its m/z, half-normalized intensity p, and p*log2(p).
|
|
28
|
+
peaks: np.ndarray
|
|
29
|
+
offsets: np.ndarray
|
|
30
|
+
precursor: np.ndarray
|
|
31
|
+
|
|
32
|
+
def __len__(self):
|
|
33
|
+
return len(self.precursor)
|
|
34
|
+
|
|
35
|
+
def row(self, i):
|
|
36
|
+
return self.peaks[self.offsets[i]:self.offsets[i + 1]]
|
|
37
|
+
|
|
38
|
+
def batch(self, rows, device):
|
|
39
|
+
offsets = self.offsets[rows.start:rows.stop + 1]
|
|
40
|
+
arrays = self.peaks[offsets[0]:offsets[-1]], offsets - offsets[0], self.precursor[rows]
|
|
41
|
+
return tuple(torch.as_tensor(a, device=device) for a in arrays), int(np.diff(offsets).max())
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class CudaEntropyGreedy(_ScalarCudaSimilarity, EntropyGreedy):
|
|
45
|
+
"""Li spectral entropy with matchms preprocessing and greedy matching order.
|
|
46
|
+
|
|
47
|
+
Set weighted=False to normalize intensities without Li weighting. batch_size
|
|
48
|
+
bounds each tile axis. NumPy and Torch outputs are scalar score matrices of
|
|
49
|
+
shape (references, queries). Only hybrid matching needs used-peak scratch.
|
|
50
|
+
"""
|
|
51
|
+
|
|
52
|
+
score_datatype = np.dtype(np.float64)
|
|
53
|
+
score_fields = ("score",)
|
|
54
|
+
|
|
55
|
+
def __init__(
|
|
56
|
+
self,
|
|
57
|
+
matching_mode="fragment",
|
|
58
|
+
tolerance=0.01,
|
|
59
|
+
use_ppm=False,
|
|
60
|
+
remove_precursor=True,
|
|
61
|
+
offset_to_precursor=-1.6,
|
|
62
|
+
noise_cutoff=0.01,
|
|
63
|
+
merge_within=0.0,
|
|
64
|
+
dtype=np.float64,
|
|
65
|
+
weighted: bool = True,
|
|
66
|
+
batch_size=2048,
|
|
67
|
+
):
|
|
68
|
+
super().__init__(matching_mode, tolerance, use_ppm, remove_precursor, offset_to_precursor,
|
|
69
|
+
noise_cutoff, merge_within, dtype)
|
|
70
|
+
if self.dtype not in (np.dtype("float32"), np.dtype("float64")):
|
|
71
|
+
raise ValueError("dtype must be float32 or float64")
|
|
72
|
+
self.weighted = weighted
|
|
73
|
+
self.batch_size = _positive_int("batch_size", batch_size)
|
|
74
|
+
|
|
75
|
+
def to_dict(self):
|
|
76
|
+
return {**super().to_dict(), "dtype": self.dtype.name}
|
|
77
|
+
|
|
78
|
+
def _pack(self, spectra):
|
|
79
|
+
arrays, offsets, precursors = [], [0], []
|
|
80
|
+
for mz, intensities, precursor in _spectrum_rows(spectra):
|
|
81
|
+
# SpectraCollection drops pandas missing metadata when reconstructing a row.
|
|
82
|
+
if isinstance(spectra, SpectraCollection) and pd.isna(precursor):
|
|
83
|
+
precursor = None
|
|
84
|
+
peaks = _clean_and_weight(
|
|
85
|
+
np.column_stack((mz, intensities)), precursor,
|
|
86
|
+
remove_precursor=self.remove_precursor, offset_to_precursor=self.offset_to_precursor,
|
|
87
|
+
noise_cutoff=self.noise_cutoff, normalize_to_half=True, merge_within_da=self.merge_within,
|
|
88
|
+
weighing_type="entropy" if self.weighted else "cosine", dtype=self.dtype,
|
|
89
|
+
)
|
|
90
|
+
# EntropyGreedy promotes each preprocessed value to Python float before scoring.
|
|
91
|
+
p = peaks[:, 1].astype(np.float64, copy=False)
|
|
92
|
+
h = np.zeros_like(p)
|
|
93
|
+
positive = p > 0
|
|
94
|
+
h[positive] = p[positive] * np.log2(p[positive])
|
|
95
|
+
arrays.append(np.column_stack((peaks, h)))
|
|
96
|
+
offsets.append(offsets[-1] + len(peaks))
|
|
97
|
+
precursors.append(np.nan if precursor is None else float(precursor))
|
|
98
|
+
return _Prepared(np.concatenate(arrays) if arrays else np.empty((0, 3)),
|
|
99
|
+
np.asarray(offsets, dtype=np.int64), np.asarray(precursors, dtype=np.float64))
|
|
100
|
+
|
|
101
|
+
def _inputs(self, spectra_1, spectra_2):
|
|
102
|
+
left = self._pack(spectra_1)
|
|
103
|
+
right = left if spectra_2 is None or spectra_1 is spectra_2 else self._pack(spectra_2)
|
|
104
|
+
return left, right, spectra_2 is None
|
|
105
|
+
|
|
106
|
+
def _recover_hybrid(self, left, right, i, j):
|
|
107
|
+
# Only reached for hybrid pairs with both precursors and oversized bitsets.
|
|
108
|
+
a, b = left.row(i), right.row(j)
|
|
109
|
+
used = dict(used_1=np.zeros(len(a), dtype=bool), used_2=np.zeros(len(b), dtype=bool))
|
|
110
|
+
score = _entropy_fragment_similarity_greedy(a, b, self.tolerance, self.use_ppm, **used)
|
|
111
|
+
return score + _entropy_neutral_loss_similarity_greedy(
|
|
112
|
+
a, b, left.precursor[i], right.precursor[j], self.tolerance, self.use_ppm, **used,
|
|
113
|
+
)
|
|
114
|
+
|
|
115
|
+
def _tiles(self, left, right, symmetric, requested, progress_bar):
|
|
116
|
+
if not len(right):
|
|
117
|
+
return
|
|
118
|
+
batch, device = self.batch_size, get_device(require_cuda=True)
|
|
119
|
+
starts = range(0, len(left), batch) if requested is None else sorted(requested)
|
|
120
|
+
if cuda.config.ENABLE_CUDASIM:
|
|
121
|
+
view, stream = torch.Tensor.numpy, 0
|
|
122
|
+
else:
|
|
123
|
+
def view(tensor):
|
|
124
|
+
return cuda.as_cuda_array(tensor, sync=False)
|
|
125
|
+
stream = cuda.external_stream(torch.cuda.current_stream().cuda_stream)
|
|
126
|
+
|
|
127
|
+
for r in tqdm(starts, desc="Scoring reference batches", disable=not progress_bar):
|
|
128
|
+
rows = slice(r, min(r + batch, len(left)))
|
|
129
|
+
rbatch = left.batch(rows, device)
|
|
130
|
+
columns = range(r if symmetric else 0, len(right), batch) if requested is None else sorted(requested[r])
|
|
131
|
+
for c in columns:
|
|
132
|
+
cols = slice(c, min(c + batch, len(right)))
|
|
133
|
+
qbatch = rbatch if left is right and r == c else right.batch(cols, device)
|
|
134
|
+
max_peaks = max(rbatch[1], qbatch[1])
|
|
135
|
+
words = 1
|
|
136
|
+
if self.matching_mode == "hybrid":
|
|
137
|
+
words = _scratch_size((min(max_peaks, ENTROPY_HYBRID_CAP) + 31) // 32)
|
|
138
|
+
positions = None if requested is None else np.asarray(requested[r][c], dtype=np.intp)
|
|
139
|
+
width = cols.stop - c
|
|
140
|
+
count = (rows.stop - r) * width if positions is None else len(positions)
|
|
141
|
+
indices = torch.as_tensor([] if positions is None else positions, dtype=torch.int64, device=device)
|
|
142
|
+
result = torch.empty(count, dtype=getattr(torch, self.dtype.name), device=device)
|
|
143
|
+
diagonal = symmetric and r == c and positions is None
|
|
144
|
+
threads = min(128, count)
|
|
145
|
+
kernel = entropy_kernel(self.matching_mode, words)
|
|
146
|
+
kernel[(count + threads - 1) // threads, threads, stream](
|
|
147
|
+
*map(view, rbatch[0]), *map(view, qbatch[0]), view(indices), self.tolerance,
|
|
148
|
+
self.use_ppm, diagonal, view(result),
|
|
149
|
+
)
|
|
150
|
+
if self.matching_mode == "hybrid" and max_peaks > ENTROPY_HYBRID_CAP:
|
|
151
|
+
failed = torch.nonzero(torch.isneginf(result)).flatten().cpu().numpy()
|
|
152
|
+
for k in failed:
|
|
153
|
+
i, j = divmod(k if positions is None else positions[k], width)
|
|
154
|
+
if diagonal and i > j:
|
|
155
|
+
continue
|
|
156
|
+
value = self._recover_hybrid(left, right, r + i, c + j)
|
|
157
|
+
result[k] = value
|
|
158
|
+
if diagonal:
|
|
159
|
+
result[j * width + i] = value
|
|
160
|
+
yield rows, cols, positions, result
|
|
161
|
+
|
|
162
|
+
def matrix(self, spectra_1, spectra_2=None, score_fields=None, progress_bar=True, array_type="scores"):
|
|
163
|
+
self._fields(score_fields)
|
|
164
|
+
left, right, symmetric = self._inputs(spectra_1, spectra_2)
|
|
165
|
+
shape = (len(left), len(right))
|
|
166
|
+
if array_type == "torch":
|
|
167
|
+
result = torch.empty(shape, dtype=getattr(torch, self.dtype.name), device=get_device(require_cuda=True))
|
|
168
|
+
elif array_type in ("numpy", "scores"):
|
|
169
|
+
result = np.empty(shape, dtype=self.dtype)
|
|
170
|
+
else:
|
|
171
|
+
raise ValueError("array_type must be 'scores', 'numpy' or 'torch'")
|
|
172
|
+
for rows, cols, _, tile in self._tiles(left, right, symmetric, None, progress_bar):
|
|
173
|
+
tile = tile.reshape(rows.stop - rows.start, cols.stop - cols.start)
|
|
174
|
+
if array_type != "torch":
|
|
175
|
+
tile = tile.cpu().numpy()
|
|
176
|
+
result[rows, cols] = tile
|
|
177
|
+
if symmetric and rows.start != cols.start:
|
|
178
|
+
result[cols, rows] = tile.T
|
|
179
|
+
return Scores({"score": result}) if array_type == "scores" else result
|
|
180
|
+
|
|
181
|
+
# EntropyGreedy callbacks receive a zero-dimensional array for each scalar.
|
|
182
|
+
@staticmethod
|
|
183
|
+
def _predicate_values(values):
|
|
184
|
+
return map(np.asarray, values)
|