diff --git a/.github/scripts/smoke_wheel.py b/.github/scripts/smoke_wheel.py new file mode 100644 index 0000000..cfb5bfa --- /dev/null +++ b/.github/scripts/smoke_wheel.py @@ -0,0 +1,62 @@ +"""Run outside the checkout with a wheel installed into a fresh environment.""" + +import sys +from importlib.metadata import distribution +from pathlib import Path + +import numpy as np +from matchms import Spectrum, similarity +from numba import cuda +from rdkit.Chem.rdFingerprintGenerator import GetMorganGenerator + +import simms +from simms import similarity as gpu + + +def main(version): + dist = distribution("simms-gpu") + assert Path(simms.__file__).resolve() == dist.locate_file("simms/__init__.py").resolve() + assert Path(simms.__file__).resolve().is_relative_to(Path(sys.prefix).resolve()) + assert simms.__version__ == dist.version == version + spectrum = Spectrum( + np.array([50.0, 75.0]), + np.array([2.0, 8.0]), + {"precursor_mz": 100.0, "smiles": "CCO", "inchikey": "LFQSCWFLJHTTHZ-UHFFFAOYSA-N"}, + metadata_harmonization=False, + ) + for name in ( + "CosineGreedy", + "ModifiedCosineGreedy", + "NeutralLossesCosine", + "EntropyGreedy", + "CosineLinear", + "ModifiedCosineLinear", + "BinnedEmbeddingSimilarity", + "FingerprintSimilarity", + ): + kwargs = ( + {"fingerprint_generator": GetMorganGenerator(radius=2, fpSize=128)} + if name == "FingerprintSimilarity" + else {} + ) + expected = getattr(similarity, name)(**kwargs).matrix([spectrum], progress_bar=False) + actual = getattr(gpu, "Cuda" + name)(**kwargs).matrix( + [spectrum], array_type="torch", progress_bar=False + ) + assert actual.is_cuda == (not cuda.config.ENABLE_CUDASIM) + planes = actual.cpu().numpy().reshape(-1) + np.testing.assert_allclose(planes[0], expected.to_array("score").item(), atol=1e-12, rtol=0) + assert planes[0] > 0 + if "matches" in expected.score_fields: + assert planes[1] == expected.to_array("matches").item() == 2 + print(f"Cuda{name}: {planes.tolist()} ({actual.device})") + network = gpu.CudaTransitiveAlignment(min_direct_matches=2).sparse_matrix([spectrum, spectrum]) + matches = network.to_coo("matches") + assert sorted(zip(matches.row, matches.col, matches.data)) == [(0, 1, 2), (1, 0, 2)] + np.testing.assert_allclose(network.to_coo("score").data, [1.0, 1.0], atol=1e-12, rtol=0) + print("CudaTransitiveAlignment: one symmetric direct edge") + print(f"simms-gpu {version} from {simms.__file__}") + + +if __name__ == "__main__": + main(sys.argv[1]) diff --git a/.github/workflows/docker-image.yml b/.github/workflows/docker-image.yml deleted file mode 100644 index f0bdc34..0000000 --- a/.github/workflows/docker-image.yml +++ /dev/null @@ -1,16 +0,0 @@ -name: Docker Image CI - -on: - release: - types: [published] - -jobs: - - build: - - runs-on: ubuntu-latest - - steps: - - uses: actions/checkout@v3 - - name: Build the Docker image - run: docker build . --file Dockerfile --tag cosine-similarity:$(date +%s) diff --git a/.github/workflows/python-package.yml b/.github/workflows/python-package.yml index 12fe252..3197fb8 100644 --- a/.github/workflows/python-package.yml +++ b/.github/workflows/python-package.yml @@ -1,40 +1,35 @@ -# This workflow will install Python dependencies, run tests and lint with a variety of Python versions -# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python - name: Python package on: push: - branches: [ "*" ] + branches: ["**"] pull_request: - branches: [ "*" ] -jobs: - build: +permissions: + contents: read +jobs: + test: runs-on: ubuntu-latest strategy: fail-fast: false matrix: - python-version: ["3.9"] #, "3.10", "3.11"] - + python-version: ["3.11", "3.12", "3.13", "3.14"] steps: - - uses: actions/checkout@v3 - - name: Set up Python ${{ matrix.python-version }} - uses: actions/setup-python@v3 - with: - python-version: ${{ matrix.python-version }} - - name: Install dependencies - run: | - python -m pip install --upgrade pip - python -m pip install flake8 pytest - pip install -e . - - name: Lint with flake8 - run: | - # stop the build if there are Python syntax errors or undefined names - flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics - # exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide - flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics - - name: Test with pytest - run: | - NUMBA_CUDA_LOW_OCCUPANCY_WARNINGS=0 NUMBA_ENABLE_CUDASIM=1 pytest -m github_ci + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: ${{ matrix.python-version }} + - name: Install package and test dependencies + run: | + python -m pip install --upgrade pip + python -m pip install torch --index-url https://download.pytorch.org/whl/cpu + extras="" + if [ "${{ matrix.python-version }}" != "3.14" ]; then + extras="chemap" + fi + python -m pip install -e . flake8 pytest nvidia-cuda-runtime $extras + - name: Lint + run: flake8 simms tests --count --select=E9,F63,F7,F82 --show-source --statistics + - name: Test with CUDA simulator + run: NUMBA_CUDA_LOW_OCCUPANCY_WARNINGS=0 NUMBA_ENABLE_CUDASIM=1 pytest -m github_ci diff --git a/.github/workflows/python-publish.yml b/.github/workflows/python-publish.yml index bdaab28..5e0bc0d 100644 --- a/.github/workflows/python-publish.yml +++ b/.github/workflows/python-publish.yml @@ -1,12 +1,4 @@ -# This workflow will upload a Python Package using Twine when a release is created -# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python#publishing-to-package-registries - -# This workflow uses actions that are not certified by GitHub. -# They are provided by a third-party and are governed by -# separate terms of service, privacy policy, and support -# documentation. - -name: Upload Python Package +name: Publish simms-gpu on: release: @@ -16,24 +8,57 @@ permissions: contents: read jobs: - deploy: - + build: + if: startsWith(github.event.release.tag_name, 'v') runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.12" + - name: Verify release version + env: + RELEASE_TAG: ${{ github.event.release.tag_name }} + run: | + python - <<'PY' + import os, runpy, tomllib + from pathlib import Path + project = tomllib.loads(Path("pyproject.toml").read_text())["project"] + version = runpy.run_path("simms/__version__.py")["__version__"] + assert project["name"] == "simms-gpu" + assert project["version"] == version and os.environ["RELEASE_TAG"] == f"v{version}" + PY + - name: Build and check sdist and wheel + run: | + python -m pip install build twine + python -m build + twine check --strict dist/* + - name: Smoke test installed wheel + env: + RELEASE_TAG: ${{ github.event.release.tag_name }} + NUMBA_CUDA_LOW_OCCUPANCY_WARNINGS: "0" + NUMBA_ENABLE_CUDASIM: "1" + run: | + python -m venv "$RUNNER_TEMP/smoke" + py="$RUNNER_TEMP/smoke/bin/python" + "$py" -m pip install torch --index-url https://download.pytorch.org/whl/cpu + "$py" -m pip install dist/*.whl chemap nvidia-cuda-runtime + cd "$RUNNER_TEMP" + "$py" -I "$GITHUB_WORKSPACE/.github/scripts/smoke_wheel.py" "${RELEASE_TAG#v}" + - uses: actions/upload-artifact@v4 + with: + name: distributions + path: dist/ + publish: + needs: build + runs-on: ubuntu-latest + environment: pypi + permissions: + id-token: write steps: - - uses: actions/checkout@v3 - - name: Set up Python - uses: actions/setup-python@v3 - with: - python-version: '3.x' - - name: Install dependencies - run: | - python -m pip install --upgrade pip - pip install build - - name: Build package - run: python -m build - - name: Publish package - uses: pypa/gh-action-pypi-publish@27b31702a0e7fc50959f5ad993c78deac1bdfc29 - with: - user: __token__ - password: ${{ secrets.PYPI_API_TOKEN }} + - uses: actions/download-artifact@v4 + with: + name: distributions + path: dist/ + - uses: pypa/gh-action-pypi-publish@release/v1 diff --git a/.gitignore b/.gitignore index 57e170d..adc3c63 100644 --- a/.gitignore +++ b/.gitignore @@ -121,7 +121,7 @@ celerybeat.pid # Environments .env -.venv +.venv/ env/ venv/ ENV/ diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..5dff757 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,11 @@ +# Changelog + +## v1.0.0 + +- Install the `simms-gpu` distribution and keep using `import simms`. The release targets Python 3.11 through 3.14 and matchms 1.0. CUDA 12 and 13 extras install the corresponding numba-cuda toolchain. The `fingerprints` extra adds chemap. +- Scorers now return matchms `Scores` from `matrix` and `calculate_scores`. Use the `score` and `matches` fields where available. Sparse scoring filters nonzero pairs and inclusive `min_score` and `min_matches` thresholds on device. Optional Python predicates receive the surviving scores. Spectral scorers accept `SpectraCollection` and `PeakArrays`, with optional device-resident Torch results. +- Added `CudaNeutralLossesCosine`, `CudaEntropyGreedy`, `CudaCosineLinear`, `CudaModifiedCosineLinear` and `CudaBinnedEmbeddingSimilarity`. Updated `CudaCosineGreedy` and `CudaModifiedCosineGreedy` to match the 1.0 greedy algorithms. `CudaModifiedCosine` remains an alias. `CudaFingerprintSimilarity` now accepts matchms fingerprint containers and chemap generators. +- Added `CudaTransitiveAlignment` for molecular networks built from direct modified-cosine edges. It returns transitive edges, paths and optional aligned peak pairs, and accepts precomputed direct scores. +- Fixed greedy score and match-count errors on crowded spectra. Pairs that exceed a GPU peak or candidate limit are rescored with all peaks before filtering. The reported 577-peak self-comparison now returns 1.0 and 577 matches. [Issue #6](https://github.com/PangeAI/SimMS/issues/6) +- Fixed spectrum-array handling. One-dimensional object arrays use the public peak API and invalid numeric arrays get an error identifying the input side. Numeric peak data can be passed as `PeakArrays`. [Issue #9](https://github.com/PangeAI/SimMS/issues/9) +- Thanks to @BioGeek for the Python and CUDA packaging work and for the padded peak-array and device-tensor proposals that inspired this release. [PR #10](https://github.com/PangeAI/SimMS/pull/10), [PR #11](https://github.com/PangeAI/SimMS/pull/11) diff --git a/README.md b/README.md index fcd30b7..b148587 100644 --- a/README.md +++ b/README.md @@ -1,163 +1,178 @@ - # SimMS - - - - - - - - - -
- Hugging Face Spaces - - - Static Badge - - - - Static Badge - -
- -Calculate the similarity between a large number of mass spectra using a GPU. SimMS aims to provide very fast replacements for commonly used similarity functions in [matchms](https://github.com/matchms/matchms). - -
- - ![img](./assets/perf_speedup.svg) - -
- -# How SimMS works, in a nutshell - -![alt text](assets/visual_guide.png) - -Comparing large sets of mass spectra can be done in parallel since scores can be calculated independently of each other. -By leveraging a large number of threads in a GPU, we created a GPU program (kernel) that calculates a 4096x4096 - similarity matrix in a fraction of a second. -By iteratively calculating similarities for batches of spectra, SimMS can quickly process datasets much larger than the GPU's memory. -For details, visit the [preprint](https://www.biorxiv.org/content/biorxiv/early/2024/07/25/2024.07.24.605006.full.pdf). - -# Quickstart - -## Hardware - -Any GPU [supported](https://numba.pydata.org/numba-doc/dev/cuda/overview.html#requirements) by Numba can be used. We tested a number of GPUs: - -- GTX 1050 Ti -- RTX 2070 -- T4 GPU (free on [Google Colab](https://colab.research.google.com/)) -- RTX 4090 (on vast.ai) -- A100 80GB (on vast.ai) -- H100SXM 80GB (on vast.ai) - -Performance (comparisons/s) is proportional to the peak GPU bandwidth (GB/s). - -The `pytorch/pytorch:2.2.1-cuda12.1-cudnn8-devel` docker [image](https://hub.docker.com/layers/pytorch/pytorch/2.2.1-cuda12.1-cudnn8-devel/images/sha256-42204bca460bb77cbd524577618e1723ad474e5d77cc51f94037fffbc2c88c6f?context=explore) was used for development and testing. - -## Install +SimMS compares tandem mass spectra on an NVIDIA GPU using the scoring algorithms in matchms 1.0.0. A score matrix has one row per reference and one column per query. Peak-matching cosine methods also return the number of assigned peaks. + +## Installation + +The PyPI distribution is `simms-gpu`. Import it in Python as `simms`. Use Python 3.11 through 3.14, an NVIDIA driver compatible with your CUDA runtime and a CUDA-enabled build of PyTorch for that runtime. Choose the matching wheel with the [PyTorch installation selector](https://pytorch.org/get-started/locally/). + ```bash -pip install git+https://github.com/PangeAI/simms +# CUDA 12, in an environment with a matching CUDA 12 PyTorch build +pip install "simms-gpu[cu12]" + +# CUDA 13 +pip install "simms-gpu[cu13]" + +# Include chemap for generating molecular fingerprints +pip install "simms-gpu[cu13,fingerprints]" ``` -## Use with MatchMS +For CUDA 12 fingerprints, use `simms-gpu[cu12,fingerprints]`. The CUDA extras supply the numba-cuda compiler and runtime dependencies. Check PyTorch with `python -c "import torch; print(torch.version.cuda, torch.cuda.is_available())"` before running on the GPU. + +## Quickstart -```py -from matchms import calculate_scores +This example loads the GNPS pesticide library and ranks references for the first query. Both collections use the same m/z grid. One-shot MGF iterators can also be passed directly to `calculate_scores`, `matrix`, `sparse_matrix`, or `PeakArrays.from_spectra`. With `CosineGreedy` defaults, each spectrum needs a positive finite precursor m/z for precursor removal. + +```python +import numpy as np +from matchms import Scores, SpectraCollection, calculate_scores from matchms.importing import load_from_mgf +from simms.similarity import CudaCosineGreedy from simms.utils import download -from simms.similarity import CudaCosineGreedy, \ - CudaModifiedCosine, \ - CudaFingerprintSimilarity -sample_file = download('pesticides.mgf') -references = list(load_from_mgf(sample_file)) -queries = list(load_from_mgf(sample_file)) +spectra = list(load_from_mgf(download("pesticides.mgf"))) +refs = SpectraCollection(spectra[:40]) +queries = SpectraCollection(spectra[40:]) +sim = CudaCosineGreedy() +scores = calculate_scores(spectra_1=refs, spectra_2=queries, similarity_function=sim) +assert isinstance(scores, Scores) + +query_scores = scores.to_array("score")[:, 0] +matches = scores.to_array("matches")[:, 0] +for i in np.argsort(-query_scores, kind="stable")[:5]: + print(i, query_scores[i], matches[i]) +``` -similarity_function = CudaCosineGreedy() +For an all-against-all comparison use `sim.matrix(refs)`. To reuse padded peak arrays and keep the output on the GPU, use the same scorer directly. -scores = calculate_scores( - references=references, - queries=queries, - similarity_function=similarity_function, -) +```python +from simms import PeakArrays -scores.scores_by_query(queries[42], 'CudaCosineGreedy_score', sort=True) +left = PeakArrays.from_spectra(refs) +right = PeakArrays.from_spectra(queries) +planes = sim.matrix(left, right, array_type="torch") +best_ref_per_query = planes[0].argmax(dim=0) ``` -# Supported similarity functions +The default cosine tensor has shape `(2, n_refs, n_queries)`, with score and matches in that order. Scalar methods return a two-dimensional tensor. `batch_size` limits each tile axis. A dense Torch result still needs enough device memory for the entire output. -- `CudaModifiedCosine`, equivalent to [ModifiedCosine](https://matchms.readthedocs.io/en/latest/api/matchms.similarity.ModifiedCosine.html) -- `CudaCosineGreedy`, equivalent to [CosineGreedy](https://matchms.readthedocs.io/en/latest/_modules/matchms/similarity/CosineGreedy.html) -- `CudaFingerprintSimilarity`, equivalent to [FingerprintSimilarity](https://matchms.readthedocs.io/en/latest/_modules/matchms/similarity/FingerprintSimilarity.html) (`jaccard`, `cosine`, `dice`) +## GPU similarities -- More coming soon - **requests are welcome**! +| SimMS class | matchms 1.0.0 counterpart | What it compares | +| --- | --- | --- | +| `CudaCosineGreedy` | `CosineGreedy` | One-to-one fragment matches ranked by weighted intensity product | +| `CudaModifiedCosineGreedy` | `ModifiedCosineGreedy` | Direct and precursor-shifted candidates in a shared assignment | +| `CudaNeutralLossesCosine` | `NeutralLossesCosine` | Precursor-shifted fragment matches | +| `CudaEntropyGreedy` | `EntropyGreedy` | Entropy-weighted fragment, neutral-loss or hybrid matches | +| `CudaCosineLinear` | `CosineLinear` | Linear fragment matching after merging nearby peaks | +| `CudaModifiedCosineLinear` | `ModifiedCosineLinear` | Linear matching with a precursor shift and conflict resolution | +| `CudaBinnedEmbeddingSimilarity` | `BinnedEmbeddingSimilarity` | Cosine or Euclidean similarity of binned intensities | +| `CudaFingerprintSimilarity` | `FingerprintSimilarity` | Tanimoto or cosine over molecular fingerprints | +`CudaModifiedCosine` is an alias for `CudaModifiedCosineGreedy`. Fingerprint matrices are indexed by valid unique compounds, in matchms `Fingerprints.inchikeys` order on each axis. Use a chemap-compatible generator with valid InChIKey and SMILES or InChI metadata, or pass prepared containers as `fingerprints_1` and `fingerprints_2`. A precursor mask for fingerprint scoring must use those same compound axes. A spectrum-level mask is directly reusable when each spectrum represents a different valid compound on its axis. RDKit generators with JSON support can be exported through `to_dict()` and reconstructed from the saved parameters. Embedding, entropy and fingerprint scorers return a single score field. -# Installation -The **easiest way** to get started is to use the colab notebook - that has everything ready for you. +Binned embeddings and precomputed fingerprints also run on CPU. The six spectral CUDA scorers require a CUDA device or the Numba simulator. For simulator tests, set `NUMBA_ENABLE_CUDASIM=1` before starting Python. -For local installations, we recommend using [`micromamba`](https://mamba.readthedocs.io/en/latest/installation/micromamba-installation.html), it is much faster. +## Transitive alignment -Total size of install in a fresh conda environment will be around 7-8GB (heaviest packages are `pytorch`, and `cudatoolkit`). +`CudaTransitiveAlignment` builds an undirected network from one collection of spectra. Its defaults retain direct modified-cosine edges with a score of at least 0.7 and at least six matches. Each reachable non-edge uses the fewest-hop path with the highest sum of direct scores. Set `max_hops` to limit path length. [Wang et al., JASMS 2024](https://doi.org/10.1021/jasms.4c00208) -```bash -# Install cudatoolkit -conda install nvidia::cuda-toolkit -y +```python +from simms.similarity import CudaTransitiveAlignment -# Install torch (follow the official guide https://pytorch.org/get-started/locally/#start-locally) -conda install pytorch -c pytorch -c nvidia -y +aligner = CudaTransitiveAlignment() +result = aligner.align(spectra, return_peak_pairs=True) +bridges = result.to_scores(sparse=True, transitive_only=True) +for edge in result.transitive_edges: + key = (edge.row, edge.col) + print(edge.score, result.paths[key], result.peak_pairs[key]) +``` -# Install numba (follow the offical guide: https://numba.pydata.org/numba-doc/latest/user/installing.html#installing-using-conda-on-x86-x86-64-power-platforms) -conda install numba -y +The aligner is available by explicit import. `simms.similarity.__all__` lists the pairwise scorers. Use `aligner.sparse_matrix(spectra, min_score=0.8)` to filter the final edges after path selection. -# Install this repository -pip install git+https://github.com/PangeAI/simms -``` +Pass `base_scores=...` to `align`, `matrix`, or `sparse_matrix` to reuse dense or sparse direct scores with both `score` and `matches` fields. Use the same spectrum order and preprocessing as the original calculation. Paths use input spectrum indices. Peak pairs use zero-based indices after precursor and noise filtering. The score matrices store edges symmetrically with a zero diagonal. Use `result.to_dict()` to serialize the paths and evidence to JSON. -## Run in docker +## RTX 4060 Laptop benchmark -The `pytorch/pytorch:2.2.1-cuda12.1-cudnn8-devel` has nearly everything you need. Once inside, do: +Each row compares 1,024 references with 1,024 disjoint queries on an Intel Core i9-14900HX and an 8 GB RTX 4060 Laptop GPU. The inputs are the first eligible spectra in file order from GNPS-random-10k, with nonempty peaks and positive finite precursor m/z. The fingerprint rows use two disjoint sets of 1,024 unique compounds from the same file, encoded once with RDKit Morgan radius 2, 2,048 bits and matchms/chemap. -```sh -pip install git+https://github.com/PangeAI/simms -``` +Times are seconds for one warmed dense `matrix` call, using matchms 1.0.0 defaults unless indicated. They include spectrum preparation, device transfers and host output. MGF parsing, fingerprint generation and JIT warmup are excluded. GPU tile size was 256. Flash times include building its CPU index, with the default worker count. Speedup uses the named CPU counterpart. VRAM is peak process memory sampled with NVML every 5 ms, including the CUDA context and allocator caches retained across cases. The JSON also records PyTorch's peak allocated bytes in MiB. + +| Method and settings | matchms CPU (s) | SimMS GPU (s) | Speedup | Flash CPU (s) | Max abs. score difference | Count mismatches | VRAM (MiB) | +| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | +| CosineGreedy | 36.148 | 0.285 | 126.73× | 0.059 | 0 | 0 | 1600 | +| CosineGreedy 0.5 Da | 39.004 | 0.308 | 126.47× | 0.069 | 0 | 0 | 1600 | +| CosineGreedy 0.5 Da mz_power=1.0 | 39.699 | 0.315 | 125.95× | n/a | 0 | 0 | 1600 | +| ModifiedCosineGreedy | 39.709 | 0.286 | 138.75× | n/a | 0 | 0 | 1600 | +| NeutralLossesCosine | 35.542 | 0.278 | 127.92× | n/a | 0 | 0 | 1600 | +| EntropyGreedy fragment | 80.557 | 0.103 | 784.89× | 0.068 | 4.44e-16 | n/a | 1600 | +| EntropyGreedy hybrid | 100.485 | 0.153 | 655.12× | 0.074 | 4.44e-16 | n/a | 1600 | +| CosineLinear | 3.389 | 0.074 | 46.01× | n/a | 0 | 0 | 1600 | +| ModifiedCosineLinear | 4.136 | 0.101 | 40.86× | n/a | 0 | 0 | 1600 | +| BinnedEmbeddingSimilarity float64 | 0.070 | 0.056 | 1.25× | n/a | 2.33e-15 | n/a | 1620 | +| BinnedEmbeddingSimilarity float32 | 0.071 | 0.037 | 1.89× | n/a | 4.61e-07 | n/a | 1620 | +| FingerprintSimilarity tanimoto | 0.042 | 0.048 | 0.88× | n/a | 2.96e-08 | n/a | 1640 | +| FingerprintSimilarity cosine | 0.033 | 0.064 | 0.51× | n/a | 7.38e-08 | n/a | 1640 | + +Every cosine peak-matching row agreed on all 1,048,576 scores and counts. Entropy, embedding and fingerprint methods return scores only. Fingerprint CPU computations use float32 inputs, which accounts for small differences against the FP64 GPU calculation. + +**Choosing an implementation.** For default fragment cosine or fragment/hybrid entropy on this GNPS slice, the CPU Flash implementations finished first. CosineFlash also led at 0.5 Da. Its interface supports intensity weighting but has no `mz_power` parameter. Use GPU greedy cosine when you need that weighting, or when later operations can consume the device tensor. For repeated searches against a fixed library, matchms can reuse a Flash index. Flash has its own matching conventions, so the parity columns above compare SimMS with the named CPU oracle. For precomputed Morgan fingerprints at this size, the CPU won both comparisons. -## Run on vast.ai +**Device-resident output.** With prepacked `PeakArrays`, `CudaCosineGreedy` produced a `(2, 4096, 2048)` FP64 CUDA tensor in 2.044 s, or **4.10 million pairs/s**. The timer excludes initial array construction and includes scoring through CUDA synchronization. Sampled process VRAM peaked at 1,768 MiB, with 137.36 MiB of live PyTorch allocations at their peak. -Use [this template](https://cloud.vast.ai/?ref_id=51575&template_id=f45f6048db515291bda978a34e908d09) as a starting point, once inside, simply do: +To reproduce on Linux with a CUDA GPU, run these commands from the checkout. Use `--mgf tests/data/pesticides.mgf --size 32 --demo-rows 48 --demo-cols 24` for a smaller run against the bundled file, with `--output /tmp/pesticides.json` to keep its results separate. -```sh -pip install git+https://github.com/PangeAI/simms +```bash +python -m pip install -e ".[cu13,fingerprints]" nvidia-ml-py +NUMBA_CUDA_LOW_OCCUPANCY_WARNINGS=0 python benchmarks/benchmark_matchms.py ``` -# Frequently asked questions +The full-precision results include the dataset SHA-256, software versions, timings and peak memory for each row. [Benchmark script](benchmarks/benchmark_matchms.py) · [Measured results](benchmarks/rtx4060.json) -### I want to get `referenece_id`, `query_id` and `score` as 1D arrays, separately. How do I do this? +## Multi-GPU Validation & Scaling -Use the `"sparse"` mode. It directly gives you the columns. You can set `sparse_threshold` to `0`, at which point you will get *all* the scores. +Both GPUs ran the same `simms-gpu 1.0.0` wheel in fresh Python 3.12 environments. The wheel smoke test exercised all nine GPU scorers. All 13 dense matchms comparisons met the [RTX 4060 benchmark](#rtx-4060-laptop-benchmark) parity tolerances, and the 1,024-spectrum transitive alignment matched the CPU reference exactly on both GPUs. -```py -from simms.similarity import CudaCosineGreedy +| GPU | Architecture | Wheel extras | PyTorch / CUDA runtime | Pytest | Transitive alignment, warm GPU / CPU (s) | +|---|---|---|---:|---:|---:| +| [NVIDIA GeForce RTX 4090](benchmarks/vast_rtx_4090.json) | Ada Lovelace | `cu12,fingerprints` | 2.10.0 / 12.8 | 341/341 | 0.102 / 17.47 | +| [NVIDIA A100-SXM4-80GB](benchmarks/vast_a100_sxm4.json) | Ampere | `cu13,fingerprints` | 2.15.0 / 13.2 | 341/341 | 0.097 / 32.97 | + +Each cell gives **million pairs/s / peak process VRAM (MiB)** for one warmed call with prepacked FP64 `PeakArrays` and tile size 256. Torch returns a dense device tensor. Sparse applies `min_score=0.7` on the GPU and returns the retained coordinates and scores on the host. Throughput counts every evaluated pair. NVML samples process memory every 5 ms, including the CUDA context and allocator caches. + +| Scorer | Output | RTX 4090, 4,096 × 2,048 | A100, 4,096 × 2,048 | RTX 4090, 9,000 × 2,048 | A100, 9,000 × 2,048 | +|---|---|---:|---:|---:|---:| +| `CudaCosineGreedy` | Torch | 11.24 / 8,480 | 11.22 / 9,502 | 11.04 / 9,110 | 11.27 / 10,132 | +| `CudaCosineGreedy` | Sparse | 11.08 / 8,544 | 11.11 / 9,566 | 10.40 / 9,252 | 11.02 / 10,274 | +| `CudaModifiedCosineGreedy` | Torch | 10.80 / 8,544 | 10.79 / 9,566 | 10.05 / 9,534 | 10.68 / 10,556 | +| `CudaModifiedCosineGreedy` | Sparse | 10.67 / 8,546 | 10.60 / 9,568 | 9.87 / 9,534 | 10.61 / 10,556 | +| `CudaEntropyGreedy` | Torch | 34.11 / 8,546 | 24.51 / 9,568 | 37.39 / 9,534 | 25.59 / 10,556 | +| `CudaEntropyGreedy` | Sparse | 31.83 / 8,546 | 22.22 / 9,568 | 34.67 / 9,534 | 24.32 / 10,556 | +| `CudaCosineLinear` | Torch | 54.45 / 8,546 | 36.42 / 9,568 | 57.96 / 9,534 | 38.04 / 10,556 | +| `CudaCosineLinear` | Sparse | 47.67 / 8,546 | 31.48 / 9,568 | 50.71 / 9,534 | 33.93 / 10,556 | + +GNPS-10k yielded 9,977 eligible spectra in file order. The 8,388,608-pair run used the first 4,096 references and the next 2,048 queries. The 18,432,000-pair run used the first 9,000 references and the last 2,048 queries, including 1,071 spectra present on both sides. Each GPU report includes the dataset and wheel checksums, package versions, exact slices, probe code, timings and memory measurements. + +## How do I get reference IDs, query IDs and scores as arrays? + +Use `min_score` for an inclusive threshold on the GPU. Cosine scorers also accept `min_matches`. Each selected field is available as a SciPy `coo_array`. Its row and column indices refer to positions in your two input collections. + +```python +hits = sim.sparse_matrix(refs, queries, min_score=0.75) +coo = hits.to_coo("score") +ref_idx, query_idx, values = coo.row, coo.col, coo.data +matched_peaks = hits.to_coo("matches").data # same stored coordinates +``` -scores_cu = CudaCosineGreedy( - sparse_threshold=0.75, # anything with a lower score gets discarded -).matrix(references, queries, array_type='sparse') +For a custom rule, pass a Python predicate. When combined with a threshold, it receives only the surviving full scores, before field projection. -# Unpack sparse results as 1D arrays -ref_id, query_id, scores = scores_cu.data['sparse_score'] -ref_id, query_id, matches = scores_cu.data['sparse_matches'] +```python +hits = sim.sparse_matrix(refs, queries, min_score=0.75, score_filter=lambda s: 3 <= s["matches"] <= 10) ``` +Use `idx_row` and `idx_col` to score only a supplied set of coordinate pairs. Repeated coordinates count once. In a commutative self-comparison, either triangle selects the pair and both directions are returned. Thresholding alone still evaluates the pairs before selecting which results to store. -# Citing SimMS +## Citing SimMS ```bibtex @article{onoprishvili2025simms, diff --git a/benchmarks/benchmark_matchms.py b/benchmarks/benchmark_matchms.py new file mode 100644 index 0000000..5edff15 --- /dev/null +++ b/benchmarks/benchmark_matchms.py @@ -0,0 +1,245 @@ +"""Benchmark matchms 1.0.0 matrix calls on two disjoint, file-order slices of real spectra. + +Install simms-gpu with its fingerprints extra, and nvidia-ml-py for VRAM sampling. +Run from the repository root with .venv/bin/python benchmarks/benchmark_matchms.py. +""" + +import argparse +import hashlib +import json +import logging +import os +import platform +import threading +from importlib.metadata import version +from pathlib import Path +from time import perf_counter + +import numpy as np +import pynvml +import torch +from matchms import Fingerprints +from matchms import similarity as cpu +from matchms.importing import load_from_mgf +from numba import cuda +from rdkit import Chem, rdBase +from rdkit.Chem.rdFingerprintGenerator import GetMorganGenerator +from threadpoolctl import threadpool_info + +from simms import PeakArrays +from simms import similarity as gpu +from simms.utils import download + + +def measure(call): + start = perf_counter() + result = call() + return result, perf_counter() - start + + +def measure_gpu(call): + # Warm the actual shape, including data-dependent CUDA kernel specializations. + call() + torch.cuda.synchronize() + torch.cuda.reset_peak_memory_stats() + handle = pynvml.nvmlDeviceGetHandleByUUID(str(torch.cuda.get_device_properties(0).uuid)) + peak = 0 + stop = threading.Event() + + def sample(): + nonlocal peak + for process in pynvml.nvmlDeviceGetComputeRunningProcesses(handle): + if process.pid == os.getpid(): + peak = max(peak, process.usedGpuMemory) + + def monitor(): + while not stop.wait(0.005): + sample() + + sample() + thread = threading.Thread(target=monitor) + thread.start() + try: + start = perf_counter() + result = call() + torch.cuda.synchronize() + seconds = perf_counter() - start + sample() + finally: + stop.set() + thread.join() + if not 0 < peak <= torch.cuda.get_device_properties(0).total_memory: + raise RuntimeError("Process VRAM measurement unavailable") + return result, dict( + gpu_s=seconds, + process_peak_mib=peak / 2**20, + torch_peak_allocated_mib=torch.cuda.max_memory_allocated() / 2**20, + ) + + +def fingerprint_inputs(spectra, n): + """Use real distinct structures. Many GNPS records lack an InChIKey.""" + unique = {} + with rdBase.BlockLogs(): + for s in spectra: + smiles, inchi = s.get("smiles"), s.get("inchi") + mol = Chem.MolFromSmiles(smiles) if smiles else None + if mol is None and inchi: + mol = Chem.MolFromInchi(inchi) + if mol is None or not mol.GetNumAtoms(): + continue + key = Chem.MolToInchiKey(mol) + if key and key not in unique: + unique[key] = s.clone().set("inchikey", key).set("smiles", Chem.MolToSmiles(mol)) + if len(unique) == 2 * n: + break + n = min(n, len(unique) // 2) + if n == 0: + raise ValueError("Need at least two distinct molecular structures") + rows = list(unique.values()) + gen = GetMorganGenerator(radius=2, fpSize=2048) + + def encode(rows): + fp = Fingerprints(gen) + fp.compute_fingerprints(rows) + assert fp.fingerprint_count == len(rows) + return fp + + return encode(rows[:n]), encode(rows[n : 2 * n]), encode(rows[:1]) + + +def matrix(method, left, right): + if isinstance(left, Fingerprints): + return method.matrix(fingerprints_1=left, fingerprints_2=right, progress_bar=False) + return method.matrix(left, right, progress_bar=False) + + +def compare(name, cpu_method, gpu_method, left, right, warm, flash=None): + matrix(cpu_method, warm, warm) + expected, seconds = measure(lambda: matrix(cpu_method, left, right)) + actual, stats = measure_gpu(lambda: matrix(gpu_method, left, right)) + assert actual.shape == expected.shape and actual.score_fields == expected.score_fields + diff = np.abs(actual.to_array("score") - expected.to_array("score")) + matches = None + if "matches" in expected.score_fields: + matches = int(np.count_nonzero(actual.to_array("matches") != expected.to_array("matches"))) + row = dict( + case=name, + shape=actual.shape, + cpu_s=seconds, + **stats, + speedup=seconds / stats["gpu_s"], + max_abs_diff=float(diff.max()), + match_mismatches=matches, + ) + if flash is not None: + matrix(flash, left, right) + _, row["flash_cpu_s"] = measure(lambda: matrix(flash, left, right)) + return row + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--mgf", type=Path, help="Alternative real MGF, e.g. tests/data/pesticides.mgf") + parser.add_argument("--size", type=int, default=1024) + parser.add_argument("--demo-rows", type=int, default=4096) + parser.add_argument("--demo-cols", type=int, default=2048) + parser.add_argument("--output", type=Path, default=Path("benchmarks/rtx4060.json")) + args = parser.parse_args() + if min(args.size, args.demo_rows, args.demo_cols) < 1: + parser.error("all sizes must be positive") + if cuda.config.ENABLE_CUDASIM or not torch.cuda.is_available() or not cuda.is_available(): + raise RuntimeError("Real CUDA is required") + pynvml.nvmlInit() + logging.getLogger("matchms").setLevel(logging.ERROR) + path = args.mgf or Path(download("GNPS-random-10k.mgf")) + rows = [ + s + for s in load_from_mgf(path) + if len(s.peaks) and np.isfinite(s.get("precursor_mz") or 0) and (s.get("precursor_mz") or 0) > 0 + ] + n = min(args.size, len(rows) // 2) + if n == 0: + raise ValueError("Need at least two eligible spectra") + left, right = rows[:n], rows[n : 2 * n] + host = Path("/proc/cpuinfo").read_text().split("model name", 1)[1].splitlines()[0].strip(": \t") + report = dict( + dataset=path.name, + sha256=hashlib.sha256(path.read_bytes()).hexdigest(), + eligible=len(rows), + python=platform.python_version(), + cpu=host, + cuda=torch.version.cuda, + driver=pynvml.nvmlSystemGetDriverVersion(), + gpu=torch.cuda.get_device_name(), + cpu_affinity=len(os.sched_getaffinity(0)), + packages={ + p: version(p) + for p in ( + "simms-gpu", + "matchms", + "numpy", + "torch", + "numba", + "numba-cuda", + "chemap", + "rdkit", + "nvidia-ml-py", + ) + }, + threadpools=[(p["internal_api"], p["num_threads"]) for p in threadpool_info()], + rows=[], + ) + cases = [ + ("CosineGreedy", {}, {}, cpu.CosineFlash()), + ("CosineGreedy", {"tolerance": 0.5}, {}, cpu.CosineFlash(tolerance=0.5)), + ("CosineGreedy", {"tolerance": 0.5, "mz_power": 1.0}, {}, None), + ("ModifiedCosineGreedy", {}, {}, None), + ("NeutralLossesCosine", {}, {}, None), + ("EntropyGreedy", {"matching_mode": "fragment"}, {}, cpu.EntropyFlash()), + ("EntropyGreedy", {"matching_mode": "hybrid"}, {}, cpu.EntropyFlash(matching_mode="hybrid")), + ("CosineLinear", {}, {}, None), + ("ModifiedCosineLinear", {}, {}, None), + ("BinnedEmbeddingSimilarity", {}, {"precision": "float64"}, None), + ("BinnedEmbeddingSimilarity", {}, {"precision": "float32"}, None), + ("FingerprintSimilarity", {"similarity_measure": "tanimoto"}, {}, None), + ("FingerprintSimilarity", {"similarity_measure": "cosine"}, {}, None), + ] + fingerprints = fingerprint_inputs(rows, n) + for method, params, gpu_params, flash in cases: + label = " ".join([method, *(f"{k}={v}" for k, v in (params | gpu_params).items())]) + print(label, flush=True) + inputs = fingerprints if method == "FingerprintSimilarity" else (left, right, left[:2]) + if method == "FingerprintSimilarity": + params = dict(params, fingerprint_generator=None) + result = compare( + label, + getattr(cpu, method)(**params), + getattr(gpu, "Cuda" + method)(**params, **gpu_params, batch_size=256), + *inputs, + flash, + ) + allowance = ( + 1e-6 if (gpu_params.get("precision") == "float32" or method == "FingerprintSimilarity") else 1e-12 + ) + if result["match_mismatches"] or not result["max_abs_diff"] <= allowance: + raise AssertionError(f"Parity failed: {result}") + report["rows"].append(result) + print(json.dumps(result), flush=True) + + nr = min(args.demo_rows, len(rows) - 1) + nc = min(args.demo_cols, len(rows) - nr) + refs = PeakArrays.from_spectra(rows[:nr], require_precursor=True) + queries = PeakArrays.from_spectra(rows[nr : nr + nc], require_precursor=True) + sim = gpu.CudaCosineGreedy(batch_size=256) + tensor, stats = measure_gpu(lambda: sim.matrix(refs, queries, array_type="torch", progress_bar=False)) + assert tensor.is_cuda and tensor.shape == (2, nr, nc) + check = cpu.CosineGreedy().pair(rows[0], rows[nr]) + np.testing.assert_allclose(tensor[:, 0, 0].cpu(), [check["score"], check["matches"]], atol=1e-12) + report["torch_demo"] = dict(shape=list(tensor.shape), pairs_per_s=nr * nc / stats["gpu_s"], **stats) + args.output.write_text(json.dumps(report, indent=2, allow_nan=False) + "\n") + print(report["torch_demo"]) + + +if __name__ == "__main__": + main() diff --git a/benchmarks/benchmark_transitive_alignment.py b/benchmarks/benchmark_transitive_alignment.py new file mode 100644 index 0000000..96a1f45 --- /dev/null +++ b/benchmarks/benchmark_transitive_alignment.py @@ -0,0 +1,168 @@ +# SPDX-License-Identifier: MIT +"""Run with python -m benchmarks.benchmark_transitive_alignment [--mgf FILE] [--size N]. + +Independent CPU reference: matchms direct matrix, NetworkX shortest paths and +Python peak correspondences. Both timed pipelines start from Spectrum objects +and return paths and evidence. File I/O and compilation are outside warm timings. +""" + +import argparse +import json +import logging +from itertools import islice, pairwise +from operator import attrgetter +from time import perf_counter + +import networkx as nx +import numpy as np +import torch +from matchms.importing import load_from_mgf +from matchms.similarity import ModifiedCosineGreedy +from matchms.similarity.spectrum_similarity_functions import collect_peak_pairs, score_best_matches +from numba import cuda + +from simms import PeakArrays +from simms.similarity import CudaTransitiveAlignment, TransitiveAlignmentResult +from simms.similarity.CudaTransitiveAlignment import AlignmentEdge +from simms.utils import download + + +def cpu_reference( + spectra, min_direct_score=0.7, min_direct_matches=6, min_transitive_score=0.0, max_hops=None +): + direct = ModifiedCosineGreedy().matrix(spectra, progress_bar=False) + scores, counts = direct.to_array("score"), direct.to_array("matches") + peaks = PeakArrays.from_spectra(spectra, True, True, -1.6, 0.01) + rows = [np.column_stack((peaks.mz[i, :n], peaks.intensities[i, :n])) for i, n in enumerate(peaks.lengths)] + + def assign(u, v, bridges=()): + candidates = [(a, b, rows[u][a, 1] * rows[v][b, 1]) for a, b in sorted(bridges)] + delta = peaks.precursor_mz[u] - peaks.precursor_mz[v] + for shift in [0.0, delta] if abs(delta) > 0.01 else [0.0]: + pairs = collect_peak_pairs(rows[u], rows[v], 0.01, shift) + if pairs is not None: + candidates.extend(pairs) + if not candidates: + return 0.0, () + candidates = np.asarray(candidates) + candidates = candidates[np.argsort(candidates[:, 2], kind="stable")[::-1]] + score, count = score_best_matches(candidates, rows[u], rows[v]) + available_left, available_right = set(range(len(rows[u]))), set(range(len(rows[v]))) + chosen = [] + for a, b, _ in candidates: + if a in available_left and b in available_right: + chosen.append((int(a), int(b))) + available_left.remove(a) + available_right.remove(b) + assert len(chosen) == count + return score, tuple(sorted(chosen)) + + graph = nx.Graph() + maps = {} + result = TransitiveAlignmentResult(len(spectra), [], [], {}, {}) + for i, j in zip(*np.nonzero(np.triu((scores >= min_direct_score) & (counts >= min_direct_matches), 1))): + u, v = int(i), int(j) + graph.add_edge(u, v, weight=scores[u, v]) + result.direct_edges.append(AlignmentEdge(u, v, float(scores[u, v]), int(counts[u, v]), 1)) + _, pairs = assign(u, v) + result.peak_pairs[u, v] = pairs + maps[u, v], maps[v, u] = dict(pairs), {b: a for a, b in pairs} + + for u in graph: + for v, hops in nx.single_source_shortest_path_length(graph, u, cutoff=max_hops).items(): + if u >= v or hops < 2: + continue + + def rank(path): + return (-sum(graph[a][b]["weight"] for a, b in pairwise(path)), tuple(reversed(path))) + + path = tuple(min(nx.all_shortest_paths(graph, u, v), key=rank)) + result.paths[u, v] = path + composed = maps[path[:2]].copy() + for a, b in pairwise(path[1:]): + forward = maps[a, b] + composed = {p: forward[q] for p, q in composed.items() if q in forward} + if composed: + score, pairs = assign(u, v, composed.items()) + if pairs and score >= min_transitive_score: + result.transitive_edges.append(AlignmentEdge(u, v, score, len(pairs), hops)) + result.peak_pairs[u, v] = pairs + return result + + +def assert_parity(cpu, gpu): + assert cpu.n_spectra == gpu.n_spectra + assert cpu.paths == gpu.paths + assert cpu.peak_pairs == gpu.peak_pairs + for a, b in ((cpu.direct_edges, gpu.direct_edges), (cpu.transitive_edges, gpu.transitive_edges)): + by_coord = attrgetter("row", "col") + assert sorted(a, key=by_coord) == sorted(b, key=by_coord) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--mgf") + parser.add_argument("--size", type=int, default=1024) + args = parser.parse_args() + if cuda.config.ENABLE_CUDASIM or not torch.cuda.is_available(): + raise RuntimeError("Real CUDA required for this benchmark") + logging.getLogger("matchms").setLevel(logging.ERROR) + rows = list( + islice( + ( + s + for s in load_from_mgf(args.mgf or download("GNPS-random-10k.mgf")) + if len(s.peaks) + and np.isfinite(s.get("precursor_mz") or 0) + and (s.get("precursor_mz") or 0) > 0 + ), + args.size, + ) + ) + method = CudaTransitiveAlignment() + + def gpu_run(): + result = method.align(rows, return_peak_pairs=True) + torch.cuda.synchronize() + return result + + def measure(f): + start = perf_counter() + result = f() + return result, perf_counter() - start + + _, cold_gpu_s = measure(gpu_run) + actual, gpu_s = measure(gpu_run) + _, cold_cpu_s = measure(lambda: cpu_reference(rows)) + expected, cpu_s = measure(lambda: cpu_reference(rows)) + assert_parity(expected, actual) + # Distinguish newly connected nodes from increases over their original + # endpoint cosine. These diagnostic pair calls are outside both timings. + direct = ModifiedCosineGreedy() + endpoint_scores = [direct.pair(rows[e.row], rows[e.col])["score"].item() for e in actual.transitive_edges] + print( + json.dumps( + { + "spectra": len(rows), + "gpu": torch.cuda.get_device_name(), + "direct_edges": len(actual.direct_edges), + "reachable_non_edges": len(actual.paths), + "new_transitive_edges": len(actual.transitive_edges), + "new_edges_with_zero_direct_score": endpoint_scores.count(0.0), + "new_edges_with_increased_score": sum( + e.score > before for e, before in zip(actual.transitive_edges, endpoint_scores) + ), + "exact_parity": True, + "cold_gpu_s": cold_gpu_s, + "cold_cpu_s": cold_cpu_s, + "warm_gpu_s": gpu_s, + "warm_cpu_s": cpu_s, + "warm_speedup": cpu_s / gpu_s, + }, + indent=2, + ) + ) + + +if __name__ == "__main__": + main() diff --git a/benchmarks/rtx4060.json b/benchmarks/rtx4060.json new file mode 100644 index 0000000..56121bc --- /dev/null +++ b/benchmarks/rtx4060.json @@ -0,0 +1,239 @@ +{ + "dataset": "GNPS-random-10k.mgf", + "sha256": "b501344f2d6bdbf7723c89af1c175e346e8ea849bb397a0142d6120769a8e054", + "eligible": 9977, + "python": "3.12.3", + "cpu": "Intel(R) Core(TM) i9-14900HX", + "cuda": "13.2", + "driver": "580.105.08", + "gpu": "NVIDIA GeForce RTX 4060 Laptop GPU", + "cpu_affinity": 32, + "packages": { + "simms-gpu": "1.0.0", + "matchms": "1.0.0", + "numpy": "2.4.6", + "torch": "2.15.0", + "numba": "0.68.1", + "numba-cuda": "0.30.4", + "chemap": "0.3.9", + "rdkit": "2026.3.5", + "nvidia-ml-py": "13.615.71" + }, + "threadpools": [ + [ + "openmp", + 32 + ], + [ + "openblas", + 32 + ], + [ + "openmp", + 24 + ], + [ + "openblas", + 32 + ] + ], + "rows": [ + { + "case": "CosineGreedy", + "shape": [ + 1024, + 1024 + ], + "cpu_s": 36.148238856112584, + "gpu_s": 0.2852462059818208, + "process_peak_mib": 1600.0, + "torch_peak_allocated_mib": 8.572265625, + "speedup": 126.72644928506557, + "max_abs_diff": 0.0, + "match_mismatches": 0, + "flash_cpu_s": 0.059244236908853054 + }, + { + "case": "CosineGreedy tolerance=0.5", + "shape": [ + 1024, + 1024 + ], + "cpu_s": 39.003802112070844, + "gpu_s": 0.30840304400771856, + "process_peak_mib": 1600.0, + "torch_peak_allocated_mib": 8.572265625, + "speedup": 126.47022417552621, + "max_abs_diff": 0.0, + "match_mismatches": 0, + "flash_cpu_s": 0.06852152408100665 + }, + { + "case": "CosineGreedy tolerance=0.5 mz_power=1.0", + "shape": [ + 1024, + 1024 + ], + "cpu_s": 39.6991261090152, + "gpu_s": 0.31520389090292156, + "process_peak_mib": 1600.0, + "torch_peak_allocated_mib": 8.572265625, + "speedup": 125.9474494280338, + "max_abs_diff": 0.0, + "match_mismatches": 0 + }, + { + "case": "ModifiedCosineGreedy", + "shape": [ + 1024, + 1024 + ], + "cpu_s": 39.70854097791016, + "gpu_s": 0.2861825090367347, + "process_peak_mib": 1600.0, + "torch_peak_allocated_mib": 8.572265625, + "speedup": 138.75250836106525, + "max_abs_diff": 0.0, + "match_mismatches": 0 + }, + { + "case": "NeutralLossesCosine", + "shape": [ + 1024, + 1024 + ], + "cpu_s": 35.54209607793018, + "gpu_s": 0.2778558898717165, + "process_peak_mib": 1600.0, + "torch_peak_allocated_mib": 8.572265625, + "speedup": 127.91557556811065, + "max_abs_diff": 0.0, + "match_mismatches": 0 + }, + { + "case": "EntropyGreedy matching_mode=fragment", + "shape": [ + 1024, + 1024 + ], + "cpu_s": 80.55733559885994, + "gpu_s": 0.10263567487709224, + "process_peak_mib": 1600.0, + "torch_peak_allocated_mib": 1.349609375, + "speedup": 784.8863048382402, + "max_abs_diff": 4.440892098500626e-16, + "match_mismatches": null, + "flash_cpu_s": 0.06752451695501804 + }, + { + "case": "EntropyGreedy matching_mode=hybrid", + "shape": [ + 1024, + 1024 + ], + "cpu_s": 100.48498482001014, + "gpu_s": 0.1533845930825919, + "process_peak_mib": 1600.0, + "torch_peak_allocated_mib": 1.349609375, + "speedup": 655.1178498475575, + "max_abs_diff": 4.440892098500626e-16, + "match_mismatches": null, + "flash_cpu_s": 0.07429953501559794 + }, + { + "case": "CosineLinear", + "shape": [ + 1024, + 1024 + ], + "cpu_s": 3.3890344069804996, + "gpu_s": 0.0736602449323982, + "process_peak_mib": 1600.0, + "torch_peak_allocated_mib": 2.2353515625, + "speedup": 46.009002686466644, + "max_abs_diff": 0.0, + "match_mismatches": 0 + }, + { + "case": "ModifiedCosineLinear", + "shape": [ + 1024, + 1024 + ], + "cpu_s": 4.135927991941571, + "gpu_s": 0.10123320505954325, + "process_peak_mib": 1600.0, + "torch_peak_allocated_mib": 2.228515625, + "speedup": 40.85544846188466, + "max_abs_diff": 0.0, + "match_mismatches": 0 + }, + { + "case": "BinnedEmbeddingSimilarity precision=float64", + "shape": [ + 1024, + 1024 + ], + "cpu_s": 0.07006163615733385, + "gpu_s": 0.05583641701377928, + "process_peak_mib": 1620.0, + "torch_peak_allocated_mib": 16.984375, + "speedup": 1.2547659736125991, + "max_abs_diff": 2.3314683517128287e-15, + "match_mismatches": null + }, + { + "case": "BinnedEmbeddingSimilarity precision=float32", + "shape": [ + 1024, + 1024 + ], + "cpu_s": 0.07076564291492105, + "gpu_s": 0.03734567388892174, + "process_peak_mib": 1620.0, + "torch_peak_allocated_mib": 12.5546875, + "speedup": 1.8948819380097743, + "max_abs_diff": 4.613766271255315e-07, + "match_mismatches": null + }, + { + "case": "FingerprintSimilarity similarity_measure=tanimoto", + "shape": [ + 1024, + 1024 + ], + "cpu_s": 0.04208856704644859, + "gpu_s": 0.04757890896871686, + "process_peak_mib": 1640.0, + "torch_peak_allocated_mib": 17.12548828125, + "speedup": 0.8846055523072592, + "max_abs_diff": 2.9556022185239783e-08, + "match_mismatches": null + }, + { + "case": "FingerprintSimilarity similarity_measure=cosine", + "shape": [ + 1024, + 1024 + ], + "cpu_s": 0.03276963694952428, + "gpu_s": 0.06396368215791881, + "process_peak_mib": 1640.0, + "torch_peak_allocated_mib": 17.6875, + "speedup": 0.5123162995623032, + "max_abs_diff": 7.380454547512016e-08, + "match_mismatches": null + } + ], + "torch_demo": { + "shape": [ + 2, + 4096, + 2048 + ], + "pairs_per_s": 4104242.2705355124, + "gpu_s": 2.0438871409278363, + "process_peak_mib": 1768.0, + "torch_peak_allocated_mib": 137.361328125 + } +} diff --git a/benchmarks/transitive_alignment_rtx4060.json b/benchmarks/transitive_alignment_rtx4060.json new file mode 100644 index 0000000..bf3066f --- /dev/null +++ b/benchmarks/transitive_alignment_rtx4060.json @@ -0,0 +1,47 @@ +{ + "dataset": "GNPS-random-10k.mgf", + "sha256": "b501344f2d6bdbf7723c89af1c175e346e8ea849bb397a0142d6120769a8e054", + "selection": "First 1024 spectra in file order with nonempty peaks and positive finite precursor_mz.", + "cpu": "Intel(R) Core(TM) i9-14900HX", + "python": "3.12.3", + "cuda": "13.2", + "packages": { + "matchms": "1.0.0", + "torch": "2.15.0", + "numba": "0.68.1", + "numba-cuda": "0.30.4", + "numpy": "2.4.6", + "scipy": "1.18.1", + "networkx": "3.7" + }, + "parameters": { + "tolerance": 0.01, + "mz_power": 0.0, + "intensity_power": 1.0, + "remove_precursor": true, + "offset_to_precursor": -1.6, + "noise_cutoff": 0.01, + "min_direct_score": 0.7, + "min_direct_matches": 6, + "min_transitive_score": 0.0, + "max_hops": null, + "batch_size": 2048, + "precision": "float64", + "return_peak_pairs": true + }, + "timing": "One first call and one warmed call per pipeline on the full input. Excludes MGF parsing. GPU synchronized before stopping the timer.", + "cpu_baseline": "matchms ModifiedCosineGreedy symmetric matrix, NetworkX shortest paths and CPU endpoint assignment.", + "spectra": 1024, + "gpu": "NVIDIA GeForce RTX 4060 Laptop GPU", + "direct_edges": 77, + "reachable_non_edges": 176, + "new_transitive_edges": 176, + "new_edges_with_zero_direct_score": 0, + "new_edges_with_increased_score": 104, + "exact_parity": true, + "cold_gpu_s": 5.351391685893759, + "cold_cpu_s": 73.8825751862023, + "warm_gpu_s": 0.34274346102029085, + "warm_cpu_s": 59.369941504905, + "warm_speedup": 173.2197642171508 +} diff --git a/benchmarks/vast_a100_sxm4.json b/benchmarks/vast_a100_sxm4.json new file mode 100644 index 0000000..05649ab --- /dev/null +++ b/benchmarks/vast_a100_sxm4.json @@ -0,0 +1,794 @@ +{ + "gpu": "NVIDIA A100-SXM4-80GB", + "extras": [ + "cu13", + "fingerprints" + ], + "wheel_sha256": "f56bbc33b66ac9c77ed33332a179e426f3bbbe9b74224351b03aecf617087022", + "git_commit": "720403d56a736bcf135113f9c87b6d3095a1fb51", + "instance_id": 63729303, + "offer": { + "id": 36994170, + "gpu_name": "A100 SXM4", + "cuda_max_good": 13.2, + "gpu_ram": 81920, + "machine_id": 41522, + "dph_total": 1.075, + "inet_down_cost": 0.009114583333333334, + "inet_up_cost": 0.013020833333333334, + "inet_down": 794.6, + "cpu_cores_effective": 19.0, + "direct_port_count": 124, + "verification": "verified", + "reliability2": 0.9923219, + "geolocation": "Taiwan, TW" + }, + "run_utc": "2026-12-02T17:40:36.686159+00:00", + "hardware": { + "gpu": "NVIDIA A100-SXM4-80GB", + "architecture": "Ampere", + "compute_capability": "8.0", + "vram_mib": 81920, + "driver": "595.91.07", + "driver_cuda": "13.2", + "cpu_model": "Intel(R) Xeon(R) Platinum 8368 CPU @ 2.40GHz", + "visible_sockets": 2, + "visible_cores_per_socket": 38, + "visible_threads_per_core": 2, + "visible_logical_cpus": 152, + "benchmark_cpu_affinity": 152, + "cgroup_cpu_quota_cores": 18.24 + }, + "wheel_smoke": [ + "CudaCosineGreedy: [1.0, 2.0] (cuda:0)", + "CudaModifiedCosineGreedy: [1.0, 2.0] (cuda:0)", + "CudaNeutralLossesCosine: [1.0, 2.0] (cuda:0)", + "CudaEntropyGreedy: [1.0] (cuda:0)", + "CudaCosineLinear: [1.0, 2.0] (cuda:0)", + "CudaModifiedCosineLinear: [1.0, 2.0] (cuda:0)", + "CudaBinnedEmbeddingSimilarity: [1.0] (cuda:0)", + "CudaFingerprintSimilarity: [1.0] (cuda:0)", + "CudaTransitiveAlignment: one symmetric direct edge", + "simms-gpu 1.0.0 from /opt/simms-venv/lib/python3.12/site-packages/simms/__init__.py" + ], + "pytest": { + "tests": 341, + "failures": 0, + "errors": 0, + "skipped": 0, + "passed": 341, + "warnings": 8, + "seconds": 105.637 + }, + "packages": [ + "anyio==4.16.0", + "certifi==2026.11.20", + "charset-normalizer==3.5.3", + "chemap==0.3.9", + "click==8.5.1", + "cloudpickle==3.1.3", + "contourpy==1.4.0", + "cuda-bindings==13.5.0", + "cuda-core==1.3.1", + "cuda-pathfinder==1.9.1", + "cuda-toolkit==13.2.2", + "cycler==0.12.1", + "deprecated==3.0.1", + "descriptastorus==2.8.0", + "e3fp==1.2.7", + "filelock==4.3.2", + "fonttools==4.69.1", + "fsspec==2026.9.0", + "h11==0.16.0", + "hf-xet==1.8.0", + "httpcore==1.0.9", + "httpx==0.29.0", + "huggingface-hub==1.33.0", + "idna==3.20", + "iniconfig==2.3.1", + "jinja2==3.1.6", + "joblib==1.6.0", + "kiwisolver==1.5.1", + "llvmlite==0.50.0", + "lxml==6.2.1", + "markupsafe==3.0.4", + "matchms==1.0.0", + "matplotlib==3.11.2", + "mmh3==5.3.1", + "mordredcommunity==2.1.0", + "mpmath==1.3.0", + "narwhals==2.30.0", + "networkx==3.7", + "numba==0.68.1", + "numba-cuda==0.30.4", + "numpy==2.4.6", + "nvidia-cublas==13.4.1.3", + "nvidia-cuda-cccl==13.2.86", + "nvidia-cuda-cupti==13.2.86", + "nvidia-cuda-nvrtc==13.2.86", + "nvidia-cuda-runtime==13.2.86", + "nvidia-cudnn-cu13==9.26.0.51", + "nvidia-cufft==12.2.0.57", + "nvidia-cufile==1.17.1.22", + "nvidia-cusolver==12.2.0.11", + "nvidia-cusparse==12.7.10.12", + "nvidia-cusparselt-cu13==0.8.1", + "nvidia-ml-py==13.615.71", + "nvidia-nccl-cu13==2.30.7", + "nvidia-nvjitlink==13.5.37", + "nvidia-nvshmem-cu13==3.7.2", + "nvidia-nvtx==13.2.86", + "nvidia-nvvm==13.2.86", + "packaging==26.4", + "pandas==3.1.2", + "pandas-flavor==0.8.1", + "pickydict==0.5.0", + "pillow==13.0.0", + "platformdirs==4.14.9", + "pluggy==1.7.0", + "pooch==1.9.0", + "psims==1.4.0", + "pubchempy==1.0.5", + "pyarrow==26.0.0", + "pygments==2.21.0", + "pynndescent==0.8.0", + "pyparsing==3.3.3", + "pyteomics==5.0.2", + "pytest==9.2.0", + "python-dateutil==4.0.0", + "pyyaml==6.0.4", + "rdkit==2026.3.5", + "requests==2.34.2", + "scikit-fingerprints==2.1.0", + "scikit-learn==1.9.1", + "scipy==1.18.1", + "sdaxen-python-utilities==0.1.5", + "setuptools==84.2.1", + "simms-gpu @ file:///opt/simms-job/simms_gpu-1.0.0-py3-none-any.whl", + "six==1.17.0", + "smart-open==10.0.1", + "sqlalchemy==2.1.9", + "sympy==1.14.0", + "threadpoolctl==3.8.0", + "torch==2.15.0", + "tqdm==4.70.1", + "triton==3.9.0", + "typing-extensions==4.16.0", + "tzdata==2026.6", + "urllib3==2.8.0", + "wrapt==2.5.2", + "xarray==2026.9.0" + ], + "matchms": { + "dataset": "GNPS-random-10k.mgf", + "sha256": "b501344f2d6bdbf7723c89af1c175e346e8ea849bb397a0142d6120769a8e054", + "eligible": 9977, + "python": "3.12.14", + "cpu": "Intel(R) Xeon(R) Platinum 8368 CPU @ 2.40GHz", + "cuda": "13.2", + "driver": "595.91.07", + "gpu": "NVIDIA A100-SXM4-80GB", + "cpu_affinity": 152, + "packages": { + "simms-gpu": "1.0.0", + "matchms": "1.0.0", + "numpy": "2.4.6", + "torch": "2.15.0", + "numba": "0.68.1", + "numba-cuda": "0.30.4", + "chemap": "0.3.9", + "rdkit": "2026.3.5", + "nvidia-ml-py": "13.615.71" + }, + "threadpools": [ + [ + "openmp", + 8 + ], + [ + "openblas", + 8 + ], + [ + "openmp", + 8 + ], + [ + "openblas", + 8 + ] + ], + "rows": [ + { + "case": "CosineGreedy", + "shape": [ + 1024, + 1024 + ], + "cpu_s": 54.55656766300672, + "gpu_s": 0.1472446419938933, + "process_peak_mib": 9302.0, + "torch_peak_allocated_mib": 8.572265625, + "speedup": 370.5164882350649, + "max_abs_diff": 0.0, + "match_mismatches": 0, + "flash_cpu_s": 0.1276535940123722 + }, + { + "case": "CosineGreedy tolerance=0.5", + "shape": [ + 1024, + 1024 + ], + "cpu_s": 58.22369840199826, + "gpu_s": 0.18972229200880975, + "process_peak_mib": 9302.0, + "torch_peak_allocated_mib": 8.572265625, + "speedup": 306.88907342156, + "max_abs_diff": 0.0, + "match_mismatches": 0, + "flash_cpu_s": 0.11602360100368969 + }, + { + "case": "CosineGreedy tolerance=0.5 mz_power=1.0", + "shape": [ + 1024, + 1024 + ], + "cpu_s": 59.57188198901713, + "gpu_s": 0.19429365699761547, + "process_peak_mib": 9302.0, + "torch_peak_allocated_mib": 8.572265625, + "speedup": 306.6074462212024, + "max_abs_diff": 0.0, + "match_mismatches": 0 + }, + { + "case": "ModifiedCosineGreedy", + "shape": [ + 1024, + 1024 + ], + "cpu_s": 59.27265289699426, + "gpu_s": 0.1564969680039212, + "process_peak_mib": 9302.0, + "torch_peak_allocated_mib": 8.572265625, + "speedup": 378.74633389388805, + "max_abs_diff": 0.0, + "match_mismatches": 0 + }, + { + "case": "NeutralLossesCosine", + "shape": [ + 1024, + 1024 + ], + "cpu_s": 52.269137053983286, + "gpu_s": 0.1435553650080692, + "process_peak_mib": 9302.0, + "torch_peak_allocated_mib": 8.572265625, + "speedup": 364.1043791783418, + "max_abs_diff": 0.0, + "match_mismatches": 0 + }, + { + "case": "EntropyGreedy matching_mode=fragment", + "shape": [ + 1024, + 1024 + ], + "cpu_s": 116.98112650500843, + "gpu_s": 0.11608633698779158, + "process_peak_mib": 9302.0, + "torch_peak_allocated_mib": 1.349609375, + "speedup": 1007.7079658160887, + "max_abs_diff": 4.440892098500626e-16, + "match_mismatches": null, + "flash_cpu_s": 0.12587492901366204 + }, + { + "case": "EntropyGreedy matching_mode=hybrid", + "shape": [ + 1024, + 1024 + ], + "cpu_s": 145.93250617801095, + "gpu_s": 0.12935256300261244, + "process_peak_mib": 9302.0, + "torch_peak_allocated_mib": 1.349609375, + "speedup": 1128.1763792733173, + "max_abs_diff": 4.440892098500626e-16, + "match_mismatches": null, + "flash_cpu_s": 0.11360591000993736 + }, + { + "case": "CosineLinear", + "shape": [ + 1024, + 1024 + ], + "cpu_s": 4.87284161298885, + "gpu_s": 0.07915923499967903, + "process_peak_mib": 9302.0, + "torch_peak_allocated_mib": 2.2353515625, + "speedup": 61.55746215850378, + "max_abs_diff": 0.0, + "match_mismatches": 0 + }, + { + "case": "ModifiedCosineLinear", + "shape": [ + 1024, + 1024 + ], + "cpu_s": 5.854130454012193, + "gpu_s": 0.11345589402480982, + "process_peak_mib": 9302.0, + "torch_peak_allocated_mib": 2.228515625, + "speedup": 51.59829292546096, + "max_abs_diff": 0.0, + "match_mismatches": 0 + }, + { + "case": "BinnedEmbeddingSimilarity precision=float64", + "shape": [ + 1024, + 1024 + ], + "cpu_s": 0.09480072697624564, + "gpu_s": 0.05628065700875595, + "process_peak_mib": 9384.0, + "torch_peak_allocated_mib": 16.984375, + "speedup": 1.6844282212536514, + "max_abs_diff": 2.4424906541753444e-15, + "match_mismatches": null + }, + { + "case": "BinnedEmbeddingSimilarity precision=float32", + "shape": [ + 1024, + 1024 + ], + "cpu_s": 0.09711063001304865, + "gpu_s": 0.03480804999708198, + "process_peak_mib": 9384.0, + "torch_peak_allocated_mib": 12.5546875, + "speedup": 2.7898899829547936, + "max_abs_diff": 3.5743322357451035e-07, + "match_mismatches": null + }, + { + "case": "FingerprintSimilarity similarity_measure=tanimoto", + "shape": [ + 1024, + 1024 + ], + "cpu_s": 0.08943320502294227, + "gpu_s": 0.015734025015262887, + "process_peak_mib": 9404.0, + "torch_peak_allocated_mib": 17.12548828125, + "speedup": 5.684063991012284, + "max_abs_diff": 2.9556022185239783e-08, + "match_mismatches": null + }, + { + "case": "FingerprintSimilarity similarity_measure=cosine", + "shape": [ + 1024, + 1024 + ], + "cpu_s": 0.01899832600611262, + "gpu_s": 0.02162904100259766, + "process_peak_mib": 9404.0, + "torch_peak_allocated_mib": 17.6875, + "speedup": 0.878371167904805, + "max_abs_diff": 1.1920928955078125e-07, + "match_mismatches": null + } + ], + "torch_demo": { + "shape": [ + 2, + 4096, + 2048 + ], + "pairs_per_s": 11415144.244765814, + "gpu_s": 0.734866579005029, + "process_peak_mib": 9532.0, + "torch_peak_allocated_mib": 137.361328125 + } + }, + "matchms_vram_scope": "process (NVML local PID)", + "transitive_alignment": { + "spectra": 1024, + "gpu": "NVIDIA A100-SXM4-80GB", + "direct_edges": 77, + "reachable_non_edges": 176, + "new_transitive_edges": 176, + "new_edges_with_zero_direct_score": 0, + "new_edges_with_increased_score": 104, + "exact_parity": true, + "cold_gpu_s": 3.3174885959888343, + "cold_cpu_s": 33.69443897198653, + "warm_gpu_s": 0.09747353600687347, + "warm_cpu_s": 32.968530187004944, + "warm_speedup": 338.23057557571445 + }, + "scaling": { + "eligible": 9977, + "memory_scope": "process (NVML local PID)", + "batch_size": 256, + "min_score": 0.7, + "rows": [ + { + "method": "CudaCosineGreedy", + "output": "torch", + "shape": [ + 4096, + 2048 + ], + "reference_slice": [ + 0, + 4096 + ], + "query_slice": [ + 4096, + 6144 + ], + "pairs": 8388608, + "pairs_per_s": 11222570.531271994, + "at_or_above_threshold": 8155, + "gpu_s": 0.747476523014484, + "process_peak_mib": 9502.0, + "torch_peak_allocated_mib": 137.361328125 + }, + { + "method": "CudaCosineGreedy", + "output": "sparse", + "shape": [ + 4096, + 2048 + ], + "reference_slice": [ + 0, + 4096 + ], + "query_slice": [ + 4096, + 6144 + ], + "pairs": 8388608, + "pairs_per_s": 11110436.250718992, + "at_or_above_threshold": 8155, + "gpu_s": 0.7550205780135002, + "process_peak_mib": 9566.0, + "torch_peak_allocated_mib": 9.42529296875 + }, + { + "method": "CudaModifiedCosineGreedy", + "output": "torch", + "shape": [ + 4096, + 2048 + ], + "reference_slice": [ + 0, + 4096 + ], + "query_slice": [ + 4096, + 6144 + ], + "pairs": 8388608, + "pairs_per_s": 10785367.658372134, + "at_or_above_threshold": 15046, + "gpu_s": 0.7777767310035415, + "process_peak_mib": 9566.0, + "torch_peak_allocated_mib": 137.361328125 + }, + { + "method": "CudaModifiedCosineGreedy", + "output": "sparse", + "shape": [ + 4096, + 2048 + ], + "reference_slice": [ + 0, + 4096 + ], + "query_slice": [ + 4096, + 6144 + ], + "pairs": 8388608, + "pairs_per_s": 10597738.687579973, + "at_or_above_threshold": 15046, + "gpu_s": 0.7915469750005286, + "process_peak_mib": 9568.0, + "torch_peak_allocated_mib": 9.4267578125 + }, + { + "method": "CudaEntropyGreedy", + "output": "torch", + "shape": [ + 4096, + 2048 + ], + "reference_slice": [ + 0, + 4096 + ], + "query_slice": [ + 4096, + 6144 + ], + "pairs": 8388608, + "pairs_per_s": 24512981.241665296, + "at_or_above_threshold": 3108, + "gpu_s": 0.34221084401360713, + "process_peak_mib": 9568.0, + "torch_peak_allocated_mib": 65.38330078125 + }, + { + "method": "CudaEntropyGreedy", + "output": "sparse", + "shape": [ + 4096, + 2048 + ], + "reference_slice": [ + 0, + 4096 + ], + "query_slice": [ + 4096, + 6144 + ], + "pairs": 8388608, + "pairs_per_s": 22220864.615189448, + "at_or_above_threshold": 3108, + "gpu_s": 0.3775104229862336, + "process_peak_mib": 9568.0, + "torch_peak_allocated_mib": 1.44677734375 + }, + { + "method": "CudaCosineLinear", + "output": "torch", + "shape": [ + 4096, + 2048 + ], + "reference_slice": [ + 0, + 4096 + ], + "query_slice": [ + 4096, + 6144 + ], + "pairs": 8388608, + "pairs_per_s": 36420513.89543544, + "at_or_above_threshold": 6800, + "gpu_s": 0.23032645898638293, + "process_peak_mib": 9568.0, + "torch_peak_allocated_mib": 130.2470703125 + }, + { + "method": "CudaCosineLinear", + "output": "sparse", + "shape": [ + 4096, + 2048 + ], + "reference_slice": [ + 0, + 4096 + ], + "query_slice": [ + 4096, + 6144 + ], + "pairs": 8388608, + "pairs_per_s": 31482861.36128452, + "at_or_above_threshold": 6800, + "gpu_s": 0.26644998698611744, + "process_peak_mib": 9568.0, + "torch_peak_allocated_mib": 2.31201171875 + }, + { + "method": "CudaCosineGreedy", + "output": "torch", + "shape": [ + 9000, + 2048 + ], + "reference_slice": [ + 0, + 9000 + ], + "query_slice": [ + 7929, + 9977 + ], + "pairs": 18432000, + "pairs_per_s": 11272146.396393592, + "at_or_above_threshold": 21787, + "gpu_s": 1.6351810340129305, + "process_peak_mib": 10132.0, + "torch_peak_allocated_mib": 579.0751953125 + }, + { + "method": "CudaCosineGreedy", + "output": "sparse", + "shape": [ + 9000, + 2048 + ], + "reference_slice": [ + 0, + 9000 + ], + "query_slice": [ + 7929, + 9977 + ], + "pairs": 18432000, + "pairs_per_s": 11018566.444618125, + "at_or_above_threshold": 21787, + "gpu_s": 1.6728128920076415, + "process_peak_mib": 10274.0, + "torch_peak_allocated_mib": 579.14013671875 + }, + { + "method": "CudaModifiedCosineGreedy", + "output": "torch", + "shape": [ + 9000, + 2048 + ], + "reference_slice": [ + 0, + 9000 + ], + "query_slice": [ + 7929, + 9977 + ], + "pairs": 18432000, + "pairs_per_s": 10684244.115392216, + "at_or_above_threshold": 36556, + "gpu_s": 1.7251571380184032, + "process_peak_mib": 10556.0, + "torch_peak_allocated_mib": 861.0751953125 + }, + { + "method": "CudaModifiedCosineGreedy", + "output": "sparse", + "shape": [ + 9000, + 2048 + ], + "reference_slice": [ + 0, + 9000 + ], + "query_slice": [ + 7929, + 9977 + ], + "pairs": 18432000, + "pairs_per_s": 10612805.878463188, + "at_or_above_threshold": 36556, + "gpu_s": 1.7367697299923748, + "process_peak_mib": 10556.0, + "torch_peak_allocated_mib": 579.140625 + }, + { + "method": "CudaEntropyGreedy", + "output": "torch", + "shape": [ + 9000, + 2048 + ], + "reference_slice": [ + 0, + 9000 + ], + "query_slice": [ + 7929, + 9977 + ], + "pairs": 18432000, + "pairs_per_s": 25594402.362261925, + "at_or_above_threshold": 9583, + "gpu_s": 0.7201574679929763, + "process_peak_mib": 10556.0, + "torch_peak_allocated_mib": 709.90087890625 + }, + { + "method": "CudaEntropyGreedy", + "output": "sparse", + "shape": [ + 9000, + 2048 + ], + "reference_slice": [ + 0, + 9000 + ], + "query_slice": [ + 7929, + 9977 + ], + "pairs": 18432000, + "pairs_per_s": 24315868.09747232, + "at_or_above_threshold": 9583, + "gpu_s": 0.7580235229979735, + "process_peak_mib": 10556.0, + "torch_peak_allocated_mib": 569.33935546875 + }, + { + "method": "CudaCosineLinear", + "output": "torch", + "shape": [ + 9000, + 2048 + ], + "reference_slice": [ + 0, + 9000 + ], + "query_slice": [ + 7929, + 9977 + ], + "pairs": 18432000, + "pairs_per_s": 38037140.81423875, + "at_or_above_threshold": 18559, + "gpu_s": 0.4845790089748334, + "process_peak_mib": 10556.0, + "torch_peak_allocated_mib": 852.14453125 + }, + { + "method": "CudaCosineLinear", + "output": "sparse", + "shape": [ + 9000, + 2048 + ], + "reference_slice": [ + 0, + 9000 + ], + "query_slice": [ + 7929, + 9977 + ], + "pairs": 18432000, + "pairs_per_s": 33934717.76667468, + "at_or_above_threshold": 18559, + "gpu_s": 0.5431605509947985, + "process_peak_mib": 10556.0, + "torch_peak_allocated_mib": 570.20947265625 + } + ] + }, + "reproduction": { + "input": "GNPS-random-10k.mgf; nonempty peaks and finite positive precursor_mz in file order. Slice endpoints are zero-based, end excluded.", + "timing": "One full-shape warm-up followed by one synchronized wall-clock measurement per output. Includes scoring and output construction. Excludes initial PeakArrays packing. NVML sampled at 5 ms; also records peak Torch allocation.", + "uv_version": "0.12.5", + "scripts": { + "remote.sh": "set -euo pipefail\nexport DEBIAN_FRONTEND=noninteractive\nexport NUMBA_CUDA_LOW_OCCUPANCY_WARNINGS=0\nexport UV_PYTHON_INSTALL_DIR=/opt/simms-python UV_NO_PROGRESS=1 UV_LINK_MODE=copy\nunset NUMBA_ENABLE_CUDASIM PYTHONPATH\nexport OMP_NUM_THREADS=8 OPENBLAS_NUM_THREADS=8 MKL_NUM_THREADS=8 NUMBA_NUM_THREADS=8 RAYON_NUM_THREADS=8\nmkdir -p results\nnvidia-smi > results/nvidia-smi.txt\nnvidia-smi --query-gpu=name,driver_version,memory.total,compute_cap --format=csv,noheader > results/gpu.csv\nlscpu > results/lscpu.txt\nnproc > results/nproc.txt\ncat /sys/fs/cgroup/cpu.max > results/cpu-max.txt || true\nif ! dpkg -s libxrender1 libxext6 libgomp1 curl ca-certificates >/dev/null 2>&1; then\n apt-get -qq update\n apt-get -qq install -y libxrender1 libxext6 libgomp1 curl ca-certificates\nfi\n./uv venv --python 3.12 --managed-python /opt/simms-venv\nsource /opt/simms-venv/bin/activate\ntorch=2.15.0\nif [[ $1 = cu12 ]]; then torch=2.10.0; fi\n./uv pip install --no-cache --python \"$VIRTUAL_ENV/bin/python\" \"simms_gpu-1.0.0-py3-none-any.whl[$1,fingerprints]\" \"torch==$torch\" matchms==1.0.0 pytest nvidia-ml-py\n./uv pip freeze --python \"$VIRTUAL_ENV/bin/python\" > results/freeze.txt\npython -c 'import torch,sys; assert torch.cuda.is_available() and torch.version.cuda.split(\".\")[0]==sys.argv[1][2:], torch.version.cuda' \"$1\"\npython -I .github/scripts/smoke_wheel.py 1.0.0 > results/smoke.txt\nsite=$(python -c 'import pathlib,simms; print(pathlib.Path(simms.__file__).parent)')\n# Both configured test roots, with package doctests taken directly from the installed wheel.\npytest -q --junitxml=results/pytest.xml \"$site\" tests > results/pytest.log 2>&1\npython scale.py > results/scale.log 2>&1\npython match.py --output /tmp/bench_matchms.json > results/match.log 2>&1\ncp /tmp/bench_matchms.json results/match.json\npython benchmarks/benchmark_transitive_alignment.py > results/transitive.log 2>&1\n", + "telemetry.py": "\"\"\"Associate the CUDA context with NVML's host PID when running in a PID namespace.\"\"\"\nimport os\nfrom pathlib import Path\nimport pynvml as nv\nimport torch\n\ndef configure():\n nv.nvmlInit()\n before = {nv.nvmlDeviceGetUUID(h): {p.pid for p in nv.nvmlDeviceGetComputeRunningProcesses(h)}\n for i in range(nv.nvmlDeviceGetCount()) for h in [nv.nvmlDeviceGetHandleByIndex(i)]}\n torch.zeros(1, device=\"cuda\")\n torch.cuda.synchronize()\n uuid = str(torch.cuda.get_device_properties(0).uuid)\n h = nv.nvmlDeviceGetHandleByUUID(uuid)\n query = nv.nvmlDeviceGetComputeRunningProcesses\n procs = query(h)\n host_ids = {p.pid for p in procs}\n if os.getpid() in host_ids:\n return \"process (NVML local PID)\"\n new = host_ids - before.get(nv.nvmlDeviceGetUUID(h), set())\n if len(new) != 1:\n raise RuntimeError(f\"Cannot identify benchmark CUDA process in NVML: before={before}, after={host_ids}\")\n pid = new.pop()\n def namespaced(handle):\n records = query(handle)\n for p in records:\n if p.pid == pid:\n p.pid = os.getpid()\n return records\n nv.nvmlDeviceGetComputeRunningProcesses = namespaced\n return \"process (NVML host PID identified by new CUDA context)\"\n", + "match.py": "import sys\nfrom pathlib import Path\nfrom telemetry import configure\nPath('results/match-telemetry.txt').write_text(configure())\nsys.path.insert(0,'benchmarks')\nimport benchmark_matchms\nbenchmark_matchms.main()\n", + "scale.py": "import gc\nimport json\nimport logging\nfrom pathlib import Path\nimport sys\nfrom telemetry import configure\nmemory_scope = configure()\nsys.path.insert(0, 'benchmarks')\nimport benchmark_matchms as bench\nfrom simms import PeakArrays, similarity\nimport numpy as np\n\nlogging.getLogger(\"matchms\").setLevel(logging.ERROR)\nrows = [s for s in bench.load_from_mgf('data/downloads/GNPS-random-10k.mgf')\n if len(s.peaks) and np.isfinite(s.get('precursor_mz') or 0) and (s.get('precursor_mz') or 0)>0]\nreport = dict(eligible=len(rows), memory_scope=memory_scope, batch_size=256, min_score=0.7, rows=[])\nfor nr in (4096, 9000):\n nc = 2048\n qs = min(nr, len(rows)-nc)\n left = PeakArrays.from_spectra(rows[:nr], require_precursor=True)\n right = PeakArrays.from_spectra(rows[qs:qs+nc], require_precursor=True)\n assert (len(left),len(right))==(nr,nc)\n for name in ('CudaCosineGreedy','CudaModifiedCosineGreedy','CudaEntropyGreedy','CudaCosineLinear'):\n method = getattr(similarity,name)(batch_size=256)\n for mode in ('torch','sparse'):\n if mode == 'torch':\n call = lambda: method.matrix(left,right,array_type='torch',progress_bar=False)\n else:\n call = lambda: method.sparse_matrix(left,right,min_score=0.7,progress_bar=False)\n output, stats = bench.measure_gpu(call)\n if mode == 'torch':\n assert output.is_cuda and tuple(output.shape[-2:])==(nr,nc)\n scores = output if output.ndim==2 else output[0]\n count = (scores>=0.7).count_nonzero().item()\n del scores\n else:\n coo = output.to_coo('score')\n assert coo.shape == (nr,nc) and coo.nnz == count and (coo.data>=0.7).all()\n del coo\n del output\n row = dict(method=name, output=mode, shape=[nr,nc], reference_slice=[0,nr], query_slice=[qs,qs+nc],\n pairs=nr*nc,pairs_per_s=nr*nc/stats['gpu_s'],at_or_above_threshold=count,**stats)\n report['rows'].append(row)\n Path('results/scaling.json').write_text(json.dumps(report,indent=2,allow_nan=False)+'\\n')\n print(json.dumps(row),flush=True)\n del left, right\n gc.collect()\n" + }, + "scaling_instructions": [ + "Use the recorded Git commit, wheel, Python 3.12 and dependency versions. Start in the checkout with the installed wheel environment active. The validation runner measured outside the source tree.", + "Put the GNPS-random-10k.mgf file under data/downloads and verify its SHA-256 against matchms.sha256. simms.utils.download(\"GNPS-random-10k.mgf\") retrieves the public copy.", + "Extract reproduction.scripts[\"scale.py\"] and [\"telemetry.py\"] as files of those names in the same temporary directory. Keep the repository root as the current working directory so the script finds benchmarks/benchmark_matchms.py and data/downloads.", + "Create results/ and set NUMBA_CUDA_LOW_OCCUPANCY_WARNINGS=0 plus OMP_NUM_THREADS, OPENBLAS_NUM_THREADS, MKL_NUM_THREADS, NUMBA_NUM_THREADS and RAYON_NUM_THREADS to 8. Run python /path/to/scale.py. It writes results/scaling.json." + ] + } +} diff --git a/benchmarks/vast_rtx_4090.json b/benchmarks/vast_rtx_4090.json new file mode 100644 index 0000000..e888bf9 --- /dev/null +++ b/benchmarks/vast_rtx_4090.json @@ -0,0 +1,795 @@ +{ + "gpu": "NVIDIA GeForce RTX 4090", + "extras": [ + "cu12", + "fingerprints" + ], + "wheel_sha256": "f56bbc33b66ac9c77ed33332a179e426f3bbbe9b74224351b03aecf617087022", + "git_commit": "720403d56a736bcf135113f9c87b6d3095a1fb51", + "instance_id": 63729062, + "offer": { + "id": 60966531, + "gpu_name": "RTX 4090", + "cuda_max_good": 13.3, + "gpu_ram": 24564, + "machine_id": 150328, + "dph_total": 0.46, + "inet_down_cost": 0.011999999999999999, + "inet_up_cost": 0.011999999999999999, + "inet_down": 10627.8, + "cpu_cores_effective": 32.0, + "direct_port_count": 98, + "verification": "verified", + "reliability2": 0.9971658, + "geolocation": "California, US" + }, + "run_utc": "2026-12-02T17:33:03.355674+00:00", + "hardware": { + "gpu": "NVIDIA GeForce RTX 4090", + "architecture": "Ada Lovelace", + "compute_capability": "8.9", + "vram_mib": 24564, + "driver": "610.57.04", + "driver_cuda": "13.3", + "cpu_model": "AMD EPYC 9474F 48-Core Processor", + "visible_sockets": 1, + "visible_cores_per_socket": 32, + "visible_threads_per_core": 1, + "visible_logical_cpus": 32, + "benchmark_cpu_affinity": 32, + "cgroup_cpu_quota_cores": 30.71999 + }, + "wheel_smoke": [ + "CudaCosineGreedy: [1.0, 2.0] (cuda:0)", + "CudaModifiedCosineGreedy: [1.0, 2.0] (cuda:0)", + "CudaNeutralLossesCosine: [1.0, 2.0] (cuda:0)", + "CudaEntropyGreedy: [1.0] (cuda:0)", + "CudaCosineLinear: [1.0, 2.0] (cuda:0)", + "CudaModifiedCosineLinear: [1.0, 2.0] (cuda:0)", + "CudaBinnedEmbeddingSimilarity: [1.0] (cuda:0)", + "CudaFingerprintSimilarity: [1.0] (cuda:0)", + "CudaTransitiveAlignment: one symmetric direct edge", + "simms-gpu 1.0.0 from /opt/simms-venv/lib/python3.12/site-packages/simms/__init__.py" + ], + "pytest": { + "tests": 341, + "failures": 0, + "errors": 0, + "skipped": 0, + "passed": 341, + "warnings": 8, + "seconds": 78.02 + }, + "packages": [ + "anyio==4.16.0", + "certifi==2026.11.20", + "charset-normalizer==3.5.3", + "chemap==0.3.9", + "click==8.5.1", + "cloudpickle==3.1.3", + "contourpy==1.4.0", + "cuda-bindings==12.9.4", + "cuda-core==1.2.2", + "cuda-pathfinder==1.9.1", + "cuda-toolkit==12.8.2.0", + "cycler==0.12.1", + "deprecated==3.0.1", + "descriptastorus==2.8.0", + "e3fp==1.2.7", + "filelock==4.3.2", + "fonttools==4.69.1", + "fsspec==2026.9.0", + "h11==0.16.0", + "hf-xet==1.8.0", + "httpcore==1.0.9", + "httpx==0.29.0", + "huggingface-hub==1.33.0", + "idna==3.20", + "iniconfig==2.3.1", + "jinja2==3.1.6", + "joblib==1.6.0", + "kiwisolver==1.5.1", + "llvmlite==0.50.0", + "lxml==6.2.1", + "markupsafe==3.0.4", + "matchms==1.0.0", + "matplotlib==3.11.2", + "mmh3==5.3.1", + "mordredcommunity==2.1.0", + "mpmath==1.3.0", + "narwhals==2.30.0", + "networkx==3.7", + "numba==0.68.1", + "numba-cuda==0.30.4", + "numpy==2.4.6", + "nvidia-cublas-cu12==12.8.4.1", + "nvidia-cuda-cccl-cu12==12.8.90", + "nvidia-cuda-cupti-cu12==12.8.90", + "nvidia-cuda-nvcc-cu12==12.8.93", + "nvidia-cuda-nvrtc-cu12==12.8.93", + "nvidia-cuda-runtime-cu12==12.8.90", + "nvidia-cudnn-cu12==9.10.2.21", + "nvidia-cufft-cu12==11.3.3.83", + "nvidia-cufile-cu12==1.13.1.3", + "nvidia-curand-cu12==10.3.9.90", + "nvidia-cusolver-cu12==11.7.3.90", + "nvidia-cusparse-cu12==12.5.8.93", + "nvidia-cusparselt-cu12==0.7.1", + "nvidia-ml-py==13.615.71", + "nvidia-nccl-cu12==2.27.5", + "nvidia-nvjitlink-cu12==12.8.93", + "nvidia-nvshmem-cu12==3.4.5", + "nvidia-nvtx-cu12==12.8.90", + "packaging==26.4", + "pandas==3.1.2", + "pandas-flavor==0.8.1", + "pickydict==0.5.0", + "pillow==13.0.0", + "platformdirs==4.14.9", + "pluggy==1.7.0", + "pooch==1.9.0", + "psims==1.4.0", + "pubchempy==1.0.5", + "pyarrow==26.0.0", + "pygments==2.21.0", + "pynndescent==0.8.0", + "pyparsing==3.3.3", + "pyteomics==5.0.2", + "pytest==9.2.0", + "python-dateutil==4.0.0", + "pyyaml==6.0.4", + "rdkit==2026.3.5", + "requests==2.34.2", + "scikit-fingerprints==2.1.0", + "scikit-learn==1.9.1", + "scipy==1.18.1", + "sdaxen-python-utilities==0.1.5", + "setuptools==84.2.1", + "simms-gpu @ file:///opt/simms-job/simms_gpu-1.0.0-py3-none-any.whl", + "six==1.17.0", + "smart-open==10.0.1", + "sqlalchemy==2.1.9", + "sympy==1.14.0", + "threadpoolctl==3.8.0", + "torch==2.10.0", + "tqdm==4.70.1", + "triton==3.6.0", + "typing-extensions==4.16.0", + "tzdata==2026.6", + "urllib3==2.8.0", + "wrapt==2.5.2", + "xarray==2026.9.0" + ], + "matchms": { + "dataset": "GNPS-random-10k.mgf", + "sha256": "b501344f2d6bdbf7723c89af1c175e346e8ea849bb397a0142d6120769a8e054", + "eligible": 9977, + "python": "3.12.14", + "cpu": "AMD EPYC 9474F 48-Core Processor", + "cuda": "12.8", + "driver": "610.57.04", + "gpu": "NVIDIA GeForce RTX 4090", + "cpu_affinity": 32, + "packages": { + "simms-gpu": "1.0.0", + "matchms": "1.0.0", + "numpy": "2.4.6", + "torch": "2.10.0", + "numba": "0.68.1", + "numba-cuda": "0.30.4", + "chemap": "0.3.9", + "rdkit": "2026.3.5", + "nvidia-ml-py": "13.615.71" + }, + "threadpools": [ + [ + "openblas", + 8 + ], + [ + "openblas", + 8 + ], + [ + "openmp", + 8 + ], + [ + "openmp", + 8 + ] + ], + "rows": [ + { + "case": "CosineGreedy", + "shape": [ + 1024, + 1024 + ], + "cpu_s": 31.509252567775548, + "gpu_s": 0.13458740431815386, + "process_peak_mib": 8352.0, + "torch_peak_allocated_mib": 8.572265625, + "speedup": 234.11739551266027, + "max_abs_diff": 0.0, + "match_mismatches": 0, + "flash_cpu_s": 0.06214970629662275 + }, + { + "case": "CosineGreedy tolerance=0.5", + "shape": [ + 1024, + 1024 + ], + "cpu_s": 33.883085718844086, + "gpu_s": 0.1682257759384811, + "process_peak_mib": 8352.0, + "torch_peak_allocated_mib": 8.572265625, + "speedup": 201.41435240717735, + "max_abs_diff": 0.0, + "match_mismatches": 0, + "flash_cpu_s": 0.06427349196746945 + }, + { + "case": "CosineGreedy tolerance=0.5 mz_power=1.0", + "shape": [ + 1024, + 1024 + ], + "cpu_s": 34.631082301959395, + "gpu_s": 0.1667250068858266, + "process_peak_mib": 8352.0, + "torch_peak_allocated_mib": 8.572265625, + "speedup": 207.71378540517793, + "max_abs_diff": 0.0, + "match_mismatches": 0 + }, + { + "case": "ModifiedCosineGreedy", + "shape": [ + 1024, + 1024 + ], + "cpu_s": 35.18238222133368, + "gpu_s": 0.13648531818762422, + "process_peak_mib": 8352.0, + "torch_peak_allocated_mib": 8.572265625, + "speedup": 257.7741158427679, + "max_abs_diff": 0.0, + "match_mismatches": 0 + }, + { + "case": "NeutralLossesCosine", + "shape": [ + 1024, + 1024 + ], + "cpu_s": 30.816935922950506, + "gpu_s": 0.1301421271637082, + "process_peak_mib": 8352.0, + "torch_peak_allocated_mib": 8.572265625, + "speedup": 236.79446920508153, + "max_abs_diff": 0.0, + "match_mismatches": 0 + }, + { + "case": "EntropyGreedy matching_mode=fragment", + "shape": [ + 1024, + 1024 + ], + "cpu_s": 69.27096132002771, + "gpu_s": 0.0770661192946136, + "process_peak_mib": 8352.0, + "torch_peak_allocated_mib": 1.349609375, + "speedup": 898.8510379666837, + "max_abs_diff": 4.440892098500626e-16, + "match_mismatches": null, + "flash_cpu_s": 0.05968586727976799 + }, + { + "case": "EntropyGreedy matching_mode=hybrid", + "shape": [ + 1024, + 1024 + ], + "cpu_s": 85.9190179030411, + "gpu_s": 0.08774810191243887, + "process_peak_mib": 8352.0, + "torch_peak_allocated_mib": 1.349609375, + "speedup": 979.1552869004169, + "max_abs_diff": 4.440892098500626e-16, + "match_mismatches": null, + "flash_cpu_s": 0.06312591210007668 + }, + { + "case": "CosineLinear", + "shape": [ + 1024, + 1024 + ], + "cpu_s": 3.068834532983601, + "gpu_s": 0.057373736053705215, + "process_peak_mib": 8352.0, + "torch_peak_allocated_mib": 2.2353515625, + "speedup": 53.488490449898364, + "max_abs_diff": 0.0, + "match_mismatches": 0 + }, + { + "case": "ModifiedCosineLinear", + "shape": [ + 1024, + 1024 + ], + "cpu_s": 3.5919368979521096, + "gpu_s": 0.06994923204183578, + "process_peak_mib": 8352.0, + "torch_peak_allocated_mib": 2.228515625, + "speedup": 51.350626634525675, + "max_abs_diff": 0.0, + "match_mismatches": 0 + }, + { + "case": "BinnedEmbeddingSimilarity precision=float64", + "shape": [ + 1024, + 1024 + ], + "cpu_s": 0.06054115667939186, + "gpu_s": 0.03850969020277262, + "process_peak_mib": 8362.0, + "torch_peak_allocated_mib": 17.0703125, + "speedup": 1.5721018881380933, + "max_abs_diff": 2.4424906541753444e-15, + "match_mismatches": null + }, + { + "case": "BinnedEmbeddingSimilarity precision=float32", + "shape": [ + 1024, + 1024 + ], + "cpu_s": 0.06300007086247206, + "gpu_s": 0.02722752606496215, + "process_peak_mib": 8362.0, + "torch_peak_allocated_mib": 12.5546875, + "speedup": 2.313837500776244, + "max_abs_diff": 2.6375946171608433e-07, + "match_mismatches": null + }, + { + "case": "FingerprintSimilarity similarity_measure=tanimoto", + "shape": [ + 1024, + 1024 + ], + "cpu_s": 0.06736777210608125, + "gpu_s": 0.025120906997472048, + "process_peak_mib": 8382.0, + "torch_peak_allocated_mib": 20.640625, + "speedup": 2.681741233023973, + "max_abs_diff": 2.9556022185239783e-08, + "match_mismatches": null + }, + { + "case": "FingerprintSimilarity similarity_measure=cosine", + "shape": [ + 1024, + 1024 + ], + "cpu_s": 0.020421199966222048, + "gpu_s": 0.024343565572053194, + "process_peak_mib": 8382.0, + "torch_peak_allocated_mib": 20.640625, + "speedup": 0.8388746465992605, + "max_abs_diff": 1.1920928955078125e-07, + "match_mismatches": null + } + ], + "torch_demo": { + "shape": [ + 2, + 4096, + 2048 + ], + "pairs_per_s": 11302658.830609722, + "gpu_s": 0.7421800591982901, + "process_peak_mib": 8510.0, + "torch_peak_allocated_mib": 145.486328125 + } + }, + "matchms_vram_scope": "process (NVML local PID)", + "transitive_alignment": { + "spectra": 1024, + "gpu": "NVIDIA GeForce RTX 4090", + "direct_edges": 77, + "reachable_non_edges": 176, + "new_transitive_edges": 176, + "new_edges_with_zero_direct_score": 0, + "new_edges_with_increased_score": 104, + "exact_parity": true, + "cold_gpu_s": 2.5826832242310047, + "cold_cpu_s": 19.60321469279006, + "warm_gpu_s": 0.10161387687548995, + "warm_cpu_s": 17.465366647578776, + "warm_speedup": 171.8797391125971 + }, + "scaling": { + "eligible": 9977, + "memory_scope": "process (NVML local PID)", + "batch_size": 256, + "min_score": 0.7, + "rows": [ + { + "method": "CudaCosineGreedy", + "output": "torch", + "shape": [ + 4096, + 2048 + ], + "reference_slice": [ + 0, + 4096 + ], + "query_slice": [ + 4096, + 6144 + ], + "pairs": 8388608, + "pairs_per_s": 11241237.253143584, + "at_or_above_threshold": 8155, + "gpu_s": 0.7462352951988578, + "process_peak_mib": 8480.0, + "torch_peak_allocated_mib": 137.361328125 + }, + { + "method": "CudaCosineGreedy", + "output": "sparse", + "shape": [ + 4096, + 2048 + ], + "reference_slice": [ + 0, + 4096 + ], + "query_slice": [ + 4096, + 6144 + ], + "pairs": 8388608, + "pairs_per_s": 11078711.628141193, + "at_or_above_threshold": 8155, + "gpu_s": 0.7571826293133199, + "process_peak_mib": 8544.0, + "torch_peak_allocated_mib": 9.42529296875 + }, + { + "method": "CudaModifiedCosineGreedy", + "output": "torch", + "shape": [ + 4096, + 2048 + ], + "reference_slice": [ + 0, + 4096 + ], + "query_slice": [ + 4096, + 6144 + ], + "pairs": 8388608, + "pairs_per_s": 10799454.718063777, + "at_or_above_threshold": 15046, + "gpu_s": 0.7767621809616685, + "process_peak_mib": 8544.0, + "torch_peak_allocated_mib": 137.361328125 + }, + { + "method": "CudaModifiedCosineGreedy", + "output": "sparse", + "shape": [ + 4096, + 2048 + ], + "reference_slice": [ + 0, + 4096 + ], + "query_slice": [ + 4096, + 6144 + ], + "pairs": 8388608, + "pairs_per_s": 10673808.004867358, + "at_or_above_threshold": 15046, + "gpu_s": 0.7859058356843889, + "process_peak_mib": 8546.0, + "torch_peak_allocated_mib": 9.4267578125 + }, + { + "method": "CudaEntropyGreedy", + "output": "torch", + "shape": [ + 4096, + 2048 + ], + "reference_slice": [ + 0, + 4096 + ], + "query_slice": [ + 4096, + 6144 + ], + "pairs": 8388608, + "pairs_per_s": 34110450.200326264, + "at_or_above_threshold": 3108, + "gpu_s": 0.2459248690865934, + "process_peak_mib": 8546.0, + "torch_peak_allocated_mib": 65.38330078125 + }, + { + "method": "CudaEntropyGreedy", + "output": "sparse", + "shape": [ + 4096, + 2048 + ], + "reference_slice": [ + 0, + 4096 + ], + "query_slice": [ + 4096, + 6144 + ], + "pairs": 8388608, + "pairs_per_s": 31829653.269047286, + "at_or_above_threshold": 3108, + "gpu_s": 0.26354694878682494, + "process_peak_mib": 8546.0, + "torch_peak_allocated_mib": 1.44677734375 + }, + { + "method": "CudaCosineLinear", + "output": "torch", + "shape": [ + 4096, + 2048 + ], + "reference_slice": [ + 0, + 4096 + ], + "query_slice": [ + 4096, + 6144 + ], + "pairs": 8388608, + "pairs_per_s": 54451695.52427418, + "at_or_above_threshold": 6800, + "gpu_s": 0.1540559558197856, + "process_peak_mib": 8546.0, + "torch_peak_allocated_mib": 130.2470703125 + }, + { + "method": "CudaCosineLinear", + "output": "sparse", + "shape": [ + 4096, + 2048 + ], + "reference_slice": [ + 0, + 4096 + ], + "query_slice": [ + 4096, + 6144 + ], + "pairs": 8388608, + "pairs_per_s": 47668128.30914115, + "at_or_above_threshold": 6800, + "gpu_s": 0.1759793870151043, + "process_peak_mib": 8546.0, + "torch_peak_allocated_mib": 2.31201171875 + }, + { + "method": "CudaCosineGreedy", + "output": "torch", + "shape": [ + 9000, + 2048 + ], + "reference_slice": [ + 0, + 9000 + ], + "query_slice": [ + 7929, + 9977 + ], + "pairs": 18432000, + "pairs_per_s": 11042731.040169094, + "at_or_above_threshold": 21787, + "gpu_s": 1.6691523077897727, + "process_peak_mib": 9110.0, + "torch_peak_allocated_mib": 579.0751953125 + }, + { + "method": "CudaCosineGreedy", + "output": "sparse", + "shape": [ + 9000, + 2048 + ], + "reference_slice": [ + 0, + 9000 + ], + "query_slice": [ + 7929, + 9977 + ], + "pairs": 18432000, + "pairs_per_s": 10404686.123690272, + "at_or_above_threshold": 21787, + "gpu_s": 1.7715094699524343, + "process_peak_mib": 9252.0, + "torch_peak_allocated_mib": 579.14013671875 + }, + { + "method": "CudaModifiedCosineGreedy", + "output": "torch", + "shape": [ + 9000, + 2048 + ], + "reference_slice": [ + 0, + 9000 + ], + "query_slice": [ + 7929, + 9977 + ], + "pairs": 18432000, + "pairs_per_s": 10048001.378133979, + "at_or_above_threshold": 36556, + "gpu_s": 1.8343946528621018, + "process_peak_mib": 9534.0, + "torch_peak_allocated_mib": 861.0751953125 + }, + { + "method": "CudaModifiedCosineGreedy", + "output": "sparse", + "shape": [ + 9000, + 2048 + ], + "reference_slice": [ + 0, + 9000 + ], + "query_slice": [ + 7929, + 9977 + ], + "pairs": 18432000, + "pairs_per_s": 9865631.637730252, + "at_or_above_threshold": 36556, + "gpu_s": 1.8683040961623192, + "process_peak_mib": 9534.0, + "torch_peak_allocated_mib": 579.140625 + }, + { + "method": "CudaEntropyGreedy", + "output": "torch", + "shape": [ + 9000, + 2048 + ], + "reference_slice": [ + 0, + 9000 + ], + "query_slice": [ + 7929, + 9977 + ], + "pairs": 18432000, + "pairs_per_s": 37394618.05095515, + "at_or_above_threshold": 9583, + "gpu_s": 0.4929051548242569, + "process_peak_mib": 9534.0, + "torch_peak_allocated_mib": 709.90087890625 + }, + { + "method": "CudaEntropyGreedy", + "output": "sparse", + "shape": [ + 9000, + 2048 + ], + "reference_slice": [ + 0, + 9000 + ], + "query_slice": [ + 7929, + 9977 + ], + "pairs": 18432000, + "pairs_per_s": 34666449.53956204, + "at_or_above_threshold": 9583, + "gpu_s": 0.5316956378519535, + "process_peak_mib": 9534.0, + "torch_peak_allocated_mib": 569.33935546875 + }, + { + "method": "CudaCosineLinear", + "output": "torch", + "shape": [ + 9000, + 2048 + ], + "reference_slice": [ + 0, + 9000 + ], + "query_slice": [ + 7929, + 9977 + ], + "pairs": 18432000, + "pairs_per_s": 57962516.41095044, + "at_or_above_threshold": 18559, + "gpu_s": 0.3179986160248518, + "process_peak_mib": 9534.0, + "torch_peak_allocated_mib": 852.14453125 + }, + { + "method": "CudaCosineLinear", + "output": "sparse", + "shape": [ + 9000, + 2048 + ], + "reference_slice": [ + 0, + 9000 + ], + "query_slice": [ + 7929, + 9977 + ], + "pairs": 18432000, + "pairs_per_s": 50709855.393881425, + "at_or_above_threshold": 18559, + "gpu_s": 0.3634796403348446, + "process_peak_mib": 9534.0, + "torch_peak_allocated_mib": 570.20947265625 + } + ] + }, + "reproduction": { + "input": "GNPS-random-10k.mgf; nonempty peaks and finite positive precursor_mz in file order. Slice endpoints are zero-based, end excluded.", + "timing": "One full-shape warm-up followed by one synchronized wall-clock measurement per output. Includes scoring and output construction. Excludes initial PeakArrays packing. NVML sampled at 5 ms; also records peak Torch allocation.", + "uv_version": "0.12.5", + "scripts": { + "remote.sh": "set -euo pipefail\nexport DEBIAN_FRONTEND=noninteractive\nexport NUMBA_CUDA_LOW_OCCUPANCY_WARNINGS=0\nexport UV_PYTHON_INSTALL_DIR=/opt/simms-python UV_NO_PROGRESS=1 UV_LINK_MODE=copy\nunset NUMBA_ENABLE_CUDASIM PYTHONPATH\nexport OMP_NUM_THREADS=8 OPENBLAS_NUM_THREADS=8 MKL_NUM_THREADS=8 NUMBA_NUM_THREADS=8 RAYON_NUM_THREADS=8\nmkdir -p results\nnvidia-smi > results/nvidia-smi.txt\nnvidia-smi --query-gpu=name,driver_version,memory.total,compute_cap --format=csv,noheader > results/gpu.csv\nlscpu > results/lscpu.txt\nnproc > results/nproc.txt\ncat /sys/fs/cgroup/cpu.max > results/cpu-max.txt || true\nif ! dpkg -s libxrender1 libxext6 libgomp1 curl ca-certificates >/dev/null 2>&1; then\n apt-get -qq update\n apt-get -qq install -y libxrender1 libxext6 libgomp1 curl ca-certificates\nfi\n./uv venv --python 3.12 --managed-python /opt/simms-venv\nsource /opt/simms-venv/bin/activate\ntorch=2.15.0\nif [[ $1 = cu12 ]]; then torch=2.10.0; fi\n./uv pip install --no-cache --python \"$VIRTUAL_ENV/bin/python\" \"simms_gpu-1.0.0-py3-none-any.whl[$1,fingerprints]\" \"torch==$torch\" matchms==1.0.0 pytest nvidia-ml-py\n./uv pip freeze --python \"$VIRTUAL_ENV/bin/python\" > results/freeze.txt\npython -c 'import torch,sys; assert torch.cuda.is_available() and torch.version.cuda.split(\".\")[0]==sys.argv[1][2:], torch.version.cuda' \"$1\"\npython -I .github/scripts/smoke_wheel.py 1.0.0 > results/smoke.txt\nsite=$(python -c 'import pathlib,simms; print(pathlib.Path(simms.__file__).parent)')\n# Both configured test roots, with package doctests taken directly from the installed wheel.\npytest -q --junitxml=results/pytest.xml \"$site\" tests > results/pytest.log 2>&1\npython scale.py > results/scale.log 2>&1\npython match.py --output /tmp/bench_matchms.json > results/match.log 2>&1\ncp /tmp/bench_matchms.json results/match.json\npython benchmarks/benchmark_transitive_alignment.py > results/transitive.log 2>&1\n", + "telemetry.py": "\"\"\"Associate the CUDA context with NVML's host PID when running in a PID namespace.\"\"\"\nimport os\nfrom pathlib import Path\nimport pynvml as nv\nimport torch\n\ndef configure():\n nv.nvmlInit()\n before = {nv.nvmlDeviceGetUUID(h): {p.pid for p in nv.nvmlDeviceGetComputeRunningProcesses(h)}\n for i in range(nv.nvmlDeviceGetCount()) for h in [nv.nvmlDeviceGetHandleByIndex(i)]}\n torch.zeros(1, device=\"cuda\")\n torch.cuda.synchronize()\n uuid = str(torch.cuda.get_device_properties(0).uuid)\n h = nv.nvmlDeviceGetHandleByUUID(uuid)\n query = nv.nvmlDeviceGetComputeRunningProcesses\n procs = query(h)\n host_ids = {p.pid for p in procs}\n if os.getpid() in host_ids:\n return \"process (NVML local PID)\"\n new = host_ids - before.get(nv.nvmlDeviceGetUUID(h), set())\n if len(new) != 1:\n raise RuntimeError(f\"Cannot identify benchmark CUDA process in NVML: before={before}, after={host_ids}\")\n pid = new.pop()\n def namespaced(handle):\n records = query(handle)\n for p in records:\n if p.pid == pid:\n p.pid = os.getpid()\n return records\n nv.nvmlDeviceGetComputeRunningProcesses = namespaced\n return \"process (NVML host PID identified by new CUDA context)\"\n", + "match.py": "import sys\nfrom pathlib import Path\nfrom telemetry import configure\nPath('results/match-telemetry.txt').write_text(configure())\nsys.path.insert(0,'benchmarks')\nimport benchmark_matchms\nbenchmark_matchms.main()\n", + "scale.py": "import gc\nimport json\nimport logging\nfrom pathlib import Path\nimport sys\nfrom telemetry import configure\nmemory_scope = configure()\nsys.path.insert(0, 'benchmarks')\nimport benchmark_matchms as bench\nfrom simms import PeakArrays, similarity\nimport numpy as np\n\nlogging.getLogger(\"matchms\").setLevel(logging.ERROR)\nrows = [s for s in bench.load_from_mgf('data/downloads/GNPS-random-10k.mgf')\n if len(s.peaks) and np.isfinite(s.get('precursor_mz') or 0) and (s.get('precursor_mz') or 0)>0]\nreport = dict(eligible=len(rows), memory_scope=memory_scope, batch_size=256, min_score=0.7, rows=[])\nfor nr in (4096, 9000):\n nc = 2048\n qs = min(nr, len(rows)-nc)\n left = PeakArrays.from_spectra(rows[:nr], require_precursor=True)\n right = PeakArrays.from_spectra(rows[qs:qs+nc], require_precursor=True)\n assert (len(left),len(right))==(nr,nc)\n for name in ('CudaCosineGreedy','CudaModifiedCosineGreedy','CudaEntropyGreedy','CudaCosineLinear'):\n method = getattr(similarity,name)(batch_size=256)\n for mode in ('torch','sparse'):\n if mode == 'torch':\n call = lambda: method.matrix(left,right,array_type='torch',progress_bar=False)\n else:\n call = lambda: method.sparse_matrix(left,right,min_score=0.7,progress_bar=False)\n output, stats = bench.measure_gpu(call)\n if mode == 'torch':\n assert output.is_cuda and tuple(output.shape[-2:])==(nr,nc)\n scores = output if output.ndim==2 else output[0]\n count = (scores>=0.7).count_nonzero().item()\n del scores\n else:\n coo = output.to_coo('score')\n assert coo.shape == (nr,nc) and coo.nnz == count and (coo.data>=0.7).all()\n del coo\n del output\n row = dict(method=name, output=mode, shape=[nr,nc], reference_slice=[0,nr], query_slice=[qs,qs+nc],\n pairs=nr*nc,pairs_per_s=nr*nc/stats['gpu_s'],at_or_above_threshold=count,**stats)\n report['rows'].append(row)\n Path('results/scaling.json').write_text(json.dumps(report,indent=2,allow_nan=False)+'\\n')\n print(json.dumps(row),flush=True)\n del left, right\n gc.collect()\n" + }, + "scaling_instructions": [ + "Use the recorded Git commit, wheel, Python 3.12 and dependency versions. Start in the checkout with the installed wheel environment active. The validation runner measured outside the source tree.", + "Put the GNPS-random-10k.mgf file under data/downloads and verify its SHA-256 against matchms.sha256. simms.utils.download(\"GNPS-random-10k.mgf\") retrieves the public copy.", + "Extract reproduction.scripts[\"scale.py\"] and [\"telemetry.py\"] as files of those names in the same temporary directory. Keep the repository root as the current working directory so the script finds benchmarks/benchmark_matchms.py and data/downloads.", + "Create results/ and set NUMBA_CUDA_LOW_OCCUPANCY_WARNINGS=0 plus OMP_NUM_THREADS, OPENBLAS_NUM_THREADS, MKL_NUM_THREADS, NUMBA_NUM_THREADS and RAYON_NUM_THREADS to 8. Run python /path/to/scale.py. It writes results/scaling.json." + ] + } +} diff --git a/pyproject.toml b/pyproject.toml index 21bb61e..c3a4a76 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,16 +1,20 @@ [project] -name = "simms" -version = "0.0.3a0" +name = "simms-gpu" +version = "1.0.0" description = "Faster Similarity for Mass Spec on GPU" authors = [ {name="Tornike Onoprishvili", email="tornikeonoprishvili@gmail.com"} ] readme = "README.md" license = "MIT" -requires-python = ">=3.8,<3.13" +requires-python = ">=3.11,<3.15" dependencies = [ - "matchms>=0.24", - "torch>=2.0.0", + "matchms>=1.0.0,<2.0.0", + "torch>=2.4.0", + "numba>=0.61", + "numba-cuda>=0.30", + "numpy>=2.0,<2.5", + "scipy>=1.11", "tqdm>=4.66.4", "joblib>=1.4.0", "requests>=2.31.0", @@ -20,7 +24,6 @@ classifiers = [ "Intended Audience :: Education", "Intended Audience :: Science/Research", "Intended Audience :: Developers", - "License :: OSI Approved :: MIT License", "Natural Language :: English", "Programming Language :: Python :: 3", ] @@ -32,17 +35,22 @@ keywords = [ "CUDA", ] +[project.optional-dependencies] +cu12 = ["numba-cuda[cu12]>=0.30", "cuda-core<1.3"] +cu13 = ["numba-cuda[cu13]>=0.30", "torch>=2.11"] +fingerprints = ["chemap>=0.3.9"] + [project.urls] homepage = "https://github.com/PangeAI/simms" repository = "https://github.com/PangeAI/simms" "Bug Tracker" = "https://github.com/PangeAI/simms/issues" [build-system] -requires = ["poetry-core>=1.0.0"] +requires = ["poetry-core>=2.0.0"] build-backend = "poetry.core.masonry.api" [tool.poetry] -package-mode = true +packages = [{include = "simms"}] [tool.poetry.group.docs] optional = true diff --git a/simms/__init__.py b/simms/__init__.py index 29fcb27..473d97a 100644 --- a/simms/__init__.py +++ b/simms/__init__.py @@ -1,31 +1,6 @@ -import os -from contextlib import contextmanager from .__version__ import __version__ - - -# Patch cuda.pinned and as_cuda_array before https://github.com/numba/numba/pull/9458 gets merged -if os.getenv("NUMBA_ENABLE_CUDASIM") == "1": - from numba import cuda - - @contextmanager - def fake_cuda_pinned(*arylist): - yield - - def fake_as_cuda_array(obj, sync=True): - return obj - - original_event = cuda.event - - def fake_event(*args, **kwargs): - return original_event() - - cuda.pinned = fake_cuda_pinned - cuda.as_cuda_array = fake_as_cuda_array - cuda.event = fake_event +from .peaks import PeakArrays __author__ = "SimMS developers community" __email__ = "tornikeonoprishvili@gmail.com" -__all__ = [ - "__version__", - "similarity", -] +__all__ = ["__version__", "PeakArrays", "similarity"] diff --git a/simms/__version__.py b/simms/__version__.py index f102a9c..5becc17 100644 --- a/simms/__version__.py +++ b/simms/__version__.py @@ -1 +1 @@ -__version__ = "0.0.1" +__version__ = "1.0.0" diff --git a/simms/peaks.py b/simms/peaks.py new file mode 100644 index 0000000..3a2cae0 --- /dev/null +++ b/simms/peaks.py @@ -0,0 +1,174 @@ +"""Array-native input for spectral similarity scoring.""" + +from collections.abc import Iterable, Mapping +from dataclasses import dataclass + +import numpy as np +from matchms import SpectraCollection +from matchms.similarity.spectrum_similarity_functions import filter_noise, filter_peaks_above_precursor + + +def _check_row(mz, intensities, index): + if mz.ndim != 1 or intensities.shape != mz.shape: + raise ValueError(f"row {index}: mz and intensities must be aligned 1D arrays") + if not (np.isfinite(mz).all() and np.isfinite(intensities).all()): + raise ValueError(f"row {index}: active peaks must be finite") + if np.any(mz[1:] < mz[:-1]): + raise ValueError(f"row {index}: mz must be sorted in non-decreasing order") + + +def _spectrum_rows(spectra): + if isinstance(spectra, PeakArrays): + for i, n in enumerate(spectra.lengths): + precursor = None if spectra.precursor_mz is None else spectra.precursor_mz[i] + yield spectra.mz[i, :n], spectra.intensities[i, :n], precursor + elif isinstance(spectra, SpectraCollection): + fragments = spectra.fragments + csr = fragments.array + mz = fragments.bin_to_mz(csr.indices) + precursors = spectra.metadata.get("precursor_mz") + for i in range(len(spectra)): + row = slice(csr.indptr[i], csr.indptr[i + 1]) + yield mz[row], csr.data[row], None if precursors is None else precursors.iloc[i] + else: + if isinstance(spectra, np.ndarray): + if spectra.ndim != 1 or spectra.dtype != object: + raise TypeError( + "spectra must be a 1D object ndarray of spectra; use PeakArrays for numeric data" + ) + elif not isinstance(spectra, Iterable) or isinstance(spectra, (str, bytes, Mapping)): + raise TypeError("expected an iterable of spectra, SpectraCollection or PeakArrays") + for i, spectrum in enumerate(spectra): + try: + peaks = spectrum.peaks + mz, intensities = peaks.mz, peaks.intensities + except AttributeError as exc: + raise TypeError( + f"spectra[{i}]: expected a spectrum with public peaks, got {type(spectrum).__name__}" + ) from exc + get = getattr(spectrum, "get", None) + yield mz, intensities, get("precursor_mz", None) if get else None + + +@dataclass(frozen=True, eq=False) +class PeakArrays: + """Sorted, zero-padded peak rows. Only the first lengths[i] entries are active.""" + + mz: np.ndarray + intensities: np.ndarray + lengths: np.ndarray + precursor_mz: np.ndarray | None = None + + def __post_init__(self): + mz, intensities = np.asarray(self.mz), np.asarray(self.intensities) + lengths = np.asarray(self.lengths) + if mz.ndim != 2 or intensities.shape != mz.shape: + raise ValueError("mz and intensities must be 2D arrays with identical shape") + if mz.dtype.kind != "f" or intensities.dtype.kind != "f": + raise TypeError("mz and intensities must be floating-point arrays") + if lengths.shape != (len(mz),) or lengths.dtype.kind not in "iu": + raise ValueError("lengths must be a 1D integral array with one entry per spectrum") + if np.any(lengths < 0) or np.any(lengths > mz.shape[1]): + raise ValueError("lengths must be between zero and the array width") + # Own the buffers so fixing dirty padding never mutates the caller's arrays. + mz, intensities, lengths = mz.copy(), intensities.copy(), lengths.astype(np.intp, copy=True) + for i, n in enumerate(lengths): + _check_row(mz[i, :n], intensities[i, :n], i) + mz[i, n:] = 0 + intensities[i, n:] = 0 + arrays = dict(mz=mz, intensities=intensities, lengths=lengths) + if self.precursor_mz is not None: + precursor = np.array(self.precursor_mz, dtype=np.float64, copy=True) + if precursor.shape != lengths.shape or not np.all(np.isfinite(precursor) & (precursor > 0)): + raise ValueError("precursor_mz must contain one positive finite value per spectrum") + arrays["precursor_mz"] = precursor + for name, array in arrays.items(): + array.setflags(write=False) + object.__setattr__(self, name, array) + + def __len__(self): + return len(self.lengths) + + @property + def width(self): + return self.mz.shape[1] + + def __getitem__(self, index): + if not isinstance(index, slice): + raise TypeError("PeakArrays supports slicing by spectrum rows") + precursor = None if self.precursor_mz is None else self.precursor_mz[index] + return PeakArrays(self.mz[index], self.intensities[index], self.lengths[index], precursor) + + def to_width(self, width, dtype=np.float32): + """Return stacked peak planes and lengths capped at the requested width.""" + if not isinstance(width, (int, np.integer)) or width < 0: + raise ValueError("width must be a non-negative integer") + result = np.zeros((2, len(self), width), dtype=dtype) + n = min(width, self.width) + result[0, :, :n], result[1, :, :n] = self.mz[:, :n], self.intensities[:, :n] + return result, np.minimum(self.lengths, width).astype(np.intp) + + @classmethod + def from_peak_lists(cls, mz_lists, intensity_lists, precursor_mz=None, dtype=np.float64): + """Pad aligned, one-dimensional arrays without truncating any peaks.""" + if len(mz_lists) != len(intensity_lists): + raise ValueError("mz_lists and intensity_lists must contain the same number of spectra") + rows = [] + for i, (mz, intensities) in enumerate(zip(mz_lists, intensity_lists)): + mz, intensities = np.asarray(mz, dtype=dtype), np.asarray(intensities, dtype=dtype) + if mz.ndim != 1 or mz.shape != intensities.shape: + raise ValueError(f"row {i}: mz and intensities must be aligned 1D arrays") + rows.append((mz, intensities)) + lengths = np.array([len(m) for m, _ in rows], dtype=np.intp) + mz = np.zeros((len(rows), lengths.max(initial=0)), dtype=dtype) + intensities = np.zeros_like(mz) + for i, (m, x) in enumerate(rows): + mz[i, : len(m)] = m + intensities[i, : len(m)] = x + return cls(mz, intensities, lengths, precursor_mz) + + @classmethod + def from_spectra( + cls, + spectra, + require_precursor=False, + remove_precursor=False, + offset_to_precursor=-1.6, + noise_cutoff=0.0, + dtype=np.float64, + ): + """Extract public peaks once, crop at the precursor, then filter relative noise.""" + denoise = noise_cutoff is not None and noise_cutoff > 0 + if isinstance(spectra, cls) and not remove_precursor and not denoise: + if require_precursor and len(spectra) and spectra.precursor_mz is None: + raise ValueError("spectra[0]: missing precursor_mz") + if spectra.mz.dtype == spectra.intensities.dtype == dtype: + return spectra + + masses, signals, precursors = [], [], [] + for i, (mz, intensity, precursor) in enumerate(_spectrum_rows(spectra)): + # matchms stacks the two peak columns before filtering. Preserve that + # dtype here, including float32 rounding at the precursor boundary. + mz, intensity = np.asarray(mz), np.asarray(intensity) + common_dtype = np.result_type(mz, intensity) + if common_dtype.kind not in "fiu": + raise TypeError(f"spectra[{i}]: expected numeric mz and intensities") + mz, intensity = mz.astype(common_dtype, copy=False), intensity.astype(common_dtype, copy=False) + _check_row(mz, intensity, i) + if precursor is not None: + try: + precursor = float(precursor) + except (TypeError, ValueError): + precursor = None + if precursor is not None and (not np.isfinite(precursor) or precursor <= 0): + precursor = None + if precursor is None and (require_precursor or remove_precursor): + raise ValueError(f"spectra[{i}]: expected positive finite precursor_mz") + if remove_precursor: + mz, intensity = filter_peaks_above_precursor(mz, intensity, precursor, offset_to_precursor) + if denoise: + mz, intensity = filter_noise(mz, intensity, noise_cutoff) + masses.append(mz) + signals.append(intensity) + precursors.append(precursor) + return cls.from_peak_lists(masses, signals, None if None in precursors else precursors, dtype) diff --git a/simms/similarity/CudaBinnedEmbeddingSimilarity.py b/simms/similarity/CudaBinnedEmbeddingSimilarity.py new file mode 100644 index 0000000..7a2c51c --- /dev/null +++ b/simms/similarity/CudaBinnedEmbeddingSimilarity.py @@ -0,0 +1,103 @@ +"""GPU-binned, max-normalized spectral embeddings.""" + +from itertools import islice + +import numpy as np +import torch +from matchms.similarity import BinnedEmbeddingSimilarity + +from ..peaks import PeakArrays, _spectrum_rows +from .vector_similarity_functions import _TiledVectorSimilarity + + +class CudaBinnedEmbeddingSimilarity(_TiledVectorSimilarity, BinnedEmbeddingSimilarity): + """Bin peaks on device, then compare embeddings in batch_size by batch_size tiles.""" + + def __init__( + self, + similarity="cosine", + max_mz=1005, + bin_width=1, + intensity_power=1, + *, + batch_size=2048, + precision="float64", + ): + BinnedEmbeddingSimilarity.__init__(self, similarity, max_mz, bin_width, intensity_power) + self._configure_tiles(batch_size, precision) + + def _score_tile(self, left, right): + if self.similarity == "euclidean": + return super()._score_tile(left, right) + + # sklearn's embedding cosine normalizes each row before GEMM and + # leaves near-zero rows at their original scale. + def normalized(data): + norms = data.norm(dim=1, keepdim=True) + return data / torch.where(norms < 10 * torch.finfo(data.dtype).eps, 1.0, norms) + + a = normalized(left) + b = a if left is right else normalized(right) + return a @ b.T + + @property + def _metric(self): + return self.similarity + + def _bin_rows(self, rows): + output = torch.zeros( + (len(rows), self.n_bins), device=self.device, dtype=getattr(torch, self.precision) + ) + # NumPy applies the bin division and intensity power in the input dtype. + # Group mixed-precision spectra to preserve that rounding at bin edges. + groups = {} + for i, (mz, intensities, _) in enumerate(rows): + groups.setdefault((mz.dtype, intensities.dtype), []).append((i, mz, intensities)) + for group in groups.values(): + mz = torch.as_tensor(np.concatenate([m for _, m, _ in group]), device=self.device) + intensity = torch.as_tensor(np.concatenate([x for _, _, x in group]), device=self.device) + indices = np.repeat([i for i, _, _ in group], [len(m) for _, m, _ in group]) + indices = torch.as_tensor(indices, device=self.device) + valid = (mz >= 0) & (mz <= self.max_mz) + # A device divisor preserves IEEE division. PyTorch lowers a Python + # scalar divisor to reciprocal multiplication on CUDA. + if not mz.is_floating_point(): + mz = mz.to(torch.float64) + width = mz.new_tensor(self.bin_width) + bins = (mz[valid] / width).floor().long().clamp_(0, self.n_bins - 1) + output.view(-1).scatter_add_( + 0, + indices[valid] * self.n_bins + bins, + intensity[valid].pow(self.intensity_power).to(output.dtype), + ) + maxima = output.amax(dim=1, keepdim=True) + return output / torch.where(maxima > 0, maxima, 1.0) + + def compute_embeddings(self, spectra): + """Return host embeddings, staging at most batch_size spectra on device.""" + if not hasattr(spectra, "__len__"): + spectra = list(spectra) + result = np.empty((len(spectra), self.n_bins), dtype=self.score_datatype) + iterator = _spectrum_rows(spectra) + for start in range(0, len(spectra), self.batch_size): + rows = list(islice(iterator, self.batch_size)) + result[start : start + len(rows)] = self._bin_rows(rows).cpu().numpy() + return result + + def _inputs(self, spectra_1, spectra_2): + left = self.compute_embeddings(spectra_1) + right = left if spectra_2 is None or spectra_1 is spectra_2 else self.compute_embeddings(spectra_2) + return left, right, spectra_2 is None + + def compute_similarity_matrix_from_embeddings(self, embeddings_1, embeddings_2=None): + a = self._validate_embeddings(embeddings_1) + b = a if embeddings_2 is None else self._validate_embeddings(embeddings_2) + return self._dense_vectors(a, b, embeddings_2 is None, "numpy", False) + + def pair(self, spectrum_1, spectrum_2): + """Compare two spectra, or two single-row PeakArrays.""" + a = spectrum_1 if isinstance(spectrum_1, PeakArrays) else [spectrum_1] + b = spectrum_2 if isinstance(spectrum_2, PeakArrays) else [spectrum_2] + if len(a) != 1 or len(b) != 1: + raise ValueError("pair expects one spectrum per input") + return self.matrix(a, b, array_type="numpy", progress_bar=False).reshape(()) diff --git a/simms/similarity/CudaCosineGreedy.py b/simms/similarity/CudaCosineGreedy.py index 959aaca..3a745e4 100644 --- a/simms/similarity/CudaCosineGreedy.py +++ b/simms/similarity/CudaCosineGreedy.py @@ -1,381 +1,230 @@ -import warnings -from itertools import product -from typing import List, Literal, Union import numpy as np import torch -from matchms import Spectrum -from matchms.similarity.BaseSimilarity import BaseSimilarity from numba import cuda -from sparsestack import StackedSparseArray from tqdm import tqdm -from ..utils import argbatch, get_device -from .spectrum_similarity_functions import cosine_kernel +from ..peaks import PeakArrays +from ..utils import get_device +from ._base import CudaSimilarity +from .spectrum_similarity_functions import LOCAL_CANDIDATES, cosine_kernel, exact_score, peak_weights -class CudaCosineGreedy(BaseSimilarity): - """ - Calculate cosine similarity score between two spectra using CUDA acceleration. - The score is calculated by finding the best possible matches between peaks of two spectra. - It provides a 'greedy' solution for the peak assignment problem, aimed at faster performance. +def _positive_int(name, value): + if isinstance(value, (bool, np.bool_)) or not isinstance(value, (int, np.integer)) or value <= 0: + raise ValueError(f"{name} must be a positive integer") + return int(value) + - This implementation is meant to replicate outputs of `matchms.similarity.CosineGreedy`. +def _scratch_size(n): + # Bucket specializations so slightly different tile widths reuse compiled kernels. + return 1 << (max(1, int(n)) - 1).bit_length() - For example: - >>> import numpy as np - >>> from matchms import Spectrum - >>> from simms.similarity import CudaCosineGreedy - >>> reference = Spectrum(mz=np.array([100, 150, 200.]), intensities=np.array([0.7, 0.2, 0.1])) - >>> query = Spectrum(mz=np.array([100, 140, 190.]), intensities=np.array([0.4, 0.2, 0.1])) - >>> cosine_greedy = CudaCosineGreedy(tolerance=0.2) - >>> score = cosine_greedy.pair(reference, query) - >>> print(f"Cosine score is {score['score']:.2f} with {score['matches']} matched peaks") - Cosine score is 0.83 with 1 matched peaks +class _GreedySimilarity(CudaSimilarity): + """Shared greedy scoring parameters and CUDA batching. + + batch_size bounds each tile axis. n_max_peaks optionally lowers the device + width below its 8192-peak safety cap. Pairs exceeding either peak cap or + match_limit are scored from the complete preprocessed rows with matchms. + precision selects FP64 (default) or FP32 device computation. """ - score_datatype = [ - ("score", np.float32), - ("matches", np.int32), - ("overflow", np.bool_), - ] + modified = False + shift = 0.0 def __init__( self, - tolerance: float = 0.1, - mz_power: float = 0.0, - intensity_power: float = 1.0, - shift: float = 0, - batch_size: int = 2048, - n_max_peaks: int = 1024, - match_limit: int = 2048, - sparse_threshold: float = 0.75, - verbose=False, + tolerance=0.01, + mz_power=0.0, + intensity_power=1.0, + noise_cutoff=0.01, + remove_precursor=True, + offset_to_precursor=-1.6, + batch_size=2048, + n_max_peaks=None, + match_limit=2048, + precision="float64", ): - """ - Initialize CudaCosineGreedy with specified parameters. - - Parameters: - ----------- - tolerance : float, optional - Tolerance for considering peaks as matching, by default 0.1. - mz_power : float, optional - Exponent for m/z values in similarity score calculation, by default 0.0. - intensity_power : float, optional - Exponent for intensity values in similarity score calculation, by default 1.0. - shift : float, optional - Value to shift m/z values, by default 0. - batch_size : int, optional - Batch size for processing spectra, by default 2048. - n_max_peaks : int, optional - Maximum number of peaks to consider in each spectrum, by default 1024. - match_limit : int, optional - Limit on the number of matches allowed, by default 2048. - sparse_threshold : float, optional - Threshold for considering scores in sparse output, by default 0.75. - verbose : bool, optional - Verbosity flag, by default False. - """ - - # Warn if CUDA device is unavailable - if not cuda.is_available(): - warnings.warn(f"{self.__class__.__name__}: CUDA device seems unavailable.") - - # Initialize parameters - self.tolerance = tolerance - self.mz_power = mz_power - self.int_power = intensity_power - self.shift = shift - self.batch_size = batch_size - self.match_limit = match_limit - self.verbose = verbose - self.n_max_peaks = n_max_peaks - self.device = get_device() - - assert 0 <= sparse_threshold <= 1, "Sparse threshold has to be greather than 0." - - self.sparse_threshold = sparse_threshold - - # Compile kernel function - self.kernel = cosine_kernel( - tolerance=self.tolerance, - shift=self.shift, - mz_power=self.mz_power, - int_power=self.int_power, - match_limit=self.match_limit, - batch_size=self.batch_size, - n_max_peaks=self.n_max_peaks, - spectra_dtype="float32", - ) - - def _spectra_peaks_to_tensor( - self, - spectra: list, - ) -> tuple[np.ndarray, np.ndarray]: - """ - Convert list of Spectrum objects into numpy arrays. - - Parameters: - ----------- - spectra : list of Spectrum - List of Spectrum objects. - - Returns: - -------- - tuple of np.ndarray - Tuple containing two numpy arrays: one for m/z values and one for intensities. - """ - # Determine dynamic shape - dynamic_shape = max(len(s.peaks) for s in spectra) - if self.n_max_peaks is None: - n_max_peaks = dynamic_shape + self.tolerance = float(tolerance) + if not np.isfinite(self.tolerance) or self.tolerance < 0: + raise ValueError("tolerance must be finite and non-negative") + self.mz_power = float(mz_power) + self.intensity_power = float(intensity_power) + self.noise_cutoff = noise_cutoff + self.remove_precursor = remove_precursor + self.offset_to_precursor = offset_to_precursor + self.batch_size = _positive_int("batch_size", batch_size) + self.n_max_peaks = None if n_max_peaks is None else _positive_int("n_max_peaks", n_max_peaks) + self.match_limit = _positive_int("match_limit", match_limit) + if precision not in ("float32", "float64"): + raise ValueError("precision must be 'float32' or 'float64'") + self.precision = precision + + @property + def device(self): + return get_device(require_cuda=True) + + def _inputs(self, spectra_1, spectra_2): + def prepare(data, side): + try: + return PeakArrays.from_spectra( + data, self.modified, self.remove_precursor, self.offset_to_precursor, self.noise_cutoff + ) + except (TypeError, ValueError) as exc: + raise type(exc)(f"{side}: {exc}") from exc + + left = prepare(spectra_1, "spectra_1") + right = left if spectra_2 is None or spectra_2 is spectra_1 else prepare(spectra_2, "spectra_2") + return left, right, spectra_2 is None and self.is_commutative + + def _batch(self, peaks, rows): + lengths = peaks.lengths[rows] + # Bound per-thread CUDA local memory. Larger spectra retain their full + # host rows for exact recovery, including when a user supplies a cap. + width = min(int(lengths.max(initial=0)), self.n_max_peaks or 8192, 8192) + mz = np.ascontiguousarray(peaks.mz[rows, :width], dtype=self.precision) + intensity = np.ascontiguousarray(peaks.intensities[rows, :width], dtype=self.precision) + weights, norms = peak_weights(mz, intensity, lengths, self.mz_power, self.intensity_power) + precursor = np.zeros(len(lengths)) if peaks.precursor_mz is None else peaks.precursor_mz[rows] + return tuple(torch.tensor(a, device=self.device) for a in (mz, weights, norms, lengths, precursor)) + + def _tile(self, rbatch, qbatch, positions, diagonal): + rmz, qmz = rbatch[0], qbatch[0] + count = len(rmz) * len(qmz) if positions is None else len(positions) + indices = torch.tensor([] if positions is None else positions, dtype=torch.int64, device=rmz.device) + result = torch.empty((2, count), dtype=rmz.dtype, device=rmz.device) + retry = torch.zeros(count, dtype=torch.int32, device=rmz.device) + width = _scratch_size(max(rmz.shape[1], qmz.shape[1])) + limit = min(self.match_limit, rmz.shape[1] * qmz.shape[1] * (2 if self.modified else 1)) + if cuda.config.ENABLE_CUDASIM: + + def view(tensor): + return tensor.numpy() + + stream = 0 else: - n_max_peaks = self.n_max_peaks - - # 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) - 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] - spectra_lens[i] = spec_len - - # Stack arrays and return - stacked_spectra = np.stack([mz, int], axis=0) - return stacked_spectra, spectra_lens - - def _get_batches(self, references, queries): - """ - Generate batches of spectra pairs for processing. - Parameters: - ----------- - references : list - List of reference Spectrum objects. - queries : list - List of query Spectrum objects. - - Returns: - -------- - list of tuple - List of tuples containing batched input data. - """ - batches_r = [] - for bstart, bend in argbatch(references, self.batch_size): - rspec, rlen = self._spectra_peaks_to_tensor(references[bstart:bend]) - batches_r.append([rspec, rlen, bstart, bend]) - - batches_q = [] - for bstart, bend in argbatch(queries, self.batch_size): - qspec, qlen = self._spectra_peaks_to_tensor(queries[bstart:bend]) - batches_q.append([qspec, qlen, bstart, bend]) - - batched_inputs = tuple(product(batches_r, batches_q)) - return batched_inputs - - def pair(self, reference: Spectrum, query: Spectrum) -> float: - """ - Do not use, unless testing. GPUs work best with a lot of data at the same time. - Calculates the cosine similarity score between a reference and a query spectrum. - - Parameters: - ----------- - reference : Spectrum - Reference spectrum. - query : Spectrum - Query spectrum. + def view(tensor): + return cuda.as_cuda_array(tensor, sync=False) + + stream = cuda.external_stream(torch.cuda.current_stream(rmz.device).cuda_stream) + + def launch(capacity, count_only=False): + lanes = count + heap_slots = 0 + if capacity > LOCAL_CANDIDATES: + heap_slots = capacity + bytes_per_heap = capacity * (3 * 4 + rmz.element_size()) + lanes = min(count, max(1, (64 << 20) // bytes_per_heap)) + heap_indices = torch.empty((lanes, 3, heap_slots), dtype=torch.int32, device=rmz.device) + heap_values = torch.empty((lanes, heap_slots), dtype=rmz.dtype, device=rmz.device) + kernel = cosine_kernel(width, capacity, self.precision, count_only) + args = ( + *map(view, rbatch), + *map(view, qbatch), + view(indices), + self.tolerance, + self.shift, + self.modified, + limit, + diagonal, + view(result), + view(retry), + view(heap_indices), + view(heap_values), + ) + for start in range(0, count, lanes): + size = min(lanes, count - start) + threads = min(size, 64) + kernel[(size + threads - 1) // threads, threads, stream](*args, start, size) + + capacity = limit + if limit > LOCAL_CANDIDATES: + launch(1, count_only=True) + # Negative entries require the CPU oracle, positive entries give the + # exact occupancy. A high configured limit alone costs no extra VRAM. + capacity = max(0, int(retry.max().item())) + launch(_scratch_size(capacity)) + return result, retry + + def _recover(self, left, right, i, j): + def row(peaks, index): + n = peaks.lengths[index] + return np.column_stack((peaks.mz[index, :n], peaks.intensities[index, :n])) + + shifts = [self.shift] + if self.modified: + delta = left.precursor_mz[i] - right.precursor_mz[j] + if abs(delta) > self.tolerance: + shifts.append(delta) + return exact_score( + row(left, i), row(right, j), shifts, self.tolerance, self.mz_power, self.intensity_power + ) - Returns: - -------- - float - Cosine similarity score between the reference and query spectra. - """ - result_mat = self.matrix([reference], [query]) - return np.asarray(result_mat.squeeze(), dtype=self.score_datatype) + def _tiles(self, left, right, symmetric, requested, progress_bar): + if not len(right): + return + batch = self.batch_size + starts = range(0, len(left), batch) if requested is None else sorted(requested) + for r in tqdm(starts, desc="Scoring reference batches", disable=not progress_bar): + rows = slice(r, min(r + batch, len(left))) + rbatch = self._batch(left, rows) + columns = ( + range(r if symmetric else 0, len(right), batch) if requested is None else sorted(requested[r]) + ) + for c in columns: + cols = slice(c, min(c + batch, len(right))) + qbatch = rbatch if right is left and r == c else self._batch(right, cols) + positions = None if requested is None else np.asarray(requested[r][c], dtype=np.intp) + diagonal = symmetric and r == c and positions is None + result, retry = self._tile(rbatch, qbatch, positions, diagonal) + failed = torch.nonzero(retry).flatten().cpu().numpy() + if failed.size: + width = cols.stop - c + local = failed if positions is None else positions[failed] + rr, cc = np.divmod(local, width) + repaired = [self._recover(left, right, r + i, c + j) for i, j in zip(rr, cc)] + # Preserve exact oracle values for host outputs and sparse + # predicates even when the device fast path used float32. + result = result.to(torch.float64) + values = torch.tensor(repaired, dtype=torch.float64, device=result.device).T + result[:, failed] = values + if diagonal: + result[:, cc * width + rr] = values + yield rows, cols, positions, result + + +class CudaCosineGreedy(_GreedySimilarity): + """matchms greedy cosine on CUDA, with an optional fixed shift of query m/z.""" - def matrix( + def __init__( self, - references: List[Spectrum], - queries: List[Spectrum], - array_type: Literal["numpy", "sparse"] = "numpy", - is_symmetric: bool = False, - ) -> Union[np.ndarray, StackedSparseArray]: - """ - 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". - is_symmetric : bool, optional - Unused. This unused argument is left is for compatibility reasons. - - Returns: - -------- - Score : Union[np.ndarray, StackedSparseArray] - 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` - """ - # Warn if is_symmetric is passed - if is_symmetric: - warnings.warn("is_symmetric is ignored here, it has no effect.") - - # Check if array_type is valid - assert array_type in [ - "numpy", - "sparse", - ], "Invalid array_type. Use 'numpy' or 'sparse'." - - # 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": - result = torch.empty(3, R, Q, dtype=torch.float32, device=self.device) - elif array_type == "sparse": - result = [] - - # Iterate over batched inputs - with torch.no_grad(): - for batch_i in tqdm(range(len(batched_inputs)), disable=not self.verbose): - # Unpack batched inputs - (rspec, rlen, rstart, rend), ( - qspec, - qlen, - qstart, - qend, - ) = batched_inputs[batch_i] - - # Tensor holding lengths and norms - metadata = torch.zeros( - 4, self.batch_size, dtype=torch.float32, device=self.device - ) - - # Convert spectra to tensors and move to device - rspec = torch.from_numpy(rspec).to(self.device) # 2, R, N - qspec = torch.from_numpy(qspec).to(self.device) # 2, Q, M - - # Pre-calculate norms - rnorm = ( - ( - ( - rspec[0, :, :] ** self.mz_power - * rspec[1, :, :] ** self.int_power - ) - ** 2 - ) - .sum(-1) - .sqrt() - ) # R - qnorm = ( - ( - ( - qspec[0, :, :] ** self.mz_power - * qspec[1, :, :] ** self.int_power - ) - ** 2 - ) - .sum(-1) - .sqrt() - ) # Q - - # Create tensor for lengths, and norms - metadata[0, : len(rlen)] = torch.from_numpy(rlen).to(self.device) - metadata[1, : len(qlen)] = torch.from_numpy(qlen).to(self.device) - metadata[2, : len(rnorm)] = rnorm - metadata[3, : len(qnorm)] = qnorm - - # Initialize output tensor - out = torch.empty( - 3, - self.batch_size, - self.batch_size, - dtype=torch.float32, - device=self.device, - ) - - # Convert tensors to CUDA arrays - rspec = cuda.as_cuda_array(rspec) - qspec = cuda.as_cuda_array(qspec) - metadata = cuda.as_cuda_array(metadata) - out = cuda.as_cuda_array(out) - - # Run GPU kernel - self.kernel(rspec, qspec, metadata, out) - - # Convert output to tensor - out = torch.as_tensor(out) - - out = out[:, : len(rlen), : len(qlen)] - - # Populate result based on array_type - if array_type == "numpy": - result[:, rstart:rend, qstart:qend] = out - - elif array_type == "sparse": - mask = out[0] >= self.sparse_threshold - if mask.any(): - row, col = torch.nonzero(mask, as_tuple=True) - rabs = (rstart + row).cpu() - qabs = (qstart + col).cpu() - score, matches, overflow = out[:, mask].cpu() - result.append( - dict( - rabs=rabs.int().cpu().numpy(), - qabs=qabs.int().cpu().numpy(), - score=score.float().cpu().numpy(), - matches=matches.int().cpu().numpy(), - overflow=overflow.bool().cpu().numpy(), - ) - ) - - # Return result based on array_type - if array_type == "numpy": - return np.rec.fromarrays( - result.cpu().numpy(), - dtype=self.score_datatype, - ) - elif array_type == "sparse": - sp = StackedSparseArray(len(references), len(queries)) - sparse_data = [] - for bunch in result: - sparse_data.append( - ( - bunch["rabs"], - bunch["qabs"], - bunch["score"], - bunch["matches"], - bunch["overflow"], - ) - ) + tolerance=0.01, + mz_power=0.0, + intensity_power=1.0, + noise_cutoff=0.01, + remove_precursor=True, + offset_to_precursor=-1.6, + batch_size=2048, + n_max_peaks=None, + match_limit=2048, + precision="float64", + shift=0.0, + ): + super().__init__( + tolerance, + mz_power, + intensity_power, + noise_cutoff, + remove_precursor, + offset_to_precursor, + batch_size, + n_max_peaks, + match_limit, + precision, + ) + self.shift = float(shift) - if sparse_data: - r, q, s, m, o = zip(*sparse_data) - r = np.concatenate(r) - q = np.concatenate(q) - sp.add_sparse_data( - r, - q, - np.rec.fromarrays( - arrayList=[ - np.concatenate(s), - np.concatenate(m), - np.concatenate(o), - ], - names=["score", "matches", "overflow"], - ), - name="sparse", - ) - return sp + @property + def is_commutative(self): + return self.shift == 0 diff --git a/simms/similarity/CudaCosineLinear.py b/simms/similarity/CudaCosineLinear.py new file mode 100644 index 0000000..5f75888 --- /dev/null +++ b/simms/similarity/CudaCosineLinear.py @@ -0,0 +1,382 @@ +"""CUDA linear cosine scoring on SIRIUS-merged peaks.""" + +import logging +from operator import mul +from dataclasses import dataclass +from functools import lru_cache + +import numpy as np +import torch +from matchms.similarity._precursor_validation import get_valid_precursor_mz +from matchms.similarity.cosine_linear_functions import _weighted_products, sirius_merge_close_peaks +from matchms.similarity.spectrum_similarity_functions import _preprocess_peak_array +from numba import cuda, int16, njit +from numba.cuda import libdevice + +from ..peaks import PeakArrays, _spectrum_rows +from ..utils import get_device +from ._base import CudaSimilarity +from .vector_similarity_functions import kernel_stream, kernel_view, tile_slices + + +_LOGGER = logging.getLogger("matchms") +_WORKSPACE_WIDTH = 2048 + + +@dataclass +class _Prepared: + mz: np.ndarray + weights: np.ndarray + offsets: np.ndarray + norms: np.ndarray + precursors: np.ndarray + + def __len__(self): + return len(self.norms) + + def batch(self, rows, device, width_limit): + offsets = self.offsets[rows.start : rows.stop + 1] + peaks = slice(offsets[0], offsets[-1]) + mz, weights = self.mz[peaks], self.weights[peaks] + offsets = offsets - offsets[0] + lengths = np.diff(offsets) + if width_limit is not None and np.any(lengths > width_limit): + # Oversized rows are scored exclusively on the CPU. Keep empty + # slots for their row indices without staging their peaks on CUDA. + keep = lengths <= width_limit + active = np.repeat(keep, lengths) + mz, weights = mz[active], weights[active] + offsets = np.r_[0, np.cumsum(np.where(keep, lengths, 0))] + arrays = (mz, weights, offsets, self.norms[rows], self.precursors[rows]) + return tuple(torch.as_tensor(a, device=device) for a in arrays) + + def peak_slice(self, index): + return slice(self.offsets[index], self.offsets[index + 1]) + + +# matchms rounds each product before adding it. Prevent CUDA from fusing +# that multiplication into the sum or into a modified-cosine DP comparison. +_device_product = mul if cuda.config.ENABLE_CUDASIM else libdevice.dmul_rn + + +@cuda.jit(device=True) +def _direct_score(mz1, w1, mz2, w2, tolerance): + i = j = matches = 0 + total = 0.0 + while i < mz1.size and j < mz2.size: + diff = mz1[i] - mz2[j] + if abs(diff) <= tolerance: + total += _device_product(w1[i], w2[j]) + matches += 1 + i += 1 + j += 1 + elif diff < 0: + i += 1 + else: + j += 1 + return total, matches + + +def _make_modified_score(product): + def _modified_score(mz1, w1, mz2, w2, precursor1, precursor2, tolerance, partners): + """Return unnormalized weight and count. Both GPU and CPU use this traversal.""" + n1, n2 = mz1.size, mz2.size + for node in range(n1 + n2): + partners[0, node] = -1 + partners[1, node] = -1 + + for kind in range(2): + if kind == 1 and abs(precursor1 - precursor2) <= tolerance: + break + offset1 = precursor1 if kind else 0.0 + offset2 = precursor2 if kind else 0.0 + j = 0 + for i in range(n1): + center = mz1[i] - offset1 + while j < n2 and mz2[j] - offset2 < center - tolerance: + j += 1 + if j < n2 and mz2[j] - offset2 <= center + tolerance: + other = n1 + j + if kind == 0 or partners[0, i] != other: + partners[kind, i] = other + partners[kind, other] = i + j += 1 + + total = 0.0 + matches = 0 + for start in range(n1 + n2): + if (partners[0, start] >= 0) == (partners[1, start] >= 0): + continue + # Only endpoints have degree one. Removing each traversed edge leaves + # the next edge unambiguous and consumes the whole component. + node = start + prev2 = prev = 0.0 + sum2 = accumulated = total + count2 = count = 0 + while True: + kind = 0 if partners[0, node] >= 0 else 1 + other = partners[kind, node] + if other < 0: + break + partners[kind, node] = -1 + partners[kind, other] = -1 + if node < n1: + benefit = product(w1[node], w2[other - n1]) + else: + benefit = product(w1[other], w2[node - n1]) + # Upstream backtracking takes the last edge on ties. Carrying the + # winning count alongside its weight avoids storing the DP table. + take = prev2 + benefit + if node == start or take >= prev: + best, best_count = take, count2 + (benefit != 0.0) + # Keep the global summation order of matchms backtracking. + best_sum = sum2 + benefit + else: + best, best_count = prev, count + best_sum = accumulated + prev2, prev = prev, best + count2, count = count, best_count + sum2, accumulated = accumulated, best_sum + node = other + total = accumulated + matches += count + return total, matches + + return _modified_score + + +_modified_device = cuda.jit(device=True)(_make_modified_score(_device_product)) +_modified_host = njit(_make_modified_score(mul)) + + +@lru_cache(maxsize=None) +def _kernel(modified, width): + workspace_shape = (2, 2 * width) + + # Specialize local storage to the merged batch width. The direct kernel + # needs only its two cursors regardless of spectrum length. + @cuda.jit + def run( + mz1, + w1, + offsets1, + norms1, + pre1, + mz2, + w2, + offsets2, + norms2, + pre2, + tolerance, + positions, + diagonal, + result, + ): + k = cuda.grid(1) + if k >= result.shape[1]: + return + pos = positions[k] if positions.size else k + i, j = pos // norms2.size, pos % norms2.size + if diagonal and i > j: + return + a, b = offsets1[i], offsets1[i + 1] + c, d = offsets2[j], offsets2[j + 1] + score = 0.0 + matches = 0 + if a < b and c < d and not (norms1[i] <= 1e-12 or norms2[j] <= 1e-12): + if modified: + partners = cuda.local.array(workspace_shape, int16) + score, matches = _modified_device( + mz1[a:b], w1[a:b], mz2[c:d], w2[c:d], pre1[i], pre2[j], tolerance, partners + ) + else: + score, matches = _direct_score(mz1[a:b], w1[a:b], mz2[c:d], w2[c:d], tolerance) + score /= norms1[i] * norms2[j] + result[0, k], result[1, k] = score, matches + if diagonal and i != j: + mirror = j * norms2.size + i + result[0, mirror], result[1, mirror] = score, matches + + return run + + +class CudaCosineLinear(CudaSimilarity): + """Linear-time direct cosine. Merge and weight each input spectrum once per call.""" + + is_commutative = True + modified = False + + def __init__( + self, + tolerance=0.01, + mz_power=0.0, + intensity_power=1.0, + noise_cutoff=0.01, + remove_precursor=False, + offset_to_precursor=-1.6, + *, + batch_size=2048, + precision="float64", + ): + self.tolerance = tolerance + self.mz_power = mz_power + self.intensity_power = intensity_power + self.noise_cutoff = noise_cutoff + self.remove_precursor = remove_precursor + self.offset_to_precursor = offset_to_precursor + if isinstance(batch_size, bool) or not isinstance(batch_size, (int, np.integer)) or batch_size < 1: + raise ValueError("batch_size must be a positive integer") + if precision not in ("float32", "float64"): + raise ValueError("precision must be 'float32' or 'float64'") + self.batch_size = int(batch_size) + self.precision = precision + + @property + def device(self): + return get_device(require_cuda=True) + + def _prepare(self, data): + masses, weights, norms, precursors = [], [], [], [] + offsets = [0] + for mz, intensity, precursor in _spectrum_rows(data): + if self.modified or self.remove_precursor: + precursor = get_valid_precursor_mz({"precursor_mz": precursor}, _LOGGER) + else: + precursor = 0.0 + peaks = _preprocess_peak_array( + np.column_stack((mz, intensity)), + precursor_mz=precursor, + remove_precursor=self.remove_precursor, + offset_to_precursor=self.offset_to_precursor, + noise_cutoff=self.noise_cutoff, + ) + merged = sirius_merge_close_peaks(peaks.astype(np.float64, copy=False), self.tolerance) + products, norm = _weighted_products(merged, self.mz_power, self.intensity_power) + masses.append(merged[:, 0]) + weights.append(products) + norms.append(norm) + precursors.append(precursor) + offsets.append(offsets[-1] + len(products)) + return _Prepared( + np.concatenate(masses) if masses else np.empty(0), + np.concatenate(weights) if weights else np.empty(0), + np.asarray(offsets), + np.asarray(norms), + np.asarray(precursors, dtype=np.float64), + ) + + def _inputs(self, spectra_1, spectra_2): + left = self._prepare(spectra_1) + right = left if spectra_2 is None or spectra_1 is spectra_2 else self._prepare(spectra_2) + return left, right, spectra_2 is None + + def pair(self, spectrum_1, spectrum_2): + a = spectrum_1 if isinstance(spectrum_1, PeakArrays) else [spectrum_1] + b = spectrum_2 if isinstance(spectrum_2, PeakArrays) else [spectrum_2] + if len(a) != 1 or len(b) != 1: + raise ValueError("pair expects one spectrum per input") + return self.matrix(a, b, array_type="numpy", progress_bar=False).reshape(()) + + def _recover(self, left, right, i, j): + if left.norms[i] <= 1e-12 or right.norms[j] <= 1e-12: + return 0.0, 0 + a, b = left.peak_slice(i), right.peak_slice(j) + partners = np.empty((2, a.stop - a.start + b.stop - b.start), dtype=np.intp) + total, matches = _modified_host( + left.mz[a], + left.weights[a], + right.mz[b], + right.weights[b], + left.precursors[i], + right.precursors[j], + self.tolerance, + partners, + ) + return total / (left.norms[i] * right.norms[j]), matches + + def _tiles(self, left, right, symmetric, requested, progress_bar): + previous = None + limit = _WORKSPACE_WIDTH if self.modified else None + lengths1, lengths2 = np.diff(left.offsets), np.diff(right.offsets) + for rows, cols, positions in tile_slices( + (len(left), len(right)), self.batch_size, symmetric, requested, progress_bar + ): + if previous != rows: + a = left.batch(rows, self.device, limit) + previous = rows + b = a if left is right and rows == cols else right.batch(cols, self.device, limit) + nr, nc = rows.stop - rows.start, cols.stop - cols.start + count = nr * nc if positions is None else len(positions) + indices = torch.as_tensor( + [] if positions is None else positions, device=self.device, dtype=torch.int64 + ) + diagonal = symmetric and rows == cols and positions is None + width = 1 + oversized = None + if self.modified: + lens1, lens2 = lengths1[rows], lengths2[cols] + largest = max( + lens1[lens1 <= _WORKSPACE_WIDTH].max(initial=1), + lens2[lens2 <= _WORKSPACE_WIDTH].max(initial=1), + ) + width = 1 << (int(largest) - 1).bit_length() + if lens1.max() > width or lens2.max() > width: + if positions is None: + oversized = np.flatnonzero((lens1[:, None] > width) | (lens2 > width)) + else: + oversized = np.flatnonzero( + (lens1[positions // nc] > width) | (lens2[positions % nc] > width) + ) + result = torch.empty((2, count), dtype=getattr(torch, self.precision), device=self.device) + threads = min(count, 64) + _kernel(self.modified, width)[ + (count + threads - 1) // threads, threads, kernel_stream(a[0].device) + ]( + *map(kernel_view, a), + *map(kernel_view, b), + self.tolerance, + kernel_view(indices), + diagonal, + kernel_view(result), + ) + if oversized is not None and oversized.size: + pos = oversized if positions is None else positions[oversized] + i, j = np.divmod(pos, nc) + if diagonal: + upper = i <= j + oversized, i, j = oversized[upper], i[upper], j[upper] + repaired = [self._recover(left, right, rows.start + x, cols.start + y) for x, y in zip(i, j)] + values = torch.tensor(repaired, device=self.device, dtype=result.dtype).T + result[:, oversized] = values + if diagonal: + result[:, j * nc + i] = values + yield rows, cols, positions, result + + +class CudaModifiedCosineLinear(CudaCosineLinear): + """Exact direct and shifted path matching, with CPU workspace for rows over 2048 merged peaks.""" + + modified = True + + def __init__( + self, + tolerance=0.01, + mz_power=0.0, + intensity_power=1.0, + noise_cutoff=0.01, + remove_precursor=True, + offset_to_precursor=-1.6, + *, + batch_size=2048, + precision="float64", + ): + super().__init__( + tolerance, + mz_power, + intensity_power, + noise_cutoff, + remove_precursor, + offset_to_precursor, + batch_size=batch_size, + precision=precision, + ) diff --git a/simms/similarity/CudaEntropyGreedy.py b/simms/similarity/CudaEntropyGreedy.py new file mode 100644 index 0000000..8f27a22 --- /dev/null +++ b/simms/similarity/CudaEntropyGreedy.py @@ -0,0 +1,184 @@ +"""Tile-streamed, one-to-one spectral entropy similarity on CUDA.""" + +from dataclasses import dataclass + +import numpy as np +import pandas as pd +import torch +from matchms import Scores, SpectraCollection +from matchms.similarity.entropy_greedy import ( + EntropyGreedy, + _entropy_fragment_similarity_greedy, + _entropy_neutral_loss_similarity_greedy, +) +from matchms.similarity.flash_utils import _clean_and_weight +from numba import cuda +from tqdm import tqdm + +from ..peaks import _spectrum_rows +from ..utils import get_device +from ._base import _ScalarCudaSimilarity +from .CudaCosineGreedy import _positive_int, _scratch_size +from .spectrum_similarity_functions import ENTROPY_HYBRID_CAP, entropy_kernel + + +@dataclass +class _Prepared: + # Each packed peak holds its m/z, half-normalized intensity p, and p*log2(p). + peaks: np.ndarray + offsets: np.ndarray + precursor: np.ndarray + + def __len__(self): + return len(self.precursor) + + def row(self, i): + return self.peaks[self.offsets[i]:self.offsets[i + 1]] + + def batch(self, rows, device): + offsets = self.offsets[rows.start:rows.stop + 1] + arrays = self.peaks[offsets[0]:offsets[-1]], offsets - offsets[0], self.precursor[rows] + return tuple(torch.as_tensor(a, device=device) for a in arrays), int(np.diff(offsets).max()) + + +class CudaEntropyGreedy(_ScalarCudaSimilarity, EntropyGreedy): + """Li spectral entropy with matchms preprocessing and greedy matching order. + + Set weighted=False to normalize intensities without Li weighting. batch_size + bounds each tile axis. NumPy and Torch outputs are scalar score matrices of + shape (references, queries). Only hybrid matching needs used-peak scratch. + """ + + score_datatype = np.dtype(np.float64) + score_fields = ("score",) + + def __init__( + self, + matching_mode="fragment", + tolerance=0.01, + use_ppm=False, + remove_precursor=True, + offset_to_precursor=-1.6, + noise_cutoff=0.01, + merge_within=0.0, + dtype=np.float64, + weighted: bool = True, + batch_size=2048, + ): + super().__init__(matching_mode, tolerance, use_ppm, remove_precursor, offset_to_precursor, + noise_cutoff, merge_within, dtype) + if self.dtype not in (np.dtype("float32"), np.dtype("float64")): + raise ValueError("dtype must be float32 or float64") + self.weighted = weighted + self.batch_size = _positive_int("batch_size", batch_size) + + def to_dict(self): + return {**super().to_dict(), "dtype": self.dtype.name} + + def _pack(self, spectra): + arrays, offsets, precursors = [], [0], [] + for mz, intensities, precursor in _spectrum_rows(spectra): + # SpectraCollection drops pandas missing metadata when reconstructing a row. + if isinstance(spectra, SpectraCollection) and pd.isna(precursor): + precursor = None + peaks = _clean_and_weight( + np.column_stack((mz, intensities)), precursor, + remove_precursor=self.remove_precursor, offset_to_precursor=self.offset_to_precursor, + noise_cutoff=self.noise_cutoff, normalize_to_half=True, merge_within_da=self.merge_within, + weighing_type="entropy" if self.weighted else "cosine", dtype=self.dtype, + ) + # EntropyGreedy promotes each preprocessed value to Python float before scoring. + p = peaks[:, 1].astype(np.float64, copy=False) + h = np.zeros_like(p) + positive = p > 0 + h[positive] = p[positive] * np.log2(p[positive]) + arrays.append(np.column_stack((peaks, h))) + offsets.append(offsets[-1] + len(peaks)) + precursors.append(np.nan if precursor is None else float(precursor)) + return _Prepared(np.concatenate(arrays) if arrays else np.empty((0, 3)), + np.asarray(offsets, dtype=np.int64), np.asarray(precursors, dtype=np.float64)) + + def _inputs(self, spectra_1, spectra_2): + left = self._pack(spectra_1) + right = left if spectra_2 is None or spectra_1 is spectra_2 else self._pack(spectra_2) + return left, right, spectra_2 is None + + def _recover_hybrid(self, left, right, i, j): + # Only reached for hybrid pairs with both precursors and oversized bitsets. + a, b = left.row(i), right.row(j) + used = dict(used_1=np.zeros(len(a), dtype=bool), used_2=np.zeros(len(b), dtype=bool)) + score = _entropy_fragment_similarity_greedy(a, b, self.tolerance, self.use_ppm, **used) + return score + _entropy_neutral_loss_similarity_greedy( + a, b, left.precursor[i], right.precursor[j], self.tolerance, self.use_ppm, **used, + ) + + def _tiles(self, left, right, symmetric, requested, progress_bar): + if not len(right): + return + batch, device = self.batch_size, get_device(require_cuda=True) + starts = range(0, len(left), batch) if requested is None else sorted(requested) + if cuda.config.ENABLE_CUDASIM: + view, stream = torch.Tensor.numpy, 0 + else: + def view(tensor): + return cuda.as_cuda_array(tensor, sync=False) + stream = cuda.external_stream(torch.cuda.current_stream().cuda_stream) + + for r in tqdm(starts, desc="Scoring reference batches", disable=not progress_bar): + rows = slice(r, min(r + batch, len(left))) + rbatch = left.batch(rows, device) + columns = range(r if symmetric else 0, len(right), batch) if requested is None else sorted(requested[r]) + for c in columns: + cols = slice(c, min(c + batch, len(right))) + qbatch = rbatch if left is right and r == c else right.batch(cols, device) + max_peaks = max(rbatch[1], qbatch[1]) + words = 1 + if self.matching_mode == "hybrid": + words = _scratch_size((min(max_peaks, ENTROPY_HYBRID_CAP) + 31) // 32) + positions = None if requested is None else np.asarray(requested[r][c], dtype=np.intp) + width = cols.stop - c + count = (rows.stop - r) * width if positions is None else len(positions) + indices = torch.as_tensor([] if positions is None else positions, dtype=torch.int64, device=device) + result = torch.empty(count, dtype=getattr(torch, self.dtype.name), device=device) + diagonal = symmetric and r == c and positions is None + threads = min(128, count) + kernel = entropy_kernel(self.matching_mode, words) + kernel[(count + threads - 1) // threads, threads, stream]( + *map(view, rbatch[0]), *map(view, qbatch[0]), view(indices), self.tolerance, + self.use_ppm, diagonal, view(result), + ) + if self.matching_mode == "hybrid" and max_peaks > ENTROPY_HYBRID_CAP: + failed = torch.nonzero(torch.isneginf(result)).flatten().cpu().numpy() + for k in failed: + i, j = divmod(k if positions is None else positions[k], width) + if diagonal and i > j: + continue + value = self._recover_hybrid(left, right, r + i, c + j) + result[k] = value + if diagonal: + result[j * width + i] = value + yield rows, cols, positions, result + + def matrix(self, spectra_1, spectra_2=None, score_fields=None, progress_bar=True, array_type="scores"): + self._fields(score_fields) + left, right, symmetric = self._inputs(spectra_1, spectra_2) + shape = (len(left), len(right)) + if array_type == "torch": + result = torch.empty(shape, dtype=getattr(torch, self.dtype.name), device=get_device(require_cuda=True)) + elif array_type in ("numpy", "scores"): + result = np.empty(shape, dtype=self.dtype) + else: + raise ValueError("array_type must be 'scores', 'numpy' or 'torch'") + for rows, cols, _, tile in self._tiles(left, right, symmetric, None, progress_bar): + tile = tile.reshape(rows.stop - rows.start, cols.stop - cols.start) + if array_type != "torch": + tile = tile.cpu().numpy() + result[rows, cols] = tile + if symmetric and rows.start != cols.start: + result[cols, rows] = tile.T + return Scores({"score": result}) if array_type == "scores" else result + + # EntropyGreedy callbacks receive a zero-dimensional array for each scalar. + @staticmethod + def _predicate_values(values): + return map(np.asarray, values) diff --git a/simms/similarity/CudaFingerprintSimilarity.py b/simms/similarity/CudaFingerprintSimilarity.py index d56bb25..e35ac46 100644 --- a/simms/similarity/CudaFingerprintSimilarity.py +++ b/simms/similarity/CudaFingerprintSimilarity.py @@ -1,182 +1,207 @@ -from typing import List, Literal, Union +"""Tiled GPU similarity of matchms molecular fingerprints.""" + +import json +from itertools import chain + import numpy as np -from matchms import Spectrum -from matchms.similarity.BaseSimilarity import BaseSimilarity -from sparsestack import StackedSparseArray -from .vector_similarity_functions import ( - cosine_similarity_matrix, - dice_similarity_matrix, - jaccard_similarity_matrix, -) - - -class CudaFingerprintSimilarity(BaseSimilarity): - """Calculate similarity between molecules based on their fingerprints. - - For this similarity measure to work, fingerprints are expected to be derived - by running :meth:`~matchms.filtering.add_fingerprint`. - - Code example: - - .. testcode:: - - >>> import numpy as np - >>> from matchms import calculate_scores - >>> from matchms import Spectrum - >>> from matchms.filtering import add_fingerprint - >>> from simms.similarity import CudaFingerprintSimilarity - >>> spectrum_1 = Spectrum(mz=np.array([], dtype="float"), - ... intensities=np.array([], dtype="float"), - ... metadata={"smiles": "CCC(C)C(C(=O)O)NC(=O)CCl"}) - >>> spectrum_2 = Spectrum(mz=np.array([], dtype="float"), - ... intensities=np.array([], dtype="float"), - ... metadata={"smiles": "CC(C)C(C(=O)O)NC(=O)CCl"}) - >>> spectrum_3 = Spectrum(mz=np.array([], dtype="float"), - ... intensities=np.array([], dtype="float"), - ... metadata={"smiles": "C(C(=O)O)(NC(=O)O)S"}) - >>> spectrums = [spectrum_1, spectrum_2, spectrum_3] - >>> # Add fingerprints - >>> spectrums = [add_fingerprint(x, nbits=256) for x in spectrums] - >>> # Specify type and calculate similarities - >>> similarity_measure = CudaFingerprintSimilarity("jaccard") - >>> scores = calculate_scores(spectrums, spectrums, similarity_measure) - >>> print(np.round(scores.scores.to_array(), 3)) - [[1. 0.878 0.415] - [0.878 1. 0.444] - [0.415 0.444 1. ]] +import torch +from matchms import Fingerprints +from matchms.similarity import FingerprintSimilarity +from scipy import sparse - """ +from ..peaks import PeakArrays +from .vector_similarity_functions import _TiledVectorSimilarity - is_commutative = True - score_datatype = np.float32 + +class CudaFingerprintSimilarity(_TiledVectorSimilarity, FingerprintSimilarity): + """Compute one score per pair of valid unique compounds in matchms fingerprint order. + + Pass spectra and a chemap generator, existing Fingerprints containers, or + precomputed 2D arrays with fingerprint_generator=None. Jaccard aliases + generalized Tanimoto. Dice uses twice the sum of minima divided by the sum + of both vectors (two empty vectors score zero for Dice and one for Tanimoto). + """ def __init__( self, - similarity_measure: Literal["cosine", "dice", "jaccard"] = "jaccard", - set_empty_scores: Union[float, int, str] = "nan", - batch_size: int = 2048, + fingerprint_generator=None, + similarity_measure="tanimoto", + set_empty_scores="nan", + ignore_stereochemistry=False, + count=False, + folded=True, + return_csr=False, + invalid_policy="raise", + *, + batch_size=2048, + precision="float64", + **fingerprint_config_kwargs, ): - """ - - Parameters - ---------- - similarity_measure: - Chose similarity measure form "cosine", "dice", "jaccard". - The default is "jaccard". - set_empty_scores: - Define what should be given instead of a similarity score in cases - where fingprints are missing. The default is "nan", which will return - np.nan's in such cases. - """ - self.set_empty_scores = set_empty_scores - assert similarity_measure in [ - "cosine", - "dice", - "jaccard", - ], "Unknown similarity measure." + if similarity_measure not in ("cosine", "tanimoto", "jaccard", "dice"): + raise ValueError("Unknown similarity measure") + if isinstance(fingerprint_generator, dict): + from rdkit.Chem.rdFingerprintGenerator import FingerprintGeneratorFromJSON + + fingerprint_generator = FingerprintGeneratorFromJSON(json.dumps(fingerprint_generator)) + weights = fingerprint_config_kwargs.get("unfolded_weights") + if weights is not None: + # JSON object keys are strings. chemap looks up integer feature IDs. + fingerprint_config_kwargs["unfolded_weights"] = {int(k): float(v) for k, v in weights.items()} + super().__init__( + fingerprint_generator, + "cosine" if similarity_measure == "cosine" else "tanimoto", + set_empty_scores, + ignore_stereochemistry, + count, + folded, + return_csr, + invalid_policy, + **fingerprint_config_kwargs, + ) self.similarity_measure = similarity_measure - self.batch_size = batch_size - - def pair(self, reference: Spectrum, query: Spectrum) -> float: - """Calculate fingerprint based similarity score between two spectra. - - Parameters - ---------- - reference - Single reference spectrum. - query - Single query spectrum. - """ - fingerprint_ref = reference.get("fingerprint") - fingerprint_query = query.get("fingerprint") - - if self.similarity_measure == "jaccard": - return jaccard_similarity_matrix([fingerprint_ref], [fingerprint_query]) - - if self.similarity_measure == "dice": - return dice_similarity_matrix([fingerprint_ref], [fingerprint_query]) - - if self.similarity_measure == "cosine": - score = cosine_similarity_matrix([fingerprint_ref], [fingerprint_query]) - return np.asarray(score, dtype=self.score_datatype) - - raise NotImplementedError + self._configure_tiles(batch_size, precision) + + @property + def _metric(self): + return self.similarity_measure + + def to_dict(self): + parameters = super().to_dict() + if self.fingerprint_generator is not None: + if not hasattr(self.fingerprint_generator, "ToJSON"): + raise TypeError("Serializing a fingerprint generator requires RDKit's ToJSON support") + parameters["fingerprint_generator"] = json.loads(self.fingerprint_generator.ToJSON()) + config = dict(parameters.pop("fingerprint_config_kwargs")) + if config.get("folded_weights") is not None: + config["folded_weights"] = np.asarray(config["folded_weights"]).tolist() + return {**parameters, **config} + + def _vectors(self, data): + if isinstance(data, Fingerprints): + return self._fingerprint_matrix(data) + if ( + isinstance(data, torch.Tensor) + or sparse.issparse(data) + or (isinstance(data, np.ndarray) and data.ndim == 2) + ): + if self.fingerprint_generator is not None: + raise ValueError("Precomputed arrays require fingerprint_generator=None") + if data.ndim != 2: + raise ValueError("Expected a 2D fingerprint matrix") + if isinstance(data, torch.Tensor) and data.layout == torch.sparse_csr: + data = data.detach().cpu() + return sparse.csr_matrix( + (data.values().numpy(), data.col_indices().numpy(), data.crow_indices().numpy()), + shape=tuple(data.shape), + ) + return data.tocsr() if sparse.issparse(data) else data + if not hasattr(data, "__len__"): + data = list(data) + if len(data) == 0: + # Empty spectra have no feature width until the other axis is prepared. + return None + if isinstance(data, PeakArrays): + raise ValueError("Generating fingerprints requires spectra with chemical metadata") + if self.fingerprint_generator is None: + raise ValueError("Provide a fingerprint_generator for spectra or pass a 2D fingerprint matrix") + return self._fingerprint_matrix(self._compute_fingerprints_from_spectra(data)) + + @staticmethod + def _unfolded_matrices(left, right): + # chemap returns feature IDs for binary rows, and (IDs, counts) for count rows. + # Build a common vocabulary before scoring disjoint compound collections. + rows = left if left is right else chain(left or (), right or ()) + keys, values, offsets = [], [], [0] + for row in rows: + bits, weights = row if isinstance(row, tuple) else (row, np.ones(len(row))) + keys.append(bits) + values.append(weights) + offsets.append(offsets[-1] + len(bits)) + vocabulary, columns = np.unique(np.concatenate(keys), return_inverse=True) + matrix = sparse.csr_matrix((np.concatenate(values), columns, offsets), + shape=(len(offsets) - 1, len(vocabulary))) + if left is right: + return matrix, matrix + split = len(left) if left is not None else 0 + return matrix[:split], matrix[split:] + + def _inputs(self, spectra_1, spectra_2): + left = self._vectors(spectra_1) + right = left if spectra_2 is None or spectra_1 is spectra_2 else self._vectors(spectra_2) + if isinstance(left, list) or isinstance(right, list): + if any(side is not None and not isinstance(side, list) for side in (left, right)): + raise ValueError("Both inputs must use unfolded fingerprints with feature IDs") + left, right = self._unfolded_matrices(left, right) + if left is None: + left = np.empty((0, 0 if right is None else right.shape[1])) + if right is None: + right = np.empty((0, left.shape[1])) + return left, right, spectra_2 is None + + @staticmethod + def _source(spectra, fingerprints): + if spectra is not None and fingerprints is not None: + raise ValueError("Provide either spectra or fingerprints for each input, not both") + return spectra if fingerprints is None else fingerprints def matrix( self, - references: List[Spectrum], - queries: List[Spectrum], - array_type: str = "numpy", - is_symmetric: bool = False, - ) -> np.array: - """Calculate matrix of fingerprint based similarity scores. - - Parameters - ---------- - references: - List of reference spectrums. - queries: - List of query spectrums. - array_type - Specify the output array type. Can be "numpy" or "sparse". - Default is "numpy" and will return a numpy array. "sparse" will return a COO-sparse array + spectra_1=None, + spectra_2=None, + fingerprints_1=None, + fingerprints_2=None, + score_fields=None, + progress_bar=True, + array_type="scores", + ): + left = self._source(spectra_1, fingerprints_1) + right = self._source(spectra_2, fingerprints_2) + if left is None: + raise ValueError("Either spectra_1 or fingerprints_1 must be provided.") + return super().matrix(left, right, score_fields, progress_bar, array_type) + + def sparse_matrix( + self, + spectra_1=None, + spectra_2=None, + idx_row=None, + idx_col=None, + score_fields=None, + score_filter=None, + progress_bar=True, + *, + min_score=None, + fingerprints_1=None, + fingerprints_2=None, + ): + left = self._source(spectra_1, fingerprints_1) + right = self._source(spectra_2, fingerprints_2) + if left is None: + raise ValueError("Either spectra_1 or fingerprints_1 must be provided.") + return super().sparse_matrix(left, right, idx_row, idx_col, score_fields, score_filter, + progress_bar, min_score=min_score) + + def pair(self, spectrum_1, spectrum_2): + """Compare two vectors, single-row containers, or two spectra with a generator. + + This extends matchms 1.0.0, whose FingerprintSimilarity.pair raises + NotImplementedError. Invalid spectra raise the same error as matrix(). """ - if array_type == "sparse": - raise NotImplementedError( - "Sparse Fingerprint similarity is not yet implemented" - ) - - def get_fingerprints(spectrums): - for index, spectrum in enumerate(spectrums): - yield index, spectrum.get("fingerprint") - - def collect_fingerprints(spectrums): - """Collect fingerprints and indices of spectrum with finterprints.""" - idx_fingerprints = [] - fingerprints = [] - for index, fp in get_fingerprints(spectrums): - if fp is not None: - idx_fingerprints.append(index) - fingerprints.append(fp) - return np.asarray(fingerprints), np.asarray(idx_fingerprints) - - def create_full_matrix(): - """Create matrix for all similarities.""" - similarity_matrix = np.zeros((len(references), len(queries))) - if self.set_empty_scores == "nan": - similarity_matrix[:] = np.nan - elif isinstance(self.set_empty_scores, (float, int)): - similarity_matrix[:] = self.set_empty_scores - return similarity_matrix - - fingerprints1, idx_fingerprints1 = collect_fingerprints(references) - fingerprints2, idx_fingerprints2 = collect_fingerprints(queries) - assert idx_fingerprints1.size > 0 and idx_fingerprints2.size > 0, ( - "Not enough molecular fingerprints.", - "Apply 'add_fingerprint'filter first.", - ) - # Calculate similarity score matrix following specified method - similarity_matrix = create_full_matrix() - - if self.similarity_measure == "jaccard": - similarity_matrix[ - np.ix_(idx_fingerprints1, idx_fingerprints2) - ] = jaccard_similarity_matrix(fingerprints1, fingerprints2) - elif self.similarity_measure == "dice": - similarity_matrix[ - np.ix_(idx_fingerprints1, idx_fingerprints2) - ] = dice_similarity_matrix(fingerprints1, fingerprints2) - elif self.similarity_measure == "cosine": - similarity_matrix[ - np.ix_(idx_fingerprints1, idx_fingerprints2) - ] = cosine_similarity_matrix(fingerprints1, fingerprints2) - if array_type == "sparse": - scores_array = StackedSparseArray(len(references), len(queries)) - scores_array.add_dense_matrix( - similarity_matrix.astype(self.score_datatype), "" - ) - return scores_array - if array_type == "numpy": - return similarity_matrix.astype(self.score_datatype) - raise NotImplementedError("Output array type is not yet implemented.") + def single(value): + if isinstance(value, Fingerprints): + if value.fingerprint_count != 1: + raise ValueError("pair expects a single fingerprint per input") + return value + if hasattr(value, "peaks"): + return [value] + array = value if isinstance(value, torch.Tensor) or sparse.issparse(value) else np.asarray(value) + if array.ndim == 1: + return array.reshape(1, -1) + if array.ndim != 2 or array.shape[0] != 1: + raise ValueError("pair expects a single fingerprint per input") + return array + + return self.matrix( + single(spectrum_1), single(spectrum_2), progress_bar=False, array_type="numpy" + ).reshape(()) diff --git a/simms/similarity/CudaModifiedCosine.py b/simms/similarity/CudaModifiedCosine.py index 9a6e916..3b1bd40 100644 --- a/simms/similarity/CudaModifiedCosine.py +++ b/simms/similarity/CudaModifiedCosine.py @@ -1,427 +1,10 @@ -import logging -import warnings -from itertools import product -from typing import List, Literal, Union -import numpy as np -import torch -from matchms import Spectrum -from matchms.filtering.metadata_processing.add_precursor_mz import _convert_precursor_mz -from matchms.similarity.BaseSimilarity import BaseSimilarity -from numba import cuda -from sparsestack import StackedSparseArray -from tqdm import tqdm -from ..utils import argbatch, get_device -from .spectrum_similarity_functions import cosine_kernel +from .CudaCosineGreedy import _GreedySimilarity -logger = logging.getLogger("simms") +class CudaModifiedCosineGreedy(_GreedySimilarity): + """matchms modified greedy cosine using direct and precursor-shifted candidates.""" + modified = True -def get_valid_precursor_mz(spectrum): - """Extract valid precursor_mz from spectrum if possible. If not raise exception.""" - message_precursor_missing = ( - "Precursor_mz missing. Apply 'add_precursor_mz' filter first." - ) - message_precursor_no_number = "Precursor_mz must be of type int or float. Apply 'add_precursor_mz' filter first." - message_precursor_below_0 = ( - "Expect precursor to be positive number." "Apply 'require_precursor_mz' first" - ) - precursor_mz = spectrum.get("precursor_mz", None) - if not isinstance(precursor_mz, (int, float)): - logger.warning(message_precursor_no_number) - precursor_mz = _convert_precursor_mz(precursor_mz) - assert precursor_mz is not None, message_precursor_missing - assert precursor_mz > 0, message_precursor_below_0 - return precursor_mz - - -class CudaModifiedCosine(BaseSimilarity): - """ - Calculate modified cosine score between mass spectra using CUDA acceleration. - - The modified cosine score aims at quantifying the similarity between two - mass spectra. The score is calculated by finding best possible matches between - peaks of two spectra. Two peaks are considered a potential match if their - m/z ratios lie within the given 'tolerance', or if their m/z ratios - lie within the tolerance once a mass-shift is applied. The mass shift is - simply the difference in precursor-m/z between the two spectra. - See Watrous et al. [PNAS, 2012, https://www.pnas.org/content/109/26/E1743] - for further details. - - This implementation is meant to replicate outputs of `matchms.similarity.ModifiedCosine`. - - For example: - >>> import numpy as np - >>> from matchms import Spectrum - >>> from simms.similarity import CudaModifiedCosine - >>> spectrum_1 = Spectrum(mz=np.array([100, 150, 200.]), - ... intensities=np.array([0.7, 0.2, 0.1]), - ... metadata={"precursor_mz": 100.0}) - >>> spectrum_2 = Spectrum(mz=np.array([104.9, 140, 190.]), - ... intensities=np.array([0.4, 0.2, 0.1]), - ... metadata={"precursor_mz": 105.0}) - >>> modified_cosine = CudaModifiedCosine(tolerance=0.2) - >>> score = modified_cosine.pair(spectrum_1, spectrum_2) - >>> print(f"Modified cosine score is {score['score']:.2f} with {score['matches']} matched peaks") - Modified cosine score is 0.83 with 1 matched peaks - """ - - score_datatype = [ - ("score", np.float32), - ("matches", np.int32), - ("overflow", np.bool_), - ] - - def __init__( - self, - tolerance: float = 0.1, - mz_power: float = 0.0, - intensity_power: float = 1.0, - batch_size: int = 2048, - n_max_peaks: int = 1024, - match_limit: int = 2048, - sparse_threshold: float = 0.75, - verbose=False, - spectra_dtype: Literal["float32", "float64"] = "float64", - ): - """ - Initialize CudaModifiedCosine with specified parameters. - - Parameters: - ----------- - tolerance : float, optional - Tolerance for considering peaks as matching, by default 0.1. - mz_power : float, optional - Exponent for m/z values in similarity score calculation, by default 0.0. - intensity_power : float, optional - Exponent for intensity values in similarity score calculation, by default 1.0. - batch_size : int, optional - Batch size for processing spectra, by default 2048. - n_max_peaks : int, optional - Maximum number of peaks to consider in each spectrum, by default 1024. - match_limit : int, optional - Limit on the number of matches allowed, by default 2048. - sparse_threshold : float, optional - Threshold for considering scores in sparse output, by default 0.75. - verbose : bool, optional - Verbosity flag, by default False. - spectra_dtype : str, optional - What dtype to use to process the spectral information. Default float64. - """ - - # Warn if CUDA device is unavailable - if not cuda.is_available(): - warnings.warn(f"{self.__class__.__name__}: CUDA device seems unavailable.") - - # Initialize parameters - self.tolerance = tolerance - self.mz_power = mz_power - self.int_power = intensity_power - self.batch_size = batch_size - self.match_limit = match_limit - self.verbose = verbose - self.n_max_peaks = n_max_peaks - - assert 0 <= sparse_threshold <= 1, "Sparse threshold has to be greather than 0." - - self.sparse_threshold = sparse_threshold - self.spectra_dtype = spectra_dtype - - self.device = get_device() - - # Compile kernel function - self.kernel = cosine_kernel( - tolerance=self.tolerance, - mz_power=self.mz_power, - int_power=self.int_power, - match_limit=self.match_limit, - batch_size=self.batch_size, - n_max_peaks=self.n_max_peaks, - precursor_shift=True, - spectra_dtype=self.spectra_dtype, - ) - - def _spectra_peaks_to_tensor( - self, - spectra: list, - ) -> tuple[np.ndarray, np.ndarray]: - """ - Convert list of Spectrum objects into numpy arrays. - - Parameters: - ----------- - spectra : list of Spectrum - List of Spectrum objects. - - Returns: - -------- - tuple of np.ndarray - Tuple containing two numpy arrays: one for m/z values and one for intensities. - """ - # Determine dynamic shape - dynamic_shape = max(len(s.peaks) for s in spectra) - if self.n_max_peaks is None: - n_max_peaks = dynamic_shape - else: - n_max_peaks = self.n_max_peaks - - # 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) - spectra_lens = np.zeros(len(spectra), dtype=np.int32) - spectra_precursor_mzs = np.zeros(len(spectra), dtype=dtype) - - # 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] - 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) - return stacked_spectra, spectra_lens, spectra_precursor_mzs - - def _get_batches(self, references, queries): - """ - Generate batches of spectra pairs for processing. - - Parameters: - ----------- - references : list - List of reference Spectrum objects. - queries : list - List of query Spectrum objects. - - Returns: - -------- - list of tuple - List of tuples containing batched input data. - """ - batches_r = [] - for bstart, bend in argbatch(references, self.batch_size): - rspec, rlen, rpmz = self._spectra_peaks_to_tensor(references[bstart:bend]) - batches_r.append([rspec, rlen, rpmz, bstart, bend]) - - batches_q = [] - for bstart, bend in argbatch(queries, self.batch_size): - qspec, qlen, qpmz = self._spectra_peaks_to_tensor(queries[bstart:bend]) - batches_q.append([qspec, qlen, qpmz, bstart, bend]) - - batched_inputs = tuple(product(batches_r, batches_q)) - return batched_inputs - - def pair(self, reference: Spectrum, query: Spectrum) -> float: - """ - Do not use - it is very inefficient, and used for testing purposes only. - Calculates the modified cosine similarity score between a reference and a query spectrum. - - Parameters: - ----------- - reference : Spectrum - Reference spectrum. - query : Spectrum - Query spectrum. - - Returns: - -------- - float - Modified cosine similarity score between the reference and query spectra. - """ - result_mat = self.matrix([reference], [query]) - return np.asarray(result_mat.squeeze(), dtype=self.score_datatype) - - def matrix( - self, - references: List[Spectrum], - queries: List[Spectrum], - array_type: Literal["numpy", "sparse"] = "numpy", - is_symmetric: bool = False, - ) -> Union[np.ndarray, StackedSparseArray]: - """ - 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". - is_symmetric : bool, optional - Unused. This unused argument is left is for compatibility reasons. - - Returns: - -------- - Score : Union[np.ndarray, StackedSparseArray] - 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` - """ - # Warn if is_symmetric is passed - if is_symmetric: - warnings.warn("is_symmetric is ignored here, it has no effect.") - - # Check if array_type is valid - assert array_type in [ - "numpy", - "sparse", - ], f"Invalid array_type '{array_type}'. Use 'numpy' or 'sparse'." - - # 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": - result = torch.empty(3, R, Q, dtype=torch.float32, device=self.device) - elif array_type == "sparse": - result = [] - - # Iterate over batched inputs - with torch.no_grad(): - for batch_i in tqdm(range(len(batched_inputs)), disable=not self.verbose): - # Unpack batched inputs - (rspec, rlen, rpmz, rstart, rend), ( - qspec, - qlen, - qpmz, - qstart, - qend, - ) = batched_inputs[batch_i] - - # Create tensor for spectrum lengths - # Tensor holding lengths and norms - dtype_ = ( - torch.float32 if self.spectra_dtype == "float32" else torch.float64 - ) - metadata = torch.zeros( - 6, self.batch_size, dtype=dtype_, device=self.device - ) - - # Convert spectra to tensors and move to device - rspec = torch.from_numpy(rspec).to(self.device) # 2, R, N - qspec = torch.from_numpy(qspec).to(self.device) # 2, Q, M - - # Pre-calculate norms - rnorm = ( - ( - ( - rspec[0, :, :] ** self.mz_power - * rspec[1, :, :] ** self.int_power - ) - ** 2 - ) - .sum(-1) - .sqrt() - ) # R - qnorm = ( - ( - ( - qspec[0, :, :] ** self.mz_power - * qspec[1, :, :] ** self.int_power - ) - ** 2 - ) - .sum(-1) - .sqrt() - ) # Q - - # Load all spectra metainformation into one tensor - metadata[0, : len(rlen)] = torch.from_numpy(rlen).to( - self.device - ) # Lengths - metadata[1, : len(qlen)] = torch.from_numpy(qlen).to(self.device) - metadata[2, : len(rnorm)] = rnorm # Norms - metadata[3, : len(qnorm)] = qnorm - metadata[4, : len(rpmz)] = torch.from_numpy(rpmz).to( - self.device - ) # Precursor m/z - metadata[5, : len(qpmz)] = torch.from_numpy(qpmz).to(self.device) - - # Initialize output tensor - out = torch.empty( - 3, - self.batch_size, - self.batch_size, - dtype=torch.float32, - device=self.device, - ) - - # Convert tensors to Numba CUDA arrays - rspec = cuda.as_cuda_array(rspec) - qspec = cuda.as_cuda_array(qspec) - metadata = cuda.as_cuda_array(metadata) - out = cuda.as_cuda_array(out) - - # Run GPU kernel - self.kernel(rspec, qspec, metadata, out) - - # Convert output to pytorch tensor - out = torch.as_tensor(out) - - # Populate result based on array_type - if array_type == "numpy": - result[:, rstart:rend, qstart:qend] = out[ - :, : len(rlen), : len(qlen) - ] - elif array_type == "sparse": - mask = out[0] >= self.sparse_threshold - row, col = torch.nonzero(mask, as_tuple=True) - rabs = (rstart + row).cpu() - qabs = (qstart + col).cpu() - score, matches, overflow = out[:, mask].cpu() - result.append( - dict( - rabs=rabs.int().cpu().numpy(), - qabs=qabs.int().cpu().numpy(), - score=score.float().cpu().numpy(), - matches=matches.int().cpu().numpy(), - overflow=overflow.bool().cpu().numpy(), - ) - ) - - # Return result based on array_type - if array_type == "numpy": - return np.rec.fromarrays( - result.cpu().numpy(), - dtype=self.score_datatype, - ) - elif array_type == "sparse": - sp = StackedSparseArray(len(references), len(queries)) - sparse_data = [] - for bunch in result: - sparse_data.append( - ( - bunch["rabs"], - bunch["qabs"], - bunch["score"], - bunch["matches"], - bunch["overflow"], - ) - ) - - if sparse_data: - r, q, s, m, o = zip(*sparse_data) - r = np.concatenate(r) - q = np.concatenate(q) - print(len(r), r, r.max(), r.min()) - print(len(q), q, q.max(), q.min()) - sp.add_sparse_data( - r, - q, - np.rec.fromarrays( - arrayList=[ - np.concatenate(s), - np.concatenate(m), - np.concatenate(o), - ], - names=["score", "matches", "overflow"], - ), - name="sparse", - ) - return sp +CudaModifiedCosine = CudaModifiedCosineGreedy diff --git a/simms/similarity/CudaNeutralLossesCosine.py b/simms/similarity/CudaNeutralLossesCosine.py new file mode 100644 index 0000000..c209950 --- /dev/null +++ b/simms/similarity/CudaNeutralLossesCosine.py @@ -0,0 +1,23 @@ +"""CUDA implementation of matchms NeutralLossesCosine.""" + +import numpy as np + +from .CudaCosineGreedy import _GreedySimilarity +from .spectrum_similarity_functions import NEUTRAL_LOSS_ONLY, exact_score + + +class CudaNeutralLossesCosine(_GreedySimilarity): + """Greedy cosine using only precursor-shifted matches between fragment peaks.""" + + modified = NEUTRAL_LOSS_ONLY + + def _recover(self, left, right, i, j): + def row(peaks, index): + n = peaks.lengths[index] + return np.column_stack((peaks.mz[index, :n], peaks.intensities[index, :n])) + + delta = left.precursor_mz[i] - right.precursor_mz[j] + return exact_score( + row(left, i), row(right, j), [delta], self.tolerance, self.mz_power, + self.intensity_power, raise_zero_division=True, + ) diff --git a/simms/similarity/CudaTransitiveAlignment.py b/simms/similarity/CudaTransitiveAlignment.py new file mode 100644 index 0000000..c869a40 --- /dev/null +++ b/simms/similarity/CudaTransitiveAlignment.py @@ -0,0 +1,295 @@ +# SPDX-License-Identifier: MIT +"""Transitive alignment following Wang et al., JASMS 2024, doi:10.1021/jasms.4c00208.""" + +from collections import deque +from dataclasses import asdict, dataclass +from itertools import chain, islice, pairwise + +import numpy as np +from matchms import Scores +from scipy.sparse import coo_array, issparse + +from ..peaks import PeakArrays +from ._transitive_peaks import PeakAligner +from .CudaModifiedCosine import CudaModifiedCosineGreedy + + +@dataclass(frozen=True) +class AlignmentEdge: + row: int + col: int + score: float + matches: int + hops: int + + +@dataclass +class TransitiveAlignmentResult: + """Undirected edges occur once (row < col). Paths include every attempted bridge. + + peak_pairs, when requested, contains the final greedy assignment for each + retained direct or transitive edge, indexed into the *preprocessed* peak rows. + Pairs are ordered by source peak index. + """ + + n_spectra: int + direct_edges: list[AlignmentEdge] + transitive_edges: list[AlignmentEdge] + paths: dict[tuple[int, int], tuple[int, ...]] + peak_pairs: dict[tuple[int, int], tuple[tuple[int, int], ...]] | None + + def to_dict(self): + """Serialize tuple-keyed mappings as records with explicit row/col fields.""" + return { + "n_spectra": self.n_spectra, + "direct_edges": [asdict(e) for e in self.direct_edges], + "transitive_edges": [asdict(e) for e in self.transitive_edges], + "paths": [{"row": u, "col": v, "path": list(p)} for (u, v), p in self.paths.items()], + "peak_pairs": None + if self.peak_pairs is None + else [ + {"row": u, "col": v, "pairs": [list(pair) for pair in pairs]} + for (u, v), pairs in self.peak_pairs.items() + ], + } + + def to_scores(self, *, sparse=False, transitive_only=False, min_score=None): + edges = self.transitive_edges if transitive_only else chain(self.direct_edges, self.transitive_edges) + rows, cols, scores, counts = [], [], [], [] + for e in edges: + if min_score is not None and not e.score >= min_score: + continue + rows.extend((e.row, e.col)) + cols.extend((e.col, e.row)) + scores.extend((e.score, e.score)) + counts.extend((e.matches, e.matches)) + shape = (self.n_spectra, self.n_spectra) + data = {} + for name, values, dtype in (("score", scores, np.float64), ("matches", counts, np.intp)): + coo = coo_array((np.asarray(values, dtype=dtype), (rows, cols)), shape=shape) + data[name] = coo if sparse else coo.toarray() + return Scores(data) + + +def _paths(edges, max_hops): + # FIFO order finalizes every predecessor's optimal weight before visiting + # the next layer. Each traversal only touches the source's component. + neighbors = {} + for e in edges: + neighbors.setdefault(e.row, []).append((e.col, e.score)) + neighbors.setdefault(e.col, []).append((e.row, e.score)) + for source in sorted(neighbors): + depth, weight, parent = {source: 0}, {source: 0.0}, {} + queue = deque([source]) + while queue: + u = queue.popleft() + d = depth[u] + 1 + if max_hops is not None and d > max_hops: + continue + for v, score in neighbors[u]: + total = weight[u] + score + if v not in depth: + depth[v], weight[v], parent[v] = d, total, u + queue.append(v) + elif depth[v] == d and (total > weight[v] or (total == weight[v] and u < parent[v])): + weight[v], parent[v] = total, u + for v, d in depth.items(): + if v > source and d >= 2: + path = [v] + while path[-1] != source: + path.append(parent[path[-1]]) + yield tuple(reversed(path)) + + +def _batches(items, size): + items = iter(items) + while batch := list(islice(items, size)): + yield batch + + +def _precomputed(base, n, min_score, min_matches): + if isinstance(base, Scores): + if not {"score", "matches"}.issubset(base.score_fields): + raise ValueError("base_scores must supply both score and matches") + field = base.to_coo if base.is_sparse else base.to_array + scores, counts = field("score"), field("matches") + else: + try: + scores, counts = base["score"], base["matches"] + except (IndexError, KeyError, TypeError, ValueError) as exc: + raise ValueError("base_scores must supply both score and matches") from exc + if scores.shape != (n, n) or counts.shape != (n, n): + raise ValueError("base_scores shape must match the number of spectra on both axes") + if issparse(scores) != issparse(counts): + raise ValueError("base score and match fields must both be sparse or both dense") + if issparse(scores): + # COO fields can arrive in different orders and have different sparsity. + # Consider explicitly stored coordinates only, including explicit zeros. + scores, counts = scores.tocsr(), counts.tocsr() + s, m = scores.tocoo(), counts.tocoo() + keys = np.union1d(s.row.astype(np.int64) * n + s.col, m.row.astype(np.int64) * n + m.col) + if not keys.size: + return [] + row, col = np.divmod(keys, n) + sv, mv = np.asarray(scores[row, col]).ravel(), np.asarray(counts[row, col]).ravel() + keep = (row != col) & (sv >= min_score) & (mv >= min_matches) + row, col, sv, mv = row[keep], col[keep], sv[keep], mv[keep] + else: + row, col = np.nonzero((scores >= min_score) & (counts >= min_matches)) + off = row != col + row, col = row[off], col[off] + sv, mv = scores[row, col], counts[row, col] + edges = {} + for u, v, score, matches in zip(row, col, sv, mv): + if not np.isfinite(score) or not np.isfinite(matches) or int(matches) != matches: + raise ValueError("retained direct edges need finite scores and integer match counts") + key = tuple(sorted((int(u), int(v)))) + edge = AlignmentEdge(*key, float(score), int(matches), 1) + previous = edges.get(key) + if previous is not None and previous != edge: + # A triangular dense matrix uses zeros for the missing direction. + if (edge.score, edge.matches) == (0, 0): + continue + if (previous.score, previous.matches) != (0, 0): + raise ValueError(f"inconsistent mirrored base scores for {key}") + edges[key] = edge + return [edges[key] for key in sorted(edges)] + + +class CudaTransitiveAlignment: + """Build a molecular network on a single collection of spectra. + + Pass base_scores to any entry point to reuse a modified-cosine matrix in + the same spectrum order and preprocessing. Accepts matchms Scores, a + structured array, or a mapping of dense or sparse score and matches fields. + Either triangle or a symmetric matrix is accepted. Self edges are omitted. + max_hops counts edges. Equal-hop, equal-sum paths prefer the smaller final + predecessor recursively. On equal peak products, shifted candidates precede + unshifted candidates, followed by bridge-only candidates (descending source + index). The direct alignment in row < col orientation is inverted on reverse + traversal. n_max_peaks and match_limit bound GPU scratch; overflow uses the + complete preprocessed spectra on the CPU. + """ + + def __init__( + self, + tolerance=0.01, + mz_power=0.0, + intensity_power=1.0, + remove_precursor=True, + offset_to_precursor=-1.6, + noise_cutoff=0.01, + min_direct_score=0.7, + min_direct_matches=6, + min_transitive_score=0.0, + max_hops=None, + batch_size=2048, + precision="float64", + *, + n_max_peaks=None, + match_limit=2048, + ): + self.direct = CudaModifiedCosineGreedy( + tolerance=tolerance, + mz_power=mz_power, + intensity_power=intensity_power, + remove_precursor=remove_precursor, + offset_to_precursor=offset_to_precursor, + noise_cutoff=noise_cutoff, + batch_size=batch_size, + precision=precision, + n_max_peaks=n_max_peaks, + match_limit=match_limit, + ) + self.min_direct_score = float(min_direct_score) + self.min_transitive_score = float(min_transitive_score) + if not np.all(np.isfinite([self.min_direct_score, self.min_transitive_score])): + raise ValueError("score thresholds must be finite") + for name, value in (("min_direct_matches", min_direct_matches), ("max_hops", max_hops)): + if name == "max_hops" and value is None: + continue + if isinstance(value, (bool, np.bool_)) or not isinstance(value, (int, np.integer)) or value < 0: + raise ValueError(f"{name} must be a non-negative integer") + self.min_direct_matches = min_direct_matches + self.max_hops = max_hops + + def _direct_edges(self, peaks, progress_bar): + # Filter upper-triangle tiles before constructing any per-edge objects. + edges = [] + if len(peaks) < 2: + return edges + tiles = self.direct._tiles(peaks, peaks, True, None, progress_bar) + for rows, cols, values in self.direct._filtered_tiles( + tiles, True, self.min_direct_score, self.min_direct_matches, diagonal=1 + ): + edges.extend( + AlignmentEdge(int(i), int(j), float(score), int(matches), 1) + for i, j, (score, matches) in zip(rows, cols, values) + ) + return sorted(edges, key=lambda e: (e.row, e.col)) + + def align(self, spectra, *, base_scores=None, return_peak_pairs=False, progress_bar=False): + """Return paths, direct and new edges, and optionally their endpoint peak indices.""" + method = self.direct + peaks = PeakArrays.from_spectra( + spectra, True, method.remove_precursor, method.offset_to_precursor, method.noise_cutoff + ) + direct = ( + self._direct_edges(peaks, progress_bar) + if base_scores is None + else _precomputed(base_scores, len(peaks), self.min_direct_score, self.min_direct_matches) + ) + result = TransitiveAlignmentResult(len(peaks), direct, [], {}, {} if return_peak_pairs else None) + paths = _paths(direct, self.max_hops) + first = next(paths, None) + if first is None and (not direct or not return_peak_pairs): + return result + + aligner = PeakAligner(peaks, method) + offsets = {} + size = 0 + for e in direct: + for u, v in ((e.row, e.col), (e.col, e.row)): + offsets[u, v] = size + size += int(peaks.lengths[u]) + maps = np.full(size, -1, dtype=np.int32) + for batch in _batches(((e.row, e.col) for e in direct), method.batch_size): + assignments = aligner.batch(batch, np.zeros(len(batch) + 1, dtype=np.int64), []) + for (u, v), (_, _, pairs) in zip(batch, assignments): + for a, b in pairs: + maps[offsets[u, v] + a] = b + maps[offsets[v, u] + b] = a + if return_peak_pairs: + result.peak_pairs[u, v] = pairs + if first is None: + return result + aligner.set_maps(maps) + for batch in _batches(chain((first,), paths), method.batch_size): + endpoints, steps, starts = [], [], [0] + for path in batch: + u, v = path[0], path[-1] + result.paths[u, v] = path + endpoints.append((u, v)) + steps.extend(offsets[a, b] for a, b in pairwise(path)) + starts.append(len(steps)) + assignments = aligner.batch(endpoints, starts, steps, return_pairs=return_peak_pairs) + for path, (score, matches, pairs) in zip(batch, assignments): + if matches and score >= self.min_transitive_score: + u, v = path[0], path[-1] + result.transitive_edges.append(AlignmentEdge(u, v, score, matches, len(path) - 1)) + if return_peak_pairs: + result.peak_pairs[u, v] = pairs + return result + + def matrix(self, spectra, *, base_scores=None, transitive_only=False, progress_bar=False): + """Symmetric dense matchms Scores with a zero diagonal.""" + return self.align(spectra, base_scores=base_scores, progress_bar=progress_bar).to_scores( + transitive_only=transitive_only + ) + + def sparse_matrix(self, spectra, *, base_scores=None, transitive_only=False, progress_bar=False, + min_score=None): + """Return symmetric sparse scores for final edges meeting the optional min_score.""" + return self.align(spectra, base_scores=base_scores, progress_bar=progress_bar).to_scores( + sparse=True, transitive_only=transitive_only, min_score=min_score + ) diff --git a/simms/similarity/__init__.py b/simms/similarity/__init__.py index c36bbae..f86f3e2 100644 --- a/simms/similarity/__init__.py +++ b/simms/similarity/__init__.py @@ -1,6 +1,24 @@ +from .CudaBinnedEmbeddingSimilarity import CudaBinnedEmbeddingSimilarity from .CudaCosineGreedy import CudaCosineGreedy +from .CudaCosineLinear import CudaCosineLinear, CudaModifiedCosineLinear +from .CudaEntropyGreedy import CudaEntropyGreedy from .CudaFingerprintSimilarity import CudaFingerprintSimilarity -from .CudaModifiedCosine import CudaModifiedCosine +from .CudaModifiedCosine import CudaModifiedCosine, CudaModifiedCosineGreedy +from .CudaNeutralLossesCosine import CudaNeutralLossesCosine +from .CudaTransitiveAlignment import CudaTransitiveAlignment as CudaTransitiveAlignment +from .CudaTransitiveAlignment import TransitiveAlignmentResult as TransitiveAlignmentResult -__all__ = ["CudaCosineGreedy", "CudaFingerprintSimilarity", "CudaModifiedCosine"] +# Callers enumerate __all__ to discover pairwise similarities. The network +# aligner and its result are available as explicit package imports above. +__all__ = [ + "CudaBinnedEmbeddingSimilarity", + "CudaCosineGreedy", + "CudaCosineLinear", + "CudaEntropyGreedy", + "CudaFingerprintSimilarity", + "CudaModifiedCosine", + "CudaModifiedCosineGreedy", + "CudaModifiedCosineLinear", + "CudaNeutralLossesCosine", +] diff --git a/simms/similarity/_base.py b/simms/similarity/_base.py new file mode 100644 index 0000000..7e05c49 --- /dev/null +++ b/simms/similarity/_base.py @@ -0,0 +1,178 @@ +"""matchms score containers and tiled dense / coordinate-restricted sparse output.""" + +import inspect + +import numpy as np +import torch +from matchms import Scores +from matchms.similarity.base_similarity import BaseSimilarityWithSparse + + +class CudaSimilarity(BaseSimilarityWithSparse): + score_datatype = np.dtype([("score", np.float64), ("matches", np.int_)]) + score_fields = score_datatype.names + + def to_dict(self): + params = {} + for name in inspect.signature(type(self)).parameters: + value = getattr(self, name) + params[name] = value.item() if isinstance(value, np.generic) else value + return {"__Similarity__": type(self).__name__, **params} + + def _fields(self, score_fields): + if isinstance(score_fields, str): + score_fields = (score_fields,) + fields = self._resolve_score_fields(score_fields) + if len(set(fields)) != len(fields): + raise ValueError("score_fields must be unique") + return fields + + def pair(self, spectrum_1, spectrum_2): + """Return the same zero-dimensional structured array as matchms.""" + return self.matrix([spectrum_1], [spectrum_2], progress_bar=False, array_type="numpy").reshape(()) + + def matrix(self, spectra_1, spectra_2=None, score_fields=None, progress_bar=True, array_type="scores"): + """Return Scores, a structured NumPy array, or a device tensor. + + Torch planes follow score_fields order, by default (score, matches), with + shape (2, rows, columns) and the requested floating-point precision. + """ + fields = self._fields(score_fields) + if array_type not in ("scores", "numpy", "torch"): + raise ValueError("array_type must be 'scores', 'numpy' or 'torch'") + left, right, symmetric = self._inputs(spectra_1, spectra_2) + shape = (len(left), len(right)) + if array_type == "torch": + result = torch.empty( + (len(fields), *shape), dtype=getattr(torch, self.precision), device=self.device + ) + elif array_type == "numpy": + result = np.empty(shape, dtype=[(f, self.score_datatype[f]) for f in fields]) + else: + result = self._create_dense_result(*shape, fields) + + for rows, cols, _, tile in self._tiles(left, right, symmetric, None, progress_bar): + if array_type != "torch": + tile = tile.cpu().numpy() + for plane, field in enumerate(fields): + values = tile[self.score_fields.index(field)].reshape( + rows.stop - rows.start, cols.stop - cols.start + ) + dest = result[plane] if array_type == "torch" else result[field] + dest[rows, cols] = values + if symmetric and rows.start != cols.start: + dest[cols, rows] = values.T + return Scores(result) if array_type == "scores" else result + + def _coordinate_tiles(self, idx_row, idx_col, shape, symmetric): + if idx_row is None and idx_col is None: + return None + if idx_row is None or idx_col is None: + raise ValueError("idx_row and idx_col must be given together") + row, col = np.asarray(idx_row), np.asarray(idx_col) + if row.ndim != 1 or row.shape != col.shape: + raise ValueError("idx_row and idx_col must be aligned 1D arrays") + for index, size in zip((row, col), shape): + if index.size and index.dtype.kind not in "iu": + raise TypeError("sparse coordinates must be integers") + if np.any(index < 0) or np.any(index >= size): + raise ValueError("sparse coordinate out of bounds") + tiles = {} + for i, j in zip(row, col): + i, j = int(i), int(j) + if symmetric and i > j: + i, j = j, i + r, c = i - i % self.batch_size, j - j % self.batch_size + width = min(self.batch_size, shape[1] - c) + tiles.setdefault(r, {}).setdefault(c, []).append((i - r) * width + j - c) + for columns in tiles.values(): + for c, positions in columns.items(): + columns[c] = list(dict.fromkeys(positions)) + return tiles + + def _filtered_tiles(self, tiles, symmetric, min_score, min_matches, score_filter=None, diagonal=0): + """Yield retained upper-triangle or rectangular coordinates and full host records.""" + predicate = score_filter + if predicate is None and getattr(self.keep_score, "__func__", None) is not BaseSimilarityWithSparse.keep_score: + predicate = self.keep_score + structured = self.is_structured_score + score_dtype = self.score_datatype["score"] if structured else self.score_datatype + for rs, cs, positions, tile in tiles: + score = tile[0] if structured else tile + keep = None + if min_score is not None: + # Compare at the precision of the public NumPy score and threshold. + dtype = np.result_type(score_dtype, min_score) + keep = score.to(getattr(torch, dtype.name)) >= min_score + if min_matches is not None: + enough = tile[1].double() >= min_matches + keep = enough if keep is None else keep & enough + if predicate is None and keep is None: + keep = score != 0 + if structured: + keep &= tile[1] != 0 + + width = cs.stop - cs.start + if symmetric and rs == cs and positions is None: + # Explicit coordinates have already been canonicalized and deduplicated. + if keep is None: + keep = torch.ones_like(score, dtype=torch.bool) + keep.view(-1, width).triu_(diagonal) + + if keep is None: + # An arbitrary Python predicate needs every remaining candidate. + local = np.arange(score.numel()) if positions is None else positions + else: + indices = torch.nonzero(keep).flatten() + if not indices.numel(): + continue + tile = tile.index_select(-1, indices) + local = indices.cpu().numpy() + if positions is not None: + local = positions[local] + host = tile.cpu().numpy() + if structured: + values = np.empty(len(local), dtype=self.score_datatype) + values["score"], values["matches"] = host + else: + values = host + if predicate is not None: + keep = np.fromiter(map(predicate, self._predicate_values(values)), bool, count=len(local)) + local, values = local[keep], values[keep] + if len(local): + i, j = np.divmod(local, width) + yield i + rs.start, j + cs.start, values + + _predicate_values = staticmethod(iter) + + def sparse_matrix( + self, spectra_1, spectra_2=None, idx_row=None, idx_col=None, + score_fields=None, score_filter=None, progress_bar=True, *, min_score=None, min_matches=None, + ): + """Apply inclusive device thresholds before any callable and field projection.""" + fields = self._fields(score_fields) + left, right, symmetric = self._inputs(spectra_1, spectra_2) + # SciPy sparse fingerprint matrices expose their number of rows only via shape. + shape = tuple(data.shape[0] if hasattr(data, "shape") else len(data) for data in (left, right)) + requested = self._coordinate_tiles(idx_row, idx_col, shape, symmetric) + tiles = self._tiles(left, right, symmetric, requested, progress_bar) + chunks = [] + for i, j, values in self._filtered_tiles(tiles, symmetric, min_score, min_matches, score_filter): + chunks.append((i, j, values)) + if symmetric: + off = i != j + chunks.append((j[off], i[off], values[off])) + if chunks: + rows, cols, values = map(np.concatenate, zip(*chunks)) + else: + rows = cols = np.empty(0, dtype=np.intp) + values = np.empty(0, dtype=self.score_datatype) + return Scores(self._build_sparse_result(rows, cols, values, shape, fields)) + + +class _ScalarCudaSimilarity(CudaSimilarity): + def sparse_matrix(self, spectra_1, spectra_2=None, idx_row=None, idx_col=None, + score_fields=None, score_filter=None, progress_bar=True, *, min_score=None): + """Apply an inclusive device score threshold before any callable.""" + return super().sparse_matrix(spectra_1, spectra_2, idx_row, idx_col, score_fields, + score_filter, progress_bar, min_score=min_score) diff --git a/simms/similarity/_transitive_peaks.py b/simms/similarity/_transitive_peaks.py new file mode 100644 index 0000000..a68b7c1 --- /dev/null +++ b/simms/similarity/_transitive_peaks.py @@ -0,0 +1,270 @@ +# SPDX-License-Identifier: MIT +"""Greedy peak evidence for retained edges and paths on the direct network.""" + +from functools import lru_cache +from math import sqrt + +import numpy as np +from matchms.similarity.spectrum_similarity_functions import collect_peak_pairs +from numba import cuda, float32, float64, int32, uint8 + +from .CudaCosineGreedy import _scratch_size +from .spectrum_similarity_functions import _collect, _sift_down, peak_weights + + +@lru_cache(maxsize=32) +def _alignment_kernel(width, capacity, precision): + real = float64 if precision == "float64" else float32 + + @cuda.jit + def kernel( + mz, + weights, + norms, + lengths, + precursors, + endpoints, + tolerance, + limit, + starts, + steps, + maps, + scores, + counts, + assignment, + ): + k = cuda.grid(1) + if k >= len(endpoints): + return + u, v = endpoints[k] + nr, nq = lengths[u], lengths[v] + scores[k], counts[k] = 0, 0 + if nr > mz.shape[1] or nq > mz.shape[1]: + counts[k] = -1 + return + if norms[u] == 0 or norms[v] == 0: + return + + left = cuda.local.array(capacity, int32) + right = cuda.local.array(capacity, int32) + order = cuda.local.array(capacity, int32) + values = cuda.local.array(capacity, real) + count = 0 + delta = precursors[u] - precursors[v] + begin, end = starts[k], starts[k + 1] + if begin < end: + survived = False + for a in range(nr): + b = a + for hop in range(begin, end): + b = maps[steps[hop] + b] + if b == -1: + break + if b == -1: + continue + survived = True + low, high = float64(mz[u, a]) - tolerance, float64(mz[u, a]) + tolerance + mass = float64(mz[v, b]) + if low <= mass <= high or (abs(delta) > tolerance and low <= mass + delta <= high): + continue # The later endpoint candidate supplies its tie order. + if count == limit: + counts[k] = -1 + return + left[count], right[count], order[count] = a, b, count + values[count] = weights[u, a] * weights[v, b] + count += 1 + if not survived: + return + + bridge_count = count + count = _collect( + mz[u], + weights[u], + nr, + mz[v], + weights[v], + nq, + tolerance, + 0.0, + count, + limit, + left, + right, + order, + values, + False, + ) + if count >= 0 and abs(delta) > tolerance: + unshifted_end = count + count = _collect( + mz[u], + weights[u], + nr, + mz[v], + weights[v], + nq, + tolerance, + delta, + count, + limit, + left, + right, + order, + values, + False, + ) + if count > unshifted_end: + # Keep the later (shifted) occurrence when both windows cover + # the same pair. Heap priority still uses original candidate IDs. + size = bridge_count + for idx in range(bridge_count, count): + if idx < unshifted_end: + mass = float64(mz[u, left[idx]]) + shifted = float64(mz[v, right[idx]]) + delta + if mass - tolerance <= shifted <= mass + tolerance: + continue + order[size] = idx + size += 1 + count = size + if count < 0: + counts[k] = -1 + return + + used = cuda.local.array(width, uint8) + for b in range(nq): + used[b] = 0 + for root in range(count // 2 - 1, -1, -1): + _sift_down(order, values, root, count) + total = real(0) + while count: + idx = order[0] + a, b = left[idx], right[idx] + if assignment[k, a] == -1 and not used[b]: + assignment[k, a] = b + used[b] = 1 + total += values[idx] + counts[k] += 1 + count -= 1 + order[0] = order[count] + _sift_down(order, values, 0, count) + scores[k] = total / sqrt(norms[u] * norms[v]) + + return kernel + + +def _recover(peaks, method, u, v, steps, maps): + """Recover *both* evidence and score from uncapped, double precision rows.""" + + def row(i): + n = peaks.lengths[i] + return np.column_stack((peaks.mz[i, :n], peaks.intensities[i, :n])) + + left, right = row(u), row(v) + products = {} + if len(steps): + for a in range(len(left)): + b = a + for offset in steps: + b = maps[offset + b] + if b == -1: + break + if b != -1: + products[a, int(b)] = None + if not products: + return 0.0, () + + delta = peaks.precursor_mz[u] - peaks.precursor_mz[v] + shifts = (0.0, delta) if abs(delta) > method.tolerance else (0.0,) + # Store the last occurrence, as in a reversed stable ascending product sort. + for shift in shifts: + pairs = collect_peak_pairs( + left, right, method.tolerance, shift, method.mz_power, method.intensity_power + ) + if pairs is not None: + for a, b, _ in pairs: + key = int(a), int(b) + products.pop(key, None) + products[key] = None + if not products: + return 0.0, () + + def weighted(row): + weights, norms = peak_weights( + row[:, 0].reshape(1, -1), + row[:, 1].reshape(1, -1), + np.array([len(row)]), + method.mz_power, + method.intensity_power, + ) + return weights[0], norms[0] + + w1, n1 = weighted(left) + w2, n2 = weighted(right) + if n1 == 0 or n2 == 0: + return 0.0, () + used_left, used_right, selected = set(), set(), [] + total = 0.0 + ordered = sorted(products, key=lambda p: w1[p[0]] * w2[p[1]]) + for a, b in reversed(ordered): + if a not in used_left and b not in used_right: + used_left.add(a) + used_right.add(b) + selected.append((a, b)) + total += w1[a] * w2[b] + return float(total / sqrt(n1 * n2)), tuple(sorted(selected)) + + +class PeakAligner: + """Upload spectra once. Each path step addresses a ragged directed map by offset.""" + + def __init__(self, peaks, method): + self.peaks, self.method = peaks, method + self.width = min(peaks.width, method.n_max_peaks or 8192, 8192) + mz = np.ascontiguousarray(peaks.mz[:, : self.width], dtype=method.precision) + intensities = np.ascontiguousarray(peaks.intensities[:, : self.width], dtype=method.precision) + weights, norms = peak_weights(mz, intensities, peaks.lengths, method.mz_power, method.intensity_power) + self.device_rows = tuple( + cuda.to_device(a) for a in (mz, weights, norms, peaks.lengths, peaks.precursor_mz) + ) + # Bound per-thread local memory even if the public candidate limit is large. + self.limit = min(method.match_limit, 512, max(1, 3 * self.width**2)) + self.kernel = _alignment_kernel( + _scratch_size(self.width), _scratch_size(self.limit), method.precision + ) + self.set_maps(np.empty(0, dtype=np.int32)) + + def set_maps(self, maps): + self.maps = maps + self.device_maps = cuda.to_device(maps) + + def batch(self, endpoints, starts, steps, *, return_pairs=True): + n = len(endpoints) + assignments = cuda.to_device(np.full((n, self.width), -1, dtype=np.int32)) + scores = cuda.device_array(n, dtype=self.method.precision) + counts = cuda.device_array(n, dtype=np.int32) + starts, steps = np.asarray(starts, dtype=np.int64), np.asarray(steps, dtype=np.int64) + self.kernel[(n + 63) // 64, min(n, 64)]( + *self.device_rows, + cuda.to_device(np.asarray(endpoints, dtype=np.intp)), + self.method.tolerance, + self.limit, + cuda.to_device(starts), + cuda.to_device(steps), + self.device_maps, + scores, + counts, + assignments, + ) + host_maps = assignments.copy_to_host() if return_pairs else None + for i, (score, count) in enumerate(zip(scores.copy_to_host(), counts.copy_to_host())): + if count < 0: + score, pairs = _recover( + self.peaks, self.method, *endpoints[i], steps[starts[i] : starts[i + 1]], self.maps + ) + yield score, len(pairs), pairs if return_pairs else None + else: + pairs = None + if return_pairs: + active = np.flatnonzero(host_maps[i] >= 0) + pairs = tuple(zip(active.tolist(), host_maps[i, active].tolist())) + yield float(score), int(count), pairs diff --git a/simms/similarity/spectrum_similarity_functions.py b/simms/similarity/spectrum_similarity_functions.py index dff3c10..e77cb95 100644 --- a/simms/similarity/spectrum_similarity_functions.py +++ b/simms/similarity/spectrum_similarity_functions.py @@ -1,531 +1,312 @@ -""" -Defines CUDA kernels written using the Numba API -""" - -import warnings -from functools import wraps -from typing import Callable, Literal -import numba -from numba import cuda, float32, int32, types, void - - -def kernel_wrapper(blocks_per_grid, threads_per_block) -> None: - """ - Convenience wrapper around CUDA kernel. Launches the kernel with the given grid/thread dimensions - """ - - def decorator(kernel_fn): - @wraps(kernel_fn) - def kernel(rspec, qspec, metadata, out, stream: cuda.stream = None): - """ - Parameters: - ----------- - rspec : cuda.devicearray - Array containing reference spectra data. - qspec : cuda.devicearray - Array containing query spectra data. - metadata : cuda.devicearray - Array containing pieces of information about each incoming spectrum. Usually, we store spectrum length, norm and - optionally precursor m/z. - out : cuda.devicearray - An array storing all the results: score, matches, and overflows - stream : cuda.stream, optional - CUDA stream for asynchronous execution of the kernel - """ - kernel_fn[blocks_per_grid, threads_per_block, stream]( - rspec, - qspec, - metadata, - out, - ) - - return kernel - - return decorator - - -def cosine_kernel( - tolerance: float = 0.1, - shift: float = 0, - mz_power: float = 0.0, - int_power: float = 1.0, - precursor_shift: bool = False, - is_symmetric: bool = False, - match_limit: int = 1024, - batch_size: int = 2048, - n_max_peaks: int = 2048, - spectra_dtype: Literal["float32", "float64"] = "float32", -) -> Callable: - """ - Compiles and returns a CUDA kernel function for calculating cosine similarity scores between spectra. - If `precursor_shift` is True, the resulting kernel behaves computes modified cosine. Otherwise, it computes cosine greedy. - - Parameters: - ----------- - tolerance : float, optional - Tolerance parameter for m/z matching, by default 0.1. - shift : float, optional - Shift parameter for m/z matching, by default 0. - mz_power : float, optional - Power parameter for m/z intensity calculation, by default 0. - int_power : float, optional - Power parameter for intensity calculation, by default 1. - precursor_shift: bool - When True, calculates `ModifiedCosine`, when false, calculates `CosineGreedy`. - is_symmetric : bool, optional - Unused. Flag indicating if the similarity matrix is symmetric, but we don't use it. Left here for matchms compatbility reasons. - match_limit : int, optional - Maximum number of matches to consider per peak, by default 1024. - batch_size : int, optional - Batch size for simultaneous pairwise processing spectra, by default 2048. New hardware (RTX4090) - is better with larger values, and older (T4) with smaller values - n_max_peaks : int, optional - Maximum number of peaks to consider per spectra, by default 2048. - spectra_dtype: str, optional - Float dtype to use for representing peaks. float32 is faster, but precision-related errors are slightly more common, - By default, we use float32 for greedy cosine and float64 for modified cosine. - - Returns - -------- - callable - CUDA kernel function for calculating cosine similarity scores. - - For example: - - >>> from simms.similarity.spectrum_similarity_functions import cosine_kernel - >>> from numba import cuda - >>> import numpy as np - >>> batch_size, n_max_peaks = 2, 4 - >>> kernel = cosine_kernel(tolerance=0.1, n_max_peaks=n_max_peaks, batch_size=batch_size) - >>> rspec = cuda.to_device(np.array([ - ... [ [1., 10., 100., 200.,], # mz values - ... [2., 20., 200., 400.,], ], - ... [ [1., 1., 1., 1.,], # Intensities - ... [1., 1., 1., 1.,], ] - ... ], dtype=np.float32)) - >>> qspec = rspec # symmetric - >>> metadata = cuda.to_device(np.array([ - ... [ 4., 4., ], # lengths of reference spectra - ... [ 4., 4., ], # lengths of query spectra - ... [ 2., 2., ], # norms of reference spectra - ... [ 2., 2., ], # norms of query spectra - ... ], dtype=np.float32)) - >>> out = cuda.to_device(np.zeros((3, batch_size, batch_size), dtype=np.float32)) - >>> kernel(rspec, qspec, metadata, out) - >>> scores, matches, overflows = out.copy_to_host() - >>> print(scores) - [[1. 0.25] - [0.25 1. ]] - """ - - if is_symmetric: - warnings.warn("no effect from is_symmetric, it is not yet implemented") - - # Define global constants. These values will be transferred by NUMBA to the GPU, as global read-only constants - PRECURSOR_SHIFT = precursor_shift - - if PRECURSOR_SHIFT: - # We need twice the match limit for modified cosine for the same accuracy - MATCH_LIMIT = match_limit * 2 - else: - MATCH_LIMIT = match_limit - - assert ( - precursor_shift is False or shift == 0 - ), "When working with precursor_shift=True mode, specifying shift != 0 is meaningless." - - if precursor_shift is True and spectra_dtype != "float64": - warnings.warn( - "When working with precursor_shift=True mode, using spectra_dtype=float64 is recommended" - ) - - SHIFT = shift - MZ_POWER = mz_power - INT_POWER = int_power - TOLERANCE = tolerance - N_MAX_PEAKS = n_max_peaks - R, Q = batch_size, batch_size - THREADS_PER_BLOCK_X = 1 - THREADS_PER_BLOCK_Y = 512 - THREADS_PER_BLOCK = (THREADS_PER_BLOCK_X, THREADS_PER_BLOCK_Y) - BLOCKS_PER_GRID_X = (R + THREADS_PER_BLOCK_X - 1) // THREADS_PER_BLOCK_X - BLOCKS_PER_GRID_Y = (Q + THREADS_PER_BLOCK_Y - 1) // THREADS_PER_BLOCK_Y - BLOCKS_PER_GRID = (BLOCKS_PER_GRID_X, BLOCKS_PER_GRID_Y) - FLOAT = numba.types.Float(spectra_dtype) - - # Arguments: matched peaks [match_limit], peak value [match_limit], and return values [2] - @cuda.jit( - int32( - # Inputs - int32, - int32, - FLOAT[:, :, ::1], - FLOAT[:, :, ::1], - FLOAT[:, ::1], - # Outputs - int32[::1], - float32[::1], - ), - device=True, - inline=True, - ) - def collect_peak_pairs( - # Inputs - reference_i, - query_j, - rspec, - qspec, - metadata, - # Outputs - matches, - values, - ): - """ - Roughly equivalent to the `matchms.similarity.spectrum_similarity_functions.find_matches` - Collects all matching peaks within TOLERANCE and writes found `matches` and their peak products in `values`. - Returns one integer `num_matches`, which specifies how many peaks we've managed to match. - """ - rleni = types.int32(metadata[0, reference_i]) - qlenj = types.int32(metadata[1, query_j]) - - # If either R or Q spectra are empty, return - if rleni == 0 or qlenj == 0: - return 0 - - # Unpack R into m/z and intensity sets - rmz = rspec[0] # rmz is [batch_size, n_max_peaks] - rint = rspec[1] # rint is [batch_size, n_max_peaks] - - # Read current thread's reference spectrum - spec1_mz = rmz[reference_i] # spec1_mz is [n_max_peaks] - spec1_int = rint[reference_i] # spec1_int is [n_max_peaks] - - # Similar steps for reading this thread's Query - qmz = qspec[0] - qint = qspec[1] - spec2_mz = qmz[query_j] - spec2_int = qint[query_j] - - lowest_idx = types.int32(0) - num_match = types.int32(0) - overflow = types.boolean(False) - - for peak1_idx in range(rleni): - if overflow: - break - mz_r = spec1_mz[peak1_idx] - int_r = spec1_int[peak1_idx] - for peak2_idx in range(lowest_idx, qlenj): - if overflow: - break - mz_q = spec2_mz[peak2_idx] - if mz_q + SHIFT > mz_r + TOLERANCE: - break - if mz_q + SHIFT + TOLERANCE < mz_r: - lowest_idx = peak2_idx + 1 - else: - if not overflow: - int_q = spec2_int[peak2_idx] - # Binary trick! - # since we know that the largest imaginable peak index can fit in 13 bits - # We pack two 16bit ints in 32bit int to use less memory - matches[num_match] = (peak1_idx << 16) | peak2_idx - values[num_match] = (mz_r**MZ_POWER * int_r**INT_POWER) * ( - mz_q**MZ_POWER * int_q**INT_POWER - ) - num_match += 1 - # Once we have filled the entire allocated `matches` array, we stop adding more. We call this the `overflow` - overflow = ( - num_match >= MATCH_LIMIT - ) # This is the errorcode for overflow - if overflow: - num_match = -num_match - return num_match - - # Arguments: matched peaks [match_limit], peak value [match_limit], and return values [2] - @cuda.jit( - int32( - # Inputs - int32, - int32, - FLOAT[:, :, ::1], - FLOAT[:, :, ::1], - FLOAT[:, ::1], - # Outputs - int32[::1], - float32[::1], - ), - device=True, - inline=True, - ) - def collect_shifted_peak_pairs( - # Inputs - reference_i, - query_j, - rspec, - qspec, - metadata, - # Outputs - matches, - values, - ): - rleni = types.int32(metadata[0, reference_i]) - qlenj = types.int32(metadata[1, query_j]) - - # If either R or Q spectra are empty, return - if rleni == 0 or qlenj == 0: - return 0 - - # Unpack R into m/z and intensity sets - rmz = rspec[0] # rmz is [batch_size, n_max_peaks] - rint = rspec[1] # rint is [batch_size, n_max_peaks] - - # Read current thread's reference spectrum - spec1_mz = rmz[reference_i] # spec1_mz is [n_max_peaks] - spec1_int = rint[reference_i] # spec1_int is [n_max_peaks] - - # Similar steps for reading this thread's Query - qmz = qspec[0] - qint = qspec[1] - spec2_mz = qmz[query_j] - spec2_int = qint[query_j] - - lowest_idx = types.int32(0) - num_match = types.int32(0) - overflow = types.boolean(False) - - for peak1_idx in range(rleni): - if overflow: +"""Bounded CUDA greedy assignment and exact matchms recovery for oversized pairs.""" + +from functools import lru_cache +from math import inf, isnan, log2, sqrt + +import numpy as np +from matchms.similarity.spectrum_similarity_functions import collect_peak_pairs, score_best_matches +from numba import cuda, float32, float64, int32, njit, uint8, uint32 + + +@njit(fastmath=True) +def _squared_norm(weighted): + # Use the same reduction and math flags as matchms.score_best_matches. + return np.sum(weighted**2) + + +@njit +def peak_weights(mz, intensity, lengths, mz_power, intensity_power): + """Compute each weight once. Padding must never be raised to a power.""" + weights = np.zeros_like(mz) + norms = np.zeros(len(lengths), dtype=mz.dtype) + for i in range(len(lengths)): + n = min(lengths[i], mz.shape[1]) + for j in range(n): + weights[i, j] = mz[i, j] ** mz_power * intensity[i, j] ** intensity_power + norms[i] = _squared_norm(weights[i, :n]) + return weights, norms + + +def exact_score(left, right, shifts, tolerance, mz_power, intensity_power, *, raise_zero_division=False): + """Use matchms's candidate generation, reversed stable sort, assignment and normalization.""" + pairs = [] + for shift in shifts: + candidates = collect_peak_pairs(left, right, tolerance, shift, mz_power, intensity_power) + if candidates is not None: + pairs.append(candidates) + if not pairs: + return 0.0, 0 + candidates = np.concatenate(pairs) + order = np.argsort(candidates[:, 2], kind="stable")[::-1] + try: + return score_best_matches(candidates[order], left, right, mz_power, intensity_power) + except ZeroDivisionError: + # matchms divides by zero when all valid weights on one side are zero. + if raise_zero_division: + raise + return 0.0, 0 + + +@cuda.jit(device=True) +def _higher_priority(values, a, b): + # Reversing a stable ascending sort puts the later candidate first on ties. + return values[a] > values[b] or (values[a] == values[b] and a > b) + + +@cuda.jit(device=True) +def _sift_down(order, values, root, size): + while 2 * root + 1 < size: + child = 2 * root + 1 + if child + 1 < size and _higher_priority(values, order[child + 1], order[child]): + child += 1 + if not _higher_priority(values, order[child], order[root]): + break + order[root], order[child] = order[child], order[root] + root = child + + +@cuda.jit(device=True) +def _collect( + rmz, rw, nr, qmz, qw, nq, tolerance, shift, count, limit, left, right, order, values, count_only +): + start = 0 + for a in range(nr): + # Keep inclusive bounds in double precision even for rounded FP32 input. + mass = float64(rmz[a]) + low, high = mass - tolerance, mass + tolerance + for b in range(start, nq): + shifted = float64(qmz[b]) + shift + if shifted > high: break - mz_r = spec1_mz[peak1_idx] - int_r = spec1_int[peak1_idx] - for peak2_idx in range(lowest_idx, qlenj): - if overflow: - break - mz_q = spec2_mz[peak2_idx] - if mz_q + SHIFT > mz_r + TOLERANCE: - break - if mz_q + SHIFT + TOLERANCE < mz_r: - lowest_idx = peak2_idx + 1 - else: - if not overflow: - int_q = spec2_int[peak2_idx] - # Binary trick! - # since we know that the largest imaginable peak index can fit in 13 bits - # We pack two 16bit ints in 32bit int to use less memory - matches[num_match] = (peak1_idx << 16) | peak2_idx - values[num_match] = (mz_r**MZ_POWER * int_r**INT_POWER) * ( - mz_q**MZ_POWER * int_q**INT_POWER - ) - num_match += 1 - # Once we have filled the entire allocated `matches` array, we stop adding more. We call this the `overflow` - overflow = num_match >= ( - MATCH_LIMIT // 2 - ) # This is the errorcode for overflow - - lowest_idx = types.int32(0) - overflow_shifted = types.boolean(False) - # shift = metadata[4, reference_i] - metadata[5, query_j] - rpmz = metadata[4, reference_i] - qpmz = metadata[5, query_j] - # r_pmz = - for peak1_idx in range(rleni): - if overflow_shifted: - break - mz_r = spec1_mz[peak1_idx] - int_r = spec1_int[peak1_idx] - for peak2_idx in range(lowest_idx, qlenj): - if overflow_shifted: - break - mz_q = spec2_mz[peak2_idx] - if mz_q + rpmz > mz_r + qpmz + TOLERANCE: - break - if mz_q + rpmz + TOLERANCE < mz_r + qpmz: - lowest_idx = peak2_idx + 1 - else: - if not overflow_shifted: - int_q = spec2_int[peak2_idx] - # Binary trick! - # since we know that the largest imaginable peak index can fit in 13 bits - # We pack two 16bit ints in 32bit int to use less memory - matches[num_match] = (peak1_idx << 16) | peak2_idx - values[num_match] = (mz_r**MZ_POWER * int_r**INT_POWER) * ( - mz_q**MZ_POWER * int_q**INT_POWER - ) - num_match += 1 - # Once we have filled the entire allocated `matches` array, we stop adding more. We call this the `overflow` - overflow_shifted = ( - num_match >= MATCH_LIMIT - ) # This is the errorcode for overflow - if overflow or overflow_shifted: - num_match = -num_match - return num_match - - @cuda.jit(void(int32[::1], float32[::1], int32), device=True, inline=True) - def sort_peaks_by_value(matches, values, num_match): - temp_matches = cuda.local.array(MATCH_LIMIT, types.int32) - temp_values = cuda.local.array(MATCH_LIMIT, types.float32) - - # k is an expanding window of sorting. We initially sort single (size-1) elements, - # At this point, all 2-tuples in the array are themselves sorted. We then double the sorting window (to 2) - # Since all 2-tuples are themselves sorted, we efficiently create size-4 sorted tuples from each. - # This doubling continues, until all elements are in order. This takes O(nlog2(n)) time, where n is match_limit. - k = types.int32(1) - while k < num_match: - for left in range(0, num_match - k, k * 2): - rght = left + k - rend = rght + k - - rend = min(rend, num_match) - - m = left - ix = left - jx = rght - while ix < rght and jx < rend: - mask = values[ix] > values[jx] - temp_matches[m] = mask * matches[ix] + (1 - mask) * matches[jx] - temp_values[m] = mask * values[ix] + (1 - mask) * values[jx] - ix += mask - jx += 1 - mask - m += 1 - - while ix < rght: - temp_matches[m] = matches[ix] - temp_values[m] = values[ix] - ix += 1 - m += 1 - - while jx < rend: - temp_matches[m] = matches[jx] - temp_values[m] = values[jx] - jx += 1 - m += 1 - - for m in range(left, rend): - matches[m] = temp_matches[m] - values[m] = temp_values[m] - k *= 2 - - @kernel_wrapper( - blocks_per_grid=BLOCKS_PER_GRID, threads_per_block=THREADS_PER_BLOCK - ) - @cuda.jit( - void(FLOAT[:, :, ::1], FLOAT[:, :, ::1], FLOAT[:, ::1], float32[:, :, ::1]) - ) - def _kernel( - rspec, - qspec, - metadata, + if shifted < low: + start = b + 1 + continue + if count == limit: + return -1 + if not count_only: + left[count], right[count] = a, b + values[count] = rw[a] * qw[b] + order[count] = count + count += 1 + return count + + +# Above this size local arrays can exhaust device memory at launch. Count +# candidates first, then use bounded batches of global scratch for large heaps. +LOCAL_CANDIDATES = 2048 +# The Wave 1 launch ABI passes False for fixed shift and True for modified cosine. +NEUTRAL_LOSS_ONLY = 2 + + +@lru_cache(maxsize=64) +def cosine_kernel(width, capacity, precision, count_only=False): + """One thread per requested pair. Local scratch sizes are compile-time constants.""" + real = float64 if precision == "float64" else float32 + + global_heap = capacity > LOCAL_CANDIDATES + local_capacity = 1 if global_heap else capacity + + @cuda.jit + def kernel( + rmz, + rw, + rn, + rlen, + rp, + qmz, + qw, + qn, + qlen, + qp, + positions, + tolerance, + shift, + modified, + limit, + diagonal, out, + retry, + heap_indices, + heap_values, + offset_k, + num_pairs, ): - """ - CUDA kernel function that will be translated to GPU-executable machine code on-the-fly. - - Parameters: - ----------- - rspec : cuda.devicearray - All reference spectra. Float tensor. - Shape [2, batch_size, n_max_peaks]. Zero-padded when spectra are smaller than n_max_peaks. - Stores mz (0th slice), and intensity (1st slice). - qspec : cuda.devicearray - Same structure as rspec. - metadata : cuda.devicearray - Array containing information about rspec and qspec. In precursor_shift=False mode, it is of shape [4, batch_size], - and [6, batch_size] otherwise. For rspec and qspec, it contains: - - Number of peaks in both spectra batches. Integer tensor. Shape [2, batch_size]. Zero-padded when the number of spectra are not divisible by - batch size and we are processing the edge-batches. - - Pre-computed norm for both spectra batches. Float tensor. Shape [2, batch_size]. - - (Optionally) when precursor_shift is True, contains precursor m/z, Shape [2, batch_size], once for each spectrum in batch. - out : cuda.devicearray - Stores results. Float tensor. Shape [batch_size, batch_size, 3]. - The last dimension (3) contains: score, matches, overflow. All values are returned as floats, and have to be dtype casted. - - The kernel is designed to efficiently compute cosine similarity scores - between reference and query spectra by relying on CUDA parallelization. - - It performs the following steps: - 1. Find potential peak matches between the spectra based on m/z tolerance. - 2. Sort matched peaks based on cosine product value. - 3. Accumulate unnormalized cosine score while discarding duplicate peaks, beginning with the largest pair. - 4. Divide unnormalized score by the pre-computed spectra norm. - """ - # Get global indices - i, j = cuda.grid(2) - - # Check we aren't out of the max possible grid size - if i >= R or j >= Q: + lane = cuda.grid(1) + k = offset_k + lane + if lane >= num_pairs: return - - # Set zeros, since we know we are in the grid - out[0, i, j] = 0 - out[1, i, j] = 0 - out[2, i, j] = 0 - - # PART 1: Find potential peak matches - # allocate matches and values arrays in GPU global memory. - # matches stores peak indices (r_idx, q_idx), two int indices in each 32 bits - # values stores score contributions - matches = cuda.local.array(MATCH_LIMIT, types.int32) - values = cuda.local.array(MATCH_LIMIT, types.float32) - - # If precursor_shift is set, we compile the kernel to calculate modified cosine for spectra (if condition) - # otherwise, we compile the kernel to only calculate the cosine greedy (else condition) - if PRECURSOR_SHIFT: - num_match = collect_shifted_peak_pairs( - i, j, rspec, qspec, metadata, matches, values - ) - else: - num_match = collect_peak_pairs( - i, j, rspec, qspec, metadata, matches, values + position = positions[k] if positions.size else k + i, j = position // qmz.shape[0], position % qmz.shape[0] + if diagonal and i > j: + return # The upper-triangle thread writes both entries. + # A counting pass can already have identified a true overflow. + if retry[k] < 0: + return + out[0, k], out[1, k], retry[k] = 0, 0, 0 + nr, nq = rlen[i], qlen[j] + truncated = nr > rmz.shape[1] or nq > qmz.shape[1] + # In neutral-loss-only mode let + # matchms distinguish a zero norm with matches (undefined cosine) from + # a zero norm without matches (score zero). + neutral_only = modified == NEUTRAL_LOSS_ONLY + if truncated or (neutral_only and nr and nq and (rn[i] == 0 or qn[j] == 0)): + retry[k] = -1 + elif rn[i] != 0 and qn[j] != 0: + if global_heap: + left, right, order = heap_indices[lane, 0], heap_indices[lane, 1], heap_indices[lane, 2] + values = heap_values[lane] + else: + left = cuda.local.array(local_capacity, int32) + right = cuda.local.array(local_capacity, int32) + order = cuda.local.array(local_capacity, int32) + values = cuda.local.array(local_capacity, real) + delta = rp[i] - qp[j] + count = _collect( + rmz[i], + rw[i], + nr, + qmz[j], + qw[j], + nq, + tolerance, + delta if neutral_only else shift, + 0, + limit, + left, + right, + order, + values, + count_only, ) - - # In case we didn't get any matches, we return. We already have set 0 as the default output above. - if num_match == 0: + if count >= 0 and modified and not neutral_only and abs(delta) > tolerance: + count = _collect( + rmz[i], + rw[i], + nr, + qmz[j], + qw[j], + nq, + tolerance, + delta, + count, + limit, + left, + right, + order, + values, + count_only, + ) + + if count_only or count < 0: + retry[k] = count + elif count: + used_r = cuda.local.array(width, uint8) + used_q = cuda.local.array(width, uint8) + for a in range(nr): + used_r[a] = 0 + for b in range(nq): + used_q[b] = 0 + for root in range(count // 2 - 1, -1, -1): + _sift_down(order, values, root, count) + total, matches = real(0), 0 + while count: + edge = order[0] + a, b = left[edge], right[edge] + if not used_r[a] and not used_q[b]: + total += values[edge] + matches += 1 + used_r[a], used_q[b] = 1, 1 + count -= 1 + order[0] = order[count] + _sift_down(order, values, 0, count) + # matchms fastmath takes one sqrt of the product of squared norms. + out[0, k], out[1, k] = total / sqrt(rn[i] * qn[j]), matches + if diagonal and i != j: + other = j * qmz.shape[0] + i + out[0, other], out[1, other] = out[0, k], out[1, k] + retry[other] = 0 + + return kernel + + +ENTROPY_HYBRID_CAP = 8192 + + +@lru_cache(maxsize=64) +def entropy_kernel(mode, words): + """Walk sorted fragment/loss masses; only hybrid needs per-pair peak bitsets.""" + fragments = mode != "neutral_loss" + losses = mode != "fragment" + hybrid = fragments and losses + + @cuda.jit + def kernel(left, lo, lp, right, ro, rp, positions, tolerance, use_ppm, diagonal, out): + k = cuda.grid(1) + if k >= out.size: return - - # We store the overflow flag inside num_match, when it's negative, it's overflown. - if num_match < 0: - out[2, i, j] = 1.0 - - # Correct the negative regardless - num_match = abs(num_match) - - # PART 2: Sort matched peaks based on cosine product value - # We use a non-recursive mergesort in order to sort matches by the peak contributions (values) - # We require a 2 additional arrays to store the sorting intermediate results. - sort_peaks_by_value(matches, values, num_match) - - # PART 3: Accumulate unnormalized cosine score and de-duplicate - # Having peak matches sorted we can start summing all peak contributions to the unnormalized score, from the largest to the smallest. - # To avoid duplicates, we create two boolean arrays that keep track of used matches. - used_r = cuda.local.array(N_MAX_PEAKS, types.boolean) - used_q = cuda.local.array(N_MAX_PEAKS, types.boolean) - for m in range(N_MAX_PEAKS): - used_r[m] = False - used_q[m] = False - - # used_matches is an integer, but we use a float for performance, because - # want to write everything into one output array (score, matches and overflow) - used_matches = 0.0 - score = 0.0 - - for m in range(num_match): - # The binary trick is undone to get both peak indices back - c = matches[m] - peak1_idx = c >> 16 - peak2_idx = c & 0x0000_FFFF - - if (not used_r[peak1_idx]) and (not used_q[peak2_idx]): - used_r[peak1_idx] = True - used_q[peak2_idx] = True - score += values[m] - used_matches += 1 - - # PART 4: Divide unnormalized score by the pre-computed spectra norm #### - # Read pre-calculated norms for R and Q, multiply to get the score norm - score_norm = metadata[2, i] * metadata[3, j] - out[0, i, j] = score / score_norm - out[1, i, j] = used_matches - return - - return _kernel + width = rp.size + pos = positions[k] if positions.size else k + i, j = pos // width, pos % width + if diagonal and i > j: + return + begin_l, begin_r = lo[i], ro[j] + size_l, size_r = lo[i + 1] - begin_l, ro[j + 1] - begin_r + use_losses = losses and not (isnan(lp[i]) or isnan(rp[j])) + track = hybrid and use_losses + used_l = cuda.local.array(words, uint32) + used_r = cuda.local.array(words, uint32) + + total = 0.0 + if track and max(size_l, size_r) > ENTROPY_HYBRID_CAP: + total = -inf # Exact host walk before dense/sparse output. + else: + if track: + for w in range((size_l + 31) // 32): + used_l[w] = 0 + for w in range((size_r + 31) // 32): + used_r[w] = 0 + for phase in range(2): + reverse = phase == 1 + if (reverse and not use_losses) or (not reverse and not fragments): + continue + a, b = (size_l - 1, size_r - 1) if reverse else (0, 0) + step = -1 if reverse else 1 + score = 0.0 + while 0 <= a < size_l and 0 <= b < size_r: + if track and reverse: + if used_l[a // 32] & (uint32(1) << uint32(a % 32)): + a -= 1 + continue + if used_r[b // 32] & (uint32(1) << uint32(b % 32)): + b -= 1 + continue + x, y = begin_l + a, begin_r + b + p, q = left[x, 1], right[y, 1] + if p <= 0.0: + a += step + continue + if q <= 0.0: + b += step + continue + m, n = left[x, 0], right[y, 0] + if reverse: + m, n = lp[i] - m, rp[j] - n + limit = tolerance * 1e-6 * 0.5 * (m + n) if use_ppm else tolerance + if abs(m - n) <= limit: + combined = p + q + score += combined * log2(combined) - left[x, 2] - right[y, 2] + if track and not reverse: + used_l[a // 32] |= uint32(1) << uint32(a % 32) + used_r[b // 32] |= uint32(1) << uint32(b % 32) + a += step + b += step + elif m < n: + a += step + else: + b += step + total += score + out[k] = total + if diagonal and i != j: + out[j * width + i] = total + + return kernel diff --git a/simms/similarity/vector_similarity_functions.py b/simms/similarity/vector_similarity_functions.py index 1d56240..a26865e 100644 --- a/simms/similarity/vector_similarity_functions.py +++ b/simms/similarity/vector_similarity_functions.py @@ -1,100 +1,202 @@ +"""Bounded CUDA tiles for scalar vector scores and matchms output containers.""" + import numpy as np import torch -from simms.utils import get_device - - -def jaccard_similarity_matrix( - references: np.ndarray, queries: np.ndarray -) -> np.ndarray: - """Returns matrix of jaccard indices between all-vs-all vectors of references - and queries. - - Parameters - ---------- - references - Reference vectors as 2D numpy array. Expects that vector_i corresponds to - references[i, :]. - queries - Query vectors as 2D numpy array. Expects that vector_i corresponds to - queries[i, :]. - - Returns - ------- - scores - Matrix of all-vs-all similarity scores. scores[i, j] will contain the score - between the vectors references[i, :] and queries[j, :]. - """ - device = get_device() - - # We know references and queries have same number of elements (bits) - refs = ( - torch.from_numpy(np.asarray(references)).to(device).float() - ) # Shape R, N - ques = ( - torch.from_numpy(np.asarray(queries)).to(device).float() - ) # Shape Q, N - - intersection = refs @ ques.T # Shape R, Q, all intersection rows are summed - union = refs.sum(1, keepdim=True) + ques.sum(1, keepdim=True).T # R, Q - union -= intersection - - jaccard = intersection.div(union).nan_to_num() - return jaccard.cpu().numpy() - - -def dice_similarity_matrix(references: np.ndarray, queries: np.ndarray) -> np.ndarray: - """Returns matrix of dice similarity scores between all-vs-all vectors of references - and queries. - - Parameters - ---------- - references - Reference vectors as 2D numpy array. Expects that vector_i corresponds to - references[i, :]. - queries - Query vectors as 2D numpy array. Expects that vector_i corresponds to - queries[i, :]. - - Returns - ------- - scores - Matrix of all-vs-all similarity scores. scores[i, j] will contain the score - between the vectors references[i, :] and queries[j, :]. - """ - device = get_device() - refs = torch.from_numpy(np.array(references)).to(device).float() # Shape R, N - ques = torch.from_numpy(np.array(queries)).to(device).float() # Shape Q, N - - intersection = refs @ ques.T # Shape R, Q, all intersection rows are summed - union = refs.sum(1, keepdim=True).abs() + ques.sum(1, keepdim=True).abs().T # R, Q - - dice = 2 * intersection.div(union).nan_to_num() - return dice.cpu().numpy() - - -def cosine_similarity_matrix(references: np.ndarray, queries: np.ndarray) -> np.ndarray: - """Returns matrix of cosine similarity scores between all-vs-all vectors of - references and queries. - - Parameters - ---------- - references - Reference vectors as 2D numpy array. Expects that vector_i corresponds to - references[i, :]. - queries - Query vectors as 2D numpy array. Expects that vector_i corresponds to - queries[i, :]. - - Returns - ------- - scores - Matrix of all-vs-all similarity scores. scores[i, j] will contain the score - between the vectors references[i, :] and queries[j, :]. - """ - device = get_device() - refs = torch.from_numpy(np.array(references)).to(device).float() # R,N - ques = torch.from_numpy(np.array(queries)).to(device).float() # Q,N - score = refs @ ques.T # R, Q - norm = refs.pow(2).sum(1, keepdim=True) @ ques.pow(2).sum(1, keepdim=True).T # R, Q - score = score.div(norm.sqrt()).nan_to_num(0) - return score.cpu().numpy() +from matchms import Scores +from numba import cuda +from scipy import sparse +from tqdm import tqdm + +from ..utils import get_device +from ._base import _ScalarCudaSimilarity + + +def tile_slices(shape, batch_size, symmetric, requested, progress_bar): + starts = range(0, shape[0], batch_size) if requested is None else sorted(requested) + for r in tqdm(starts, desc="Scoring reference batches", disable=not progress_bar): + rows = slice(r, min(r + batch_size, shape[0])) + columns = ( + range(r if symmetric else 0, shape[1], batch_size) if requested is None else sorted(requested[r]) + ) + for c in columns: + cols = slice(c, min(c + batch_size, shape[1])) + positions = None if requested is None else np.asarray(requested[r][c], dtype=np.intp) + yield rows, cols, positions + + +def kernel_view(tensor): + if cuda.config.ENABLE_CUDASIM: + return tensor.numpy() + return cuda.as_cuda_array(tensor, sync=False) + + +def kernel_stream(device): + if cuda.config.ENABLE_CUDASIM: + return 0 + return cuda.external_stream(torch.cuda.current_stream(device).cuda_stream) + + +@cuda.jit +def _count_overlap(left, right, dice, result): + # Adjacent lanes read adjacent features of the transposed query tile. + j, i = cuda.grid(2) + if i >= left.shape[0] or j >= right.shape[1]: + return + common = 0.0 + union = 0.0 + for k in range(left.shape[1]): + x, y = left[i, k], right[k, j] + common += min(x, y) + union += max(x, y) + if dice: + result[i, j] = 2 * common / (common + union) if union else 0.0 + else: + result[i, j] = common / union if union else 1.0 + + +def _similarity_tile(left, right, metric): + if metric == "euclidean": + return -torch.cdist(left, right, p=2, compute_mode="donot_use_mm_for_euclid_dist") + if metric == "cosine": + norms = left.norm(dim=1)[:, None] * right.norm(dim=1) + return torch.where(norms != 0, (left @ right.T) / norms, 0.0) + + binary = ((left == 0) | (left == 1)).all() & ((right == 0) | (right == 1)).all() + if binary: + common = left @ right.T + total = left.sum(dim=1)[:, None] + right.sum(dim=1) + if metric == "dice": + return torch.where(total != 0, 2 * common / total, 0.0) + union = total - common + return torch.where(union != 0, common / union, 1.0) + + result = left.new_empty((len(left), len(right))) + query_columns = right.T.contiguous() + blocks = ((len(right) + 15) // 16, (len(left) + 7) // 8) + if left.device.type == "cuda" or cuda.config.ENABLE_CUDASIM: + _count_overlap[blocks, (16, 8), kernel_stream(left.device)]( + kernel_view(left), kernel_view(query_columns), metric == "dice", kernel_view(result) + ) + else: + for i, row in enumerate(left): + common = torch.minimum(row, right).sum(dim=1) + union = torch.maximum(row, right).sum(dim=1) + if metric == "dice": + result[i] = torch.where(union != 0, 2 * common / (union + common), 0.0) + else: + result[i] = torch.where(union != 0, common / union, 1.0) + return result + + +def _compact_csr(left, right): + """Drop globally empty columns before densifying tiles of unfolded fingerprints.""" + if not (sparse.issparse(left) and sparse.issparse(right)): + return left, right + columns = np.union1d(left.indices, right.indices) if left is not right else np.unique(left.indices) + + def compact(data): + return sparse.csr_matrix( + (data.data, np.searchsorted(columns, data.indices), data.indptr), + shape=(data.shape[0], len(columns)), + ) + + a = compact(left) + return a, a if left is right else compact(right) + + +class _TiledVectorSimilarity(_ScalarCudaSimilarity): + """Scalar Scores and NumPy outputs live on the host. Torch returns a 2D device tensor.""" + + is_commutative = True + score_fields = ("score",) + score_datatype = np.float64 + + def _configure_tiles(self, batch_size, precision): + if isinstance(batch_size, bool) or not isinstance(batch_size, (int, np.integer)) or batch_size < 1: + raise ValueError("batch_size must be a positive integer") + if precision not in ("float32", "float64"): + raise ValueError("precision must be 'float32' or 'float64'") + self.batch_size = int(batch_size) + self.precision = precision + self.score_datatype = np.dtype(precision) + + @property + def device(self): + return get_device() + + def _score_tile(self, left, right): + return _similarity_tile(left, right, self._metric) + + def _vector_tiles(self, left, right, symmetric, requested, progress_bar): + if left.ndim != 2 or right.ndim != 2 or left.shape[1] != right.shape[1]: + raise ValueError("Expected two 2D arrays with the same number of features") + left, right = _compact_csr(left, right) + shape = left.shape[0], right.shape[0] + previous = None + + def upload(data, rows): + batch = data[rows] + if sparse.issparse(batch): + batch = batch.toarray() + if isinstance(batch, np.ndarray) and any(stride < 0 for stride in batch.strides): + batch = np.ascontiguousarray(batch) + return torch.as_tensor(batch, device=self.device, dtype=getattr(torch, self.precision)).detach() + + for rows, cols, positions in tile_slices(shape, self.batch_size, symmetric, requested, progress_bar): + if rows != previous: + a = upload(left, rows) + previous = rows + b = a if left is right and rows == cols else upload(right, cols) + yield rows, cols, positions, self._score_tile(a, b) + + def _dense_vectors(self, left, right, symmetric, array_type, progress_bar): + shape = (left.shape[0], right.shape[0]) + if array_type == "torch": + result = torch.empty(shape, device=self.device, dtype=getattr(torch, self.precision)) + elif array_type in ("numpy", "scores"): + result = np.empty(shape, dtype=self.score_datatype) + else: + raise ValueError("array_type must be 'scores', 'numpy' or 'torch'") + for rows, cols, _, tile in self._vector_tiles(left, right, symmetric, None, progress_bar): + values = tile if array_type == "torch" else tile.cpu().numpy() + result[rows, cols] = values + if symmetric and rows != cols: + result[cols, rows] = values.T + return Scores({"score": result}) if array_type == "scores" else result + + def matrix(self, spectra_1, spectra_2=None, score_fields=None, progress_bar=True, array_type="scores"): + self._fields(score_fields) + left, right, symmetric = self._inputs(spectra_1, spectra_2) + return self._dense_vectors(left, right, symmetric, array_type, progress_bar) + + def _tiles(self, left, right, symmetric, requested, progress_bar): + for rows, cols, positions, tile in self._vector_tiles(left, right, symmetric, requested, progress_bar): + scores = tile.flatten() + if positions is not None: + scores = scores.index_select(0, torch.as_tensor(positions, device=tile.device)) + yield rows, cols, positions, scores + + +def _raw_matrix(references, queries, metric, batch_size, precision): + scorer = _TiledVectorSimilarity() + scorer._configure_tiles(batch_size, precision) + scorer._metric = metric + a = references if hasattr(references, "shape") else np.asarray(references) + b = queries if hasattr(queries, "shape") else np.asarray(queries) + return scorer._dense_vectors(a, b, False, "numpy", False) + + +def jaccard_similarity_matrix(references, queries, batch_size=2048, precision="float64"): + return _raw_matrix(references, queries, "tanimoto", batch_size, precision) + + +def dice_similarity_matrix(references, queries, batch_size=2048, precision="float64"): + return _raw_matrix(references, queries, "dice", batch_size, precision) + + +def cosine_similarity_matrix(references, queries, batch_size=2048, precision="float64"): + return _raw_matrix(references, queries, "cosine", batch_size, precision) + + +def euclidean_similarity_matrix(references, queries, batch_size=2048, precision="float64"): + return _raw_matrix(references, queries, "euclidean", batch_size, precision) diff --git a/simms/utils.py b/simms/utils.py index 8e1812d..d2a9163 100644 --- a/simms/utils.py +++ b/simms/utils.py @@ -1,13 +1,14 @@ -import logging import os import shutil +import tempfile import time from pathlib import Path from typing import Iterable, Literal, Optional, Type -import numpy as np import requests import torch -from matchms import Spectrum +from joblib import Memory +from numba import cuda +from matchms import Scores, Spectrum from matchms.filtering import ( normalize_intensities, reduce_to_number_of_peaks, @@ -15,24 +16,10 @@ select_by_mz, select_by_relative_intensity, ) -from matchms.similarity.BaseSimilarity import BaseSimilarity +from matchms.similarity.base_similarity import BaseSimilarity -try: - from joblib import Memory - - cache = Memory( - "cache", - verbose=0, - ).cache -except ImportError: - - def nop(fun): - return fun - - cache = nop - -logger = logging.getLogger("simms") +cache = Memory("cache", verbose=0).cache def argbatch(lst: list, batch_size: int) -> Iterable[tuple[int, int]]: @@ -58,40 +45,6 @@ def mkdir(p: Path, clean=False) -> Path: return p -def spectra_peaks_to_tensor( - spectra: list, - dtype: str = "float32", - n_max_peaks: int = None, - ignore_null_spectra: bool = False, -) -> tuple[np.ndarray, np.ndarray]: - """ - Working with GPU requires us to have a fixed shape for mz/int arrays. - This isn't the case for real-life data, so we have to either pad or trim the spectra so that - all of them are the same size. - - Returns: - spectra: [2, len(spectra)] float32 - batch: [len(spectra)] int32 - """ - dynamic_shape = max(len(s.peaks) for s in spectra) - n_max_peaks = dynamic_shape if n_max_peaks is None else n_max_peaks - - mz = np.empty((len(spectra), n_max_peaks), dtype=dtype) - int = np.empty((len(spectra), n_max_peaks), dtype=dtype) - batch = np.empty(len(spectra), dtype=np.int32) - for i, s in enumerate(spectra): - if s is not None: - # .to_numpy creates an unneeded copy - we don't need to do that twice - 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] - batch[i] = spec_len - elif s is None and ignore_null_spectra: - batch[i] = 0 - spec = np.stack([mz, int], axis=0) - return spec, batch - - def process_spectrum(spectrum: Spectrum) -> Optional[Spectrum]: """ One of the many ways to preprocess the spectrum - we use this by default. @@ -104,23 +57,9 @@ def process_spectrum(spectrum: Spectrum) -> Optional[Spectrum]: return spectrum -def download( - name: Literal[ - "ALL_GNPS.mgf", - "ALL_GNPS.pickle", - "GNPS-random-1k.mgf", - "GNPS-random-10k.mgf", - "GNPS-LIBRARY.mgf", - "GNPS-LIBRARY.pickle", - "GNPS-LIBRARY-default-filter-nmax-2048.pickle", - "GNPS-LIBRARY-default-filter-nmax-1024.pickle", - "pesticides.mgf", - "GNPS-MSMLS.mgf", - "MASSBANK.mgf", - ] -) -> str: +def download(name: Literal["GNPS-random-10k.mgf", "pesticides.mgf"]) -> str: """ - Downloads a set of sample spectra files from https://github.com/PangeAI/simms/releases/tag/samples-0.1 + Downloads a set of sample spectra files from https://github.com/PangeAI/simms/releases/tag/sample-files Downloaded files are cached, and not re-downloaded after the initial call. """ # Define the local file path @@ -135,18 +74,19 @@ def download( # URL for downloading the file url = f"https://github.com/PangeAI/simms/releases/download/sample-files/{name}" - # Download the file using requests - response = requests.get(url, stream=True) - if response.status_code == 200: - with open(local_file, "wb") as f: - for chunk in response.iter_content(chunk_size=8192): - if chunk: # Filter out keep-alive new chunks - f.write(chunk) - return str(local_file) - else: - raise Exception( - f"Failed to download file from {url}. HTTP status code: {response.status_code}" - ) + temp_path = None + try: + with requests.get(url, stream=True, timeout=60) as response: + response.raise_for_status() + with tempfile.NamedTemporaryFile(dir=local_dir, delete=False) as temp: + temp_path = Path(temp.name) + for chunk in response.iter_content(chunk_size=8192): + temp.write(chunk) + os.replace(temp_path, local_file) + finally: + if temp_path is not None: + temp_path.unlink(missing_ok=True) + return str(local_file) class Timer: @@ -164,7 +104,7 @@ def get_correct_scores( queries: list, similarity_class: Type[BaseSimilarity], **similarity_parameters, -) -> np.ndarray: +) -> Scores: """ MatchMS is quite slow for large number of spectra. To avoid re-calculating same scores with exact same arguments for testing, we cache the results on the disk and read them back if everything matches (class, args, all spectra involved). @@ -172,12 +112,15 @@ def get_correct_scores( return similarity_class(**similarity_parameters).matrix(references, queries) -def get_device() -> str: - """ - Return device 'cpu' or 'cuda' if available. - """ - if ( - os.getenv("NUMBA_ENABLE_CUDASIM") == "1" - ): # Used for testing the kernel then CUDA isn't available +def get_device(*, require_cuda=False) -> str: + """Select the scoring device, allowing CPU vector math and the Numba simulator.""" + if cuda.config.ENABLE_CUDASIM: return "cpu" - return "cuda" if torch.cuda.is_available() else "cpu" + if torch.cuda.is_available(): + return "cuda" + if require_cuda: + raise RuntimeError( + "Spectral scoring requires CUDA. Install CUDA-enabled PyTorch and a compatible " + "NVIDIA driver, or set NUMBA_ENABLE_CUDASIM=1 before starting Python for testing." + ) + return "cpu" diff --git a/tests/builder_Spectrum.py b/tests/builder_Spectrum.py index ec6a0ea..7eccb52 100644 --- a/tests/builder_Spectrum.py +++ b/tests/builder_Spectrum.py @@ -1,53 +1,51 @@ -import numpy as np -from matchms import Spectrum - - -class SpectrumBuilder: - """Builder class to better handle Spectrum creation throughout all matchms unit tests.""" - - def __init__(self): - self._mz = np.array([], dtype="float") - self._intensities = np.array([], dtype="float") - self._metadata = {} - self._metadata_harmonization = False - - def from_spectrum(self, spectrum: Spectrum): - return ( - self.with_mz(spectrum.peaks.mz) - .with_intensities(spectrum.peaks.intensities) - .with_metadata(spectrum.metadata) - ) - - def with_mz(self, mz: np.ndarray): - if isinstance(mz, np.ndarray): - self._mz = np.copy(mz) - else: - self._mz = np.array(mz, dtype="float") - return self - - def with_intensities(self, intensities: np.ndarray): - if isinstance(intensities, np.ndarray): - self._intensities = np.copy(intensities) - else: - self._intensities = np.array(intensities, dtype="float") - return self - - def with_metadata(self, metadata: dict, metadata_harmonization: bool = False): - self._metadata = metadata.copy() - self._metadata_harmonization = metadata_harmonization - return self - - def build(self) -> Spectrum: - spectrum = Spectrum( - mz=self._mz, - intensities=self._intensities, - metadata=self._metadata, - metadata_harmonization=self._metadata_harmonization, - ) - return spectrum - - -def spectra_factory(key, values): - builder = SpectrumBuilder() - spectra = [builder.with_metadata({key: x}).build() for x in values] - return spectra +import numpy as np +from matchms import Spectrum + + +def _peak_array(values): + array = np.asarray(values) + return array.copy() if array.dtype.kind == "f" else array.astype(float) + + +class SpectrumBuilder: + """Builder class to better handle Spectrum creation throughout all matchms unit tests.""" + + def __init__(self): + self._mz = np.array([], dtype="float") + self._intensities = np.array([], dtype="float") + self._metadata = {} + self._metadata_harmonization = False + + def from_spectrum(self, spectrum: Spectrum): + return ( + self.with_mz(spectrum.peaks.mz) + .with_intensities(spectrum.peaks.intensities) + .with_metadata(spectrum.metadata) + ) + + def with_mz(self, mz: np.ndarray): + self._mz = _peak_array(mz) + return self + + def with_intensities(self, intensities: np.ndarray): + self._intensities = _peak_array(intensities) + return self + + def with_metadata(self, metadata: dict, metadata_harmonization: bool = False): + self._metadata = metadata.copy() + self._metadata_harmonization = metadata_harmonization + return self + + def build(self) -> Spectrum: + return Spectrum( + mz=self._mz, + intensities=self._intensities, + metadata=self._metadata, + metadata_harmonization=self._metadata_harmonization, + ) + + +def spectra_factory(key, values): + builder = SpectrumBuilder() + spectra = [builder.with_metadata({key: x}).build() for x in values] + return spectra diff --git a/tests/conftest.py b/tests/conftest.py index 4c46c73..0ebaf4d 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,47 +1,24 @@ -import warnings -import pytest -from joblib import Memory - - -memory = Memory(location="cache") - - -def pytest_configure(config): - config.addinivalue_line("markers", "performance") - - -@pytest.fixture(autouse=True, scope="session") -def warn_on_no_cuda(): - import os - import numba - - if not numba.cuda.is_available(): - warnings.warn( - "CUDA was unavailable - consider using `NUMBA_ENABLE_CUDASIM=1 pytest ` to simulate having GPU and cudatoolkit for testing purposes" - ) - yield +from itertools import islice +from pathlib import Path +import numpy as np +import pytest +from matchms.importing import load_from_mgf -@pytest.fixture(autouse=True, scope="session") -def ignore_warnings(): - import os - os.environ["NUMBA_DISABLE_PERFORMANCE_WARNINGS"] = "1" - yield +from simms.utils import download @pytest.fixture(scope="session") -@memory.cache(verbose=0) -def gnps(): - from simms.utils import download - from matchms.importing import load_from_mgf +def pesticides(): + return list(load_from_mgf(Path(__file__).parent / "data" / "pesticides.mgf")) - spectra = tuple(load_from_mgf(download("GNPS-random-10k.mgf"))) - return spectra @pytest.fixture(scope="session") -@memory.cache -def gnps_with_fingerprint(gnps: list): - from matchms.filtering import add_fingerprint - - spectra = [add_fingerprint(s) for s in gnps] - return spectra +def gnps(): + spectra = load_from_mgf(download("GNPS-random-10k.mgf")) + eligible = ( + s + for s in spectra + if len(s.peaks) and np.isfinite(s.get("precursor_mz") or 0) and (s.get("precursor_mz") or 0) > 0 + ) + return list(islice(eligible, 512)) diff --git a/tests/similarity/fixtures/issue6_lewisgeng.txt b/tests/similarity/fixtures/issue6_lewisgeng.txt new file mode 100644 index 0000000..bce2e5d --- /dev/null +++ b/tests/similarity/fixtures/issue6_lewisgeng.txt @@ -0,0 +1,578 @@ +# m/z and intensity from lewisgeng: https://github.com/PangeAI/SimMS/issues/6#issuecomment-3459869607 +544.80069197 0 +544.80368305 9 +544.80661309 0 +545.04058878 0 +545.04351882 7 +545.04650990 0 +545.07019437 0 +545.07318545 5 +545.07611548 14 +545.07910656 2 +545.08203660 0 +545.09979995 0 +545.10279103 9 +545.10572107 7 +545.10871215 0 +545.23012558 0 +545.23311666 19 +545.23604670 2 +545.23903778 0 +545.41380231 0 +545.41679339 7 +545.41972342 21 +545.42271450 0 +546.09540231 0 +547.05932374 2 +547.06231482 7 +547.06524486 0 +547.10974481 0 +547.11273589 7 +547.11566593 5 +547.11865701 0 +547.76869818 0 +547.77168927 2 +547.77461930 5 +547.77761038 0 +548.46067558 0 +548.46366666 2 +548.46665774 7 +548.46958778 0 +549.00749402 0 +549.01042406 5 +549.01341514 2 +549.01640622 0 +549.05803719 0 +549.06096723 7 +549.06395831 14 +549.06694939 0 +549.06987943 0 +549.07287051 7 +549.07586159 2 +549.07879163 0 +549.08477379 0 +549.08776487 9 +549.09069491 0 +549.09667707 0 +549.09960711 5 +549.10259819 7 +549.10558927 0 +549.15613244 0 +549.15906248 2 +549.16205356 9 +549.16504464 0 +549.17987796 0 +549.18286904 5 +549.18586012 2 +549.18879016 0 +549.19178124 16 +549.19477232 9 +549.19770236 0 +550.01854053 0 +550.02153161 7 +550.02452269 0 +550.17328321 0 +550.17627429 9 +550.17920433 0 +550.82509482 0 +550.82808590 12 +550.83107698 0 +551.03654598 0 +551.03947602 2 +551.04246710 5 +551.04545818 0 +551.07524691 0 +551.07823800 5 +551.08116804 16 +551.08415912 0 +551.09905348 0 +551.10204457 16 +551.10503565 5 +551.10802673 0 +551.47434268 0 +551.47733377 5 +551.48032485 2 +551.48331593 0 +551.75440562 0 +551.75739670 2 +551.76038778 7 +551.76337886 0 +552.06138830 0 +552.06437938 19 +552.06737046 0 +552.15978879 0 +552.16271883 5 +552.16570991 2 +552.16870100 0 +552.21344514 0 +552.21637518 2 +552.21936626 16 +552.22235735 0 +552.28791698 0 +552.29090806 19 +552.29389915 7 +552.29689023 0 +552.31477568 0 +552.31776676 9 +552.32075784 0 +552.32374892 12 +552.32667896 7 +552.32967005 0 +552.45792032 0 +552.46085036 9 +552.46384144 5 +552.46683253 0 +553.06034870 0 +553.06333978 9 +553.06633087 12 +553.06932195 21 +553.07231303 0 +553.10808393 0 +553.11107502 7 +553.11406610 14 +553.11705718 2 +553.12004826 7 +553.12303935 0 +553.23340418 0 +553.23639526 5 +553.23938635 9 +553.24237743 0 +553.28413050 0 +553.28712158 5 +553.29011266 7 +553.29310374 0 +553.30201595 0 +553.30500703 7 +553.30799811 0 +553.44528269 0 +553.44827378 2 +553.45126486 5 +553.45425594 0 +553.80946225 0 +553.81239229 7 +553.81538337 9 +553.81837445 0 +554.03336614 0 +554.03635723 12 +554.03934831 5 +554.04233939 0 +554.04832156 0 +554.05125160 5 +554.05424268 2 +554.05723376 0 +554.09605679 0 +554.09904788 2 +554.10203896 5 +554.10503004 0 +554.12889766 0 +554.13188874 5 +554.13487983 7 +554.13787091 0 +554.23346347 0 +554.23645455 14 +554.23938459 2 +554.24237568 0 +554.26331325 0 +554.26630434 7 +554.26929542 9 +554.27228650 25 +554.27527759 30 +554.27826867 100 +554.28119871 123 +554.28418979 204 +554.28718087 338 +554.29017196 540 +554.29316304 735 +554.29615412 1150 +554.29914520 1799 +554.30213629 2054 +554.30512737 1822 +554.30811845 1917 +554.31110954 1841 +554.31410062 1535 +554.31709170 1011 +554.32002174 988 +554.32301282 686 +554.32600391 427 +554.32899499 779 +554.33198607 373 +554.33497715 464 +554.33796824 408 +554.34095932 255 +554.34395040 176 +554.34694149 174 +554.34993257 151 +554.35292365 139 +554.35591473 93 +554.35890582 104 +554.36189690 93 +554.36482694 109 +554.36781802 127 +554.37080910 70 +554.37380019 72 +554.37679127 107 +554.37978235 58 +554.38277344 46 +554.38576452 67 +554.38875560 25 +554.39174668 51 +554.39473777 58 +554.39772885 49 +554.40071993 35 +554.40371101 30 +554.40664105 58 +554.40963214 21 +554.41262322 28 +554.41561430 14 +554.41860539 28 +554.42159647 79 +554.42458755 19 +554.42757863 35 +554.43056972 35 +554.43356080 7 +554.43655188 7 +554.43954296 16 +554.44253405 12 +554.44552513 44 +554.44851621 7 +554.45144625 12 +554.45443734 12 +554.45742842 16 +554.46041950 12 +554.46341058 0 +554.46640167 5 +554.46939275 2 +554.47238383 19 +554.47537492 0 +554.47836600 0 +554.48135708 2 +554.48434816 5 +554.48733925 0 +554.49033033 0 +554.49332141 9 +554.49631249 12 +554.49924253 5 +554.50223362 0 +554.50821578 0 +554.51120687 9 +554.51419795 2 +554.51718903 0 +554.52915336 0 +554.53214445 5 +554.53513553 25 +554.53812661 0 +554.54703882 0 +554.55002990 16 +554.55302098 0 +554.55601207 0 +554.55900315 9 +554.56199423 7 +554.56498531 0 +554.66057788 0 +554.66356896 9 +554.66656004 2 +554.66955113 0 +555.03110590 0 +555.03409698 9 +555.03708806 16 +555.04007915 5 +555.04307023 5 +555.04606131 2 +555.04905240 0 +555.18951121 0 +555.19250229 14 +555.19549338 0 +555.24634179 0 +555.24933287 19 +555.25232395 0 +555.26129720 0 +555.26428828 16 +555.26727937 2 +555.27027045 0 +555.27326153 0 +555.27619157 14 +555.27918266 28 +555.28217374 14 +555.28516482 28 +555.28815591 44 +555.29114699 121 +555.29413807 202 +555.29712915 260 +555.30012024 475 +555.30311132 424 +555.30610240 420 +555.30909349 304 +555.31208457 290 +555.31507565 341 +555.31806674 248 +555.32105782 260 +555.32404890 218 +555.32703998 250 +555.33003107 178 +555.33302215 141 +555.33601323 88 +555.33900432 100 +555.34199540 46 +555.34498648 72 +555.34797757 116 +555.35096865 30 +555.35395973 49 +555.35695082 19 +555.35994190 23 +555.36293298 32 +555.36592406 76 +555.36891515 39 +555.37190623 14 +555.37489731 51 +555.37788840 32 +555.38087948 35 +555.38387056 2 +555.38686165 0 +555.38979169 2 +555.39278277 30 +555.39577385 16 +555.39876494 16 +555.40175602 14 +555.40474710 7 +555.40773818 2 +555.41072927 7 +555.41372035 5 +555.41671143 5 +555.41970252 2 +555.42269360 0 +555.42867577 0 +555.43166685 5 +555.43465793 7 +555.43764901 7 +555.44064010 0 +555.44363118 7 +555.44662226 5 +555.44961335 7 +555.45260443 0 +555.45559551 0 +555.45858660 2 +555.46157768 7 +555.46456876 5 +555.46755985 0 +555.48251526 0 +555.48550634 5 +555.48849743 2 +555.49148851 0 +555.59312429 0 +555.59611537 2 +555.59910646 9 +555.60209754 0 +556.02078814 0 +556.02377922 5 +556.02677031 2 +556.02976139 0 +556.06565439 0 +556.06864547 2 +556.07163656 25 +556.07462764 0 +556.28107343 0 +556.28406451 21 +556.28705559 12 +556.29004668 2 +556.29303776 32 +556.29602884 49 +556.29901993 12 +556.30201101 42 +556.30500209 42 +556.30799318 100 +556.31098426 65 +556.31397534 56 +556.31696643 32 +556.31995751 46 +556.32294859 53 +556.32593968 32 +556.32893076 46 +556.33198289 28 +556.33497397 5 +556.33796505 19 +556.34095614 79 +556.34394722 28 +556.34693830 7 +556.34992939 16 +556.35292047 12 +556.35591155 2 +556.35890264 0 +556.36189372 0 +556.36488480 14 +556.36787589 5 +556.37086697 2 +556.37385805 12 +556.37684914 2 +556.37984022 9 +556.38283130 0 +556.38881347 0 +556.39180455 7 +556.39479564 2 +556.39778672 5 +556.40077780 5 +556.40376889 0 +556.40675997 5 +556.40975105 7 +556.41274214 0 +556.42470647 0 +556.42769755 2 +556.43068864 5 +556.43367972 0 +557.02335045 0 +557.02634154 5 +557.02933262 19 +557.03232370 0 +557.04727912 0 +557.05033125 7 +557.05332233 0 +557.09220642 0 +557.09519750 12 +557.09818858 2 +557.10117967 0 +557.26886348 0 +557.27191560 7 +557.27490668 5 +557.27789777 0 +557.30182644 0 +557.30481752 2 +557.30780860 21 +557.31079969 0 +557.31379077 0 +557.31678186 5 +557.31977294 5 +557.32282506 23 +557.32581615 28 +557.32880723 0 +557.33478940 0 +557.33778048 2 +557.34077157 9 +557.34376265 12 +557.34675373 0 +557.37373453 0 +557.37672561 5 +557.37971670 9 +557.38270778 0 +557.42464399 0 +557.42763508 7 +557.43062616 7 +557.43361724 0 +557.86799585 0 +557.87098693 9 +557.87397802 12 +557.87696910 0 +558.10172768 0 +558.10471877 5 +558.10770985 12 +558.11070094 0 +558.24859601 0 +558.25158709 7 +558.25457817 2 +558.25756926 0 +558.34449382 0 +558.34748490 7 +558.35047599 2 +558.35346707 0 +559.02212696 0 +559.02517908 5 +559.02817017 5 +559.03116125 0 +559.04312559 0 +559.04617771 2 +559.04916880 5 +559.05215988 0 +559.06412422 0 +559.06717635 5 +559.07016743 12 +559.07315851 7 +559.07614960 7 +559.07914068 0 +559.08213177 7 +559.08512285 0 +559.08811393 0 +559.09116606 9 +559.09415715 0 +559.37611261 0 +559.37916474 7 +559.38215582 2 +559.38514691 0 +559.78125193 0 +559.78424301 2 +559.78723409 12 +559.79028622 0 +560.06345158 0 +560.06644267 12 +560.06943375 0 +560.10245776 0 +560.10544885 2 +560.10843993 5 +560.11143102 0 +560.20751198 0 +560.21056410 2 +560.21355519 19 +560.21654627 0 +560.31561831 0 +560.31860940 5 +560.32166153 5 +560.32465261 0 +560.99447244 0 +560.99746352 7 +561.00051565 2 +561.00350673 0 +561.03958288 0 +561.04257396 7 +561.04556505 0 +561.06058151 0 +561.06357260 7 +561.06662472 14 +561.06961581 2 +561.07260689 0 +561.08164119 0 +561.08463227 2 +561.08762336 19 +561.09061444 0 +561.12369950 0 +561.12669059 2 +561.12968167 5 +561.13273380 0 +561.28595059 0 +561.28900272 5 +561.29199380 21 +561.29498489 0 +561.57455976 0 +561.57755084 12 +561.58054193 5 +561.58353301 0 +562.23009571 0 +562.23308679 7 +562.23607788 0 +562.98836632 0 +562.99135741 7 +562.99434849 0 +563.03652890 0 +563.03951999 7 +563.04251107 7 +563.04556320 0 +563.06363180 0 +563.06662288 5 +563.06961397 5 +563.07260505 0 +563.10874225 0 +563.11179437 2 +563.11478546 5 +563.11777654 0 +563.12681084 0 +563.12980193 2 +563.13285406 5 +563.13584514 0 +563.15391374 0 +563.15690482 2 +563.15995695 5 +563.16294804 0 +563.36768478 0 +563.37067587 7 +563.37372799 5 +563.37671908 0 +564.24724706 0 +564.25023814 5 +564.25329027 7 +564.25628136 0 diff --git a/tests/similarity/test_binned_embedding_similarity.py b/tests/similarity/test_binned_embedding_similarity.py new file mode 100644 index 0000000..a5f0f6c --- /dev/null +++ b/tests/similarity/test_binned_embedding_similarity.py @@ -0,0 +1,103 @@ +import numpy as np +import pytest +import torch +from matchms import Scores, SpectraCollection, Spectrum, calculate_scores +from matchms.similarity import BinnedEmbeddingSimilarity + +from simms import PeakArrays +from simms.similarity.CudaBinnedEmbeddingSimilarity import CudaBinnedEmbeddingSimilarity +from simms.utils import get_device + + +def data(): + def row(mz, intensity): + return Spectrum(np.asarray(mz, float), np.asarray(intensity, float), metadata_harmonization=False) + + return [ + row([0, 0.24, 0.25, 1.125, 1.25], [4, 9, 1, 16, 100]), + row([], []), + row([0.25, 0.5], [0, 0]), + row([0.25, 0.75, 1], [1, 9, 4]), + row([2], [5]), + ] + + +@pytest.mark.github_ci +@pytest.mark.parametrize("metric", ["cosine", "euclidean"]) +@pytest.mark.parametrize("container", ["spectra", "collection", "peaks"]) +def test_embeddings_scores_and_sparse(metric, container): + spectra = data() + source = { + "spectra": spectra, + "collection": SpectraCollection(spectra), + "peaks": PeakArrays.from_spectra(spectra), + }[container] + cpu_data = source if container == "collection" else spectra + kwargs = dict(similarity=metric, max_mz=1.125, bin_width=0.25, intensity_power=0.5) + cpu = BinnedEmbeddingSimilarity(**kwargs) + gpu = CudaBinnedEmbeddingSimilarity(**kwargs, batch_size=2) + assert cpu.n_bins == gpu.n_bins == 5 + embedding = gpu.compute_embeddings(source) + np.testing.assert_allclose(embedding, cpu.compute_embeddings(cpu_data), atol=1e-14) + np.testing.assert_allclose(embedding[0], [1, 0.2, 0, 0, 0.8]) + expected = cpu.matrix(cpu_data, progress_bar=False).to_array() + scores = calculate_scores(source, source, gpu) + assert isinstance(scores, Scores) + assert scores.score_fields == ("score",) + assert scores.to_array().dtype == np.float64 + np.testing.assert_allclose(scores.to_array(), expected, atol=1e-14) + np.testing.assert_allclose(gpu.sparse_matrix(source).to_array(), expected, atol=1e-14) + tensor = gpu.matrix(source, array_type="torch") + assert tensor.device.type == get_device() and tensor.dtype == torch.float64 + np.testing.assert_allclose(tensor.cpu(), expected, atol=1e-14) + assert gpu.pair(spectra[0], spectra[3]) == pytest.approx(cpu.pair(spectra[0], spectra[3])) + assert gpu.to_dict() == { + "__Similarity__": type(gpu).__name__, + **kwargs, + "batch_size": 2, + "precision": "float64", + } + + +@pytest.mark.github_ci +def test_bin_boundaries_and_rectangular_float32(): + mz = np.array([-0.01, 0, 0.3, 0.6, 0.9, 1.0, 1.01]) + x = np.arange(1.0, len(mz) + 1) + spectra = [Spectrum(mz, x, metadata_harmonization=False)] + data()[1:] + kwargs = dict(bin_width=0.1, max_mz=1.0) + cpu = BinnedEmbeddingSimilarity(**kwargs) + gpu = CudaBinnedEmbeddingSimilarity(**kwargs, precision="float32", batch_size=2) + np.testing.assert_allclose( + gpu.compute_embeddings(iter(spectra)), cpu.compute_embeddings(spectra), atol=1e-7 + ) + actual = gpu.matrix(spectra[:2], spectra, array_type="numpy") + assert actual.dtype == np.float32 + np.testing.assert_allclose(actual, cpu.matrix(spectra[:2], spectra).to_array(), atol=1e-7) + filtered = gpu.sparse_matrix( + spectra[:2], spectra, idx_row=[0, 1], idx_col=[0, 2], score_filter=lambda s: s > 0.5 + ) + assert filtered.is_sparse + assert filtered.to_coo().nnz == 1 + assert gpu.matrix([], spectra).shape == (0, len(spectra)) + + +@pytest.mark.github_ci +@pytest.mark.parametrize( + "kwargs", + [{"bin_width": 0}, {"max_mz": -1}, {"similarity": "other"}, {"batch_size": 0}, {"precision": "int32"}], +) +def test_invalid_configuration(kwargs): + with pytest.raises(ValueError): + CudaBinnedEmbeddingSimilarity(**kwargs) + + +@pytest.mark.github_ci +def test_nonpositive_bins_and_near_zero_cosine(): + data = [ + Spectrum(np.array([0.25]), np.array([value]), metadata_harmonization=False) + for value in [-1e-18, -0.5, 0.0] + ] + cpu = BinnedEmbeddingSimilarity(max_mz=0.5) + gpu = CudaBinnedEmbeddingSimilarity(max_mz=0.5, batch_size=2) + np.testing.assert_array_equal(gpu.compute_embeddings(data), cpu.compute_embeddings(data)) + np.testing.assert_allclose(gpu.matrix(data).to_array(), cpu.matrix(data).to_array(), atol=0) diff --git a/tests/similarity/test_cosine_greedy.py b/tests/similarity/test_cosine_greedy.py index dde9b15..c3a3984 100644 --- a/tests/similarity/test_cosine_greedy.py +++ b/tests/similarity/test_cosine_greedy.py @@ -15,9 +15,9 @@ def compute_expected_score(mz_power, intensity_power, spectrum_1, spectrum_2, ma * (mz2[matches[1]] ** mz_power) * (intensity2[matches[1]] ** intensity_power) ) - denominator = np.sqrt( - (((mz1**mz_power) * (intensity1**intensity_power)) ** 2).sum() - ) * np.sqrt((((mz2**mz_power) * (intensity2**intensity_power)) ** 2).sum()) + denominator = np.sqrt((((mz1**mz_power) * (intensity1**intensity_power)) ** 2).sum()) * np.sqrt( + (((mz2**mz_power) * (intensity2**intensity_power)) ** 2).sum() + ) expected_score = multiply_matching_intensities.sum() / denominator return expected_score @@ -92,14 +92,14 @@ def compute_expected_score(mz_power, intensity_power, spectrum_1, spectrum_2, ma ], ) @pytest.mark.github_ci -def test_cosine_greedy_pair( - peaks, tolerance, mz_power, intensity_power, expected_matches -): +def test_cosine_greedy_pair(peaks, tolerance, mz_power, intensity_power, expected_matches): builder = SpectrumBuilder() spectrum_1 = builder.with_mz(peaks[0][0]).with_intensities(peaks[0][1]).build() spectrum_2 = builder.with_mz(peaks[1][0]).with_intensities(peaks[1][1]).build() cosine_greedy = CudaCosineGreedy( + remove_precursor=False, + noise_cutoff=0.0, batch_size=8, tolerance=tolerance, mz_power=mz_power, @@ -111,43 +111,63 @@ def test_cosine_greedy_pair( mz_power, intensity_power, spectrum_1, spectrum_2, expected_matches ) - assert score["score"] == pytest.approx( - expected_score, 0.0001 - ), f"Expected different cosine score. {score['score']:.5f} {expected_score:.5f}" - assert score["matches"] == len( - expected_matches[0] - ), "Expected different number of matching peaks." + assert score["score"] == pytest.approx(expected_score, 0.0001), ( + f"Expected different cosine score. {score['score']:.5f} {expected_score:.5f}" + ) + assert score["matches"] == len(expected_matches[0]), "Expected different number of matching peaks." + + +@pytest.mark.parametrize("self_comparison", [True, False]) +@pytest.mark.github_ci +def test_cosine_greedy_matrix(self_comparison): + from matchms.similarity import CosineGreedy + + builder = SpectrumBuilder().with_metadata({"precursor_mz": 400.0}) + spectra = [ + builder.with_mz(mz).with_intensities(weights).build() + for mz, weights in [([100, 200], [1, 2]), ([100, 250], [2, 1]), ([150], [1])] + ] + queries = None if self_comparison else spectra[1:] + expected = CosineGreedy().matrix(spectra, queries, progress_bar=False) + actual = CudaCosineGreedy(batch_size=2).matrix(spectra, queries, progress_bar=False) + assert actual.score_fields == ("score", "matches") + for field in actual.score_fields: + np.testing.assert_allclose(actual.to_array(field), expected.to_array(field), rtol=1e-14) -@pytest.mark.parametrize("symmetric", [[True], [False]]) @pytest.mark.github_ci -def test_cosine_greedy_matrix(symmetric): +@pytest.mark.parametrize("match_limit", [1, 8]) +def test_fixed_shift_is_directional_even_in_self_matrix(match_limit): + from simms import PeakArrays + + peaks = PeakArrays.from_peak_lists([[100, 105], [95, 100]], [[1, 2], [1, 2]]) + sim = CudaCosineGreedy(shift=5, match_limit=match_limit, remove_precursor=False) + scores = sim.matrix(peaks) + assert scores.to_array("matches").tolist() == [[1, 2], [0, 1]] + assert scores.to_array("score")[0, 1] == pytest.approx(1) + + +@pytest.mark.github_ci +def test_tied_products_use_reversed_stable_order(): + from matchms.similarity import CosineGreedy + + # At equal product the later reference takes the shared query peak. builder = SpectrumBuilder() - spectrum_1 = ( - builder.with_mz(np.array([100, 200, 300], dtype="float")) - .with_intensities(np.array([0.1, 0.2, 1.0], dtype="float")) - .build() - ) + r = builder.with_mz([10, 12]).with_intensities([1, 1]).build() + q = builder.with_mz([9, 11]).with_intensities([0.5, 1]).build() + args = dict(tolerance=1, remove_precursor=False) + expected = CosineGreedy(**args).pair(r, q) + actual = CudaCosineGreedy(**args).pair(r, q) + assert actual.dtype == expected.dtype and actual.shape == expected.shape == () + np.testing.assert_allclose(actual["score"], expected["score"], rtol=1e-14) + assert actual["matches"] == expected["matches"] - spectrum_2 = ( - builder.with_mz(np.array([110, 190, 290], dtype="float")) - .with_intensities(np.array([0.5, 0.2, 1.0], dtype="float")) - .build() - ) - spectrums = [spectrum_1, spectrum_2] - cosine_greedy = CudaCosineGreedy(batch_size=8) - scores = cosine_greedy.matrix(spectrums, spectrums, is_symmetric=symmetric) - - assert scores[0][0][0] == pytest.approx( - scores[1][1][0], 0.000001 - ), "Expected different cosine score." - assert scores[0][0]["score"] == pytest.approx( - scores[1][1]["score"], 0.000001 - ), "Expected different cosine score." - assert scores[0][1][0] == pytest.approx( - scores[1][0][0], 0.000001 - ), "Expected different cosine score." - assert scores[0][1]["score"] == pytest.approx( - scores[1][0]["score"], 0.000001 - ), "Expected different cosine score." +@pytest.mark.github_ci +def test_default_fp64_tolerance_boundary_and_explicit_fp32(): + from matchms.similarity import CosineGreedy + + builder = SpectrumBuilder().with_metadata({"precursor_mz": 1500}).with_intensities([1]) + r, q = builder.with_mz([1000.0]).build(), builder.with_mz([1000.00999999]).build() + assert CudaCosineGreedy().pair(r, q).item() == CosineGreedy().pair(r, q).item() == (1.0, 1) + assert CudaCosineGreedy(precision="float32").pair(r, q).item() == (0.0, 0) diff --git a/tests/similarity/test_cosine_linear.py b/tests/similarity/test_cosine_linear.py new file mode 100644 index 0000000..894917f --- /dev/null +++ b/tests/similarity/test_cosine_linear.py @@ -0,0 +1,176 @@ +import importlib +import inspect + +import numpy as np +import pytest +import torch +from matchms import Scores, SpectraCollection, Spectrum, calculate_scores +from matchms.similarity import CosineLinear, ModifiedCosineLinear + +from simms import PeakArrays +from simms.similarity.CudaCosineLinear import CudaCosineLinear, CudaModifiedCosineLinear +from simms.utils import get_device + + +IMPLEMENTATIONS = [(CosineLinear, CudaCosineLinear), (ModifiedCosineLinear, CudaModifiedCosineLinear)] + + +def spectrum(mz, intensity, precursor=None): + return Spectrum( + np.asarray(mz, float), + np.asarray(intensity, float), + metadata={} if precursor is None else {"precursor_mz": precursor}, + metadata_harmonization=False, + ) + + +def inputs(): + return [ + spectrum([10, 10.25, 10.5, 11, 12, 28.5], [1, 1, 0.1, 0.6, 0, 0.8], 30.0), + spectrum([11, 12, 13, 20], [0.6, 1, 0.8, 0.001], 31.0), + spectrum([], [], 30.0), + spectrum([10, 12], [0, 0], 30.0), + spectrum([10.125, 12, 13], [0.2, 1, 0.4], 30.25), + ] + + +@pytest.mark.github_ci +@pytest.mark.parametrize("cpu,gpu", IMPLEMENTATIONS) +def test_defaults_and_preprocessing_once(cpu, gpu, monkeypatch): + params = inspect.signature(cpu).parameters + scorer = gpu(batch_size=2) + assert {p: getattr(scorer, p) for p in params} == {p: s.default for p, s in params.items()} + assert scorer.to_dict() == {"__Similarity__": gpu.__name__, **vars(scorer)} + module = importlib.import_module("simms.similarity.CudaCosineLinear") + original = module.sirius_merge_close_peaks + calls = [] + + def counted(peaks, tolerance): + calls.append(len(peaks)) + return original(peaks, tolerance) + + monkeypatch.setattr(module, "sirius_merge_close_peaks", counted) + data = inputs() + actual = calculate_scores(data, data, scorer) + expected = cpu().matrix(data, data, progress_bar=False) + assert isinstance(actual, Scores) + assert len(calls) == len(data) + np.testing.assert_allclose(actual.to_array("score"), expected.to_array("score"), atol=1e-14) + np.testing.assert_array_equal(actual.to_array("matches"), expected.to_array("matches")) + + +@pytest.mark.github_ci +@pytest.mark.parametrize("cpu,gpu", IMPLEMENTATIONS) +@pytest.mark.parametrize("container", ["collection", "peaks"]) +def test_containers_sparse_and_torch(cpu, gpu, container): + data = inputs() + source = SpectraCollection(data) if container == "collection" else PeakArrays.from_spectra(data) + oracle = source if container == "collection" else data + kwargs = dict(tolerance=0.125, mz_power=0.5, intensity_power=0.5, noise_cutoff=None) + scorer = gpu(batch_size=2, **kwargs) + expected = cpu(**kwargs).matrix(oracle, progress_bar=False) + score = expected.to_array("score") + actual = scorer.matrix(source, score_fields=("matches", "score"), array_type="torch", progress_bar=False) + assert actual.device.type == get_device() + assert actual.dtype == torch.float64 + np.testing.assert_allclose(actual[1].cpu(), score, rtol=1e-13) + np.testing.assert_array_equal(actual[0].cpu(), expected.to_array("matches")) + sparse = scorer.sparse_matrix( + source, + idx_row=[0, 0, 1], + idx_col=[0, 1, 4], + score_fields=["matches"], + score_filter=lambda x: x["score"] > 0.5, + ) + assert sparse.is_sparse + retained = np.zeros(score.shape, int) + for i, j in [(0, 0), (0, 1), (1, 4)]: + if score[i, j] > 0.5: + retained[i, j] = retained[j, i] = expected.to_array("matches")[i, j] + np.testing.assert_array_equal(sparse.to_array(), retained) + + +@pytest.mark.github_ci +@pytest.mark.parametrize("cpu,gpu", IMPLEMENTATIONS) +def test_merge_window_ties_and_precursors(cpu, gpu): + a = spectrum([10, 10.25, 10.5], [1, 1, 0.5], 40.0) + b = spectrum([10, 30], [2, 0.5], 40.0) + kwargs = dict(tolerance=0.125, remove_precursor=False) + actual = gpu(**kwargs).pair(a, b) + assert actual.shape == () + assert actual["score"] == pytest.approx(4 / 4.25) + np.testing.assert_allclose(actual["score"], cpu(**kwargs).pair(a, b)["score"]) + assert actual["matches"] == 1 + missing = spectrum([1], [1]) + with pytest.raises(AssertionError, match="Precursor_mz"): + gpu(remove_precursor=True).pair(missing, a) + if gpu is CudaModifiedCosineLinear: + with pytest.raises(AssertionError, match="Precursor_mz"): + gpu(remove_precursor=False).pair(missing, a) + else: + assert gpu().pair(missing, missing)["matches"] == 1 + + +@pytest.mark.github_ci +def test_modified_path_ties_zero_edges_and_duplicate_partner(): + # The middle edge has the same benefit as both outer edges together. + # The CPU backtracking rule selects the last edge on a tie. + for x, y, shift in [([1, 2], [2, 1], 1.0), ([0, 1], [1, 0], 1.0), ([1, 1], [1, 1], 0.1875)]: + a = spectrum([10, 11], x, 30.0) + mz = [10.09375, 11.09375] if shift < 1 else [11, 12] + b = spectrum(mz, y, 30.0 + shift) + kwargs = dict(tolerance=0.125, noise_cutoff=None) + actual = CudaModifiedCosineLinear(**kwargs).pair(a, b) + expected = ModifiedCosineLinear(**kwargs).pair(a, b) + assert actual["score"] == pytest.approx(expected["score"], abs=1e-14) + assert actual["matches"] == expected["matches"] + + +@pytest.mark.github_ci +def test_direct_counts_zero_product_modified_excludes_it(): + a = spectrum([1, 2], [1, 0], 10.0) + b = spectrum([1, 2], [1, 1], 10.0) + assert CudaCosineLinear(noise_cutoff=None).pair(a, b)["matches"] == 2 + assert CudaModifiedCosineLinear(noise_cutoff=None).pair(a, b)["matches"] == 1 + + +@pytest.mark.parametrize("cpu,gpu", IMPLEMENTATIONS) +def test_workspace_boundary_and_long_rows(cpu, gpu): + def row(n): + return spectrum(np.arange(n, dtype=float), np.linspace(0.5, 1.0, n), n + 10.0) + + data = [row(2048), row(2049), row(9)] + scorer = gpu(batch_size=2) + expected = cpu().matrix(data, progress_bar=False) + actual = scorer.matrix(data, array_type="numpy") + np.testing.assert_array_equal(actual["matches"], expected.to_array("matches")) + np.testing.assert_allclose(actual["score"], expected.to_array("score"), atol=2e-14) + sparse = scorer.sparse_matrix(data, idx_row=[1], idx_col=[2]) + assert sparse.to_array("matches")[1, 2] == expected.to_array("matches")[1, 2] + + +@pytest.mark.github_ci +def test_shifted_random_paths(): + rng = np.random.default_rng(630) + data = [] + for i in range(12): + mz = np.sort(rng.choice(18, size=12, replace=False)).astype(float) + 10 + data.append(spectrum(mz, rng.integers(0, 5, len(mz)), 45.0 + i % 5)) + scorer = CudaModifiedCosineLinear(batch_size=4, noise_cutoff=None) + actual = scorer.matrix(data[:7], data[5:], array_type="numpy") + expected = ModifiedCosineLinear(noise_cutoff=None).matrix(data[:7], data[5:], progress_bar=False) + np.testing.assert_allclose(actual["score"], expected.to_array("score"), atol=2e-14) + np.testing.assert_array_equal(actual["matches"], expected.to_array("matches")) + + +@pytest.mark.github_ci +@pytest.mark.parametrize("cpu,gpu", IMPLEMENTATIONS) +def test_fp64_product_rounding_and_accumulation_order(cpu, gpu): + rng = np.random.default_rng(731) + data = [ + spectrum(np.sort(rng.choice(50, size=30, replace=False)), rng.random(30), 60.0 + i) for i in range(5) + ] + actual = gpu(batch_size=3).matrix(data, array_type="numpy") + expected = cpu().matrix(data, progress_bar=False) + np.testing.assert_array_equal(actual["matches"], expected.to_array("matches")) + np.testing.assert_array_equal(actual["score"], expected.to_array("score")) diff --git a/tests/similarity/test_entropy_greedy.py b/tests/similarity/test_entropy_greedy.py new file mode 100644 index 0000000..3ddfdfe --- /dev/null +++ b/tests/similarity/test_entropy_greedy.py @@ -0,0 +1,188 @@ +from inspect import signature +from itertools import islice +from pathlib import Path + +import numpy as np +import pytest +import torch +from matchms import Scores, SpectraCollection, Spectrum, calculate_scores +from matchms.importing import load_from_mgf +from matchms.similarity import EntropyGreedy +from matchms.similarity.base_similarity import BaseSimilarityWithSparse + +from simms import PeakArrays +from simms.similarity.CudaEntropyGreedy import CudaEntropyGreedy +from simms.utils import get_device + + +def spectrum(mz, intensity, precursor=None): + metadata = {} if precursor is None else {"precursor_mz": precursor} + return Spectrum(np.asarray(mz, dtype=float), np.asarray(intensity, dtype=float), metadata, + metadata_harmonization=False) + + +def assert_scores(actual, expected): + if np.asarray(actual).dtype == np.float32 or np.asarray(expected).dtype == np.float32: + np.testing.assert_allclose(actual, expected, rtol=1e-6, atol=1e-6) + else: + np.testing.assert_allclose(actual, expected, rtol=2e-14, atol=1e-16) + + +@pytest.mark.github_ci +def test_constructor_and_serialization(): + gpu = CudaEntropyGreedy("hybrid", dtype=np.float32, weighted=False, batch_size=3) + assert isinstance(gpu, BaseSimilarityWithSparse) + assert gpu.score_fields == ("score",) and gpu.score_datatype == np.dtype("float32") + cpu_params = signature(EntropyGreedy).parameters + gpu_params = signature(CudaEntropyGreedy).parameters + assert list(gpu_params)[:len(cpu_params)] == list(cpu_params) + assert all(gpu_params[k].default == v.default for k, v in cpu_params.items()) + config = gpu.to_dict() + assert config.pop("__Similarity__") == "CudaEntropyGreedy" + assert config == {**{k: v.default for k, v in cpu_params.items()}, "matching_mode": "hybrid", + "dtype": "float32", "weighted": False, "batch_size": 3} + assert CudaEntropyGreedy(**config).to_dict() == gpu.to_dict() + + +@pytest.mark.github_ci +@pytest.mark.parametrize("mode", ["fragment", "neutral_loss", "hybrid"]) +@pytest.mark.parametrize("use_ppm", [True, False]) +def test_order_cleaning_merge_and_missing_precursors(mode, use_ppm): + # Direct and shifted candidates compete for the same physical peaks. The + # high-intensity precursor is cropped before noise filtering and merging. + rows = [spectrum([10, 10.003, 20, 30, 40, 99], [2, 0.5, 8, 3, 5, 1000], 100), + spectrum([20, 30, 30.004, 50, 109], [9, 4, 1, 1, 1000], 110), + spectrum([20, 30, 50], [3, 1, 7]), spectrum([], [], 120)] + args = dict(matching_mode=mode, use_ppm=use_ppm, tolerance=100 if use_ppm else 0.01, + noise_cutoff=0.05, merge_within=0.005) + gpu, cpu = CudaEntropyGreedy(**args, batch_size=2), EntropyGreedy(**args) + for data in (rows, SpectraCollection(rows)): + expected = cpu.matrix(list(data), progress_bar=False).to_array() + actual = gpu.matrix(data, progress_bar=False).to_array() + assert_scores(actual, expected) + if mode == "neutral_loss": + assert not actual[2].any() + assert not actual[3].any() + assert_scores(gpu.pair(rows[0], rows[1]), cpu.pair(rows[0], rows[1])) + + +@pytest.mark.github_ci +@pytest.mark.parametrize("mode", ["fragment", "neutral_loss"]) +@pytest.mark.parametrize("use_ppm", [False, True]) +def test_inclusive_symmetric_tolerance(mode, use_ppm): + a, b = (spectrum([99], [1], 200), spectrum([101], [1], 200)) + boundary = 20000.0 if use_ppm else 2.0 + for tolerance, expected in [(boundary, 1.0), (np.nextafter(boundary, 0.0), 0.0)]: + args = dict(matching_mode=mode, use_ppm=use_ppm, tolerance=tolerance) + assert CudaEntropyGreedy(**args).pair(a, b) == EntropyGreedy(**args).pair(a, b) == expected + + +@pytest.mark.github_ci +def test_ppm_uses_signed_loss_mass_and_da_accepts_negative_losses(): + s = spectrum([101], [1], 100) + for use_ppm in (True, False): + args = dict(matching_mode="neutral_loss", tolerance=0.5, use_ppm=use_ppm, remove_precursor=False) + assert CudaEntropyGreedy(**args).pair(s, s) == EntropyGreedy(**args).pair(s, s) == float(not use_ppm) + + +@pytest.mark.github_ci +@pytest.mark.parametrize("mode, pairs", [ + ("fragment", [(1, 0), (2, 1)]), + ("neutral_loss", [(3, 2), (1, 1), (0, 0)]), + ("hybrid", [(1, 0), (2, 1), (3, 2)]), +]) +def test_unweighted_from_jensen_shannon_terms(mode, pairs): + a, b = spectrum([10, 20, 30, 40], [1, 2, 3, 4], 100), spectrum([20, 30, 50], [1, 1, 3], 110) + p, q = np.array([1, 2, 3, 4]) / 20, np.array([1, 1, 3]) / 10 + expected = sum(p[i] * np.log2((p[i] + q[j]) / p[i]) + q[j] * np.log2((p[i] + q[j]) / q[j]) + for i, j in pairs) + assert_scores(CudaEntropyGreedy(mode, weighted=False).pair(a, b), expected) + weighted = EntropyGreedy(mode).pair(a, b) + assert not np.isclose(expected, weighted) + assert_scores(CudaEntropyGreedy(mode).pair(a, b), weighted) + + +@pytest.mark.github_ci +def test_reverse_loss_walk_prefers_higher_fragment_mz(): + a, b = spectrum([40, 40.25], [9, 1], 100), spectrum([50], [1], 110) + args = dict(matching_mode="neutral_loss", tolerance=0.25) + assert_scores(CudaEntropyGreedy(**args).pair(a, b), EntropyGreedy(**args).pair(a, b)) + + +@pytest.mark.github_ci +def test_high_entropy_leaves_weights_unchanged(): + a = spectrum(np.arange(48), np.tile([1, 2, 3], 16)) + b = spectrum(np.arange(24), np.tile([3, 2, 1], 8)) + expected = EntropyGreedy().pair(a, b) + for weighted in (True, False): + assert_scores(CudaEntropyGreedy(weighted=weighted).pair(a, b), expected) + + +@pytest.mark.github_ci +@pytest.mark.parametrize("dtype", [np.float64, np.float32]) +def test_native_inputs_score_containers_and_restricted_sparse(dtype): + rows = [spectrum([20, 40], [0.3, 1], 100), spectrum([20, 50], [1, 3], 110), + spectrum([8], [1], 120)] + gpu, cpu = CudaEntropyGreedy("hybrid", dtype=dtype, batch_size=2), EntropyGreedy("hybrid", dtype=dtype) + for data in (PeakArrays.from_spectra(rows), SpectraCollection(rows)): + oracle_rows = list(data) if isinstance(data, SpectraCollection) else rows + expected = cpu.matrix(oracle_rows, progress_bar=False).to_array() + got = calculate_scores(data, None, gpu) + assert isinstance(got, Scores) and got.score_fields == ("score",) + assert_scores(got.to_array(), expected) + tensor = gpu.matrix(data, score_fields=("score",), array_type="torch", progress_bar=False) + assert tensor.device.type == get_device() and tensor.dtype == getattr(torch, np.dtype(dtype).name) + assert_scores(tensor.cpu().numpy(), expected) + got = gpu.sparse_matrix(data, progress_bar=False) + assert got.is_sparse and got.to_coo().dtype == dtype + assert_scores(got.to_array(), expected) + for coords in [([0, 1, 0], [1, 0, 0]), ([], [])]: + opts = dict(idx_row=coords[0], idx_col=coords[1], score_filter=lambda x: x > 0.2, progress_bar=False) + assert_scores(gpu.sparse_matrix(data, **opts).to_array(), cpu.sparse_matrix(oracle_rows, **opts).to_array()) + zero = gpu.sparse_matrix(data[:1], data[-1:], idx_row=[0], idx_col=[0]) + assert zero.shape == (1, 1) and zero.to_coo().nnz == 0 + pair = gpu.pair(rows[0], rows[1]) + assert pair.shape == () and pair.dtype == dtype + assert gpu.matrix([], rows, array_type="numpy").shape == (0, 3) + assert gpu.sparse_matrix(rows, []).shape == (3, 0) + + +@pytest.mark.github_ci +def test_missing_precursor_in_peak_arrays(): + data = PeakArrays.from_peak_lists([[10], [10]], [[1], [1]]) + assert not CudaEntropyGreedy("neutral_loss").matrix(data).to_array().any() + np.testing.assert_array_equal(CudaEntropyGreedy("hybrid").matrix(data).to_array(), np.ones((2, 2))) + + +@pytest.mark.github_ci +def test_hybrid_over_cap_recovered_before_sparse_filter_and_mirror(): + # The only eligible match lies beyond the 8192nd peak, on the loss pass. + a = spectrum(np.arange(1, 8194), np.ones(8193), 10000) + b = spectrum([18193], [1], 20000) + gpu, cpu = CudaEntropyGreedy("hybrid"), EntropyGreedy("hybrid") + expected = cpu.pair(a, b).item() + assert expected > 0 + assert_scores(gpu.pair(a, b), expected) + opts = dict(idx_row=[0], idx_col=[1], score_filter=lambda v: v >= expected) + assert_scores(gpu.sparse_matrix([a, b], **opts).to_array(), [[0, expected], [expected, 0]]) + + +@pytest.mark.parametrize("length", [8192, 8193]) +def test_hybrid_cap_boundary_and_bitset_word_edges(length): + a = spectrum(np.arange(length), np.ones(length), 10000) + b = spectrum([31, 32, 63, 64, 191, length + 8], [1, 2, 3, 4, 5, 6], 10010) + rows = [a, b] + expected = EntropyGreedy("hybrid").matrix(rows, progress_bar=False) + actual = CudaEntropyGreedy("hybrid").matrix(rows, progress_bar=False) + assert_scores(actual.to_array(), expected.to_array()) + + +@pytest.mark.github_ci +@pytest.mark.parametrize("mode", ["fragment", "neutral_loss", "hybrid"]) +def test_pesticide_reference_matrix(mode): + path = Path(__file__).parents[1] / "data" / "pesticides.mgf" + rows = list(islice(load_from_mgf(str(path)), 8)) + args = dict(matching_mode=mode, merge_within=0.01, use_ppm=True, tolerance=30.0) + expected = EntropyGreedy(**args).matrix(rows[:5], rows[2:], progress_bar=False) + actual = CudaEntropyGreedy(**args, batch_size=3).matrix(rows[:5], rows[2:], array_type="numpy") + assert_scores(actual, expected.to_array()) diff --git a/tests/similarity/test_fingerprint_similarity.py b/tests/similarity/test_fingerprint_similarity.py index 60fd002..0cf011d 100644 --- a/tests/similarity/test_fingerprint_similarity.py +++ b/tests/similarity/test_fingerprint_similarity.py @@ -1,155 +1,142 @@ import numpy as np import pytest -from matchms import Spectrum, calculate_scores -from sparsestack import StackedSparseArray +import torch +from matchms import Fingerprints, Scores, SpectraCollection, Spectrum, calculate_scores +from matchms.similarity import FingerprintSimilarity +from rdkit import Chem +from rdkit.Chem import rdFingerprintGenerator +from scipy import sparse + from simms.similarity import CudaFingerprintSimilarity +from simms.similarity import vector_similarity_functions as vectors +from simms.utils import get_device -@pytest.mark.parametrize( - "test_method, expected_score", - [("cosine", 0.6761234), ("jaccard", 0.5), ("dice", 2 / 3)], -) -@pytest.mark.github_ci -def test_fingerprint_similarity_pair_calculations(test_method, expected_score): - """Test cosine score pair with two fingerprint.""" - fingerprint1 = np.array([1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0]) - spectrum1 = Spectrum( - mz=np.array([], dtype="float"), - intensities=np.array([], dtype="float"), - metadata={"fingerprint": fingerprint1}, - ) +def spectra(): + def row(smiles, key=None): + inchikey = key or Chem.MolToInchiKey(Chem.MolFromSmiles(smiles)) + return Spectrum( + np.array([1.0]), + np.array([1.0]), + metadata={"smiles": smiles, "inchikey": inchikey}, + metadata_harmonization=False, + ) - fingerprint2 = np.array([0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1]) - spectrum2 = Spectrum( - mz=np.array([], dtype="float"), - intensities=np.array([], dtype="float"), - metadata={"fingerprint": fingerprint2}, - ) + return [row("CCO"), row("CCCC"), row("CCO"), row("C", key="invalid"), row("CCCO")] - similarity_measure = CudaFingerprintSimilarity(similarity_measure=test_method) - score_pair = similarity_measure.pair(spectrum1, spectrum2) - assert score_pair == pytest.approx( - expected_score, 1e-6 - ), "Expected different score." +def generator(): + return rdFingerprintGenerator.GetMorganGenerator(radius=2, fpSize=64) -@pytest.mark.parametrize("test_method", ["cosine", "jaccard", "dice"]) -@pytest.mark.github_ci -def test_fingerprint_similarity_parallel_empty_fingerprint(test_method): - """Test score matrix with empty fingerprint using the provided methods.""" - fingerprint1 = np.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) - spectrum1 = Spectrum( - mz=np.array([], dtype="float"), - intensities=np.array([], dtype="float"), - metadata={"fingerprint": fingerprint1}, - ) - fingerprint2 = np.array([0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1]) - spectrum2 = Spectrum( - mz=np.array([], dtype="float"), - intensities=np.array([], dtype="float"), - metadata={"fingerprint": fingerprint2}, - ) - - similarity_measure = CudaFingerprintSimilarity(similarity_measure=test_method) - score_matrix = similarity_measure.matrix( - [spectrum1, spectrum2], [spectrum1, spectrum2] - ) - assert score_matrix == pytest.approx( - np.array([[0, 0], [0, 1.0]]), 0.001 - ), "Expected different values." - - -@pytest.mark.parametrize( - "test_method, expected_score, array_type, set_empty", - [ - ("cosine", 0.84515425, "numpy", np.nan), - ("jaccard", 0.71428571, "numpy", np.nan), - ("dice", 0.83333333, "numpy", 0), - ], -) @pytest.mark.github_ci -def test_fingerprint_similarity_parallel( - test_method, expected_score, array_type, set_empty -): - """Test score matrix with known values for the provided methods.""" - spectrum0 = Spectrum( - mz=np.array([], dtype="float"), - intensities=np.array([], dtype="float"), - metadata={}, - ) - - fingerprint1 = np.array([0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0]) - spectrum1 = Spectrum( - mz=np.array([], dtype="float"), - intensities=np.array([], dtype="float"), - metadata={"fingerprint": fingerprint1}, - ) - - fingerprint2 = np.array([0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1]) - spectrum2 = Spectrum( - mz=np.array([], dtype="float"), - intensities=np.array([], dtype="float"), - metadata={"fingerprint": fingerprint2}, - ) - - similarity_measure = CudaFingerprintSimilarity( - set_empty_scores=set_empty, similarity_measure=test_method - ) - score_matrix = similarity_measure.matrix( - [spectrum0, spectrum1, spectrum2], - [spectrum0, spectrum1, spectrum2], - array_type=array_type, - ) - expected_matrix = np.array( - [ - [set_empty, set_empty, set_empty], - [set_empty, 1, expected_score], - [set_empty, expected_score, 1], - ] - ) - if isinstance(score_matrix, (StackedSparseArray)): - score_matrix = score_matrix.to_array() - assert np.allclose( - score_matrix, expected_matrix, equal_nan=True - ), "Expected different values." +@pytest.mark.parametrize("count,csr", [(False, False), (True, True), (True, False), (False, True)]) +@pytest.mark.parametrize("metric", ["cosine", "tanimoto"]) +def test_matchms_generated_and_stored_fingerprints(count, csr, metric): + pytest.importorskip("chemap") + data = spectra() + source = SpectraCollection(data) + gen = generator() + kwargs = dict(similarity_measure=metric, count=count, return_csr=csr) + cpu = FingerprintSimilarity(gen, **kwargs) + gpu = CudaFingerprintSimilarity(gen, **kwargs, batch_size=2) + expected = cpu.matrix(data, progress_bar=False).to_array() + scores = gpu.matrix(source) + assert isinstance(scores, Scores) + assert scores.shape == (3, 3) and scores.score_fields == ("score",) + assert scores.to_array().dtype == np.float64 + np.testing.assert_allclose(scores.to_array(), expected, atol=2e-7) + + a = Fingerprints(gen, count=count, return_csr=csr) + a.compute_fingerprints(data) + b = Fingerprints(gen, count=count, return_csr=not csr) + b.compute_fingerprints([data[4], data[0]]) + assert a.fingerprint_count == 3 and b.fingerprint_count == 2 + expected = cpu.matrix(fingerprints_1=a, fingerprints_2=b).to_array() + np.testing.assert_allclose(gpu.matrix(fingerprints_1=a, fingerprints_2=b).to_array(), expected, atol=2e-7) + np.testing.assert_allclose(calculate_scores(a, b, gpu).to_array(), expected, atol=2e-7) + assert gpu.pair(data[0], data[4]) == pytest.approx(expected[0, 0], abs=2e-7) + assert gpu.fingerprint_generator is gen @pytest.mark.github_ci -def test_fingerprint_similarity_with_scores_sorting(): - """Test if score works with Scores.scores_by_query and sorting.""" - spectrum0 = Spectrum( - mz=np.array([100.0, 101.0], dtype="float"), - intensities=np.array([0.4, 0.5], dtype="float"), - metadata={}, - ) +@pytest.mark.parametrize("metric", ["tanimoto", "jaccard", "cosine", "dice"]) +@pytest.mark.parametrize("counts", [False, True]) +def test_precomputed_arrays_pair_sparse_and_tiling(metric, counts, monkeypatch): + a = np.array([[0, 0, 0], [1, 2, 4], [3, 2, 0], [1, 0, 2], [1, 1, 1]]) + b = np.array([[3, 1, 2], [0, 0, 0], [2, 4, 0]]) + if not counts: + a, b = a > 0, b > 0 + af, bf = a.astype(float), b.astype(float) + common = np.minimum(af[:, None], bf).sum(axis=2) + union = np.maximum(af[:, None], bf).sum(axis=2) + if metric == "cosine": + norm = np.linalg.norm(af, axis=1)[:, None] * np.linalg.norm(bf, axis=1) + expected = np.divide(af @ bf.T, norm, where=norm != 0, out=np.zeros_like(union)) + elif metric == "dice": + total = common + union + expected = np.divide(2 * common, total, where=total != 0, out=np.zeros_like(union)) + else: + expected = np.divide(common, union, where=union != 0, out=np.ones_like(union)) + + gpu = CudaFingerprintSimilarity(similarity_measure=metric, batch_size=2) + tile = vectors._similarity_tile + visited = [] + + def observed(left, right, measure): + visited.append((len(left), len(right))) + assert left.device.type == right.device.type == get_device() + return tile(left, right, measure) + + monkeypatch.setattr(vectors, "_similarity_tile", observed) + tensor = gpu.matrix(torch.tensor(a, device=get_device()), sparse.csr_array(b), array_type="torch") + assert tensor.device.type == get_device() and tensor.dtype == torch.float64 + np.testing.assert_allclose(tensor.cpu(), expected, atol=1e-14) + assert visited == [(2, 2), (2, 1), (2, 2), (2, 1), (1, 2), (1, 1)] + computed = gpu.matrix(sparse.csr_matrix(a), sparse.csr_matrix(b), array_type="numpy") + np.testing.assert_allclose(computed, expected, atol=1e-14) + assert gpu.pair(a[0], b[1]) == expected[0, 1] + assert gpu.pair(a[1], sparse.csr_matrix(b[:1])) == pytest.approx(expected[1, 0]) + + restricted = gpu.sparse_matrix( + fingerprints_1=a, fingerprints_2=b, idx_row=[1, 4], idx_col=[0, 2], score_filter=lambda x: x >= 0.3 + ) + assert restricted.is_sparse + retained = np.zeros_like(expected) + for i, j in [(1, 0), (4, 2)]: + if expected[i, j] >= 0.3: + retained[i, j] = expected[i, j] + np.testing.assert_allclose(restricted.to_array(), retained) - fingerprint1 = np.array([0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0]) - spectrum1 = Spectrum( - mz=np.array([100.0, 101.0], dtype="float"), - intensities=np.array([0.4, 0.5], dtype="float"), - metadata={"fingerprint": fingerprint1}, - ) - fingerprint2 = np.array([0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1]) - spectrum2 = Spectrum( - mz=np.array([100.0, 101.0], dtype="float"), - intensities=np.array([0.4, 0.5], dtype="float"), - metadata={"fingerprint": fingerprint2}, - ) - - similarity_measure = CudaFingerprintSimilarity( - set_empty_scores=0, similarity_measure="cosine" - ) +@pytest.mark.github_ci +def test_empty_sparse_rows_wide_csr_and_precision(): + # An unfolded feature identifier can be much larger than device memory. + x = sparse.csr_matrix(([2.0, 3.0], ([0, 2], [2**32, 2**32])), shape=(3, 2**32 + 1)) + gpu = CudaFingerprintSimilarity(batch_size=1, precision="float32") + result = gpu.sparse_matrix(x).to_array() + assert result.dtype == np.float32 + np.testing.assert_allclose(result, [[1, 0, 2 / 3], [0, 1, 0], [2 / 3, 0, 1]]) + assert gpu.matrix(np.zeros((2, 0))).to_array().tolist() == [[1, 1], [1, 1]] + config = CudaFingerprintSimilarity(generator(), scaling="log", count=True).to_dict() + assert config.pop("__Similarity__") == "CudaFingerprintSimilarity" + assert CudaFingerprintSimilarity(**config).fingerprint_config_kwargs == {"scaling": "log"} - scores = calculate_scores( - [spectrum0, spectrum1, spectrum2], - [spectrum0, spectrum1, spectrum2], - similarity_measure, - ) - scores_by_ref_sorted = scores.scores_by_query(spectrum1, sort=True) - expected_scores = np.array([1.0, 0.84515425]) - assert np.allclose( - np.array([x[1] for x in scores_by_ref_sorted]), expected_scores, atol=1e-6 - ), "Expected different scores and/or order." +@pytest.mark.github_ci +def test_invalid_metadata_and_input_contract(): + gen = generator() + invalid = [spectra()[3]] + if pytest.importorskip("chemap", reason="chemap required for generator-backed Fingerprints"): + for sim in [FingerprintSimilarity(gen), CudaFingerprintSimilarity(gen)]: + with pytest.raises(ValueError, match="container is empty"): + sim.matrix(invalid) + with pytest.raises(ValueError, match="Provide either"): + sim.matrix(invalid, fingerprints_1=Fingerprints(gen)) + gpu = CudaFingerprintSimilarity() + with pytest.raises(ValueError, match="2D"): + gpu.matrix(np.arange(3)) + with pytest.raises(ValueError, match="same number of features"): + gpu.matrix(np.ones((2, 4)), np.ones((2, 5))) + with pytest.raises(ValueError, match="score field"): + gpu.matrix(np.ones((2, 4)), score_fields=["matches"]) diff --git a/tests/similarity/test_issues_regressions.py b/tests/similarity/test_issues_regressions.py new file mode 100644 index 0000000..5516204 --- /dev/null +++ b/tests/similarity/test_issues_regressions.py @@ -0,0 +1,322 @@ +import inspect +from pathlib import Path +from types import SimpleNamespace + +import numpy as np +import pytest +import torch +from matchms import Scores, SpectraCollection, Spectrum, calculate_scores +from matchms.similarity import CosineGreedy, ModifiedCosineGreedy +from numba import cuda +from scipy.sparse import coo_array + +from simms import PeakArrays +from simms.similarity import CudaCosineGreedy, CudaModifiedCosine, CudaModifiedCosineGreedy + + +pytestmark = pytest.mark.github_ci + + +def spectrum(mz, intensities, precursor=600.0): + return Spectrum( + np.asarray(mz, dtype=float), + np.asarray(intensities, dtype=float), + {"precursor_mz": precursor}, + metadata_harmonization=False, + ) + + +def test_issue6_original_lewisgeng_spectrum(): + mz, intensities = np.loadtxt(Path(__file__).parent / "fixtures" / "issue6_lewisgeng.txt", unpack=True) + assert len(mz) == 577 and np.sum(intensities**2) == 28007149 + s = spectrum(mz, intensities) + args = dict(tolerance=0.1, remove_precursor=False, noise_cutoff=0.0) + expected = CosineGreedy(**args).pair(s, s) + sim = CudaCosineGreedy(**args) + actual = sim.pair(s, s) + assert actual["score"] == expected["score"] == 1.0 + assert actual["matches"] == expected["matches"] == 577 + sparse = sim.sparse_matrix([s], score_filter=lambda v: v["score"] == 1) + assert sparse.to_coo("matches").data.tolist() == [577] + + +@pytest.mark.parametrize( + "method,oracle", [(CudaCosineGreedy, CosineGreedy), (CudaModifiedCosineGreedy, ModifiedCosineGreedy)] +) +def test_exactly_full_and_truncated_recovery(method, oracle, monkeypatch): + s = spectrum([100, 101], [1, 1000]) + sim = method(match_limit=2, noise_cutoff=0) + recover = sim._recover + calls = [] + + def counted(*args): + calls.append(args[-2:]) + return recover(*args) + + monkeypatch.setattr(sim, "_recover", counted) + expected = oracle(noise_cutoff=0).pair(s, s) + assert sim.pair(s, s)["matches"] == 2 + assert calls == [] + for limit, cap in [(1, None), (2, 1)]: + sim.match_limit, sim.n_max_peaks = limit, cap + got = sim.matrix([s], [s], array_type="torch") + assert got[:, 0, 0].tolist() == [expected["score"], expected["matches"]] + assert calls == [(0, 0), (0, 0)] + + +class PublicSpectrum: + def __init__(self): + self.reads = 0 + + @property + def peaks(self): + self.reads += 1 + assert self.reads == 1 + return SimpleNamespace(mz=np.array([100.0, 150.0]), intensities=np.array([1.0, 2.0])) + + def get(self, key, default=None): + return 500.0 if key == "precursor_mz" else default + + +def test_issue9_public_peaks_read_once_for_object_array_including_retry(): + s = PublicSpectrum() + rows = np.array([s], dtype=object) + result = calculate_scores(rows, rows, CudaCosineGreedy(match_limit=1)) + assert s.reads == 1 and isinstance(result, Scores) + assert result.to_array("matches").item() == 2 + + +@pytest.mark.parametrize( + "bad,reason", + [ + (np.array([[100.0, 1.0]]), "object ndarray"), + (np.array([1.0]), "object ndarray"), + ([None], r"spectra\[0\]"), + ([object()], r"spectra\[0\]"), + ([np.array([1.0, 2.0])], r"spectra\[0\]"), + ], +) +def test_issue9_invalid_input_identifies_side_and_element(bad, reason): + with pytest.raises(TypeError, match="spectra_2: .*" + reason): + CudaCosineGreedy().matrix([], bad) + + +@pytest.mark.parametrize("method", [CudaCosineGreedy, CudaModifiedCosine]) +def test_issue9_empty_axes_empty_rows_and_zero_norm(method): + empty = spectrum([], []) + zero = spectrum([1, 2], [0, 0]) + sim = method() + for rows, cols, shape in [([], None, (0, 0)), ([empty], [], (1, 0)), ([], [empty], (0, 1))]: + assert sim.matrix(rows, cols).shape == sim.sparse_matrix(rows, cols).shape == shape + for s in (empty, zero): + assert sim.pair(s, s).item() == (0.0, 0) + + +@pytest.mark.parametrize( + "method,oracle", [(CudaCosineGreedy, CosineGreedy), (CudaModifiedCosineGreedy, ModifiedCosineGreedy)] +) +def test_collection_direct_csr_and_calculate_scores(method, oracle, monkeypatch): + rows = [spectrum([100.01, 100.02, 150], [1, 2, 5]), spectrum([100.04, 151], [3, 4], 601.0)] + coll = SpectraCollection(rows, mz_precision=0.1) + expected = oracle().matrix(list(coll), list(coll), progress_bar=False) + + def forbid(*args): + pytest.fail("Scoring reconstructed a Spectrum from a collection row") + + monkeypatch.setattr(SpectraCollection, "_spectrum_from_row", forbid) + got = calculate_scores(coll, coll, method(batch_size=1)) + for field in expected.score_fields: + np.testing.assert_allclose(got.to_array(field), expected.to_array(field), rtol=1e-14) + + +def test_sparse_projection_explicit_coordinates_mirroring_and_zero_hits(): + peaks = PeakArrays.from_peak_lists([[100, 200], [100, 150], [80]], [[1, 1], [1, 1], [1]]) + sim = CudaCosineGreedy(remove_precursor=False, batch_size=1) + selected = sim.sparse_matrix( + peaks, + idx_row=[0, 0, 1, 2], + idx_col=[0, 1, 0, 2], + score_fields=["matches"], + score_filter=lambda s: s["score"] < 0.9, + ) + assert selected.score_fields == ("matches",) + coo = selected.to_coo("matches") + assert isinstance(coo, coo_array) + assert sorted(zip(coo.row, coo.col, coo.data)) == [(0, 1, 1), (1, 0, 1)] + for result in [ + sim.sparse_matrix(peaks, score_filter=lambda _: False), + sim.sparse_matrix(peaks, idx_row=[], idx_col=[]), + sim.sparse_matrix(peaks, peaks, [0], [2]), + ]: + for field in sim.score_fields: + stored = result.to_coo(field) + assert stored.dtype == sim.score_datatype[field] + assert stored.nnz == 0 and stored.shape == (3, 3) + + +def test_sparse_default_filter_applies_to_full_score_before_projection(): + # One valid zero-product match, with nonzero norm on both sides. + a, b = spectrum([10, 20], [0, 1]), spectrum([10, 30], [1, 1]) + sim = CudaCosineGreedy(noise_cutoff=0) + assert sim.pair(a, b).item() == (0.0, 1) + assert sim.sparse_matrix([a], [b], score_fields=["matches"]).to_coo().nnz == 0 + kept = sim.sparse_matrix([a], [b], score_fields=["matches"], score_filter=lambda s: s["matches"] > 0) + assert kept.to_coo().data.tolist() == [1] + + +@pytest.mark.parametrize("delta,expected_count", [(0.0, 0), (0.08, 0), (0.15, 1)]) +def test_modified_near_zero_precursor_shift(delta, expected_count): + a, b = spectrum([100], [1]), spectrum([100.15], [1], 600.0 + delta) + args = dict(tolerance=0.1) + expected = ModifiedCosineGreedy(**args).pair(a, b) + assert CudaModifiedCosine is CudaModifiedCosineGreedy + actual = CudaModifiedCosine(**args).pair(a, b) + assert actual.item() == expected.item() + assert actual["matches"] == expected_count + + +@pytest.mark.parametrize("mz_power,intensity_power", [(0.0, 0.0), (-1.0, -0.5)]) +def test_norm_uses_only_active_slots(mz_power, intensity_power): + rows = [spectrum([100], [1]), spectrum([100, 150, 200], [1, 2, 3])] + args = dict(mz_power=mz_power, intensity_power=intensity_power) + expected = CosineGreedy(**args).matrix(rows, progress_bar=False) + actual = CudaCosineGreedy(**args).matrix(rows) + for f in actual.score_fields: + np.testing.assert_allclose(actual.to_array(f), expected.to_array(f), rtol=1e-14) + + +@pytest.mark.parametrize("precision", ["float32", "float64"]) +def test_output_projection_and_device(precision): + peaks = PeakArrays.from_peak_lists([[50], [50, 70], [80]], [[1], [2, 3], [2]]) + sim = CudaCosineGreedy(remove_precursor=False, precision=precision, batch_size=2) + fields = ("matches", "score") + tensor = sim.matrix(peaks, score_fields=fields, array_type="torch") + host = sim.matrix(peaks, score_fields=fields, array_type="numpy") + assert tensor.shape == (2, 3, 3) and tensor.dtype == getattr(torch, precision) + assert tensor.is_cuda == (not cuda.config.ENABLE_CUDASIM) + assert host.dtype.names == fields + for i, field in enumerate(fields): + np.testing.assert_array_equal(tensor[i].cpu().numpy(), host[field]) + assert sim.matrix(peaks, score_fields=["score"]).score_fields == ("score",) + + +@pytest.mark.parametrize("method", [CudaCosineGreedy, CudaModifiedCosineGreedy]) +def test_constructor_serialization_and_validation(method): + sim = method(precision="float32", n_max_peaks=17) + serialized = sim.to_dict() + assert serialized.pop("__Similarity__") == method.__name__ + assert set(serialized) == set(inspect.signature(method).parameters) + assert method(**serialized).to_dict() == sim.to_dict() + for bad in [dict(batch_size=0), dict(n_max_peaks=-1), dict(match_limit=1.5), dict(precision="int32")]: + with pytest.raises(ValueError): + method(**bad) + for fields in [[], ["missing"], ["score", "score"]]: + with pytest.raises(ValueError): + sim.matrix([], score_fields=fields) + + +@pytest.mark.parametrize("array_type", ["scores", "numpy"]) +def test_host_output_tiles_and_reference_reuse(array_type, monkeypatch): + refs = PeakArrays.from_peak_lists([[100.0]] * 5, [[1.0]] * 5) + queries = PeakArrays.from_peak_lists([[100.0]] * 7, [[1.0]] * 7) + sim = CudaCosineGreedy(remove_precursor=False, batch_size=3) + transfers, allocations = [], [] + batch, empty = sim._batch, torch.empty + + def record_batch(peaks, rows): + transfers.append((len(peaks), rows.start)) + return batch(peaks, rows) + + def record_allocation(shape, **kwargs): + allocations.append(shape) + return empty(shape, **kwargs) + + monkeypatch.setattr(sim, "_batch", record_batch) + monkeypatch.setattr(torch, "empty", record_allocation) + actual = sim.matrix(refs, queries, array_type=array_type) + assert actual.shape == (5, 7) + assert [start for peaks, start in transfers if peaks == len(refs)] == [0, 3] + assert [shape for shape in allocations if len(shape) == 2 and shape[0] == 2 and shape[1]] == [ + (2, 9), + (2, 9), + (2, 3), + (2, 6), + (2, 6), + (2, 2), + ] + assert all(np.prod(shape) < 35 for shape in allocations) + + +def test_pair_launch_and_explicit_sparse_work(monkeypatch): + s = spectrum([1], [1]) + sim = CudaCosineGreedy() + tile = sim._tile + launches = [] + + def record(left, right, positions, diagonal): + launches.append((len(left[0]), len(right[0]), None if positions is None else positions.tolist())) + return tile(left, right, positions, diagonal) + + monkeypatch.setattr(sim, "_tile", record) + assert sim.pair(s, s).item() == (1.0, 1) + sim.sparse_matrix([s] * 4, [s] * 5, [0, 2], [3, 1]) + assert launches == [(1, 1, None), (4, 5, [3, 11])] + + +def test_large_candidate_limit_honored_at_exact_capacity(monkeypatch): + # 46 identical masses on each side produce exactly 2116 ordered candidates. + # This also exercises global scratch when a single heap outgrows local memory. + s = spectrum([100] * 46, np.arange(1, 47)) + sim = CudaCosineGreedy(match_limit=46**2) + monkeypatch.setattr(sim, "_recover", lambda *args: pytest.fail("spurious overflow")) + actual = sim.pair(s, s) + assert actual.item() == CosineGreedy().pair(s, s).item() + + +@pytest.mark.parametrize( + "args", + [ + {"idx_row": [0]}, + {"idx_col": [0]}, + {"idx_row": [0], "idx_col": [0, 1]}, + {"idx_row": [0], "idx_col": [-1]}, + {"idx_row": [2], "idx_col": [0]}, + {"idx_row": [0.5], "idx_col": [0]}, + ], +) +def test_invalid_sparse_coordinates(args): + peaks = PeakArrays.from_peak_lists([[10]], [[1]], [20]) + with pytest.raises((ValueError, TypeError)): + CudaCosineGreedy().sparse_matrix(peaks, **args) + + +@pytest.mark.parametrize( + "gpu,cpu", [(CudaCosineGreedy, CosineGreedy), (CudaModifiedCosineGreedy, ModifiedCosineGreedy)] +) +def test_rectangular_fp64_scores_against_matchms(gpu, cpu): + rng = np.random.default_rng(117) + + def spectra(n): + result = [] + for _ in range(n): + size = rng.integers(8, 32) + mz = np.sort(rng.integers(1, 50, size)) + result.append(spectrum(mz, rng.uniform(0.05, 1.0, size), float(rng.integers(45, 50)))) + return result + + refs, queries = spectra(5), spectra(7) + args = dict(mz_power=0.5, intensity_power=0.75, noise_cutoff=0.1) + expected = cpu(**args).matrix(refs, queries, progress_bar=False) + actual = gpu(**args, batch_size=3).matrix(refs, queries, progress_bar=False) + for field in actual.score_fields: + np.testing.assert_array_equal(actual.to_array(field), expected.to_array(field)) + + +def test_fp32_truncation_keeps_oracle_precision_before_sparse_filter(): + a, b = spectrum([100, 200], [1, 2]), spectrum([100, 211], [1, 3]) + expected = CosineGreedy().pair(a, b) + assert float(np.float32(expected["score"])) != float(expected["score"]) + sim = CudaCosineGreedy(n_max_peaks=1, precision="float32") + assert sim.pair(a, b).item() == expected.item() + sparse = sim.sparse_matrix([a], [b], score_filter=lambda s: s["score"] == expected["score"]) + assert sparse.to_coo("score").data.tolist() == [expected["score"]] diff --git a/tests/similarity/test_matchms_compatibility.py b/tests/similarity/test_matchms_compatibility.py index 947fbe3..c504a41 100644 --- a/tests/similarity/test_matchms_compatibility.py +++ b/tests/similarity/test_matchms_compatibility.py @@ -1,124 +1,39 @@ -from typing import List -import numpy as np import pytest -from matchms import Scores, Spectrum, calculate_scores -from matchms.similarity import ( - BaseSimilarity, - CosineGreedy, - FingerprintSimilarity, - ModifiedCosine, -) -from simms.similarity import ( - CudaCosineGreedy, - CudaFingerprintSimilarity, - CudaModifiedCosine, -) -from simms.utils import get_correct_scores - - -def equality_function(prefix: str): - def equality(scores: Scores, scores_cu: Scores): - score = scores["score"] - matches = scores["matches"] - - score_cu = scores_cu[f"Cuda{prefix}_score"] - matches_cu = scores_cu[f"Cuda{prefix}_matches"] - not_ovfl = 1 - scores_cu[f"Cuda{prefix}_overflow"] - - # We allow only overflowed values to be different (don't count toward acc) - acc = np.isclose(matches * not_ovfl, matches_cu * not_ovfl, equal_nan=True) - assert acc.mean() >= 0.99 - - acc = np.isclose(score * not_ovfl, score_cu * not_ovfl, equal_nan=True) - assert acc.mean() >= 0.99 +from matchms import calculate_scores +from matchms import similarity as cpu +from matchms.filtering import derive_inchikey_from_inchi +from rdkit.Chem.rdFingerprintGenerator import GetMorganGenerator - # We allow only few overflows - assert not_ovfl.mean() >= 0.99 - - return equality - - -def equality_function_fingerprint( - scores: Scores, - scores_cu: Scores, -): - acc = np.isclose(scores, scores_cu, equal_nan=True) - assert acc.mean() >= 0.99 +from simms import similarity as gpu +from tests.utils import assert_scores_equal +@pytest.mark.github_ci @pytest.mark.parametrize( - "SimilarityClass, args, CudaSimilarityClass, cu_args, equality_function", + "method,kwargs", [ - ( - CosineGreedy, - dict(), - CudaCosineGreedy, - dict(), - equality_function("CosineGreedy"), - ), - ( - ModifiedCosine, - dict(), - CudaModifiedCosine, - dict(), - equality_function("ModifiedCosine"), - ), - ( - FingerprintSimilarity, - dict( - similarity_measure="jaccard", - ), - CudaFingerprintSimilarity, - dict( - similarity_measure="jaccard", - ), - equality_function_fingerprint, - ), - ( - FingerprintSimilarity, - dict( - similarity_measure="cosine", - ), - CudaFingerprintSimilarity, - dict( - similarity_measure="cosine", - ), - equality_function_fingerprint, - ), - ( - FingerprintSimilarity, - dict( - similarity_measure="dice", - ), - CudaFingerprintSimilarity, - dict( - similarity_measure="dice", - ), - equality_function_fingerprint, - ), + ("CosineGreedy", {}), + ("ModifiedCosineGreedy", {}), + ("NeutralLossesCosine", {}), + ("EntropyGreedy", {"matching_mode": "fragment"}), + ("EntropyGreedy", {"matching_mode": "hybrid"}), + ("CosineLinear", {}), + ("ModifiedCosineLinear", {}), + ("BinnedEmbeddingSimilarity", {}), + ("FingerprintSimilarity", {"similarity_measure": "tanimoto"}), + ("FingerprintSimilarity", {"similarity_measure": "cosine"}), ], ) -def test_compatibility( - gnps_with_fingerprint: List[Spectrum], - SimilarityClass: BaseSimilarity, - args: dict, - CudaSimilarityClass: BaseSimilarity, - cu_args: dict, - equality_function: callable, -): - references, queries = gnps_with_fingerprint[:256], gnps_with_fingerprint[:256] - - scores = get_correct_scores( - references=references, queries=queries, similarity_class=SimilarityClass, **args - ) - - cuda_kernel = CudaSimilarityClass( - **cu_args, batch_size=max(len(references), len(queries)) - ) - scores_cu = calculate_scores( - references=references, - queries=queries, - similarity_function=cuda_kernel, - ).to_array() - - equality_function(scores, scores_cu) +def test_calculate_scores_compatibility(pesticides, method, kwargs): + refs, queries = pesticides[:3], pesticides[2:6] + atol = 1e-12 if method in {"BinnedEmbeddingSimilarity", "EntropyGreedy"} else 0.0 + if method == "FingerprintSimilarity": + pytest.importorskip("chemap") + refs, queries = ([derive_inchikey_from_inchi(s) for s in side] for side in (refs, queries)) + kwargs = dict(kwargs, fingerprint_generator=GetMorganGenerator(radius=2, fpSize=2048)) + # matchms computes fingerprint similarities on float32 inputs. + atol = 2e-7 + expected = calculate_scores(refs, queries, getattr(cpu, method)(**kwargs)) + actual = calculate_scores(refs, queries, getattr(gpu, "Cuda" + method)(**kwargs, batch_size=2)) + assert_scores_equal(actual, expected, atol=atol) + assert actual.to_array("score").max() > 0 diff --git a/tests/similarity/test_modified_cosine.py b/tests/similarity/test_modified_cosine.py index 261e153..8fe1fa1 100644 --- a/tests/similarity/test_modified_cosine.py +++ b/tests/similarity/test_modified_cosine.py @@ -4,7 +4,6 @@ from matchms.filtering import normalize_intensities from simms.similarity import CudaModifiedCosine -# from matchms.similarity import ModifiedCosine from ..builder_Spectrum import SpectrumBuilder @@ -19,7 +18,7 @@ def compute_expected_score(spectrum_1, spectrum_2, matches): @pytest.mark.github_ci def test_modified_cosine_without_precursor_mz(): - """Test without precursor-m/z. Should raise assertion error.""" + """Test without precursor-m/z. Should identify the invalid precursor.""" mz = np.array([100, 150, 200, 300, 500, 510, 1100], dtype="float") intensities = np.array([700, 200, 100, 1000, 200, 5, 500], dtype="float") builder = SpectrumBuilder() @@ -30,12 +29,9 @@ def test_modified_cosine_without_precursor_mz(): norm_spectrum_2 = normalize_intensities(spectrum_2) modified_cosine = CudaModifiedCosine(batch_size=2) - with pytest.raises(AssertionError) as msg: + with pytest.raises(ValueError, match="precursor_mz"): modified_cosine.pair(norm_spectrum_1, norm_spectrum_2) - expected_message = "Precursor_mz missing. Apply 'add_precursor_mz' filter first." - assert str(msg.value) == expected_message - @pytest.mark.parametrize( "peaks, tolerance, masses, expected_matches", @@ -123,20 +119,16 @@ def test_modified_cosine_with_mass_shift(peaks, tolerance, masses, expected_matc norm_spectrum_2 = normalize_intensities(spectrum_2) if tolerance is None: - modified_cosine = CudaModifiedCosine(batch_size=4) + modified_cosine = CudaModifiedCosine(remove_precursor=False, noise_cutoff=0.0, batch_size=4) else: - modified_cosine = CudaModifiedCosine(batch_size=4, tolerance=tolerance) + modified_cosine = CudaModifiedCosine( + remove_precursor=False, noise_cutoff=0.0, batch_size=4, tolerance=tolerance + ) score = modified_cosine.pair(norm_spectrum_1, norm_spectrum_2) - expected_score = compute_expected_score( - norm_spectrum_1, norm_spectrum_2, expected_matches - ) - assert score["score"] == pytest.approx( - expected_score, 0.0001 - ), "Expected different cosine score." - assert score["matches"] == len( - expected_matches - ), "Expected differnt number of matching peaks." + expected_score = compute_expected_score(norm_spectrum_1, norm_spectrum_2, expected_matches) + assert score["score"] == pytest.approx(expected_score, 0.0001), "Expected different cosine score." + assert score["matches"] == len(expected_matches), "Expected differnt number of matching peaks." @pytest.mark.github_ci @@ -160,12 +152,10 @@ def test_modified_cosine_order_of_input_spectrums(): score_1_2 = modified_cosine.pair(norm_spectrum_1, norm_spectrum_2) score_2_1 = modified_cosine.pair(norm_spectrum_2, norm_spectrum_1) - assert ( - score_1_2["score"] == score_2_1["score"] - ), "Expected that the order of the arguments would not matter." - assert ( - score_1_2 == score_2_1 - ), "Expected that the order of the arguments would not matter." + assert score_1_2["score"] == score_2_1["score"], ( + "Expected that the order of the arguments would not matter." + ) + assert score_1_2 == score_2_1, "Expected that the order of the arguments would not matter." @pytest.mark.github_ci @@ -186,15 +176,12 @@ def test_modified_cosine_precursor_mz_as_invalid_string(): norm_spectrum_1 = normalize_intensities(spectrum_1) norm_spectrum_2 = normalize_intensities(spectrum_2) modified_cosine = CudaModifiedCosine(batch_size=2, tolerance=1.0) - with pytest.raises(AssertionError) as msg: - _ = modified_cosine.pair(norm_spectrum_1, norm_spectrum_2) - - expected_message = "Precursor_mz missing. Apply 'add_precursor_mz' filter first." - assert str(msg.value) == expected_message + with pytest.raises(ValueError, match=r"spectra_2.*precursor_mz"): + modified_cosine.pair(norm_spectrum_1, norm_spectrum_2) @pytest.mark.github_ci -def test_modified_cosine_precursor_mz_as_string(caplog): +def test_modified_cosine_precursor_mz_as_string(): """Test modified cosine on two spectra with precursor_mz given as string.""" spectrum_1 = Spectrum( mz=np.array([100, 200, 300], dtype="float"), @@ -215,10 +202,5 @@ def test_modified_cosine_precursor_mz_as_string(caplog): modified_cosine = CudaModifiedCosine(batch_size=2, tolerance=1.0) score = modified_cosine.pair(norm_spectrum_1, norm_spectrum_2) - assert score["score"] == pytest.approx( - 0.0, 1e-5 - ), "Expected different modified cosine score." + assert score["score"] == pytest.approx(0.0, 1e-5), "Expected different modified cosine score." assert score["matches"] == 0, "Expected 0 matching peaks." - expected_msg = "Precursor_mz must be of type int or float. Apply 'add_precursor_mz' filter first." - print("\n===>", expected_msg, "\n", caplog.text, "\n") - assert expected_msg in caplog.text, "Expected different log message" diff --git a/tests/similarity/test_neutral_losses_cosine.py b/tests/similarity/test_neutral_losses_cosine.py new file mode 100644 index 0000000..bf2857d --- /dev/null +++ b/tests/similarity/test_neutral_losses_cosine.py @@ -0,0 +1,116 @@ +from inspect import signature +from itertools import islice +from pathlib import Path + +import numpy as np +import pytest +import torch +from matchms import Scores, SpectraCollection, Spectrum, calculate_scores +from matchms.importing import load_from_mgf +from matchms.similarity import NeutralLossesCosine + +from simms import PeakArrays +from simms.similarity.CudaNeutralLossesCosine import CudaNeutralLossesCosine +from simms.utils import get_device + + +def spectrum(mz, intensity, precursor=None): + metadata = {} if precursor is None else {"precursor_mz": precursor} + return Spectrum(np.asarray(mz, dtype=float), np.asarray(intensity, dtype=float), metadata, + metadata_harmonization=False) + + +def check_scores(actual, expected): + np.testing.assert_array_equal(actual.to_array("matches"), expected.to_array("matches")) + np.testing.assert_allclose(actual.to_array("score"), expected.to_array("score"), rtol=2e-14, atol=0) + + +@pytest.mark.github_ci +def test_defaults_and_serialization(): + cpu, gpu = signature(NeutralLossesCosine).parameters, signature(CudaNeutralLossesCosine).parameters + assert list(gpu) == [*cpu, "batch_size", "n_max_peaks", "match_limit", "precision"] + assert all(gpu[k].default == v.default for k, v in cpu.items()) + config = CudaNeutralLossesCosine(precision="float32", n_max_peaks=7, batch_size=3).to_dict() + assert config.pop("__Similarity__") == "CudaNeutralLossesCosine" + assert config == {**{k: v.default for k, v in gpu.items()}, + "precision": "float32", "n_max_peaks": 7, "batch_size": 3} + + +@pytest.mark.github_ci +@pytest.mark.parametrize("precursor", [None, "invalid", 0.0, -1, np.inf, np.nan]) +def test_precursor_required_even_without_crop(precursor): + with pytest.raises(ValueError, match=r"spectra_2.*precursor_mz"): + CudaNeutralLossesCosine(remove_precursor=False).pair( + spectrum([40], [1], 100), spectrum([40], [1], precursor) + ) + + +@pytest.mark.github_ci +@pytest.mark.parametrize("delta,second_mz,count", [(0, 50, 1), (10, 50, 0), (10, 60, 1), (0.125, 50.25, 1)]) +def test_only_shifted_candidates_including_small_shifts(delta, second_mz, count): + a, b = spectrum([50], [1], 120), spectrum([second_mz], [3], str(120 + delta)) + args = dict(tolerance=0.125) + assert CudaNeutralLossesCosine(**args).pair(a, b).item() == NeutralLossesCosine(**args).pair(a, b).item() + assert CudaNeutralLossesCosine(**args).pair(a, b)["matches"] == count + + +@pytest.mark.github_ci +@pytest.mark.parametrize("caps", [{}, {"match_limit": 1}, {"n_max_peaks": 1}]) +def test_crop_noise_original_masses_and_recovery_before_sparse_filter(caps): + # Crop the strongest peak first. The peaks on both inclusive thresholds survive. + a = spectrum([10, 20, 30, 98.4, 99], [0.49, 0.5, 0.6, 1, 100], 100) + b = spectrum([30, 40, 50, 118.4, 119], [0.49, 0.8, 1, 0.5, 100], 120) + args = dict(noise_cutoff=0.5, mz_power=1.5, intensity_power=0.75) + cpu, gpu = NeutralLossesCosine(**args), CudaNeutralLossesCosine(**args, **caps) + expected = cpu.pair(a, b) + got = gpu.pair(a, b) + assert got.dtype == expected.dtype and got.shape == () + assert got["matches"] == expected["matches"] == 3 + np.testing.assert_allclose(got["score"], expected["score"], rtol=2e-14) + sparse = gpu.sparse_matrix([a, b], idx_row=[0], idx_col=[1], score_fields=["score"], + score_filter=lambda s: s["matches"] == 3) + assert sparse.score_fields == ("score",) + np.testing.assert_allclose(sparse.to_array(), [[0, expected["score"]], [expected["score"], 0]], rtol=2e-14) + + +@pytest.mark.github_ci +def test_adapters_dense_torch_sparse_and_zero_hits(): + rows = [spectrum([40, 80], [1, 2], 100), spectrum([50, 70], [2, 1], 110), + spectrum([12], [1], 125)] + cpu, gpu = NeutralLossesCosine(), CudaNeutralLossesCosine(batch_size=2) + for data in (rows, PeakArrays.from_spectra(rows), SpectraCollection(rows)): + oracle_rows = list(data) if isinstance(data, SpectraCollection) else rows + expected = cpu.matrix(oracle_rows, progress_bar=False) + got = calculate_scores(data, None, gpu) + assert isinstance(got, Scores) + check_scores(got, expected) + check_scores(gpu.sparse_matrix(data, progress_bar=False), expected) + tensor = gpu.matrix(data, array_type="torch", score_fields=["matches", "score"]) + assert tensor.device.type == get_device() and tensor.dtype == torch.float64 + np.testing.assert_array_equal(tensor[0].cpu(), expected.to_array("matches")) + np.testing.assert_allclose(tensor[1].cpu(), expected.to_array("score"), rtol=2e-14) + opts = dict(idx_row=[1, 0, 2], idx_col=[0, 1, 2], progress_bar=False) + check_scores(gpu.sparse_matrix(rows, **opts), cpu.sparse_matrix(rows, **opts)) + opts = dict(idx_row=[0], idx_col=[0], progress_bar=False) + zero = gpu.sparse_matrix(rows[:1], rows[-1:], **opts) + assert zero.shape == (1, 1) and zero.to_coo("score").nnz == zero.to_coo("matches").nnz == 0 + + +@pytest.mark.github_ci +def test_zero_norm_matches_and_no_matches(): + a = spectrum([40], [0], 100) + b = spectrum([80], [1], 100) + for sim in [NeutralLossesCosine(), CudaNeutralLossesCosine()]: + assert sim.pair(a, b).item() == (0.0, 0) + with pytest.raises(ZeroDivisionError): + sim.pair(a, a) + + +@pytest.mark.github_ci +def test_pesticide_reference_matrix(): + path = Path(__file__).parents[1] / "data" / "pesticides.mgf" + rows = list(islice(load_from_mgf(str(path)), 8)) + args = dict(mz_power=0.5, intensity_power=0.75) + expected = NeutralLossesCosine(**args).matrix(rows[:5], rows[2:], progress_bar=False) + actual = CudaNeutralLossesCosine(**args, batch_size=3).matrix(rows[:5], rows[2:], progress_bar=False) + check_scores(actual, expected) diff --git a/tests/similarity/test_peak_arrays.py b/tests/similarity/test_peak_arrays.py new file mode 100644 index 0000000..3cd1c61 --- /dev/null +++ b/tests/similarity/test_peak_arrays.py @@ -0,0 +1,91 @@ +import numpy as np +import pytest + +from simms import PeakArrays + + +pytestmark = pytest.mark.github_ci + + +@pytest.mark.parametrize( + "mz,ints,lengths,error", + [ + ([1.0], [1.0], [1], ValueError), + ([[1.0]], [[1.0, 2.0]], [1], ValueError), + ([[1]], [[1.0]], [1], TypeError), + ([[1.0]], [[1]], [1], TypeError), + ([[1.0]], [[1.0]], [[1]], ValueError), + ([[1.0]], [[1.0]], [0.5], ValueError), + ([[1.0]], [[1.0]], [-1], ValueError), + ([[1.0]], [[1.0]], [2], ValueError), + ([[np.nan]], [[1.0]], [1], ValueError), + ([[1.0]], [[np.inf]], [1], ValueError), + ([[2.0, 1.0]], [[1.0, 1.0]], [2], ValueError), + ], +) +def test_invalid_arrays(mz, ints, lengths, error): + with pytest.raises(error): + PeakArrays(np.array(mz), np.array(ints), np.array(lengths)) + + +@pytest.mark.parametrize("precursor", [[], [0], [-1], [np.nan], [np.inf], [[5]]]) +def test_invalid_precursor(precursor): + with pytest.raises(ValueError, match="precursor_mz"): + PeakArrays.from_peak_lists([[1]], [[1]], precursor) + + +@pytest.mark.parametrize( + "mz,ints", [([[1, 2, 3]], [[7]]), ([1], [[3]]), ([[[1, 2]]], [[3, 4]]), ([[1]], [[2], [3]])] +) +def test_peak_lists_reject_misaligned_rows(mz, ints): + with pytest.raises(ValueError): + PeakArrays.from_peak_lists(mz, ints) + + +def test_padding_slicing_and_dtype(): + mz = np.array([[1.0, 1.0, np.nan], [3.0, 99.0, 101.0]]) + peaks = PeakArrays(mz, mz, np.array([2, 1]), np.array([500.0, 501.0])) + assert peaks.mz.tolist() == peaks.intensities.tolist() == [[1.0, 1.0, 0.0], [3.0, 0.0, 0.0]] + assert np.isnan(mz[0, 2]) + assert peaks[1:].precursor_mz.tolist() == [501.0] + stacked, lengths = peaks.to_width(1) + assert stacked.shape == (2, 2, 1) + assert lengths.tolist() == [1, 1] + small = PeakArrays.from_spectra(peaks, dtype=np.float32) + assert small.mz.dtype == small.intensities.dtype == np.float32 + assert small.precursor_mz.dtype == np.float64 + + +def test_crop_then_relative_noise_inclusive_boundaries(): + # The strongest peak is cropped. Both the exact m/z and noise cutoffs survive. + p = PeakArrays.from_peak_lists([[3, 4, 8.4, 9, 10], [11]], [[0.49, 0.5, 1, 90, 100], [1]], [10, 10]) + got = PeakArrays.from_spectra(p, remove_precursor=True, noise_cutoff=0.5) + assert got.lengths.tolist() == [2, 0] + assert got.mz.tolist() == [[4, 8.4], [0, 0]] + assert got.intensities.tolist() == [[0.5, 1], [0, 0]] + assert p.lengths.tolist() == [5, 1] + + +def test_optional_precursor_missing_from_part_of_a_collection(): + from matchms import SpectraCollection, Spectrum + + rows = [ + Spectrum(np.array([100.0]), np.array([1.0]), m, metadata_harmonization=False) + for m in [{}, {"precursor_mz": 200.0}] + ] + coll = SpectraCollection(rows) + assert PeakArrays.from_spectra(coll).precursor_mz is None + with pytest.raises(ValueError, match=r"spectra\[0\].*precursor_mz"): + PeakArrays.from_spectra(coll, require_precursor=True) + + +def test_preprocessing_preserves_matchms_float32_boundary(): + from matchms import Spectrum + from matchms.similarity.spectrum_similarity_functions import _process_spectrum_peaks + + mz = np.array([100, 100.25], dtype=np.float32) + s = Spectrum(mz, np.ones_like(mz), {"precursor_mz": 100.25 - 1e-7}, metadata_harmonization=False) + args = dict(remove_precursor=True, offset_to_precursor=0.0, noise_cutoff=0.01) + expected = _process_spectrum_peaks(s, **args) + got = PeakArrays.from_spectra([s], **args) + np.testing.assert_array_equal(got.mz[0], expected[:, 0]) diff --git a/tests/similarity/test_transitive_alignment.py b/tests/similarity/test_transitive_alignment.py new file mode 100644 index 0000000..488a33c --- /dev/null +++ b/tests/similarity/test_transitive_alignment.py @@ -0,0 +1,257 @@ +# SPDX-License-Identifier: MIT +import json + +import numpy as np +import pytest +from matchms import Scores, SpectraCollection, Spectrum +from matchms.similarity import ModifiedCosineGreedy +from scipy.sparse import coo_array + +from benchmarks.benchmark_transitive_alignment import assert_parity, cpu_reference +from simms import PeakArrays +from simms.similarity import CudaTransitiveAlignment + + +def spectrum(mz, intensities, precursor): + return Spectrum( + np.array(mz, dtype=float), + np.array(intensities, dtype=float), + {"precursor_mz": float(precursor)}, + metadata_harmonization=False, + ) + + +def chain_spectra(hops): + # Each modification shifts exactly one of two disjoint fragment groups. + # Across >=2 hops every fragment therefore has a partial precursor shift. + mz = np.arange(100, 400, 50) + precursor = 500 + intensities = [1, 2, 3, 4, 5, 6] + rows = [spectrum(mz, intensities, precursor)] + for step, delta in enumerate([1, 3, 7, 13][:hops]): + mz[step % 2 :: 2] += delta + precursor += delta + rows.append(spectrum(mz, intensities, precursor)) + return rows + + +def base_matrix(n, entries): + base = np.zeros((n, n), dtype=[("score", float), ("matches", int)]) + for u, v, score, matches in entries: + base[u, v] = score, matches + return base + + +@pytest.mark.github_ci +@pytest.mark.parametrize("hops", [2, 3, 4]) +def test_multimodification_chain(hops): + rows = chain_spectra(hops) + direct = ModifiedCosineGreedy().pair(rows[0], rows[-1]) + assert (direct["score"], direct["matches"]) == (0.0, 0) + result = CudaTransitiveAlignment(batch_size=2).align(rows, return_peak_pairs=True) + assert [(e.row, e.col, e.score, e.matches) for e in result.direct_edges] == [ + (i, i + 1, 1.0, 6) for i in range(hops) + ] + assert len(result.transitive_edges) == hops * (hops - 1) // 2 + for e in result.transitive_edges: + assert (e.score, e.matches, e.hops) == (1.0, 6, e.col - e.row) + assert result.paths[e.row, e.col] == tuple(range(e.row, e.col + 1)) + assert result.peak_pairs[e.row, e.col] == tuple((i, i) for i in range(6)) + data = json.loads(json.dumps(result.to_dict(), allow_nan=False)) + assert len(data["paths"]) == len(result.paths) + assert all(entry["pairs"][0] == [0, 0] for entry in data["peak_pairs"]) + + +@pytest.mark.github_ci +@pytest.mark.parametrize("kind", ["generator", "collection", "arrays"]) +def test_supported_inputs_and_transitive_only_scores(kind): + rows = chain_spectra(2) + inputs = { + "generator": lambda: iter(rows), + "collection": lambda: SpectraCollection(rows), + "arrays": lambda: PeakArrays.from_spectra(rows), + } + method = CudaTransitiveAlignment() + expected = np.array([[0, 1, 1], [1, 0, 1], [1, 1, 0]]) + dense = method.matrix(inputs[kind]()) + assert isinstance(dense, Scores) and not dense.is_sparse + np.testing.assert_array_equal(dense.to_array("score"), expected) + np.testing.assert_array_equal(dense.to_array("matches"), expected * 6) + sparse = method.sparse_matrix(inputs[kind](), transitive_only=True) + assert isinstance(sparse, Scores) and sparse.is_sparse + for name, value in [("score", 1.0), ("matches", 6)]: + coo = sparse.to_coo(name) + assert set(zip(coo.row, coo.col, coo.data)) == {(0, 2, value), (2, 0, value)} + assert coo.nnz == 2 + + +@pytest.mark.github_ci +def test_sparse_output_threshold_preserves_bridge_paths(): + rows = chain_spectra(2) + base = base_matrix(3, [(0, 1, 0.75, 6), (1, 2, 0.8, 6)]) + method = CudaTransitiveAlignment() + scores = method.sparse_matrix(rows, base_scores=base, min_score=1) + np.testing.assert_array_equal(scores.to_array("score"), [[0, 0, 1], [0, 0, 0], [1, 0, 0]]) + empty = method.sparse_matrix(rows, base_scores=base, min_score=np.nextafter(1.0, np.inf)) + for field, dtype in [("score", np.float64), ("matches", np.intp)]: + coo = empty.to_coo(field) + assert isinstance(coo, coo_array) and coo.nnz == 0 and coo.dtype == dtype + + +@pytest.mark.github_ci +@pytest.mark.parametrize("rows", [[], chain_spectra(0), [spectrum([], [], 500), spectrum([], [], 500)]]) +def test_empty_singleton_and_empty_peak_rows(rows): + result = CudaTransitiveAlignment().align(iter(rows)) + assert result.paths == {} and result.peak_pairs is None + assert result.direct_edges == result.transitive_edges == [] + assert result.to_scores().shape == (len(rows), len(rows)) + assert result.to_scores(sparse=True).to_coo("score").nnz == 0 + + +@pytest.mark.github_ci +def test_path_weights_hop_limit_and_disconnected_components(): + rows = [chain_spectra(0)[0]] * 8 + # 0 -> 3 -> 2 beats the equally short path via 1. The path to 4 via + # 5 is shorter than either route via 2, despite lower total weight. + entries = [ + (0, 1, 0.8, 6), + (1, 2, 0.9, 6), + (0, 3, 0.95, 6), + (3, 2, 1.0, 6), + (2, 4, 1.0, 6), + (0, 5, 0.7, 6), + (5, 4, 0.7, 6), + (6, 7, 1.0, 6), + (0, 2, 1.0, 5), + (0, 7, 0.69, 6), + ] + base = base_matrix(8, entries) + method = CudaTransitiveAlignment() + result = method.align(rows, base_scores=base) + assert result.paths[0, 2] == (0, 3, 2) + assert result.paths[0, 4] == (0, 5, 4) + assert result.paths[1, 5] == (1, 0, 5) + assert all(v < 6 for _, v in result.paths) + assert result.paths[3, 5] == (3, 0, 5) + limited = CudaTransitiveAlignment(max_hops=2).align(rows, base_scores=base) + assert limited.paths == {k: v for k, v in result.paths.items() if len(v) <= 3} + assert CudaTransitiveAlignment(max_hops=1).align(rows, base_scores=base).paths == {} + + +@pytest.mark.github_ci +def test_precomputed_sparse_independent_coordinates_and_no_direct_rescoring(monkeypatch): + rows = chain_spectra(2) + score = coo_array(([0.9, 0.8], ([1, 0], [2, 1])), shape=(3, 3)) + matches = coo_array(([6, 6, 7], ([0, 1, 2], [1, 2, 0])), shape=(3, 3)) + method = CudaTransitiveAlignment() + monkeypatch.setattr(method, "_direct_edges", lambda *args: pytest.fail("recomputed base scores")) + expected = method.align(rows, base_scores=Scores({"score": score, "matches": matches})) + assert expected.paths == {(0, 2): (0, 1, 2)} + assert [e.score for e in expected.direct_edges] == [0.8, 0.9] + for dense in (False, True): + base = { + k: (a.toarray() if dense else a.T.tocsr()) for k, a in [("score", score), ("matches", matches)] + } + assert method.align(rows, base_scores=base) == expected + with pytest.raises(ValueError, match="shape"): + method.align(rows, base_scores=base_matrix(2, [])) + with pytest.raises(ValueError, match="matches"): + method.align(rows, base_scores=Scores({"score": score})) + + +@pytest.mark.github_ci +def test_no_survivor_despite_direct_endpoint_candidate(): + rows = [spectrum(mz, [1, 1], 100) for mz in ([10, 30], [10, 20], [20, 30])] + base = base_matrix(3, [(0, 1, 0.5, 1), (1, 2, 0.5, 1)]) + method = CudaTransitiveAlignment(min_direct_score=0.5, min_direct_matches=1) + result = method.align(rows, base_scores=base, return_peak_pairs=True) + assert result.paths == {(0, 2): (0, 1, 2)} + assert (0, 2) not in result.peak_pairs + assert result.transitive_edges == [] + assert result.to_scores()[0, 2] == {"score": 0.0, "matches": 0} + + +@pytest.mark.github_ci +@pytest.mark.parametrize("caps", [{}, {"match_limit": 3}, {"n_max_peaks": 2}, {"precision": "float32"}]) +@pytest.mark.parametrize("competitor", [1.0, 3.0]) +def test_endpoint_pool_conflict_deduplication_full_norms_and_overflow(caps, competitor): + rows = [ + spectrum([100, 170, 220, 280, 310], [2, 2, 4, 1, 1], 500), + spectrum([101, 170, 280], [1, 2, 1], 501), + spectrum([101, 104, 170, 222, 280, 314], [1, competitor, 2, 5, 1, 1], 504), + ] + base = base_matrix(3, [(0, 1, 0.8, 3), (1, 2, 0.9, 3)]) + method = CudaTransitiveAlignment(min_direct_matches=3, **caps) + result = method.align(rows, base_scores=base, return_peak_pairs=True) + # The endpoint-shifted candidate wins the conflict with the bridge + # (also on a tie). Two endpoint candidates duplicate composed pairs. + assert result.peak_pairs[0, 2] == ((0, 1), (1, 2), (3, 4), (4, 5)) + (edge,) = result.transitive_edges + assert edge.matches == 4 + expected = (2 * competitor + 6) / np.sqrt(26 * (32 + competitor**2)) + assert edge.score == pytest.approx(expected, rel=1e-7 if caps.get("precision") else 1e-15) + assert ( + not CudaTransitiveAlignment(min_direct_matches=3, min_transitive_score=0.99) + .align(rows, base_scores=base) + .transitive_edges + ) + + +@pytest.mark.github_ci +def test_direct_equal_products_matchms_order_overlapping_windows_and_reverse_maps(): + # Both right peaks qualify unshifted, but only the earlier peak also + # qualifies shifted. It wins because shifted candidates are visited first. + rows = [spectrum([100], [1], 501.5), spectrum([99.5, 101], [1, 1], 500)] + result = CudaTransitiveAlignment(tolerance=1, min_direct_matches=1).align(rows, return_peak_pairs=True) + assert result.peak_pairs[0, 1] == ((0, 0),) + order = [0, 2, 1, 3] + chain = chain_spectra(3) + result = CudaTransitiveAlignment().align([chain[i] for i in order], return_peak_pairs=True) + limited = CudaTransitiveAlignment(max_hops=2).align([chain[i] for i in order]) + assert (0, 3) not in limited.paths + assert len(limited.transitive_edges) == 2 + assert result.paths[0, 3] == (0, 2, 1, 3) + assert result.peak_pairs[0, 3] == tuple((i, i) for i in range(6)) + + +@pytest.mark.github_ci +def test_filtered_indices_weighted_products_and_full_precision_cap(monkeypatch): + from simms.similarity import _transitive_peaks + + # All rows lose a low-intensity peak and the precursor. Powers change + # the products and norms; an unmatched source peak still contributes. + rows = [ + spectrum([11, 40, 60, 80, 100], [0.001, 2, 3, 1, 1], 100), + spectrum([11, 41, 60, 101], [0.001, 2, 3, 1], 101), + spectrum([11, 41, 63, 104], [0.001, 3, 2, 1], 104), + ] + setup = {"min_direct_matches": 2, "min_direct_score": 0.0, "mz_power": 1.0, "intensity_power": 0.5} + base = base_matrix(3, [(0, 1, 0.8, 2), (1, 2, 0.8, 2)]) + recover = _transitive_peaks._recover + calls = [] + + def track(peaks, method, u, v, *rest): + calls.append((u, v)) + return recover(peaks, method, u, v, *rest) + + monkeypatch.setattr(_transitive_peaks, "_recover", track) + left = np.array([40, 60, 80]) * np.sqrt([2, 3, 1]) + right = np.array([41, 63]) * np.sqrt([3, 2]) + expected = left[:2] @ right / (np.linalg.norm(left) * np.linalg.norm(right)) + for caps in ({}, {"match_limit": 1, "precision": "float32"}): + result = CudaTransitiveAlignment(**setup, **caps).align( + rows, base_scores=base, return_peak_pairs=True + ) + assert result.peak_pairs[0, 2] == ((0, 0), (1, 1)) + (edge,) = result.transitive_edges + assert (edge.score, edge.matches) == (pytest.approx(expected, abs=2e-15, rel=0), 2) + assert calls == ([(0, 1), (1, 2), (0, 2)] if caps else []) + + +def test_pesticides_exact_cpu_parity(pesticides): + # Exercise the real-file network as well as the handcrafted fixtures. + params = {"min_direct_score": 0.5, "min_direct_matches": 3} + expected = cpu_reference(pesticides, **params) + actual = CudaTransitiveAlignment(**params).align(pesticides, return_peak_pairs=True) + assert expected.direct_edges and expected.transitive_edges + assert_parity(expected, actual) diff --git a/tests/similarity/test_workflow_edge_cases.py b/tests/similarity/test_workflow_edge_cases.py new file mode 100644 index 0000000..8365506 --- /dev/null +++ b/tests/similarity/test_workflow_edge_cases.py @@ -0,0 +1,494 @@ +"""Release workflows using the public matchms 1.0.0 interfaces.""" + +import json +import os +import subprocess +import sys +from types import SimpleNamespace + +import numpy as np +import pytest +import torch +from matchms import Pipeline, Scores, SpectraCollection, Spectrum, calculate_scores +from matchms import similarity as cpu +from matchms.importing import load_from_mgf +from matchms.pipeline import create_workflow +from rdkit.Chem.rdFingerprintGenerator import GetMorganGenerator +from scipy.sparse import coo_array + +from simms import PeakArrays +from simms import similarity as gpu +from simms.utils import download, get_device, process_spectrum +from tests.utils import assert_scores_equal + + +METHODS = ( + gpu.CudaCosineGreedy, gpu.CudaModifiedCosineGreedy, gpu.CudaNeutralLossesCosine, + gpu.CudaEntropyGreedy, gpu.CudaCosineLinear, gpu.CudaModifiedCosineLinear, + gpu.CudaBinnedEmbeddingSimilarity, gpu.CudaFingerprintSimilarity, +) +COSINES = tuple(cls for cls in METHODS if "Cosine" in cls.__name__) +GREEDY = COSINES[:3] +CHEMICALS = ( + ("CCO", "LFQSCWFLJHTTHZ-UHFFFAOYSA-N"), + ("CCCC", "IJDNQMDRQITEOD-UHFFFAOYSA-N"), + ("CCCO", "BDERNNFJNOPAEC-UHFFFAOYSA-N"), +) + + +def parameters(cls): + if cls is gpu.CudaFingerprintSimilarity: + pytest.importorskip("chemap") + return {"fingerprint_generator": GetMorganGenerator(radius=2, fpSize=64)} + return {} + + +def spectrum(mz, precursor=200.5, dtype=float, compound=0): + mz = np.asarray(mz, dtype=dtype) + smiles, key = CHEMICALS[compound] + metadata = {"smiles": smiles, "inchikey": key} + if precursor is not None: + metadata["precursor_mz"] = precursor + return Spectrum(mz, np.arange(1, mz.size + 1, dtype=dtype), metadata, metadata_harmonization=False) + + +@pytest.fixture +def mgf(tmp_path): + path = tmp_path / "library.mgf" + path.write_text("".join( + f"BEGIN IONS\nTITLE=row{i}\nPEPMASS={mass}\nSMILES={smiles}\nINCHIKEY={key}\n" + f"50 1\n{60 + i} 2\nEND IONS\n" + for i, ((smiles, key), mass) in enumerate(zip(CHEMICALS, [200, 200.05, 400])) + )) + return path + + +@pytest.mark.github_ci +@pytest.mark.parametrize("cls", METHODS) +def test_mgf_iterators_persistence_and_masked_pipeline(cls, mgf, tmp_path): + kwargs = parameters(cls) + sim = cls(batch_size=2, **kwargs) + oracle = getattr(cpu, cls.__name__[4:])(**kwargs) + rows = list(load_from_mgf(mgf)) + expected = oracle.matrix(rows, progress_bar=False) + atol = 2e-7 if cls is gpu.CudaFingerprintSimilarity else 1e-12 + assert expected.shape == (3, 3) + config = json.loads(json.dumps(sim.to_dict())) + assert config.pop("__Similarity__") == cls.__name__ + restored = cls(**config) + + dense = calculate_scores(load_from_mgf(mgf), load_from_mgf(mgf), sim) + same_iterator = load_from_mgf(mgf) + for output in (dense, sim.matrix(same_iterator, same_iterator), restored.matrix(load_from_mgf(mgf)), + sim.matrix(load_from_mgf(mgf), load_from_mgf(mgf))): + assert_scores_equal(output, expected, atol=atol) + sparse = sim.sparse_matrix(load_from_mgf(mgf)) + for result in (dense, sparse): + path = tmp_path / "scores.npz" + result.save(path) + saved = Scores.load(path) + assert_scores_equal(saved, result, atol=0) + for field in expected.score_fields: + assert saved.to_array(field).dtype == expected.to_array(field).dtype + np.testing.assert_allclose(saved.to_array(field), expected.to_array(field), atol=atol, rtol=0) + + workflow = create_workflow(score_computations=[ + ["PrecursorMzMatch", {"tolerance": 0.1}], ["mask", {"operation": "==", "value": True}], + [cls, config], + ]) + pipeline = Pipeline(workflow, progress_bar=False) + pipeline.run(str(mgf), create_report=False) + mask = np.array([[1, 1, 0], [1, 1, 0], [0, 0, 1]], dtype=bool) + assert pipeline.scores.is_sparse + for field in expected.score_fields: + np.testing.assert_allclose(pipeline.scores.to_array(field), expected.to_array(field) * mask, + atol=atol, rtol=0) + + +@pytest.mark.github_ci +def test_mgf_peak_arrays(mgf): + peaks = PeakArrays.from_spectra(load_from_mgf(mgf)) + np.testing.assert_array_equal(peaks.lengths, [2, 2, 2]) + np.testing.assert_array_equal(peaks.mz[:, 1], [60, 61, 62]) + assert gpu.CudaModifiedCosine is gpu.CudaModifiedCosineGreedy + + +@pytest.mark.github_ci +@pytest.mark.parametrize("cls", METHODS) +def test_sparse_coordinates_filters_and_projection(cls): + rows = [spectrum([50, 60 + i], compound=i) for i in range(3)] + sim = cls(batch_size=2, **parameters(cls)) + dense = sim.matrix(rows) + for self_comparison in (True, False): + rhs = None if self_comparison else rows + coords = [(2, 0), (1, 0), (2, 0), (1, 1)] + i, j = zip(*coords) + fields = sim.score_fields + for selected in ([["matches", "score"], ["score"], ["matches"]] if len(fields) == 2 else [["score"]]): + def keep(value): + return value["matches"] == 1 if len(fields) == 2 else value < 0.999 + + scores = sim.sparse_matrix(rows, rhs, idx_row=i, idx_col=j, + score_filter=keep, score_fields=selected) + assert scores.score_fields == tuple(selected) + for field in selected: + expected = np.zeros(dense.shape) + for r, c in coords: + if r != c: + expected[r, c] = dense.to_array(field)[r, c] + if self_comparison: + expected[c, r] = expected[r, c] + np.testing.assert_allclose(scores.to_array(field), expected) + assert scores.to_coo(field).nnz == np.count_nonzero(expected) + empty = sim.sparse_matrix(rows, idx_row=[], idx_col=[]) + assert empty.shape == (3, 3) + for field in empty.score_fields: + assert empty.to_coo(field).nnz == 0 + if len(sim.score_fields) == 1: + with pytest.raises(ValueError, match="score field"): + sim.sparse_matrix(rows, score_fields=["matches"]) + + +@pytest.mark.github_ci +@pytest.mark.parametrize("cls", METHODS) +@pytest.mark.parametrize("symmetric", [True, False], ids=["self", "rectangular"]) +@pytest.mark.parametrize("explicit", [False, True], ids=["all_pairs", "coordinates"]) +def test_sparse_thresholds_match_callable(cls, symmetric, explicit): + rows = [spectrum([50, 60 + i], compound=i) for i in range(3)] + rhs = None if symmetric else rows[1:] + sim = cls(batch_size=2, **parameters(cls)) + options = {"score_fields": sim.score_fields[::-1], "progress_bar": False} + if explicit: + options.update(idx_row=[2, 1, 1, 0, 0], idx_col=[0, 0, 1, 1, 1]) + thresholds = {"min_score": 0.125} + if sim.is_structured_score: + thresholds["min_matches"] = 2 + + def keep(s): + return s["score"] >= 0.125 and s["matches"] >= 2 if sim.is_structured_score else s >= 0.125 + + actual = sim.sparse_matrix(rows, rhs, **thresholds, **options) + expected = sim.sparse_matrix(rows, rhs, score_filter=keep, **options) + empty = sim.sparse_matrix(rows, rhs, min_score=2, **options) + assert actual.shape == expected.shape == empty.shape == (3, 3 if symmetric else 2) + assert actual.score_fields == expected.score_fields == sim.score_fields[::-1] + for field in actual.score_fields: + a, b, e = (result.to_coo(field) for result in (actual, expected, empty)) + assert isinstance(a, coo_array) and isinstance(e, coo_array) + assert a.dtype == b.dtype == e.dtype + assert e.nnz == 0 + assert a.nnz == len(set(zip(a.row, a.col))) + for attr in ("row", "col", "data"): + np.testing.assert_array_equal(getattr(a, attr), getattr(b, attr)) + + +@pytest.mark.github_ci +@pytest.mark.parametrize("cls", [gpu.CudaCosineLinear, gpu.CudaEntropyGreedy, gpu.CudaBinnedEmbeddingSimilarity]) +def test_sparse_device_compaction_boundaries_and_custom_predicates(cls, monkeypatch): + # Inject the same recovered tile to cover NaN, exact ties, explicit zero + # fields and a float64 threshold between adjacent float32 scores. + sim = cls(dtype=np.float32) if cls is gpu.CudaEntropyGreedy else cls(precision="float32") + structured = sim.is_structured_score + data = [[float("nan"), 0, 0.5, 0.75], [2, 2, 0, 2]] + tile = torch.tensor(data if structured else data[0], dtype=torch.float32, device=get_device()) + monkeypatch.setattr(sim, "_inputs", lambda *args: (range(1), range(4), False)) + monkeypatch.setattr(sim, "_tiles", lambda *args: [(slice(0, 1), slice(0, 4), None, tile)]) + transfers = [] + cpu = torch.Tensor.cpu + + def track_cpu(tensor, *args, **kwargs): + transfers.append(tensor.shape[-1]) + return cpu(tensor, *args, **kwargs) + + monkeypatch.setattr(torch.Tensor, "cpu", track_cpu) + def scores(**kwargs): + return sim.sparse_matrix([], progress_bar=False, **kwargs) + + default = scores().to_coo("score") + assert default.col.tolist() == ([0, 3] if structured else [0, 2, 3]) + assert np.isnan(default.data[0]) + assert max(transfers) == default.nnz + transfers.clear() + called = [] + + def keep(s): + value = s["score"] if structured else s + called.append(float(value)) + return value == 0.75 + + result = scores(min_score=0.5, score_filter=keep, score_fields=["matches"] if structured else ["score"]) + assert called == [0.5, 0.75] + assert max(transfers) == 2 + assert result.to_coo(result.score_fields[0]).col.tolist() == [3] + higher = np.nextafter(np.float64(0.5), np.inf) + assert scores(min_score=higher).to_coo("score").col.tolist() == [3] + assert scores(min_score=np.nan).to_coo("score").nnz == 0 + if structured: + assert scores(min_matches=2).to_coo("matches").col.tolist() == [0, 1, 3] + assert scores(min_score=0, min_matches=2).to_coo("matches").col.tolist() == [1, 3] + monkeypatch.setattr(sim, "keep_score", keep) + called.clear() + assert scores().to_coo("score").col.tolist() == [3] + assert len(called) == 4 and np.isnan(called[0]) + called.clear() + assert scores(min_score=0.75).to_coo("score").col.tolist() == [3] + assert called == [0.75] + + +@pytest.mark.github_ci +@pytest.mark.parametrize("cls", METHODS) +def test_precursor_values_and_collection_missing_values(cls): + kwargs = parameters(cls) + sim, oracle = cls(**kwargs), getattr(cpu, cls.__name__[4:])(**kwargs) + reference = [spectrum([50])] + for precursor in ("200.5", None, np.nan, np.inf, 0., -1.): + query = [spectrum([50], precursor)] + if (precursor is None or precursor != precursor or precursor in (0., -1.)) and ( + cls in GREEDY or cls is gpu.CudaModifiedCosineLinear + ): + with pytest.raises(AssertionError, match="(?i)precursor"): + oracle.matrix(reference, query) + with pytest.raises((AssertionError, ValueError), match="(?i)precursor"): + sim.matrix(reference, query) + elif precursor == np.inf and cls in GREEDY: + # Raw peak buffers deliberately require a finite precursor for cropping/shifting. + assert np.isfinite(oracle.matrix(reference, query).to_array("score")).all() + with pytest.raises(ValueError, match="finite precursor_mz"): + sim.matrix(reference, query) + else: + assert_scores_equal(sim.matrix(reference, query), oracle.matrix(reference, query), atol=2e-7) + + coll = SpectraCollection([spectrum([50], None), spectrum([50], np.nan, compound=1), + spectrum([50], 200.5, compound=2)]) + if cls in GREEDY or cls is gpu.CudaModifiedCosineLinear: + with pytest.raises((ValueError, AssertionError), match="(?i)precursor"): + sim.matrix(coll) + with pytest.raises(AssertionError, match="(?i)precursor"): + oracle.matrix(list(coll)) + else: + assert_scores_equal(sim.matrix(coll), oracle.matrix(list(coll)), atol=2e-7) + + +@pytest.mark.github_ci +@pytest.mark.parametrize("cls", METHODS) +def test_empty_axes_and_peak_rows(cls): + rows = [spectrum([]), spectrum([40], compound=1), spectrum([40, 40, 80], compound=2)] + kwargs = parameters(cls) + sim, oracle = cls(**kwargs), getattr(cpu, cls.__name__[4:])(**kwargs) + for source in ([], iter(()), PeakArrays.from_peak_lists([], []), SpectraCollection(rows)[:0]): + assert sim.matrix(source).shape == sim.sparse_matrix(source).shape == (0, 0) + assert sim.matrix(source, rows).shape == (0, 3) + assert sim.sparse_matrix(rows, source).shape == (3, 0) + assert_scores_equal(sim.matrix(rows), oracle.matrix(rows), atol=2e-7) + + +@pytest.mark.github_ci +def test_empty_spectra_collection_constructor(): + with pytest.raises(ValueError, match="at least one Spectrum"): + SpectraCollection([]) + + +@pytest.mark.github_ci +@pytest.mark.parametrize("cls", [*COSINES, gpu.CudaEntropyGreedy]) +@pytest.mark.parametrize("kwargs", [{"remove_precursor": True}, {"remove_precursor": False, "noise_cutoff": 2}]) +def test_all_peaks_filtered(cls, kwargs): + rows = [spectrum([60], 50), spectrum([70, 80], 50)] + assert_scores_equal(cls(**kwargs).matrix(rows), getattr(cpu, cls.__name__[4:])(**kwargs).matrix(rows)) + + +@pytest.mark.github_ci +@pytest.mark.parametrize("cls", COSINES) +def test_zero_powers_ignore_padding(cls): + rows = [spectrum([40, 40, 80]), spectrum([40]), spectrum([])] + kwargs = dict(mz_power=0, intensity_power=0) + assert_scores_equal(cls(**kwargs).matrix(rows), getattr(cpu, cls.__name__[4:])(**kwargs).matrix(rows)) + + +@pytest.mark.github_ci +@pytest.mark.parametrize("cls", METHODS[:-1]) +@pytest.mark.parametrize("dtype", [np.int32, np.float32, np.float64]) +def test_numeric_peak_dtypes(cls, dtype): + # matchms Spectrum requires floating peaks. Its linear CPU merger requires float64. + masses = [[1, 1, 3], [2, 3]] + expected_rows = [spectrum(mz) for mz in masses] + if dtype == np.int32: + rows = [SimpleNamespace(peaks=SimpleNamespace(mz=s.peaks.mz.astype(dtype), + intensities=s.peaks.intensities.astype(dtype)), get=s.get) + for s in expected_rows] + else: + rows = [spectrum(mz, dtype=dtype) for mz in masses] + kwargs = {"bin_width": 0.5} if cls is gpu.CudaBinnedEmbeddingSimilarity else {} + assert_scores_equal(cls(**kwargs).matrix(rows), getattr(cpu, cls.__name__[4:])(**kwargs).matrix(expected_rows)) + + +@pytest.mark.github_ci +@pytest.mark.parametrize("batch_size", [1, 2]) +def test_directional_shift_never_mirrors(batch_size): + rows = [spectrum([50]), spectrum([60])] + sim = gpu.CudaCosineGreedy(shift=10, batch_size=batch_size) + expected = [[0., 0.], [1., 0.]] + for scores in (sim.matrix(rows), sim.sparse_matrix(rows), + sim.sparse_matrix(rows, idx_row=[0, 1, 1], idx_col=[1, 0, 0])): + np.testing.assert_array_equal(scores.to_array("score"), expected) + np.testing.assert_array_equal(scores.to_array("matches"), expected) + + +@pytest.mark.parametrize("cls", [*GREEDY, gpu.CudaModifiedCosineLinear]) +def test_cpu_recovery_keeps_match_past_device_limit(cls, monkeypatch): + n = 2049 if cls is gpu.CudaModifiedCosineLinear else 8193 + a, b = spectrum(np.arange(1, n + 1), n + 20), spectrum([n], n + 20) + sim = cls(noise_cutoff=None) + expected = getattr(cpu, cls.__name__[4:])(noise_cutoff=None).pair(a, b) + assert expected["matches"] == 1 + calls = [] + recover = sim._recover + + def observed(left, right, i, j): + calls.append((i, j)) + return recover(left, right, i, j) + + monkeypatch.setattr(sim, "_recover", observed) + result = sim.sparse_matrix([a], [b], idx_row=[0], idx_col=[0]) + assert calls == [(0, 0)] + assert result.to_array("score").item() == pytest.approx(expected["score"], rel=1e-12) + assert result.to_array("matches").item() == 1 + + +@pytest.mark.github_ci +def test_cpu_only_and_optional_dependency_isolation(): + # New interpreter: Numba reads simulator configuration at import time. + code = """ +import sys +sys.modules['chemap'] = None +import simms +import simms.similarity as gpu +import numpy as np +import torch +from matchms import Spectrum +from rdkit.Chem.rdFingerprintGenerator import GetMorganGenerator +assert not torch.cuda.is_available() +s = Spectrum(np.array([1.]), np.array([1.]), { + 'precursor_mz': 100., 'smiles': 'CCO', 'inchikey': 'LFQSCWFLJHTTHZ-UHFFFAOYSA-N'}) +for cls in (gpu.CudaCosineGreedy, gpu.CudaModifiedCosineGreedy, gpu.CudaNeutralLossesCosine, + gpu.CudaEntropyGreedy, gpu.CudaCosineLinear, gpu.CudaModifiedCosineLinear): + for score in (cls().matrix, cls().sparse_matrix): + try: + score([s]) + except RuntimeError as exc: + assert 'requires CUDA' in str(exc) and 'NUMBA_ENABLE_CUDASIM=1' in str(exc) + else: + raise AssertionError(cls) +assert gpu.CudaBinnedEmbeddingSimilarity().pair(s, s) == 1 +assert gpu.CudaFingerprintSimilarity().pair([2, 0], [1, 0]) == 0.5 +try: + gpu.CudaFingerprintSimilarity(GetMorganGenerator()).matrix([s]) +except ImportError as exc: + assert 'chemap' in str(exc) +else: + raise AssertionError('missing optional dependency') +""" + env = {**os.environ, "CUDA_VISIBLE_DEVICES": ""} + env.pop("NUMBA_ENABLE_CUDASIM", None) + subprocess.run([sys.executable, "-c", code], env=env, check=True) + + +@pytest.mark.github_ci +def test_sample_helpers(tmp_path, monkeypatch, mgf): + monkeypatch.chdir(tmp_path) + payload = mgf.read_bytes() + calls = [] + + class Response: + def __enter__(self): + return self + + def __exit__(self, *exc): + pass + + def raise_for_status(self): + pass + + def iter_content(self, chunk_size): + yield payload[:8] + if len(calls) == 1: + raise ConnectionError("interrupted download") + yield payload[8:] + + def get(url, **kwargs): + calls.append(url) + return Response() + + monkeypatch.setattr("simms.utils.requests.get", get) + with pytest.raises(ConnectionError): + download("pesticides.mgf") + assert not list((tmp_path / "data/downloads").iterdir()) + path = download("pesticides.mgf") + assert download("pesticides.mgf") == path and len(calls) == 2 + assert len(list(load_from_mgf(path))) == 3 + assert process_spectrum(next(load_from_mgf(path))) is None + result = process_spectrum(spectrum([1, 20, 30, 40, 50, 60, 1100])) + np.testing.assert_array_equal(result.peaks.mz, [20, 30, 40, 50, 60]) + assert result.peaks.intensities.max() == 1 + + +@pytest.mark.github_ci +@pytest.mark.parametrize("cls", METHODS) +def test_configuration_with_numpy_parameters(cls): + kwargs = parameters(cls) + if cls is gpu.CudaFingerprintSimilarity: + kwargs.update(folded_weights=np.arange(64, dtype=np.float32), count=np.bool_(True)) + elif cls is gpu.CudaBinnedEmbeddingSimilarity: + kwargs["bin_width"] = np.float32(0.5) + else: + kwargs["noise_cutoff"] = np.float32(0.01) + sim = cls(**kwargs) + config = json.loads(json.dumps(sim.to_dict())) + del config["__Similarity__"] + restored = cls(**config) + rows = [spectrum([50]), spectrum([50, 77], compound=1)] + assert_scores_equal(restored.matrix(rows), sim.matrix(rows), atol=0) + + +@pytest.mark.github_ci +@pytest.mark.parametrize("count", [False, True]) +def test_unfolded_fingerprint_scores(count): + pytest.importorskip("chemap") + from rdkit import Chem + + gen = GetMorganGenerator(radius=2) + kwargs = {"unfolded_weights": {2246728737: np.float32(2.5)}} if count else {} + sim = gpu.CudaFingerprintSimilarity(gen, count=count, folded=False, **kwargs) + config = json.loads(json.dumps(sim.to_dict())) + del config["__Similarity__"] + sim = gpu.CudaFingerprintSimilarity(**config) + rows = [spectrum([50], compound=i) for i in range(3)] + features = [gen.GetSparseCountFingerprint(Chem.MolFromSmiles(smiles)).GetNonzeroElements() + for smiles, _ in CHEMICALS] + ids = sorted(set().union(*features)) + vectors = np.array([[row.get(i, 0) for i in ids] for row in features]) + if count: + vectors = vectors * [kwargs["unfolded_weights"].get(i, 1.) for i in ids] + else: + vectors = vectors.astype(bool) + expected = np.minimum(vectors[:, None], vectors).sum(axis=2) / np.maximum(vectors[:, None], vectors).sum(axis=2) + np.testing.assert_allclose(sim.matrix(iter(rows)).to_array(), expected) + np.testing.assert_allclose(sim.sparse_matrix(iter(rows[:2]), iter(rows[1:])).to_array(), expected[:2, 1:]) + assert sim.matrix([], rows).shape == (0, 3) + + +@pytest.mark.github_ci +def test_nonfingerprint_scores_without_chemap(): + code = """ +import sys +sys.modules["chemap"] = None +import simms +import simms.similarity as gpu +import numpy as np +from matchms import Spectrum +s = Spectrum(np.array([1.]), np.array([1.]), {"precursor_mz": 100.}) +for name in gpu.__all__: + if name not in ("CudaFingerprintSimilarity", "CudaModifiedCosine"): + scores = getattr(gpu, name)().matrix(iter([s]), progress_bar=False) + assert scores.to_array("score").item() == 1., name +""" + subprocess.run([sys.executable, "-c", code], check=True) diff --git a/tests/stress/test_stress.py b/tests/stress/test_stress.py index ca45dbb..c6708ec 100644 --- a/tests/stress/test_stress.py +++ b/tests/stress/test_stress.py @@ -1,130 +1,38 @@ -from typing import Type import numpy as np import pytest from matchms.filtering import reduce_to_number_of_peaks -from matchms.similarity import CosineGreedy, ModifiedCosine -from matchms.similarity.BaseSimilarity import BaseSimilarity -from sparsestack import StackedSparseArray -from simms.similarity import CudaCosineGreedy, CudaModifiedCosine +from matchms.similarity import CosineGreedy, ModifiedCosineGreedy +from simms.similarity import CudaCosineGreedy, CudaModifiedCosineGreedy +from tests.utils import assert_scores_equal -def trimmed_spectra(gnps, n_max_peaks): - spectra = [reduce_to_number_of_peaks(sp, n_max=n_max_peaks) for sp in gnps] - spectra = [sp for sp in spectra if sp is not None] - return spectra - -@pytest.mark.parametrize( - "array_type", - [ - "sparse", - "numpy", - ], -) +@pytest.mark.parametrize("sparse", [False, True]) @pytest.mark.parametrize( - "Similarity, CudaSimilarity", + "oracle,method", [ - [CosineGreedy, CudaCosineGreedy], - [ModifiedCosine, CudaModifiedCosine], + (CosineGreedy, CudaCosineGreedy), + (ModifiedCosineGreedy, CudaModifiedCosineGreedy), ], ) -@pytest.mark.parametrize( - "reference_size, query_size", - [ - [64, 128], # large data - [16, 32], # small data - ], -) -@pytest.mark.parametrize( - "tolerance, batch_size, n_max_peaks, match_limit, mz_power, intensity_power", - [ - ( - 0.1, - 64, - 1024, - 1024, - 0, - 1, - ), # batch smaller than data - ], -) -def test_stress( - Similarity: Type[BaseSimilarity], - CudaSimilarity: Type[BaseSimilarity], - gnps: list, - reference_size: int, - query_size: int, - tolerance: float, - batch_size: int, - n_max_peaks: int, - match_limit: int, - mz_power: float, - intensity_power: float, - array_type: str, -): - spectra = trimmed_spectra(tuple(gnps[: reference_size + query_size]), n_max_peaks) - references, queries = spectra[:reference_size], spectra[reference_size:] - - kernel: BaseSimilarity = Similarity( - tolerance=tolerance, - mz_power=mz_power, - intensity_power=intensity_power, - ) - target = kernel.matrix(references, queries) - - kernel: BaseSimilarity = CudaSimilarity( - mz_power=mz_power, - intensity_power=intensity_power, - tolerance=tolerance, - batch_size=batch_size, - n_max_peaks=n_max_peaks, - match_limit=match_limit, - sparse_threshold=0.1, - verbose=False, - ) - - if array_type == "sparse": - result: StackedSparseArray = kernel.matrix( - references, queries, array_type=array_type - ) - assert isinstance(result, StackedSparseArray) - result = result.to_array() - - score = result["sparse_score"] - matches = result["sparse_matches"] - overflow = result["sparse_overflow"] - - mask = target["score"] > 0.1 - - equals = np.isclose(target["score"] * mask, score * mask, atol=1e-3) - assert equals.mean() > 0.999 - # not_filtered = result_target['score'] > .1 # Not matching sub-threshold scores - # mask = (~overflow) & not_filtered - # equals = np.isclose(result_target['score'], result['sparse_score'], atol=1e-3) | mask - match_equals = np.isclose(matches, result["sparse_matches"]) | mask - equals_except_overflows = equals | overflow - match_equals_except_overflows = match_equals | overflow - overflow_rate = overflow.mean() - overflow_num = overflow.sum() +@pytest.mark.parametrize("nr,nq", [(64, 128), (16, 32)]) +def test_stress(gnps, oracle, method, nr, nq, sparse): + rows = [reduce_to_number_of_peaks(s, n_max=1024) for s in gnps[: nr + nq]] + refs, queries = rows[:nr], rows[nr:] + cpu = oracle(tolerance=0.1) + gpu = method(tolerance=0.1, batch_size=32, match_limit=1024) + if sparse: + + def keep(s): + return s["score"] > 0.1 + + actual = gpu.sparse_matrix(refs, queries, score_filter=keep) + expected = cpu.sparse_matrix(refs, queries, score_filter=keep) + assert actual.to_coo("score").nnz > 0 + assert_scores_equal(actual, expected) else: - result: np.ndarray = kernel.matrix(references, queries, array_type=array_type) - assert isinstance(result, np.ndarray) - equals = np.isclose(target["score"], result["score"], atol=1e-3) - match_equals = np.isclose(target["matches"], result["matches"]) - equals_except_overflows = equals | result["overflow"] - match_equals_except_overflows = match_equals | result["overflow"] - overflow_rate = result["overflow"].mean() - overflow_num = result["overflow"].sum() - - # Calculate accuracy rates and overflow statistics - accuracy_rate = equals_except_overflows.mean() - inaccuracy_num = (1 - equals_except_overflows).sum() - match_accuracy_rate = match_equals_except_overflows.mean() - match_inaccuracy_num = (1 - match_equals_except_overflows).sum() - - report = f""" - accuracy={accuracy_rate:.7f}, num incorrect {inaccuracy_num} - match_acc={match_accuracy_rate:.7f}, num incorrect {match_inaccuracy_num} - overflow={overflow_rate:.7f}, num overflow {overflow_num} - """ - assert accuracy_rate > 0.999, report + expected = cpu.matrix(refs, queries) + actual = gpu.matrix(refs, queries, array_type="numpy") + assert actual.shape == expected.shape == (nr, nq) + np.testing.assert_allclose(actual["score"], expected.to_array("score"), rtol=0, atol=1e-12) + np.testing.assert_array_equal(actual["matches"], expected.to_array("matches")) diff --git a/tests/usecase/test_faq.py b/tests/usecase/test_faq.py index 6fb1c26..0e018d6 100644 --- a/tests/usecase/test_faq.py +++ b/tests/usecase/test_faq.py @@ -1,25 +1,22 @@ -from simms.similarity import CudaCosineGreedy -from simms.utils import get_correct_scores -from matchms import Spectrum -from matchms.similarity import CosineGreedy -from typing import List -import pytest import numpy as np +import pytest +from matchms.similarity import CosineGreedy +from scipy.sparse import coo_array +from simms.similarity import CudaCosineGreedy -def test_unpacking_sparse_scores_works( - gnps: List[Spectrum], -): - np.random.seed(42) - references = np.random.choice(gnps, 100) - queries = np.random.choice(gnps, 150) - - scores = CudaCosineGreedy( - sparse_threshold=.75 - ).matrix(references,queries, array_type='sparse') - - # CASE 1 - assert np.allclose(scores.to_array().shape, [100,150]) - assert all(scores.data['sparse_score'] >= .75) # ref ID, query ID, - assert len(scores.data['sparse_matches']) == len(scores.data['sparse_score']) # ref ID, query ID, matches +@pytest.mark.github_ci +def test_unpacking_sparse_scores_works(pesticides): + refs, queries = pesticides[:4], pesticides[2:7] + result = CudaCosineGreedy().sparse_matrix(refs, queries, score_filter=lambda s: s["score"] >= 0.75) + scores, matches = result.to_coo("score"), result.to_coo("matches") + assert isinstance(scores, coo_array) and isinstance(matches, coo_array) + assert scores.shape == (4, 5) and scores.nnz > 0 + np.testing.assert_array_equal(matches.row, scores.row) + np.testing.assert_array_equal(matches.col, scores.col) + expected = CosineGreedy().matrix(refs, queries) + coords = scores.row, scores.col + assert scores.nnz == np.count_nonzero(expected.to_array("score") >= 0.75) + np.testing.assert_allclose(scores.data, expected.to_array("score")[coords], rtol=0, atol=1e-12) + np.testing.assert_array_equal(matches.data, expected.to_array("matches")[coords]) diff --git a/tests/usecase/test_sparsity.py b/tests/usecase/test_sparsity.py index c09a207..7b276af 100644 --- a/tests/usecase/test_sparsity.py +++ b/tests/usecase/test_sparsity.py @@ -1,54 +1,14 @@ -import numpy as np -from matchms import calculate_scores -from simms.similarity import CudaCosineGreedy -from ..utils import get_expected_cosine_greedy_score - +from matchms import Scores, calculate_scores +from matchms.similarity import CosineGreedy -def test_sparse_calculate_scores( - gnps: list, -): - batch_size = 512 - match_limit = 1024 - sparse_threshold = 0.75 +from simms.similarity import CudaCosineGreedy +from tests.utils import assert_scores_equal - r = gnps[:batch_size] - q = gnps[:batch_size] - expected_score = get_expected_cosine_greedy_score(r, q) - kernel = CudaCosineGreedy( - batch_size=batch_size, - match_limit=match_limit, - sparse_threshold=sparse_threshold, - verbose=False, +def test_sparse_calculate_scores(gnps): + expected = calculate_scores(gnps, gnps, CosineGreedy()) + expected = expected.filter(expected["score"] >= 0.75) + actual = CudaCosineGreedy(batch_size=128).sparse_matrix( + gnps, gnps, score_filter=lambda s: s["score"] >= 0.75 ) - result = calculate_scores( - references=r, - queries=q, - similarity_function=kernel, - array_type="sparse", - ) - - score = result.to_array("CudaCosineGreedy_sparse_score") - matches = result.to_array("CudaCosineGreedy_sparse_matches") - overflow = result.to_array("CudaCosineGreedy_sparse_overflow") - - is_discarded = expected_score["score"] < sparse_threshold - equals = np.isclose(expected_score["score"], score, atol=0.001) - match_equals = np.isclose(expected_score["matches"], matches) - - equals_except_overflows = equals | is_discarded | overflow - match_equals_except_overflows = match_equals | is_discarded | overflow - - accuracy_rate = equals_except_overflows.mean() - inaccuracy_num = (1 - equals_except_overflows).sum() - match_accuracy_rate = match_equals_except_overflows.mean() - match_inaccuracy_num = (1 - match_equals_except_overflows).sum() - overflow_rate = overflow.mean() - overflow_num = overflow.sum() - - report = f""" - accuracy={accuracy_rate:.7f}, num incorrect {inaccuracy_num} - match_acc={match_accuracy_rate:.7f}, num incorrect {match_inaccuracy_num} - overflow={overflow_rate:.7f}, num overflow {overflow_num} - """ - assert accuracy_rate > 0.999 and match_accuracy_rate > 0.999, f"{report}" + assert_scores_equal(actual, Scores({field: expected.to_coo(field) for field in expected.score_fields})) diff --git a/tests/usecase/test_tutorial_pesticide.py b/tests/usecase/test_tutorial_pesticide.py index 8ed7966..d1f9a52 100644 --- a/tests/usecase/test_tutorial_pesticide.py +++ b/tests/usecase/test_tutorial_pesticide.py @@ -1,97 +1,23 @@ -from pathlib import Path import numpy as np from matchms import calculate_scores -from matchms.filtering import ( - default_filters, - normalize_intensities, - reduce_to_number_of_peaks, -) -from matchms.importing import load_from_mgf +from matchms.filtering import default_filters, normalize_intensities, reduce_to_number_of_peaks from matchms.similarity import CosineGreedy -from numba import cuda -from simms.similarity import CudaCosineGreedy -from simms.utils import download - - -def test_tutorial_pesticide(): - pest_file = download("pesticides.mgf") - assert isinstance(pest_file, str), "Don't use strings for downloader" - - file = list(load_from_mgf(str(pest_file))) - # Apply filters to clean and enhance each spectrum - spectrums = [] - - for spectrum in file: - # Apply default filter to standardize ion mode, correct charge and more. - # Default filter is fully explained at https://matchms.readthedocs.io/en/latest/api/matchms.filtering.html . - spectrum = default_filters(spectrum) - # Scale peak intensities to maximum of 1 - spectrum = normalize_intensities(spectrum) - spectrums.append(spectrum) - - scores = calculate_scores( - references=spectrums, - queries=spectrums, - similarity_function=CosineGreedy(), - is_symmetric=True, - ) - - # Matchms allows to get the best matches for any query using scores_by_query - query = spectrums[15] # just an example - best_matches = scores.scores_by_query(query, "CosineGreedy_score", sort=True) - # It is necessary to make sure that the number of peaks are reasonable - - MAX_PEAKS = 1024 - - def process_spectrum(spectrum: np.ndarray) -> np.ndarray: - # spectrum = select_by_mz(spectrum, mz_from=10.0, mz_to=1000.0) - # spectrum = normalize_intensities(spectrum) - # spectrum = select_by_relative_intensity(spectrum, intensity_from=0.001) - # spectrum = reduce_to_number_of_peaks(spectrum, n_max=1000) - spectrum = reduce_to_number_of_peaks(spectrum, n_max=MAX_PEAKS) - # spectrum = require_minimum_number_of_peaks(spectrum, n_required=5) - return spectrum - - f_specs = [process_spectrum(s) for s in spectrums] - scores_cu = calculate_scores( - references=f_specs, - queries=f_specs, - similarity_function=CudaCosineGreedy(batch_size=512), - ) - # This computed all-vs-all similarity scores, the array of which can be accessed as scores.scores - print(f"Size of matrix of computed similarities: {scores_cu.scores.shape}") - - # Matchms allows to get the best matches for any query using scores_by_query - query = spectrums[15] # just an example - best_matches_cu = scores_cu.scores_by_query( - query, "CudaCosineGreedy_score", sort=True - ) - - # Print the calculated scores_cu for each spectrum pair - for reference, (score, matches, overflow) in best_matches_cu[:10]: - # Ignore scores_cu between same spectrum - if reference != query: - print(f"Reference scan id: {reference.metadata['scans']}") - print(f"Query scan id: {query.metadata['scans']}") - print(f"Score: {score:.4f}") - print(f"Number of matching peaks: {matches}") - print(f"Did GPU overflow at this pair: {overflow}") - print("----------------------------") - - for a, b in zip(best_matches[:20], best_matches_cu[:20]): - reference, (score_a, matches_a) = a - reference, (score_b, matches_b, overflow_b) = b - if reference != query: - # If we didn't overflow - if not overflow_b: - assert np.isclose(score_a, score_b), ("score error", score_a, score_b) - assert np.isclose(matches_a, matches_b), ( - "match error", - matches_a, - matches_b, - ) - # If overflow, score must be leq - else: - assert score_a >= score_b - assert matches_a >= matches_b +from simms.similarity import CudaCosineGreedy +from tests.utils import assert_scores_equal + + +def test_tutorial_pesticide(pesticides): + spectra = [ + reduce_to_number_of_peaks(normalize_intensities(default_filters(s)), n_max=1024) for s in pesticides + ] + expected = calculate_scores(spectra, None, CosineGreedy()) + actual = calculate_scores(spectra, None, CudaCosineGreedy(batch_size=32)) + assert_scores_equal(actual, expected) + query = 15 + cpu_column, gpu_column = [r.to_array("score")[:, query] for r in (expected, actual)] + cpu_order = np.argsort(-cpu_column, kind="stable") + gpu_order = np.argsort(-gpu_column, kind="stable") + cpu_refs = [spectra[i].get("spectrum_id") for i in cpu_order if i != query] + gpu_refs = [spectra[i].get("spectrum_id") for i in gpu_order if i != query] + assert all(cpu_refs) and gpu_refs[:20] == cpu_refs[:20] diff --git a/tests/usecase/test_tutorial_readme_sample.py b/tests/usecase/test_tutorial_readme_sample.py index 796f1fd..8f07dae 100644 --- a/tests/usecase/test_tutorial_readme_sample.py +++ b/tests/usecase/test_tutorial_readme_sample.py @@ -1,67 +1,20 @@ -from pathlib import Path import numpy as np -from matchms import calculate_scores -from matchms.filtering import ( - default_filters, - normalize_intensities, - reduce_to_number_of_peaks, -) -from matchms.importing import load_from_mgf +import pytest +from matchms import SpectraCollection, calculate_scores from matchms.similarity import CosineGreedy -from numba import cuda -from simms.similarity import CudaCosineGreedy -from simms.utils import download - - -def readme_fn(): - from matchms import calculate_scores - from matchms.importing import load_from_mgf - from simms.similarity import ( - CudaCosineGreedy, - CudaFingerprintSimilarity, - CudaModifiedCosine, - ) - from simms.utils import download - - sample_file = download("pesticides.mgf") - references = list(load_from_mgf(sample_file)) - queries = list(load_from_mgf(sample_file)) - - similarity_function = CudaCosineGreedy() - - scores = calculate_scores( - references=references, - queries=queries, - similarity_function=similarity_function, - ) - - scores.scores_by_query(queries[42], "CudaCosineGreedy_score", sort=True) - return scores - -def test_readme_not_fail(): - readme_fn() - - -def test_readme_correct(): - - scores_cu = readme_fn() - - from matchms import calculate_scores - from matchms.importing import load_from_mgf - from matchms.similarity import CosineGreedy - from simms.utils import download - - sample_file = download("pesticides.mgf") # Download sample file - references = list(load_from_mgf(sample_file)) # Read using MatchMS - queries = list(load_from_mgf(sample_file)) - - scores = calculate_scores( - references=references, - queries=queries, - similarity_function=CosineGreedy(), - ) - assert np.isclose( - scores._scores["CosineGreedy_score"], - scores_cu._scores["CudaCosineGreedy_score"], - ).all() +from simms import PeakArrays +from simms.similarity import CudaCosineGreedy +from tests.utils import assert_scores_equal + + +@pytest.mark.github_ci +def test_readme_quickstart(pesticides): + refs, queries = SpectraCollection(pesticides[:4]), SpectraCollection(pesticides[2:5]) + sim = CudaCosineGreedy() + actual = calculate_scores(refs, queries, sim) + expected = calculate_scores(list(refs), list(queries), CosineGreedy()) + assert_scores_equal(actual, expected) + tensor = sim.matrix(PeakArrays.from_spectra(refs), PeakArrays.from_spectra(queries), array_type="torch") + np.testing.assert_array_equal(tensor[0].cpu(), expected.to_array("score")) + np.testing.assert_array_equal(tensor[1].cpu(), expected.to_array("matches")) diff --git a/tests/utils.py b/tests/utils.py index 5fd689d..69d4f06 100644 --- a/tests/utils.py +++ b/tests/utils.py @@ -1,37 +1,23 @@ -import warnings -from typing import Type import numpy as np -import pytest -from joblib import Memory - - -memory = Memory(location="cache") - - -@memory.cache -def get_expected_cosine_greedy_score( - references: tuple, - queries: tuple, - **kwargs, -) -> np.ndarray: - from matchms.similarity import CosineGreedy - - return CosineGreedy(**kwargs).matrix( - references=references, - queries=queries, - ) - - -@memory.cache(verbose=0) -def get_expected_score( - method: Type, - references: tuple, - queries: tuple, - **kwargs, -) -> np.ndarray: - from matchms.similarity import CosineGreedy - - return method(**kwargs).matrix( - references=references, - queries=queries, - ) +from matchms import Scores + + +def assert_scores_equal(actual, expected, atol=1e-12): + """Check every score and every integer count, including sparse coordinates.""" + assert isinstance(actual, Scores) and isinstance(expected, Scores) + assert actual.shape == expected.shape + assert actual.score_fields == expected.score_fields + assert actual.is_sparse == expected.is_sparse + for field in expected.score_fields: + if expected.is_sparse: + a, b = actual.to_coo(field), expected.to_coo(field) + ia, ib = np.lexsort((a.col, a.row)), np.lexsort((b.col, b.row)) + np.testing.assert_array_equal(a.row[ia], b.row[ib]) + np.testing.assert_array_equal(a.col[ia], b.col[ib]) + x, y = a.data[ia], b.data[ib] + else: + x, y = actual.to_array(field), expected.to_array(field) + if field == "matches": + np.testing.assert_array_equal(x, y) + else: + np.testing.assert_allclose(x, y, atol=atol, rtol=0)