simms-gpu 1.0.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.
Files changed (29) hide show
  1. {simms_gpu-1.0.0 → simms_gpu-1.2.0}/PKG-INFO +23 -2
  2. {simms_gpu-1.0.0 → simms_gpu-1.2.0}/README.md +22 -1
  3. {simms_gpu-1.0.0 → simms_gpu-1.2.0}/pyproject.toml +1 -1
  4. {simms_gpu-1.0.0 → simms_gpu-1.2.0}/simms/__init__.py +2 -1
  5. simms_gpu-1.2.0/simms/__version__.py +1 -0
  6. simms_gpu-1.2.0/simms/molecules.py +154 -0
  7. simms_gpu-1.2.0/simms/similarity/CudaMyopicMCES.py +247 -0
  8. {simms_gpu-1.0.0 → simms_gpu-1.2.0}/simms/similarity/__init__.py +2 -0
  9. simms_gpu-1.2.0/simms/similarity/_mces_engine.py +120 -0
  10. simms_gpu-1.2.0/simms/similarity/_mces_milp.py +132 -0
  11. simms_gpu-1.2.0/simms/similarity/_mces_model.py +151 -0
  12. simms_gpu-1.2.0/simms/similarity/_mces_pdhg.py +310 -0
  13. simms_gpu-1.2.0/simms/similarity/_mces_search.py +439 -0
  14. {simms_gpu-1.0.0 → simms_gpu-1.2.0}/simms/similarity/spectrum_similarity_functions.py +1 -1
  15. simms_gpu-1.0.0/simms/__version__.py +0 -1
  16. {simms_gpu-1.0.0 → simms_gpu-1.2.0}/LICENSE +0 -0
  17. {simms_gpu-1.0.0 → simms_gpu-1.2.0}/simms/peaks.py +0 -0
  18. {simms_gpu-1.0.0 → simms_gpu-1.2.0}/simms/similarity/CudaBinnedEmbeddingSimilarity.py +0 -0
  19. {simms_gpu-1.0.0 → simms_gpu-1.2.0}/simms/similarity/CudaCosineGreedy.py +0 -0
  20. {simms_gpu-1.0.0 → simms_gpu-1.2.0}/simms/similarity/CudaCosineLinear.py +0 -0
  21. {simms_gpu-1.0.0 → simms_gpu-1.2.0}/simms/similarity/CudaEntropyGreedy.py +0 -0
  22. {simms_gpu-1.0.0 → simms_gpu-1.2.0}/simms/similarity/CudaFingerprintSimilarity.py +0 -0
  23. {simms_gpu-1.0.0 → simms_gpu-1.2.0}/simms/similarity/CudaModifiedCosine.py +0 -0
  24. {simms_gpu-1.0.0 → simms_gpu-1.2.0}/simms/similarity/CudaNeutralLossesCosine.py +0 -0
  25. {simms_gpu-1.0.0 → simms_gpu-1.2.0}/simms/similarity/CudaTransitiveAlignment.py +0 -0
  26. {simms_gpu-1.0.0 → simms_gpu-1.2.0}/simms/similarity/_base.py +0 -0
  27. {simms_gpu-1.0.0 → simms_gpu-1.2.0}/simms/similarity/_transitive_peaks.py +0 -0
  28. {simms_gpu-1.0.0 → simms_gpu-1.2.0}/simms/similarity/vector_similarity_functions.py +0 -0
  29. {simms_gpu-1.0.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.0.0
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, 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/).
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,11 +106,32 @@ 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 (Numba CPU or CUDA, with SciPy HiGHS fallback) |
109
110
 
110
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.
111
112
 
112
113
  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.
113
114
 
115
+ ## Myopic MCES (`CudaMyopicMCES`)
116
+
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.
120
+
121
+ ```python
122
+ from simms import MolecularGraphs
123
+ from simms.similarity import CudaMyopicMCES
124
+
125
+ graphs = MolecularGraphs.from_smiles(["CC(=O)Oc1ccccc1C(=O)O", "O=C(O)c1ccccc1O", "Cn1cnc2c1c(=O)n(C)c(=O)n2C"])
126
+ mces = CudaMyopicMCES(threshold=10.0)
127
+ scores = mces.matrix(graphs)
128
+ close_pairs = mces.sparse_matrix(graphs, max_distance=10.0, exact_only=True)
129
+ ```
130
+
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.
132
+
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
+
114
135
  ## Transitive alignment
115
136
 
