diff --git a/README.md b/README.md index fcd30b7..e1ac6a6 100644 --- a/README.md +++ b/README.md @@ -156,6 +156,24 @@ ref_id, query_id, scores = scores_cu.data['sparse_score'] ref_id, query_id, matches = scores_cu.data['sparse_matches'] ``` +### My spectra are already arrays (NumPy, Parquet, HDF5). Do I need matchms `Spectrum` objects? + +No. Pass a `PeakArrays`: padded m/z and intensity arrays plus the number of peaks per spectrum (and precursor m/z for `CudaModifiedCosine`). It skips creating `Spectrum` objects and converting them on every `matrix()` call, which adds up for millions of spectra. With `array_type="torch"`, the scores stay on the GPU as a `(3, R, Q)` tensor (score, matched peaks, overflow), for filtering there before anything is copied to the host. + +```py +from simms import PeakArrays +from simms.similarity import CudaCosineGreedy + +# mz_list, intensity_list: one array per spectrum, each in ascending m/z +references = PeakArrays.from_peak_lists(mz_list, intensity_list, n_max_peaks=1024) +queries = PeakArrays.from_peak_lists(query_mz_list, query_intensity_list, n_max_peaks=1024) + +scores = CudaCosineGreedy().matrix(references, queries, array_type="torch") +best_score, best_reference = scores[0].max(dim=0) # computed on the GPU +``` + +`PeakArrays.from_spectra(spectra)` converts `Spectrum` objects once, for reuse across many `matrix()` calls. + # Citing SimMS diff --git a/simms/__init__.py b/simms/__init__.py index 29fcb27..c092c76 100644 --- a/simms/__init__.py +++ b/simms/__init__.py @@ -1,6 +1,7 @@ import os from contextlib import contextmanager from .__version__ import __version__ +from .peaks import PeakArrays # Patch cuda.pinned and as_cuda_array before https://github.com/numba/numba/pull/9458 gets merged @@ -27,5 +28,6 @@ def fake_event(*args, **kwargs): __email__ = "tornikeonoprishvili@gmail.com" __all__ = [ "__version__", + "PeakArrays", "similarity", ] diff --git a/simms/peaks.py b/simms/peaks.py new file mode 100644 index 0000000..3035888 --- /dev/null +++ b/simms/peaks.py @@ -0,0 +1,137 @@ +"""Spectra as padded peak arrays, an alternative to lists of matchms ``Spectrum`` objects. + +The similarity kernels work on fixed-width arrays of m/z and intensities. ``matrix()`` builds them from +``Spectrum`` objects one spectrum at a time; for millions of spectra that conversion, and creating the +``Spectrum`` objects in the first place, can take longer than the GPU computation. ``PeakArrays`` holds the +arrays directly, so data that is already in arrays (Parquet, HDF5, NumPy) can go straight to the GPU. +""" + +from dataclasses import dataclass +from typing import Optional, Sequence + +import numpy as np + + +@dataclass(frozen=True) +class PeakArrays: + """A batch of spectra as zero-padded arrays. + + Attributes + ---------- + mz : np.ndarray + ``(n_spectra, width)`` m/z values. Each row holds its spectrum's peaks in ascending m/z, then zeros. + intensities : np.ndarray + ``(n_spectra, width)`` intensities, aligned with ``mz``. + lengths : np.ndarray + ``(n_spectra,)`` number of peaks in each row. + precursor_mz : np.ndarray, optional + ``(n_spectra,)`` precursor m/z, needed by ``CudaModifiedCosine``. + + >>> import numpy as np + >>> from simms.peaks import PeakArrays + >>> peaks = PeakArrays.from_peak_lists( + ... mz=[np.array([100.0, 150.0]), np.array([120.0, 130.0, 140.0])], + ... intensities=[np.array([0.5, 1.0]), np.array([1.0, 0.2, 0.3])], + ... ) + >>> peaks.mz.shape, peaks.lengths.tolist() + ((2, 3), [2, 3]) + """ + + mz: np.ndarray + intensities: np.ndarray + lengths: np.ndarray + precursor_mz: Optional[np.ndarray] = None + + def __post_init__(self): + if self.mz.ndim != 2 or self.mz.shape != self.intensities.shape: + raise ValueError("mz and intensities must be 2-D arrays of the same shape.") + if self.lengths.shape != (self.mz.shape[0],): + raise ValueError("lengths must have one entry per spectrum.") + if self.lengths.size and (self.lengths.min() < 0 or self.lengths.max() > self.mz.shape[1]): + raise ValueError("lengths must lie between 0 and the array width.") + if self.precursor_mz is not None and self.precursor_mz.shape != (self.mz.shape[0],): + raise ValueError("precursor_mz must have one entry per spectrum.") + + def __len__(self) -> int: + return self.mz.shape[0] + + def __getitem__(self, index: slice) -> "PeakArrays": + if not isinstance(index, slice): + raise TypeError("PeakArrays supports slicing only, e.g. peaks[0:2048].") + return PeakArrays( + mz=self.mz[index], + intensities=self.intensities[index], + lengths=self.lengths[index], + precursor_mz=None if self.precursor_mz is None else self.precursor_mz[index], + ) + + @property + def width(self) -> int: + """The number of peak slots per spectrum.""" + return self.mz.shape[1] + + def to_width(self, width: int, dtype=np.float32) -> "tuple[np.ndarray, np.ndarray]": + """Stacked ``(2, n_spectra, width)`` m/z and intensities, and lengths capped at ``width``. + + Rows longer than ``width`` keep their first ``width`` peaks, as ``matrix()`` does for ``Spectrum`` + objects with more than ``n_max_peaks`` peaks. + """ + stacked = np.zeros((2, len(self), width), dtype=dtype) + keep = min(width, self.width) + stacked[0, :, :keep] = self.mz[:, :keep] + stacked[1, :, :keep] = self.intensities[:, :keep] + return stacked, np.minimum(self.lengths, width).astype(np.int32) + + @classmethod + def from_peak_lists( + cls, + mz: Sequence[np.ndarray], + intensities: Sequence[np.ndarray], + precursor_mz: Optional[Sequence[float]] = None, + n_max_peaks: Optional[int] = None, + dtype=np.float64, + ) -> "PeakArrays": + """Pad per-spectrum peak arrays (each in ascending m/z) into a ``PeakArrays``. + + With ``n_max_peaks``, each spectrum keeps its first ``n_max_peaks`` peaks. + + ``dtype`` is the storage type of m/z and intensities. The float64 default keeps the values matchms + ``Spectrum`` objects hold, so both similarity classes give exactly the scores they give for ``Spectrum`` + input. float32 halves the memory and is exact for ``CudaCosineGreedy``, which computes in float32, but + ``CudaModifiedCosine`` computes in float64 by default, and rounded m/z can flip matches that lie near the + tolerance. Precursor m/z is always stored as float64. + """ + if len(mz) != len(intensities): + raise ValueError("mz and intensities must hold the same number of spectra.") + lengths = np.fromiter((len(m) for m in mz), dtype=np.int64, count=len(mz)) + if n_max_peaks is not None: + lengths = np.minimum(lengths, n_max_peaks) + width = int(lengths.max(initial=0)) + mz_out = np.zeros((len(mz), width), dtype=dtype) + int_out = np.zeros((len(mz), width), dtype=dtype) + for i, (m, x) in enumerate(zip(mz, intensities)): + n = lengths[i] + mz_out[i, :n] = m[:n] + int_out[i, :n] = x[:n] + return cls( + mz=mz_out, + intensities=int_out, + lengths=lengths.astype(np.int32), + precursor_mz=None if precursor_mz is None else np.asarray(precursor_mz, dtype=np.float64), + ) + + @classmethod + def from_spectra(cls, spectra, n_max_peaks: Optional[int] = None, with_precursor_mz: bool = False, dtype=np.float64) -> "PeakArrays": + """Convert matchms ``Spectrum`` objects once, so that repeated ``matrix()`` calls skip the conversion.""" + precursor = None + if with_precursor_mz: + from .similarity.CudaModifiedCosine import get_valid_precursor_mz + + precursor = [get_valid_precursor_mz(s) for s in spectra] + return cls.from_peak_lists( + mz=[s.peaks.mz for s in spectra], + intensities=[s.peaks.intensities for s in spectra], + precursor_mz=precursor, + n_max_peaks=n_max_peaks, + dtype=dtype, + ) diff --git a/simms/similarity/CudaCosineGreedy.py b/simms/similarity/CudaCosineGreedy.py index 959aaca..928bb7e 100644 --- a/simms/similarity/CudaCosineGreedy.py +++ b/simms/similarity/CudaCosineGreedy.py @@ -8,6 +8,7 @@ from numba import cuda from sparsestack import StackedSparseArray from tqdm import tqdm +from ..peaks import PeakArrays from ..utils import argbatch, get_device from .spectrum_similarity_functions import cosine_kernel @@ -110,21 +111,25 @@ def __init__( def _spectra_peaks_to_tensor( self, - spectra: list, + spectra: Union[list, PeakArrays], ) -> tuple[np.ndarray, np.ndarray]: """ - Convert list of Spectrum objects into numpy arrays. + Convert list of Spectrum objects, or a PeakArrays, into numpy arrays. Parameters: ----------- - spectra : list of Spectrum - List of Spectrum objects. + spectra : list of Spectrum, or PeakArrays + List of Spectrum objects, or spectra as padded arrays. Returns: -------- tuple of np.ndarray Tuple containing two numpy arrays: one for m/z values and one for intensities. """ + if isinstance(spectra, PeakArrays): + width = self.n_max_peaks if self.n_max_peaks is not None else int(spectra.lengths.max(initial=1)) + return spectra.to_width(width, dtype=np.float32) + # Determine dynamic shape dynamic_shape = max(len(s.peaks) for s in spectra) if self.n_max_peaks is None: @@ -135,7 +140,7 @@ def _spectra_peaks_to_tensor( # Initialize arrays dtype = np.float32 mz = np.zeros((len(spectra), n_max_peaks), dtype=dtype) - int = np.zeros((len(spectra), n_max_peaks), dtype=dtype) + intensities = np.zeros((len(spectra), n_max_peaks), dtype=dtype) spectra_lens = np.zeros(len(spectra), dtype=np.int32) # Populate arrays @@ -143,11 +148,11 @@ def _spectra_peaks_to_tensor( if s is not None: spec_len = min(len(s.peaks), n_max_peaks) mz[i, :spec_len] = s._peaks.mz[:spec_len] - int[i, :spec_len] = s._peaks.intensities[:spec_len] + intensities[i, :spec_len] = s._peaks.intensities[:spec_len] spectra_lens[i] = spec_len # Stack arrays and return - stacked_spectra = np.stack([mz, int], axis=0) + stacked_spectra = np.stack([mz, intensities], axis=0) return stacked_spectra, spectra_lens def _get_batches(self, references, queries): @@ -201,31 +206,32 @@ def pair(self, reference: Spectrum, query: Spectrum) -> float: def matrix( self, - references: List[Spectrum], - queries: List[Spectrum], - array_type: Literal["numpy", "sparse"] = "numpy", + references: Union[List[Spectrum], PeakArrays], + queries: Union[List[Spectrum], PeakArrays], + array_type: Literal["numpy", "sparse", "torch"] = "numpy", is_symmetric: bool = False, - ) -> Union[np.ndarray, StackedSparseArray]: + ) -> Union[np.ndarray, StackedSparseArray, torch.Tensor]: """ Calculate a matrix of similarity scores between reference and query spectra. Parameters: ----------- - references : List[Spectrum] - List of reference Spectrum objects. - queries : List[Spectrum] - List of query Spectrum objects. - array_type : Literal["numpy", "sparse"], optional - Specify the output array type, by default "numpy". + references : List[Spectrum] or PeakArrays + Reference spectra: a list of Spectrum objects, or a `simms.peaks.PeakArrays`. + queries : List[Spectrum] or PeakArrays + Query spectra: a list of Spectrum objects, or a `simms.peaks.PeakArrays`. + array_type : Literal["numpy", "sparse", "torch"], optional + Specify the output array type, by default "numpy". "torch" returns the (3, R, Q) float32 tensor of + scores, matched peaks and overflow flags, left on the device, without copying it to the host. is_symmetric : bool, optional Unused. This unused argument is left is for compatibility reasons. Returns: -------- - Score : Union[np.ndarray, StackedSparseArray] + Score : Union[np.ndarray, StackedSparseArray, torch.Tensor] Matrix of similarity scores between reference and query spectra. Type of Score depends on on `array_type` argument, with "sparse" array_type - returning a `sparsestack.StackedSparseArray` + returning a `sparsestack.StackedSparseArray` and "torch" a `torch.Tensor` """ # Warn if is_symmetric is passed if is_symmetric: @@ -235,14 +241,15 @@ def matrix( assert array_type in [ "numpy", "sparse", - ], "Invalid array_type. Use 'numpy' or 'sparse'." + "torch", + ], "Invalid array_type. Use 'numpy', 'sparse' or 'torch'." # Initialize batched inputs batched_inputs = self._get_batches(references=references, queries=queries) R, Q = len(references), len(queries) # Initialize result variable based on array_type - if array_type == "numpy": + if array_type in ("numpy", "torch"): result = torch.empty(3, R, Q, dtype=torch.float32, device=self.device) elif array_type == "sparse": result = [] @@ -321,7 +328,7 @@ def matrix( out = out[:, : len(rlen), : len(qlen)] # Populate result based on array_type - if array_type == "numpy": + if array_type in ("numpy", "torch"): result[:, rstart:rend, qstart:qend] = out elif array_type == "sparse": @@ -342,6 +349,8 @@ def matrix( ) # Return result based on array_type + if array_type == "torch": + return result if array_type == "numpy": return np.rec.fromarrays( result.cpu().numpy(), diff --git a/simms/similarity/CudaModifiedCosine.py b/simms/similarity/CudaModifiedCosine.py index 9a6e916..5e193d4 100644 --- a/simms/similarity/CudaModifiedCosine.py +++ b/simms/similarity/CudaModifiedCosine.py @@ -10,6 +10,7 @@ from numba import cuda from sparsestack import StackedSparseArray from tqdm import tqdm +from ..peaks import PeakArrays from ..utils import argbatch, get_device from .spectrum_similarity_functions import cosine_kernel @@ -144,21 +145,28 @@ def __init__( def _spectra_peaks_to_tensor( self, - spectra: list, + spectra: Union[list, PeakArrays], ) -> tuple[np.ndarray, np.ndarray]: """ - Convert list of Spectrum objects into numpy arrays. + Convert list of Spectrum objects, or a PeakArrays, into numpy arrays. Parameters: ----------- - spectra : list of Spectrum - List of Spectrum objects. + spectra : list of Spectrum, or PeakArrays + List of Spectrum objects, or spectra as padded arrays with `precursor_mz`. Returns: -------- tuple of np.ndarray Tuple containing two numpy arrays: one for m/z values and one for intensities. """ + if isinstance(spectra, PeakArrays): + if spectra.precursor_mz is None: + raise ValueError("CudaModifiedCosine needs PeakArrays with precursor_mz.") + width = self.n_max_peaks if self.n_max_peaks is not None else int(spectra.lengths.max(initial=1)) + stacked, lengths = spectra.to_width(width, dtype=self.spectra_dtype) + return stacked, lengths, spectra.precursor_mz.astype(self.spectra_dtype) + # Determine dynamic shape dynamic_shape = max(len(s.peaks) for s in spectra) if self.n_max_peaks is None: @@ -169,7 +177,7 @@ def _spectra_peaks_to_tensor( # Initialize arrays dtype = self.spectra_dtype mz = np.zeros((len(spectra), n_max_peaks), dtype=dtype) - int_ = np.zeros((len(spectra), n_max_peaks), dtype=dtype) + intensities = np.zeros((len(spectra), n_max_peaks), dtype=dtype) spectra_lens = np.zeros(len(spectra), dtype=np.int32) spectra_precursor_mzs = np.zeros(len(spectra), dtype=dtype) @@ -178,11 +186,11 @@ def _spectra_peaks_to_tensor( if s is not None: spec_len = min(len(s.peaks), n_max_peaks) mz[i, :spec_len] = s._peaks.mz[:spec_len] - int_[i, :spec_len] = s._peaks.intensities[:spec_len] + intensities[i, :spec_len] = s._peaks.intensities[:spec_len] spectra_lens[i] = spec_len spectra_precursor_mzs[i] = get_valid_precursor_mz(s) # Stack arrays and return - stacked_spectra = np.stack([mz, int_], axis=0) + stacked_spectra = np.stack([mz, intensities], axis=0) return stacked_spectra, spectra_lens, spectra_precursor_mzs def _get_batches(self, references, queries): @@ -236,31 +244,32 @@ def pair(self, reference: Spectrum, query: Spectrum) -> float: def matrix( self, - references: List[Spectrum], - queries: List[Spectrum], - array_type: Literal["numpy", "sparse"] = "numpy", + references: Union[List[Spectrum], PeakArrays], + queries: Union[List[Spectrum], PeakArrays], + array_type: Literal["numpy", "sparse", "torch"] = "numpy", is_symmetric: bool = False, - ) -> Union[np.ndarray, StackedSparseArray]: + ) -> Union[np.ndarray, StackedSparseArray, torch.Tensor]: """ Calculate a matrix of similarity scores between reference and query spectra. Parameters: ----------- - references : List[Spectrum] - List of reference Spectrum objects. - queries : List[Spectrum] - List of query Spectrum objects. - array_type : Literal["numpy", "sparse"], optional - Specify the output array type, by default "numpy". + references : List[Spectrum] or PeakArrays + Reference spectra: a list of Spectrum objects, or a `simms.peaks.PeakArrays`. + queries : List[Spectrum] or PeakArrays + Query spectra: a list of Spectrum objects, or a `simms.peaks.PeakArrays`. + array_type : Literal["numpy", "sparse", "torch"], optional + Specify the output array type, by default "numpy". "torch" returns the (3, R, Q) float32 tensor of + scores, matched peaks and overflow flags, left on the device, without copying it to the host. is_symmetric : bool, optional Unused. This unused argument is left is for compatibility reasons. Returns: -------- - Score : Union[np.ndarray, StackedSparseArray] + Score : Union[np.ndarray, StackedSparseArray, torch.Tensor] Matrix of similarity scores between reference and query spectra. Type of Score depends on on `array_type` argument, with "sparse" array_type - returning a `sparsestack.StackedSparseArray` + returning a `sparsestack.StackedSparseArray` and "torch" a `torch.Tensor` """ # Warn if is_symmetric is passed if is_symmetric: @@ -270,14 +279,15 @@ def matrix( assert array_type in [ "numpy", "sparse", - ], f"Invalid array_type '{array_type}'. Use 'numpy' or 'sparse'." + "torch", + ], f"Invalid array_type '{array_type}'. Use 'numpy', 'sparse' or 'torch'." # Initialize batched inputs batched_inputs = self._get_batches(references=references, queries=queries) R, Q = len(references), len(queries) # Initialize result variable based on array_type - if array_type == "numpy": + if array_type in ("numpy", "torch"): result = torch.empty(3, R, Q, dtype=torch.float32, device=self.device) elif array_type == "sparse": result = [] @@ -365,7 +375,7 @@ def matrix( out = torch.as_tensor(out) # Populate result based on array_type - if array_type == "numpy": + if array_type in ("numpy", "torch"): result[:, rstart:rend, qstart:qend] = out[ :, : len(rlen), : len(qlen) ] @@ -386,6 +396,8 @@ def matrix( ) # Return result based on array_type + if array_type == "torch": + return result if array_type == "numpy": return np.rec.fromarrays( result.cpu().numpy(), diff --git a/tests/similarity/test_peak_arrays.py b/tests/similarity/test_peak_arrays.py new file mode 100644 index 0000000..f73f763 --- /dev/null +++ b/tests/similarity/test_peak_arrays.py @@ -0,0 +1,132 @@ +import numpy as np +import pytest +import torch +from matchms import Spectrum +from simms.peaks import PeakArrays +from simms.similarity import CudaCosineGreedy, CudaModifiedCosine + + +def random_spectra(n, rng, max_peaks=12): + spectra = [] + for _ in range(n): + k = int(rng.integers(1, max_peaks + 1)) + mz = np.sort(rng.choice(np.arange(100.0, 160.0, 0.5), size=k, replace=False)) + spectra.append( + Spectrum( + mz=mz, + intensities=rng.uniform(0.1, 1.0, size=k), + metadata={"precursor_mz": float(rng.uniform(300.0, 310.0))}, + ) + ) + return spectra + + +def test_from_peak_lists_pads_and_truncates(): + peaks = PeakArrays.from_peak_lists( + mz=[np.array([100.0, 150.0, 200.0]), np.array([120.0])], + intensities=[np.array([1.0, 0.5, 0.2]), np.array([0.7])], + precursor_mz=[500.0, 600.0], + n_max_peaks=2, + ) + assert peaks.mz.tolist() == [[100.0, 150.0], [120.0, 0.0]] + assert peaks.intensities[1].tolist() == pytest.approx([0.7, 0.0]) + assert peaks.lengths.tolist() == [2, 1] + assert peaks.precursor_mz.tolist() == [500.0, 600.0] + assert len(peaks[1:2]) == 1 + assert peaks[1:2].precursor_mz.tolist() == [600.0] + + +def test_from_spectra_keeps_peaks(): + spectra = random_spectra(5, np.random.default_rng(0)) + peaks = PeakArrays.from_spectra(spectra, with_precursor_mz=True) + for i, s in enumerate(spectra): + n = len(s.peaks) + assert peaks.lengths[i] == n + np.testing.assert_allclose(peaks.mz[i, :n], s.peaks.mz, rtol=1e-6) + np.testing.assert_allclose(peaks.precursor_mz[i], s.get("precursor_mz"), rtol=1e-6) + + +def test_rejects_inconsistent_arrays(): + with pytest.raises(ValueError): + PeakArrays(mz=np.zeros((2, 3)), intensities=np.zeros((2, 4)), lengths=np.zeros(2, int)) + with pytest.raises(ValueError): + PeakArrays(mz=np.zeros((2, 3)), intensities=np.zeros((2, 3)), lengths=np.array([1, 5])) + + +@pytest.mark.parametrize("n_max_peaks", [16, 6]) +def test_cosine_greedy_peak_arrays_match_spectra(n_max_peaks): + rng = np.random.default_rng(1) + references, queries = random_spectra(11, rng), random_spectra(7, rng) + similarity = CudaCosineGreedy(tolerance=0.2, batch_size=8, n_max_peaks=n_max_peaks) + expected = similarity.matrix(references, queries) + got = similarity.matrix(PeakArrays.from_spectra(references), PeakArrays.from_spectra(queries)) + np.testing.assert_allclose(got["score"], expected["score"], rtol=1e-6) + np.testing.assert_array_equal(got["matches"], expected["matches"]) + + +def test_modified_cosine_peak_arrays_match_spectra(): + rng = np.random.default_rng(2) + references, queries = random_spectra(9, rng), random_spectra(6, rng) + similarity = CudaModifiedCosine(tolerance=0.2, batch_size=8, n_max_peaks=16) + expected = similarity.matrix(references, queries) + got = similarity.matrix( + PeakArrays.from_spectra(references, with_precursor_mz=True), + PeakArrays.from_spectra(queries, with_precursor_mz=True), + ) + np.testing.assert_allclose(got["score"], expected["score"], rtol=1e-6) + np.testing.assert_array_equal(got["matches"], expected["matches"]) + + +def test_modified_cosine_default_storage_keeps_edge_matches(): + # A query peak just inside the tolerance in float64 that float32 rounding pushes outside it. + tolerance = 0.1 + ref_mz, query_mz = next( + (r, r + tolerance - eps) + for r in 1000.0 + np.arange(200) * 1.3e-5 + for eps in np.linspace(1e-7, 5e-5, 50) + if float(np.float32(r + tolerance - eps)) - float(np.float32(r)) > tolerance + ) + reference = Spectrum(mz=np.array([ref_mz, 1100.0]), intensities=np.array([1.0, 0.5]), metadata={"precursor_mz": 1500.0}) + query = Spectrum(mz=np.array([query_mz, 1100.0]), intensities=np.array([1.0, 0.5]), metadata={"precursor_mz": 1500.0}) + similarity = CudaModifiedCosine(tolerance=tolerance, batch_size=4, n_max_peaks=4) + expected = similarity.matrix([reference], [query]) + assert expected["matches"][0, 0] == 2 + got = similarity.matrix( + PeakArrays.from_spectra([reference], with_precursor_mz=True), + PeakArrays.from_spectra([query], with_precursor_mz=True), + ) + np.testing.assert_array_equal(got["matches"], expected["matches"]) + np.testing.assert_allclose(got["score"], expected["score"], rtol=1e-12) + rounded = similarity.matrix( + PeakArrays.from_spectra([reference], with_precursor_mz=True, dtype=np.float32), + PeakArrays.from_spectra([query], with_precursor_mz=True, dtype=np.float32), + ) + assert rounded["matches"][0, 0] == 1 + + +def test_from_peak_lists_stores_float64_by_default(): + peaks = PeakArrays.from_peak_lists([np.array([100.0])], [np.array([1.0])], precursor_mz=[500.123456789]) + assert peaks.mz.dtype == np.float64 and peaks.intensities.dtype == np.float64 + assert peaks.precursor_mz.dtype == np.float64 + small = PeakArrays.from_peak_lists([np.array([100.0])], [np.array([1.0])], precursor_mz=[500.123456789], dtype=np.float32) + assert small.mz.dtype == np.float32 and small.precursor_mz.dtype == np.float64 + + +def test_modified_cosine_needs_precursor_mz(): + spectra = random_spectra(3, np.random.default_rng(3)) + similarity = CudaModifiedCosine(batch_size=8, n_max_peaks=16) + with pytest.raises(ValueError, match="precursor_mz"): + similarity.matrix(PeakArrays.from_spectra(spectra), PeakArrays.from_spectra(spectra)) + + +@pytest.mark.parametrize("similarity_class", [CudaCosineGreedy, CudaModifiedCosine]) +def test_torch_output_matches_numpy(similarity_class): + rng = np.random.default_rng(4) + references, queries = random_spectra(10, rng), random_spectra(5, rng) + similarity = similarity_class(tolerance=0.2, batch_size=8, n_max_peaks=16) + expected = similarity.matrix(references, queries) + got = similarity.matrix(references, queries, array_type="torch") + assert isinstance(got, torch.Tensor) + assert tuple(got.shape) == (3, 10, 5) + np.testing.assert_allclose(got[0].cpu().numpy(), expected["score"], rtol=1e-6) + np.testing.assert_array_equal(got[1].cpu().numpy(), expected["matches"])