simms-gpu 1.0.0__tar.gz → 1.1.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 (26) hide show
  1. {simms_gpu-1.0.0 → simms_gpu-1.1.0}/PKG-INFO +22 -1
  2. {simms_gpu-1.0.0 → simms_gpu-1.1.0}/README.md +21 -0
  3. {simms_gpu-1.0.0 → simms_gpu-1.1.0}/pyproject.toml +1 -1
  4. {simms_gpu-1.0.0 → simms_gpu-1.1.0}/simms/__init__.py +2 -1
  5. simms_gpu-1.1.0/simms/__version__.py +1 -0
  6. simms_gpu-1.1.0/simms/molecules.py +154 -0
  7. simms_gpu-1.1.0/simms/similarity/CudaMyopicMCES.py +308 -0
  8. {simms_gpu-1.0.0 → simms_gpu-1.1.0}/simms/similarity/__init__.py +2 -0
  9. simms_gpu-1.1.0/simms/similarity/_mces_milp.py +79 -0
  10. simms_gpu-1.1.0/simms/similarity/_mces_search.py +439 -0
  11. simms_gpu-1.0.0/simms/__version__.py +0 -1
  12. {simms_gpu-1.0.0 → simms_gpu-1.1.0}/LICENSE +0 -0
  13. {simms_gpu-1.0.0 → simms_gpu-1.1.0}/simms/peaks.py +0 -0
  14. {simms_gpu-1.0.0 → simms_gpu-1.1.0}/simms/similarity/CudaBinnedEmbeddingSimilarity.py +0 -0
  15. {simms_gpu-1.0.0 → simms_gpu-1.1.0}/simms/similarity/CudaCosineGreedy.py +0 -0
  16. {simms_gpu-1.0.0 → simms_gpu-1.1.0}/simms/similarity/CudaCosineLinear.py +0 -0
  17. {simms_gpu-1.0.0 → simms_gpu-1.1.0}/simms/similarity/CudaEntropyGreedy.py +0 -0
  18. {simms_gpu-1.0.0 → simms_gpu-1.1.0}/simms/similarity/CudaFingerprintSimilarity.py +0 -0
  19. {simms_gpu-1.0.0 → simms_gpu-1.1.0}/simms/similarity/CudaModifiedCosine.py +0 -0
  20. {simms_gpu-1.0.0 → simms_gpu-1.1.0}/simms/similarity/CudaNeutralLossesCosine.py +0 -0
  21. {simms_gpu-1.0.0 → simms_gpu-1.1.0}/simms/similarity/CudaTransitiveAlignment.py +0 -0
  22. {simms_gpu-1.0.0 → simms_gpu-1.1.0}/simms/similarity/_base.py +0 -0
  23. {simms_gpu-1.0.0 → simms_gpu-1.1.0}/simms/similarity/_transitive_peaks.py +0 -0
  24. {simms_gpu-1.0.0 → simms_gpu-1.1.0}/simms/similarity/spectrum_similarity_functions.py +0 -0
  25. {simms_gpu-1.0.0 → simms_gpu-1.1.0}/simms/similarity/vector_similarity_functions.py +0 -0
  26. {simms_gpu-1.0.0 → simms_gpu-1.1.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.1.0
4
4
  Summary: Faster Similarity for Mass Spec on GPU
5
5
  License-Expression: MIT
6
6
  License-File: LICENSE
@@ -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 (GPU bounds + bounded graph search + 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 exact thresholded (`threshold=10.0`) or unrestricted (`threshold=None`) weighted Maximum Common Edge Subgraph distances matching `myopic-mces 2.3.0`, with zero extra dependencies beyond SimMS's core install (`numba-cuda`, `rdkit`, and SciPy's in-process HiGHS `scipy.optimize.milp`). Duplicate SMILES/structures are deduplicated automatically and pairs exceeding `max_frames` or `max_gpu_atoms` fall back to exact in-process HiGHS before returning or sparse filtering.
118
+
119
+ ```python
120
+ from simms import MolecularGraphs
121
+ from simms.similarity import CudaMyopicMCES
122
+
123
+ graphs = MolecularGraphs.from_smiles(["CC(=O)Oc1ccccc1C(=O)O", "O=C(O)c1ccccc1O", "Cn1cnc2c1c(=O)n(C)c(=O)n2C"])
124
+ mces = CudaMyopicMCES(threshold=10.0)
125
+ scores = mces.matrix(graphs)
126
+ close_pairs = mces.sparse_matrix(graphs, max_distance=10.0, exact_only=True)
127
+ ```
128
+
129
+ On the RTX 4060 Laptop GPU (`2,240/2,240` exact oracle parity vs `myopic-mces 2.3.0`, max diff `1.66e-12`; [benchmarks/myopic_mces_rtx4060.json](benchmarks/myopic_mces_rtx4060.json)):
130
+
131
+ - **1,000 mixed pairs (`threshold=10`):** `17.9 ms` (`92.2×` vs 8-core upstream HiGHS, `690×` vs 8-core CBC)
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.)*
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)
@@ -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 (GPU bounds + bounded graph search + 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 exact thresholded (`threshold=10.0`) or unrestricted (`threshold=None`) weighted Maximum Common Edge Subgraph distances matching `myopic-mces 2.3.0`, with zero extra dependencies beyond SimMS's core install (`numba-cuda`, `rdkit`, and SciPy's in-process HiGHS `scipy.optimize.milp`). Duplicate SMILES/structures are deduplicated automatically and pairs exceeding `max_frames` or `max_gpu_atoms` fall back to exact in-process HiGHS before returning or sparse filtering.
80
+
81
+ ```python
82
+ from simms import MolecularGraphs
83
+ from simms.similarity import CudaMyopicMCES
84
+
85
+ graphs = MolecularGraphs.from_smiles(["CC(=O)Oc1ccccc1C(=O)O", "O=C(O)c1ccccc1O", "Cn1cnc2c1c(=O)n(C)c(=O)n2C"])
86
+ mces = CudaMyopicMCES(threshold=10.0)
87
+ scores = mces.matrix(graphs)
88
+ close_pairs = mces.sparse_matrix(graphs, max_distance=10.0, exact_only=True)
89
+ ```
90
+
91
+ On the RTX 4060 Laptop GPU (`2,240/2,240` exact oracle parity vs `myopic-mces 2.3.0`, max diff `1.66e-12`; [benchmarks/myopic_mces_rtx4060.json](benchmarks/myopic_mces_rtx4060.json)):
92
+
93
+ - **1,000 mixed pairs (`threshold=10`):** `17.9 ms` (`92.2×` vs 8-core upstream HiGHS, `690×` vs 8-core CBC)
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.)*
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.1.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.1.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 or not mol.GetNumAtoms():
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,308 @@
1
+ # SPDX-License-Identifier: MIT
2
+ """Thresholded weighted molecular common-edge distances on CUDA."""
3
+ from collections import defaultdict
4
+ from concurrent.futures import ThreadPoolExecutor
5
+ from itertools import islice, product
6
+ from operator import index
7
+
8
+ import numpy as np
9
+ import torch
10
+ from matchms import Scores
11
+ from numba import cuda
12
+ from scipy.sparse import coo_array
13
+ from tqdm import tqdm
14
+
15
+ from ..molecules import MolecularGraphs
16
+ from ..utils import get_device
17
+ from ._base import CudaSimilarity
18
+ from ._mces_milp import solve_milp
19
+ from ._mces_search import filter_kernel, pack, solve_kernel
20
+ from .vector_similarity_functions import kernel_stream, kernel_view
21
+
22
+
23
+ @cuda.jit
24
+ def _scatter(ids, values, flags, scores, exact):
25
+ k = cuda.grid(1)
26
+ if k < len(ids):
27
+ scores[ids[k]], exact[ids[k]] = values[k], flags[k]
28
+
29
+
30
+ @cuda.jit
31
+ def _retain(scores, exact, maximum, has_maximum, only_exact, ids, values, flags, count):
32
+ k = cuda.grid(1)
33
+ if k < len(scores):
34
+ if (not has_maximum or scores[k] <= maximum) and (not only_exact or exact[k]):
35
+ slot = cuda.atomic.add(count, 0, 1)
36
+ ids[slot], values[slot], flags[slot] = k, scores[k], exact[k]
37
+
38
+
39
+ def _launch(n):
40
+ threads = 32
41
+ return (n + threads - 1) // threads, threads
42
+
43
+
44
+ def _library(left, right):
45
+ graphs, keys = [], {}
46
+
47
+ def groups(container):
48
+ ids = []
49
+ for graph in container.graphs:
50
+ if graph.key not in keys:
51
+ keys[graph.key] = len(graphs)
52
+ graphs.append(graph)
53
+ ids.append(keys[graph.key])
54
+ remap = np.array(ids + [-1], np.int32)
55
+ axis = remap[container.index]
56
+ grouped = defaultdict(list)
57
+ for i, g in enumerate(axis):
58
+ grouped[int(g)].append(i)
59
+ return axis, grouped
60
+
61
+ a = groups(left)
62
+ b = a if left is right else groups(right)
63
+ return graphs, a, b
64
+
65
+
66
+ def _coordinates(row, col, shape):
67
+ if row is None or col is None:
68
+ raise ValueError("idx_row and idx_col must be given together")
69
+ row, col = np.asarray(row), np.asarray(col)
70
+ if row.ndim != 1 or row.shape != col.shape:
71
+ raise ValueError("idx_row and idx_col must be aligned 1D arrays")
72
+ for axis, size in zip((row, col), shape):
73
+ if axis.size and axis.dtype.kind not in "iu":
74
+ raise TypeError("sparse coordinates must be integers")
75
+ if np.any(axis < 0) or np.any(axis >= size):
76
+ raise ValueError("sparse coordinate out of bounds")
77
+ return zip(row, col)
78
+
79
+
80
+ class _Pairs:
81
+ """Stream unique compound pairs and expand results back to spectrum coordinates."""
82
+
83
+ def __init__(self, a, b, symmetric, row, col):
84
+ (axis_a, self.left), (axis_b, self.right) = a, b
85
+ self.requested = None
86
+ if row is not None or col is not None:
87
+ self.requested = defaultdict(set)
88
+ for i, j in _coordinates(row, col, (len(axis_a), len(axis_b))):
89
+ key = tuple(sorted((axis_a[i], axis_b[j])))
90
+ self.requested[key].add((i, j))
91
+ if symmetric:
92
+ self.requested[key].add((j, i))
93
+
94
+ def __iter__(self):
95
+ if self.requested is not None:
96
+ yield from self.requested
97
+ return
98
+ for i in self.left:
99
+ for j in self.right:
100
+ if i > j and j in self.left and i in self.right:
101
+ continue
102
+ yield i, j
103
+
104
+ def batches(self, graphs, batch_size):
105
+ def split(tile):
106
+ width = max((len(graphs[g].elements) for i, j in tile if i >= 0 and j >= 0 and i != j
107
+ for g in (i, j)), default=1)
108
+ # Bound concurrent LAP scratch without penalizing unrelated small pairs.
109
+ if len(tile) > 1 and len(tile) * 4 * width * width > (64 << 20):
110
+ mid = len(tile) // 2
111
+ yield from split(tile[:mid])
112
+ yield from split(tile[mid:])
113
+ else:
114
+ yield tile, width
115
+
116
+ pairs = iter(self)
117
+ while tile := list(islice(pairs, batch_size)):
118
+ yield from split(tile)
119
+
120
+ def expand(self, tile, ids, records, predicate):
121
+ for k, pair_id in enumerate(ids):
122
+ if predicate is None or predicate(records[k]):
123
+ for i, j in self.locations(tile[pair_id]):
124
+ yield i, j, k
125
+
126
+ def locations(self, pair):
127
+ if self.requested is not None:
128
+ yield from self.requested[pair]
129
+ return
130
+ i, j = pair
131
+ yield from product(self.left[i], self.right[j])
132
+ if i != j and j in self.left and i in self.right:
133
+ yield from product(self.left[j], self.right[i])
134
+
135
+
136
+ class CudaMyopicMCES(CudaSimilarity):
137
+ """Weighted edge-edit distance under an injective element-preserving atom map.
138
+
139
+ A finite threshold returns exact optima through the threshold (inclusive).
140
+ Above it, score is the neighborhood lower bound if it rejected the pair
141
+ and always_stronger_bound is set, otherwise the threshold. Inspect 'exact'
142
+ to distinguish capped results, especially when filtering at the threshold.
143
+ Set threshold=None for unrestricted exact distances. Torch output planes
144
+ follow score_fields order. Sparse output preserves retained zero distances.
145
+ """
146
+
147
+ score_datatype = np.dtype([("score", np.float64), ("exact", np.bool_)])
148
+ score_fields = score_datatype.names
149
+
150
+ def __init__(self, threshold: float | None = 10.0, always_stronger_bound: bool = True,
151
+ batch_size: int = 2048, max_frames: int = 50_000, max_gpu_atoms: int = 64,
152
+ n_fallback_workers: int | None = None):
153
+ self.threshold = None if threshold is None else float(threshold)
154
+ if threshold is not None and (not np.isfinite(self.threshold) or self.threshold < 0):
155
+ raise ValueError("threshold must be nonnegative and finite, or None")
156
+ self.always_stronger_bound = bool(always_stronger_bound)
157
+ self.batch_size = index(batch_size)
158
+ self.max_frames = index(max_frames)
159
+ self.max_gpu_atoms = index(max_gpu_atoms)
160
+ self.n_fallback_workers = None if n_fallback_workers is None else index(n_fallback_workers)
161
+ if min(self.batch_size, self.max_frames, self.max_gpu_atoms,
162
+ 1 if n_fallback_workers is None else self.n_fallback_workers) < 1:
163
+ raise ValueError("batch_size, max_frames, max_gpu_atoms and n_fallback_workers must be positive")
164
+ self.device = get_device(require_cuda=True)
165
+ if not cuda.is_available():
166
+ raise RuntimeError("MCES requires CUDA or NUMBA_ENABLE_CUDASIM=1")
167
+
168
+ def pair(self, a, b):
169
+ def single(item):
170
+ if isinstance(item, MolecularGraphs):
171
+ if len(item) != 1:
172
+ raise ValueError("pair expects one molecule per input")
173
+ return item
174
+ return [item]
175
+
176
+ return self.matrix(single(a), single(b), array_type="numpy", progress_bar=False).reshape(())
177
+
178
+ @staticmethod
179
+ def _upload(arrays):
180
+ return tuple(cuda.to_device(arr) for arr in arrays)
181
+
182
+ def _solve(self, library, graphs, pairs, width, pool, maximum, only_exact, device_output):
183
+ n = len(pairs)
184
+ meta, vertices, adjacency, neighbors = library
185
+ device_pairs = cuda.to_device(np.asarray(pairs, np.int32))
186
+ work = cuda.device_array((n, 7, width + 1), np.int32)
187
+ costs = cuda.device_array((n, width, width), np.int32)
188
+ seeds = cuda.device_array((n, 3, width), np.int32)
189
+ lower = cuda.device_array(n, np.int32)
190
+ stream = kernel_stream(self.device) if device_output else 0
191
+ if device_output:
192
+ planes = (torch.empty(n, device=self.device, dtype=torch.float64),
193
+ torch.empty(n, device=self.device, dtype=torch.bool))
194
+ scores, exact = map(kernel_view, planes)
195
+ else:
196
+ scores, exact = cuda.device_array(n, np.float64), cuda.device_array(n, np.bool_)
197
+ pending = cuda.device_array(n, np.int32)
198
+ count = cuda.to_device(np.zeros(1, np.int32))
199
+ threshold = np.inf if self.threshold is None else self.threshold
200
+ blocks, threads = _launch(n)
201
+ filter_kernel[blocks, threads, stream](meta, vertices, neighbors, device_pairs, threshold * 2,
202
+ self.always_stronger_bound, costs, work, seeds, lower)
203
+ lanes = 1 if cuda.config.ENABLE_CUDASIM else 32
204
+ solve_kernel[n, lanes, stream](
205
+ meta, vertices, adjacency, neighbors, device_pairs, threshold, self.always_stronger_bound,
206
+ self.max_gpu_atoms, self.max_frames, lower, seeds, work, scores, exact, pending, count,
207
+ )
208
+ if stream:
209
+ stream.synchronize()
210
+ size = int(count.copy_to_host()[0])
211
+ if size:
212
+ ids = pending[:size].copy_to_host()
213
+
214
+ def solve(k):
215
+ i, j = pairs[k]
216
+ return solve_milp(graphs[i], graphs[j], self.threshold)
217
+
218
+ values, flags = zip(*pool.map(solve, ids))
219
+ blocks, threads = _launch(size)
220
+ _scatter[blocks, threads, stream](pending[:size], cuda.to_device(np.array(values, np.float64)),
221
+ cuda.to_device(np.array(flags, bool)), scores, exact)
222
+ if device_output:
223
+ return range(n), *planes
224
+ if maximum is None and not only_exact:
225
+ return range(n), scores.copy_to_host(), exact.copy_to_host()
226
+ count.copy_to_device(np.zeros(1, np.int32))
227
+ values = cuda.device_array_like(scores)
228
+ flags = cuda.device_array_like(exact)
229
+ _retain[_launch(n)](scores, exact, 0. if maximum is None else float(maximum),
230
+ maximum is not None, only_exact, pending, values, flags, count)
231
+ size = int(count.copy_to_host()[0])
232
+ return (pending[:size].copy_to_host(), values[:size].copy_to_host(), flags[:size].copy_to_host())
233
+
234
+ def _compute(self, left, right, fields, progress_bar, array_type, row=None, col=None,
235
+ predicate=None, maximum=None, only_exact=False):
236
+ symmetric = right is None
237
+ same = symmetric or left is right
238
+ left = MolecularGraphs.from_spectra(left)
239
+ right = left if same else MolecularGraphs.from_spectra(right)
240
+ shape = (len(left), len(right))
241
+ graphs, a, b = _library(left, right)
242
+ plan = _Pairs(a, b, symmetric, row, col)
243
+ dtype = np.dtype([(f, self.score_datatype[f]) for f in fields])
244
+ sparse = array_type == "sparse"
245
+ if sparse:
246
+ chunks = []
247
+ elif array_type == "torch":
248
+ result = torch.empty((len(fields), *shape), dtype=torch.float64, device=self.device)
249
+ elif array_type == "scores":
250
+ result = self._create_dense_result(*shape, fields)
251
+ else:
252
+ result = np.empty(shape, dtype)
253
+ if graphs:
254
+ library = self._upload(pack(graphs))
255
+ else:
256
+ # Sentinel-only pairs leave the kernels before graph access.
257
+ library = tuple(cuda.to_device(arr) for arr in
258
+ (np.zeros((1, 5), np.int64), np.empty((0, 5), np.int32),
259
+ np.empty(0, np.uint8), np.empty((0, 3), np.int32)))
260
+ with ThreadPoolExecutor(self.n_fallback_workers) as pool, tqdm(
261
+ desc="Scoring molecular pairs", unit="pair", disable=not progress_bar
262
+ ) as progress:
263
+ for tile, width in plan.batches(graphs, self.batch_size):
264
+ ids, values, flags = self._solve(library, graphs, tile, width, pool, maximum,
265
+ only_exact, array_type == "torch")
266
+ if array_type == "torch":
267
+ records = {"score": values, "exact": flags}
268
+ else:
269
+ records = np.empty(len(values), self.score_datatype)
270
+ records["score"], records["exact"] = values, flags
271
+ locations = plan.expand(tile, ids, records, predicate)
272
+ while block := list(islice(locations, max(len(tile), 4096))):
273
+ i, j, k = np.asarray(block, np.intp).T
274
+ if sparse:
275
+ chunks.append((i, j, records[k]))
276
+ elif array_type == "torch":
277
+ i, j, k = (torch.as_tensor(x, device=self.device) for x in (i, j, k))
278
+ for p, field in enumerate(fields):
279
+ result[p, i, j] = records[field][k].to(result.dtype)
280
+ else:
281
+ for field in fields:
282
+ result[field][i, j] = records[field][k]
283
+ progress.update(len(tile))
284
+ if sparse:
285
+ if chunks:
286
+ i, j, values = map(np.concatenate, zip(*chunks))
287
+ else:
288
+ i = j = np.empty(0, np.intp)
289
+ values = np.empty(0, self.score_datatype)
290
+ return Scores({f: coo_array((values[f], (i, j)), shape=shape) for f in fields})
291
+ return Scores(result) if array_type == "scores" else result
292
+
293
+ def matrix(self, left, right=None, score_fields=None, progress_bar=True, array_type="scores"):
294
+ if array_type not in ("scores", "numpy", "torch"):
295
+ raise ValueError("array_type must be 'scores', 'numpy' or 'torch'")
296
+ return self._compute(left, right, self._fields(score_fields), progress_bar, array_type)
297
+
298
+ def keep_score(self, score):
299
+ """Retain all requested distances, including exact zeros and missing values."""
300
+ return True
301
+
302
+ def sparse_matrix(self, left, right=None, idx_row=None, idx_col=None, score_fields=None,
303
+ score_filter=None, progress_bar=True, max_distance=None, exact_only=False):
304
+ """Retain inclusive distance/exactness matches, then apply a full-record predicate."""
305
+ if score_filter is None and getattr(self.keep_score, "__func__", None) is not CudaMyopicMCES.keep_score:
306
+ score_filter = self.keep_score
307
+ return self._compute(left, right, self._fields(score_fields), progress_bar, "sparse",
308
+ idx_row, idx_col, score_filter, max_distance, exact_only)
@@ -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,79 @@
1
+ # SPDX-License-Identifier: MIT
2
+ """Sparse binary model for the weighted common-edge edit distance (SciPy/HiGHS)."""
3
+ from collections import defaultdict
4
+ from warnings import filterwarnings
5
+
6
+ import numpy as np
7
+ from scipy.optimize import Bounds, LinearConstraint, milp
8
+ from scipy.sparse import csc_matrix
9
+
10
+
11
+ # SciPy forwards the native threads option. Scope the warning filter to this
12
+ # module: entering/exiting catch_warnings in concurrent workers races on 3.11.
13
+ filterwarnings("ignore", message=r"Unrecognized options detected: .*'threads'.*", category=RuntimeWarning,
14
+ module=r"^simms\.similarity\._mces_milp$")
15
+
16
+
17
+ def solve_milp(a, b, threshold):
18
+ """Return the certified optimum, or the threshold after certified infeasibility."""
19
+ # Eliminate the unmatched-edge variables: an edge unused by a match pays
20
+ # its weight. A matched edge pair saves twice its smaller weight.
21
+ total = a.weight + b.weight
22
+ edge_a = list(zip(*np.nonzero(np.triu(a.adjacency, 1))))
23
+ edge_b = list(zip(*np.nonzero(np.triu(b.adjacency, 1))))
24
+ atom_vars = {}
25
+ objective = []
26
+ rows = defaultdict(dict)
27
+
28
+ for i, elem in enumerate(a.elements):
29
+ for j in np.flatnonzero(b.elements == elem):
30
+ var = len(objective)
31
+ atom_vars[i, j] = var
32
+ objective.append(0)
33
+ rows["atom_a", i][var] = rows["atom_b", j][var] = 1
34
+ for e, (i, h) in enumerate(edge_a):
35
+ for f, (j, k) in enumerate(edge_b):
36
+ if not (((i, j) in atom_vars and (h, k) in atom_vars)
37
+ or ((i, k) in atom_vars and (h, j) in atom_vars)):
38
+ continue
39
+ var = len(objective)
40
+ objective.append(-2 * int(min(a.adjacency[i, h], b.adjacency[j, k])))
41
+ rows["edge_a", e][var] = rows["edge_b", f][var] = 1
42
+ # Incidence consistency, aggregated by (vertex, opposite edge).
43
+ for src in (i, h):
44
+ row = rows["inc_a", src, f]
45
+ row[var] = 1
46
+ for dst in (j, k):
47
+ if (src, dst) in atom_vars:
48
+ row[atom_vars[src, dst]] = -1
49
+ for dst in (j, k):
50
+ row = rows["inc_b", dst, e]
51
+ row[var] = 1
52
+ for src in (i, h):
53
+ if (src, dst) in atom_vars:
54
+ row[atom_vars[src, dst]] = -1
55
+
56
+ if len(objective) == len(atom_vars):
57
+ score = total / 2
58
+ return (score, True) if threshold is None or score <= threshold else (threshold, False)
59
+ if threshold is not None:
60
+ rows["limit",] = {i: c for i, c in enumerate(objective) if c}
61
+
62
+ ri, ci, values, upper = [], [], [], []
63
+ for r, (key, entries) in enumerate(rows.items()):
64
+ ri.extend([r] * len(entries))
65
+ ci.extend(entries)
66
+ values.extend(entries.values())
67
+ if key[0] == "limit":
68
+ upper.append(np.floor(2 * threshold) - total)
69
+ else:
70
+ upper.append(0 if key[0].startswith("inc") else 1)
71
+ matrix = csc_matrix((values, (ri, ci)), shape=(len(upper), len(objective)))
72
+ result = milp(np.asarray(objective, float), integrality=np.ones(len(objective), np.uint8),
73
+ bounds=Bounds(0, 1), constraints=LinearConstraint(matrix, -np.inf, upper),
74
+ options={"mip_rel_gap": 0.0, "threads": 1})
75
+ if result.status == 2 and threshold is not None:
76
+ return threshold, False
77
+ if not result.success:
78
+ raise RuntimeError(f"HiGHS could not certify the MCES distance: {result.message}")
79
+ return (total + round(result.fun)) / 2, True
@@ -0,0 +1,439 @@
1
+ # SPDX-License-Identifier: MIT
2
+ """Integer MCES bounds and depth-first search, specialized for CUDA or CPU JIT.
3
+
4
+ Weights, lower bounds and distances inside the search use doubled bond order.
5
+ An overlapping edge saves its weight in *both* graphs. No connectivity
6
+ constraint is imposed on the matched edges.
7
+ """
8
+ import numpy as np
9
+ from numba import cuda
10
+
11
+
12
+ def _objective_bound(total, lower, divisor_a, divisor_b):
13
+ """Round the search target to an attainable distance, preserving the public LAP bound."""
14
+ while divisor_b:
15
+ divisor_a, divisor_b = divisor_b, divisor_a % divisor_b
16
+ step = max(1, 2 * divisor_a)
17
+ return lower + (total - lower) % step
18
+
19
+
20
+ def _incident(a, b, na, nb, left_after, occupied):
21
+ """Maximum incident overlap by neighbor element, optionally across a DFS cut."""
22
+ p, q = a[3], b[3]
23
+ end_p, end_q = p + a[4], q + b[4]
24
+ value = 0
25
+ while p < end_p and q < end_q:
26
+ if left_after >= 0 and na[p, 0] <= left_after:
27
+ p += 1
28
+ elif left_after >= 0 and occupied[nb[q, 0]]:
29
+ q += 1
30
+ elif na[p, 1] < nb[q, 1]:
31
+ p += 1
32
+ elif na[p, 1] > nb[q, 1]:
33
+ q += 1
34
+ else:
35
+ value += min(na[p, 2], nb[q, 2])
36
+ p += 1
37
+ q += 1
38
+ return value
39
+
40
+
41
+ def _move_gain(atom, neighbors, adjacency, size, mapping, old, new, exclude):
42
+ """Change in conserved weight when moving one end of each incident edge."""
43
+ gain = 0
44
+ for k in range(atom[3], atom[3] + atom[4]):
45
+ other = neighbors[k, 0]
46
+ target = mapping[other]
47
+ if other != exclude and target >= 0:
48
+ weight = neighbors[k, 2]
49
+ if new >= 0:
50
+ gain += min(weight, int(adjacency[new * size + target]))
51
+ if old >= 0:
52
+ gain -= min(weight, int(adjacency[old * size + target]))
53
+ return gain
54
+
55
+
56
+ def _assignment(cost, size, w):
57
+ """Shortest augmenting path Hungarian LAP. w[2, j] gives row for column j."""
58
+ u, v, owner, parent, slack, used = w[0], w[1], w[2], w[3], w[4], w[5]
59
+ for j in range(size + 1):
60
+ u[j] = v[j] = owner[j] = 0
61
+ for i in range(1, size + 1):
62
+ owner[0] = i
63
+ for j in range(size + 1):
64
+ slack[j] = 2147483647
65
+ used[j] = 0
66
+ j = 0
67
+ while True:
68
+ used[j] = 1
69
+ row = owner[j]
70
+ delta, next_j = 2147483647, 0
71
+ for k in range(1, size + 1):
72
+ if not used[k]:
73
+ reduced = cost[row - 1, k - 1] - u[row] - v[k]
74
+ if reduced < slack[k]:
75
+ slack[k], parent[k] = reduced, j
76
+ if slack[k] < delta:
77
+ delta, next_j = slack[k], k
78
+ for k in range(size + 1):
79
+ if used[k]:
80
+ u[owner[k]] += delta
81
+ v[k] -= delta
82
+ else:
83
+ slack[k] -= delta
84
+ j = next_j
85
+ if owner[j] == 0:
86
+ break
87
+ while j:
88
+ k = parent[j]
89
+ owner[j] = owner[k]
90
+ j = k
91
+
92
+
93
+ def _specialize(compile_fn, gpu=False):
94
+ incident = compile_fn(_incident)
95
+ assignment = compile_fn(_assignment)
96
+ move_gain = compile_fn(_move_gain)
97
+
98
+ @compile_fn
99
+ def bounds(a, b, na, nb, total, limit, stronger, cost, w, seed, dual_a, dual_b):
100
+ # Zipped, degree-descending lists within equal-element groups.
101
+ p = q = overlap = 0
102
+ while p < len(a) and q < len(b):
103
+ x, y = a[a[p, 2]], b[b[q, 2]]
104
+ if x[0] < y[0]:
105
+ p += 1
106
+ elif x[0] > y[0]:
107
+ q += 1
108
+ else:
109
+ overlap += min(x[1], y[1])
110
+ p += 1
111
+ q += 1
112
+ weak = total - overlap
113
+ if weak > limit and not stronger:
114
+ return weak
115
+ for i in range(len(a)):
116
+ seed[i] = -1
117
+ dual_a[i] = 0
118
+ for j in range(len(b)):
119
+ dual_b[j] = 0
120
+ p = q = overlap = 0
121
+ while p < len(a) and q < len(b):
122
+ el, er = a[a[p, 2], 0], b[b[q, 2], 0]
123
+ if el < er:
124
+ p += 1
125
+ continue
126
+ if er < el:
127
+ q += 1
128
+ continue
129
+ end_p, end_q = p + 1, q + 1
130
+ while end_p < len(a) and a[a[end_p, 2], 0] == el:
131
+ end_p += 1
132
+ while end_q < len(b) and b[b[end_q, 2], 0] == el:
133
+ end_q += 1
134
+ rows, cols = end_p - p, end_q - q
135
+ size = max(rows, cols)
136
+ for i in range(size):
137
+ for j in range(size):
138
+ value = 0
139
+ if i < rows and j < cols:
140
+ value = incident(a[a[p + i, 2]], b[b[q + j, 2]], na, nb, -1, w[0])
141
+ cost[i, j] = -value
142
+ assignment(cost, size, w)
143
+ for i in range(rows):
144
+ dual_a[a[p + i, 2]] = -w[0, i + 1]
145
+ for j in range(cols):
146
+ dual_b[b[q + j, 2]] = -w[1, j + 1]
147
+ i = w[2, j + 1] - 1
148
+ if i < rows:
149
+ seed[a[p + i, 2]] = b[q + j, 2]
150
+ overlap -= cost[i, j]
151
+ p, q = end_p, end_q
152
+ return total - overlap
153
+
154
+ @compile_fn
155
+ def feasible(a, b, na, adj_b, total, lower, seed, inverse):
156
+ size = len(b)
157
+ best = 0
158
+ for i in range(len(a)):
159
+ j = seed[i]
160
+ if j >= 0:
161
+ for k in range(a[i, 3], a[i, 3] + a[i, 4]):
162
+ src = na[k, 0]
163
+ dst = seed[src]
164
+ if src < i and dst >= 0:
165
+ best += min(na[k, 2], int(adj_b[j * size + dst]))
166
+ if total - 2 * best == lower:
167
+ return best
168
+ # Improve the feasible LAP seed by element-preserving swaps, including
169
+ # moving into a free target. Strict improvements guarantee termination.
170
+ for j in range(size):
171
+ inverse[j] = -1
172
+ for i in range(len(a)):
173
+ if seed[i] >= 0:
174
+ inverse[seed[i]] = i
175
+ while True:
176
+ gain, src, dst = 0, 0, 0
177
+ for i in range(len(a)):
178
+ old = seed[i]
179
+ for j in range(size):
180
+ h = inverse[j]
181
+ if a[i, 0] != b[j, 0] or (h >= 0 and h <= i and old >= 0):
182
+ continue
183
+ delta = move_gain(a[i], na, adj_b, size, seed, old, j, h)
184
+ if h >= 0:
185
+ delta += move_gain(a[h], na, adj_b, size, seed, j, old, i)
186
+ if delta > gain:
187
+ gain, src, dst = delta, i, j
188
+ if not gain:
189
+ break
190
+ old, h = seed[src], inverse[dst]
191
+ if h >= 0:
192
+ seed[h] = old
193
+ if old >= 0:
194
+ inverse[old] = h
195
+ seed[src], inverse[dst] = dst, src
196
+ best += gain
197
+ if total - 2 * best == lower:
198
+ return best
199
+
200
+ return best
201
+
202
+ @compile_fn
203
+ def explore(a, b, na, nb, adj_b, wa, wb, lower, limit, cap, seed, dual_a, dual_b,
204
+ w, best, first, stride, shared):
205
+ size = len(b)
206
+ total = wa + wb
207
+ mapping, used, cursor = w[0], w[1], w[2]
208
+ matched, free_a, free_b = w[3], w[4], w[5]
209
+ for j in range(size):
210
+ used[j] = 0
211
+ dual = w[6]
212
+ dual[0] = 0
213
+ for i in range(len(a)):
214
+ dual[0] += dual_a[i]
215
+ for j in range(size):
216
+ dual[0] += dual_b[j]
217
+ depth = frames = 0
218
+ cursor[0], matched[0] = first, 0
219
+ free_a[0], free_b[0] = wa, wb
220
+ while depth >= 0:
221
+ candidate = cursor[depth]
222
+ if candidate > size:
223
+ depth -= 1
224
+ if depth >= 0 and mapping[depth] >= 0:
225
+ used[mapping[depth]] = 0
226
+ continue
227
+ cursor[depth] += stride if depth == 0 else 1
228
+ # Visit the assignment seed first, followed by all other targets and deletion.
229
+ preferred = seed[depth]
230
+ if preferred >= 0:
231
+ if candidate == 0:
232
+ candidate = preferred
233
+ elif candidate <= preferred:
234
+ candidate -= 1
235
+ atom = a[depth]
236
+ if candidate == size:
237
+ # With nonnegative edge rewards a maximal same-element injection
238
+ # always attains the optimum. Only a surplus source may be deleted.
239
+ remaining = 0
240
+ for i in range(depth, len(a)):
241
+ if a[i, 0] == atom[0]:
242
+ remaining += 1
243
+ for j in range(size):
244
+ if b[j, 0] == atom[0] and not used[j]:
245
+ remaining -= 1
246
+ if remaining <= 0:
247
+ continue
248
+ candidate = -1
249
+ elif used[candidate] or atom[0] != b[candidate, 0]:
250
+ continue
251
+ frames += 1
252
+ if gpu and stride > 1:
253
+ used_frames = cuda.atomic.add(shared, 0, 1) + 1
254
+ best = cuda.atomic.max(shared, 1, best)
255
+ if total - 2 * best == lower:
256
+ return lower, frames
257
+ else:
258
+ used_frames = frames
259
+ if used_frames >= cap:
260
+ return -1, frames
261
+ mapping[depth] = candidate
262
+ common = matched[depth]
263
+ left_weight, right_weight = free_a[depth], free_b[depth]
264
+ for k in range(atom[3], atom[3] + atom[4]):
265
+ other, weight = na[k, 0], na[k, 2]
266
+ if other > depth:
267
+ left_weight -= weight
268
+ elif mapping[other] >= 0 and candidate >= 0:
269
+ common += min(weight, int(adj_b[candidate * size + mapping[other]]))
270
+ if candidate >= 0:
271
+ used[candidate] = 1
272
+ for k in range(b[candidate, 3], b[candidate, 3] + b[candidate, 4]):
273
+ if not used[nb[k, 0]]:
274
+ right_weight -= nb[k, 2]
275
+ # Any completion has three disjoint edge sets: fixed prefix edges,
276
+ # edges crossing the cut, and edges wholly in the two unused suffixes.
277
+ # Relax each frontier vertex to an independent neighbor assignment.
278
+ remaining_dual = dual[depth] - dual_a[depth]
279
+ if candidate >= 0:
280
+ remaining_dual -= dual_b[candidate]
281
+ frontier = 0
282
+ for i in range(depth + 1):
283
+ j = mapping[i]
284
+ if j >= 0:
285
+ frontier += incident(a[i], b[j], na, nb, depth, used)
286
+ # The LAP dual prices bound incident overlap for every unassigned
287
+ # vertex pair. Each preserved edge is counted at both endpoints.
288
+ upper = common + min(frontier + min(left_weight, right_weight),
289
+ (frontier + remaining_dual) // 2)
290
+ if common > best:
291
+ best = common
292
+ if gpu and stride > 1:
293
+ cuda.atomic.max(shared, 1, best)
294
+ if total - 2 * best == lower:
295
+ return lower, frames
296
+ if upper > best and total - 2 * upper <= limit and depth + 1 < len(a):
297
+ depth += 1
298
+ matched[depth], free_a[depth], free_b[depth] = common, left_weight, right_weight
299
+ dual[depth] = remaining_dual
300
+ cursor[depth] = 0
301
+ elif candidate >= 0:
302
+ used[candidate] = 0
303
+ return total - 2 * best, frames
304
+
305
+ @compile_fn
306
+ def search(a, b, na, nb, adj_b, wa, wb, lower, limit, cap, seed, dual_a, dual_b, w):
307
+ best = feasible(a, b, na, adj_b, wa + wb, lower, seed, w[0])
308
+ if wa + wb - 2 * best == lower:
309
+ return lower, 0
310
+ return explore(a, b, na, nb, adj_b, wa, wb, lower, limit, cap, seed, dual_a, dual_b,
311
+ w, best, 0, 1, w[0])
312
+
313
+ return bounds, search, feasible, explore
314
+
315
+
316
+ gpu_objective_bound = cuda.jit(device=True)(_objective_bound)
317
+ gpu_bounds, gpu_search, gpu_feasible, gpu_explore = _specialize(cuda.jit(device=True), gpu=True)
318
+
319
+
320
+ def pack(graphs):
321
+ """One ragged, contiguous library. Adjacency and neighbor indices are graph-local."""
322
+ offsets = np.zeros((len(graphs) + 1, 5), np.int64)
323
+ for i, g in enumerate(graphs):
324
+ offsets[i + 1, :3] = offsets[i, :3] + (len(g.elements), g.adjacency.size, len(g.neighbors))
325
+ offsets[i, 3:] = g.weight, g.weight_gcd
326
+ return (offsets, np.concatenate([g.vertices for g in graphs]),
327
+ np.concatenate([g.adjacency.ravel() for g in graphs]),
328
+ np.concatenate([g.neighbors for g in graphs]))
329
+
330
+
331
+ @cuda.jit
332
+ def filter_kernel(meta, vertices, neighbors, pairs, limit, stronger, costs, work, seeds, lower):
333
+ k = cuda.grid(1)
334
+ if k < len(pairs):
335
+ i, j = pairs[k, 0], pairs[k, 1]
336
+ if i < 0 or j < 0 or i == j:
337
+ lower[k] = 0
338
+ return
339
+ a = vertices[meta[i, 0]:meta[i + 1, 0]]
340
+ b = vertices[meta[j, 0]:meta[j + 1, 0]]
341
+ na = neighbors[meta[i, 2]:meta[i + 1, 2]]
342
+ nb = neighbors[meta[j, 2]:meta[j + 1, 2]]
343
+ lower[k] = gpu_bounds(a, b, na, nb, meta[i, 3] + meta[j, 3], limit,
344
+ stronger, costs[k], work[k], seeds[k, 0], seeds[k, 1], seeds[k, 2])
345
+
346
+
347
+ @cuda.jit
348
+ def solve_kernel(meta, vertices, adjacency, neighbors, pairs, threshold, stronger, atom_cap,
349
+ frame_cap, lower, seeds, work, scores, exact, pending, count):
350
+ k = cuda.blockIdx.x
351
+ lane = cuda.threadIdx.x
352
+ stride = cuda.blockDim.x
353
+ i, j = pairs[k, 0], pairs[k, 1]
354
+ if i < 0 or j < 0 or i == j:
355
+ if lane == 0:
356
+ valid = i >= 0 and j >= 0
357
+ scores[k] = 0.0 if valid else np.nan
358
+ exact[k] = valid
359
+ return
360
+ limit = threshold * 2
361
+ lb = lower[k]
362
+ if lb > limit:
363
+ if lane == 0:
364
+ scores[k] = lb / 2 if stronger else threshold
365
+ exact[k] = False
366
+ return
367
+ a = vertices[meta[i, 0]:meta[i + 1, 0]]
368
+ b = vertices[meta[j, 0]:meta[j + 1, 0]]
369
+ distance = -1
370
+ if max(len(a), len(b)) <= atom_cap:
371
+ lb = gpu_objective_bound(meta[i, 3] + meta[j, 3], lb, meta[i, 4], meta[j, 4])
372
+ if lb > limit:
373
+ if lane == 0:
374
+ scores[k], exact[k] = threshold, False
375
+ return
376
+ na = neighbors[meta[i, 2]:meta[i + 1, 2]]
377
+ nb = neighbors[meta[j, 2]:meta[j + 1, 2]]
378
+ adj = adjacency[meta[j, 1]:meta[j + 1, 1]]
379
+ if max(len(a), len(b)) <= 64 and max(len(na), len(nb)) <= 256:
380
+ # Cache graph data once per pair for the cooperating search lanes.
381
+ vertex_cache = cuda.shared.array((2, 64, 5), np.int32)
382
+ neighbor_cache = cuda.shared.array((2, 256, 3), np.int32)
383
+ bond_cache = cuda.shared.array(4096, np.uint8)
384
+ prices = cuda.shared.array((3, 64), np.int32)
385
+ stack = cuda.shared.array((8, 7, 65), np.int32)
386
+ shared = cuda.shared.array(3, np.int32)
387
+ for v in range(lane, max(len(a), len(b)), stride):
388
+ for col in range(5):
389
+ if v < len(a):
390
+ vertex_cache[0, v, col] = a[v, col]
391
+ if v < len(b):
392
+ vertex_cache[1, v, col] = b[v, col]
393
+ if v < len(a):
394
+ prices[0, v] = seeds[k, 0, v]
395
+ prices[1, v] = seeds[k, 1, v]
396
+ if v < len(b):
397
+ prices[2, v] = seeds[k, 2, v]
398
+ for e in range(lane, max(len(na), len(nb)), stride):
399
+ for col in range(3):
400
+ if e < len(na):
401
+ neighbor_cache[0, e, col] = na[e, col]
402
+ if e < len(nb):
403
+ neighbor_cache[1, e, col] = nb[e, col]
404
+ for e in range(lane, len(adj), stride):
405
+ bond_cache[e] = adj[e]
406
+ cuda.syncthreads()
407
+ local_a, local_b = vertex_cache[0, :len(a)], vertex_cache[1, :len(b)]
408
+ wa, wb = meta[i, 3], meta[j, 3]
409
+ if lane == 0:
410
+ shared[0] = shared[2] = 0
411
+ shared[1] = gpu_feasible(local_a, local_b, neighbor_cache[0], bond_cache,
412
+ wa + wb, lb, prices[0], stack[0, 0])
413
+ cuda.syncthreads()
414
+ # Independent lanes enumerate disjoint root choices. All lanes
415
+ # share the incumbent and one frame budget for the entire pair.
416
+ lanes = min(stride, 8)
417
+ initial = cuda.atomic.add(shared, 1, 0)
418
+ if lane < lanes and wa + wb - 2 * initial > lb:
419
+ distance, _ = gpu_explore(local_a, local_b, neighbor_cache[0], neighbor_cache[1],
420
+ bond_cache, wa, wb, lb, limit, frame_cap, prices[0],
421
+ prices[1], prices[2], stack[lane], initial, lane, lanes, shared)
422
+ if distance < 0:
423
+ cuda.atomic.max(shared, 2, 1)
424
+ else:
425
+ cuda.atomic.max(shared, 1, (wa + wb - distance) // 2)
426
+ cuda.syncthreads()
427
+ distance = wa + wb - 2 * shared[1]
428
+ if shared[2] and distance > lb:
429
+ distance = -1
430
+ elif lane == 0:
431
+ distance, _ = gpu_search(a, b, na, nb, adj, meta[i, 3], meta[j, 3], lb,
432
+ limit, frame_cap, seeds[k, 0], seeds[k, 1], seeds[k, 2], work[k])
433
+ if lane == 0:
434
+ if distance < 0:
435
+ slot = cuda.atomic.add(count, 0, 1)
436
+ pending[slot] = k
437
+ else:
438
+ exact[k] = distance <= limit
439
+ scores[k] = distance / 2 if distance <= limit else threshold
@@ -1 +0,0 @@
1
- __version__ = "1.0.0"
File without changes
File without changes
File without changes