116
137
  `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)
@@ -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, 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/).
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,11 +68,32 @@ 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 (Numba CPU or CUDA, with SciPy HiGHS fallback) |
71
72
 
72
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.
73
74
 
74
75
  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.
75
76
 
77
+ ## Myopic MCES (`CudaMyopicMCES`)
78
+
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.
82
+
83
+ ```python
84
+ from simms import MolecularGraphs
85
+ from simms.similarity import CudaMyopicMCES
86
+
87
+ graphs = MolecularGraphs.from_smiles(["CC(=O)Oc1ccccc1C(=O)O", "O=C(O)c1ccccc1O", "Cn1cnc2c1c(=O)n(C)c(=O)n2C"])
88
+ mces = CudaMyopicMCES(threshold=10.0)
89
+ scores = mces.matrix(graphs)
90
+ close_pairs = mces.sparse_matrix(graphs, max_distance=10.0, exact_only=True)
91
+ ```
92
+
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.
94
+
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
+
76
97
  ## Transitive alignment
77
98
 
78
99
  `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)
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "simms-gpu"
3
- version = "1.0.0"
3
+ version = "1.2.0"
4
4
  description = "Faster Similarity for Mass Spec on GPU"
5
5
  authors = [
6
6
  {name="Tornike Onoprishvili", email="tornikeonoprishvili@gmail.com"}
@@ -1,6 +1,7 @@
1
1
  from .__version__ import __version__
2
+ from .molecules import MolecularGraphs
2
3
  from .peaks import PeakArrays
3
4
 
4
5
  __author__ = "SimMS developers community"
5
6
  __email__ = "tornikeonoprishvili@gmail.com"
6
- __all__ = ["__version__", "PeakArrays", "similarity"]
7
+ __all__ = ["__version__", "PeakArrays", "MolecularGraphs", "similarity"]
@@ -0,0 +1 @@
1
+ __version__ = "1.2.0"
@@ -0,0 +1,154 @@
1
+ # SPDX-License-Identifier: MIT
2
+ """Reusable element-labelled molecular graphs for weighted common-edge matching."""
3
+ from dataclasses import dataclass
4
+
5
+ import numpy as np
6
+ from matchms import SpectraCollection
7
+ from rdkit import Chem
8
+
9
+
10
+ @dataclass(frozen=True, eq=False)
11
+ class _Graph:
12
+ key: str
13
+ elements: np.ndarray
14
+ adjacency: np.ndarray
15
+ # Per vertex: element, weighted degree, signature order, neighbor offset, count.
16
+ vertices: np.ndarray
17
+ # Per incident edge: neighbor index, neighbor element, doubled bond order.
18
+ neighbors: np.ndarray
19
+ weight: int
20
+ weight_gcd: int
21
+
22
+
23
+ def _readonly(array):
24
+ array.flags.writeable = False
25
+ return array
26
+
27
+
28
+ def _graph(mol, key):
29
+ atoms = list(mol.GetAtoms())
30
+ # Keep the search frontier connected within each component. Break ties by
31
+ # ring membership and degree, then by input index for deterministic searches.
32
+ remaining = set(range(len(atoms)))
33
+ adjacent = [set(n.GetIdx() for n in atom.GetNeighbors()) for atom in atoms]
34
+ order, visited = [], set()
35
+ while remaining:
36
+ i = max(remaining, key=lambda a: (len(adjacent[a] & visited), atoms[a].IsInRing(),
37
+ len(adjacent[a]), -a))
38
+ order.append(i)
39
+ visited.add(i)
40
+ remaining.remove(i)
41
+ index = {old: new for new, old in enumerate(order)}
42
+ elements = np.array([atoms[i].GetAtomicNum() for i in order], dtype=np.uint8)
43
+ adj = np.zeros((len(order), len(order)), dtype=np.uint8)
44
+ for bond in mol.GetBonds():
45
+ scaled = 2 * bond.GetBondTypeAsDouble()
46
+ if scaled != int(scaled) or not 0 <= scaled <= 255:
47
+ raise ValueError("Bond order cannot be represented in half units")
48
+ a, b = index[bond.GetBeginAtomIdx()], index[bond.GetEndAtomIdx()]
49
+ adj[a, b] = adj[b, a] = int(scaled)
50
+ degree = adj.sum(axis=1, dtype=np.int32)
51
+ by_type = np.lexsort((-degree, elements))
52
+ neighbors, vertices = [], []
53
+ for i in range(len(order)):
54
+ edges = sorted(((int(j), int(elements[j]), int(adj[i, j])) for j in np.flatnonzero(adj[i])),
55
+ key=lambda edge: (edge[1], -edge[2], edge[0]))
56
+ vertices.append((elements[i], degree[i], by_type[i], len(neighbors), len(edges)))
57
+ neighbors.extend(edges)
58
+ return _Graph(key, _readonly(elements), _readonly(adj),
59
+ _readonly(np.array(vertices, np.int32).reshape(-1, 5)),
60
+ _readonly(np.array(neighbors, np.int32).reshape(-1, 3)),
61
+ int(degree.sum() // 2), int(np.gcd.reduce(adj.ravel(), initial=0)))
62
+
63
+
64
+ @dataclass(frozen=True, eq=False)
65
+ class MolecularGraphs:
66
+ """Unique molecular graphs and a read-only index back to input order.
67
+
68
+ An index of -1 represents a missing or unparseable structure. Bond orders
69
+ in each graph's adjacency matrix are doubled integers. Metadata sources
70
+ are tried in SMILES, then InChI order.
71
+ """
72
+
73
+ graphs: tuple
74
+ index: np.ndarray
75
+
76
+ def __post_init__(self):
77
+ graphs = tuple(self.graphs)
78
+ if not all(isinstance(g, _Graph) for g in graphs):
79
+ raise TypeError("graphs must contain prepared molecular graphs")
80
+ ids = np.asarray(self.index)
81
+ if ids.ndim != 1 or ids.dtype.kind not in "iu":
82
+ raise ValueError("index must be a one-dimensional integer array")
83
+ if ids.size and (ids.min() < -1 or ids.max() >= len(graphs)):
84
+ raise ValueError("molecular graph index out of range")
85
+ object.__setattr__(self, "graphs", graphs)
86
+ object.__setattr__(self, "index", _readonly(ids.astype(np.int32)))
87
+
88
+ def __len__(self):
89
+ return len(self.index)
90
+
91
+ @classmethod
92
+ def from_smiles(cls, smiles_list):
93
+ """Prepare a sequence or iterable of SMILES strings."""
94
+ return cls._prepare(smiles_list, "smiles")
95
+
96
+ @classmethod
97
+ def from_mols(cls, mol_list):
98
+ """Prepare RDKit molecules without mutating caller-owned atoms."""
99
+ return cls._prepare(mol_list, "mol")
100
+
101
+ @classmethod
102
+ def from_spectra(cls, spectra):
103
+ """Read spectrum metadata, or accept already prepared graphs."""
104
+ return cls._prepare(spectra, "auto")
105
+
106
+ @classmethod
107
+ def _prepare(cls, items, kind):
108
+ if isinstance(items, cls):
109
+ return items
110
+ if isinstance(items, SpectraCollection):
111
+ metadata = items.metadata
112
+ items = (dict(zip(("smiles", "inchi"), row)) for row in
113
+ metadata.reindex(columns=["smiles", "inchi"]).itertuples(index=False, name=None))
114
+ graphs, indices = [], []
115
+ keys, parsed = {}, {}
116
+
117
+ def register(mol):
118
+ if mol is None:
119
+ return -1
120
+ try:
121
+ key = Chem.MolToSmiles(mol, allBondsExplicit=True)
122
+ if key not in keys:
123
+ graph = _graph(mol, key)
124
+ keys[key] = len(graphs)
125
+ graphs.append(graph)
126
+ return keys[key]
127
+ except (RuntimeError, ValueError, OverflowError):
128
+ return -1
129
+
130
+ def parse(value, inchi=False):
131
+ if not isinstance(value, str) or not value.strip():
132
+ return -1
133
+ token = value.strip()
134
+ key = (inchi, token)
135
+ if key not in parsed:
136
+ try:
137
+ mol = Chem.MolFromInchi(token) if inchi else Chem.MolFromSmiles(token)
138
+ parsed[key] = register(mol)
139
+ except (RuntimeError, ValueError):
140
+ parsed[key] = -1
141
+ return parsed[key]
142
+
143
+ for item in items:
144
+ idx = -1
145
+ if kind != "smiles" and isinstance(item, Chem.Mol):
146
+ idx = register(item)
147
+ elif kind != "mol" and isinstance(item, str):
148
+ idx = parse(item)
149
+ elif kind == "auto" and hasattr(item, "get"):
150
+ idx = parse(item.get("smiles"))
151
+ if idx < 0:
152
+ idx = parse(item.get("inchi"), inchi=True)
153
+ indices.append(idx)
154
+ return cls(tuple(graphs), np.array(indices, dtype=np.int32))
@@ -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)
@@ -4,6 +4,7 @@ from .CudaCosineLinear import CudaCosineLinear, CudaModifiedCosineLinear
4
4
  from .CudaEntropyGreedy import CudaEntropyGreedy
5
5
  from .CudaFingerprintSimilarity import CudaFingerprintSimilarity
6
6
  from .CudaModifiedCosine import CudaModifiedCosine, CudaModifiedCosineGreedy
7
+ from .CudaMyopicMCES import CudaMyopicMCES
7
8
  from .CudaNeutralLossesCosine import CudaNeutralLossesCosine
8
9
  from .CudaTransitiveAlignment import CudaTransitiveAlignment as CudaTransitiveAlignment
9
10
  from .CudaTransitiveAlignment import TransitiveAlignmentResult as TransitiveAlignmentResult
@@ -20,5 +21,6 @@ __all__ = [
20
21
  "CudaModifiedCosine",
21
22
  "CudaModifiedCosineGreedy",
22
23
  "CudaModifiedCosineLinear",
24
+ "CudaMyopicMCES",
23
25
  "CudaNeutralLossesCosine",
24
26
  ]
@@ -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]