Skip to content

Commit 657d7df

Browse files
committed
removed global ids (both in usage and storage)
1 parent 0ca9c55 commit 657d7df

13 files changed

Lines changed: 12 additions & 243 deletions

File tree

TreeMS2/groups/group.py

Lines changed: 0 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,6 @@ def __init__(self, group_name: str):
1515
self.failed_parsed = 0
1616
self.failed_processed = 0
1717

18-
self.begin = 0
19-
self.end = 0
20-
2118
def set_id(self, file_id: int):
2219
self._id = file_id
2320

@@ -42,18 +39,6 @@ def add(self, peak_file: PeakFile) -> PeakFile:
4239
def get_peak_file(self, peak_file_id):
4340
return self._peak_files[peak_file_id]
4441

45-
def update(self, begin_id):
46-
self.begin = begin_id
47-
self.end = begin_id + self.total_spectra - 1
48-
cur_id = self.begin
49-
for peak_file in self._peak_files:
50-
cur_id = peak_file.update(cur_id)
51-
return self.end + 1
52-
53-
def get_global_id(self, peak_file_id: int, spectrum_id: int) -> int:
54-
global_id = self._peak_files[peak_file_id].get_global_id(spectrum_id)
55-
return global_id
56-
5742
def total_valid_spectra(self) -> int:
5843
return self.total_spectra - self.failed_parsed - self.failed_processed
5944

@@ -64,8 +49,6 @@ def to_dict(self) -> Dict[str, Any]:
6449
"total_spectra": self.total_spectra,
6550
"failed_parsed": self.failed_parsed,
6651
"failed_processed": self.failed_processed,
67-
"begin": self.begin,
68-
"end": self.end,
6952
"files": [file.to_dict() for file in self._peak_files],
7053
}
7154

@@ -76,8 +59,6 @@ def from_dict(cls, data: Dict[str, Any]) -> "Group":
7659
group.total_spectra = data["total_spectra"]
7760
group.failed_parsed = data["failed_parsed"]
7861
group.failed_processed = data["failed_processed"]
79-
group.begin = data["begin"]
80-
group.end = data["end"]
8162
for file in data["files"]:
8263
_, file_extension = os.path.splitext(file["filename"])
8364
match file_extension:
@@ -86,7 +67,3 @@ def from_dict(cls, data: Dict[str, Any]) -> "Group":
8667
case _:
8768
continue
8869
return group
89-
90-
def __repr__(self) -> str:
91-
files_repr = "\n\t".join([repr(file) for file in self._peak_files])
92-
return f"{self.__class__.__name__}(id={self._id}, [{self.begin}, {self.end}]):\n\t{files_repr}"

TreeMS2/groups/groups.py

Lines changed: 1 addition & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -21,9 +21,6 @@ def __init__(self):
2121
self.failed_parsed = 0
2222
self.failed_processed = 0
2323

24-
self.begin = 0
25-
self.end = 0
26-
2724
def add(self, group: Group) -> Group:
2825
for g in self._groups:
2926
if g.get_group_name() == group.get_group_name():
@@ -50,22 +47,6 @@ def get_group(self, group_id: int) -> Group:
5047
def get_group_ids(self) -> List[int]:
5148
return [group.get_id() for group in self._groups]
5249

53-
def update(self):
54-
self.end = self.total_spectra - 1
55-
cur_id = self.begin
56-
for group in self._groups:
57-
cur_id = group.update(begin_id=cur_id)
58-
59-
def get_global_id(self, group_id: int, file_id, spectrum_id) -> int:
60-
global_id = self._groups[group_id].get_global_id(file_id, spectrum_id)
61-
return global_id
62-
63-
def get_group_id_from_global_id(self, global_id: int) -> int:
64-
for group in self._groups:
65-
if group.begin <= global_id <= group.end:
66-
return group.get_id()
67-
raise ValueError(f"Global id '{global_id}' does not belong to any group.")
68-
6950
def total_valid_spectra(self) -> int:
7051
return self.total_spectra - self.failed_parsed - self.failed_processed
7152

@@ -145,8 +126,6 @@ def to_dict(self) -> Dict[str, Any]:
145126
"total_spectra": self.total_spectra,
146127
"failed_parsed": self.failed_parsed,
147128
"failed_processed": self.failed_processed,
148-
"begin": self.begin,
149-
"end": self.end,
150129
"groups": [group.to_dict() for group in self._groups],
151130
}
152131

