masscube 1.2.4__tar.gz → 1.2.6__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 (28) hide show
  1. {masscube-1.2.4 → masscube-1.2.6}/PKG-INFO +15 -2
  2. {masscube-1.2.4 → masscube-1.2.6}/pyproject.toml +4 -3
  3. {masscube-1.2.4 → masscube-1.2.6}/src/masscube/alignment.py +24 -30
  4. {masscube-1.2.4 → masscube-1.2.6}/src/masscube/annotation.py +30 -9
  5. {masscube-1.2.4 → masscube-1.2.6}/src/masscube/feature_detection.py +3 -1
  6. {masscube-1.2.4 → masscube-1.2.6}/src/masscube/feature_evaluation.py +8 -5
  7. {masscube-1.2.4 → masscube-1.2.6}/src/masscube/feature_grouping.py +12 -13
  8. {masscube-1.2.4 → masscube-1.2.6}/src/masscube/network.py +0 -1
  9. {masscube-1.2.4 → masscube-1.2.6}/src/masscube/normalization.py +55 -21
  10. {masscube-1.2.4 → masscube-1.2.6}/src/masscube/params.py +54 -37
  11. {masscube-1.2.4 → masscube-1.2.6}/src/masscube/raw_data_utils.py +66 -80
  12. {masscube-1.2.4 → masscube-1.2.6}/src/masscube/stats.py +3 -1
  13. masscube-1.2.6/src/masscube/utils_functions.py +558 -0
  14. {masscube-1.2.4 → masscube-1.2.6}/src/masscube/visualization.py +59 -41
  15. {masscube-1.2.4 → masscube-1.2.6}/src/masscube/workflows.py +36 -15
  16. {masscube-1.2.4 → masscube-1.2.6}/src/masscube.egg-info/PKG-INFO +15 -2
  17. {masscube-1.2.4 → masscube-1.2.6}/src/masscube.egg-info/requires.txt +1 -0
  18. masscube-1.2.4/src/masscube/utils_functions.py +0 -273
  19. {masscube-1.2.4 → masscube-1.2.6}/LICENSE +0 -0
  20. {masscube-1.2.4 → masscube-1.2.6}/README.md +0 -0
  21. {masscube-1.2.4 → masscube-1.2.6}/setup.cfg +0 -0
  22. {masscube-1.2.4 → masscube-1.2.6}/src/masscube/__init__.py +0 -0
  23. {masscube-1.2.4 → masscube-1.2.6}/src/masscube/classifier_builder.py +0 -0
  24. {masscube-1.2.4 → masscube-1.2.6}/src/masscube/mzpkl.py +0 -0
  25. {masscube-1.2.4 → masscube-1.2.6}/src/masscube.egg-info/SOURCES.txt +0 -0
  26. {masscube-1.2.4 → masscube-1.2.6}/src/masscube.egg-info/dependency_links.txt +0 -0
  27. {masscube-1.2.4 → masscube-1.2.6}/src/masscube.egg-info/entry_points.txt +0 -0
  28. {masscube-1.2.4 → masscube-1.2.6}/src/masscube.egg-info/top_level.txt +0 -0
@@ -1,6 +1,6 @@
1
- Metadata-Version: 2.1
1
+ Metadata-Version: 2.4
2
2
  Name: masscube
3
- Version: 1.2.4
3
+ Version: 1.2.6
4
4
  Summary: Accurate and fast data processing for metabolomics
5
5
  Author-email: Huaxu Yu <yhxchem@outlook.com>
6
6
  Maintainer-email: Huaxu Yu <yhxchem@outlook.com>
@@ -12,6 +12,19 @@ Classifier: Operating System :: OS Independent
12
12
  Requires-Python: >=3.8
13
13
  Description-Content-Type: text/markdown
14
14
  License-File: LICENSE
15
+ Requires-Dist: numpy>=1.24
16
+ Requires-Dist: pandas>=2.2.1
17
+ Requires-Dist: pyteomics==4.6.3
18
+ Requires-Dist: scipy>=1.10.1
19
+ Requires-Dist: tqdm>=4.66.1
20
+ Requires-Dist: lxml>=4.9.3
21
+ Requires-Dist: matplotlib>=3.8.2
22
+ Requires-Dist: ms_entropy==1.3.4
23
+ Requires-Dist: scikit-learn>=1.3.2
24
+ Requires-Dist: statsmodels>=0.14.2
25
+ Requires-Dist: umap-learn>=0.5.7
26
+ Requires-Dist: IsoSpecPy>=2.2.3
27
+ Dynamic: license-file
15
28
 
16
29
  # MassCube
17
30
 
@@ -1,10 +1,10 @@
1
1
  [build-system]
2
- requires = ["setuptools<66", "wheel"]
2
+ requires = ["setuptools>=66.1.0"]
3
3
  build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "masscube"
7
- version = "1.2.4"
7
+ version = "1.2.6"
8
8
  authors = [
9
9
  { name="Huaxu Yu", email="yhxchem@outlook.com" },
10
10
  ]
