simms-gpu 1.0.0__py3-none-any.whl
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/__init__.py +6 -0
- simms/__version__.py +1 -0
- simms/peaks.py +174 -0
- simms/similarity/CudaBinnedEmbeddingSimilarity.py +103 -0
- simms/similarity/CudaCosineGreedy.py +230 -0
- simms/similarity/CudaCosineLinear.py +382 -0
- simms/similarity/CudaEntropyGreedy.py +184 -0
- simms/similarity/CudaFingerprintSimilarity.py +207 -0
- simms/similarity/CudaModifiedCosine.py +10 -0
- simms/similarity/CudaNeutralLossesCosine.py +23 -0
- simms/similarity/CudaTransitiveAlignment.py +295 -0
- simms/similarity/__init__.py +24 -0
- simms/similarity/_base.py +178 -0
- simms/similarity/_transitive_peaks.py +270 -0
- simms/similarity/spectrum_similarity_functions.py +312 -0
- simms/similarity/vector_similarity_functions.py +202 -0
- simms/utils.py +126 -0
- simms_gpu-1.0.0.dist-info/METADATA +225 -0
- simms_gpu-1.0.0.dist-info/RECORD +21 -0
- simms_gpu-1.0.0.dist-info/WHEEL +4 -0
- simms_gpu-1.0.0.dist-info/licenses/LICENSE +20 -0
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
"""Tiled GPU similarity of matchms molecular fingerprints."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
from itertools import chain
|
|
5
|
+
|
|
6
|
+
import numpy as np
|
|
7
|
+
import torch
|
|
8
|
+
from matchms import Fingerprints
|
|
9
|
+
from matchms.similarity import FingerprintSimilarity
|
|
10
|
+
from scipy import sparse
|
|
11
|
+
|
|
12
|
+
from ..peaks import PeakArrays
|
|
13
|
+
from .vector_similarity_functions import _TiledVectorSimilarity
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class CudaFingerprintSimilarity(_TiledVectorSimilarity, FingerprintSimilarity):
|
|
17
|
+
"""Compute one score per pair of valid unique compounds in matchms fingerprint order.
|
|
18
|
+
|
|
19
|
+
Pass spectra and a chemap generator, existing Fingerprints containers, or
|
|
20
|
+
precomputed 2D arrays with fingerprint_generator=None. Jaccard aliases
|
|
21
|
+
generalized Tanimoto. Dice uses twice the sum of minima divided by the sum
|
|
22
|
+
of both vectors (two empty vectors score zero for Dice and one for Tanimoto).
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
def __init__(
|
|
26
|
+
self,
|
|
27
|
+
fingerprint_generator=None,
|
|
28
|
+
similarity_measure="tanimoto",
|
|
29
|
+
set_empty_scores="nan",
|
|
30
|
+
ignore_stereochemistry=False,
|
|
31
|
+
count=False,
|
|
32
|
+
folded=True,
|
|
33
|
+
return_csr=False,
|
|
34
|
+
invalid_policy="raise",
|
|
35
|
+
*,
|
|
36
|
+
batch_size=2048,
|
|
37
|
+
precision="float64",
|
|
38
|
+
**fingerprint_config_kwargs,
|
|
39
|
+
):
|
|
40
|
+
if similarity_measure not in ("cosine", "tanimoto", "jaccard", "dice"):
|
|
41
|
+
raise ValueError("Unknown similarity measure")
|
|
42
|
+
if isinstance(fingerprint_generator, dict):
|
|
43
|
+
from rdkit.Chem.rdFingerprintGenerator import FingerprintGeneratorFromJSON
|
|
44
|
+
|
|
45
|
+
fingerprint_generator = FingerprintGeneratorFromJSON(json.dumps(fingerprint_generator))
|
|
46
|
+
weights = fingerprint_config_kwargs.get("unfolded_weights")
|
|
47
|
+
if weights is not None:
|
|
48
|
+
# JSON object keys are strings. chemap looks up integer feature IDs.
|
|
49
|
+
fingerprint_config_kwargs["unfolded_weights"] = {int(k): float(v) for k, v in weights.items()}
|
|
50
|
+
super().__init__(
|
|
51
|
+
fingerprint_generator,
|
|
52
|
+
"cosine" if similarity_measure == "cosine" else "tanimoto",
|
|
53
|
+
set_empty_scores,
|
|
54
|
+
ignore_stereochemistry,
|
|
55
|
+
count,
|
|
56
|
+
folded,
|
|
57
|
+
return_csr,
|
|
58
|
+
invalid_policy,
|
|
59
|
+
**fingerprint_config_kwargs,
|
|
60
|
+
)
|
|
61
|
+
self.similarity_measure = similarity_measure
|
|
62
|
+
self._configure_tiles(batch_size, precision)
|
|
63
|
+
|
|
64
|
+
@property
|
|
65
|
+
def _metric(self):
|
|
66
|
+
return self.similarity_measure
|
|
67
|
+
|
|
68
|
+
def to_dict(self):
|
|
69
|
+
parameters = super().to_dict()
|
|
70
|
+
if self.fingerprint_generator is not None:
|
|
71
|
+
if not hasattr(self.fingerprint_generator, "ToJSON"):
|
|
72
|
+
raise TypeError("Serializing a fingerprint generator requires RDKit's ToJSON support")
|
|
73
|
+
parameters["fingerprint_generator"] = json.loads(self.fingerprint_generator.ToJSON())
|
|
74
|
+
config = dict(parameters.pop("fingerprint_config_kwargs"))
|
|
75
|
+
if config.get("folded_weights") is not None:
|
|
76
|
+
config["folded_weights"] = np.asarray(config["folded_weights"]).tolist()
|
|
77
|
+
return {**parameters, **config}
|
|
78
|
+
|
|
79
|
+
def _vectors(self, data):
|
|
80
|
+
if isinstance(data, Fingerprints):
|
|
81
|
+
return self._fingerprint_matrix(data)
|
|
82
|
+
if (
|
|
83
|
+
isinstance(data, torch.Tensor)
|
|
84
|
+
or sparse.issparse(data)
|
|
85
|
+
or (isinstance(data, np.ndarray) and data.ndim == 2)
|
|
86
|
+
):
|
|
87
|
+
if self.fingerprint_generator is not None:
|
|
88
|
+
raise ValueError("Precomputed arrays require fingerprint_generator=None")
|
|
89
|
+
if data.ndim != 2:
|
|
90
|
+
raise ValueError("Expected a 2D fingerprint matrix")
|
|
91
|
+
if isinstance(data, torch.Tensor) and data.layout == torch.sparse_csr:
|
|
92
|
+
data = data.detach().cpu()
|
|
93
|
+
return sparse.csr_matrix(
|
|
94
|
+
(data.values().numpy(), data.col_indices().numpy(), data.crow_indices().numpy()),
|
|
95
|
+
shape=tuple(data.shape),
|
|
96
|
+
)
|
|
97
|
+
return data.tocsr() if sparse.issparse(data) else data
|
|
98
|
+
if not hasattr(data, "__len__"):
|
|
99
|
+
data = list(data)
|
|
100
|
+
if len(data) == 0:
|
|
101
|
+
# Empty spectra have no feature width until the other axis is prepared.
|
|
102
|
+
return None
|
|
103
|
+
if isinstance(data, PeakArrays):
|
|
104
|
+
raise ValueError("Generating fingerprints requires spectra with chemical metadata")
|
|
105
|
+
if self.fingerprint_generator is None:
|
|
106
|
+
raise ValueError("Provide a fingerprint_generator for spectra or pass a 2D fingerprint matrix")
|
|
107
|
+
return self._fingerprint_matrix(self._compute_fingerprints_from_spectra(data))
|
|
108
|
+
|
|
109
|
+
@staticmethod
|
|
110
|
+
def _unfolded_matrices(left, right):
|
|
111
|
+
# chemap returns feature IDs for binary rows, and (IDs, counts) for count rows.
|
|
112
|
+
# Build a common vocabulary before scoring disjoint compound collections.
|
|
113
|
+
rows = left if left is right else chain(left or (), right or ())
|
|
114
|
+
keys, values, offsets = [], [], [0]
|
|
115
|
+
for row in rows:
|
|
116
|
+
bits, weights = row if isinstance(row, tuple) else (row, np.ones(len(row)))
|
|
117
|
+
keys.append(bits)
|
|
118
|
+
values.append(weights)
|
|
119
|
+
offsets.append(offsets[-1] + len(bits))
|
|
120
|
+
vocabulary, columns = np.unique(np.concatenate(keys), return_inverse=True)
|
|
121
|
+
matrix = sparse.csr_matrix((np.concatenate(values), columns, offsets),
|
|
122
|
+
shape=(len(offsets) - 1, len(vocabulary)))
|
|
123
|
+
if left is right:
|
|
124
|
+
return matrix, matrix
|
|
125
|
+
split = len(left) if left is not None else 0
|
|
126
|
+
return matrix[:split], matrix[split:]
|
|
127
|
+
|
|
128
|
+
def _inputs(self, spectra_1, spectra_2):
|
|
129
|
+
left = self._vectors(spectra_1)
|
|
130
|
+
right = left if spectra_2 is None or spectra_1 is spectra_2 else self._vectors(spectra_2)
|
|
131
|
+
if isinstance(left, list) or isinstance(right, list):
|
|
132
|
+
if any(side is not None and not isinstance(side, list) for side in (left, right)):
|
|
133
|
+
raise ValueError("Both inputs must use unfolded fingerprints with feature IDs")
|
|
134
|
+
left, right = self._unfolded_matrices(left, right)
|
|
135
|
+
if left is None:
|
|
136
|
+
left = np.empty((0, 0 if right is None else right.shape[1]))
|
|
137
|
+
if right is None:
|
|
138
|
+
right = np.empty((0, left.shape[1]))
|
|
139
|
+
return left, right, spectra_2 is None
|
|
140
|
+
|
|
141
|
+
@staticmethod
|
|
142
|
+
def _source(spectra, fingerprints):
|
|
143
|
+
if spectra is not None and fingerprints is not None:
|
|
144
|
+
raise ValueError("Provide either spectra or fingerprints for each input, not both")
|
|
145
|
+
return spectra if fingerprints is None else fingerprints
|
|
146
|
+
|
|
147
|
+
def matrix(
|
|
148
|
+
self,
|
|
149
|
+
spectra_1=None,
|
|
150
|
+
spectra_2=None,
|
|
151
|
+
fingerprints_1=None,
|
|
152
|
+
fingerprints_2=None,
|
|
153
|
+
score_fields=None,
|
|
154
|
+
progress_bar=True,
|
|
155
|
+
array_type="scores",
|
|
156
|
+
):
|
|
157
|
+
left = self._source(spectra_1, fingerprints_1)
|
|
158
|
+
right = self._source(spectra_2, fingerprints_2)
|
|
159
|
+
if left is None:
|
|
160
|
+
raise ValueError("Either spectra_1 or fingerprints_1 must be provided.")
|
|
161
|
+
return super().matrix(left, right, score_fields, progress_bar, array_type)
|
|
162
|
+
|
|
163
|
+
def sparse_matrix(
|
|
164
|
+
self,
|
|
165
|
+
spectra_1=None,
|
|
166
|
+
spectra_2=None,
|
|
167
|
+
idx_row=None,
|
|
168
|
+
idx_col=None,
|
|
169
|
+
score_fields=None,
|
|
170
|
+
score_filter=None,
|
|
171
|
+
progress_bar=True,
|
|
172
|
+
*,
|
|
173
|
+
min_score=None,
|
|
174
|
+
fingerprints_1=None,
|
|
175
|
+
fingerprints_2=None,
|
|
176
|
+
):
|
|
177
|
+
left = self._source(spectra_1, fingerprints_1)
|
|
178
|
+
right = self._source(spectra_2, fingerprints_2)
|
|
179
|
+
if left is None:
|
|
180
|
+
raise ValueError("Either spectra_1 or fingerprints_1 must be provided.")
|
|
181
|
+
return super().sparse_matrix(left, right, idx_row, idx_col, score_fields, score_filter,
|
|
182
|
+
progress_bar, min_score=min_score)
|
|
183
|
+
|
|
184
|
+
def pair(self, spectrum_1, spectrum_2):
|
|
185
|
+
"""Compare two vectors, single-row containers, or two spectra with a generator.
|
|
186
|
+
|
|
187
|
+
This extends matchms 1.0.0, whose FingerprintSimilarity.pair raises
|
|
188
|
+
NotImplementedError. Invalid spectra raise the same error as matrix().
|
|
189
|
+
"""
|
|
190
|
+
|
|
191
|
+
def single(value):
|
|
192
|
+
if isinstance(value, Fingerprints):
|
|
193
|
+
if value.fingerprint_count != 1:
|
|
194
|
+
raise ValueError("pair expects a single fingerprint per input")
|
|
195
|
+
return value
|
|
196
|
+
if hasattr(value, "peaks"):
|
|
197
|
+
return [value]
|
|
198
|
+
array = value if isinstance(value, torch.Tensor) or sparse.issparse(value) else np.asarray(value)
|
|
199
|
+
if array.ndim == 1:
|
|
200
|
+
return array.reshape(1, -1)
|
|
201
|
+
if array.ndim != 2 or array.shape[0] != 1:
|
|
202
|
+
raise ValueError("pair expects a single fingerprint per input")
|
|
203
|
+
return array
|
|
204
|
+
|
|
205
|
+
return self.matrix(
|
|
206
|
+
single(spectrum_1), single(spectrum_2), progress_bar=False, array_type="numpy"
|
|
207
|
+
).reshape(())
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
from .CudaCosineGreedy import _GreedySimilarity
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class CudaModifiedCosineGreedy(_GreedySimilarity):
|
|
5
|
+
"""matchms modified greedy cosine using direct and precursor-shifted candidates."""
|
|
6
|
+
|
|
7
|
+
modified = True
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
CudaModifiedCosine = CudaModifiedCosineGreedy
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"""CUDA implementation of matchms NeutralLossesCosine."""
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
|
|
5
|
+
from .CudaCosineGreedy import _GreedySimilarity
|
|
6
|
+
from .spectrum_similarity_functions import NEUTRAL_LOSS_ONLY, exact_score
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class CudaNeutralLossesCosine(_GreedySimilarity):
|
|
10
|
+
"""Greedy cosine using only precursor-shifted matches between fragment peaks."""
|
|
11
|
+
|
|
12
|
+
modified = NEUTRAL_LOSS_ONLY
|
|
13
|
+
|
|
14
|
+
def _recover(self, left, right, i, j):
|
|
15
|
+
def row(peaks, index):
|
|
16
|
+
n = peaks.lengths[index]
|
|
17
|
+
return np.column_stack((peaks.mz[index, :n], peaks.intensities[index, :n]))
|
|
18
|
+
|
|
19
|
+
delta = left.precursor_mz[i] - right.precursor_mz[j]
|
|
20
|
+
return exact_score(
|
|
21
|
+
row(left, i), row(right, j), [delta], self.tolerance, self.mz_power,
|
|
22
|
+
self.intensity_power, raise_zero_division=True,
|
|
23
|
+
)
|
|
@@ -0,0 +1,295 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT
|
|
2
|
+
"""Transitive alignment following Wang et al., JASMS 2024, doi:10.1021/jasms.4c00208."""
|
|
3
|
+
|
|
4
|
+
from collections import deque
|
|
5
|
+
from dataclasses import asdict, dataclass
|
|
6
|
+
from itertools import chain, islice, pairwise
|
|
7
|
+
|
|
8
|
+
import numpy as np
|
|
9
|
+
from matchms import Scores
|
|
10
|
+
from scipy.sparse import coo_array, issparse
|
|
11
|
+
|
|
12
|
+
from ..peaks import PeakArrays
|
|
13
|
+
from ._transitive_peaks import PeakAligner
|
|
14
|
+
from .CudaModifiedCosine import CudaModifiedCosineGreedy
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@dataclass(frozen=True)
|
|
18
|
+
class AlignmentEdge:
|
|
19
|
+
row: int
|
|
20
|
+
col: int
|
|
21
|
+
score: float
|
|
22
|
+
matches: int
|
|
23
|
+
hops: int
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@dataclass
|
|
27
|
+
class TransitiveAlignmentResult:
|
|
28
|
+
"""Undirected edges occur once (row < col). Paths include every attempted bridge.
|
|
29
|
+
|
|
30
|
+
peak_pairs, when requested, contains the final greedy assignment for each
|
|
31
|
+
retained direct or transitive edge, indexed into the *preprocessed* peak rows.
|
|
32
|
+
Pairs are ordered by source peak index.
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
n_spectra: int
|
|
36
|
+
direct_edges: list[AlignmentEdge]
|
|
37
|
+
transitive_edges: list[AlignmentEdge]
|
|
38
|
+
paths: dict[tuple[int, int], tuple[int, ...]]
|
|
39
|
+
peak_pairs: dict[tuple[int, int], tuple[tuple[int, int], ...]] | None
|
|
40
|
+
|
|
41
|
+
def to_dict(self):
|
|
42
|
+
"""Serialize tuple-keyed mappings as records with explicit row/col fields."""
|
|
43
|
+
return {
|
|
44
|
+
"n_spectra": self.n_spectra,
|
|
45
|
+
"direct_edges": [asdict(e) for e in self.direct_edges],
|
|
46
|
+
"transitive_edges": [asdict(e) for e in self.transitive_edges],
|
|
47
|
+
"paths": [{"row": u, "col": v, "path": list(p)} for (u, v), p in self.paths.items()],
|
|
48
|
+
"peak_pairs": None
|
|
49
|
+
if self.peak_pairs is None
|
|
50
|
+
else [
|
|
51
|
+
{"row": u, "col": v, "pairs": [list(pair) for pair in pairs]}
|
|
52
|
+
for (u, v), pairs in self.peak_pairs.items()
|
|
53
|
+
],
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
def to_scores(self, *, sparse=False, transitive_only=False, min_score=None):
|
|
57
|
+
edges = self.transitive_edges if transitive_only else chain(self.direct_edges, self.transitive_edges)
|
|
58
|
+
rows, cols, scores, counts = [], [], [], []
|
|
59
|
+
for e in edges:
|
|
60
|
+
if min_score is not None and not e.score >= min_score:
|
|
61
|
+
continue
|
|
62
|
+
rows.extend((e.row, e.col))
|
|
63
|
+
cols.extend((e.col, e.row))
|
|
64
|
+
scores.extend((e.score, e.score))
|
|
65
|
+
counts.extend((e.matches, e.matches))
|
|
66
|
+
shape = (self.n_spectra, self.n_spectra)
|
|
67
|
+
data = {}
|
|
68
|
+
for name, values, dtype in (("score", scores, np.float64), ("matches", counts, np.intp)):
|
|
69
|
+
coo = coo_array((np.asarray(values, dtype=dtype), (rows, cols)), shape=shape)
|
|
70
|
+
data[name] = coo if sparse else coo.toarray()
|
|
71
|
+
return Scores(data)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _paths(edges, max_hops):
|
|
75
|
+
# FIFO order finalizes every predecessor's optimal weight before visiting
|
|
76
|
+
# the next layer. Each traversal only touches the source's component.
|
|
77
|
+
neighbors = {}
|
|
78
|
+
for e in edges:
|
|
79
|
+
neighbors.setdefault(e.row, []).append((e.col, e.score))
|
|
80
|
+
neighbors.setdefault(e.col, []).append((e.row, e.score))
|
|
81
|
+
for source in sorted(neighbors):
|
|
82
|
+
depth, weight, parent = {source: 0}, {source: 0.0}, {}
|
|
83
|
+
queue = deque([source])
|
|
84
|
+
while queue:
|
|
85
|
+
u = queue.popleft()
|
|
86
|
+
d = depth[u] + 1
|
|
87
|
+
if max_hops is not None and d > max_hops:
|
|
88
|
+
continue
|
|
89
|
+
for v, score in neighbors[u]:
|
|
90
|
+
total = weight[u] + score
|
|
91
|
+
if v not in depth:
|
|
92
|
+
depth[v], weight[v], parent[v] = d, total, u
|
|
93
|
+
queue.append(v)
|
|
94
|
+
elif depth[v] == d and (total > weight[v] or (total == weight[v] and u < parent[v])):
|
|
95
|
+
weight[v], parent[v] = total, u
|
|
96
|
+
for v, d in depth.items():
|
|
97
|
+
if v > source and d >= 2:
|
|
98
|
+
path = [v]
|
|
99
|
+
while path[-1] != source:
|
|
100
|
+
path.append(parent[path[-1]])
|
|
101
|
+
yield tuple(reversed(path))
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _batches(items, size):
|
|
105
|
+
items = iter(items)
|
|
106
|
+
while batch := list(islice(items, size)):
|
|
107
|
+
yield batch
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _precomputed(base, n, min_score, min_matches):
|
|
111
|
+
if isinstance(base, Scores):
|
|
112
|
+
if not {"score", "matches"}.issubset(base.score_fields):
|
|
113
|
+
raise ValueError("base_scores must supply both score and matches")
|
|
114
|
+
field = base.to_coo if base.is_sparse else base.to_array
|
|
115
|
+
scores, counts = field("score"), field("matches")
|
|
116
|
+
else:
|
|
117
|
+
try:
|
|
118
|
+
scores, counts = base["score"], base["matches"]
|
|
119
|
+
except (IndexError, KeyError, TypeError, ValueError) as exc:
|
|
120
|
+
raise ValueError("base_scores must supply both score and matches") from exc
|
|
121
|
+
if scores.shape != (n, n) or counts.shape != (n, n):
|
|
122
|
+
raise ValueError("base_scores shape must match the number of spectra on both axes")
|
|
123
|
+
if issparse(scores) != issparse(counts):
|
|
124
|
+
raise ValueError("base score and match fields must both be sparse or both dense")
|
|
125
|
+
if issparse(scores):
|
|
126
|
+
# COO fields can arrive in different orders and have different sparsity.
|
|
127
|
+
# Consider explicitly stored coordinates only, including explicit zeros.
|
|
128
|
+
scores, counts = scores.tocsr(), counts.tocsr()
|
|
129
|
+
s, m = scores.tocoo(), counts.tocoo()
|
|
130
|
+
keys = np.union1d(s.row.astype(np.int64) * n + s.col, m.row.astype(np.int64) * n + m.col)
|
|
131
|
+
if not keys.size:
|
|
132
|
+
return []
|
|
133
|
+
row, col = np.divmod(keys, n)
|
|
134
|
+
sv, mv = np.asarray(scores[row, col]).ravel(), np.asarray(counts[row, col]).ravel()
|
|
135
|
+
keep = (row != col) & (sv >= min_score) & (mv >= min_matches)
|
|
136
|
+
row, col, sv, mv = row[keep], col[keep], sv[keep], mv[keep]
|
|
137
|
+
else:
|
|
138
|
+
row, col = np.nonzero((scores >= min_score) & (counts >= min_matches))
|
|
139
|
+
off = row != col
|
|
140
|
+
row, col = row[off], col[off]
|
|
141
|
+
sv, mv = scores[row, col], counts[row, col]
|
|
142
|
+
edges = {}
|
|
143
|
+
for u, v, score, matches in zip(row, col, sv, mv):
|
|
144
|
+
if not np.isfinite(score) or not np.isfinite(matches) or int(matches) != matches:
|
|
145
|
+
raise ValueError("retained direct edges need finite scores and integer match counts")
|
|
146
|
+
key = tuple(sorted((int(u), int(v))))
|
|
147
|
+
edge = AlignmentEdge(*key, float(score), int(matches), 1)
|
|
148
|
+
previous = edges.get(key)
|
|
149
|
+
if previous is not None and previous != edge:
|
|
150
|
+
# A triangular dense matrix uses zeros for the missing direction.
|
|
151
|
+
if (edge.score, edge.matches) == (0, 0):
|
|
152
|
+
continue
|
|
153
|
+
if (previous.score, previous.matches) != (0, 0):
|
|
154
|
+
raise ValueError(f"inconsistent mirrored base scores for {key}")
|
|
155
|
+
edges[key] = edge
|
|
156
|
+
return [edges[key] for key in sorted(edges)]
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
class CudaTransitiveAlignment:
|
|
160
|
+
"""Build a molecular network on a single collection of spectra.
|
|
161
|
+
|
|
162
|
+
Pass base_scores to any entry point to reuse a modified-cosine matrix in
|
|
163
|
+
the same spectrum order and preprocessing. Accepts matchms Scores, a
|
|
164
|
+
structured array, or a mapping of dense or sparse score and matches fields.
|
|
165
|
+
Either triangle or a symmetric matrix is accepted. Self edges are omitted.
|
|
166
|
+
max_hops counts edges. Equal-hop, equal-sum paths prefer the smaller final
|
|
167
|
+
predecessor recursively. On equal peak products, shifted candidates precede
|
|
168
|
+
unshifted candidates, followed by bridge-only candidates (descending source
|
|
169
|
+
index). The direct alignment in row < col orientation is inverted on reverse
|
|
170
|
+
traversal. n_max_peaks and match_limit bound GPU scratch; overflow uses the
|
|
171
|
+
complete preprocessed spectra on the CPU.
|
|
172
|
+
"""
|
|
173
|
+
|
|
174
|
+
def __init__(
|
|
175
|
+
self,
|
|
176
|
+
tolerance=0.01,
|
|
177
|
+
mz_power=0.0,
|
|
178
|
+
intensity_power=1.0,
|
|
179
|
+
remove_precursor=True,
|
|
180
|
+
offset_to_precursor=-1.6,
|
|
181
|
+
noise_cutoff=0.01,
|
|
182
|
+
min_direct_score=0.7,
|
|
183
|
+
min_direct_matches=6,
|
|
184
|
+
min_transitive_score=0.0,
|
|
185
|
+
max_hops=None,
|
|
186
|
+
batch_size=2048,
|
|
187
|
+
precision="float64",
|
|
188
|
+
*,
|
|
189
|
+
n_max_peaks=None,
|
|
190
|
+
match_limit=2048,
|
|
191
|
+
):
|
|
192
|
+
self.direct = CudaModifiedCosineGreedy(
|
|
193
|
+
tolerance=tolerance,
|
|
194
|
+
mz_power=mz_power,
|
|
195
|
+
intensity_power=intensity_power,
|
|
196
|
+
remove_precursor=remove_precursor,
|
|
197
|
+
offset_to_precursor=offset_to_precursor,
|
|
198
|
+
noise_cutoff=noise_cutoff,
|
|
199
|
+
batch_size=batch_size,
|
|
200
|
+
precision=precision,
|
|
201
|
+
n_max_peaks=n_max_peaks,
|
|
202
|
+
match_limit=match_limit,
|
|
203
|
+
)
|
|
204
|
+
self.min_direct_score = float(min_direct_score)
|
|
205
|
+
self.min_transitive_score = float(min_transitive_score)
|
|
206
|
+
if not np.all(np.isfinite([self.min_direct_score, self.min_transitive_score])):
|
|
207
|
+
raise ValueError("score thresholds must be finite")
|
|
208
|
+
for name, value in (("min_direct_matches", min_direct_matches), ("max_hops", max_hops)):
|
|
209
|
+
if name == "max_hops" and value is None:
|
|
210
|
+
continue
|
|
211
|
+
if isinstance(value, (bool, np.bool_)) or not isinstance(value, (int, np.integer)) or value < 0:
|
|
212
|
+
raise ValueError(f"{name} must be a non-negative integer")
|
|
213
|
+
self.min_direct_matches = min_direct_matches
|
|
214
|
+
self.max_hops = max_hops
|
|
215
|
+
|
|
216
|
+
def _direct_edges(self, peaks, progress_bar):
|
|
217
|
+
# Filter upper-triangle tiles before constructing any per-edge objects.
|
|
218
|
+
edges = []
|
|
219
|
+
if len(peaks) < 2:
|
|
220
|
+
return edges
|
|
221
|
+
tiles = self.direct._tiles(peaks, peaks, True, None, progress_bar)
|
|
222
|
+
for rows, cols, values in self.direct._filtered_tiles(
|
|
223
|
+
tiles, True, self.min_direct_score, self.min_direct_matches, diagonal=1
|
|
224
|
+
):
|
|
225
|
+
edges.extend(
|
|
226
|
+
AlignmentEdge(int(i), int(j), float(score), int(matches), 1)
|
|
227
|
+
for i, j, (score, matches) in zip(rows, cols, values)
|
|
228
|
+
)
|
|
229
|
+
return sorted(edges, key=lambda e: (e.row, e.col))
|
|
230
|
+
|
|
231
|
+
def align(self, spectra, *, base_scores=None, return_peak_pairs=False, progress_bar=False):
|
|
232
|
+
"""Return paths, direct and new edges, and optionally their endpoint peak indices."""
|
|
233
|
+
method = self.direct
|
|
234
|
+
peaks = PeakArrays.from_spectra(
|
|
235
|
+
spectra, True, method.remove_precursor, method.offset_to_precursor, method.noise_cutoff
|
|
236
|
+
)
|
|
237
|
+
direct = (
|
|
238
|
+
self._direct_edges(peaks, progress_bar)
|
|
239
|
+
if base_scores is None
|
|
240
|
+
else _precomputed(base_scores, len(peaks), self.min_direct_score, self.min_direct_matches)
|
|
241
|
+
)
|
|
242
|
+
result = TransitiveAlignmentResult(len(peaks), direct, [], {}, {} if return_peak_pairs else None)
|
|
243
|
+
paths = _paths(direct, self.max_hops)
|
|
244
|
+
first = next(paths, None)
|
|
245
|
+
if first is None and (not direct or not return_peak_pairs):
|
|
246
|
+
return result
|
|
247
|
+
|
|
248
|
+
aligner = PeakAligner(peaks, method)
|
|
249
|
+
offsets = {}
|
|
250
|
+
size = 0
|
|
251
|
+
for e in direct:
|
|
252
|
+
for u, v in ((e.row, e.col), (e.col, e.row)):
|
|
253
|
+
offsets[u, v] = size
|
|
254
|
+
size += int(peaks.lengths[u])
|
|
255
|
+
maps = np.full(size, -1, dtype=np.int32)
|
|
256
|
+
for batch in _batches(((e.row, e.col) for e in direct), method.batch_size):
|
|
257
|
+
assignments = aligner.batch(batch, np.zeros(len(batch) + 1, dtype=np.int64), [])
|
|
258
|
+
for (u, v), (_, _, pairs) in zip(batch, assignments):
|
|
259
|
+
for a, b in pairs:
|
|
260
|
+
maps[offsets[u, v] + a] = b
|
|
261
|
+
maps[offsets[v, u] + b] = a
|
|
262
|
+
if return_peak_pairs:
|
|
263
|
+
result.peak_pairs[u, v] = pairs
|
|
264
|
+
if first is None:
|
|
265
|
+
return result
|
|
266
|
+
aligner.set_maps(maps)
|
|
267
|
+
for batch in _batches(chain((first,), paths), method.batch_size):
|
|
268
|
+
endpoints, steps, starts = [], [], [0]
|
|
269
|
+
for path in batch:
|
|
270
|
+
u, v = path[0], path[-1]
|
|
271
|
+
result.paths[u, v] = path
|
|
272
|
+
endpoints.append((u, v))
|
|
273
|
+
steps.extend(offsets[a, b] for a, b in pairwise(path))
|
|
274
|
+
starts.append(len(steps))
|
|
275
|
+
assignments = aligner.batch(endpoints, starts, steps, return_pairs=return_peak_pairs)
|
|
276
|
+
for path, (score, matches, pairs) in zip(batch, assignments):
|
|
277
|
+
if matches and score >= self.min_transitive_score:
|
|
278
|
+
u, v = path[0], path[-1]
|
|
279
|
+
result.transitive_edges.append(AlignmentEdge(u, v, score, matches, len(path) - 1))
|
|
280
|
+
if return_peak_pairs:
|
|
281
|
+
result.peak_pairs[u, v] = pairs
|
|
282
|
+
return result
|
|
283
|
+
|
|
284
|
+
def matrix(self, spectra, *, base_scores=None, transitive_only=False, progress_bar=False):
|
|
285
|
+
"""Symmetric dense matchms Scores with a zero diagonal."""
|
|
286
|
+
return self.align(spectra, base_scores=base_scores, progress_bar=progress_bar).to_scores(
|
|
287
|
+
transitive_only=transitive_only
|
|
288
|
+
)
|
|
289
|
+
|
|
290
|
+
def sparse_matrix(self, spectra, *, base_scores=None, transitive_only=False, progress_bar=False,
|
|
291
|
+
min_score=None):
|
|
292
|
+
"""Return symmetric sparse scores for final edges meeting the optional min_score."""
|
|
293
|
+
return self.align(spectra, base_scores=base_scores, progress_bar=progress_bar).to_scores(
|
|
294
|
+
sparse=True, transitive_only=transitive_only, min_score=min_score
|
|
295
|
+
)
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
from .CudaBinnedEmbeddingSimilarity import CudaBinnedEmbeddingSimilarity
|
|
2
|
+
from .CudaCosineGreedy import CudaCosineGreedy
|
|
3
|
+
from .CudaCosineLinear import CudaCosineLinear, CudaModifiedCosineLinear
|
|
4
|
+
from .CudaEntropyGreedy import CudaEntropyGreedy
|
|
5
|
+
from .CudaFingerprintSimilarity import CudaFingerprintSimilarity
|
|
6
|
+
from .CudaModifiedCosine import CudaModifiedCosine, CudaModifiedCosineGreedy
|
|
7
|
+
from .CudaNeutralLossesCosine import CudaNeutralLossesCosine
|
|
8
|
+
from .CudaTransitiveAlignment import CudaTransitiveAlignment as CudaTransitiveAlignment
|
|
9
|
+
from .CudaTransitiveAlignment import TransitiveAlignmentResult as TransitiveAlignmentResult
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
# Callers enumerate __all__ to discover pairwise similarities. The network
|
|
13
|
+
# aligner and its result are available as explicit package imports above.
|
|
14
|
+
__all__ = [
|
|
15
|
+
"CudaBinnedEmbeddingSimilarity",
|
|
16
|
+
"CudaCosineGreedy",
|
|
17
|
+
"CudaCosineLinear",
|
|
18
|
+
"CudaEntropyGreedy",
|
|
19
|
+
"CudaFingerprintSimilarity",
|
|
20
|
+
"CudaModifiedCosine",
|
|
21
|
+
"CudaModifiedCosineGreedy",
|
|
22
|
+
"CudaModifiedCosineLinear",
|
|
23
|
+
"CudaNeutralLossesCosine",
|
|
24
|
+
]
|