@@ -167,8 +146,7 @@ def from_dict(cls, data: Dict[str, Any]) -> Optional["Groups"]:
167146
groups.total_spectra = data["total_spectra"]
168147
groups.failed_parsed = data["failed_parsed"]
169148
groups.failed_processed = data["failed_processed"]
170-
groups.begin = data["begin"]
171-
groups.end = data["end"]
149+
172150
groups._groups = [Group.from_dict(group) for group in data["groups"]]
173151
return groups
174152
except (KeyError, TypeError, AttributeError):
@@ -184,7 +162,3 @@ def load(cls, path: str) -> Optional["Groups"]:
184162
return cls.from_dict(data)
185163
except (json.JSONDecodeError, OSError, PermissionError):
186164
return None # Return None if the file is unreadable or corrupted
187-
188-
def __repr__(self) -> str:
189-
groups_repr = "\n\t".join([repr(group) for group in self._groups])
190-
return f"{self.__class__.__name__}({self.get_size()} groups, {self.get_nr_files()} files, [{self.begin}, {self.end}]):\n\t{groups_repr}"

TreeMS2/groups/peak_file/peak_file.py

Lines changed: 0 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,6 @@ def __init__(self, file_path: str):
1515
self.failed_parsed = 0
1616
self.failed_processed = 0
1717

18-
self.begin = 0
19-
self.end = 0
2018
self.filtered: List[int] = []
2119

2220
@abstractmethod
@@ -39,15 +37,6 @@ def set_group_id(self, group_id: int):
3937
def get_group_id(self):
4038
return self._group_id
4139

42-
def update(self, begin_id: int):
43-
self.begin = begin_id
44-
self.end = begin_id + self.total_spectra - 1
45-
self.filtered = [x + self.begin for x in self.filtered]
46-
return self.end + 1
47-
48-
def get_global_id(self, spectrum_id: int) -> int:
49-
return self.begin + spectrum_id
50-
5140
def total_valid_spectra(self) -> int:
5241
return self.total_spectra - self.failed_parsed - self.failed_processed
5342

@@ -58,8 +47,6 @@ def to_dict(self) -> Dict[str, Any]:
5847
"total_spectra": self.total_spectra,
5948
"failed_parsed": self.failed_parsed,
6049
"failed_processed": self.failed_processed,
61-
"begin": self.begin,
62-
"end": self.end,
6350
"filtered": self.filtered,
6451
}
6552

@@ -70,10 +57,5 @@ def from_dict(cls, data: Dict[str, Any]) -> "PeakFile":
7057
peak_file.total_spectra = data["total_spectra"]
7158
peak_file.failed_parsed = data["failed_parsed"]
7259
peak_file.failed_processed = data["failed_processed"]
73-
peak_file.begin = data["begin"]
74-
peak_file.end = data["end"]
7560
peak_file.filtered = data["filtered"]
7661
return peak_file
77-
78-
def __repr__(self) -> str:
79-
return f"{self.__class__.__name__}(id={self._id}, filepath={self.file_path}, [{self.begin}, {self.end}])"

TreeMS2/similarity_matrix/filters/mask_filter.py

Lines changed: 0 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -21,18 +21,3 @@ def apply(self, similarity_matrix: SimilarityMatrix):
2121
@abstractmethod
2222
def construct_mask(self, similarity_matrix: SimilarityMatrix) -> SpectraMatrix:
2323
pass
24-
25-
@abstractmethod
26-
def write_filter_statistics(self, target_dir: str, total_spectra: int):
27-
pass
28-
29-
@abstractmethod
30-
def save_mask(self, target_dir: str):
31-
pass
32-
33-
@abstractmethod
34-
def save_mask_global(self, target_dir: str, total_spectra: int):
35-
pass
36-
37-
def __repr__(self) -> str:
38-
return f"{self.__class__.__name__}()"
Lines changed: 1 addition & 70 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,6 @@
1-
import os
2-
31
import numpy as np
4-
import pandas as pd
52
from scipy.sparse import csr_matrix
63

7-
from TreeMS2.groups.groups import Groups
84
from TreeMS2.logger_config import get_logger
95
from TreeMS2.similarity_matrix.filters.mask_filter import MaskFilter
106
from TreeMS2.similarity_matrix.similarity_matrix import SimilarityMatrix
@@ -15,11 +11,10 @@
1511

1612