@@ -31,7 +31,8 @@ dependencies = [
31
31
  "ms_entropy==1.3.4",
32
32
  "scikit-learn>=1.3.2",
33
33
  "statsmodels>=0.14.2",
34
- "umap-learn>=0.5.7"
34
+ "umap-learn>=0.5.7",
35
+ "IsoSpecPy>=2.2.3"
35
36
  ]
36
37
 
37
38
  [project.scripts]
@@ -61,6 +61,7 @@ class AlignedFeature:
61
61
  self.rt = 0.0 # retention time
62
62
  self.reference_file = None # the reference file with the highest peak height
63
63
  self.reference_scan_idx = None # the scan index of the peak apex from the reference file
64
+ self.reference_peak_shape = None # the representative peak shape: [[rt, intensity], ...]
64
65
  self.highest_intensity = 0.0 # the highest peak height from individual files (which is the reference file)
65
66
  self.ms2 = None # representative MS2 spectrum
66
67
  self.ms2_reference_file = None # the reference file for the representative MS2 spectrum
@@ -75,7 +76,6 @@ class AlignedFeature:
75
76
  self.is_in_source_fragment = False # whether it is an in-source fragment
76
77
  self.adduct_type = None # adduct type
77
78
 
78
- self.annotation_algorithm = None # annotation algorithm. Not used now.
79
79
  self.search_mode = None # 'identity search', 'fuzzy search', or 'mzrt_search'
80
80
  self.similarity = None # similarity score (0-1)
81
81
  self.annotation = None # name of annotated compound
@@ -87,6 +87,7 @@ class AlignedFeature:
87
87
  self.matched_retention_time = None # matched retention time
88
88
  self.matched_adduct_type = None # matched adduct type
89
89
  self.matched_ms2 = None # matched ms2 spectra
90
+ self.matched_spectra = [] # list of matched spectra (dictionaries)
90
91
 
91
92
 
