-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathMassSpectrumClasses.py
More file actions
1749 lines (1405 loc) · 57.6 KB
/
MassSpectrumClasses.py
File metadata and controls
1749 lines (1405 loc) · 57.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from pathlib import Path
import numpy as np
from lmfit.models import GaussianModel
# from matplotlib import rcParamsDefault, rcParams
from numpy import array, float64, histogram, trapz, where
from pandas import DataFrame
from corems.encapsulation.constant import Labels
from corems.encapsulation.factory.parameters import MSParameters
from corems.encapsulation.input.parameter_from_json import (
load_and_set_parameters_ms,
load_and_set_toml_parameters_ms,
)
from corems.mass_spectrum.calc.KendrickGroup import KendrickGrouping
from corems.mass_spectrum.calc.MassSpectrumCalc import MassSpecCalc
from corems.mass_spectrum.calc.MeanResolvingPowerFilter import MeanResolvingPowerFilter
from corems.ms_peak.factory.MSPeakClasses import ICRMassPeak as MSPeak
__author__ = "Yuri E. Corilo"
__date__ = "Jun 12, 2019"
def overrides(interface_class):
"""Checks if the method overrides a method from an interface class."""
def overrider(method):
assert method.__name__ in dir(interface_class)
return method
return overrider
class MassSpecBase(MassSpecCalc, KendrickGrouping):
"""A mass spectrum base class, stores the profile data and instrument settings.
Iteration over a list of MSPeaks classes stored at the _mspeaks attributes.
_mspeaks is populated under the hood by calling process_mass_spec method.
Iteration is null if _mspeaks is empty.
Parameters
----------
mz_exp : array_like
The m/z values of the mass spectrum.
abundance : array_like
The abundance values of the mass spectrum.
d_params : dict
A dictionary of parameters for the mass spectrum.
**kwargs
Additional keyword arguments.
Attributes
----------
mspeaks : list
A list of mass peaks.
is_calibrated : bool
Whether the mass spectrum is calibrated.
is_centroid : bool
Whether the mass spectrum is centroided.
has_frequency : bool
Whether the mass spectrum has a frequency domain.
calibration_order : None or int
The order of the mass spectrum's calibration.
calibration_points : None or ndarray
The calibration points of the mass spectrum.
calibration_ref_mzs: None or ndarray
The reference m/z values of the mass spectrum's calibration.
calibration_meas_mzs : None or ndarray
The measured m/z values of the mass spectrum's calibration.
calibration_RMS : None or float
The root mean square of the mass spectrum's calibration.
calibration_segment : None or CalibrationSegment
The calibration segment of the mass spectrum.
_abundance : ndarray
The abundance values of the mass spectrum.
_mz_exp : ndarray
The m/z values of the mass spectrum.
_mspeaks : list
A list of mass peaks.
_dict_nominal_masses_indexes : dict
A dictionary of nominal masses and their indexes.
_baseline_noise : float
The baseline noise of the mass spectrum.
_baseline_noise_std : float
The standard deviation of the baseline noise of the mass spectrum.
_dynamic_range : float or None
The dynamic range of the mass spectrum.
_transient_settings : None or TransientSettings
The transient settings of the mass spectrum.
_frequency_domain : None or FrequencyDomain
The frequency domain of the mass spectrum.
_mz_cal_profile : None or MzCalibrationProfile
The m/z calibration profile of the mass spectrum.
Methods
-------
* process_mass_spec(). Main function to process the mass spectrum,
including calculating the noise threshold, peak picking, and resetting the MSpeak indexes.
See also: MassSpecCentroid(), MassSpecfromFreq(), MassSpecProfile()
"""
def __init__(self, mz_exp, abundance, d_params, **kwargs):
self._abundance = array(abundance, dtype=float64)
self._mz_exp = array(mz_exp, dtype=float64)
# objects created after process_mass_spec() function
self._mspeaks = list()
self.mspeaks = list()
self._dict_nominal_masses_indexes = dict()
self._baseline_noise = 0.001
self._baseline_noise_std = 0.001
self._dynamic_range = None
# set to None: initialization occurs inside subclass MassSpecfromFreq
self._transient_settings = None
self._frequency_domain = None
self._mz_cal_profile = None
self.is_calibrated = False
self._set_parameters_objects(d_params)
self._init_settings()
self.is_centroid = False
self.has_frequency = False
self.calibration_order = None
self.calibration_points = None
self.calibration_ref_mzs = None
self.calibration_meas_mzs = None
self.calibration_RMS = None
self.calibration_segment = None
self.calibration_raw_error_median = None
self.calibration_raw_error_stdev = None
def _init_settings(self):
"""Initializes the settings for the mass spectrum."""
self._parameters = MSParameters()
def __len__(self):
return len(self.mspeaks)
def __getitem__(self, position) -> MSPeak:
return self.mspeaks[position]
def set_indexes(self, list_indexes):
"""Set the mass spectrum to iterate over only the selected MSpeaks indexes.
Parameters
----------
list_indexes : list of int
A list of integers representing the indexes of the MSpeaks to iterate over.
"""
self.mspeaks = [self._mspeaks[i] for i in list_indexes]
for i, mspeak in enumerate(self.mspeaks):
mspeak.index = i
self._set_nominal_masses_start_final_indexes()
def reset_indexes(self):
"""Reset the mass spectrum to iterate over all MSpeaks objects.
This method resets the mass spectrum to its original state, allowing iteration over all MSpeaks objects.
It also sets the index of each MSpeak object to its corresponding position in the mass spectrum.
"""
self.mspeaks = self._mspeaks
for i, mspeak in enumerate(self.mspeaks):
mspeak.index = i
self._set_nominal_masses_start_final_indexes()
def add_mspeak(
self,
ion_charge,
mz_exp,
abundance,
resolving_power,
signal_to_noise,
massspec_indexes,
exp_freq=None,
ms_parent=None,
):
"""Add a new MSPeak object to the MassSpectrum object.
Parameters
----------
ion_charge : int
The ion charge of the MSPeak.
mz_exp : float
The experimental m/z value of the MSPeak.
abundance : float
The abundance of the MSPeak.
resolving_power : float
The resolving power of the MSPeak.
signal_to_noise : float
The signal-to-noise ratio of the MSPeak.
massspec_indexes : list
A list of indexes of the MSPeak in the MassSpectrum object.
exp_freq : float, optional
The experimental frequency of the MSPeak. Defaults to None.
ms_parent : MSParent, optional
The MSParent object associated with the MSPeak. Defaults to None.
"""
mspeak = MSPeak(
ion_charge,
mz_exp,
abundance,
resolving_power,
signal_to_noise,
massspec_indexes,
len(self._mspeaks),
exp_freq=exp_freq,
ms_parent=ms_parent,
)
self._mspeaks.append(mspeak)
def _set_parameters_objects(self, d_params):
"""Set the parameters of the MassSpectrum object.
Parameters
----------
d_params : dict
A dictionary containing the parameters to set.
Notes
-----
This method sets the following parameters of the MassSpectrum object:
- _calibration_terms
- label
- analyzer
- acquisition_time
- instrument_label
- polarity
- scan_number
- retention_time
- mobility_rt
- mobility_scan
- _filename
- _dir_location
- _baseline_noise
- _baseline_noise_std
- sample_name
"""
self._calibration_terms = (
d_params.get("Aterm"),
d_params.get("Bterm"),
d_params.get("Cterm"),
)
self.label = d_params.get(Labels.label)
self.analyzer = d_params.get("analyzer")
self.acquisition_time = d_params.get("acquisition_time")
self.instrument_label = d_params.get("instrument_label")
self.polarity = int(d_params.get("polarity"))
self.scan_number = d_params.get("scan_number")
self.retention_time = d_params.get("rt")
self.mobility_rt = d_params.get("mobility_rt")
self.mobility_scan = d_params.get("mobility_scan")
self._filename = d_params.get("filename_path")
self._dir_location = d_params.get("dir_location")
self._baseline_noise = d_params.get("baseline_noise")
self._baseline_noise_std = d_params.get("baseline_noise_std")
if d_params.get("sample_name") != "Unknown":
self.sample_name = d_params.get("sample_name")
if not self.sample_name:
self.sample_name = self.filename.stem
else:
self.sample_name = self.filename.stem
def reset_cal_therms(self, Aterm, Bterm, C, fas=0):
"""Reset calibration terms and recalculate the mass-to-charge ratio and abundance.
Parameters
----------
Aterm : float
The A-term calibration coefficient.
Bterm : float
The B-term calibration coefficient.
C : float
The C-term calibration coefficient.
fas : float, optional
The frequency amplitude scaling factor. Default is 0.
"""
self._calibration_terms = (Aterm, Bterm, C)
self._mz_exp = self._f_to_mz()
self._abundance = self._abundance
self.find_peaks()
self.reset_indexes()
def clear_molecular_formulas(self):
"""Clear the molecular formulas for all mspeaks in the MassSpectrum.
Returns
-------
numpy.ndarray
An array of the cleared molecular formulas for each mspeak in the MassSpectrum.
"""
self.check_mspeaks()
return array([mspeak.clear_molecular_formulas() for mspeak in self.mspeaks])
def process_mass_spec(self, keep_profile=True):
"""Process the mass spectrum.
Parameters
----------
keep_profile : bool, optional
Whether to keep the profile data after processing. Defaults to True.
Notes
-----
This method does the following:
- calculates the noise threshold
- does peak picking (creates mspeak_objs)
- resets the mspeak_obj indexes
"""
# if runned mannually make sure to rerun filter_by_noise_threshold
# calculates noise threshold
# do peak picking( create mspeak_objs)
# reset mspeak_obj the indexes
self.cal_noise_threshold()
self.find_peaks()
self.reset_indexes()
if self.mspeaks:
self._dynamic_range = self.max_abundance / self.min_abundance
else:
self._dynamic_range = 0
if not keep_profile:
self._abundance *= 0
self._mz_exp *= 0
def cal_noise_threshold(self):
"""Calculate the noise threshold of the mass spectrum."""
if self.label == Labels.simulated_profile:
self._baseline_noise, self._baseline_noise_std = 0.1, 1
if self.settings.noise_threshold_method == "log":
self._baseline_noise, self._baseline_noise_std = (
self.run_log_noise_threshold_calc()
)
else:
self._baseline_noise, self._baseline_noise_std = (
self.run_noise_threshold_calc()
)
@property
def parameters(self):
"""Return the parameters of the mass spectrum."""
return self._parameters
@parameters.setter
def parameters(self, instance_MSParameters):
self._parameters = instance_MSParameters
def set_parameter_from_json(self, parameters_path):
"""Set the parameters of the mass spectrum from a JSON file.
Parameters
----------
parameters_path : str
The path to the JSON file containing the parameters.
"""
load_and_set_parameters_ms(self, parameters_path=parameters_path)
def set_parameter_from_toml(self, parameters_path):
load_and_set_toml_parameters_ms(self, parameters_path=parameters_path)
@property
def mspeaks_settings(self):
"""Return the MS peak settings of the mass spectrum."""
return self.parameters.ms_peak
@mspeaks_settings.setter
def mspeaks_settings(self, instance_MassSpecPeakSetting):
self.parameters.ms_peak = instance_MassSpecPeakSetting
@property
def settings(self):
"""Return the settings of the mass spectrum."""
return self.parameters.mass_spectrum
@settings.setter
def settings(self, instance_MassSpectrumSetting):
self.parameters.mass_spectrum = instance_MassSpectrumSetting
@property
def molecular_search_settings(self):
"""Return the molecular search settings of the mass spectrum."""
return self.parameters.molecular_search
@molecular_search_settings.setter
def molecular_search_settings(self, instance_MolecularFormulaSearchSettings):
self.parameters.molecular_search = instance_MolecularFormulaSearchSettings
@property
def mz_cal_profile(self):
"""Return the calibrated m/z profile of the mass spectrum."""
return self._mz_cal_profile
@mz_cal_profile.setter
def mz_cal_profile(self, mz_cal_list):
if len(mz_cal_list) == len(self._mz_exp):
self._mz_cal_profile = mz_cal_list
else:
raise Exception(
"calibrated array (%i) is not of the same size of the data (%i)"
% (len(mz_cal_list), len(self.mz_exp_profile))
)
@property
def mz_cal(self):
"""Return the calibrated m/z values of the mass spectrum."""
return array([mspeak.mz_cal for mspeak in self.mspeaks])
@mz_cal.setter
def mz_cal(self, mz_cal_list):
if len(mz_cal_list) == len(self.mspeaks):
self.is_calibrated = True
for index, mz_cal in enumerate(mz_cal_list):
self.mspeaks[index].mz_cal = mz_cal
else:
raise Exception(
"calibrated array (%i) is not of the same size of the data (%i)"
% (len(mz_cal_list), len(self._mspeaks))
)
@property
def mz_exp(self):
"""Return the experimental m/z values of the mass spectrum."""
self.check_mspeaks()
if self.is_calibrated:
return array([mspeak.mz_cal for mspeak in self.mspeaks])
else:
return array([mspeak.mz_exp for mspeak in self.mspeaks])
@property
def freq_exp_profile(self):
"""Return the experimental frequency profile of the mass spectrum."""
return self._frequency_domain
@freq_exp_profile.setter
def freq_exp_profile(self, new_data):
self._frequency_domain = array(new_data)
@property
def freq_exp_pp(self):
"""Return the experimental frequency values of the mass spectrum that are used for peak picking."""
_, _, freq = self.prepare_peak_picking_data()
return freq
@property
def mz_exp_profile(self):
"""Return the experimental m/z profile of the mass spectrum."""
if self.is_calibrated:
return self.mz_cal_profile
else:
return self._mz_exp
@mz_exp_profile.setter
def mz_exp_profile(self, new_data):
self._mz_exp = array(new_data)
@property
def mz_exp_pp(self):
"""Return the experimental m/z values of the mass spectrum that are used for peak picking."""
mz, _, _ = self.prepare_peak_picking_data()
return mz
@property
def abundance_profile(self):
"""Return the abundance profile of the mass spectrum."""
return self._abundance
@abundance_profile.setter
def abundance_profile(self, new_data):
self._abundance = array(new_data)
@property
def abundance_profile_pp(self):
"""Return the abundance profile of the mass spectrum that is used for peak picking."""
_, abundance, _ = self.prepare_peak_picking_data()
return abundance
@property
def abundance(self):
"""Return the abundance values of the mass spectrum."""
self.check_mspeaks()
return array([mspeak.abundance for mspeak in self.mspeaks])
def freq_exp(self):
"""Return the experimental frequency values of the mass spectrum."""
self.check_mspeaks()
return array([mspeak.freq_exp for mspeak in self.mspeaks])
@property
def resolving_power(self):
"""Return the resolving power values of the mass spectrum."""
self.check_mspeaks()
return array([mspeak.resolving_power for mspeak in self.mspeaks])
@property
def signal_to_noise(self):
self.check_mspeaks()
return array([mspeak.signal_to_noise for mspeak in self.mspeaks])
@property
def nominal_mz(self):
"""Return the nominal m/z values of the mass spectrum."""
if self._dict_nominal_masses_indexes:
return sorted(list(self._dict_nominal_masses_indexes.keys()))
else:
raise ValueError("Nominal indexes not yet set")
def get_mz_and_abundance_peaks_tuples(self):
"""Return a list of tuples containing the m/z and abundance values of the mass spectrum."""
self.check_mspeaks()
return [(mspeak.mz_exp, mspeak.abundance) for mspeak in self.mspeaks]
@property
def kmd(self):
"""Return the Kendrick mass defect values of the mass spectrum."""
self.check_mspeaks()
return array([mspeak.kmd for mspeak in self.mspeaks])
@property
def kendrick_mass(self):
"""Return the Kendrick mass values of the mass spectrum."""
self.check_mspeaks()
return array([mspeak.kendrick_mass for mspeak in self.mspeaks])
@property
def max_mz_exp(self):
"""Return the maximum experimental m/z value of the mass spectrum."""
return max([mspeak.mz_exp for mspeak in self.mspeaks])
@property
def min_mz_exp(self):
"""Return the minimum experimental m/z value of the mass spectrum."""
return min([mspeak.mz_exp for mspeak in self.mspeaks])
@property
def max_abundance(self):
"""Return the maximum abundance value of the mass spectrum."""
return max([mspeak.abundance for mspeak in self.mspeaks])
@property
def max_signal_to_noise(self):
"""Return the maximum signal-to-noise ratio of the mass spectrum."""
return max([mspeak.signal_to_noise for mspeak in self.mspeaks])
@property
def most_abundant_mspeak(self):
"""Return the most abundant MSpeak object of the mass spectrum."""
return max(self.mspeaks, key=lambda m: m.abundance)
@property
def min_abundance(self):
"""Return the minimum abundance value of the mass spectrum."""
return min([mspeak.abundance for mspeak in self.mspeaks])
# takes too much cpu time
@property
def dynamic_range(self):
"""Return the dynamic range of the mass spectrum."""
return self._dynamic_range
@property
def baseline_noise(self):
"""Return the baseline noise of the mass spectrum."""
if self._baseline_noise:
return self._baseline_noise
else:
return None
@property
def baseline_noise_std(self):
"""Return the standard deviation of the baseline noise of the mass spectrum."""
if self._baseline_noise_std == 0:
return self._baseline_noise_std
if self._baseline_noise_std:
return self._baseline_noise_std
else:
return None
@property
def Aterm(self):
"""Return the A-term calibration coefficient of the mass spectrum."""
return self._calibration_terms[0]
@property
def Bterm(self):
"""Return the B-term calibration coefficient of the mass spectrum."""
return self._calibration_terms[1]
@property
def Cterm(self):
"""Return the C-term calibration coefficient of the mass spectrum."""
return self._calibration_terms[2]
@property
def filename(self):
"""Return the filename of the mass spectrum."""
return Path(self._filename)
@property
def dir_location(self):
"""Return the directory location of the mass spectrum."""
return self._dir_location
def sort_by_mz(self):
"""Sort the mass spectrum by m/z values."""
return sorted(self, key=lambda m: m.mz_exp)
def sort_by_abundance(self, reverse=False):
"""Sort the mass spectrum by abundance values."""
return sorted(self, key=lambda m: m.abundance, reverse=reverse)
@property
def tic(self):
"""Return the total ion current of the mass spectrum."""
return trapz(self.abundance_profile, self.mz_exp_profile)
def check_mspeaks_warning(self):
"""Check if the mass spectrum has MSpeaks objects.
Raises
------
Warning
If the mass spectrum has no MSpeaks objects.
"""
import warnings
if self.mspeaks:
pass
else:
warnings.warn("mspeaks list is empty, continuing without filtering data")
def check_mspeaks(self):
"""Check if the mass spectrum has MSpeaks objects.
Raises
------
Exception
If the mass spectrum has no MSpeaks objects.
"""
if self.mspeaks:
pass
else:
raise Exception(
"mspeaks list is empty, please run process_mass_spec() first"
)
def remove_assignment_by_index(self, indexes):
"""Remove the molecular formula assignment of the MSpeaks objects at the specified indexes.
Parameters
----------
indexes : list of int
A list of indexes of the MSpeaks objects to remove the molecular formula assignment from.
"""
for i in indexes:
self.mspeaks[i].clear_molecular_formulas()
def filter_by_index(self, list_indexes):
"""Filter the mass spectrum by the specified indexes.
Parameters
----------
list_indexes : list of int
A list of indexes of the MSpeaks objects to drop.
"""
self.mspeaks = [
self.mspeaks[i] for i in range(len(self.mspeaks)) if i not in list_indexes
]
for i, mspeak in enumerate(self.mspeaks):
mspeak.index = i
self._set_nominal_masses_start_final_indexes()
def filter_by_mz(self, min_mz, max_mz):
"""Filter the mass spectrum by the specified m/z range.
Parameters
----------
min_mz : float
The minimum m/z value to keep.
max_mz : float
The maximum m/z value to keep.
"""
self.check_mspeaks_warning()
indexes = [
index
for index, mspeak in enumerate(self.mspeaks)
if not min_mz <= mspeak.mz_exp <= max_mz
]
self.filter_by_index(indexes)
def filter_by_s2n(self, min_s2n, max_s2n=False):
"""Filter the mass spectrum by the specified signal-to-noise ratio range.
Parameters
----------
min_s2n : float
The minimum signal-to-noise ratio to keep.
max_s2n : float, optional
The maximum signal-to-noise ratio to keep. Defaults to False (no maximum).
"""
self.check_mspeaks_warning()
if max_s2n:
indexes = [
index
for index, mspeak in enumerate(self.mspeaks)
if not min_s2n <= mspeak.signal_to_noise <= max_s2n
]
else:
indexes = [
index
for index, mspeak in enumerate(self.mspeaks)
if mspeak.signal_to_noise <= min_s2n
]
self.filter_by_index(indexes)
def filter_by_abundance(self, min_abund, max_abund=False):
"""Filter the mass spectrum by the specified abundance range.
Parameters
----------
min_abund : float
The minimum abundance to keep.
max_abund : float, optional
The maximum abundance to keep. Defaults to False (no maximum).
"""
self.check_mspeaks_warning()
if max_abund:
indexes = [
index
for index, mspeak in enumerate(self.mspeaks)
if not min_abund <= mspeak.abundance <= max_abund
]
else:
indexes = [
index
for index, mspeak in enumerate(self.mspeaks)
if mspeak.abundance <= min_abund
]
self.filter_by_index(indexes)
def filter_by_max_resolving_power(self, B, T):
"""Filter the mass spectrum by the specified maximum resolving power.
Parameters
----------
B : float
T : float
"""
rpe = lambda m, z: (1.274e7 * z * B * T) / (m * z)
self.check_mspeaks_warning()
indexes_to_remove = [
index
for index, mspeak in enumerate(self.mspeaks)
if mspeak.resolving_power >= rpe(mspeak.mz_exp, mspeak.ion_charge)
]
self.filter_by_index(indexes_to_remove)
def filter_by_mean_resolving_power(
self, ndeviations=3, plot=False, guess_pars=False
):
"""Filter the mass spectrum by the specified mean resolving power.
Parameters
----------
ndeviations : float, optional
The number of standard deviations to use for filtering. Defaults to 3.
plot : bool, optional
Whether to plot the resolving power distribution. Defaults to False.
guess_pars : bool, optional
Whether to guess the parameters for the Gaussian model. Defaults to False.
"""
self.check_mspeaks_warning()
indexes_to_remove = MeanResolvingPowerFilter(
self, ndeviations, plot, guess_pars
).main()
self.filter_by_index(indexes_to_remove)
def filter_by_min_resolving_power(self, B, T, apodization_method: str=None, tolerance: float=0):
"""Filter the mass spectrum by the calculated minimum theoretical resolving power.
This is currently designed only for FTICR data, and accounts only for magnitude mode data
Accurate results require passing the apodisaion method used to calculate the resolving power.
see the ICRMassPeak function `resolving_power_calc` for more details.
Parameters
----------
B : Magnetic field strength in Tesla, float
T : transient length in seconds, float
apodization_method : str, optional
The apodization method to use for calculating the resolving power. Defaults to None.
tolerance : float, optional
The tolerance for the threshold. Defaults to 0, i.e. no tolerance
"""
if self.analyzer != "ICR":
raise Exception(
"This method is only applicable to ICR mass spectra. "
)
self.check_mspeaks_warning()
indexes_to_remove = [
index
for index, mspeak in enumerate(self.mspeaks)
if mspeak.resolving_power < (1-tolerance) * mspeak.resolving_power_calc(B, T, apodization_method=apodization_method)
]
self.filter_by_index(indexes_to_remove)
def filter_by_noise_threshold(self):
"""Filter the mass spectrum by the noise threshold."""
threshold = self.get_noise_threshold()[1][0]
self.check_mspeaks_warning()
indexes_to_remove = [
index
for index, mspeak in enumerate(self.mspeaks)
if mspeak.abundance <= threshold
]
self.filter_by_index(indexes_to_remove)
def find_peaks(self):
"""Find the peaks of the mass spectrum."""
# needs to clear previous results from peak_picking
self._mspeaks = list()
# then do peak picking
self.do_peak_picking()
# print("A total of %i peaks were found" % len(self._mspeaks))
def change_kendrick_base_all_mspeaks(self, kendrick_dict_base):
"""Change the Kendrick base of all MSpeaks objects.
Parameters
----------
kendrick_dict_base : dict
A dictionary of the Kendrick base to change to.
Notes
-----
Example of kendrick_dict_base parameter: kendrick_dict_base = {"C": 1, "H": 2} or {"C": 1, "H": 1, "O":1} etc
"""
self.parameters.ms_peak.kendrick_base = kendrick_dict_base
for mspeak in self.mspeaks:
mspeak.change_kendrick_base(kendrick_dict_base)
def get_nominal_mz_first_last_indexes(self, nominal_mass):
"""Return the first and last indexes of the MSpeaks objects with the specified nominal mass.
Parameters
----------
nominal_mass : int
The nominal mass to get the indexes for.
Returns
-------
tuple
A tuple containing the first and last indexes of the MSpeaks objects with the specified nominal mass.
"""
if self._dict_nominal_masses_indexes:
if nominal_mass in self._dict_nominal_masses_indexes.keys():
return (
self._dict_nominal_masses_indexes.get(nominal_mass)[0],
self._dict_nominal_masses_indexes.get(nominal_mass)[1] + 1,
)
else:
# import warnings
# uncomment warn to distribution
# warnings.warn("Nominal mass not found in _dict_nominal_masses_indexes, returning (0, 0) for nominal mass %i"%nominal_mass)
return (0, 0)
else:
raise Exception(
"run process_mass_spec() function before trying to access the data"
)
def get_masses_count_by_nominal_mass(self):
"""Return a dictionary of the nominal masses and their counts."""
dict_nominal_masses_count = {}
all_nominal_masses = list(set([i.nominal_mz_exp for i in self.mspeaks]))
for nominal_mass in all_nominal_masses:
if nominal_mass not in dict_nominal_masses_count:
dict_nominal_masses_count[nominal_mass] = len(
list(self.get_nominal_mass_indexes(nominal_mass))
)
return dict_nominal_masses_count
def datapoints_count_by_nominal_mz(self, mz_overlay=0.1):
"""Return a dictionary of the nominal masses and their counts.
Parameters
----------
mz_overlay : float, optional
The m/z overlay to use for counting. Defaults to 0.1.
Returns
-------
dict
A dictionary of the nominal masses and their counts.
"""
dict_nominal_masses_count = {}
all_nominal_masses = list(set([i.nominal_mz_exp for i in self.mspeaks]))
for nominal_mass in all_nominal_masses:
if nominal_mass not in dict_nominal_masses_count:
min_mz = nominal_mass - mz_overlay
max_mz = nominal_mass + 1 + mz_overlay
indexes = indexes = where(
(self.mz_exp_profile > min_mz) & (self.mz_exp_profile < max_mz)
)
dict_nominal_masses_count[nominal_mass] = indexes[0].size
return dict_nominal_masses_count
def get_nominal_mass_indexes(self, nominal_mass, overlay=0.1):
"""Return the indexes of the MSpeaks objects with the specified nominal mass.
Parameters
----------
nominal_mass : int
The nominal mass to get the indexes for.
overlay : float, optional
The m/z overlay to use for counting. Defaults to 0.1.
Returns
-------
generator
A generator of the indexes of the MSpeaks objects with the specified nominal mass.
"""
min_mz_to_look = nominal_mass - overlay
max_mz_to_look = nominal_mass + 1 + overlay
return (
i
for i in range(len(self.mspeaks))
if min_mz_to_look <= self.mspeaks[i].mz_exp <= max_mz_to_look
)
# indexes = (i for i in range(len(self.mspeaks)) if min_mz_to_look <= self.mspeaks[i].mz_exp <= max_mz_to_look)
# return indexes
def _set_nominal_masses_start_final_indexes(self):
"""Set the start and final indexes of the MSpeaks objects for all nominal masses."""
dict_nominal_masses_indexes = {}