Skip to content

Commit 0ca9c55

Browse files
committed
update counts for similarity sets more efficiently
1 parent 2d57be1 commit 0ca9c55

1 file changed

Lines changed: 6 additions & 29 deletions

File tree

TreeMS2/similarity_sets.py

Lines changed: 6 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -23,38 +23,15 @@ def __init__(self, groups: Groups, vector_store: Optional[VectorStore]):
2323

2424
def update_similarity_sets(self, similarity_matrix: SimilarityMatrix):
2525
rows, cols = similarity_matrix.matrix.nonzero()
26-
total_spectra = self.groups.total_spectra
2726

28-
global_ids = self.vector_store.get_col("global_id").to_numpy(dtype=np.uint32).ravel()
29-
row_ids = global_ids[rows]
30-
col_ids = global_ids[cols]
27+
group_ids = self.vector_store.get_col("group_id").to_numpy(dtype=np.uint16).ravel()
28+
row_group_ids = group_ids[rows]
29+
col_group_ids = group_ids[cols]
3130

32-
m = csr_matrix((similarity_matrix.matrix.data, (row_ids, col_ids)), shape=(total_spectra, total_spectra),
33-
dtype=np.bool_)
31+
pairs = np.vstack((row_group_ids, col_group_ids)).T
32+
unique_pairs, counts = np.unique(pairs, axis=0, return_counts=True)
3433

35-
# loop over groups representing the rows in s
36-
for row_group in self.groups.get_groups():
37-
row_group_id = row_group.get_id()
38-
# retrieve id of first and last spectrum in group
39-
row_begin = row_group.begin
40-
row_end = row_group.end
41-
# loop over groups representing the columns in s
42-
for col_group in self.groups.get_groups():
43-
col_group_id = col_group.get_id()
44-
45-
# diagonal should contain the number of vectors for the group in the vector store being analyzed
46-
if row_group_id == col_group_id:
47-
self.similarity_sets[row_group_id, col_group_id] = self.vector_store.group_counts[row_group_id]
48-
continue
49-
# retrieve id of first and last spectrum in group
50-
col_begin = col_group.begin
51-
col_end = col_group.end
52-
# count the number of spectra in group A that have at least one similar in group B
53-
# m[row_begin:row_end + 1, col_begin:col_end] extracts the relevant submatrix
54-
# .getnnz(axis=1) counts the number of nonzero entries per row
55-
# > 0 converts it into a boolean array where True means the row has at least one nonzero value
56-
self.similarity_sets[row_group_id, col_group_id] += (
57-
m[row_begin:row_end + 1, col_begin:col_end].getnnz(axis=1) > 0).sum()
34+
self.similarity_sets[unique_pairs[:, 0], unique_pairs[:, 1]] += counts.astype(np.uint64)
5835

5936
def write(self, path: str):
6037
s = self.similarity_sets

0 commit comments

Comments
 (0)