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,312 @@
|
|
|
1
|
+
"""Bounded CUDA greedy assignment and exact matchms recovery for oversized pairs."""
|
|
2
|
+
|
|
3
|
+
from functools import lru_cache
|
|
4
|
+
from math import inf, isnan, log2, sqrt
|
|
5
|
+
|
|
6
|
+
import numpy as np
|
|
7
|
+
from matchms.similarity.spectrum_similarity_functions import collect_peak_pairs, score_best_matches
|
|
8
|
+
from numba import cuda, float32, float64, int32, njit, uint8, uint32
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@njit(fastmath=True)
|
|
12
|
+
def _squared_norm(weighted):
|
|
13
|
+
# Use the same reduction and math flags as matchms.score_best_matches.
|
|
14
|
+
return np.sum(weighted**2)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@njit
|
|
18
|
+
def peak_weights(mz, intensity, lengths, mz_power, intensity_power):
|
|
19
|
+
"""Compute each weight once. Padding must never be raised to a power."""
|
|
20
|
+
weights = np.zeros_like(mz)
|
|
21
|
+
norms = np.zeros(len(lengths), dtype=mz.dtype)
|
|
22
|
+
for i in range(len(lengths)):
|
|
23
|
+
n = min(lengths[i], mz.shape[1])
|
|
24
|
+
for j in range(n):
|
|
25
|
+
weights[i, j] = mz[i, j] ** mz_power * intensity[i, j] ** intensity_power
|
|
26
|
+
norms[i] = _squared_norm(weights[i, :n])
|
|
27
|
+
return weights, norms
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def exact_score(left, right, shifts, tolerance, mz_power, intensity_power, *, raise_zero_division=False):
|
|
31
|
+
"""Use matchms's candidate generation, reversed stable sort, assignment and normalization."""
|
|
32
|
+
pairs = []
|
|
33
|
+
for shift in shifts:
|
|
34
|
+
candidates = collect_peak_pairs(left, right, tolerance, shift, mz_power, intensity_power)
|
|
35
|
+
if candidates is not None:
|
|
36
|
+
pairs.append(candidates)
|
|
37
|
+
if not pairs:
|
|
38
|
+
return 0.0, 0
|
|
39
|
+
candidates = np.concatenate(pairs)
|
|
40
|
+
order = np.argsort(candidates[:, 2], kind="stable")[::-1]
|
|
41
|
+
try:
|
|
42
|
+
return score_best_matches(candidates[order], left, right, mz_power, intensity_power)
|
|
43
|
+
except ZeroDivisionError:
|
|
44
|
+
# matchms divides by zero when all valid weights on one side are zero.
|
|
45
|
+
if raise_zero_division:
|
|
46
|
+
raise
|
|
47
|
+
return 0.0, 0
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
@cuda.jit(device=True)
|
|
51
|
+
def _higher_priority(values, a, b):
|
|
52
|
+
# Reversing a stable ascending sort puts the later candidate first on ties.
|
|
53
|
+
return values[a] > values[b] or (values[a] == values[b] and a > b)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
@cuda.jit(device=True)
|
|
57
|
+
def _sift_down(order, values, root, size):
|
|
58
|
+
while 2 * root + 1 < size:
|
|
59
|
+
child = 2 * root + 1
|
|
60
|
+
if child + 1 < size and _higher_priority(values, order[child + 1], order[child]):
|
|
61
|
+
child += 1
|
|
62
|
+
if not _higher_priority(values, order[child], order[root]):
|
|
63
|
+
break
|
|
64
|
+
order[root], order[child] = order[child], order[root]
|
|
65
|
+
root = child
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
@cuda.jit(device=True)
|
|
69
|
+
def _collect(
|
|
70
|
+
rmz, rw, nr, qmz, qw, nq, tolerance, shift, count, limit, left, right, order, values, count_only
|
|
71
|
+
):
|
|
72
|
+
start = 0
|
|
73
|
+
for a in range(nr):
|
|
74
|
+
# Keep inclusive bounds in double precision even for rounded FP32 input.
|
|
75
|
+
mass = float64(rmz[a])
|
|
76
|
+
low, high = mass - tolerance, mass + tolerance
|
|
77
|
+
for b in range(start, nq):
|
|
78
|
+
shifted = float64(qmz[b]) + shift
|
|
79
|
+
if shifted > high:
|
|
80
|
+
break
|
|
81
|
+
if shifted < low:
|
|
82
|
+
start = b + 1
|
|
83
|
+
continue
|
|
84
|
+
if count == limit:
|
|
85
|
+
return -1
|
|
86
|
+
if not count_only:
|
|
87
|
+
left[count], right[count] = a, b
|
|
88
|
+
values[count] = rw[a] * qw[b]
|
|
89
|
+
order[count] = count
|
|
90
|
+
count += 1
|
|
91
|
+
return count
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
# Above this size local arrays can exhaust device memory at launch. Count
|
|
95
|
+
# candidates first, then use bounded batches of global scratch for large heaps.
|
|
96
|
+
LOCAL_CANDIDATES = 2048
|
|
97
|
+
# The Wave 1 launch ABI passes False for fixed shift and True for modified cosine.
|
|
98
|
+
NEUTRAL_LOSS_ONLY = 2
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
@lru_cache(maxsize=64)
|
|
102
|
+
def cosine_kernel(width, capacity, precision, count_only=False):
|
|
103
|
+
"""One thread per requested pair. Local scratch sizes are compile-time constants."""
|
|
104
|
+
real = float64 if precision == "float64" else float32
|
|
105
|
+
|
|
106
|
+
global_heap = capacity > LOCAL_CANDIDATES
|
|
107
|
+
local_capacity = 1 if global_heap else capacity
|
|
108
|
+
|
|
109
|
+
@cuda.jit
|
|
110
|
+
def kernel(
|
|
111
|
+
rmz,
|
|
112
|
+
rw,
|
|
113
|
+
rn,
|
|
114
|
+
rlen,
|
|
115
|
+
rp,
|
|
116
|
+
qmz,
|
|
117
|
+
qw,
|
|
118
|
+
qn,
|
|
119
|
+
qlen,
|
|
120
|
+
qp,
|
|
121
|
+
positions,
|
|
122
|
+
tolerance,
|
|
123
|
+
shift,
|
|
124
|
+
modified,
|
|
125
|
+
limit,
|
|
126
|
+
diagonal,
|
|
127
|
+
out,
|
|
128
|
+
retry,
|
|
129
|
+
heap_indices,
|
|
130
|
+
heap_values,
|
|
131
|
+
offset_k,
|
|
132
|
+
num_pairs,
|
|
133
|
+
):
|
|
134
|
+
lane = cuda.grid(1)
|
|
135
|
+
k = offset_k + lane
|
|
136
|
+
if lane >= num_pairs:
|
|
137
|
+
return
|
|
138
|
+
position = positions[k] if positions.size else k
|
|
139
|
+
i, j = position // qmz.shape[0], position % qmz.shape[0]
|
|
140
|
+
if diagonal and i > j:
|
|
141
|
+
return # The upper-triangle thread writes both entries.
|
|
142
|
+
# A counting pass can already have identified a true overflow.
|
|
143
|
+
if retry[k] < 0:
|
|
144
|
+
return
|
|
145
|
+
out[0, k], out[1, k], retry[k] = 0, 0, 0
|
|
146
|
+
nr, nq = rlen[i], qlen[j]
|
|
147
|
+
truncated = nr > rmz.shape[1] or nq > qmz.shape[1]
|
|
148
|
+
# In neutral-loss-only mode let
|
|
149
|
+
# matchms distinguish a zero norm with matches (undefined cosine) from
|
|
150
|
+
# a zero norm without matches (score zero).
|
|
151
|
+
neutral_only = modified == NEUTRAL_LOSS_ONLY
|
|
152
|
+
if truncated or (neutral_only and nr and nq and (rn[i] == 0 or qn[j] == 0)):
|
|
153
|
+
retry[k] = -1
|
|
154
|
+
elif rn[i] != 0 and qn[j] != 0:
|
|
155
|
+
if global_heap:
|
|
156
|
+
left, right, order = heap_indices[lane, 0], heap_indices[lane, 1], heap_indices[lane, 2]
|
|
157
|
+
values = heap_values[lane]
|
|
158
|
+
else:
|
|
159
|
+
left = cuda.local.array(local_capacity, int32)
|
|
160
|
+
right = cuda.local.array(local_capacity, int32)
|
|
161
|
+
order = cuda.local.array(local_capacity, int32)
|
|
162
|
+
values = cuda.local.array(local_capacity, real)
|
|
163
|
+
delta = rp[i] - qp[j]
|
|
164
|
+
count = _collect(
|
|
165
|
+
rmz[i],
|
|
166
|
+
rw[i],
|
|
167
|
+
nr,
|
|
168
|
+
qmz[j],
|
|
169
|
+
qw[j],
|
|
170
|
+
nq,
|
|
171
|
+
tolerance,
|
|
172
|
+
delta if neutral_only else shift,
|
|
173
|
+
0,
|
|
174
|
+
limit,
|
|
175
|
+
left,
|
|
176
|
+
right,
|
|
177
|
+
order,
|
|
178
|
+
values,
|
|
179
|
+
count_only,
|
|
180
|
+
)
|
|
181
|
+
if count >= 0 and modified and not neutral_only and abs(delta) > tolerance:
|
|
182
|
+
count = _collect(
|
|
183
|
+
rmz[i],
|
|
184
|
+
rw[i],
|
|
185
|
+
nr,
|
|
186
|
+
qmz[j],
|
|
187
|
+
qw[j],
|
|
188
|
+
nq,
|
|
189
|
+
tolerance,
|
|
190
|
+
delta,
|
|
191
|
+
count,
|
|
192
|
+
limit,
|
|
193
|
+
left,
|
|
194
|
+
right,
|
|
195
|
+
order,
|
|
196
|
+
values,
|
|
197
|
+
count_only,
|
|
198
|
+
)
|
|
199
|
+
|
|
200
|
+
if count_only or count < 0:
|
|
201
|
+
retry[k] = count
|
|
202
|
+
elif count:
|
|
203
|
+
used_r = cuda.local.array(width, uint8)
|
|
204
|
+
used_q = cuda.local.array(width, uint8)
|
|
205
|
+
for a in range(nr):
|
|
206
|
+
used_r[a] = 0
|
|
207
|
+
for b in range(nq):
|
|
208
|
+
used_q[b] = 0
|
|
209
|
+
for root in range(count // 2 - 1, -1, -1):
|
|
210
|
+
_sift_down(order, values, root, count)
|
|
211
|
+
total, matches = real(0), 0
|
|
212
|
+
while count:
|
|
213
|
+
edge = order[0]
|
|
214
|
+
a, b = left[edge], right[edge]
|
|
215
|
+
if not used_r[a] and not used_q[b]:
|
|
216
|
+
total += values[edge]
|
|
217
|
+
matches += 1
|
|
218
|
+
used_r[a], used_q[b] = 1, 1
|
|
219
|
+
count -= 1
|
|
220
|
+
order[0] = order[count]
|
|
221
|
+
_sift_down(order, values, 0, count)
|
|
222
|
+
# matchms fastmath takes one sqrt of the product of squared norms.
|
|
223
|
+
out[0, k], out[1, k] = total / sqrt(rn[i] * qn[j]), matches
|
|
224
|
+
if diagonal and i != j:
|
|
225
|
+
other = j * qmz.shape[0] + i
|
|
226
|
+
out[0, other], out[1, other] = out[0, k], out[1, k]
|
|
227
|
+
retry[other] = 0
|
|
228
|
+
|
|
229
|
+
return kernel
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
ENTROPY_HYBRID_CAP = 8192
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
@lru_cache(maxsize=64)
|
|
236
|
+
def entropy_kernel(mode, words):
|
|
237
|
+
"""Walk sorted fragment/loss masses; only hybrid needs per-pair peak bitsets."""
|
|
238
|
+
fragments = mode != "neutral_loss"
|
|
239
|
+
losses = mode != "fragment"
|
|
240
|
+
hybrid = fragments and losses
|
|
241
|
+
|
|
242
|
+
@cuda.jit
|
|
243
|
+
def kernel(left, lo, lp, right, ro, rp, positions, tolerance, use_ppm, diagonal, out):
|
|
244
|
+
k = cuda.grid(1)
|
|
245
|
+
if k >= out.size:
|
|
246
|
+
return
|
|
247
|
+
width = rp.size
|
|
248
|
+
pos = positions[k] if positions.size else k
|
|
249
|
+
i, j = pos // width, pos % width
|
|
250
|
+
if diagonal and i > j:
|
|
251
|
+
return
|
|
252
|
+
begin_l, begin_r = lo[i], ro[j]
|
|
253
|
+
size_l, size_r = lo[i + 1] - begin_l, ro[j + 1] - begin_r
|
|
254
|
+
use_losses = losses and not (isnan(lp[i]) or isnan(rp[j]))
|
|
255
|
+
track = hybrid and use_losses
|
|
256
|
+
used_l = cuda.local.array(words, uint32)
|
|
257
|
+
used_r = cuda.local.array(words, uint32)
|
|
258
|
+
|
|
259
|
+
total = 0.0
|
|
260
|
+
if track and max(size_l, size_r) > ENTROPY_HYBRID_CAP:
|
|
261
|
+
total = -inf # Exact host walk before dense/sparse output.
|
|
262
|
+
else:
|
|
263
|
+
if track:
|
|
264
|
+
for w in range((size_l + 31) // 32):
|
|
265
|
+
used_l[w] = 0
|
|
266
|
+
for w in range((size_r + 31) // 32):
|
|
267
|
+
used_r[w] = 0
|
|
268
|
+
for phase in range(2):
|
|
269
|
+
reverse = phase == 1
|
|
270
|
+
if (reverse and not use_losses) or (not reverse and not fragments):
|
|
271
|
+
continue
|
|
272
|
+
a, b = (size_l - 1, size_r - 1) if reverse else (0, 0)
|
|
273
|
+
step = -1 if reverse else 1
|
|
274
|
+
score = 0.0
|
|
275
|
+
while 0 <= a < size_l and 0 <= b < size_r:
|
|
276
|
+
if track and reverse:
|
|
277
|
+
if used_l[a // 32] & (uint32(1) << uint32(a % 32)):
|
|
278
|
+
a -= 1
|
|
279
|
+
continue
|
|
280
|
+
if used_r[b // 32] & (uint32(1) << uint32(b % 32)):
|
|
281
|
+
b -= 1
|
|
282
|
+
continue
|
|
283
|
+
x, y = begin_l + a, begin_r + b
|
|
284
|
+
p, q = left[x, 1], right[y, 1]
|
|
285
|
+
if p <= 0.0:
|
|
286
|
+
a += step
|
|
287
|
+
continue
|
|
288
|
+
if q <= 0.0:
|
|
289
|
+
b += step
|
|
290
|
+
continue
|
|
291
|
+
m, n = left[x, 0], right[y, 0]
|
|
292
|
+
if reverse:
|
|
293
|
+
m, n = lp[i] - m, rp[j] - n
|
|
294
|
+
limit = tolerance * 1e-6 * 0.5 * (m + n) if use_ppm else tolerance
|
|
295
|
+
if abs(m - n) <= limit:
|
|
296
|
+
combined = p + q
|
|
297
|
+
score += combined * log2(combined) - left[x, 2] - right[y, 2]
|
|
298
|
+
if track and not reverse:
|
|
299
|
+
used_l[a // 32] |= uint32(1) << uint32(a % 32)
|
|
300
|
+
used_r[b // 32] |= uint32(1) << uint32(b % 32)
|
|
301
|
+
a += step
|
|
302
|
+
b += step
|
|
303
|
+
elif m < n:
|
|
304
|
+
a += step
|
|
305
|
+
else:
|
|
306
|
+
b += step
|
|
307
|
+
total += score
|
|
308
|
+
out[k] = total
|
|
309
|
+
if diagonal and i != j:
|
|
310
|
+
out[j * width + i] = total
|
|
311
|
+
|
|
312
|
+
return kernel
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
"""Bounded CUDA tiles for scalar vector scores and matchms output containers."""
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
import torch
|
|
5
|
+
from matchms import Scores
|
|
6
|
+
from numba import cuda
|
|
7
|
+
from scipy import sparse
|
|
8
|
+
from tqdm import tqdm
|
|
9
|
+
|
|
10
|
+
from ..utils import get_device
|
|
11
|
+
from ._base import _ScalarCudaSimilarity
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def tile_slices(shape, batch_size, symmetric, requested, progress_bar):
|
|
15
|
+
starts = range(0, shape[0], batch_size) if requested is None else sorted(requested)
|
|
16
|
+
for r in tqdm(starts, desc="Scoring reference batches", disable=not progress_bar):
|
|
17
|
+
rows = slice(r, min(r + batch_size, shape[0]))
|
|
18
|
+
columns = (
|
|
19
|
+
range(r if symmetric else 0, shape[1], batch_size) if requested is None else sorted(requested[r])
|
|
20
|
+
)
|
|
21
|
+
for c in columns:
|
|
22
|
+
cols = slice(c, min(c + batch_size, shape[1]))
|
|
23
|
+
positions = None if requested is None else np.asarray(requested[r][c], dtype=np.intp)
|
|
24
|
+
yield rows, cols, positions
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def kernel_view(tensor):
|
|
28
|
+
if cuda.config.ENABLE_CUDASIM:
|
|
29
|
+
return tensor.numpy()
|
|
30
|
+
return cuda.as_cuda_array(tensor, sync=False)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def kernel_stream(device):
|
|
34
|
+
if cuda.config.ENABLE_CUDASIM:
|
|
35
|
+
return 0
|
|
36
|
+
return cuda.external_stream(torch.cuda.current_stream(device).cuda_stream)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@cuda.jit
|
|
40
|
+
def _count_overlap(left, right, dice, result):
|
|
41
|
+
# Adjacent lanes read adjacent features of the transposed query tile.
|
|
42
|
+
j, i = cuda.grid(2)
|
|
43
|
+
if i >= left.shape[0] or j >= right.shape[1]:
|
|
44
|
+
return
|
|
45
|
+
common = 0.0
|
|
46
|
+
union = 0.0
|
|
47
|
+
for k in range(left.shape[1]):
|
|
48
|
+
x, y = left[i, k], right[k, j]
|
|
49
|
+
common += min(x, y)
|
|
50
|
+
union += max(x, y)
|
|
51
|
+
if dice:
|
|
52
|
+
result[i, j] = 2 * common / (common + union) if union else 0.0
|
|
53
|
+
else:
|
|
54
|
+
result[i, j] = common / union if union else 1.0
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _similarity_tile(left, right, metric):
|
|
58
|
+
if metric == "euclidean":
|
|
59
|
+
return -torch.cdist(left, right, p=2, compute_mode="donot_use_mm_for_euclid_dist")
|
|
60
|
+
if metric == "cosine":
|
|
61
|
+
norms = left.norm(dim=1)[:, None] * right.norm(dim=1)
|
|
62
|
+
return torch.where(norms != 0, (left @ right.T) / norms, 0.0)
|
|
63
|
+
|
|
64
|
+
binary = ((left == 0) | (left == 1)).all() & ((right == 0) | (right == 1)).all()
|
|
65
|
+
if binary:
|
|
66
|
+
common = left @ right.T
|
|
67
|
+
total = left.sum(dim=1)[:, None] + right.sum(dim=1)
|
|
68
|
+
if metric == "dice":
|
|
69
|
+
return torch.where(total != 0, 2 * common / total, 0.0)
|
|
70
|
+
union = total - common
|
|
71
|
+
return torch.where(union != 0, common / union, 1.0)
|
|
72
|
+
|
|
73
|
+
result = left.new_empty((len(left), len(right)))
|
|
74
|
+
query_columns = right.T.contiguous()
|
|
75
|
+
blocks = ((len(right) + 15) // 16, (len(left) + 7) // 8)
|
|
76
|
+
if left.device.type == "cuda" or cuda.config.ENABLE_CUDASIM:
|
|
77
|
+
_count_overlap[blocks, (16, 8), kernel_stream(left.device)](
|
|
78
|
+
kernel_view(left), kernel_view(query_columns), metric == "dice", kernel_view(result)
|
|
79
|
+
)
|
|
80
|
+
else:
|
|
81
|
+
for i, row in enumerate(left):
|
|
82
|
+
common = torch.minimum(row, right).sum(dim=1)
|
|
83
|
+
union = torch.maximum(row, right).sum(dim=1)
|
|
84
|
+
if metric == "dice":
|
|
85
|
+
result[i] = torch.where(union != 0, 2 * common / (union + common), 0.0)
|
|
86
|
+
else:
|
|
87
|
+
result[i] = torch.where(union != 0, common / union, 1.0)
|
|
88
|
+
return result
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _compact_csr(left, right):
|
|
92
|
+
"""Drop globally empty columns before densifying tiles of unfolded fingerprints."""
|
|
93
|
+
if not (sparse.issparse(left) and sparse.issparse(right)):
|
|
94
|
+
return left, right
|
|
95
|
+
columns = np.union1d(left.indices, right.indices) if left is not right else np.unique(left.indices)
|
|
96
|
+
|
|
97
|
+
def compact(data):
|
|
98
|
+
return sparse.csr_matrix(
|
|
99
|
+
(data.data, np.searchsorted(columns, data.indices), data.indptr),
|
|
100
|
+
shape=(data.shape[0], len(columns)),
|
|
101
|
+
)
|
|
102
|
+
|
|
103
|
+
a = compact(left)
|
|
104
|
+
return a, a if left is right else compact(right)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
class _TiledVectorSimilarity(_ScalarCudaSimilarity):
|
|
108
|
+
"""Scalar Scores and NumPy outputs live on the host. Torch returns a 2D device tensor."""
|
|
109
|
+
|
|
110
|
+
is_commutative = True
|
|
111
|
+
score_fields = ("score",)
|
|
112
|
+
score_datatype = np.float64
|
|
113
|
+
|
|
114
|
+
def _configure_tiles(self, batch_size, precision):
|
|
115
|
+
if isinstance(batch_size, bool) or not isinstance(batch_size, (int, np.integer)) or batch_size < 1:
|
|
116
|
+
raise ValueError("batch_size must be a positive integer")
|
|
117
|
+
if precision not in ("float32", "float64"):
|
|
118
|
+
raise ValueError("precision must be 'float32' or 'float64'")
|
|
119
|
+
self.batch_size = int(batch_size)
|
|
120
|
+
self.precision = precision
|
|
121
|
+
self.score_datatype = np.dtype(precision)
|
|
122
|
+
|
|
123
|
+
@property
|
|
124
|
+
def device(self):
|
|
125
|
+
return get_device()
|
|
126
|
+
|
|
127
|
+
def _score_tile(self, left, right):
|
|
128
|
+
return _similarity_tile(left, right, self._metric)
|
|
129
|
+
|
|
130
|
+
def _vector_tiles(self, left, right, symmetric, requested, progress_bar):
|
|
131
|
+
if left.ndim != 2 or right.ndim != 2 or left.shape[1] != right.shape[1]:
|
|
132
|
+
raise ValueError("Expected two 2D arrays with the same number of features")
|
|
133
|
+
left, right = _compact_csr(left, right)
|
|
134
|
+
shape = left.shape[0], right.shape[0]
|
|
135
|
+
previous = None
|
|
136
|
+
|
|
137
|
+
def upload(data, rows):
|
|
138
|
+
batch = data[rows]
|
|
139
|
+
if sparse.issparse(batch):
|
|
140
|
+
batch = batch.toarray()
|
|
141
|
+
if isinstance(batch, np.ndarray) and any(stride < 0 for stride in batch.strides):
|
|
142
|
+
batch = np.ascontiguousarray(batch)
|
|
143
|
+
return torch.as_tensor(batch, device=self.device, dtype=getattr(torch, self.precision)).detach()
|
|
144
|
+
|
|
145
|
+
for rows, cols, positions in tile_slices(shape, self.batch_size, symmetric, requested, progress_bar):
|
|
146
|
+
if rows != previous:
|
|
147
|
+
a = upload(left, rows)
|
|
148
|
+
previous = rows
|
|
149
|
+
b = a if left is right and rows == cols else upload(right, cols)
|
|
150
|
+
yield rows, cols, positions, self._score_tile(a, b)
|
|
151
|
+
|
|
152
|
+
def _dense_vectors(self, left, right, symmetric, array_type, progress_bar):
|
|
153
|
+
shape = (left.shape[0], right.shape[0])
|
|
154
|
+
if array_type == "torch":
|
|
155
|
+
result = torch.empty(shape, device=self.device, dtype=getattr(torch, self.precision))
|
|
156
|
+
elif array_type in ("numpy", "scores"):
|
|
157
|
+
result = np.empty(shape, dtype=self.score_datatype)
|
|
158
|
+
else:
|
|
159
|
+
raise ValueError("array_type must be 'scores', 'numpy' or 'torch'")
|
|
160
|
+
for rows, cols, _, tile in self._vector_tiles(left, right, symmetric, None, progress_bar):
|
|
161
|
+
values = tile if array_type == "torch" else tile.cpu().numpy()
|
|
162
|
+
result[rows, cols] = values
|
|
163
|
+
if symmetric and rows != cols:
|
|
164
|
+
result[cols, rows] = values.T
|
|
165
|
+
return Scores({"score": result}) if array_type == "scores" else result
|
|
166
|
+
|
|
167
|
+
def matrix(self, spectra_1, spectra_2=None, score_fields=None, progress_bar=True, array_type="scores"):
|
|
168
|
+
self._fields(score_fields)
|
|
169
|
+
left, right, symmetric = self._inputs(spectra_1, spectra_2)
|
|
170
|
+
return self._dense_vectors(left, right, symmetric, array_type, progress_bar)
|
|
171
|
+
|
|
172
|
+
def _tiles(self, left, right, symmetric, requested, progress_bar):
|
|
173
|
+
for rows, cols, positions, tile in self._vector_tiles(left, right, symmetric, requested, progress_bar):
|
|
174
|
+
scores = tile.flatten()
|
|
175
|
+
if positions is not None:
|
|
176
|
+
scores = scores.index_select(0, torch.as_tensor(positions, device=tile.device))
|
|
177
|
+
yield rows, cols, positions, scores
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def _raw_matrix(references, queries, metric, batch_size, precision):
|
|
181
|
+
scorer = _TiledVectorSimilarity()
|
|
182
|
+
scorer._configure_tiles(batch_size, precision)
|
|
183
|
+
scorer._metric = metric
|
|
184
|
+
a = references if hasattr(references, "shape") else np.asarray(references)
|
|
185
|
+
b = queries if hasattr(queries, "shape") else np.asarray(queries)
|
|
186
|
+
return scorer._dense_vectors(a, b, False, "numpy", False)
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def jaccard_similarity_matrix(references, queries, batch_size=2048, precision="float64"):
|
|
190
|
+
return _raw_matrix(references, queries, "tanimoto", batch_size, precision)
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def dice_similarity_matrix(references, queries, batch_size=2048, precision="float64"):
|
|
194
|
+
return _raw_matrix(references, queries, "dice", batch_size, precision)
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def cosine_similarity_matrix(references, queries, batch_size=2048, precision="float64"):
|
|
198
|
+
return _raw_matrix(references, queries, "cosine", batch_size, precision)
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def euclidean_similarity_matrix(references, queries, batch_size=2048, precision="float64"):
|
|
202
|
+
return _raw_matrix(references, queries, "euclidean", batch_size, precision)
|
simms/utils.py
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import shutil
|
|
3
|
+
import tempfile
|
|
4
|
+
import time
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import Iterable, Literal, Optional, Type
|
|
7
|
+
import requests
|
|
8
|
+
import torch
|
|
9
|
+
from joblib import Memory
|
|
10
|
+
from numba import cuda
|
|
11
|
+
from matchms import Scores, Spectrum
|
|
12
|
+
from matchms.filtering import (
|
|
13
|
+
normalize_intensities,
|
|
14
|
+
reduce_to_number_of_peaks,
|
|
15
|
+
require_minimum_number_of_peaks,
|
|
16
|
+
select_by_mz,
|
|
17
|
+
select_by_relative_intensity,
|
|
18
|
+
)
|
|
19
|
+
from matchms.similarity.base_similarity import BaseSimilarity
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
cache = Memory("cache", verbose=0).cache
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def argbatch(lst: list, batch_size: int) -> Iterable[tuple[int, int]]:
|
|
26
|
+
"""
|
|
27
|
+
Given a list, return batches of indices, of size `batch_size`. It can be used as follows:
|
|
28
|
+
|
|
29
|
+
```
|
|
30
|
+
for bstart, bend in argbatch(references, 2048):
|
|
31
|
+
rbatch = references[bstart:bend]
|
|
32
|
+
# Do something with `rbatch`
|
|
33
|
+
```
|
|
34
|
+
"""
|
|
35
|
+
for i in range(0, len(lst), batch_size):
|
|
36
|
+
yield i, i + batch_size
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def mkdir(p: Path, clean=False) -> Path:
|
|
40
|
+
"Modified pathlib mkdir, made a bit convenient to use."
|
|
41
|
+
p = Path(p)
|
|
42
|
+
if clean and p.is_dir() and p.exists():
|
|
43
|
+
shutil.rmtree(p, ignore_errors=True)
|
|
44
|
+
p.mkdir(exist_ok=True, parents=True)
|
|
45
|
+
return p
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def process_spectrum(spectrum: Spectrum) -> Optional[Spectrum]:
|
|
49
|
+
"""
|
|
50
|
+
One of the many ways to preprocess the spectrum - we use this by default.
|
|
51
|
+
"""
|
|
52
|
+
spectrum = select_by_mz(spectrum, mz_from=10.0, mz_to=1000.0)
|
|
53
|
+
spectrum = normalize_intensities(spectrum)
|
|
54
|
+
spectrum = select_by_relative_intensity(spectrum, intensity_from=0.001)
|
|
55
|
+
spectrum = reduce_to_number_of_peaks(spectrum, n_max=1024)
|
|
56
|
+
spectrum = require_minimum_number_of_peaks(spectrum, n_required=5)
|
|
57
|
+
return spectrum
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def download(name: Literal["GNPS-random-10k.mgf", "pesticides.mgf"]) -> str:
|
|
61
|
+
"""
|
|
62
|
+
Downloads a set of sample spectra files from https://github.com/PangeAI/simms/releases/tag/sample-files
|
|
63
|
+
Downloaded files are cached, and not re-downloaded after the initial call.
|
|
64
|
+
"""
|
|
65
|
+
# Define the local file path
|
|
66
|
+
local_dir = Path("data/downloads")
|
|
67
|
+
local_dir.mkdir(parents=True, exist_ok=True)
|
|
68
|
+
local_file = local_dir / name
|
|
69
|
+
|
|
70
|
+
# Check if the file already exists locally
|
|
71
|
+
if local_file.exists():
|
|
72
|
+
return str(local_file)
|
|
73
|
+
|
|
74
|
+
# URL for downloading the file
|
|
75
|
+
url = f"https://github.com/PangeAI/simms/releases/download/sample-files/{name}"
|
|
76
|
+
|
|
77
|
+
temp_path = None
|
|
78
|
+
try:
|
|
79
|
+
with requests.get(url, stream=True, timeout=60) as response:
|
|
80
|
+
response.raise_for_status()
|
|
81
|
+
with tempfile.NamedTemporaryFile(dir=local_dir, delete=False) as temp:
|
|
82
|
+
temp_path = Path(temp.name)
|
|
83
|
+
for chunk in response.iter_content(chunk_size=8192):
|
|
84
|
+
temp.write(chunk)
|
|
85
|
+
os.replace(temp_path, local_file)
|
|
86
|
+
finally:
|
|
87
|
+
if temp_path is not None:
|
|
88
|
+
temp_path.unlink(missing_ok=True)
|
|
89
|
+
return str(local_file)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
class Timer:
|
|
93
|
+
def __enter__(self):
|
|
94
|
+
self.duration = -time.perf_counter()
|
|
95
|
+
return self
|
|
96
|
+
|
|
97
|
+
def __exit__(self, *args):
|
|
98
|
+
self.duration += time.perf_counter()
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
@cache
|
|
102
|
+
def get_correct_scores(
|
|
103
|
+
references: list,
|
|
104
|
+
queries: list,
|
|
105
|
+
similarity_class: Type[BaseSimilarity],
|
|
106
|
+
**similarity_parameters,
|
|
107
|
+
) -> Scores:
|
|
108
|
+
"""
|
|
109
|
+
MatchMS is quite slow for large number of spectra. To avoid re-calculating same scores with exact same arguments for testing,
|
|
110
|
+
we cache the results on the disk and read them back if everything matches (class, args, all spectra involved).
|
|
111
|
+
"""
|
|
112
|
+
return similarity_class(**similarity_parameters).matrix(references, queries)
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def get_device(*, require_cuda=False) -> str:
|
|
116
|
+
"""Select the scoring device, allowing CPU vector math and the Numba simulator."""
|
|
117
|
+
if cuda.config.ENABLE_CUDASIM:
|
|
118
|
+
return "cpu"
|
|
119
|
+
if torch.cuda.is_available():
|
|
120
|
+
return "cuda"
|
|
121
|
+
if require_cuda:
|
|
122
|
+
raise RuntimeError(
|
|
123
|
+
"Spectral scoring requires CUDA. Install CUDA-enabled PyTorch and a compatible "
|
|
124
|
+
"NVIDIA driver, or set NUMBA_ENABLE_CUDASIM=1 before starting Python for testing."
|
|
125
|
+
)
|
|
126
|
+
return "cpu"
|