masscube 1.2.8__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.
Files changed (28) hide show
  1. {masscube-1.2.8 → masscube-1.2.9}/PKG-INFO +1 -1
  2. {masscube-1.2.8 → masscube-1.2.9}/pyproject.toml +1 -1
  3. {masscube-1.2.8 → masscube-1.2.9}/src/masscube/alignment.py +3 -3
  4. masscube-1.2.9/src/masscube/feature_evaluation.py +193 -0
  5. {masscube-1.2.8 → masscube-1.2.9}/src/masscube/params.py +10 -29
  6. {masscube-1.2.8 → masscube-1.2.9}/src/masscube/raw_data_utils.py +25 -24
  7. {masscube-1.2.8 → masscube-1.2.9}/src/masscube/workflows.py +14 -17
  8. {masscube-1.2.8 → masscube-1.2.9}/src/masscube.egg-info/PKG-INFO +1 -1
  9. masscube-1.2.8/src/masscube/feature_evaluation.py +0 -187
  10. {masscube-1.2.8 → masscube-1.2.9}/LICENSE +0 -0
  11. {masscube-1.2.8 → masscube-1.2.9}/README.md +0 -0
  12. {masscube-1.2.8 → masscube-1.2.9}/setup.cfg +0 -0
  13. {masscube-1.2.8 → masscube-1.2.9}/src/masscube/__init__.py +0 -0
  14. {masscube-1.2.8 → masscube-1.2.9}/src/masscube/annotation.py +0 -0
  15. {masscube-1.2.8 → masscube-1.2.9}/src/masscube/classifier_builder.py +0 -0
  16. {masscube-1.2.8 → masscube-1.2.9}/src/masscube/feature_detection.py +0 -0
  17. {masscube-1.2.8 → masscube-1.2.9}/src/masscube/feature_grouping.py +0 -0
  18. {masscube-1.2.8 → masscube-1.2.9}/src/masscube/mzpkl.py +0 -0
  19. {masscube-1.2.8 → masscube-1.2.9}/src/masscube/network.py +0 -0
  20. {masscube-1.2.8 → masscube-1.2.9}/src/masscube/normalization.py +0 -0
  21. {masscube-1.2.8 → masscube-1.2.9}/src/masscube/stats.py +0 -0
  22. {masscube-1.2.8 → masscube-1.2.9}/src/masscube/utils_functions.py +0 -0
  23. {masscube-1.2.8 → masscube-1.2.9}/src/masscube/visualization.py +0 -0
  24. {masscube-1.2.8 → masscube-1.2.9}/src/masscube.egg-info/SOURCES.txt +0 -0
  25. {masscube-1.2.8 → masscube-1.2.9}/src/masscube.egg-info/dependency_links.txt +0 -0
  26. {masscube-1.2.8 → masscube-1.2.9}/src/masscube.egg-info/entry_points.txt +0 -0
  27. {masscube-1.2.8 → masscube-1.2.9}/src/masscube.egg-info/requires.txt +0 -0
  28. {masscube-1.2.8 → masscube-1.2.9}/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.8
3
+ Version: 1.2.9
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>
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "masscube"
7
- version = "1.2.8"
7
+ version = "1.2.9"
8
8
  authors = [
9
9
  { name="Huaxu Yu", email="yhxchem@outlook.com" },
10
10
  ]
@@ -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.project_dir, "rt_correction_models.pkl")):
243
- with open(os.path.join(params.project_dir, "rt_correction_models.pkl"), "rb") as f:
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:
@@ -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
- if not os.path.exists(self.sample_dir) or len(os.listdir(self.sample_dir)) == 0:
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
- if not os.path.exists(self.single_file_dir):
214
- os.makedirs(self.single_file_dir)
215
- if not os.path.exists(self.tmp_file_dir):
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
- file_names = os.listdir(self.sample_dir)
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 os.listdir(self.sample_dir) if not f.startswith(".") and
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
- for i in range(len(self.sample_metadata)):
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 i, line in enumerate(f):
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
- for i in self.ms1_idx:
505
- if rt_range[0] < self.scans[i].time < rt_range[1]:
506
- mz_diff = np.abs(self.scans[i].signals[:, 0] - target_mz)
507
- # if scan is not empty and at least one ion is matched
508
- if len(mz_diff) > 0 and np.min(mz_diff) < mz_tol:
509
- eic_time_arr.append(self.scans[i].time)
510
- eic_signals.append(self.scans[i].signals[np.argmin(mz_diff)])
511
- eic_scan_idx_arr.append(i)
512
- else:
513
- eic_time_arr.append(self.scans[i].time)
514
- eic_signals.append([np.nan, 0])
515
- eic_scan_idx_arr.append(i)
516
-
517
- if self.scans[i].time > rt_range[1]:
518
- break
519
-
520
- eic_time_arr = np.array(eic_time_arr, dtype=np.float32)
521
- eic_signals = np.array(eic_signals, dtype=np.float32)
522
- eic_scan_idx_arr = np.array(eic_scan_idx_arr, dtype=np.int32)
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, intensity_range=[params.ms1_abs_int_tol, np.inf])
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)
@@ -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
- for i in range(len(params.sample_metadata)):
188
- f = params.sample_metadata.iloc[i, 0]
189
- if f not in processed_files:
190
- to_be_processed.append(params.sample_metadata.loc[i, 'ABSOLUTE_PATH'])
191
- print("\t{} files to process out of {} files.".format(len(to_be_processed), len(params.sample_metadata)))
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
- for i in range(0, len(to_be_processed), params.batch_size):
196
- if len(to_be_processed) - i < params.batch_size:
197
- print("\tProcessing files from " + str(i) + " to " + str(len(to_be_processed)))
198
- else:
199
- print("\tProcessing files from " + str(i) + " to " + str(i+params.batch_size))
200
- p = multiprocessing.Pool(workers)
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("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: masscube
3
- Version: 1.2.8
3
+ Version: 1.2.9
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>
@@ -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