92
93
  """
@@ -113,37 +114,30 @@ def feature_alignment(path: str, params: Params):
113
114
 
114
115
  # STEP 1: preparation
115
116
  features = []
116
- names = [f + ".txt" for f in params.sample_names]
117
- names = [os.path.join(path, name) for name in names]
118
- not_found_files = [params.sample_names[i] for i in range(len(names)) if not os.path.exists(names[i])]
119
- if len(not_found_files) > 0:
120
- for f in not_found_files:
121
- params.problematic_files[f] = "file does not exist"
122
- # remove those files from names
123
- names = [names[i] for i in range(len(names)) if params.sample_names[i] not in not_found_files]
124
- # remove those files from sample metadata
125
- params.sample_metadata = params.sample_metadata[~params.sample_metadata.iloc[:,1].isin(not_found_files)]
126
- params.sample_names = list(params.sample_metadata.iloc[:, 0])
117
+ params.sample_metadata['SINGLE_FILE_PATH'] = [os.path.join(path, f + ".txt") for f in params.sample_metadata.iloc[:, 0]]
118
+ for i in range(len(params.sample_metadata)):
119
+ if not os.path.exists(params.sample_metadata['SINGLE_FILE_PATH'][i]):
120
+ params.sample_metadata.loc[i, "VALID"] = False
121
+ # remove invalid files
122
+ params.sample_metadata = params.sample_metadata[params.sample_metadata["VALID"]]
123
+ params.sample_metadata.index = np.arange(len(params.sample_metadata))
127
124
 
128
125
  # find anchors for retention time correction
129
126
  if params.correct_rt:
130
127
  intensities = []
131
- for n in names:
128
+ for n in params.sample_metadata['SINGLE_FILE_PATH']:
132
129
  df = pd.read_csv(n, sep="\t", low_memory=False)
133
130
  intensities.append(np.sum(df["peak_height"]))
134
131
  # use the file with median total intensity as the reference file
135
- anchor_selection_name = names[np.argsort(intensities)[len(intensities)//2]]
132
+ anchor_selection_name = params.sample_metadata['SINGLE_FILE_PATH'][np.argsort(intensities)[len(intensities)//2]]
136
133
  mz_ref, rt_ref = rt_anchor_selection(anchor_selection_name, num=100)
137
134
  rt_cor_functions = {}
138
135
 
139
136
  # STEP 2: read individual feature tables and align features
140
- for i, file_name in enumerate(tqdm(params.sample_names)):
141
-
142
- if not os.path.exists(names[i]):
143
- continue
144
-
137
+ for i in tqdm(range(len(params.sample_metadata))):
138
+ file_name = params.sample_metadata.iloc[i, 0]
145
139
  # read feature table
146
- current_table = pd.read_csv(names[i], low_memory=False, sep="\t")
140
+ current_table = pd.read_csv(params.sample_metadata['SINGLE_FILE_PATH'][i], sep="\t", low_memory=False)
147
141
  current_table = current_table[current_table["MS2"].notna()|(current_table["total_scans"]>params.scan_number_cutoff)]
148
142
 
149
143
  # sort current table by peak height from high to low
@@ -170,14 +164,14 @@ def feature_alignment(path: str, params: Params):
170
164
  availible_features[idx[0]] = False
171
165
  # check if this file can be the reference file
172
166
  if current_table.loc[idx[0], "peak_height"] > f.highest_intensity:
173
- _assign_reference_values(f=f, df=current_table, i=i, p=idx[0], file_name=file_name)
167
+ _assign_reference_values(f=f, df=current_table, p=idx[0], file_name=file_name)
174
168
 
175
169
  # if an feature is not detected in the previous files, add it to the features
176
170
  for j, b in enumerate(availible_features):
177
171
  if b:
178
- f = AlignedFeature(file_number=len(params.sample_names))
172
+ f = AlignedFeature(file_number=len(params.sample_metadata))
179
173
  _assign_value_to_feature(f=f, df=current_table, i=i, p=j, file_name=file_name)
180
- _assign_reference_values(f=f, df=current_table, i=i, p=j, file_name=file_name)
174
+ _assign_reference_values(f=f, df=current_table, p=j, file_name=file_name)
181
175
  features.append(f)
182
176
 
183
177
  # summarize (calculate the average mz and rt) and reorder the features
@@ -251,10 +245,11 @@ def gap_filling(features, params: Params):
251
245
  else:
252
246
  rt_cor_functions = None
253
247
 
254
- for i, file_name in enumerate(tqdm(params.sample_names)):
248
+ for i in tqdm(range(len(params.sample_metadata))):
249
+ file_name = params.sample_metadata.iloc[i, 0]
255
250
  fn = os.path.join(params.tmp_file_dir, file_name + ".mzpkl")
256
251
  if os.path.exists(fn):
257
- d = read_raw_file_to_obj(fn)
252
+ d = read_raw_file_to_obj(fn, ms1_abs_int_tol=params.ms1_abs_int_tol, centroid_mz_tol=None)
258
253
  # correct retention time if model is available
259
254
  if rt_cor_functions is not None and file_name in rt_cor_functions.keys():
260
255
  f = rt_cor_functions[file_name]
@@ -367,7 +362,7 @@ def convert_features_to_df(features, sample_names, quant_method="peak_height"):
367
362
  results = []
368
363
  sample_names = list(sample_names)
369
364
  columns=["group_ID", "feature_ID", "m/z", "RT", "adduct", "is_isotope", "is_in_source_fragment", "Gaussian_similarity", "noise_score",
370
- "asymmetry_factor", "detection_rate", "detection_rate_gap_filled", "alignment_reference_file", "charge", "isotopes", "MS2_reference_file", "MS2", "matched_MS2",
365
+ "asymmetry_factor", "peak_shape", "detection_rate", "detection_rate_gap_filled", "alignment_reference_file", "charge", "isotopes", "MS2_reference_file", "MS2", "matched_MS2",
371
366
  "search_mode", "annotation", "formula", "similarity", "matched_peak_number", "SMILES", "InChIKey"] + sample_names
372
367
 
373
368
  for f in features:
@@ -381,7 +376,7 @@ def convert_features_to_df(features, sample_names, quant_method="peak_height"):
381
376
  quant = [int(x) for x in quant]
382
377
 
383
378
  results.append([f.feature_group_id, f.id, f.mz, f.rt, f.adduct_type, f.is_isotope, f.is_in_source_fragment, f.gaussian_similarity, f.noise_score,
384
- f.asymmetry_factor, f.detection_rate, f.detection_rate_gap_filled, f.reference_file, f.charge_state, f.isotope_signals, f.ms2_reference_file,
379
+ f.asymmetry_factor, f.reference_peak_shape, f.detection_rate, f.detection_rate_gap_filled, f.reference_file, f.charge_state, f.isotope_signals, f.ms2_reference_file,
385
380
  f.ms2, f.matched_ms2, f.search_mode, f.annotation, f.formula, f.similarity, f.matched_peak_number, f.smiles, f.inchikey] + quant)
386
381
 
387
382
  feature_table = pd.DataFrame(results, columns=columns)
@@ -644,7 +639,7 @@ def _assign_value_to_feature(f, df, i, p, file_name):
644
639
  f.ms2_seq.append([file_name, df.loc[p, "MS2"]])
645
640
 
646
641
 
647
- def _assign_reference_values(f, df, i, p, file_name):
642
+ def _assign_reference_values(f, df, p, file_name):
648
643
  """
649
644
  Assign the reference values to the aligned feature.
650
645
 
@@ -654,8 +649,6 @@ def _assign_reference_values(f, df, i, p, file_name):
654
649
  The aligned feature.
655
650
  df: DataFrame
656
651
  The feature table from the individual file.
657
- i: int
658
- The file index among all files to be aligned.
659
652
  p: int
660
653
  The row index of the feature in the current individual file.
661
654
  file_name: str
