simms-gpu 1.1.0__tar.gz → 1.2.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {simms_gpu-1.1.0 → simms_gpu-1.2.0}/PKG-INFO +8 -8
- {simms_gpu-1.1.0 → simms_gpu-1.2.0}/README.md +7 -7
- {simms_gpu-1.1.0 → simms_gpu-1.2.0}/pyproject.toml +1 -1
- simms_gpu-1.2.0/simms/__version__.py +1 -0
- {simms_gpu-1.1.0 → simms_gpu-1.2.0}/simms/molecules.py +1 -1
- simms_gpu-1.2.0/simms/similarity/CudaMyopicMCES.py +247 -0
- simms_gpu-1.2.0/simms/similarity/_mces_engine.py +120 -0
- simms_gpu-1.2.0/simms/similarity/_mces_milp.py +132 -0
- simms_gpu-1.2.0/simms/similarity/_mces_model.py +151 -0
- simms_gpu-1.2.0/simms/similarity/_mces_pdhg.py +310 -0
- simms_gpu-1.2.0/simms/similarity/_mces_search.py +439 -0
- {simms_gpu-1.1.0 → simms_gpu-1.2.0}/simms/similarity/spectrum_similarity_functions.py +1 -1
- simms_gpu-1.1.0/simms/__version__.py +0 -1
- simms_gpu-1.1.0/simms/similarity/CudaMyopicMCES.py +0 -308
- simms_gpu-1.1.0/simms/similarity/_mces_milp.py +0 -79
- simms_gpu-1.1.0/simms/similarity/_mces_search.py +0 -439
- {simms_gpu-1.1.0 → simms_gpu-1.2.0}/LICENSE +0 -0
- {simms_gpu-1.1.0 → simms_gpu-1.2.0}/simms/__init__.py +0 -0
- {simms_gpu-1.1.0 → simms_gpu-1.2.0}/simms/peaks.py +0 -0
- {simms_gpu-1.1.0 → simms_gpu-1.2.0}/simms/similarity/CudaBinnedEmbeddingSimilarity.py +0 -0
- {simms_gpu-1.1.0 → simms_gpu-1.2.0}/simms/similarity/CudaCosineGreedy.py +0 -0
- {simms_gpu-1.1.0 → simms_gpu-1.2.0}/simms/similarity/CudaCosineLinear.py +0 -0
- {simms_gpu-1.1.0 → simms_gpu-1.2.0}/simms/similarity/CudaEntropyGreedy.py +0 -0
- {simms_gpu-1.1.0 → simms_gpu-1.2.0}/simms/similarity/CudaFingerprintSimilarity.py +0 -0
- {simms_gpu-1.1.0 → simms_gpu-1.2.0}/simms/similarity/CudaModifiedCosine.py +0 -0
- {simms_gpu-1.1.0 → simms_gpu-1.2.0}/simms/similarity/CudaNeutralLossesCosine.py +0 -0
- {simms_gpu-1.1.0 → simms_gpu-1.2.0}/simms/similarity/CudaTransitiveAlignment.py +0 -0
- {simms_gpu-1.1.0 → simms_gpu-1.2.0}/simms/similarity/__init__.py +0 -0
- {simms_gpu-1.1.0 → simms_gpu-1.2.0}/simms/similarity/_base.py +0 -0
- {simms_gpu-1.1.0 → simms_gpu-1.2.0}/simms/similarity/_transitive_peaks.py +0 -0
- {simms_gpu-1.1.0 → simms_gpu-1.2.0}/simms/similarity/vector_similarity_functions.py +0 -0
- {simms_gpu-1.1.0 → simms_gpu-1.2.0}/simms/utils.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: simms-gpu
|
|
3
|
-
Version: 1.
|
|
3
|
+
Version: 1.2.0
|
|
4
4
|
Summary: Faster Similarity for Mass Spec on GPU
|
|
5
5
|
License-Expression: MIT
|
|
6
6
|
License-File: LICENSE
|
|
@@ -42,7 +42,7 @@ SimMS compares tandem mass spectra on an NVIDIA GPU using the scoring algorithms
|
|
|
42
42
|
|
|
43
43
|
## Installation
|
|
44
44
|
|
|
45
|
-
The PyPI distribution is `simms-gpu`. Import it in Python as `simms`. Use Python 3.11 through 3.14
|
|
45
|
+
The PyPI distribution is `simms-gpu`. Import it in Python as `simms`. Use Python 3.11 through 3.14. GPU scoring requires an NVIDIA driver and a CUDA-enabled build of PyTorch for the chosen runtime. For CPU molecular scoring, install the base package and select `backend="cpu"`. Choose the matching wheel with the [PyTorch installation selector](https://pytorch.org/get-started/locally/).
|
|
46
46
|
|
|
47
47
|
```bash
|
|
48
48
|
# CUDA 12, in an environment with a matching CUDA 12 PyTorch build
|
|
@@ -106,7 +106,7 @@ The default cosine tensor has shape `(2, n_refs, n_queries)`, with score and mat
|
|
|
106
106
|
| `CudaModifiedCosineLinear` | `ModifiedCosineLinear` | Linear matching with a precursor shift and conflict resolution |
|
|
107
107
|
| `CudaBinnedEmbeddingSimilarity` | `BinnedEmbeddingSimilarity` | Cosine or Euclidean similarity of binned intensities |
|
|
108
108
|
| `CudaFingerprintSimilarity` | `FingerprintSimilarity` | Tanimoto or cosine over molecular fingerprints |
|
|
109
|
-
| `CudaMyopicMCES` | `myopic-mces` (`MCES`) | Exact thresholded or unrestricted Myopic MCES molecular distance (
|
|
109
|
+
| `CudaMyopicMCES` | `myopic-mces` (`MCES`) | Exact thresholded or unrestricted Myopic MCES molecular distance (Numba CPU or CUDA, with SciPy HiGHS fallback) |
|
|
110
110
|
|
|
111
111
|
`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.
|
|
112
112
|
|
|
@@ -114,7 +114,9 @@ Binned embeddings and precomputed fingerprints also run on CPU. The six spectral
|
|
|
114
114
|
|
|
115
115
|
## Myopic MCES (`CudaMyopicMCES`)
|
|
116
116
|
|
|
117
|
-
`CudaMyopicMCES` computes
|
|
117
|
+
`CudaMyopicMCES` computes weighted molecular common-edge distances on CUDA (default) or a multicore CPU. Use `backend="auto"` to select an available device. All three modes accept the same prepared graphs, spectra, SMILES, and RDKit molecules. The package ships one pure-Python wheel. Numba compiles the kernels at runtime.
|
|
118
|
+
|
|
119
|
+
A finite threshold includes exact hits at the boundary. Use `exact_only=True` for hit retrieval. With the default `always_stronger_bound=True`, dense scores retain upstream's neighborhood bound (`filter2`) when it exceeds the threshold. Other rejections return the threshold with `exact=False`. With `always_stronger_bound=False`, every rejection returns that capped score. Set `threshold=None` for unrestricted exact distances.
|
|
118
120
|
|
|
119
121
|
```python
|
|
120
122
|
from simms import MolecularGraphs
|
|
@@ -126,11 +128,9 @@ scores = mces.matrix(graphs)
|
|
|
126
128
|
close_pairs = mces.sparse_matrix(graphs, max_distance=10.0, exact_only=True)
|
|
127
129
|
```
|
|
128
130
|
|
|
129
|
-
|
|
131
|
+
Exact-hit queries start with a histogram screen. A Hungarian assignment, local swaps and capped graph search resolve easy pairs. The remaining pairs use a primal-dual relaxation, integer certificates and an oriented-edge HiGHS fallback. `max_frames` defaults to 8,192. Models above `max_gpu_atoms` use CPU refinement. With `backend="cpu"`, Torch output is a CPU tensor.
|
|
130
132
|
|
|
131
|
-
|
|
132
|
-
- **120 `filter2` survivors (`threshold=10`):** `444 ms` (`4.24×` vs 8-core upstream HiGHS, `24.9×` vs 8-core CBC)
|
|
133
|
-
- *(Honest baseline note: an 8-core Numba CPU port of the same graph-native algorithm ran `1.1×–3.6×` faster than Numba CUDA on these 120–1,000 pair laptop batches, showing that most of the speedup over upstream `myopic-mces` comes from replacing generic MILP setup with compact integer graph bounds + in-process HiGHS fallback.)*
|
|
133
|
+
On one million prepared GNPS pairs at threshold 10, warm exact-hit retrieval took **4.62 s on CUDA** and **11.01 s on CPU**. Both returned all 11,245 reference hits with identical distances. Dense scoring took 7.82 s and 13.22 s, respectively, and matched every reference score and exact flag. These are three-run medians on an RTX 4060 Laptop GPU and eight i9-14900HX P-cores. [Benchmark results](benchmarks/myopic_mces_v1_2_rtx4060.json) · [Benchmark script](benchmarks/benchmark_mces_matrix.py)
|
|
134
134
|
|
|
135
135
|
## Transitive alignment
|
|
136
136
|
|
|
@@ -4,7 +4,7 @@ SimMS compares tandem mass spectra on an NVIDIA GPU using the scoring algorithms
|
|
|
4
4
|
|
|
5
5
|
## Installation
|
|
6
6
|
|
|
7
|
-
The PyPI distribution is `simms-gpu`. Import it in Python as `simms`. Use Python 3.11 through 3.14
|
|
7
|
+
The PyPI distribution is `simms-gpu`. Import it in Python as `simms`. Use Python 3.11 through 3.14. GPU scoring requires an NVIDIA driver and a CUDA-enabled build of PyTorch for the chosen runtime. For CPU molecular scoring, install the base package and select `backend="cpu"`. Choose the matching wheel with the [PyTorch installation selector](https://pytorch.org/get-started/locally/).
|
|
8
8
|
|
|
9
9
|
```bash
|
|
10
10
|
# CUDA 12, in an environment with a matching CUDA 12 PyTorch build
|
|
@@ -68,7 +68,7 @@ The default cosine tensor has shape `(2, n_refs, n_queries)`, with score and mat
|
|
|
68
68
|
| `CudaModifiedCosineLinear` | `ModifiedCosineLinear` | Linear matching with a precursor shift and conflict resolution |
|
|
69
69
|
| `CudaBinnedEmbeddingSimilarity` | `BinnedEmbeddingSimilarity` | Cosine or Euclidean similarity of binned intensities |
|
|
70
70
|
| `CudaFingerprintSimilarity` | `FingerprintSimilarity` | Tanimoto or cosine over molecular fingerprints |
|
|
71
|
-
| `CudaMyopicMCES` | `myopic-mces` (`MCES`) | Exact thresholded or unrestricted Myopic MCES molecular distance (
|
|
71
|
+
| `CudaMyopicMCES` | `myopic-mces` (`MCES`) | Exact thresholded or unrestricted Myopic MCES molecular distance (Numba CPU or CUDA, with SciPy HiGHS fallback) |
|
|
72
72
|
|
|
73
73
|
`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.
|
|
74
74
|
|
|
@@ -76,7 +76,9 @@ Binned embeddings and precomputed fingerprints also run on CPU. The six spectral
|
|
|
76
76
|
|
|
77
77
|
## Myopic MCES (`CudaMyopicMCES`)
|
|
78
78
|
|
|
79
|
-
`CudaMyopicMCES` computes
|
|
79
|
+
`CudaMyopicMCES` computes weighted molecular common-edge distances on CUDA (default) or a multicore CPU. Use `backend="auto"` to select an available device. All three modes accept the same prepared graphs, spectra, SMILES, and RDKit molecules. The package ships one pure-Python wheel. Numba compiles the kernels at runtime.
|
|
80
|
+
|
|
81
|
+
A finite threshold includes exact hits at the boundary. Use `exact_only=True` for hit retrieval. With the default `always_stronger_bound=True`, dense scores retain upstream's neighborhood bound (`filter2`) when it exceeds the threshold. Other rejections return the threshold with `exact=False`. With `always_stronger_bound=False`, every rejection returns that capped score. Set `threshold=None` for unrestricted exact distances.
|
|
80
82
|
|
|
81
83
|
```python
|
|
82
84
|
from simms import MolecularGraphs
|
|
@@ -88,11 +90,9 @@ scores = mces.matrix(graphs)
|
|
|
88
90
|
close_pairs = mces.sparse_matrix(graphs, max_distance=10.0, exact_only=True)
|
|
89
91
|
```
|
|
90
92
|
|
|
91
|
-
|
|
93
|
+
Exact-hit queries start with a histogram screen. A Hungarian assignment, local swaps and capped graph search resolve easy pairs. The remaining pairs use a primal-dual relaxation, integer certificates and an oriented-edge HiGHS fallback. `max_frames` defaults to 8,192. Models above `max_gpu_atoms` use CPU refinement. With `backend="cpu"`, Torch output is a CPU tensor.
|
|
92
94
|
|
|
93
|
-
|
|
94
|
-
- **120 `filter2` survivors (`threshold=10`):** `444 ms` (`4.24×` vs 8-core upstream HiGHS, `24.9×` vs 8-core CBC)
|
|
95
|
-
- *(Honest baseline note: an 8-core Numba CPU port of the same graph-native algorithm ran `1.1×–3.6×` faster than Numba CUDA on these 120–1,000 pair laptop batches, showing that most of the speedup over upstream `myopic-mces` comes from replacing generic MILP setup with compact integer graph bounds + in-process HiGHS fallback.)*
|
|
95
|
+
On one million prepared GNPS pairs at threshold 10, warm exact-hit retrieval took **4.62 s on CUDA** and **11.01 s on CPU**. Both returned all 11,245 reference hits with identical distances. Dense scoring took 7.82 s and 13.22 s, respectively, and matched every reference score and exact flag. These are three-run medians on an RTX 4060 Laptop GPU and eight i9-14900HX P-cores. [Benchmark results](benchmarks/myopic_mces_v1_2_rtx4060.json) · [Benchmark script](benchmarks/benchmark_mces_matrix.py)
|
|
96
96
|
|
|
97
97
|
## Transitive alignment
|
|
98
98
|
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "1.2.0"
|
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT
|
|
2
|
+
"""Thresholded weighted molecular common-edge distances on CUDA and CPU."""
|
|
3
|
+
from collections import defaultdict
|
|
4
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
5
|
+
from operator import index
|
|
6
|
+
|
|
7
|
+
import numpy as np
|
|
8
|
+
import torch
|
|
9
|
+
from matchms import Scores
|
|
10
|
+
from numba import cuda
|
|
11
|
+
from scipy.sparse import coo_array
|
|
12
|
+
from tqdm import tqdm
|
|
13
|
+
|
|
14
|
+
from ..molecules import MolecularGraphs
|
|
15
|
+
from ..utils import get_device
|
|
16
|
+
from ._base import CudaSimilarity
|
|
17
|
+
from ._mces_engine import Engine
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _library(left, right):
|
|
21
|
+
graphs, keys = [], {}
|
|
22
|
+
|
|
23
|
+
def groups(container):
|
|
24
|
+
ids = []
|
|
25
|
+
for graph in container.graphs:
|
|
26
|
+
if graph.key not in keys:
|
|
27
|
+
keys[graph.key] = len(graphs)
|
|
28
|
+
graphs.append(graph)
|
|
29
|
+
ids.append(keys[graph.key])
|
|
30
|
+
remap = np.array(ids + [-1], np.int32)
|
|
31
|
+
axis = remap[container.index]
|
|
32
|
+
grouped = defaultdict(list)
|
|
33
|
+
for i, g in enumerate(axis):
|
|
34
|
+
grouped[int(g)].append(i)
|
|
35
|
+
return axis, grouped
|
|
36
|
+
|
|
37
|
+
a = groups(left)
|
|
38
|
+
b = a if left is right else groups(right)
|
|
39
|
+
return graphs, a, b
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _coordinates(row, col, shape):
|
|
43
|
+
if row is None or col is None:
|
|
44
|
+
raise ValueError("idx_row and idx_col must be given together")
|
|
45
|
+
row, col = np.asarray(row), np.asarray(col)
|
|
46
|
+
if row.ndim != 1 or row.shape != col.shape:
|
|
47
|
+
raise ValueError("idx_row and idx_col must be aligned 1D arrays")
|
|
48
|
+
for axis, size in zip((row, col), shape):
|
|
49
|
+
if axis.size and axis.dtype.kind not in "iu":
|
|
50
|
+
raise TypeError("sparse coordinates must be integers")
|
|
51
|
+
if np.any(axis < 0) or np.any(axis >= size):
|
|
52
|
+
raise ValueError("sparse coordinate out of bounds")
|
|
53
|
+
return zip(row, col)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class _Pairs:
|
|
57
|
+
"""Stream unique compound pairs and expand results back to spectrum coordinates."""
|
|
58
|
+
|
|
59
|
+
def __init__(self, a, b, symmetric, row, col):
|
|
60
|
+
(axis_a, self.left), (axis_b, self.right) = a, b
|
|
61
|
+
self.requested = None
|
|
62
|
+
if row is not None or col is not None:
|
|
63
|
+
self.requested = defaultdict(set)
|
|
64
|
+
for i, j in _coordinates(row, col, (len(axis_a), len(axis_b))):
|
|
65
|
+
key = tuple(sorted((axis_a[i], axis_b[j])))
|
|
66
|
+
self.requested[key].add((i, j))
|
|
67
|
+
if symmetric:
|
|
68
|
+
self.requested[key].add((j, i))
|
|
69
|
+
|
|
70
|
+
def tiles(self, size):
|
|
71
|
+
if self.requested is not None:
|
|
72
|
+
keys = np.asarray(list(self.requested), np.int32).reshape(-1, 2)
|
|
73
|
+
for start in range(0, len(keys), size):
|
|
74
|
+
yield keys[start:start + size].T
|
|
75
|
+
return
|
|
76
|
+
a, b = np.array(list(self.left), np.int32), np.array(list(self.right), np.int32)
|
|
77
|
+
for start in range(0, len(a) * len(b), size):
|
|
78
|
+
idx = np.arange(start, min(start + size, len(a) * len(b)))
|
|
79
|
+
i, j = a[idx // len(b)], b[idx % len(b)]
|
|
80
|
+
keep = (i <= j) | ~np.isin(i, b) | ~np.isin(j, a)
|
|
81
|
+
yield i[keep], j[keep]
|
|
82
|
+
|
|
83
|
+
def locations(self, left, right):
|
|
84
|
+
if self.requested is not None:
|
|
85
|
+
parts = [np.asarray(list(self.requested[i, j]), np.intp) for i, j in zip(left, right)]
|
|
86
|
+
coords = np.concatenate(parts)
|
|
87
|
+
yield coords[:, 0], coords[:, 1], np.repeat(np.arange(len(parts)), [len(p) for p in parts])
|
|
88
|
+
return
|
|
89
|
+
unique = all(len(v) == 1 for v in self.left.values()) and all(len(v) == 1 for v in self.right.values())
|
|
90
|
+
for a, b, reverse in ((left, right, False), (right, left, True)):
|
|
91
|
+
ids = np.arange(len(a))
|
|
92
|
+
if reverse:
|
|
93
|
+
ids = ids[(a != b) & np.isin(a, list(self.left)) & np.isin(b, list(self.right))]
|
|
94
|
+
if not len(ids):
|
|
95
|
+
continue
|
|
96
|
+
if unique:
|
|
97
|
+
# Dense lookup also accommodates the missing-structure sentinel via +1.
|
|
98
|
+
row = np.empty(max(self.left) + 2, np.intp)
|
|
99
|
+
col = np.empty(max(self.right) + 2, np.intp)
|
|
100
|
+
for k, v in self.left.items():
|
|
101
|
+
row[k + 1] = v[0]
|
|
102
|
+
for k, v in self.right.items():
|
|
103
|
+
col[k + 1] = v[0]
|
|
104
|
+
yield row[a[ids] + 1], col[b[ids] + 1], ids
|
|
105
|
+
else:
|
|
106
|
+
for k in ids:
|
|
107
|
+
rows, cols = self.left[a[k]], self.right[b[k]]
|
|
108
|
+
yield np.repeat(rows, len(cols)), np.tile(cols, len(rows)), k
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
class CudaMyopicMCES(CudaSimilarity):
|
|
112
|
+
"""Weighted edge-edit distance under an injective element-preserving atom map.
|
|
113
|
+
|
|
114
|
+
A finite threshold returns exact optima through the threshold (inclusive).
|
|
115
|
+
Above it, score is the neighborhood lower bound if it rejected the pair
|
|
116
|
+
and always_stronger_bound is set, otherwise the threshold. Inspect 'exact'
|
|
117
|
+
to distinguish capped results, especially when filtering at the threshold.
|
|
118
|
+
Set threshold=None for unrestricted exact distances. Torch output planes
|
|
119
|
+
follow score_fields order. Sparse output preserves retained zero distances.
|
|
120
|
+
"""
|
|
121
|
+
|
|
122
|
+
score_datatype = np.dtype([("score", np.float64), ("exact", np.bool_)])
|
|
123
|
+
score_fields = score_datatype.names
|
|
124
|
+
|
|
125
|
+
def __init__(self, threshold: float | None = 10.0, always_stronger_bound: bool = True,
|
|
126
|
+
batch_size: int = 2048, max_frames: int = 8_192, max_gpu_atoms: int = 64,
|
|
127
|
+
n_fallback_workers: int | None = None, backend: str = "cuda"):
|
|
128
|
+
self.threshold = None if threshold is None else float(threshold)
|
|
129
|
+
if threshold is not None and (not np.isfinite(self.threshold) or self.threshold < 0):
|
|
130
|
+
raise ValueError("threshold must be nonnegative and finite, or None")
|
|
131
|
+
self.always_stronger_bound = bool(always_stronger_bound)
|
|
132
|
+
self.batch_size = index(batch_size)
|
|
133
|
+
self.max_frames = index(max_frames)
|
|
134
|
+
self.max_gpu_atoms = index(max_gpu_atoms)
|
|
135
|
+
self.n_fallback_workers = None if n_fallback_workers is None else index(n_fallback_workers)
|
|
136
|
+
if min(self.batch_size, self.max_frames, self.max_gpu_atoms,
|
|
137
|
+
1 if n_fallback_workers is None else self.n_fallback_workers) < 1:
|
|
138
|
+
raise ValueError("batch_size, max_frames, max_gpu_atoms and n_fallback_workers must be positive")
|
|
139
|
+
if backend not in ("cuda", "cpu", "auto"):
|
|
140
|
+
raise ValueError("backend must be 'cuda', 'cpu' or 'auto'")
|
|
141
|
+
self.backend = backend
|
|
142
|
+
self.device = None
|
|
143
|
+
if backend != "cpu" and cuda.is_available():
|
|
144
|
+
try:
|
|
145
|
+
device = get_device(require_cuda=backend == "cuda")
|
|
146
|
+
except RuntimeError:
|
|
147
|
+
if backend == "cuda":
|
|
148
|
+
raise
|
|
149
|
+
device = None
|
|
150
|
+
if device == "cuda" or cuda.config.ENABLE_CUDASIM:
|
|
151
|
+
self.device = device
|
|
152
|
+
if backend == "cuda" and self.device is None:
|
|
153
|
+
raise RuntimeError("MCES requires CUDA or NUMBA_ENABLE_CUDASIM=1")
|
|
154
|
+
|
|
155
|
+
def pair(self, a, b):
|
|
156
|
+
def single(item):
|
|
157
|
+
if isinstance(item, MolecularGraphs):
|
|
158
|
+
if len(item) != 1:
|
|
159
|
+
raise ValueError("pair expects one molecule per input")
|
|
160
|
+
return item
|
|
161
|
+
return [item]
|
|
162
|
+
|
|
163
|
+
return self.matrix(single(a), single(b), array_type="numpy", progress_bar=False).reshape(())
|
|
164
|
+
|
|
165
|
+
def _compute(self, left, right, fields, progress_bar, array_type, row=None, col=None,
|
|
166
|
+
predicate=None, maximum=None, only_exact=False, is_symmetric=False):
|
|
167
|
+
symmetric = right is None
|
|
168
|
+
same = symmetric or left is right
|
|
169
|
+
left = MolecularGraphs.from_spectra(left)
|
|
170
|
+
right = left if same else MolecularGraphs.from_spectra(right)
|
|
171
|
+
shape = (len(left), len(right))
|
|
172
|
+
graphs, a, b = _library(left, right)
|
|
173
|
+
if is_symmetric and not np.array_equal(a[0], b[0]):
|
|
174
|
+
raise ValueError("is_symmetric requires identical molecular axes")
|
|
175
|
+
plan = _Pairs(a, b, symmetric or is_symmetric, row, col)
|
|
176
|
+
dtype = np.dtype([(f, self.score_datatype[f]) for f in fields])
|
|
177
|
+
sparse = array_type == "sparse"
|
|
178
|
+
if sparse:
|
|
179
|
+
chunks = []
|
|
180
|
+
elif array_type == "torch":
|
|
181
|
+
result = torch.empty((len(fields), *shape), dtype=torch.float64, device=self.device or "cpu")
|
|
182
|
+
elif array_type == "scores":
|
|
183
|
+
result = self._create_dense_result(*shape, fields)
|
|
184
|
+
else:
|
|
185
|
+
result = np.empty(shape, dtype)
|
|
186
|
+
fast = self.threshold is not None and (
|
|
187
|
+
only_exact or not self.always_stronger_bound or (maximum is not None and maximum < self.threshold))
|
|
188
|
+
engine = Engine(graphs, self, fast, maximum) if graphs else None
|
|
189
|
+
with ThreadPoolExecutor(self.n_fallback_workers) as pool, tqdm(
|
|
190
|
+
desc="Scoring molecular pairs", unit="pair", disable=not progress_bar
|
|
191
|
+
) as progress:
|
|
192
|
+
for left_ids, right_ids in plan.tiles(min(1 << 20, self.batch_size * 512)):
|
|
193
|
+
if engine is None:
|
|
194
|
+
values, flags = np.full(len(left_ids), np.nan), np.zeros(len(left_ids), bool)
|
|
195
|
+
else:
|
|
196
|
+
values, flags = engine.solve(left_ids, right_ids, pool)
|
|
197
|
+
keep = np.ones(len(values), bool)
|
|
198
|
+
if maximum is not None:
|
|
199
|
+
keep &= values <= maximum
|
|
200
|
+
if only_exact:
|
|
201
|
+
keep &= flags
|
|
202
|
+
ids = np.flatnonzero(keep)
|
|
203
|
+
records = np.empty(len(ids), self.score_datatype)
|
|
204
|
+
records["score"], records["exact"] = values[ids], flags[ids]
|
|
205
|
+
if predicate is not None:
|
|
206
|
+
passed = np.fromiter(map(predicate, records), bool, len(records))
|
|
207
|
+
ids, records = ids[passed], records[passed]
|
|
208
|
+
if len(ids):
|
|
209
|
+
for i, j, k in plan.locations(left_ids[ids], right_ids[ids]):
|
|
210
|
+
if sparse:
|
|
211
|
+
chunks.append((i, j, np.broadcast_to(records[k], i.shape)))
|
|
212
|
+
elif array_type == "torch":
|
|
213
|
+
for plane, field in enumerate(fields):
|
|
214
|
+
data = np.ascontiguousarray(records[field][k])
|
|
215
|
+
result[plane, i, j] = torch.as_tensor(data, device=self.device or "cpu",
|
|
216
|
+
dtype=result.dtype)
|
|
217
|
+
else:
|
|
218
|
+
for field in fields:
|
|
219
|
+
result[field][i, j] = records[field][k]
|
|
220
|
+
progress.update(len(left_ids))
|
|
221
|
+
if sparse:
|
|
222
|
+
if chunks:
|
|
223
|
+
i, j, values = map(np.concatenate, zip(*chunks))
|
|
224
|
+
else:
|
|
225
|
+
i = j = np.empty(0, np.intp)
|
|
226
|
+
values = np.empty(0, self.score_datatype)
|
|
227
|
+
return Scores({f: coo_array((values[f], (i, j)), shape=shape) for f in fields})
|
|
228
|
+
return Scores(result) if array_type == "scores" else result
|
|
229
|
+
|
|
230
|
+
def matrix(self, left, right=None, score_fields=None, progress_bar=True, array_type="scores", *, is_symmetric=False):
|
|
231
|
+
if array_type not in ("scores", "numpy", "torch"):
|
|
232
|
+
raise ValueError("array_type must be 'scores', 'numpy' or 'torch'")
|
|
233
|
+
return self._compute(left, right, self._fields(score_fields), progress_bar, array_type,
|
|
234
|
+
is_symmetric=is_symmetric)
|
|
235
|
+
|
|
236
|
+
def keep_score(self, score):
|
|
237
|
+
"""Retain all requested distances, including exact zeros and missing values."""
|
|
238
|
+
return True
|
|
239
|
+
|
|
240
|
+
def sparse_matrix(self, left, right=None, idx_row=None, idx_col=None, score_fields=None,
|
|
241
|
+
score_filter=None, progress_bar=True, max_distance=None, exact_only=False,
|
|
242
|
+
*, is_symmetric=False):
|
|
243
|
+
"""Retain inclusive distance/exactness matches, then apply a full-record predicate."""
|
|
244
|
+
if score_filter is None and getattr(self.keep_score, "__func__", None) is not CudaMyopicMCES.keep_score:
|
|
245
|
+
score_filter = self.keep_score
|
|
246
|
+
return self._compute(left, right, self._fields(score_fields), progress_bar, "sparse",
|
|
247
|
+
idx_row, idx_col, score_filter, max_distance, exact_only, is_symmetric)
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT
|
|
2
|
+
"""Per-call workspaces and scheduling for the thresholded MCES pipeline."""
|
|
3
|
+
from contextlib import nullcontext
|
|
4
|
+
|
|
5
|
+
import numpy as np
|
|
6
|
+
from numba import cuda
|
|
7
|
+
|
|
8
|
+
from ._mces_milp import solve_milp
|
|
9
|
+
from ._mces_model import count_models, pack_models
|
|
10
|
+
from ._mces_pdhg import iterate, verify
|
|
11
|
+
from ._mces_search import cpu_screen, device_features, front, pack, screen_kernel, simulator_launch
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class Engine:
|
|
15
|
+
def __init__(self, graphs, scorer, fast, maximum):
|
|
16
|
+
self.graphs = graphs
|
|
17
|
+
self.lib, self.hist = pack(graphs)
|
|
18
|
+
self.weights = np.ascontiguousarray(self.lib.meta[:-1, 3])
|
|
19
|
+
self.scorer = scorer
|
|
20
|
+
self.fast = fast
|
|
21
|
+
threshold = scorer.threshold
|
|
22
|
+
self.threshold = threshold
|
|
23
|
+
if fast and maximum is not None and maximum < threshold:
|
|
24
|
+
threshold = maximum
|
|
25
|
+
largest = 2 * int(self.weights.max())
|
|
26
|
+
self.limit = float(largest) if threshold is None or threshold >= largest / 2 else 2 * threshold
|
|
27
|
+
self.gpu = scorer.device is not None
|
|
28
|
+
# Bound resident screening storage even for chemically diverse libraries.
|
|
29
|
+
self.device_hist = None
|
|
30
|
+
if fast and self.gpu and self.hist.nbytes < (128 << 20):
|
|
31
|
+
features, packed = device_features(self.hist)
|
|
32
|
+
self.device_hist = cuda.to_device(self.weights), cuda.to_device(features), packed
|
|
33
|
+
|
|
34
|
+
def screen(self, left, right):
|
|
35
|
+
if self.device_hist is None:
|
|
36
|
+
return cpu_screen(left, right, self.weights, self.hist, self.limit)
|
|
37
|
+
keep = cuda.device_array(len(left), np.bool_)
|
|
38
|
+
with simulator_launch if cuda.config.ENABLE_CUDASIM else nullcontext():
|
|
39
|
+
screen_kernel[(len(left) + 127) // 128, 128](
|
|
40
|
+
cuda.to_device(left), cuda.to_device(right), *self.device_hist, self.limit, keep)
|
|
41
|
+
return keep.copy_to_host()
|
|
42
|
+
|
|
43
|
+
def solve(self, left, right, pool):
|
|
44
|
+
valid = (left >= 0) & (right >= 0)
|
|
45
|
+
exact = valid & (left == right)
|
|
46
|
+
scores = np.full(len(left), np.inf if self.threshold is None else self.threshold)
|
|
47
|
+
scores[~valid] = np.nan
|
|
48
|
+
scores[exact] = 0.
|
|
49
|
+
ids = np.flatnonzero(valid & ~exact)
|
|
50
|
+
if self.fast and len(ids):
|
|
51
|
+
ids = ids[self.screen(left[ids], right[ids])]
|
|
52
|
+
if not len(ids):
|
|
53
|
+
return scores, exact
|
|
54
|
+
a, b = left[ids], right[ids]
|
|
55
|
+
states = np.empty((len(ids), 3), np.int64)
|
|
56
|
+
batch = self.scorer.batch_size
|
|
57
|
+
for start in range(0, len(ids), batch):
|
|
58
|
+
chunk = slice(start, start + batch)
|
|
59
|
+
states[chunk] = front(self.lib, a[chunk], b[chunk], self.limit,
|
|
60
|
+
self.scorer.max_frames)
|
|
61
|
+
rejected = states[:, 1] == -2
|
|
62
|
+
if not self.fast:
|
|
63
|
+
scores[ids[rejected]] = states[rejected, 0] / 2
|
|
64
|
+
pending = np.flatnonzero((states[:, 1] == -1) & (states[:, 0] <= self.limit))
|
|
65
|
+
tail = {}
|
|
66
|
+
if len(pending):
|
|
67
|
+
widths = np.diff(self.lib.meta[:, 0])
|
|
68
|
+
on_cuda = self.gpu & (np.maximum(widths[a[pending]], widths[b[pending]]) <= self.scorer.max_gpu_atoms)
|
|
69
|
+
for use_gpu in (True, False):
|
|
70
|
+
group = pending[on_cuda == use_gpu]
|
|
71
|
+
if len(group):
|
|
72
|
+
self.refine(a, b, states, group, tail, use_gpu)
|
|
73
|
+
solved = (states[:, 1] >= 0) & (states[:, 1] <= self.limit)
|
|
74
|
+
scores[ids[solved]] = states[solved, 1] / 2
|
|
75
|
+
exact[ids[solved]] = True
|
|
76
|
+
oversize = np.flatnonzero(states[:, 1] == -3)
|
|
77
|
+
|
|
78
|
+
def fallback(k):
|
|
79
|
+
args = tail.get(k, ())
|
|
80
|
+
# Reduced costs were proved at this call's effective cutoff.
|
|
81
|
+
score, flag = solve_milp(self.graphs[a[k]], self.graphs[b[k]], self.limit / 2, *args)
|
|
82
|
+
return (score, True) if flag else (self.threshold, False)
|
|
83
|
+
|
|
84
|
+
remaining = [*oversize, *tail]
|
|
85
|
+
for k, (score, flag) in zip(remaining, pool.map(fallback, remaining)):
|
|
86
|
+
scores[ids[k]], exact[ids[k]] = score, flag
|
|
87
|
+
return scores, exact
|
|
88
|
+
|
|
89
|
+
def refine(self, left, right, state, pending, tail, gpu):
|
|
90
|
+
sizes = count_models(self.lib, left[pending], right[pending])
|
|
91
|
+
order = np.argsort(sizes[:, 2], kind="stable")
|
|
92
|
+
pending, sizes = pending[order], sizes[order]
|
|
93
|
+
# Bound scratch by actual nonzeros. A single exceptionally large model
|
|
94
|
+
# goes directly to host HiGHS. No device buffer is shared between calls.
|
|
95
|
+
large = sizes[:, 2] > 4_000_000
|
|
96
|
+
state[pending[large], 1] = -3
|
|
97
|
+
pending, sizes = pending[~large], sizes[~large]
|
|
98
|
+
for iterations in (96, 384, 768):
|
|
99
|
+
if not len(pending):
|
|
100
|
+
break
|
|
101
|
+
sums = np.append(0, np.cumsum(sizes[:, 2]))
|
|
102
|
+
start = 0
|
|
103
|
+
while start < len(pending):
|
|
104
|
+
end = min(start + self.scorer.batch_size,
|
|
105
|
+
np.searchsorted(sums, sums[start] + 4_000_000, side="right") - 1)
|
|
106
|
+
keys = pending[start:end]
|
|
107
|
+
a, b = left[keys], right[keys]
|
|
108
|
+
model, offsets = pack_models(self.lib, a, b, sizes[start:end])
|
|
109
|
+
x, y = iterate(model, offsets, iterations, gpu)
|
|
110
|
+
values = state[keys]
|
|
111
|
+
final = iterations == 768
|
|
112
|
+
fix = verify(self.lib, a, b, model, offsets, sizes[start:end, 3], x, y, values,
|
|
113
|
+
self.limit, final)
|
|
114
|
+
state[keys] = values
|
|
115
|
+
if final:
|
|
116
|
+
for idx in np.flatnonzero(values[:, 1] == -1):
|
|
117
|
+
tail[keys[idx]] = (int(values[idx, 2]), fix[offsets[idx, 0]:offsets[idx + 1, 0]].copy())
|
|
118
|
+
start = end
|
|
119
|
+
keep = state[pending, 1] == -1
|
|
120
|
+
pending, sizes = pending[keep], sizes[keep]
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT
|
|
2
|
+
"""Exact oriented-edge HiGHS tail for capped searches and cyclic integrality gaps."""
|
|
3
|
+
from warnings import filterwarnings
|
|
4
|
+
|
|
5
|
+
import numpy as np
|
|
6
|
+
from scipy.optimize import Bounds, LinearConstraint, linprog, milp
|
|
7
|
+
from scipy.sparse import csc_matrix, vstack
|
|
8
|
+
|
|
9
|
+
from ._mces_model import allocate_model, dimensions, fill_model
|
|
10
|
+
from ._mces_search import Graph, reverse_edges
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
filterwarnings("ignore", message=r"Unrecognized options detected: .*'threads'.*",
|
|
14
|
+
module=r"^simms\.similarity\._mces_milp$")
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _cycle(g):
|
|
18
|
+
"""Find a fundamental cycle, or certify the entire graph is a forest."""
|
|
19
|
+
parent = np.full(len(g.vertices), -1, np.intp)
|
|
20
|
+
depth = np.full(len(parent), -1, np.intp)
|
|
21
|
+
shortest = None
|
|
22
|
+
for root in range(len(parent)):
|
|
23
|
+
if depth[root] >= 0:
|
|
24
|
+
continue
|
|
25
|
+
depth[root] = 0
|
|
26
|
+
stack = [root]
|
|
27
|
+
while stack:
|
|
28
|
+
i = stack.pop()
|
|
29
|
+
for j in np.flatnonzero(g.adjacency[i]):
|
|
30
|
+
if depth[j] < 0:
|
|
31
|
+
parent[j], depth[j] = i, depth[i] + 1
|
|
32
|
+
stack.append(j)
|
|
33
|
+
elif j != parent[i] and i != parent[j] and i < j:
|
|
34
|
+
a, b = i, j
|
|
35
|
+
path = [(i, j)]
|
|
36
|
+
while a != b:
|
|
37
|
+
if depth[a] >= depth[b]:
|
|
38
|
+
path.append((a, parent[a]))
|
|
39
|
+
a = parent[a]
|
|
40
|
+
else:
|
|
41
|
+
path.append((b, parent[b]))
|
|
42
|
+
b = parent[b]
|
|
43
|
+
if shortest is None or len(path) < len(shortest):
|
|
44
|
+
shortest = path
|
|
45
|
+
return shortest
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _ring_disjunction(a, b, model, atom_count):
|
|
49
|
+
rings = _cycle(a), _cycle(b)
|
|
50
|
+
if bool(rings[0]) == bool(rings[1]):
|
|
51
|
+
return []
|
|
52
|
+
side = 0 if rings[0] else 1
|
|
53
|
+
g = (a, b)[side]
|
|
54
|
+
edge_ids = (model.edge_a, model.edge_b)[side][atom_count:]
|
|
55
|
+
branches = []
|
|
56
|
+
for i, j in rings[side]:
|
|
57
|
+
directions = []
|
|
58
|
+
for u, v in ((i, j), (j, i)):
|
|
59
|
+
start, count = g.vertices[u, 3:5]
|
|
60
|
+
directions.append(start + np.flatnonzero(g.neighbors[start:start + count, 0] == v)[0])
|
|
61
|
+
branches.append(atom_count + np.flatnonzero(np.isin(edge_ids, directions)))
|
|
62
|
+
return branches
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def solve_model(a, b, threshold, model, atoms, best, fix):
|
|
66
|
+
total = a.weight + b.weight
|
|
67
|
+
limit = total if threshold is None or threshold >= total / 2 else int(2 * threshold)
|
|
68
|
+
step = max(1, 2 * int(np.gcd(a.weight_gcd, b.weight_gcd)))
|
|
69
|
+
cutoff = min(limit, best - step)
|
|
70
|
+
incumbent = (best / 2, True) if best <= limit else (threshold, False)
|
|
71
|
+
if cutoff < 0 or len(model.objective) == atoms:
|
|
72
|
+
return incumbent
|
|
73
|
+
coefficients = np.ones(len(model.ci), np.int8)
|
|
74
|
+
for c in range(atoms):
|
|
75
|
+
coefficients[model.cp[c] + 2:model.cp[c + 1]] = -1
|
|
76
|
+
matrix = csc_matrix((coefficients, model.ci, model.cp), shape=(len(model.rhs), len(model.objective)))
|
|
77
|
+
lo, hi = (fix > 0).astype(float), (fix >= 0).astype(float)
|
|
78
|
+
obj = -model.objective.astype(np.float64)
|
|
79
|
+
rhs = model.rhs
|
|
80
|
+
branches = _ring_disjunction(a, b, model, atoms)
|
|
81
|
+
if branches:
|
|
82
|
+
# Every injection of a cycle into a forest omits at least one whole
|
|
83
|
+
# edge. Prove each disjunct separately using integer dual bounds.
|
|
84
|
+
for indices in branches:
|
|
85
|
+
upper = hi.copy()
|
|
86
|
+
upper[indices] = 0
|
|
87
|
+
if np.any(lo > upper):
|
|
88
|
+
continue
|
|
89
|
+
lp = linprog(obj, A_ub=matrix, b_ub=rhs, bounds=np.column_stack((lo, upper)),
|
|
90
|
+
method="highs-ipm", options={"threads": 1})
|
|
91
|
+
if lp.status == 2:
|
|
92
|
+
continue
|
|
93
|
+
if not lp.success:
|
|
94
|
+
break
|
|
95
|
+
scale = 1 << 20
|
|
96
|
+
q = np.maximum(0, np.rint(-lp.ineqlin.marginals * scale)).astype(np.int64)
|
|
97
|
+
reduced = -obj.astype(np.int64) * scale - matrix.T @ q
|
|
98
|
+
bound = rhs.astype(np.int64) @ q + np.where(reduced >= 0, upper, lo).astype(np.int64) @ reduced
|
|
99
|
+
if bound >= (total - cutoff) * scale:
|
|
100
|
+
break
|
|
101
|
+
else:
|
|
102
|
+
return incumbent
|
|
103
|
+
ring = np.zeros(len(obj))
|
|
104
|
+
ring[np.concatenate(branches)] = 1
|
|
105
|
+
matrix = vstack((matrix, ring), format="csc")
|
|
106
|
+
rhs = np.append(rhs, len(branches) - 1)
|
|
107
|
+
matrix = vstack((matrix, obj), format="csc")
|
|
108
|
+
rhs = np.append(rhs, cutoff - total)
|
|
109
|
+
integrality = np.zeros(len(obj), np.uint8)
|
|
110
|
+
integrality[:atoms] = 1
|
|
111
|
+
result = milp(obj, integrality=integrality, bounds=Bounds(lo, hi),
|
|
112
|
+
constraints=LinearConstraint(matrix, -np.inf, rhs),
|
|
113
|
+
options={"mip_rel_gap": 0., "threads": 1})
|
|
114
|
+
if result.status == 2:
|
|
115
|
+
return incumbent
|
|
116
|
+
if not result.success:
|
|
117
|
+
raise RuntimeError(f"HiGHS could not certify the MCES distance: {result.message}")
|
|
118
|
+
return (total + round(result.fun)) / 2, True
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def solve_milp(a, b, threshold, best=None, fix=None):
|
|
122
|
+
def local(g):
|
|
123
|
+
return Graph(g.vertices, g.neighbors, g.adjacency.ravel(), g.elements,
|
|
124
|
+
reverse_edges(g.vertices, g.neighbors), g.weight, g.weight_gcd)
|
|
125
|
+
|
|
126
|
+
left, right = local(a), local(b)
|
|
127
|
+
cols, rows, nnz, atoms = dimensions(left, right)
|
|
128
|
+
model = allocate_model(cols, rows, nnz)
|
|
129
|
+
fill_model(left, right, model, np.zeros(3, np.int64), np.array([cols, rows, nnz]))
|
|
130
|
+
if fix is None:
|
|
131
|
+
fix = np.zeros(cols, np.int8)
|
|
132
|
+
return solve_model(a, b, threshold, model, atoms, a.weight + b.weight if best is None else best, fix)
|