Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
2 changes: 2 additions & 0 deletions simms/__init__.py
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -27,5 +28,6 @@ def fake_event(*args, **kwargs):
__email__ = "tornikeonoprishvili@gmail.com"
__all__ = [
"__version__",
"PeakArrays",
"similarity",
]
137 changes: 137 additions & 0 deletions simms/peaks.py
Original file line number Diff line number Diff line change
@@ -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,
)
53 changes: 31 additions & 22 deletions simms/similarity/CudaCosineGreedy.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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:
Expand All @@ -135,19 +140,19 @@ 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
for i, s in enumerate(spectra):
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):
Expand Down Expand Up @@ -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:
Expand All @@ -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 = []
Expand Down Expand Up @@ -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":
Expand All @@ -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(),
Expand Down
Loading
Loading