@@ -666,6 +659,7 @@ def _assign_reference_values(f, df, i, p, file_name):
666
659
  f.rt = df.loc[p, "RT"]
667
660
  f.reference_file = file_name
668
661
  f.reference_scan_idx = df.loc[p, "scan_idx"]
662
+ f.reference_peak_shape = df.loc[p, "peak_shape"]
669
663
  f.highest_intensity = df.loc[p, "peak_height"]
670
664
  f.gaussian_similarity = df.loc[p, "Gaussian_similarity"]
671
665
  f.noise_score = df.loc[p, "noise_score"]
@@ -40,6 +40,7 @@ Within each block, key is defined as:
40
40
  - INCHIKEY: the InChIKey
41
41
  - INSTRUMENTTYPE: the instrument type
42
42
  - COLLISIONENERGY: the collision energy
43
+ - DATABASE: the database name
43
44
  - COMMENT: the comment
44
45
  - Num Peaks: the number of peaks
45
46
  - [mz1 intensity1]: the m/z and intensity of each fragment
@@ -59,6 +60,7 @@ Example:
59
60
  INCHIKEY: COLNVLDHVKWLRT-QMMMGPOBSA-N
60
61
  INSTRUMENTTYPE: LC-ESI-QFT
61
62
  COLLISIONENERGY: 35.0 eV
63
+ DATABASE: EMBL-MCF_spec98214
62
64
  COMMENT: DB#=EMBL-MCF_spec98214; origin=EMBL - Metabolomics Core Facility Spectral Library
63
65
  Num Peaks: 7
64
66
  103.054 15
@@ -69,7 +71,7 @@ Example:
69
71
  149.059 16
70
72
  166.086 56
71
73
 
72
- 3. json format
74
+ 3. a list of dictionaries (or json format)
73
75
 
74
76
  A list of dictionaries, each dictionary contains the following keys:
75
77
 
@@ -84,10 +86,11 @@ A list of dictionaries, each dictionary contains the following keys:
84
86
  "ontology": the ontology of the compound
85
87
  "smiles": the SMILES string
86
88
  "inchikey": the InChIKey
87
- "instrumenttype": the instrument type
88
- "collisionenergy": the collision energy
89
+ "instrument_type": the instrument type
90
+ "collision_energy": the collision energy
91
+ "database": the database name
89
92
  "comment": the comment
90
- "num peaks": the number of peaks
93
+ "num_peaks": the number of peaks
91
94
  "peaks": a list of lists, each sublist contains two elements: m/z and intensity: [[mz1, intensity1], [mz2, intensity2], ...]
92
95
  }
93
96
 
@@ -103,10 +106,11 @@ Example:
103
106
  "ontology": "Phenylalanine and derivatives",
104
107
  "smiles": "C1=CC=C(C=C1)C[C@@H](C(=O)O)N",
105
108
  "inchikey": "COLNVLDHVKWLRT-QMMMGPOBSA-N",
106
- "instrumenttype": "LC-ESI-QFT",
107
- "collisionenergy": "35.0 eV",
109
+ "instrument_type": "LC-ESI-QFT",
110
+ "collision_energy": "35.0 eV",
111
+ "database": "EMBL-MCF_spec98214"
108
112
  "comment": "DB#=EMBL-MCF_spec98214; origin=EMBL - Metabolomics Core Facility Spectral Library",
109
- "num peaks": "7",
113
+ "num_peaks": "7",
110
114
  "peaks": [["103.054", "15"], ["107.049", "14"], ["120.081", "1000"], ["121.084", "16"], ["131.049", "41"], ["149.059", "16"], ["166.086", "56"]],
111
115
  }
112
116
 
@@ -165,7 +169,7 @@ def load_ms2_db(path):
165
169
  a['precursor_type'] = a.pop('precursortype')
166
170
  if 'ionmode' in a.keys():
167
171
  a['ion_mode'] = a.pop('ionmode')
168
- if 'retentiontime' in a.keys():
172
+ if 'retentiontime' in a.keys() and a['retentiontime'] != '':
169
173
  a['retention_time'] = float(a.pop('retentiontime'))
170
174
  db.append(a)
171
175
  _correct_db(db)
@@ -214,6 +218,10 @@ def annotate_aligned_features(features, params, num=5):
214
218
 
215
219
  entropy_search = load_ms2_db(params.ms2_library_path)
216
220
 
221
+ # ion mode filtering
222
+ ion_mode_mask = np.array([1 if (entropy_search[i]['ion_mode'].lower() == params.ion_mode) else 0 for
223
+ i in range(len(entropy_search.precursor_mz_array))], dtype=bool)
224
+
217
225
  if params.consider_rt:
218
226
  rt_arr = np.zeros(len(entropy_search.precursor_mz_array))+np.inf
219
227
  for i, ms2 in enumerate(entropy_search):
@@ -230,8 +238,13 @@ def annotate_aligned_features(features, params, num=5):
230
238
  for file_name, ms2 in f.ms2_seq:
