masscube 1.2.5__tar.gz → 1.2.7__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.5 → masscube-1.2.7}/PKG-INFO +2 -1
  2. {masscube-1.2.5 → masscube-1.2.7}/pyproject.toml +3 -2
  3. {masscube-1.2.5 → masscube-1.2.7}/src/masscube/alignment.py +24 -30
  4. {masscube-1.2.5 → masscube-1.2.7}/src/masscube/annotation.py +67 -12
  5. {masscube-1.2.5 → masscube-1.2.7}/src/masscube/feature_detection.py +3 -1
  6. {masscube-1.2.5 → masscube-1.2.7}/src/masscube/feature_evaluation.py +8 -5
  7. {masscube-1.2.5 → masscube-1.2.7}/src/masscube/feature_grouping.py +12 -13
  8. {masscube-1.2.5 → masscube-1.2.7}/src/masscube/normalization.py +60 -22
  9. {masscube-1.2.5 → masscube-1.2.7}/src/masscube/params.py +54 -37
  10. {masscube-1.2.5 → masscube-1.2.7}/src/masscube/raw_data_utils.py +39 -58
  11. {masscube-1.2.5 → masscube-1.2.7}/src/masscube/stats.py +1 -1
  12. masscube-1.2.7/src/masscube/utils_functions.py +558 -0
  13. {masscube-1.2.5 → masscube-1.2.7}/src/masscube/visualization.py +22 -11
  14. {masscube-1.2.5 → masscube-1.2.7}/src/masscube/workflows.py +36 -16
  15. {masscube-1.2.5 → masscube-1.2.7}/src/masscube.egg-info/PKG-INFO +2 -1
  16. {masscube-1.2.5 → masscube-1.2.7}/src/masscube.egg-info/requires.txt +1 -0
  17. masscube-1.2.5/src/masscube/utils_functions.py +0 -273
  18. {masscube-1.2.5 → masscube-1.2.7}/LICENSE +0 -0
  19. {masscube-1.2.5 → masscube-1.2.7}/README.md +0 -0
  20. {masscube-1.2.5 → masscube-1.2.7}/setup.cfg +0 -0
  21. {masscube-1.2.5 → masscube-1.2.7}/src/masscube/__init__.py +0 -0
  22. {masscube-1.2.5 → masscube-1.2.7}/src/masscube/classifier_builder.py +0 -0
  23. {masscube-1.2.5 → masscube-1.2.7}/src/masscube/mzpkl.py +0 -0
  24. {masscube-1.2.5 → masscube-1.2.7}/src/masscube/network.py +0 -0
  25. {masscube-1.2.5 → masscube-1.2.7}/src/masscube.egg-info/SOURCES.txt +0 -0
  26. {masscube-1.2.5 → masscube-1.2.7}/src/masscube.egg-info/dependency_links.txt +0 -0
  27. {masscube-1.2.5 → masscube-1.2.7}/src/masscube.egg-info/entry_points.txt +0 -0
  28. {masscube-1.2.5 → masscube-1.2.7}/src/masscube.egg-info/top_level.txt +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: masscube
3
- Version: 1.2.5
3
+ Version: 1.2.7
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>
@@ -23,6 +23,7 @@ Requires-Dist: ms_entropy==1.3.4
23
23
  Requires-Dist: scikit-learn>=1.3.2
24
24
  Requires-Dist: statsmodels>=0.14.2
25
25
  Requires-Dist: umap-learn>=0.5.7
26
+ Requires-Dist: IsoSpecPy>=2.2.3
26
27
  Dynamic: license-file
27
28
 
28
29
  # MassCube
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "masscube"
7
- version = "1.2.5"
7
+ version = "1.2.7"
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"]
@@ -169,7 +169,7 @@ def load_ms2_db(path):
169
169
  a['precursor_type'] = a.pop('precursortype')
170
170
  if 'ionmode' in a.keys():
171
171
  a['ion_mode'] = a.pop('ionmode')
172
- if 'retentiontime' in a.keys():
172
+ if 'retentiontime' in a.keys() and a['retentiontime'] != '':
173
173
  a['retention_time'] = float(a.pop('retentiontime'))