1713
class PrecursorMzFilter(MaskFilter):
18-
def __init__(self, groups: Groups, vector_store: VectorStore,
14+
def __init__(self, vector_store: VectorStore,
1915
precursor_mz_window: float):
2016
self.precursor_mz_window = precursor_mz_window
2117
self.vector_store = vector_store
22-
self.groups = groups
2318
super().__init__(None)
2419

2520
def construct_mask(self, similarity_matrix: SimilarityMatrix) -> SpectraMatrix:
@@ -42,67 +37,3 @@ def construct_mask(self, similarity_matrix: SimilarityMatrix) -> SpectraMatrix:
4237
dtype=np.bool_)
4338
mask = SpectraMatrix(m)
4439
return mask
45-
46-
def write_filter_statistics(self, target_dir: str, total_spectra):
47-
if self.mask is None:
48-
raise ValueError("No mask has been constructed")
49-
50-
rows, cols = self.mask.matrix.nonzero()
51-
52-
row_ids = self.vector_store.get_data(rows, ["global_id"])["global_id"].to_numpy(dtype=np.int32)
53-
col_ids = self.vector_store.get_data(cols, ["global_id"])["global_id"].to_numpy(dtype=np.int32)
54-
m = csr_matrix((self.mask.matrix.data, (row_ids, col_ids)), shape=(total_spectra, total_spectra),
55-
dtype=np.bool_)
56-
57-
nr_groups = self.groups.get_size()
58-
s = np.zeros((nr_groups, nr_groups), dtype=np.uint64)
59-
# loop over groups representing the rows in s
60-
for row_group in self.groups.get_groups():
61-
row_group_id = row_group.get_id()
62-
# retrieve id of first and last spectrum in group
63-
row_begin = row_group.begin
64-
row_end = row_group.end
65-
# loop over groups representing the columns in s
66-
for col_group in self.groups.get_groups():
67-
col_group_id = col_group.get_id()
68-
# retrieve id of first and last spectrum in group
69-
col_begin = col_group.begin
70-
col_end = col_group.end
71-
# count the number of spectra that have been filtered between group A and group B
72-
filtered = m[row_begin:row_end + 1, col_begin:col_end + 1].nnz
73-
s[row_group_id, col_group_id] = filtered
74-
75-
# create a dataframe
76-
group_names = [group.get_group_name() for group in self.groups.get_groups()]
77-
df = pd.DataFrame(s, index=group_names, columns=group_names)
78-
79-
# create path
80-
filters_dir = os.path.join(target_dir, "filters")
81-
os.makedirs(filters_dir, exist_ok=True)
82-
path = os.path.join(filters_dir, "precursor_mz.txt")
83-
84-
# write statistics to disk
85-
with open(path, 'w') as f:
86-
# Write a header explanation
87-
f.write(
88-
f"Number of spectra considered similar between each pair of groups with a precursor m/z difference larger than {self.precursor_mz_window}:\n\n")
89-
# Write the matrix
90-
f.write(df.to_string())
91-
logger.info(
92-
f"Overview of the number of similarities filtered due to precursor m/z difference written to '{path}'")
93-
return s
94-
95-
def save_mask(self, target_dir: str):
96-
# save mask
97-
path = self.mask.write(os.path.join(target_dir, "precursor_mz"))
98-
logger.info(f"Precursor mz mask has been written to '{path}'.")
99-
return path
100-
101-
def save_mask_global(self, target_dir: str, total_spectra: int):
102-
# save mask
103-
path = self.mask.write_global(os.path.join(target_dir, "precursor_mz_global"), total_spectra, self.vector_store)
104-
logger.info(f"Precursor mz mask has been written to '{path}'.")
105-
return path
106-
107-
def __repr__(self) -> str:
108-
return f"{self.__class__.__name__}(precursor_mz_window={self.precursor_mz_window:.3f})"

TreeMS2/similarity_matrix/pipeline.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@
44
from .filters.mask_filter import MaskFilter
55
from .filters.precursor_mz_filter import PrecursorMzFilter
66
from .similarity_matrix import SimilarityMatrix
7-
from ..groups.groups import Groups
87
from ..vector_store.vector_store import VectorStore
98