231
239
  signals = extract_signals_from_string(ms2)
232
240
  signals = entropy_search.clean_spectrum_for_search(f.mz, signals, precursor_ions_removal_da=params.precursor_mz_offset)
241
+ if len(signals) == 0:
242
+ continue
233
243
  parsed_ms2.append([file_name, signals])
234
244
 
245
+ if len(parsed_ms2) == 0:
246
+ continue
247
+
235
248
  parsed_ms2.sort(key=lambda x: np.sum(x[1][:, 1]), reverse=True)
236
249
  parsed_ms2 = parsed_ms2[:num]
237
250
  f.ms2_reference_file = parsed_ms2[0][0]
@@ -246,7 +259,7 @@ def annotate_aligned_features(features, params, num=5):
246
259
  for file_name, signals in parsed_ms2:
247
260
  similarity, matched_num = entropy_search.identity_search(precursor_mz=f.mz, peaks=signals, ms1_tolerance_in_da=params.mz_tol_ms1,
248
261
  ms2_tolerance_in_da=params.mz_tol_ms2, output_matched_peak_number=True)
249
- similarities.append(similarity)
262
+ similarities.append(similarity * ion_mode_mask)
250
263
  matched_nums.append(matched_num)
251
264
 
252
265
  if params.consider_rt:
@@ -279,6 +292,7 @@ def annotate_aligned_features(features, params, num=5):
279
292
  if matched is None and params.fuzzy_search:
280
293
  similarity = entropy_search.hybrid_search(precursor_mz=f.mz, peaks=f.ms2, ms1_tolerance_in_da=params.mz_tol_ms1,
281
294
  ms2_tolerance_in_da=params.mz_tol_ms2)
295
+ similarity = similarity * ion_mode_mask
282
296
  idx = np.argmax(similarity)
283
297
  if similarity[idx] > params.ms2_sim_tol:
284
298
  matched = entropy_search[idx]
