masscube 1.2.7__tar.gz → 1.2.9__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.
- {masscube-1.2.7 → masscube-1.2.9}/PKG-INFO +1 -1
- {masscube-1.2.7 → masscube-1.2.9}/pyproject.toml +1 -1
- {masscube-1.2.7 → masscube-1.2.9}/src/masscube/alignment.py +8 -5
- masscube-1.2.9/src/masscube/feature_evaluation.py +193 -0
- {masscube-1.2.7 → masscube-1.2.9}/src/masscube/params.py +10 -29
- {masscube-1.2.7 → masscube-1.2.9}/src/masscube/raw_data_utils.py +25 -24
- {masscube-1.2.7 → masscube-1.2.9}/src/masscube/stats.py +2 -1
- {masscube-1.2.7 → masscube-1.2.9}/src/masscube/workflows.py +15 -18
- {masscube-1.2.7 → masscube-1.2.9}/src/masscube.egg-info/PKG-INFO +1 -1
- masscube-1.2.7/src/masscube/feature_evaluation.py +0 -187
- {masscube-1.2.7 → masscube-1.2.9}/LICENSE +0 -0
- {masscube-1.2.7 → masscube-1.2.9}/README.md +0 -0
- {masscube-1.2.7 → masscube-1.2.9}/setup.cfg +0 -0
- {masscube-1.2.7 → masscube-1.2.9}/src/masscube/__init__.py +0 -0
- {masscube-1.2.7 → masscube-1.2.9}/src/masscube/annotation.py +0 -0
- {masscube-1.2.7 → masscube-1.2.9}/src/masscube/classifier_builder.py +0 -0
- {masscube-1.2.7 → masscube-1.2.9}/src/masscube/feature_detection.py +0 -0
- {masscube-1.2.7 → masscube-1.2.9}/src/masscube/feature_grouping.py +0 -0
- {masscube-1.2.7 → masscube-1.2.9}/src/masscube/mzpkl.py +0 -0
- {masscube-1.2.7 → masscube-1.2.9}/src/masscube/network.py +0 -0
- {masscube-1.2.7 → masscube-1.2.9}/src/masscube/normalization.py +0 -0
- {masscube-1.2.7 → masscube-1.2.9}/src/masscube/utils_functions.py +0 -0
- {masscube-1.2.7 → masscube-1.2.9}/src/masscube/visualization.py +0 -0
- {masscube-1.2.7 → masscube-1.2.9}/src/masscube.egg-info/SOURCES.txt +0 -0
- {masscube-1.2.7 → masscube-1.2.9}/src/masscube.egg-info/dependency_links.txt +0 -0
- {masscube-1.2.7 → masscube-1.2.9}/src/masscube.egg-info/entry_points.txt +0 -0
- {masscube-1.2.7 → masscube-1.2.9}/src/masscube.egg-info/requires.txt +0 -0
- {masscube-1.2.7 → masscube-1.2.9}/src/masscube.egg-info/top_level.txt +0 -0
|
@@ -239,8 +239,8 @@ def gap_filling(features, params: Params):
|
|
|
239
239
|
if params.gap_filling_method == 'local_maximum':
|
|
240
240
|
|
|
241
241
|
# if retention time correction is applied, read the model
|
|
242
|
-
if params.correct_rt and os.path.exists(os.path.join(params.
|
|
243
|
-
with open(os.path.join(params.
|
|
242
|
+
if params.correct_rt and os.path.exists(os.path.join(params.project_file_dir, "rt_correction_models.pkl")):
|
|
243
|
+
with open(os.path.join(params.project_file_dir, "rt_correction_models.pkl"), "rb") as f:
|
|
244
244
|
rt_cor_functions = pickle.load(f)
|
|
245
245
|
else:
|
|
246
246
|
rt_cor_functions = None
|
|
@@ -263,7 +263,7 @@ def gap_filling(features, params: Params):
|
|
|
263
263
|
f.peak_height_arr[i] = np.max(eic_signals[:, 1])
|
|
264
264
|
f.peak_area_arr[i] = int(np.trapz(y=eic_signals[:, 1], x=eic_time_arr))
|
|
265
265
|
f.top_average_arr[i] = np.mean(np.sort(eic_signals[:, 1])[-3:])
|
|
266
|
-
|
|
266
|
+
|
|
267
267
|
# calculate the detection rate after gap filling (blank samples are not included)
|
|
268
268
|
v = ~params.sample_metadata['is_blank']
|
|
269
269
|
for f in features:
|
|
@@ -412,13 +412,16 @@ def output_feature_to_msp(feature_table, output_path):
|
|
|
412
412
|
f.write("\n")
|
|
413
413
|
continue
|
|
414
414
|
|
|
415
|
-
if feature_table['annotation'][i] is None:
|
|
415
|
+
if feature_table['annotation'][i] is None or feature_table['annotation'][i] != feature_table['annotation'][i]:
|
|
416
416
|
name = "Unknown"
|
|
417
417
|
else:
|
|
418
418
|
name = str(feature_table['annotation'][i])
|
|
419
419
|
|
|
420
420
|
peaks = re.findall(r"\d+\.\d+", feature_table['MS2'][i])
|
|
421
|
-
|
|
421
|
+
try:
|
|
422
|
+
f.write("NAME: " + name + "\n")
|
|
423
|
+
except:
|
|
424
|
+
f.write("NAME: Unknown\n")
|
|
422
425
|
f.write("PRECURSORMZ: " + str(feature_table['m/z'][i]) + "\n")
|
|
423
426
|
f.write("PRECURSORTYPE: " + str(feature_table['adduct'][i]) + "\n")
|
|
424
427
|
f.write("RETENTIONTIME: " + str(feature_table['RT'][i]) + "\n")
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
# Author: Huaxu Yu
|
|
2
|
+
|
|
3
|
+
# Evaluate feature quality by chromatographic peak shapes, mz errors, rt errors, etc.
|
|
4
|
+
|
|
5
|
+
# imports
|
|
6
|
+
import numpy as np
|
|
7
|
+
from numpy import dot
|
|
8
|
+
|
|
9
|
+
"""
|
|
10
|
+
Functions
|
|
11
|
+
------------------------------------------------------------------------------------------------------------------------
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
def calculate_gaussian_similarity(x, y, len_tol=5):
|
|
15
|
+
"""
|
|
16
|
+
calculate the gaussian similarity using Pearson correlation coefficient.
|
|
17
|
+
|
|
18
|
+
Parameters
|
|
19
|
+
----------
|
|
20
|
+
x: numpy array
|
|
21
|
+
Retention times.
|
|
22
|
+
y: numpy array
|
|
23
|
+
MS1 signal intensities.
|
|
24
|
+
len_tol: int
|
|
25
|
+
Minimum length of the peak to calculate the similarity score.
|
|
26
|
+
If the length of the peak is less than this value, return 0.
|
|
27
|
+
|
|
28
|
+
Returns
|
|
29
|
+
-------
|
|
30
|
+
float
|
|
31
|
+
similarity score
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
if not isinstance(x, np.ndarray):
|
|
35
|
+
x = np.array(x)
|
|
36
|
+
if not isinstance(y, np.ndarray):
|
|
37
|
+
y = np.array(y)
|
|
38
|
+
|
|
39
|
+
# if the length of the peak is less than the tolerance, return 0
|
|
40
|
+
if len(x) < len_tol or np.max(y) <= 0:
|
|
41
|
+
return 0.0
|
|
42
|
+
|
|
43
|
+
# Estimate the parameters of the Gaussian function
|
|
44
|
+
# a: amplitude, b: mean, c: standard deviation
|
|
45
|
+
a = np.max(y)
|
|
46
|
+
idx = np.argmax(y)
|
|
47
|
+
b = x[idx]
|
|
48
|
+
|
|
49
|
+
# Compute approximate FWHM using half-height
|
|
50
|
+
right_idx = np.where(y[idx:] < a / 2)[0]
|
|
51
|
+
left_idx = np.where(y[:idx] < a / 2)[0]
|
|
52
|
+
|
|
53
|
+
c1 = (x[right_idx[0] + idx] - b) if len(right_idx) > 0 else (x[-1] - b)
|
|
54
|
+
c2 = (b - x[left_idx[-1]]) if len(left_idx) > 0 else (b - x[0])
|
|
55
|
+
|
|
56
|
+
fwhm = c1 + c2
|
|
57
|
+
c = fwhm / 2.355 if fwhm > 0 else 1e-6 # Avoid division by zero
|
|
58
|
+
|
|
59
|
+
# Generate fitted Gaussian curve
|
|
60
|
+
y_fit = a * np.exp(-0.5 * ((x - b) / c) ** 2)
|
|
61
|
+
|
|
62
|
+
# Fast correlation using dot product
|
|
63
|
+
y = y.astype(float)
|
|
64
|
+
y_fit = y_fit.astype(float)
|
|
65
|
+
y -= y.mean()
|
|
66
|
+
y_fit -= y_fit.mean()
|
|
67
|
+
similarity = dot(y, y_fit) / (np.linalg.norm(y) * np.linalg.norm(y_fit) + 1e-12)
|
|
68
|
+
|
|
69
|
+
return max(0, similarity)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def calculate_noise_score(y, rel_int_tol=0.05, len_tol=5):
|
|
73
|
+
"""
|
|
74
|
+
Calculate the noise score that reflect the signal fluctuation.
|
|
75
|
+
|
|
76
|
+
Parameters
|
|
77
|
+
----------
|
|
78
|
+
y: array-like
|
|
79
|
+
Intensity values of the peak.
|
|
80
|
+
rel_int_tol: float
|
|
81
|
+
Relative intensity threshold (filter low signals).
|
|
82
|
+
len_tol: int
|
|
83
|
+
Minimum length of the peak to calculate the noise score.
|
|
84
|
+
If the length of the peak is less than this value, return 0.
|
|
85
|
+
|
|
86
|
+
Returns
|
|
87
|
+
-------
|
|
88
|
+
float
|
|
89
|
+
Noise score (0 = no noise, higher = noiser)
|
|
90
|
+
"""
|
|
91
|
+
|
|
92
|
+
y = np.array(y, dtype=float) if not isinstance(y, np.ndarray) else y
|
|
93
|
+
|
|
94
|
+
y = y[y > np.max(y) * rel_int_tol]
|
|
95
|
+
|
|
96
|
+
if len(y) < len_tol:
|
|
97
|
+
return 0
|
|
98
|
+
|
|
99
|
+
y = np.concatenate(([0], y, [0]))
|
|
100
|
+
diff = np.diff(y)
|
|
101
|
+
|
|
102
|
+
return np.sum(np.abs(diff)) / np.max(y) / 2 - 1
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def calculate_asymmetry_factor(y, threshold_ratio=0.1):
|
|
106
|
+
"""
|
|
107
|
+
Calculate peak asymmetry at a given threshold level (default: 10%).
|
|
108
|
+
|
|
109
|
+
Parameters
|
|
110
|
+
----------
|
|
111
|
+
y : array-like
|
|
112
|
+
Intensity values
|
|
113
|
+
threshold_ratio : float
|
|
114
|
+
Fraction of peak height to define tails (default = 0.1 = 10%)
|
|
115
|
+
|
|
116
|
+
Returns
|
|
117
|
+
-------
|
|
118
|
+
float
|
|
119
|
+
Asymmetry factor:
|
|
120
|
+
- ~1 = symmetric
|
|
121
|
+
- >1 = right-skewed
|
|
122
|
+
- <1 = left-skewed
|
|
123
|
+
- np.inf = undefined
|
|
124
|
+
"""
|
|
125
|
+
|
|
126
|
+
y = np.array(y, dtype=float) if not isinstance(y, np.ndarray) else y
|
|
127
|
+
|
|
128
|
+
if len(y) < 5 or np.max(y) <= 0:
|
|
129
|
+
return np.inf
|
|
130
|
+
|
|
131
|
+
idx = np.argmax(y)
|
|
132
|
+
|
|
133
|
+
# Define threshold
|
|
134
|
+
threshold = y[idx] * threshold_ratio
|
|
135
|
+
|
|
136
|
+
# Find last point before peak below threshold (left tail)
|
|
137
|
+
left_candidates = np.where(y[:idx] < threshold)[0]
|
|
138
|
+
left_idx = left_candidates[-1] if len(left_candidates) else 0
|
|
139
|
+
|
|
140
|
+
# Find first point after peak below threshold (right tail)
|
|
141
|
+
right_candidates = np.where(y[idx:] < threshold)[0]
|
|
142
|
+
right_idx = (right_candidates[0] + idx) if len(right_candidates) else (len(y) - 1)
|
|
143
|
+
|
|
144
|
+
# Avoid division by zero
|
|
145
|
+
if idx == left_idx:
|
|
146
|
+
return 99.0
|
|
147
|
+
|
|
148
|
+
return (right_idx - idx) / (idx - left_idx)
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def squared_error_to_smoothed_curve(original_signal, fit_signal):
|
|
152
|
+
"""
|
|
153
|
+
Calculate the sum of squared error between the original signal and the fitted signal.
|
|
154
|
+
|
|
155
|
+
Parameters
|
|
156
|
+
----------
|
|
157
|
+
original_signal: numpy array
|
|
158
|
+
The original signal.
|
|
159
|
+
fit_signal: numpy array
|
|
160
|
+
The fitted signal.
|
|
161
|
+
|
|
162
|
+
Returns
|
|
163
|
+
-------
|
|
164
|
+
float
|
|
165
|
+
The noise score.
|
|
166
|
+
"""
|
|
167
|
+
|
|
168
|
+
diff = (original_signal - fit_signal) / np.max(original_signal)
|
|
169
|
+
return np.sum(diff**2)
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
"""
|
|
173
|
+
Helper functions
|
|
174
|
+
------------------------------------------------------------------------------------------------------------------------
|
|
175
|
+
"""
|
|
176
|
+
|
|
177
|
+
# calculate the Gaussian similarity
|
|
178
|
+
def _gaussian(x, a, b, c):
|
|
179
|
+
"""
|
|
180
|
+
Gaussian function
|
|
181
|
+
|
|
182
|
+
Parameters
|
|
183
|
+
----------
|
|
184
|
+
x: numpy array
|
|
185
|
+
Retention time
|
|
186
|
+
a: float
|
|
187
|
+
Amplitude
|
|
188
|
+
b: float
|
|
189
|
+
Mean
|
|
190
|
+
c: float
|
|
191
|
+
Standard deviation
|
|
192
|
+
"""
|
|
193
|
+
return a * np.exp(-0.5 * ((x - b) / c) ** 2)
|
|
@@ -198,7 +198,9 @@ class Params:
|
|
|
198
198
|
|
|
199
199
|
# STEP 2: check if the required files are prepared
|
|
200
200
|
# three items are required: raw MS data, sample table and parameter file
|
|
201
|
-
|
|
201
|
+
sample_files = [f for f in os.listdir(self.sample_dir) if not f.startswith(".") and
|
|
202
|
+
(f.lower().endswith(".mzml") or f.lower().endswith(".mzxml"))]
|
|
203
|
+
if not os.path.exists(self.sample_dir) or len(sample_files) == 0:
|
|
202
204
|
raise ValueError("No raw MS data is found in the project directory.")
|
|
203
205
|
if not os.path.exists(os.path.join(self.project_dir, "sample_table.csv")):
|
|
204
206
|
print("No sample table is found in the project directory. Normalization and statistical analysis will NOT be performed.")
|
|
@@ -210,16 +212,9 @@ class Params:
|
|
|
210
212
|
print("To perform feature annotation, please specify the path of MS/MS library in the parameter file.")
|
|
211
213
|
|
|
212
214
|
# STEP 3: create the output directories if not exist
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
os.makedirs(self.tmp_file_dir)
|
|
217
|
-
if not os.path.exists(self.ms2_matching_dir):
|
|
218
|
-
os.makedirs(self.ms2_matching_dir)
|
|
219
|
-
if not os.path.exists(self.bpc_dir):
|
|
220
|
-
os.makedirs(self.bpc_dir)
|
|
221
|
-
if not os.path.exists(self.project_file_dir):
|
|
222
|
-
os.makedirs(self.project_file_dir)
|
|
215
|
+
for d in [self.single_file_dir, self.tmp_file_dir, self.ms2_matching_dir,
|
|
216
|
+
self.bpc_dir, self.project_file_dir, self.statistics_dir, self.normalization_dir]:
|
|
217
|
+
os.makedirs(d, exist_ok=True)
|
|
223
218
|
|
|
224
219
|
# STEP 4: read the parameters from csv file or use default values
|
|
225
220
|
if os.path.exists(os.path.join(self.project_dir, "parameters.csv")):
|
|
@@ -227,17 +222,10 @@ class Params:
|
|
|
227
222
|
else:
|
|
228
223
|
print("Using default parameters...")
|
|
229
224
|
# determine the type of MS and ion mode
|
|
230
|
-
|
|
231
|
-
file_names = [f for f in file_names if f.lower().endswith(".mzml") or f.lower().endswith(".mzxml")]
|
|
232
|
-
file_name = os.path.join(self.sample_dir, file_names[0])
|
|
225
|
+
file_name = os.path.join(self.sample_dir, sample_files[0])
|
|
233
226
|
ms_type, ion_mode, _ = find_ms_info(file_name)
|
|
234
227
|
self.set_default(ms_type, ion_mode)
|
|
235
228
|
self.plot_bpc = True
|
|
236
|
-
|
|
237
|
-
if not os.path.exists(self.statistics_dir) and self.run_statistics:
|
|
238
|
-
os.makedirs(self.statistics_dir)
|
|
239
|
-
if not os.path.exists(self.normalization_dir) and (self.sample_normalization or self.signal_normalization):
|
|
240
|
-
os.makedirs(self.normalization_dir)
|
|
241
229
|
|
|
242
230
|
# STEP 5: read the sample names and sample metadata from the sample table
|
|
243
231
|
if os.path.exists(os.path.join(self.project_dir, "sample_table.csv")):
|
|
@@ -245,8 +233,7 @@ class Params:
|
|
|
245
233
|
# find the absolute paths of the raw MS data in order
|
|
246
234
|
self._check_raw_files_in_data_dir()
|
|
247
235
|
else:
|
|
248
|
-
names = [f.split(".")[0] for f in
|
|
249
|
-
(f.lower().endswith(".mzml") or f.lower().endswith(".mzxml"))]
|
|
236
|
+
names = [f.split(".")[0] for f in sample_files]
|
|
250
237
|
self.sample_metadata = pd.DataFrame({'sample_name': names, 'is_qc': False, 'is_blank': False})
|
|
251
238
|
self._check_raw_files_in_data_dir()
|
|
252
239
|
|
|
@@ -256,9 +243,7 @@ class Params:
|
|
|
256
243
|
|
|
257
244
|
# find the start time of the raw MS data
|
|
258
245
|
self.sample_metadata['time'] = [get_start_time(path) for path in self.sample_metadata['ABSOLUTE_PATH']]
|
|
259
|
-
|
|
260
|
-
if self.sample_metadata['time'][i] != self.sample_metadata['time'][i]:
|
|
261
|
-
self.sample_metadata.loc[i, 'VALID'] = False
|
|
246
|
+
self.sample_metadata['VALID'] = self.sample_metadata['time'].notna()
|
|
262
247
|
|
|
263
248
|
# remove the invalid files
|
|
264
249
|
self.sample_metadata = self.sample_metadata[self.sample_metadata['VALID'] == True]
|
|
@@ -384,12 +369,8 @@ def find_ms_info(file_name):
|
|
|
384
369
|
|
|
385
370
|
# for mzml and mzxml
|
|
386
371
|
if file_name.lower().endswith('.mzml') or file_name.lower().endswith('.mzxml'):
|
|
387
|
-
text = ""
|
|
388
372
|
with open(file_name, 'r') as f:
|
|
389
|
-
for
|
|
390
|
-
text += line
|
|
391
|
-
if i > 200:
|
|
392
|
-
break
|
|
373
|
+
text = ''.join([next(f) for _ in range(200)])
|
|
393
374
|
text = text.lower()
|
|
394
375
|
if 'orbitrap' in text or 'q exactive' in text:
|
|
395
376
|
ms_type = 'orbitrap'
|
|
@@ -491,35 +491,35 @@ class MSData:
|
|
|
491
491
|
Scan index of the EIC.
|
|
492
492
|
"""
|
|
493
493
|
|
|
494
|
-
eic_time_arr = []
|
|
495
|
-
eic_signals = []
|
|
496
|
-
eic_scan_idx_arr = []
|
|
497
|
-
|
|
498
494
|
if rt_range is None:
|
|
499
495
|
if target_rt is None:
|
|
500
496
|
rt_range = [0, np.inf]
|
|
501
497
|
else:
|
|
502
498
|
rt_range = [target_rt - rt_tol, target_rt + rt_tol]
|
|
499
|
+
# Extract times and filter by RT
|
|
500
|
+
times = np.array([self.scans[i].time for i in self.ms1_idx], dtype=np.float32)
|
|
501
|
+
mask_rt = (times >= rt_range[0]) & (times <= rt_range[1])
|
|
502
|
+
valid_idx = np.where(mask_rt)[0]
|
|
503
503
|
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
504
|
+
if len(valid_idx) == 0:
|
|
505
|
+
return np.array([]), np.array([]), np.array([])
|
|
506
|
+
|
|
507
|
+
eic_time_arr = times[valid_idx]
|
|
508
|
+
eic_scan_idx_arr = np.array([self.ms1_idx[k] for k in valid_idx], dtype=np.int32)
|
|
509
|
+
|
|
510
|
+
eic_signals = np.zeros((len(valid_idx), 2), dtype=np.float32)
|
|
511
|
+
eic_signals[:, 0] = np.nan # Default m/z as NaN, intensity stays 0
|
|
512
|
+
|
|
513
|
+
# Fill values
|
|
514
|
+
for idx_out, idx_scan in enumerate(eic_scan_idx_arr):
|
|
515
|
+
signals = self.scans[idx_scan].signals # shape: (n_peaks, 2)
|
|
516
|
+
if signals.shape[0] == 0:
|
|
517
|
+
continue # leave as [nan, 0]
|
|
518
|
+
# Find the closest m/z to target_mz within tolerance
|
|
519
|
+
v = np.abs(signals[:, 0] - target_mz)
|
|
520
|
+
if np.min(v) < mz_tol:
|
|
521
|
+
# If multiple m/z values are found, take the first one
|
|
522
|
+
eic_signals[idx_out] = signals[np.argmin(v)]
|
|
523
523
|
|
|
524
524
|
return eic_time_arr, eic_signals, eic_scan_idx_arr
|
|
525
525
|
|
|
@@ -983,7 +983,8 @@ def _preprocess_signals_to_scan(level, id, scan_time, signals, params, precursor
|
|
|
983
983
|
return Scan(level=level, id=id, scan_time=scan_time, signals=signals, precursor_mz=precursor_mz)
|
|
984
984
|
|
|
985
985
|
if level == 1:
|
|
986
|
-
signals = clean_signals(signals,
|
|
986
|
+
signals = clean_signals(signals, mz_range=[params.mz_lower_limit, params.mz_upper_limit],
|
|
987
|
+
intensity_range=[params.ms1_abs_int_tol, np.inf])
|
|
987
988
|
|
|
988
989
|
elif level == 2:
|
|
989
990
|
int_lower = max(params.ms2_abs_int_tol, np.max(signals[:, 1]) * params.ms2_rel_int_tol)
|
|
@@ -194,7 +194,7 @@ def umap_analysis(feature_table, params):
|
|
|
194
194
|
df = df[(~df['is_qc']) & (~df['is_blank'])]
|
|
195
195
|
n = df.iloc[:, 0].values
|
|
196
196
|
data_arr = feature_table[n].values # samples in columns and features in rows
|
|
197
|
-
keys = [i for i in df.columns[1:] if i not in
|
|
197
|
+
keys = [i for i in df.columns[1:] if i not in PROJECT_KEYS]
|
|
198
198
|
|
|
199
199
|
# UMAP analysis
|
|
200
200
|
data_arr = data_arr.T
|
|
@@ -270,3 +270,4 @@ def generate_random_color(num):
|
|
|
270
270
|
|
|
271
271
|
|
|
272
272
|
COLORS = ["#FF5050", "#0078F0", "#00B050", "#FFC000", "#7030A0", "#FF00FF", "#00B0F0", "#FF0000", "#00FF00", "#0000FF"]
|
|
273
|
+
PROJECT_KEYS = ['is_qc', 'is_blank', 'analytical_order', 'time', 'ABSOLUTE_PATH', 'VALID', 'batch_id', 'SINGLE_FILE_PATH']
|
|
@@ -5,12 +5,13 @@
|
|
|
5
5
|
# Import modules
|
|
6
6
|
import os
|
|
7
7
|
import multiprocessing
|
|
8
|
+
from joblib import Parallel, delayed
|
|
9
|
+
from tqdm import tqdm
|
|
8
10
|
import pickle
|
|
9
11
|
from copy import deepcopy
|
|
10
12
|
import pandas as pd
|
|
11
13
|
import numpy as np
|
|
12
14
|
from importlib.metadata import version
|
|
13
|
-
from scipy.stats import zscore
|
|
14
15
|
import time
|
|
15
16
|
|
|
16
17
|
from .raw_data_utils import read_raw_file_to_obj
|
|
@@ -183,25 +184,21 @@ def untargeted_metabolomics_workflow(path=None, return_results=False, only_proce
|
|
|
183
184
|
# STEP 2. Process individual files
|
|
184
185
|
print("Step 2: Processing individual files for feature detection...")
|
|
185
186
|
processed_files = [f.split(".")[0] for f in os.listdir(params.single_file_dir) if f.lower().endswith(".txt")]
|
|
186
|
-
to_be_processed = [
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
if
|
|
190
|
-
|
|
191
|
-
print("\t{} files to process out of {
|
|
187
|
+
to_be_processed = [
|
|
188
|
+
params.sample_metadata.loc[i, 'ABSOLUTE_PATH']
|
|
189
|
+
for i in range(len(params.sample_metadata))
|
|
190
|
+
if params.sample_metadata.iloc[i, 0] not in processed_files
|
|
191
|
+
]
|
|
192
|
+
print(f"\t{len(to_be_processed)} files to process out of {len(params.sample_metadata)} files.")
|
|
192
193
|
|
|
193
194
|
workers = int(multiprocessing.cpu_count() * params.percent_cpu_to_use)
|
|
194
195
|
print("\tA total of {} CPU cores are detected, {} cores are used.".format(multiprocessing.cpu_count(), workers))
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
p.starmap(process_single_file, [(f, params) for f in to_be_processed[i:i+params.batch_size]])
|
|
202
|
-
p.close()
|
|
203
|
-
p.join()
|
|
204
|
-
|
|
196
|
+
|
|
197
|
+
Parallel(n_jobs=workers, backend="loky")(
|
|
198
|
+
delayed(process_single_file)(f, params)
|
|
199
|
+
for f in tqdm(to_be_processed, desc="Processing files", unit="file")
|
|
200
|
+
)
|
|
201
|
+
|
|
205
202
|
metadata[2]["status"] = "completed"
|
|
206
203
|
print("\tIndividual file processing is completed.")
|
|
207
204
|
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
|
|
@@ -254,10 +251,10 @@ def untargeted_metabolomics_workflow(path=None, return_results=False, only_proce
|
|
|
254
251
|
output_feature_table(feature_table, output_path)
|
|
255
252
|
# output the acquired MS2 spectra to a MSP file (designed for MassWiki)
|
|
256
253
|
output_path = os.path.join(params.project_file_dir, "features.msp")
|
|
254
|
+
output_feature_to_msp(feature_table, output_path)
|
|
257
255
|
# output features as pickle file to the project directory
|
|
258
256
|
with open(os.path.join(params.project_file_dir, "aligned_features.pkl"), "wb") as f:
|
|
259
257
|
pickle.dump(features, f)
|
|
260
|
-
output_feature_to_msp(feature_table, output_path)
|
|
261
258
|
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
|
|
262
259
|
else:
|
|
263
260
|
print("Step 3: Feature alignment is skipped. Using the existing aligned feature table.")
|
|
@@ -1,187 +0,0 @@
|
|
|
1
|
-
# Author: Huaxu Yu
|
|
2
|
-
|
|
3
|
-
# Evaluate feature quality by chromatographic peak shapes, mz errors, rt errors, etc.
|
|
4
|
-
|
|
5
|
-
# imports
|
|
6
|
-
import numpy as np
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
"""
|
|
10
|
-
Functions
|
|
11
|
-
------------------------------------------------------------------------------------------------------------------------
|
|
12
|
-
"""
|
|
13
|
-
|
|
14
|
-
def calculate_gaussian_similarity(x, y):
|
|
15
|
-
"""
|
|
16
|
-
calculate the gaussian similarity using dot product
|
|
17
|
-
|
|
18
|
-
Parameters
|
|
19
|
-
----------
|
|
20
|
-
x: numpy array
|
|
21
|
-
Retention time
|
|
22
|
-
y: numpy array
|
|
23
|
-
Intensity
|
|
24
|
-
|
|
25
|
-
Returns
|
|
26
|
-
-------
|
|
27
|
-
float
|
|
28
|
-
similarity score
|
|
29
|
-
"""
|
|
30
|
-
|
|
31
|
-
if type(x) is not np.ndarray:
|
|
32
|
-
x = np.array(x)
|
|
33
|
-
if type(y) is not np.ndarray:
|
|
34
|
-
y = np.array(y)
|
|
35
|
-
|
|
36
|
-
# if the length of the peak is less than 5, return 0
|
|
37
|
-
if len(x) < 5:
|
|
38
|
-
return 0.0
|
|
39
|
-
|
|
40
|
-
# Estimate the parameters of the Gaussian function
|
|
41
|
-
# a: amplitude, b: mean, c: standard deviation
|
|
42
|
-
a = np.max(y)
|
|
43
|
-
idx = np.argmax(y)
|
|
44
|
-
b = x[idx]
|
|
45
|
-
|
|
46
|
-
c1 = x[-1] - b
|
|
47
|
-
c2 = b - x[0]
|
|
48
|
-
|
|
49
|
-
if idx == len(y) - 1:
|
|
50
|
-
c1 = 0
|
|
51
|
-
else:
|
|
52
|
-
for i in range(idx, len(y)):
|
|
53
|
-
if y[i] < a / 2:
|
|
54
|
-
c1 = x[i] - b
|
|
55
|
-
break
|
|
56
|
-
if idx == 0:
|
|
57
|
-
c2 = 0
|
|
58
|
-
else:
|
|
59
|
-
for i in range(idx, 0, -1):
|
|
60
|
-
if y[i] < a / 2:
|
|
61
|
-
c2 = b - x[i]
|
|
62
|
-
break
|
|
63
|
-
c = (c1 + c2) / 2.355
|
|
64
|
-
|
|
65
|
-
y_fit = _gaussian(x, a, b, c)
|
|
66
|
-
|
|
67
|
-
similarity = np.corrcoef(y, y_fit)[0, 1]
|
|
68
|
-
|
|
69
|
-
return np.max([0, similarity])
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
def calculate_noise_score(y, rel_int_tol=0.05, min_len=5):
|
|
73
|
-
"""
|
|
74
|
-
Calculate the noise score that reflect the signal fluctuation.
|
|
75
|
-
|
|
76
|
-
Parameters
|
|
77
|
-
----------
|
|
78
|
-
y: numpy array
|
|
79
|
-
Intensity
|
|
80
|
-
rel_int_tol: float
|
|
81
|
-
Relative intensity tolerance.
|
|
82
|
-
min_len: int
|
|
83
|
-
Minimum length of the peak to calculate the noise score.
|
|
84
|
-
|
|
85
|
-
Returns
|
|
86
|
-
-------
|
|
87
|
-
float
|
|
88
|
-
noise level
|
|
89
|
-
"""
|
|
90
|
-
|
|
91
|
-
y = y[y > np.max(y) * rel_int_tol]
|
|
92
|
-
|
|
93
|
-
if len(y) < min_len:
|
|
94
|
-
return np.nan
|
|
95
|
-
|
|
96
|
-
y = np.concatenate(([0], y, [0]))
|
|
97
|
-
diff = np.diff(y)
|
|
98
|
-
|
|
99
|
-
return np.sum(np.abs(diff)) / np.max(y) / 2 - 1
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
def calculate_asymmetry_factor(y):
|
|
103
|
-
"""
|
|
104
|
-
Calcualte the asymmetry factor of the peak at 10% of the peak height.
|
|
105
|
-
|
|
106
|
-
Parameters
|
|
107
|
-
----------
|
|
108
|
-
y: numpy array
|
|
109
|
-
Intensity
|
|
110
|
-
|
|
111
|
-
Returns
|
|
112
|
-
-------
|
|
113
|
-
float
|
|
114
|
-
asymmetry factor
|
|
115
|
-
"""
|
|
116
|
-
|
|
117
|
-
if len(y) < 5:
|
|
118
|
-
return 1.0
|
|
119
|
-
|
|
120
|
-
idx = np.argmax(y)
|
|
121
|
-
|
|
122
|
-
if idx == 0:
|
|
123
|
-
return 99.0
|
|
124
|
-
elif idx == len(y) - 1:
|
|
125
|
-
return 0.0
|
|
126
|
-
|
|
127
|
-
arr = y < 0.1 * y[idx]
|
|
128
|
-
|
|
129
|
-
left_idx = np.where(arr[:idx])[0]
|
|
130
|
-
right_idx = np.where(arr[idx:])[0]
|
|
131
|
-
|
|
132
|
-
if len(left_idx) == 0:
|
|
133
|
-
left_idx = 0
|
|
134
|
-
else:
|
|
135
|
-
left_idx = left_idx[-1]
|
|
136
|
-
|
|
137
|
-
if len(right_idx) == 0:
|
|
138
|
-
right_idx = len(y) - 1
|
|
139
|
-
else:
|
|
140
|
-
right_idx = right_idx[0] + idx
|
|
141
|
-
|
|
142
|
-
return (right_idx - idx) / (idx - left_idx)
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
def squared_error_to_smoothed_curve(original_signal, fit_signal):
|
|
146
|
-
"""
|
|
147
|
-
Calculate the sum of squared error between the original signal and the fitted signal.
|
|
148
|
-
|
|
149
|
-
Parameters
|
|
150
|
-
----------
|
|
151
|
-
original_signal: numpy array
|
|
152
|
-
The original signal.
|
|
153
|
-
fit_signal: numpy array
|
|
154
|
-
The fitted signal.
|
|
155
|
-
|
|
156
|
-
Returns
|
|
157
|
-
-------
|
|
158
|
-
float
|
|
159
|
-
The noise score.
|
|
160
|
-
"""
|
|
161
|
-
|
|
162
|
-
diff = (original_signal - fit_signal) / np.max(original_signal)
|
|
163
|
-
return np.sum(diff**2)
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
"""
|
|
167
|
-
Helper functions
|
|
168
|
-
------------------------------------------------------------------------------------------------------------------------
|
|
169
|
-
"""
|
|
170
|
-
|
|
171
|
-
# calculate the Gaussian similarity
|
|
172
|
-
def _gaussian(x, a, b, c):
|
|
173
|
-
"""
|
|
174
|
-
Gaussian function
|
|
175
|
-
|
|
176
|
-
Parameters
|
|
177
|
-
----------
|
|
178
|
-
x: numpy array
|
|
179
|
-
Retention time
|
|
180
|
-
a: float
|
|
181
|
-
Amplitude
|
|
182
|
-
b: float
|
|
183
|
-
Mean
|
|
184
|
-
c: float
|
|
185
|
-
Standard deviation
|
|
186
|
-
"""
|
|
187
|
-
return a * np.exp(-0.5 * ((x - b) / c) ** 2)
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|