109
logger = get_logger(__name__)
@@ -35,11 +34,11 @@ def __repr__(self) -> str:
3534
class SimilarityMatrixPipelineFactory:
3635
@staticmethod
3736
def create_pipeline(
38-
groups: Groups, vector_store: VectorStore,
37+
vector_store: VectorStore,
3938
precursor_mz_window: Optional[float]) -> SimilarityMatrixPipeline:
4039
mask_filters = []
4140
if precursor_mz_window is not None:
4241
mask_filters.append(
43-
PrecursorMzFilter(groups=groups, vector_store=vector_store, precursor_mz_window=precursor_mz_window))
42+
PrecursorMzFilter(vector_store=vector_store, precursor_mz_window=precursor_mz_window))
4443
pipeline = SimilarityMatrixPipeline(mask_filters=mask_filters)
4544
return pipeline
Lines changed: 1 addition & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,9 @@
11
import numpy as np
22
import numpy.typing as npt
3-
from scipy.sparse import csr_matrix, load_npz
3+
from scipy.sparse import csr_matrix
44

55
from TreeMS2.logger_config import get_logger
66
from TreeMS2.similarity_matrix.spectra_matrix import SpectraMatrix
7-
from TreeMS2.vector_store.vector_store import VectorStore
87

98
logger = get_logger(__name__)
109

@@ -17,25 +16,3 @@ def __init__(self, *args, similarity_threshold: float):
1716

1817
def update(self, data: npt.NDArray[np.bool_], rows: npt.NDArray[np.int64], cols: npt.NDArray[np.int64]):
1918
self.matrix += csr_matrix((data, (rows, cols)), self.matrix.shape)
20-
21-
def write(self, path: str) -> str:
22-
path = super().write(path)
23-
return path
24-
25-
def write_global(self, path: str, total_spectra: int, vector_store: VectorStore):
26-
path = super().write_global(path, total_spectra, vector_store)
27-
return path
28-
29-
@classmethod
30-
def load_with_threshold(cls, path: str, similarity_threshold: float) -> 'SimilarityMatrix':
31-
# Load the matrix from file
32-
matrix = load_npz(path)
33-
# Create an instance of SimilarityMatrix with the loaded matrix and threshold
34-
return cls(matrix, similarity_threshold=similarity_threshold)
35-
36-
def __sub__(self, other):
37-
if isinstance(other, SpectraMatrix):
38-
# Perform the subtraction and return a SimilarityMatrix
39-
return SimilarityMatrix(self.matrix - other.matrix, similarity_threshold=self.similarity_threshold)
40-
else:
41-
raise ValueError("Subtraction is only supported between SimilarityMatrix and SpectraMatrix instances.")
Lines changed: 1 addition & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,5 @@
11
import numpy as np
2-
from scipy.sparse import csr_matrix, save_npz, load_npz
3-
4-
from TreeMS2.vector_store.vector_store import VectorStore
2+
from scipy.sparse import csr_matrix
53

64

75
class SpectraMatrix:
@@ -23,29 +21,5 @@ def __init__(self, *args):
2321
else:
2422
raise ValueError("Invalid arguments for initializing SpectraMatrix.")
2523

26-
def nr_bytes(self):
27-
return self.matrix.data.nbytes + self.matrix.indptr.nbytes + self.matrix.indices.nbytes
28-
29-
def write(self, path: str) -> str:
30-
save_npz(path, self.matrix)
31-
return path
32-
33-
def write_global(self, path: str, total_spectra: int, vector_store: VectorStore):
34-
rows, cols = self.matrix.nonzero()
35-
row_ids = vector_store.get_data(rows, ["global_id"])["global_id"].to_numpy(dtype=np.int32)
36-
col_ids = vector_store.get_data(cols, ["global_id"])["global_id"].to_numpy(dtype=np.int32)
37-
m = csr_matrix((self.matrix.data, (row_ids, col_ids)), shape=(total_spectra, total_spectra), dtype=np.bool_)
38-
save_npz(path, m)
39-
return path
40-
4124
def subtract(self, spectra_matrix: 'SpectraMatrix'):
4225
self.matrix -= spectra_matrix.matrix
43-
44-
@classmethod
45-
def load(cls, path: str) -> 'SpectraMatrix':
46-
# Load the sparse matrix
47-
matrix = load_npz(path)
48-
# Create a new instance of SpectraMatrix
49-
instance = cls(matrix)
50-
51-
return instance

TreeMS2/similarity_sets.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@
44
import numpy as np
55
import numpy.typing as npt
66
import pandas as pd
7-
from scipy.sparse import csr_matrix
87

98
from TreeMS2.groups.groups import Groups
109
from TreeMS2.logger_config import get_logger

0 commit comments

Comments
 (0)