@@ -315,6 +329,10 @@ def annotate_features(d, sim_tol=None, fuzzy_search=True, ms2_library_path=None,
315
329
  search_engine = load_ms2_db(d.params.ms2_library_path)
316
330
  else:
317
331
  search_engine = load_ms2_db(ms2_library_path)
332
+
333
+ # ion mode filtering
334
+ ion_mode_mask = np.array([1 if (search_engine[i]['ion_mode'].lower() == d.params.ion_mode) else 0 for
335
+ i in range(len(search_engine.precursor_mz_array))], dtype=bool)
318
336
 
319
337
  if sim_tol is None:
320
338
  sim_tol = d.params.ms2_sim_tol
@@ -333,8 +351,11 @@ def annotate_features(d, sim_tol=None, fuzzy_search=True, ms2_library_path=None,
333
351
  matched = None
334
352
  matched_peak_num = None
335
353
  signals = search_engine.clean_spectrum_for_search(precursor_mz=f.mz, peaks=f.ms2.signals, precursor_ions_removal_da=2.0)
354
+ if len(signals) == 0:
355
+ continue
336
356
  scores, peak_nums = search_engine.identity_search(precursor_mz=f.mz, peaks=signals, ms1_tolerance_in_da=d.params.mz_tol_ms1,
337
357
  ms2_tolerance_in_da=d.params.mz_tol_ms2, output_matched_peak_number=True)
358
+ scores = ion_mode_mask
338
359
  if consider_rt:
339
360
  rt_boo = np.abs(rt_arr - f.rt) < d.params.rt_tol_annotation
340
361
  scores_rt = scores * rt_boo
@@ -30,6 +30,7 @@ class Feature:
30
30
  self.scan_idx_seq = [] # scan index sequence
31
31
  self.ms2_seq = [] # MS2 spectra
32
32
  self.gap_counter = 0 # count the number of consecutive zeros in the end of the peak
33
+ self.peak_shape = None # peak shape ([[rt, intensity], ...])
33
34
 
34
35
  # summary
35
36
  self.id = None # feature id
@@ -49,7 +50,7 @@ class Feature:
49
50
  self.is_segmented = False # whether the feature is segmented from a larger feature
50
51
  self.is_isotope = None # whether the feature is an isotope
51
52
  self.charge_state = 1 # charge state of the feature
52
- self.isotope_signals = [] # isotope signals [[mz, intensity], ...]
53
+ self.isotope_signals = None # isotope signals [[mz, intensity], ...]
53
54
  self.is_in_source_fragment = None # whether the feature is an in-source fragment
54
55
  self.adduct_type = None # adduct type
55
56
 
@@ -143,6 +144,7 @@ class Feature:
143
144
  self.rt = self.rt_seq[apx]
144
145
  self.scan_idx = self.scan_idx_seq[apx]
145
146
  self.length = np.sum(self.signals[:, 1] > 0)
147
+ self.peak_shape = np.array([[self.rt_seq[i], self.signals[i, 1]] for i in range(len(self.signals))])
146
148
 
147
149
  if ph:
148
150
  self.peak_height = int(self.signals[apx, 1])
@@ -69,7 +69,7 @@ def calculate_gaussian_similarity(x, y):
69
69
  return np.max([0, similarity])
70
70
 
71
71
 
72
- def calculate_noise_score(y, rel_int_tol=0.05):
72
+ def calculate_noise_score(y, rel_int_tol=0.05, min_len=5):
73
73
  """
74
74
  Calculate the noise score that reflect the signal fluctuation.
75
75
 
@@ -79,6 +79,8 @@ def calculate_noise_score(y, rel_int_tol=0.05):
79
79
  Intensity
80
80
  rel_int_tol: float
81
81
  Relative intensity tolerance.
82
+ min_len: int
83
+ Minimum length of the peak to calculate the noise score.
82
84
 
83
85
  Returns
84
86
  -------
@@ -88,12 +90,13 @@ def calculate_noise_score(y, rel_int_tol=0.05):
88
90
 
89
91
  y = y[y > np.max(y) * rel_int_tol]
90
92
 
91
- if len(y) < 5:
92
- return 0.0
93
+ if len(y) < min_len:
94
+ return np.nan
93
95
 
96
+ y = np.concatenate(([0], y, [0]))
94
97
  diff = np.diff(y)
95
- score = np.sum(np.abs(diff)) / np.max(y) / 2 - 1
96
- return np.max([0, score])
98
+
99
+ return np.sum(np.abs(diff)) / np.max(y) / 2 - 1
97
100
 
98
101
 
99
102
  def calculate_asymmetry_factor(y):
@@ -71,11 +71,11 @@ def group_features_after_alignment(features, params: Params):
71
71
 
72
72
  k = np.argmin(np.abs(d.ms1_time_arr-f.rt))
73
73
 
74
- f.isotope_signals = find_isotope_signals(mz=f.mz, intensity=np.max(eic_a[:,1]), signals=d.scans[d.ms1_idx[k]].signals,
74
+ f.isotope_signals = find_isotope_signals(mz=f.mz, signals=d.scans[d.ms1_idx[k]].signals,
75
75
  mz_tol=params.mz_tol_feature_grouping, rel_int_limit=params.isotope_rel_int_limit)
76
76
  if f.adduct_type is None:
77
77
  f.adduct_type = "[M+H]+" if params.ion_mode.lower() == "positive" else "[M-H]-"
78
- for s in f.isotope_signals:
78
+ for s in f.isotope_signals[1:]:
79
79
  w1 = np.abs(mz_arr - s[0]) < params.mz_tol_feature_grouping
80
80
  w2 = np.abs(rt_arr - f.rt) < params.rt_tol_feature_grouping
81
81
  w = np.where(w1 & w2 & to_anno)[0]
@@ -107,11 +107,11 @@ def group_features_after_alignment(features, params: Params):
107
107
  features[vi].is_in_source_fragment = True
108
108
  features[vi].adduct_type = "ISF"
109
109
  # find isotopes for this ion and do not use scan-to-scan correlation
110
- features[vi].isotope_signals = find_isotope_signals(features[vi].mz, intensity=np.max(eic_b),
110
+ features[vi].isotope_signals = find_isotope_signals(features[vi].mz,
111
111
  signals=d.scans[d.ms1_idx[k]].signals, mz_tol=params.mz_tol_feature_grouping,
112
112
  rel_int_limit=params.isotope_rel_int_limit)
113
113
  # retrieve the isotope signals from the feature list
114
- for s in features[vi].isotope_signals:
114
+ for s in features[vi].isotope_signals[1:]:
115
115
  w1 = np.abs(mz_arr - s[0]) < params.mz_tol_feature_grouping
116
116
  w2 = np.abs(rt_arr - f.rt) < params.rt_tol_feature_grouping
117
117
  w = np.where(w1 & w2 & to_anno)[0]
@@ -155,11 +155,11 @@ def group_features_single_file(d):
155
155
  _, eic_a, _ = d.get_eic_data(f.mz, f.rt, mz_tol=d.params.mz_tol_ms1, rt_tol=0.25)
156
156
  k = np.argmin(np.abs(d.ms1_time_arr-f.rt))
157
157
 
158
- f.isotope_signals = find_isotope_signals(mz=f.mz, intensity=np.max(eic_a), signals=d.scans[k].signals,
158
+ f.isotope_signals = find_isotope_signals(mz=f.mz, signals=d.scans[k].signals,
159
159
  mz_tol=d.params.mz_tol_feature_grouping, rel_int_limit=d.params.isotope_rel_int_limit)
160
160
  if f.adduct_type is None:
161
161
  f.adduct_type = "[M+H]+" if d.params.ion_mode.lower() == "positive" else "[M-H]-"
162
- for s in f.isotope_signals:
162
+ for s in f.isotope_signals[1:]:
163
163
  w1 = np.abs(mz_arr - s[0]) < d.params.mz_tol_feature_grouping
164
164
  w2 = np.abs(rt_arr - f.rt) < d.params.rt_tol_feature_grouping
165
165
  w = np.where(w1 & w2 & to_anno)[0]
@@ -191,10 +191,10 @@ def group_features_single_file(d):
191
191
  d.features[vi].is_in_source_fragment = True
192
192
  d.features[vi].adduct_type = "ISF"
193
193
  # find isotopes for this ion and do not use scan-to-scan correlation
194
- d.features[vi].isotope_signals = find_isotope_signals(mz=d.features[vi].mz, intensity=np.max(eic_b), signals=d.scans[k].signals,
194
+ d.features[vi].isotope_signals = find_isotope_signals(mz=d.features[vi].mz, signals=d.scans[k].signals,
195
195
  mz_tol=d.params.mz_tol_feature_grouping, rel_int_limit=d.params.isotope_rel_int_limit)
196
196
  # retrieve the isotope signals from the feature list
197
- for s in d.features[vi].isotope_signals:
197
+ for s in d.features[vi].isotope_signals[1:]:
198
198
  w1 = np.abs(mz_arr - s[0]) < d.params.mz_tol_feature_grouping
199
199
  w2 = np.abs(rt_arr - f.rt) < d.params.rt_tol_feature_grouping
200
200
  w = np.where(w1 & w2 & to_anno)[0]
@@ -255,7 +255,7 @@ def generate_search_dict(feature, adduct_form, ion_mode):
255
255
  return search_dict
256
256
 
257
257
 
258
- def find_isotope_signals(mz, intensity, signals, mz_tol=0.012, charge_state=1, num=5, rel_int_limit=1.5):
258
+ def find_isotope_signals(mz, signals, mz_tol=0.012, charge_state=1, num=5, rel_int_limit=1.5):
259
259
  """
260
260
  Find isotope patterns from the MS1 signals.
261
261
 
@@ -263,8 +263,6 @@ def find_isotope_signals(mz, intensity, signals, mz_tol=0.012, charge_state=1, n
263
263
  ----------
264
264
  mz: float
265
265
  The m/z value of the feature.
266
- intensity: float
267
- The intensity of the feature's peak apex.
268
266
  signals: np.array
269
267
  The MS1 signals as [[m/z, intensity], ...]
270
268
  mz_tol: float
@@ -284,9 +282,10 @@ def find_isotope_signals(mz, intensity, signals, mz_tol=0.012, charge_state=1, n
284
282
 
285
283
  diff = signals[:, 0] - mz
286
284
  isotope_signals = []
287
- limit = rel_int_limit * intensity
285
+
288
286
  if charge_state == 1:
289
- for i in range(1, num):
287
+ limit = signals[np.argmin(np.abs(diff))][1] * rel_int_limit
288
+ for i in range(num):
290
289
  v = np.abs(diff - 1.003355*i) < mz_tol
291
290
  if np.sum(v) > 0:
292
291
  tmp = signals[v]
@@ -84,7 +84,6 @@ def network_analysis(feature_list, annotation_type="hybrid_and_identity", featur
84
84
  # hide outer frame
85
85
  plt.box(False)
86
86
  plt.rcParams['font.size'] = 12
87
- plt.rcParams['font.family'] = 'Arial'
88
87
  # add legend with arial font
89
88
  plt.legend(handles=[plt.Line2D([0], [0], color="#BC6C25", marker="o", lw=0, markersize=7, label="Identity", markeredgewidth=0.5, markeredgecolor="black", alpha=0.5),
90
89
  plt.Line2D([0], [0], color="#FEFAE0", marker="o", lw=0, markersize=7, label="Hybrid", markeredgewidth=0.5, markeredgecolor="black", alpha=0.5),
@@ -280,23 +280,23 @@ def signal_normalization(feature_table, sample_metadata, method='lowess', output
280
280
  # STEP 2: get analytical order
281
281
  tmp = sample_metadata.sort_values(by="analytical_order")
282
282
  samples = tmp.iloc[:, 0].values
283
- qc_idx = tmp['is_qc'].values
284
- sample_idx = ~tmp['is_blank'].values
283
+ is_qc = tmp['is_qc'].values
284
+ is_qc_or_sample = ~tmp['is_blank'].values
285
+ batch_ids = tmp['batch_id'].values
285
286
 
286
287
  arr = feature_table.loc[:, samples].values
287
288
  n = len(samples)
288
- n_qc = np.sum(qc_idx)
289
289
 
290
290
  # STEP 3: normalize samples
291
291
  if method == 'lowess':
292
292
  print("\tSignal normalization is running: lowess normalization.")
293
293
  for id, a in enumerate(tqdm(arr)):
294
- r = lowess_normalization(a, qc_idx, frac=np.min([0.5, 8/n_qc]), it=3)
294
+ r = lowess_normalization(a, is_qc, batch_ids=batch_ids)
295
295
  if r['fit_curve'] is not None:
296
296
  # visualization
297
297
  if output_plot_path is not None:
298
298
  plot_lowess_normalization(arr=a, fit_curve=r['fit_curve'], arr_new=r['normed_arr'],
299
- sample_idx=sample_idx, qc_idx=qc_idx, n=n, id=id, output_dir=output_plot_path)
299
+ is_qc_or_sample=is_qc_or_sample, qc_idx=is_qc, n=n, id=id, output_dir=output_plot_path)
300
300
  arr[id] = r['normed_arr']
301
301
 
302
302
  feature_table.loc[:, samples] = arr
@@ -304,7 +304,7 @@ def signal_normalization(feature_table, sample_metadata, method='lowess', output
304
304
  return feature_table
305
305
 
306
306
 
307
- def lowess_normalization(array, qc_idx, frac=0.07, it=3):
307
+ def lowess_normalization(array, is_qc, it=3, batch_ids=None, frac=None):
308
308
  """
309
309
  A function to normalize samples using quality control samples.
310
310
 
@@ -312,13 +312,15 @@ def lowess_normalization(array, qc_idx, frac=0.07, it=3):
312
312
  ----------
313
313
  array : numpy array
314
314
  The data to be normalized.
315
- qc_idx : numpy array of bool
315
+ is_qc : numpy array of bool
316
316
  Boolean array indicating whether a sample is a quality control sample. It's length
317
317
  should be the same as the length of array.
318
318
  frac : float
319
319
  The fraction of the data used when estimating each y-value (used in lowess). See statsmodels package for details.
320
320
  it : int
321
321
  The number of residual-based reweightings to perform (used in lowess). See statsmodels package for details.
322
+ batch_ids : numpy array
323
+ The batch IDs of the samples. If provided, the normalization will be performed within each batch and then combined.
322
324
 
323
325
  Returns
324
326
  -------
@@ -328,19 +330,51 @@ def lowess_normalization(array, qc_idx, frac=0.07, it=3):
328
330
  """
329
331
 
330
332
  # only use qc data > 0 for normalization
331
- valid_idx = qc_idx & (array > 0)
332
- qc_arr = array[valid_idx]
333
-
334
- # if there are more than 2 QC samples
335
- if len(qc_arr) > 2:
336
- x = np.arange(len(array))
337
- model = lowess(qc_arr, x[valid_idx], frac=frac, it=it)
338
- y = np.interp(x, model[:, 0], model[:, 1])
339
- y[y < 1] = 1 # gap filling
340
- int_arr_corr = array / y * np.max(y)
341
- else:
333
+ valid_idx = is_qc & (array > 0)
334
+
335
+ if batch_ids is None:
336
+ batch_ids = np.zeros(len(array), dtype=int)
337
+
338
+ unique_batch_ids = np.unique(batch_ids)
339
+ x = np.arange(len(array))
340
+
341
+ fitted_y = np.ones(len(array))
342
+ models = []
343
+
344
+ not_corrected_batches = []
345
+
346
+ for id in unique_batch_ids:
347
+ qc_idx_i = valid_idx & (batch_ids == id)
348
+ if np.sum(qc_idx_i) > 2:
349
+ # apply lowess normalization
350
+ frac = np.min([0.8, 8/np.sum(qc_idx_i)])
351
+ xi = x[batch_ids == id]
352
+ model = lowess(array[qc_idx_i], x[qc_idx_i], frac=frac, it=it)
353
+ yi = np.interp(xi, model[:, 0], model[:, 1])
354
+ yi[yi < 1] = 1 # gap filling
355
+ fitted_y[batch_ids == id] = yi
356
+ else:
357
+ # perform no correction
358
+ model = None
359
+ not_corrected_batches.append(id)
360
+
361
+ models.append(model)
362
+
363
+ # calculate the corrected intensity array
364
+ int_arr_corr = array / fitted_y * np.max(fitted_y)
365
+
366
+ # for not corrected batches, change it back to the original data
367
+ for id in not_corrected_batches:
368
+ int_arr_corr[batch_ids == id] = array[batch_ids == id]
369
+
370
+ # check the normalization results, if the normed RSD is bigger than the original RSD, then use the original data
371
+ tmp = array[is_qc]
372
+ tmp_normed = int_arr_corr[is_qc]
373
+ tmp = tmp[tmp > 0]
374
+ tmp_normed = tmp_normed[tmp_normed > 0]
375
+ if (len(tmp) == 0) or (len(tmp_normed) == 0) or (np.std(tmp_normed) / np.mean(tmp_normed) > np.std(tmp) / np.mean(tmp)):
342
376
  int_arr_corr = array
343
- y = None
344
- model = None
377
+ models = [None] * len(unique_batch_ids)
378
+ fitted_y = np.ones(len(array))
345
379
 
346
- return {'model': model, 'fit_curve': y, 'normed_arr': int_arr_corr}
380
+ return {'model': models, 'fit_curve': fitted_y, 'normed_arr': int_arr_corr}