174
174
  db.append(a)
175
175
  _correct_db(db)
@@ -218,6 +218,17 @@ def annotate_aligned_features(features, params, num=5):
218
218
 
219
219
  entropy_search = load_ms2_db(params.ms2_library_path)
220
220
 
221
+ # ion mode filtering
222
+ ion_mode_mask = []
223
+ for i in range(len(entropy_search.precursor_mz_array)):
224
+ if 'ion_mode' in entropy_search[i]:
225
+ ion_mode_mask.append(1 if (entropy_search[i]['ion_mode'].lower() == params.ion_mode) else 0)
226
+ elif 'ionmode' in entropy_search[i]:
227
+ ion_mode_mask.append(1 if (entropy_search[i]['ionmode'].lower() == params.ion_mode) else 0)
228
+ else:
229
+ ion_mode_mask.append(0)
230
+ ion_mode_mask = np.array(ion_mode_mask, dtype=bool)
231
+
221
232
  if params.consider_rt:
222
233
  rt_arr = np.zeros(len(entropy_search.precursor_mz_array))+np.inf
223
234
  for i, ms2 in enumerate(entropy_search):
@@ -234,8 +245,13 @@ def annotate_aligned_features(features, params, num=5):
234
245
  for file_name, ms2 in f.ms2_seq:
235
246
  signals = extract_signals_from_string(ms2)
236
247
  signals = entropy_search.clean_spectrum_for_search(f.mz, signals, precursor_ions_removal_da=params.precursor_mz_offset)
248
+ if len(signals) == 0:
249
+ continue
237
250
  parsed_ms2.append([file_name, signals])
238
251
 
252
+ if len(parsed_ms2) == 0:
253
+ continue
254
+
239
255
  parsed_ms2.sort(key=lambda x: np.sum(x[1][:, 1]), reverse=True)
240
256
  parsed_ms2 = parsed_ms2[:num]
241
257
  f.ms2_reference_file = parsed_ms2[0][0]
@@ -250,7 +266,7 @@ def annotate_aligned_features(features, params, num=5):
250
266
  for file_name, signals in parsed_ms2:
251
267
  similarity, matched_num = entropy_search.identity_search(precursor_mz=f.mz, peaks=signals, ms1_tolerance_in_da=params.mz_tol_ms1,
252
268
  ms2_tolerance_in_da=params.mz_tol_ms2, output_matched_peak_number=True)
253
- similarities.append(similarity)
269
+ similarities.append(similarity * ion_mode_mask)
254
270
  matched_nums.append(matched_num)
255
271
 
256
272
  if params.consider_rt:
@@ -283,6 +299,7 @@ def annotate_aligned_features(features, params, num=5):
283
299
  if matched is None and params.fuzzy_search:
284
300
  similarity = entropy_search.hybrid_search(precursor_mz=f.mz, peaks=f.ms2, ms1_tolerance_in_da=params.mz_tol_ms1,
285
301
  ms2_tolerance_in_da=params.mz_tol_ms2)
302
+ similarity = similarity * ion_mode_mask
286
303
  idx = np.argmax(similarity)
287
304
  if similarity[idx] > params.ms2_sim_tol:
288
305
  matched = entropy_search[idx]
