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
simms/__init__.py
ADDED
simms/__version__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "1.0.0"
|
simms/peaks.py
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
"""Array-native input for spectral similarity scoring."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Iterable, Mapping
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
|
|
6
|
+
import numpy as np
|
|
7
|
+
from matchms import SpectraCollection
|
|
8
|
+
from matchms.similarity.spectrum_similarity_functions import filter_noise, filter_peaks_above_precursor
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def _check_row(mz, intensities, index):
|
|
12
|
+
if mz.ndim != 1 or intensities.shape != mz.shape:
|
|
13
|
+
raise ValueError(f"row {index}: mz and intensities must be aligned 1D arrays")
|
|
14
|
+
if not (np.isfinite(mz).all() and np.isfinite(intensities).all()):
|
|
15
|
+
raise ValueError(f"row {index}: active peaks must be finite")
|
|
16
|
+
if np.any(mz[1:] < mz[:-1]):
|
|
17
|
+
raise ValueError(f"row {index}: mz must be sorted in non-decreasing order")
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _spectrum_rows(spectra):
|
|
21
|
+
if isinstance(spectra, PeakArrays):
|
|
22
|
+
for i, n in enumerate(spectra.lengths):
|
|
23
|
+
precursor = None if spectra.precursor_mz is None else spectra.precursor_mz[i]
|
|
24
|
+
yield spectra.mz[i, :n], spectra.intensities[i, :n], precursor
|
|
25
|
+
elif isinstance(spectra, SpectraCollection):
|
|
26
|
+
fragments = spectra.fragments
|
|
27
|
+
csr = fragments.array
|
|
28
|
+
mz = fragments.bin_to_mz(csr.indices)
|
|
29
|
+
precursors = spectra.metadata.get("precursor_mz")
|
|
30
|
+
for i in range(len(spectra)):
|
|
31
|
+
row = slice(csr.indptr[i], csr.indptr[i + 1])
|
|
32
|
+
yield mz[row], csr.data[row], None if precursors is None else precursors.iloc[i]
|
|
33
|
+
else:
|
|
34
|
+
if isinstance(spectra, np.ndarray):
|
|
35
|
+
if spectra.ndim != 1 or spectra.dtype != object:
|
|
36
|
+
raise TypeError(
|
|
37
|
+
"spectra must be a 1D object ndarray of spectra; use PeakArrays for numeric data"
|
|
38
|
+
)
|
|
39
|
+
elif not isinstance(spectra, Iterable) or isinstance(spectra, (str, bytes, Mapping)):
|
|
40
|
+
raise TypeError("expected an iterable of spectra, SpectraCollection or PeakArrays")
|
|
41
|
+
for i, spectrum in enumerate(spectra):
|
|
42
|
+
try:
|
|
43
|
+
peaks = spectrum.peaks
|
|
44
|
+
mz, intensities = peaks.mz, peaks.intensities
|
|
45
|
+
except AttributeError as exc:
|
|
46
|
+
raise TypeError(
|
|
47
|
+
f"spectra[{i}]: expected a spectrum with public peaks, got {type(spectrum).__name__}"
|
|
48
|
+
) from exc
|
|
49
|
+
get = getattr(spectrum, "get", None)
|
|
50
|
+
yield mz, intensities, get("precursor_mz", None) if get else None
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
@dataclass(frozen=True, eq=False)
|
|
54
|
+
class PeakArrays:
|
|
55
|
+
"""Sorted, zero-padded peak rows. Only the first lengths[i] entries are active."""
|
|
56
|
+
|
|
57
|
+
mz: np.ndarray
|
|
58
|
+
intensities: np.ndarray
|
|
59
|
+
lengths: np.ndarray
|
|
60
|
+
precursor_mz: np.ndarray | None = None
|
|
61
|
+
|
|
62
|
+
def __post_init__(self):
|
|
63
|
+
mz, intensities = np.asarray(self.mz), np.asarray(self.intensities)
|
|
64
|
+
lengths = np.asarray(self.lengths)
|
|
65
|
+
if mz.ndim != 2 or intensities.shape != mz.shape:
|
|
66
|
+
raise ValueError("mz and intensities must be 2D arrays with identical shape")
|
|
67
|
+
if mz.dtype.kind != "f" or intensities.dtype.kind != "f":
|
|
68
|
+
raise TypeError("mz and intensities must be floating-point arrays")
|
|
69
|
+
if lengths.shape != (len(mz),) or lengths.dtype.kind not in "iu":
|
|
70
|
+
raise ValueError("lengths must be a 1D integral array with one entry per spectrum")
|
|
71
|
+
if np.any(lengths < 0) or np.any(lengths > mz.shape[1]):
|
|
72
|
+
raise ValueError("lengths must be between zero and the array width")
|
|
73
|
+
# Own the buffers so fixing dirty padding never mutates the caller's arrays.
|
|
74
|
+
mz, intensities, lengths = mz.copy(), intensities.copy(), lengths.astype(np.intp, copy=True)
|
|
75
|
+
for i, n in enumerate(lengths):
|
|
76
|
+
_check_row(mz[i, :n], intensities[i, :n], i)
|
|
77
|
+
mz[i, n:] = 0
|
|
78
|
+
intensities[i, n:] = 0
|
|
79
|
+
arrays = dict(mz=mz, intensities=intensities, lengths=lengths)
|
|
80
|
+
if self.precursor_mz is not None:
|
|
81
|
+
precursor = np.array(self.precursor_mz, dtype=np.float64, copy=True)
|
|
82
|
+
if precursor.shape != lengths.shape or not np.all(np.isfinite(precursor) & (precursor > 0)):
|
|
83
|
+
raise ValueError("precursor_mz must contain one positive finite value per spectrum")
|
|
84
|
+
arrays["precursor_mz"] = precursor
|
|
85
|
+
for name, array in arrays.items():
|
|
86
|
+
array.setflags(write=False)
|
|
87
|
+
object.__setattr__(self, name, array)
|
|
88
|
+
|
|
89
|
+
def __len__(self):
|
|
90
|
+
return len(self.lengths)
|
|
91
|
+
|
|
92
|
+
@property
|
|
93
|
+
def width(self):
|
|
94
|
+
return self.mz.shape[1]
|
|
95
|
+
|
|
96
|
+
def __getitem__(self, index):
|
|
97
|
+
if not isinstance(index, slice):
|
|
98
|
+
raise TypeError("PeakArrays supports slicing by spectrum rows")
|
|
99
|
+
precursor = None if self.precursor_mz is None else self.precursor_mz[index]
|
|
100
|
+
return PeakArrays(self.mz[index], self.intensities[index], self.lengths[index], precursor)
|
|
101
|
+
|
|
102
|
+
def to_width(self, width, dtype=np.float32):
|
|
103
|
+
"""Return stacked peak planes and lengths capped at the requested width."""
|
|
104
|
+
if not isinstance(width, (int, np.integer)) or width < 0:
|
|
105
|
+
raise ValueError("width must be a non-negative integer")
|
|
106
|
+
result = np.zeros((2, len(self), width), dtype=dtype)
|
|
107
|
+
n = min(width, self.width)
|
|
108
|
+
result[0, :, :n], result[1, :, :n] = self.mz[:, :n], self.intensities[:, :n]
|
|
109
|
+
return result, np.minimum(self.lengths, width).astype(np.intp)
|
|
110
|
+
|
|
111
|
+
@classmethod
|
|
112
|
+
def from_peak_lists(cls, mz_lists, intensity_lists, precursor_mz=None, dtype=np.float64):
|
|
113
|
+
"""Pad aligned, one-dimensional arrays without truncating any peaks."""
|
|
114
|
+
if len(mz_lists) != len(intensity_lists):
|
|
115
|
+
raise ValueError("mz_lists and intensity_lists must contain the same number of spectra")
|
|
116
|
+
rows = []
|
|
117
|
+
for i, (mz, intensities) in enumerate(zip(mz_lists, intensity_lists)):
|
|
118
|
+
mz, intensities = np.asarray(mz, dtype=dtype), np.asarray(intensities, dtype=dtype)
|
|
119
|
+
if mz.ndim != 1 or mz.shape != intensities.shape:
|
|
120
|
+
raise ValueError(f"row {i}: mz and intensities must be aligned 1D arrays")
|
|
121
|
+
rows.append((mz, intensities))
|
|
122
|
+
lengths = np.array([len(m) for m, _ in rows], dtype=np.intp)
|
|
123
|
+
mz = np.zeros((len(rows), lengths.max(initial=0)), dtype=dtype)
|
|
124
|
+
intensities = np.zeros_like(mz)
|
|
125
|
+
for i, (m, x) in enumerate(rows):
|
|
126
|
+
mz[i, : len(m)] = m
|
|
127
|
+
intensities[i, : len(m)] = x
|
|
128
|
+
return cls(mz, intensities, lengths, precursor_mz)
|
|
129
|
+
|
|
130
|
+
@classmethod
|
|
131
|
+
def from_spectra(
|
|
132
|
+
cls,
|
|
133
|
+
spectra,
|
|
134
|
+
require_precursor=False,
|
|
135
|
+
remove_precursor=False,
|
|
136
|
+
offset_to_precursor=-1.6,
|
|
137
|
+
noise_cutoff=0.0,
|
|
138
|
+
dtype=np.float64,
|
|
139
|
+
):
|
|
140
|
+
"""Extract public peaks once, crop at the precursor, then filter relative noise."""
|
|
141
|
+
denoise = noise_cutoff is not None and noise_cutoff > 0
|
|
142
|
+
if isinstance(spectra, cls) and not remove_precursor and not denoise:
|
|
143
|
+
if require_precursor and len(spectra) and spectra.precursor_mz is None:
|
|
144
|
+
raise ValueError("spectra[0]: missing precursor_mz")
|
|
145
|
+
if spectra.mz.dtype == spectra.intensities.dtype == dtype:
|
|
146
|
+
return spectra
|
|
147
|
+
|
|
148
|
+
masses, signals, precursors = [], [], []
|
|
149
|
+
for i, (mz, intensity, precursor) in enumerate(_spectrum_rows(spectra)):
|
|
150
|
+
# matchms stacks the two peak columns before filtering. Preserve that
|
|
151
|
+
# dtype here, including float32 rounding at the precursor boundary.
|
|
152
|
+
mz, intensity = np.asarray(mz), np.asarray(intensity)
|
|
153
|
+
common_dtype = np.result_type(mz, intensity)
|
|
154
|
+
if common_dtype.kind not in "fiu":
|
|
155
|
+
raise TypeError(f"spectra[{i}]: expected numeric mz and intensities")
|
|
156
|
+
mz, intensity = mz.astype(common_dtype, copy=False), intensity.astype(common_dtype, copy=False)
|
|
157
|
+
_check_row(mz, intensity, i)
|
|
158
|
+
if precursor is not None:
|
|
159
|
+
try:
|
|
160
|
+
precursor = float(precursor)
|
|
161
|
+
except (TypeError, ValueError):
|
|
162
|
+
precursor = None
|
|
163
|
+
if precursor is not None and (not np.isfinite(precursor) or precursor <= 0):
|
|
164
|
+
precursor = None
|
|
165
|
+
if precursor is None and (require_precursor or remove_precursor):
|
|
166
|
+
raise ValueError(f"spectra[{i}]: expected positive finite precursor_mz")
|
|
167
|
+
if remove_precursor:
|
|
168
|
+
mz, intensity = filter_peaks_above_precursor(mz, intensity, precursor, offset_to_precursor)
|
|
169
|
+
if denoise:
|
|
170
|
+
mz, intensity = filter_noise(mz, intensity, noise_cutoff)
|
|
171
|
+
masses.append(mz)
|
|
172
|
+
signals.append(intensity)
|
|
173
|
+
precursors.append(precursor)
|
|
174
|
+
return cls.from_peak_lists(masses, signals, None if None in precursors else precursors, dtype)
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
"""GPU-binned, max-normalized spectral embeddings."""
|
|
2
|
+
|
|
3
|
+
from itertools import islice
|
|
4
|
+
|
|
5
|
+
import numpy as np
|
|
6
|
+
import torch
|
|
7
|
+
from matchms.similarity import BinnedEmbeddingSimilarity
|
|
8
|
+
|
|
9
|
+
from ..peaks import PeakArrays, _spectrum_rows
|
|
10
|
+
from .vector_similarity_functions import _TiledVectorSimilarity
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class CudaBinnedEmbeddingSimilarity(_TiledVectorSimilarity, BinnedEmbeddingSimilarity):
|
|
14
|
+
"""Bin peaks on device, then compare embeddings in batch_size by batch_size tiles."""
|
|
15
|
+
|
|
16
|
+
def __init__(
|
|
17
|
+
self,
|
|
18
|
+
similarity="cosine",
|
|
19
|
+
max_mz=1005,
|
|
20
|
+
bin_width=1,
|
|
21
|
+
intensity_power=1,
|
|
22
|
+
*,
|
|
23
|
+
batch_size=2048,
|
|
24
|
+
precision="float64",
|
|
25
|
+
):
|
|
26
|
+
BinnedEmbeddingSimilarity.__init__(self, similarity, max_mz, bin_width, intensity_power)
|
|
27
|
+
self._configure_tiles(batch_size, precision)
|
|
28
|
+
|
|
29
|
+
def _score_tile(self, left, right):
|
|
30
|
+
if self.similarity == "euclidean":
|
|
31
|
+
return super()._score_tile(left, right)
|
|
32
|
+
|
|
33
|
+
# sklearn's embedding cosine normalizes each row before GEMM and
|
|
34
|
+
# leaves near-zero rows at their original scale.
|
|
35
|
+
def normalized(data):
|
|
36
|
+
norms = data.norm(dim=1, keepdim=True)
|
|
37
|
+
return data / torch.where(norms < 10 * torch.finfo(data.dtype).eps, 1.0, norms)
|
|
38
|
+
|
|
39
|
+
a = normalized(left)
|
|
40
|
+
b = a if left is right else normalized(right)
|
|
41
|
+
return a @ b.T
|
|
42
|
+
|
|
43
|
+
@property
|
|
44
|
+
def _metric(self):
|
|
45
|
+
return self.similarity
|
|
46
|
+
|
|
47
|
+
def _bin_rows(self, rows):
|
|
48
|
+
output = torch.zeros(
|
|
49
|
+
(len(rows), self.n_bins), device=self.device, dtype=getattr(torch, self.precision)
|
|
50
|
+
)
|
|
51
|
+
# NumPy applies the bin division and intensity power in the input dtype.
|
|
52
|
+
# Group mixed-precision spectra to preserve that rounding at bin edges.
|
|
53
|
+
groups = {}
|
|
54
|
+
for i, (mz, intensities, _) in enumerate(rows):
|
|
55
|
+
groups.setdefault((mz.dtype, intensities.dtype), []).append((i, mz, intensities))
|
|
56
|
+
for group in groups.values():
|
|
57
|
+
mz = torch.as_tensor(np.concatenate([m for _, m, _ in group]), device=self.device)
|
|
58
|
+
intensity = torch.as_tensor(np.concatenate([x for _, _, x in group]), device=self.device)
|
|
59
|
+
indices = np.repeat([i for i, _, _ in group], [len(m) for _, m, _ in group])
|
|
60
|
+
indices = torch.as_tensor(indices, device=self.device)
|
|
61
|
+
valid = (mz >= 0) & (mz <= self.max_mz)
|
|
62
|
+
# A device divisor preserves IEEE division. PyTorch lowers a Python
|
|
63
|
+
# scalar divisor to reciprocal multiplication on CUDA.
|
|
64
|
+
if not mz.is_floating_point():
|
|
65
|
+
mz = mz.to(torch.float64)
|
|
66
|
+
width = mz.new_tensor(self.bin_width)
|
|
67
|
+
bins = (mz[valid] / width).floor().long().clamp_(0, self.n_bins - 1)
|
|
68
|
+
output.view(-1).scatter_add_(
|
|
69
|
+
0,
|
|
70
|
+
indices[valid] * self.n_bins + bins,
|
|
71
|
+
intensity[valid].pow(self.intensity_power).to(output.dtype),
|
|
72
|
+
)
|
|
73
|
+
maxima = output.amax(dim=1, keepdim=True)
|
|
74
|
+
return output / torch.where(maxima > 0, maxima, 1.0)
|
|
75
|
+
|
|
76
|
+
def compute_embeddings(self, spectra):
|
|
77
|
+
"""Return host embeddings, staging at most batch_size spectra on device."""
|
|
78
|
+
if not hasattr(spectra, "__len__"):
|
|
79
|
+
spectra = list(spectra)
|
|
80
|
+
result = np.empty((len(spectra), self.n_bins), dtype=self.score_datatype)
|
|
81
|
+
iterator = _spectrum_rows(spectra)
|
|
82
|
+
for start in range(0, len(spectra), self.batch_size):
|
|
83
|
+
rows = list(islice(iterator, self.batch_size))
|
|
84
|
+
result[start : start + len(rows)] = self._bin_rows(rows).cpu().numpy()
|
|
85
|
+
return result
|
|
86
|
+
|
|
87
|
+
def _inputs(self, spectra_1, spectra_2):
|
|
88
|
+
left = self.compute_embeddings(spectra_1)
|
|
89
|
+
right = left if spectra_2 is None or spectra_1 is spectra_2 else self.compute_embeddings(spectra_2)
|
|
90
|
+
return left, right, spectra_2 is None
|
|
91
|
+
|
|
92
|
+
def compute_similarity_matrix_from_embeddings(self, embeddings_1, embeddings_2=None):
|
|
93
|
+
a = self._validate_embeddings(embeddings_1)
|
|
94
|
+
b = a if embeddings_2 is None else self._validate_embeddings(embeddings_2)
|
|
95
|
+
return self._dense_vectors(a, b, embeddings_2 is None, "numpy", False)
|
|
96
|
+
|
|
97
|
+
def pair(self, spectrum_1, spectrum_2):
|
|
98
|
+
"""Compare two spectra, or two single-row PeakArrays."""
|
|
99
|
+
a = spectrum_1 if isinstance(spectrum_1, PeakArrays) else [spectrum_1]
|
|
100
|
+
b = spectrum_2 if isinstance(spectrum_2, PeakArrays) else [spectrum_2]
|
|
101
|
+
if len(a) != 1 or len(b) != 1:
|
|
102
|
+
raise ValueError("pair expects one spectrum per input")
|
|
103
|
+
return self.matrix(a, b, array_type="numpy", progress_bar=False).reshape(())
|
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
import torch
|
|
3
|
+
from numba import cuda
|
|
4
|
+
from tqdm import tqdm
|
|
5
|
+
|
|
6
|
+
from ..peaks import PeakArrays
|
|
7
|
+
from ..utils import get_device
|
|
8
|
+
from ._base import CudaSimilarity
|
|
9
|
+
from .spectrum_similarity_functions import LOCAL_CANDIDATES, cosine_kernel, exact_score, peak_weights
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def _positive_int(name, value):
|
|
13
|
+
if isinstance(value, (bool, np.bool_)) or not isinstance(value, (int, np.integer)) or value <= 0:
|
|
14
|
+
raise ValueError(f"{name} must be a positive integer")
|
|
15
|
+
return int(value)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _scratch_size(n):
|
|
19
|
+
# Bucket specializations so slightly different tile widths reuse compiled kernels.
|
|
20
|
+
return 1 << (max(1, int(n)) - 1).bit_length()
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class _GreedySimilarity(CudaSimilarity):
|
|
24
|
+
"""Shared greedy scoring parameters and CUDA batching.
|
|
25
|
+
|
|
26
|
+
batch_size bounds each tile axis. n_max_peaks optionally lowers the device
|
|
27
|
+
width below its 8192-peak safety cap. Pairs exceeding either peak cap or
|
|
28
|
+
match_limit are scored from the complete preprocessed rows with matchms.
|
|
29
|
+
precision selects FP64 (default) or FP32 device computation.
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
modified = False
|
|
33
|
+
shift = 0.0
|
|
34
|
+
|
|
35
|
+
def __init__(
|
|
36
|
+
self,
|
|
37
|
+
tolerance=0.01,
|
|
38
|
+
mz_power=0.0,
|
|
39
|
+
intensity_power=1.0,
|
|
40
|
+
noise_cutoff=0.01,
|
|
41
|
+
remove_precursor=True,
|
|
42
|
+
offset_to_precursor=-1.6,
|
|
43
|
+
batch_size=2048,
|
|
44
|
+
n_max_peaks=None,
|
|
45
|
+
match_limit=2048,
|
|
46
|
+
precision="float64",
|
|
47
|
+
):
|
|
48
|
+
self.tolerance = float(tolerance)
|
|
49
|
+
if not np.isfinite(self.tolerance) or self.tolerance < 0:
|
|
50
|
+
raise ValueError("tolerance must be finite and non-negative")
|
|
51
|
+
self.mz_power = float(mz_power)
|
|
52
|
+
self.intensity_power = float(intensity_power)
|
|
53
|
+
self.noise_cutoff = noise_cutoff
|
|
54
|
+
self.remove_precursor = remove_precursor
|
|
55
|
+
self.offset_to_precursor = offset_to_precursor
|
|
56
|
+
self.batch_size = _positive_int("batch_size", batch_size)
|
|
57
|
+
self.n_max_peaks = None if n_max_peaks is None else _positive_int("n_max_peaks", n_max_peaks)
|
|
58
|
+
self.match_limit = _positive_int("match_limit", match_limit)
|
|
59
|
+
if precision not in ("float32", "float64"):
|
|
60
|
+
raise ValueError("precision must be 'float32' or 'float64'")
|
|
61
|
+
self.precision = precision
|
|
62
|
+
|
|
63
|
+
@property
|
|
64
|
+
def device(self):
|
|
65
|
+
return get_device(require_cuda=True)
|
|
66
|
+
|
|
67
|
+
def _inputs(self, spectra_1, spectra_2):
|
|
68
|
+
def prepare(data, side):
|
|
69
|
+
try:
|
|
70
|
+
return PeakArrays.from_spectra(
|
|
71
|
+
data, self.modified, self.remove_precursor, self.offset_to_precursor, self.noise_cutoff
|
|
72
|
+
)
|
|
73
|
+
except (TypeError, ValueError) as exc:
|
|
74
|
+
raise type(exc)(f"{side}: {exc}") from exc
|
|
75
|
+
|
|
76
|
+
left = prepare(spectra_1, "spectra_1")
|
|
77
|
+
right = left if spectra_2 is None or spectra_2 is spectra_1 else prepare(spectra_2, "spectra_2")
|
|
78
|
+
return left, right, spectra_2 is None and self.is_commutative
|
|
79
|
+
|
|
80
|
+
def _batch(self, peaks, rows):
|
|
81
|
+
lengths = peaks.lengths[rows]
|
|
82
|
+
# Bound per-thread CUDA local memory. Larger spectra retain their full
|
|
83
|
+
# host rows for exact recovery, including when a user supplies a cap.
|
|
84
|
+
width = min(int(lengths.max(initial=0)), self.n_max_peaks or 8192, 8192)
|
|
85
|
+
mz = np.ascontiguousarray(peaks.mz[rows, :width], dtype=self.precision)
|
|
86
|
+
intensity = np.ascontiguousarray(peaks.intensities[rows, :width], dtype=self.precision)
|
|
87
|
+
weights, norms = peak_weights(mz, intensity, lengths, self.mz_power, self.intensity_power)
|
|
88
|
+
precursor = np.zeros(len(lengths)) if peaks.precursor_mz is None else peaks.precursor_mz[rows]
|
|
89
|
+
return tuple(torch.tensor(a, device=self.device) for a in (mz, weights, norms, lengths, precursor))
|
|
90
|
+
|
|
91
|
+
def _tile(self, rbatch, qbatch, positions, diagonal):
|
|
92
|
+
rmz, qmz = rbatch[0], qbatch[0]
|
|
93
|
+
count = len(rmz) * len(qmz) if positions is None else len(positions)
|
|
94
|
+
indices = torch.tensor([] if positions is None else positions, dtype=torch.int64, device=rmz.device)
|
|
95
|
+
result = torch.empty((2, count), dtype=rmz.dtype, device=rmz.device)
|
|
96
|
+
retry = torch.zeros(count, dtype=torch.int32, device=rmz.device)
|
|
97
|
+
width = _scratch_size(max(rmz.shape[1], qmz.shape[1]))
|
|
98
|
+
limit = min(self.match_limit, rmz.shape[1] * qmz.shape[1] * (2 if self.modified else 1))
|
|
99
|
+
if cuda.config.ENABLE_CUDASIM:
|
|
100
|
+
|
|
101
|
+
def view(tensor):
|
|
102
|
+
return tensor.numpy()
|
|
103
|
+
|
|
104
|
+
stream = 0
|
|
105
|
+
else:
|
|
106
|
+
|
|
107
|
+
def view(tensor):
|
|
108
|
+
return cuda.as_cuda_array(tensor, sync=False)
|
|
109
|
+
|
|
110
|
+
stream = cuda.external_stream(torch.cuda.current_stream(rmz.device).cuda_stream)
|
|
111
|
+
|
|
112
|
+
def launch(capacity, count_only=False):
|
|
113
|
+
lanes = count
|
|
114
|
+
heap_slots = 0
|
|
115
|
+
if capacity > LOCAL_CANDIDATES:
|
|
116
|
+
heap_slots = capacity
|
|
117
|
+
bytes_per_heap = capacity * (3 * 4 + rmz.element_size())
|
|
118
|
+
lanes = min(count, max(1, (64 << 20) // bytes_per_heap))
|
|
119
|
+
heap_indices = torch.empty((lanes, 3, heap_slots), dtype=torch.int32, device=rmz.device)
|
|
120
|
+
heap_values = torch.empty((lanes, heap_slots), dtype=rmz.dtype, device=rmz.device)
|
|
121
|
+
kernel = cosine_kernel(width, capacity, self.precision, count_only)
|
|
122
|
+
args = (
|
|
123
|
+
*map(view, rbatch),
|
|
124
|
+
*map(view, qbatch),
|
|
125
|
+
view(indices),
|
|
126
|
+
self.tolerance,
|
|
127
|
+
self.shift,
|
|
128
|
+
self.modified,
|
|
129
|
+
limit,
|
|
130
|
+
diagonal,
|
|
131
|
+
view(result),
|
|
132
|
+
view(retry),
|
|
133
|
+
view(heap_indices),
|
|
134
|
+
view(heap_values),
|
|
135
|
+
)
|
|
136
|
+
for start in range(0, count, lanes):
|
|
137
|
+
size = min(lanes, count - start)
|
|
138
|
+
threads = min(size, 64)
|
|
139
|
+
kernel[(size + threads - 1) // threads, threads, stream](*args, start, size)
|
|
140
|
+
|
|
141
|
+
capacity = limit
|
|
142
|
+
if limit > LOCAL_CANDIDATES:
|
|
143
|
+
launch(1, count_only=True)
|
|
144
|
+
# Negative entries require the CPU oracle, positive entries give the
|
|
145
|
+
# exact occupancy. A high configured limit alone costs no extra VRAM.
|
|
146
|
+
capacity = max(0, int(retry.max().item()))
|
|
147
|
+
launch(_scratch_size(capacity))
|
|
148
|
+
return result, retry
|
|
149
|
+
|
|
150
|
+
def _recover(self, left, right, i, j):
|
|
151
|
+
def row(peaks, index):
|
|
152
|
+
n = peaks.lengths[index]
|
|
153
|
+
return np.column_stack((peaks.mz[index, :n], peaks.intensities[index, :n]))
|
|
154
|
+
|
|
155
|
+
shifts = [self.shift]
|
|
156
|
+
if self.modified:
|
|
157
|
+
delta = left.precursor_mz[i] - right.precursor_mz[j]
|
|
158
|
+
if abs(delta) > self.tolerance:
|
|
159
|
+
shifts.append(delta)
|
|
160
|
+
return exact_score(
|
|
161
|
+
row(left, i), row(right, j), shifts, self.tolerance, self.mz_power, self.intensity_power
|
|
162
|
+
)
|
|
163
|
+
|
|
164
|
+
def _tiles(self, left, right, symmetric, requested, progress_bar):
|
|
165
|
+
if not len(right):
|
|
166
|
+
return
|
|
167
|
+
batch = self.batch_size
|
|
168
|
+
starts = range(0, len(left), batch) if requested is None else sorted(requested)
|
|
169
|
+
for r in tqdm(starts, desc="Scoring reference batches", disable=not progress_bar):
|
|
170
|
+
rows = slice(r, min(r + batch, len(left)))
|
|
171
|
+
rbatch = self._batch(left, rows)
|
|
172
|
+
columns = (
|
|
173
|
+
range(r if symmetric else 0, len(right), batch) if requested is None else sorted(requested[r])
|
|
174
|
+
)
|
|
175
|
+
for c in columns:
|
|
176
|
+
cols = slice(c, min(c + batch, len(right)))
|
|
177
|
+
qbatch = rbatch if right is left and r == c else self._batch(right, cols)
|
|
178
|
+
positions = None if requested is None else np.asarray(requested[r][c], dtype=np.intp)
|
|
179
|
+
diagonal = symmetric and r == c and positions is None
|
|
180
|
+
result, retry = self._tile(rbatch, qbatch, positions, diagonal)
|
|
181
|
+
failed = torch.nonzero(retry).flatten().cpu().numpy()
|
|
182
|
+
if failed.size:
|
|
183
|
+
width = cols.stop - c
|
|
184
|
+
local = failed if positions is None else positions[failed]
|
|
185
|
+
rr, cc = np.divmod(local, width)
|
|
186
|
+
repaired = [self._recover(left, right, r + i, c + j) for i, j in zip(rr, cc)]
|
|
187
|
+
# Preserve exact oracle values for host outputs and sparse
|
|
188
|
+
# predicates even when the device fast path used float32.
|
|
189
|
+
result = result.to(torch.float64)
|
|
190
|
+
values = torch.tensor(repaired, dtype=torch.float64, device=result.device).T
|
|
191
|
+
result[:, failed] = values
|
|
192
|
+
if diagonal:
|
|
193
|
+
result[:, cc * width + rr] = values
|
|
194
|
+
yield rows, cols, positions, result
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
class CudaCosineGreedy(_GreedySimilarity):
|
|
198
|
+
"""matchms greedy cosine on CUDA, with an optional fixed shift of query m/z."""
|
|
199
|
+
|
|
200
|
+
def __init__(
|
|
201
|
+
self,
|
|
202
|
+
tolerance=0.01,
|
|
203
|
+
mz_power=0.0,
|
|
204
|
+
intensity_power=1.0,
|
|
205
|
+
noise_cutoff=0.01,
|
|
206
|
+
remove_precursor=True,
|
|
207
|
+
offset_to_precursor=-1.6,
|
|
208
|
+
batch_size=2048,
|
|
209
|
+
n_max_peaks=None,
|
|
210
|
+
match_limit=2048,
|
|
211
|
+
precision="float64",
|
|
212
|
+
shift=0.0,
|
|
213
|
+
):
|
|
214
|
+
super().__init__(
|
|
215
|
+
tolerance,
|
|
216
|
+
mz_power,
|
|
217
|
+
intensity_power,
|
|
218
|
+
noise_cutoff,
|
|
219
|
+
remove_precursor,
|
|
220
|
+
offset_to_precursor,
|
|
221
|
+
batch_size,
|
|
222
|
+
n_max_peaks,
|
|
223
|
+
match_limit,
|
|
224
|
+
precision,
|
|
225
|
+
)
|
|
226
|
+
self.shift = float(shift)
|
|
227
|
+
|
|
228
|
+
@property
|
|
229
|
+
def is_commutative(self):
|
|
230
|
+
return self.shift == 0
|