@@ -316,16 +333,27 @@ def annotate_features(d, sim_tol=None, fuzzy_search=True, ms2_library_path=None,
316
333
  """
317
334
 
318
335
  if ms2_library_path is None:
319
- search_engine = load_ms2_db(d.params.ms2_library_path)
336
+ entropy_search = load_ms2_db(d.params.ms2_library_path)
320
337
  else:
321
- search_engine = load_ms2_db(ms2_library_path)
338
+ entropy_search = load_ms2_db(ms2_library_path)
339
+
340
+ # ion mode filtering
341
+ ion_mode_mask = []
342
+ for i in range(len(entropy_search.precursor_mz_array)):
343
+ if 'ion_mode' in entropy_search[i]:
344
+ ion_mode_mask.append(1 if (entropy_search[i]['ion_mode'].lower() == d.params.ion_mode) else 0)
345
+ elif 'ionmode' in entropy_search[i]:
346
+ ion_mode_mask.append(1 if (entropy_search[i]['ionmode'].lower() == d.params.ion_mode) else 0)
347
+ else:
348
+ ion_mode_mask.append(0)
349
+ ion_mode_mask = np.array(ion_mode_mask, dtype=bool)
322
350
 
323
351
  if sim_tol is None:
324
352
  sim_tol = d.params.ms2_sim_tol
325
353
 
326
354
  if consider_rt:
327
- rt_arr = np.zeros(len(search_engine.precursor_mz_array))+np.inf
328
- for i, ms2 in enumerate(search_engine):
355
+ rt_arr = np.zeros(len(entropy_search.precursor_mz_array))+np.inf
356
+ for i, ms2 in enumerate(entropy_search):
329
357
  if 'retention_time' in ms2:
330
358
  rt_arr[i] = ms2['retention_time']
331
359
 
@@ -336,15 +364,18 @@ def annotate_features(d, sim_tol=None, fuzzy_search=True, ms2_library_path=None,
336
364
 
337
365
  matched = None
338
366
  matched_peak_num = None
339
- signals = search_engine.clean_spectrum_for_search(precursor_mz=f.mz, peaks=f.ms2.signals, precursor_ions_removal_da=2.0)
340
- scores, peak_nums = search_engine.identity_search(precursor_mz=f.mz, peaks=signals, ms1_tolerance_in_da=d.params.mz_tol_ms1,
367
+ signals = entropy_search.clean_spectrum_for_search(precursor_mz=f.mz, peaks=f.ms2.signals, precursor_ions_removal_da=2.0)
368
+ if len(signals) == 0:
369
+ continue
370
+ scores, peak_nums = entropy_search.identity_search(precursor_mz=f.mz, peaks=signals, ms1_tolerance_in_da=d.params.mz_tol_ms1,
341
371
  ms2_tolerance_in_da=d.params.mz_tol_ms2, output_matched_peak_number=True)
372
+ scores = ion_mode_mask
342
373
  if consider_rt:
343
374
  rt_boo = np.abs(rt_arr - f.rt) < d.params.rt_tol_annotation
344
375
  scores_rt = scores * rt_boo
345
376
  idx = np.argmax(scores_rt)
346
377
  if scores_rt[idx] > sim_tol:
347
- matched = search_engine[idx]
378
+ matched = entropy_search[idx]
348
379
  matched = {k.lower():v for k,v in matched.items()}
349
380
  matched_peak_num = peak_nums[idx]
350
381
  _assign_annotation_results_to_feature(f, score=scores_rt[idx], matched=matched, matched_peak_num=matched_peak_num,
@@ -353,18 +384,18 @@ def annotate_features(d, sim_tol=None, fuzzy_search=True, ms2_library_path=None,
353
384
  if matched is None:
354
385
  idx = np.argmax(scores)
355
386
  if scores[idx] > sim_tol:
356
- matched = search_engine[idx]
387
+ matched = entropy_search[idx]
357
388
  matched = {k.lower():v for k,v in matched.items()}
358
389
  matched_peak_num = peak_nums[idx]
359
390
  _assign_annotation_results_to_feature(f, score=scores[idx], matched=matched, matched_peak_num=matched_peak_num,
360
391
  search_mode='identity_search')
361
392
 
362
393
  if matched is None and fuzzy_search:
363
- scores = search_engine.hybrid_search(precursor_mz=f.mz, peaks=signals, ms1_tolerance_in_da=d.params.mz_tol_ms1,
394
+ scores = entropy_search.hybrid_search(precursor_mz=f.mz, peaks=signals, ms1_tolerance_in_da=d.params.mz_tol_ms1,
364
395
  ms2_tolerance_in_da=d.params.mz_tol_ms2)
365
396
  idx = np.argmax(scores)
366
397
  if scores[idx] > sim_tol:
367
- matched = search_engine[idx]
398
+ matched = entropy_search[idx]
368
399
  matched_peak_num = None
369
400
  _assign_annotation_results_to_feature(f, score=scores[idx], matched=matched, matched_peak_num=matched_peak_num,
370
401
  search_mode='fuzzy_search')
@@ -562,6 +593,30 @@ def index_msp_to_pkl(msp_path, output_path=None):
562
593
  pickle.dump(entropy_search, open(os.path.join(output_path, file_name + ".pkl"), 'wb'))
563
594
 
564
595
 
596
+ def index_json_to_pkl(json_path, output_path=None):
597
+ """
598
+ A function to index JSON file to pickle format.
599
+
600
+ Parameters
601
+ ----------
602
+ json_path : str
603
+ The path to the JSON file.
604
+ output_path : str
605
+ The path to the output pickle file.
606
+ """
607
+
608
+ file_name = os.path.basename(json_path).split(".")[0]
609
+
610
+ if output_path is None:
611
+ output_path = os.path.dirname(json_path)
612
+
613
+ db = json.load(open(json_path, 'r'))
614
+ entropy_search = FlashEntropySearch()
615
+ entropy_search.build_index(db)
616
+
617
+ pickle.dump(entropy_search, open(os.path.join(output_path, file_name + ".pkl"), 'wb'))
618
+
619
+
565
620
  def _correct_db(db):
566
621
  """
567
622
  Correct the MS2 database by changing the key names.
@@ -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]
@@ -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,55 @@ 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:
342
- int_arr_corr = array
343
- y = None
344
- model = None
333
+ valid_idx = is_qc & (array > 0)
334
+
335
+ if np.sum(valid_idx) < 3:
336
+ return {'model': None, 'fit_curve': None, 'normed_arr': array}
337
+
338
+ if batch_ids is None:
339
+ batch_ids = np.zeros(len(array), dtype=int)
340
+
341
+ unique_batch_ids = np.unique(batch_ids)
342
+ x = np.arange(len(array))
343
+
344
+ fitted_y = np.ones(len(array))
345
+ models = []
346
+
347
+ not_corrected_batches = []
348
+
349
+ for id in unique_batch_ids:
350
+ qc_idx_i = valid_idx & (batch_ids == id)
351
+ if np.sum(qc_idx_i) > 2:
352
+ # apply lowess normalization
353
+ frac = np.min([0.8, 8/np.sum(qc_idx_i)])
354
+ xi = x[batch_ids == id]
355
+ model = lowess(array[qc_idx_i], x[qc_idx_i], frac=frac, it=it)
356
+ yi = np.interp(xi, model[:, 0], model[:, 1])
357
+ yi[yi < 1] = 1 # gap filling
358
+ fitted_y[batch_ids == id] = yi
359
+ else:
360
+ # perform no correction
361
+ model = None
362
+ not_corrected_batches.append(id)
363
+
364
+ models.append(model)
365
+
366
+ # calculate the corrected intensity array
367
+ int_arr_corr = array / fitted_y * np.max(fitted_y)
345
368
 
346
- return {'model': model, 'fit_curve': y, 'normed_arr': int_arr_corr}
369
+ # for not corrected batches, change it back to the original data
370
+ for id in not_corrected_batches:
371
+ int_arr_corr[batch_ids == id] = array[batch_ids == id]
372
+
373
+ # check the normalization results, if the normed RSD is bigger than the original RSD, then use the original data
374
+ tmp = array[is_qc]
375
+ tmp_normed = int_arr_corr[is_qc]
376
+ tmp = tmp[tmp > 0]
377
+ tmp_normed = tmp_normed[tmp_normed > 0]
378
+ if (len(tmp) == 0) or (len(tmp_normed) == 0):
379
+ if np.std(tmp_normed) / np.mean(tmp_normed) > np.std(tmp) / np.mean(tmp):
380
+ int_arr_corr = array
381
+ models = [None] * len(unique_batch_ids)
382
+ fitted_y = np.ones(len(array))
383
+
384
+ return {'model': models, 'fit_curve': fitted_y, 'normed_arr': int_arr_corr}