-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathMS_functions.py
2640 lines (2176 loc) · 108 KB
/
MS_functions.py
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
#
# SeSiMe
#
# Copyright 2019 Netherlands eScience Center
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
""" Functions specific to MS data
(e.g. importing and data processing functions)
Florian Huber
Netherlands eScience Center, 2019
"""
import os
import helper_functions as functions
import fnmatch
import copy
import numpy as np
from scipy.optimize import curve_fit
from scipy.optimize import linear_sum_assignment
import random
import pandas as pd
from pyteomics import mgf
from rdkit import DataStructs
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem.Fingerprints import FingerprintMols
from rdkit.Chem import AllChem
# Add multi core parallelization
from concurrent.futures import ThreadPoolExecutor, as_completed
## --------------------------------------------------------------------------------------------------
## ---------------------------- Spectrum class ------------------------------------------------------
## --------------------------------------------------------------------------------------------------
class Spectrum(object):
""" Spectrum class to store key information
Functions include:
- Import data from mass spec files (protoype so far, works with only few formats)
- Calculate losses from peaks.
- Process / filter peaks
Args:
-------
min_frag: float
Lower limit of m/z to take into account (Default = 0.0).
max_frag: float
Upper limit of m/z to take into account (Default = 1000.0).
min_loss: float
Lower limit of losses to take into account (Default = 10.0).
max_loss: float
Upper limit of losses to take into account (Default = 200.0).
min_intensity_perc: float
Filter out peaks with intensities lower than the min_intensity_perc percentage
of the highest peak intensity (Default = 0.0, essentially meaning: OFF).
exp_intensity_filter: float
Filter out peaks by applying an exponential fit to the intensity histogram.
Intensity threshold will be set at where the exponential function will have dropped
to exp_intensity_filter (Default = 0.01).
min_peaks: int
Minimum number of peaks to keep, unless less are present from the start (Default = 10).
merge_energies: bool
Merge close peaks or not (False | True, Default is True).
merge_ppm: int
Merge peaks if their m/z is <= 1e6*merge_ppm (Default = 10).
replace: 'max' or None
If peaks are merged, either the heighest intensity of both is taken ('max'),
or their intensitites are added (None).
"""
def __init__(self, min_frag = 0.0, max_frag = 1000.0,
min_loss = 10.0, max_loss = 200.0,
min_intensity_perc = 0.0,
exp_intensity_filter = 0.01,
peaks_per_mz = 20/200,
min_peaks = 10,
max_peaks = None,
merge_energies = True,
merge_ppm = 10,
replace = 'max'):
self.id = []
self.filename = []
self.peaks = []
self.precursor_mz = []
self.parent_mz = []
self.metadata = {}
self.family = None
self.annotations = []
self.smiles = []
self.inchi = []
self.PROTON_MASS = 1.00727645199076
self.min_frag = min_frag
self.max_frag = max_frag
self.min_loss = min_loss
self.max_loss = max_loss
self.min_intensity_perc = min_intensity_perc
if exp_intensity_filter == 0:
self.exp_intensity_filter = None
else:
self.exp_intensity_filter = exp_intensity_filter
self.peaks_per_mz = peaks_per_mz
self.min_peaks = min_peaks
self.max_peaks = max_peaks
self.merge_energies = merge_energies
self.merge_ppm = merge_ppm
self.replace = replace
def ion_masses(self, precursormass, int_charge):
"""
Compute the parent masses. Single charge version is used for
loss computation.
"""
mul = abs(int_charge)
parent_mass = precursormass * mul
parent_mass -= int_charge * self.PROTON_MASS
single_charge_precursor_mass = precursormass*mul
if int_charge > 0:
single_charge_precursor_mass -= (int_charge-1) * self.PROTON_MASS
elif int_charge < 0:
single_charge_precursor_mass += (mul-1) * self.PROTON_MASS
else:
# charge = zero - leave them all the same
parent_mass = precursormass
single_charge_precursor_mass = precursormass
return parent_mass, single_charge_precursor_mass
def interpret_charge(self, charge):
"""
Method to interpret the ever variable charge field in the different
formats. Should never fail now.
"""
if not charge: # if it is none
return 1
try:
if not type(charge) == str:
charge = str(charge)
# Try removing any + signs
charge = charge.replace("+", "")
# Remove trailing minus signs
if charge.endswith('-'):
charge = charge[:-1]
if not charge.startswith('-'):
charge = '-' + charge
# Turn into an int
int_charge = int(charge)
return int_charge
except:
int_charge = 1
return int_charge
def read_spectrum(self, path, file, id):
""" Read .ms file and extract most relevant information
"""
with open(os.path.join(path, file),'r') as f:
temp_mass = []
temp_intensity = []
doc_name = file.split('/')[-1]
self.filename = doc_name
self.id = id
for line in f:
rline = line.rstrip()
if len(rline) > 0:
if rline.startswith('>') or rline.startswith('#'):
keyval = rline[1:].split(' ')[0]
valval = rline[len(keyval)+2:]
if not keyval == 'ms2peaks':
self.metadata[keyval] = valval
if keyval == 'compound':
self.annotation = valval
if keyval == 'precursormass':
self.precursor_mz = float(valval)
if keyval == 'Precursor_MZ':
self.precursor_mz = float(valval)
if keyval == 'parentmass':
self.parent_mz = float(valval)
if keyval == 'intensity':
self.intensity = float(valval)
if keyval == 'smiles':
self.smiles = valval
else:
# If it gets here, its a fragment peak (MS2 level peak)
sr = rline.split(' ')
mass = float(sr[0])
intensity = float(sr[1])
if self.merge_energies and len(temp_mass)>0:
# Compare to other peaks
errs = 1e6*np.abs(mass-np.array(temp_mass))/mass
if errs.min() < self.merge_ppm:
# Don't add, but merge the intensity
min_pos = errs.argmin()
if self.replace == 'max':
temp_intensity[min_pos] = max(intensity,temp_intensity[min_pos])
else:
temp_intensity[min_pos] += intensity
else:
temp_mass.append(mass)
temp_intensity.append(intensity)
else:
temp_mass.append(mass)
temp_intensity.append(intensity)
peaks = list(zip(temp_mass, temp_intensity))
peaks = process_peaks(peaks, self.min_frag, self.max_frag,
self.min_intensity_perc, self.exp_intensity_filter,
self.min_peaks, self.max_peaks)
self.peaks = peaks
self.n_peaks = len(peaks)
def read_spectrum_mgf(self, spectrum_mgf, id):
""" Translate spectrum dictionary as created by pyteomics package
into metabolomics.py spectrum object.
"""
self.id = id
self.metadata = spectrum_mgf['params']
if 'charge' in spectrum_mgf['params']:
self.metadata['charge'] = spectrum_mgf['params']['charge'][0]
else:
self.metadata['charge'] = 1
self.metadata['precursormass'] = spectrum_mgf['params']['pepmass'][0]
self.metadata['parentintensity'] = spectrum_mgf['params']['pepmass'][1]
# Following corrects parentmass according to charge
# if charge is known. This should lead to better computation of neutral losses
single_charge_precursor_mass = self.metadata['precursormass']
precursor_mass = self.metadata['precursormass']
parent_mass = self.metadata['precursormass']
str_charge = self.metadata['charge']
int_charge = self.interpret_charge(str_charge)
parent_mass, single_charge_precursor_mass = self.ion_masses(precursor_mass, int_charge)
self.metadata['parentmass'] = parent_mass
self.metadata['singlechargeprecursormass'] = single_charge_precursor_mass
self.metadata['charge'] = int_charge
# Get precursor mass (later used to calculate losses!)
self.precursor_mz = float(self.metadata['precursormass'])
self.parent_mz = float(self.metadata['parentmass'])
if 'smiles' in self.metadata:
self.smiles = self.metadata['smiles']
if 'inchi' in self.metadata:
self.inchi = self.metadata['inchi']
peaks = list(zip(spectrum_mgf['m/z array'], spectrum_mgf['intensity array']))
if len(peaks) >= self.min_peaks:
peaks = process_peaks(peaks, self.min_frag, self.max_frag,
self.min_intensity_perc, self.exp_intensity_filter,
self.min_peaks, self.max_peaks)
self.peaks = peaks
self.n_peaks = len(peaks)
def get_losses(self):
""" Use spectrum class and extract peaks and losses
Losses are here the differences between the spectrum precursor mz and the MS2 level peaks.
Remove losses outside window min_loss <-> max_loss.
"""
MS1_peak = self.precursor_mz
losses = np.array(self.peaks.copy())
losses[:,0] = MS1_peak - losses[:,0]
keep_idx = np.where((losses[:,0] > self.min_loss) & (losses[:,0] < self.max_loss))[0]
# TODO: now array is tranfered back to list (to be able to store as json later). Seems weird.
losses_list = [(x[0], x[1]) for x in losses[keep_idx,:]]
self.losses = losses_list
def dict_to_spectrum(spectra_dict):
""" Create spectrum object from spectra_dict.
"""
spectra = []
keys = []
for key, value in spectra_dict.items():
keys.append(key)
if "max_peaks" not in value:
value["max_peaks"] = None
spectrum = Spectrum(min_frag = value["min_frag"],
max_frag = value["max_frag"],
min_loss = value["min_loss"],
max_loss = value["max_loss"],
min_intensity_perc = 0,
exp_intensity_filter = value["exp_intensity_filter"],
min_peaks = value["min_peaks"],
max_peaks = value["max_peaks"])
for key2, value2 in value.items():
setattr(spectrum, key2, value2)
spectrum.peaks = [(x[0],x[1]) for x in spectrum.peaks] # convert to tuples
# Collect in form of list of spectrum objects
spectra.append(spectrum)
return spectra
def process_peaks(peaks, min_frag, max_frag,
min_intensity_perc,
exp_intensity_filter,
min_peaks,
max_peaks = None):
""" Process peaks
Remove peaks outside window min_frag <-> max_frag.
Remove peaks with intensities < min_intensity_perc/100*max(intensities)
Uses exponential fit to intensity histogram. Threshold for maximum allowed peak
intensity will be set where the exponential fit reaches exp_intensity_filter.
Args:
-------
min_frag: float
Lower limit of m/z to take into account (Default = 0.0).
max_frag: float
Upper limit of m/z to take into account (Default = 1000.0).
min_intensity_perc: float
Filter out peaks with intensities lower than the min_intensity_perc percentage
of the highest peak intensity (Default = 0.0, essentially meaning: OFF).
exp_intensity_filter: float
Filter out peaks by applying an exponential fit to the intensity histogram.
Intensity threshold will be set at where the exponential function will have dropped
to exp_intensity_filter (Default = 0.01).
min_peaks: int
Minimum number of peaks to keep, unless less are present from the start (Default = 10).
max_peaks: int
Maximum number of peaks to keep. Set to 'None' to ignore (Default = 'None').
"""
def exponential_func(x, a, b):
return a*np.exp(-b*x)
if isinstance(peaks, list):
peaks = np.array(peaks)
if peaks.shape[1] != 2:
print("Peaks were given in unexpected format...")
if min_intensity_perc > 0:
intensity_thres = np.max(peaks[:,1]) * min_intensity_perc/100
keep_idx = np.where((peaks[:,0] > min_frag) & (peaks[:,0] < max_frag) & (peaks[:,1] > intensity_thres))[0]
if (len(keep_idx) < min_peaks):
# If not enough peaks selected, try again without intensity threshold
keep_idx2 = np.where((peaks[:,0] > min_frag) & (peaks[:,0] < max_frag))[0]
peaks = peaks[keep_idx2,:]
else:
peaks = peaks[keep_idx,:]
else:
keep_idx = np.where((peaks[:,0] > min_frag) & (peaks[:,0] < max_frag))[0]
peaks = peaks[keep_idx,:]
if (exp_intensity_filter is not None) and len(peaks) > 2*min_peaks:
# Fit exponential to peak intensity distribution
num_bins = 100 # number of bins for histogram
# Ignore highest peak for further analysis
peaks2 = peaks.copy()
peaks2[np.where(peaks2[:,1] == np.max(peaks2[:,1])),:] = 0
hist, bins = np.histogram(peaks2[:,1], bins=num_bins)
start = np.where(hist == np.max(hist))[0][0] # Take maximum intensity bin as starting point
last = int(num_bins/2)
x = bins[start:last]
y = hist[start:last]
try:
popt, pcov = curve_fit(exponential_func, x , y, p0=(peaks.shape[0], 1e-4))
threshold = -np.log(exp_intensity_filter)/popt[1]
except RuntimeError:
print("RuntimeError for ", len(peaks), " peaks. Use mean intensity as threshold.")
threshold = np.mean(peaks2[:,1])
except TypeError:
print("Unclear TypeError for ", len(peaks), " peaks. Use mean intensity as threshold.")
print(x, "and y: ", y)
threshold = np.mean(peaks2[:,1])
keep_idx = np.where(peaks[:,1] > threshold)[0]
if len(keep_idx) < min_peaks:
peaks = peaks[np.lexsort((peaks[:,0], peaks[:,1])),:][-min_peaks:]
else:
peaks = peaks[keep_idx, :]
# Sort by peak intensity
peaks = peaks[np.lexsort((peaks[:,0], peaks[:,1])),:]
if max_peaks is not None:
return [(x[0], x[1]) for x in peaks[-max_peaks:,:]] # TODO: now array is transfered back to list (to be able to store as json later). Seems weird.
else:
return [(x[0], x[1]) for x in peaks]
else:
# Sort by peak intensity
peaks = peaks[np.lexsort((peaks[:,0], peaks[:,1])),:]
if max_peaks is not None:
return [(x[0], x[1]) for x in peaks[-max_peaks:,:]]
else:
return [(x[0], x[1]) for x in peaks]
## ----------------------------------------------------------------------------
## -------------------------- Functions to load MS data------------------------
## ----------------------------------------------------------------------------
def load_MS_data(path_data, path_json,
filefilter="*.*",
results_file = None,
num_decimals = 3,
min_frag = 0.0, max_frag = 1000.0,
min_loss = 10.0, max_loss = 200.0,
min_intensity_perc = 0.0,
exp_intensity_filter = 0.01,
peaks_per_mz = 20/200,
min_peaks = 10,
max_peaks = None,
merge_energies = True,
merge_ppm = 10,
replace = 'max',
peak_loss_words = ['peak_', 'loss_']):
""" Collect spectra from set of files
Partly taken from ms2ldaviz.
Prototype. Needs to be replaces by more versatile parser, accepting more MS data formats.
"""
spectra = []
spectra_dict = {}
MS_documents = []
MS_documents_intensity = []
dirs = os.listdir(path_data)
spectra_files = fnmatch.filter(dirs, filefilter)
if results_file is not None:
try:
spectra_dict = functions.json_to_dict(path_json + results_file)
spectra_metadata = pd.read_csv(path_json + results_file[:-5] + "_metadata.csv")
print("Spectra json file found and loaded.")
spectra = dict_to_spectrum(spectra_dict)
collect_new_data = False
with open(path_json + results_file[:-4] + "txt", "r") as f:
for line in f:
line = line.replace('"', '').replace("'", "").replace("[", "").replace("]", "").replace("\n", "")
MS_documents.append(line.split(", "))
with open(path_json + results_file[:-5] + "_intensity.txt", "r") as f:
for line in f:
line = line.replace("[", "").replace("]", "")
MS_documents_intensity.append([int(x) for x in line.split(", ")])
except FileNotFoundError:
print("Could not find file ", path_json, results_file)
print("New data from ", path_data, " will be imported.")
collect_new_data = True
# Read data from files if no pre-stored data is found:
if spectra_dict == {} or results_file is None:
# Run over all spectrum files:
for i, filename in enumerate(spectra_files):
# Show progress
if (i+1) % 10 == 0 or i == len(spectra_files)-1:
print('\r', ' Load spectrum ', i+1, ' of ', len(spectra_files), ' spectra.', end="")
if peaks_per_mz != 0:
# TODO: remove following BAD BAD hack:
# Import first (acutally only needed is PRECURSOR MASS)
spec = Spectrum(min_frag = min_frag,
max_frag = max_frag,
min_loss = min_loss,
max_loss = max_loss,
min_intensity_perc = min_intensity_perc,
exp_intensity_filter = None,
peaks_per_mz = peaks_per_mz,
min_peaks = min_peaks,
max_peaks = max_peaks,
merge_energies = merge_energies,
merge_ppm = merge_ppm,
replace = replace)
# Load spectrum data from file:
spec.read_spectrum(path_data, filename, i)
# Scale the min_peak filter
def min_peak_scaling(x, A, B):
return int(A + B * x)
min_peaks_scaled = min_peak_scaling(spec.precursor_mz, min_peaks, peaks_per_mz)
else:
min_peaks_scaled = min_peaks
spectrum = Spectrum(min_frag = min_frag,
max_frag = max_frag,
min_loss = min_loss,
max_loss = max_loss,
min_intensity_perc = min_intensity_perc,
exp_intensity_filter = exp_intensity_filter,
peaks_per_mz = peaks_per_mz,
min_peaks = min_peaks_scaled,
max_peaks = max_peaks,
merge_energies = merge_energies,
merge_ppm = merge_ppm,
replace = replace)
# Load spectrum data from file:
spectrum.read_spectrum(path_data, filename, i)
# Get precursor mass (later used to calculate losses!)
if spec.precursor_mz is not None:
if 'Precursor_MZ' in spec.metadata:
spec.precursor_mz = float(spec.metadata['Precursor_MZ'])
else:
spec.precursor_mz = spec.parent_mz
# Calculate losses:
spectrum.get_losses()
# Collect in form of list of spectrum objects, and as dictionary
spectra.append(spectrum)
spectra_dict[filename] = spectrum.__dict__
MS_documents, MS_documents_intensity, spectra_metadata = create_MS_documents(spectra, num_decimals,
peak_loss_words,
min_loss, max_loss)
# Add filenames to metadata
filenames = []
for spectrum in spectra:
filenames.append(spectrum.filename)
spectra_metadata["filename"] = filenames
# Save collected data
if collect_new_data == True:
spectra_metadata.to_csv(path_json + results_file[:-5] + "_metadata.csv", index=False)
functions.dict_to_json(spectra_dict, path_json + results_file)
# Store documents
with open(path_json + results_file[:-4] + "txt", "w") as f:
for s in MS_documents:
f.write(str(s) +"\n")
with open(path_json + results_file[:-5] + "_intensity.txt", "w") as f:
for s in MS_documents_intensity:
f.write(str(s) +"\n")
return spectra, spectra_dict, MS_documents, MS_documents_intensity, spectra_metadata
def load_MGF_data(file_mgf,
file_json = None,
num_decimals = 3,
min_frag = 0.0, max_frag = 1000.0,
min_loss = 10.0, max_loss = 200.0,
min_intensity_perc = 0.0,
exp_intensity_filter = 0.01,
peaks_per_mz = 20/200,
min_peaks = 10,
max_peaks = None,
peak_loss_words = ['peak_', 'loss_']):
""" Collect spectra from MGF file
1) Importing MGF file - based on pyteomics parser.
2) Filter spectra: can be based on mininum relative intensity or based on
and exponential intenstiy distribution.
3) Create documents with peaks (and losses) as words. Words are constructed
from peak mz values and restricted to 'num_decimals' decimals.
Args:
-------
file_mgf: str
MGF file that should be imported.
file_json: str
File under which already processed data is stored. If not None and if it
exists, data will simply be imported from that file.
Otherwise data will be imported from file_mgf and final results are stored
under file_json.(default= None).
num_decimals: int
Number of decimals to keep from each peak-position for creating words.
min_frag: float
Lower limit of m/z to take into account (Default = 0.0).
max_frag: float
Upper limit of m/z to take into account (Default = 1000.0).
min_loss: float
Lower limit of losses to take into account (Default = 10.0).
max_loss: float
Upper limit of losses to take into account (Default = 200.0).
min_intensity_perc: float
Filter out peaks with intensities lower than the min_intensity_perc percentage
of the highest peak intensity (Default = 0.0, essentially meaning: OFF).
exp_intensity_filter: float
Filter out peaks by applying an exponential fit to the intensity histogram.
Intensity threshold will be set at where the exponential function will have dropped
to exp_intensity_filter (Default = 0.01).
peaks_per_mz: float
Factor to describe linear increase of mininum peaks per spectrum with increasing
parentmass. Formula is: int(min_peaks + peaks_per_mz * parentmass).
min_peaks: int
Minimum number of peaks to keep, unless less are present from the start (Default = 10).
merge_energies: bool
Merge close peaks or not (False | True, Default is True).
merge_ppm: int
Merge peaks if their m/z is <= 1e6*merge_ppm (Default = 10).
replace: 'max' or None
If peaks are merged, either the heighest intensity of both is taken ('max'),
or their intensitites are added (None).
"""
spectra = []
spectra_dict = {}
MS_documents = []
MS_documents_intensity = []
collect_new_data = True
if file_json is not None:
try:
spectra_dict = functions.json_to_dict(file_json)
spectra_metadata = pd.read_csv(file_json[:-5] + "_metadata.csv")
print("Spectra json file found and loaded.")
spectra = dict_to_spectrum(spectra_dict)
collect_new_data = False
with open(file_json[:-4] + "txt", "r") as f:
for line in f:
line = line.replace('"', '').replace("'", "").replace("[", "").replace("]", "").replace("\n", "")
MS_documents.append(line.split(", "))
with open(file_json[:-5] + "_intensity.txt", "r") as f:
for line in f:
line = line.replace("[", "").replace("]", "")
MS_documents_intensity.append([int(x) for x in line.split(", ")])
except FileNotFoundError:
print("Could not find file ", file_json)
print("Data will be imported from ", file_mgf)
# Read data from files if no pre-stored data is found:
if spectra_dict == {} or file_json is None:
# Scale the min_peak filter
def min_peak_scaling(x, A, B):
return int(A + B * x)
with mgf.MGF(file_mgf) as reader:
for i, spec in enumerate(reader):
# Make conform with spectrum class as defined in MS_functions.py
#--------------------------------------------------------------------
# Scale the min_peak filter
if spec is not None:
min_peaks_scaled = min_peak_scaling(spec['params']['pepmass'][0], min_peaks, peaks_per_mz)
spectrum = Spectrum(min_frag = min_frag,
max_frag = max_frag,
min_loss = min_loss,
max_loss = max_loss,
min_intensity_perc = min_intensity_perc,
exp_intensity_filter = exp_intensity_filter,
peaks_per_mz = peaks_per_mz,
min_peaks = min_peaks_scaled,
max_peaks = max_peaks)
id = i #spec.spectrum_id
spectrum.read_spectrum_mgf(spec, id)
spectrum.get_losses
# Calculate losses:
if len(spectrum.peaks) >= min_peaks:
spectrum.get_losses()
# Collect in form of list of spectrum objects
spectra.append(spectrum)
else:
print("Found empty spectra for ID: ", i)
# Filter out spectra with few peaks
min_peaks_absolute = min_peaks
num_spectra_initial = len(spectra)
spectra = [copy.deepcopy(x) for x in spectra if len(x.peaks) >= min_peaks_absolute]
print("Take ", len(spectra), "spectra out of ", num_spectra_initial, ".")
# Check spectrum IDs
ids = []
for spec in spectra:
ids.append(spec.id)
if len(list(set(ids))) < len(spectra):
print("Non-unique spectrum IDs found. Resetting all IDs.")
for i, spec in enumerate(spectra):
spectra[i].id = i
# Collect dictionary
for spec in spectra:
id = spec.id
spectra_dict[id] = spec.__dict__
# Create documents from peaks (and losses)
MS_documents, MS_documents_intensity, spectra_metadata = create_MS_documents(spectra, num_decimals,
peak_loss_words,
min_loss, max_loss)
# Save collected data
if collect_new_data == True:
spectra_metadata.to_csv(file_json[:-5] + "_metadata.csv", index=False)
functions.dict_to_json(spectra_dict, file_json)
# Store documents
with open(file_json[:-4] + "txt", "w") as f:
for s in MS_documents:
f.write(str(s) +"\n")
with open(file_json[:-5] + "_intensity.txt", "w") as f:
for s in MS_documents_intensity:
f.write(str(s) +"\n")
return spectra, spectra_dict, MS_documents, MS_documents_intensity, spectra_metadata
## --------------------------------------------------------------------------------------------------
## ---------------------- Functions to analyse MS data ----------------------------------------------
## --------------------------------------------------------------------------------------------------
def create_MS_documents(spectra,
num_decimals,
peak_loss_words = ['peak_', 'loss_'],
min_loss = 10.0,
max_loss = 200.0,
ignore_losses = False):
""" Create documents from peaks and losses.
Every peak and every loss will be transformed into a WORD.
Words then look like this: "peak_100.038" or "loss_59.240"
Args:
--------
spectra: list
List of all spectrum class elements = all spectra to be in corpus
num_decimals: int
Number of decimals to take into account
min_loss: float
Lower limit of losses to take into account (Default = 10.0).
max_loss: float
Upper limit of losses to take into account (Default = 200.0).
ignore_losses: bool
True: Ignore losses, False: make words from losses and peaks.
"""
MS_documents = []
MS_documents_intensity = []
spectra_metadata = pd.DataFrame(columns=['doc_ID', 'spectrum_ID', 'sub_ID', 'precursor_mz', 'parent_intensity', 'no_peaks_losses'])
for spec_id, spectrum in enumerate(spectra):
doc = []
doc_intensity = []
if not ignore_losses:
losses = np.array(spectrum.losses)
if len(losses) > 0:
keep_idx = np.where((losses[:,0] > min_loss) & (losses[:,0] < max_loss))[0]
losses = losses[keep_idx,:]
else:
print("No losses detected for: ", spec_id, spectrum.id)
peaks = np.array(spectrum.peaks)
# Sort peaks and losses by m/z
peaks = peaks[np.lexsort((peaks[:,1], peaks[:,0])),:]
if not ignore_losses:
if len(losses) > 0:
losses = losses[np.lexsort((losses[:,1], losses[:,0])),:]
if (spec_id+1) % 100 == 0 or spec_id == len(spectra)-1: # show progress
print('\r', ' Created documents for ', spec_id+1, ' of ', len(spectra), ' spectra.', end="")
for i in range(len(peaks)):
doc.append(peak_loss_words[0] + "{:.{}f}".format(peaks[i,0], num_decimals))
doc_intensity.append(int(peaks[i,1]))
if not ignore_losses:
for i in range(len(losses)):
doc.append(peak_loss_words[1] + "{:.{}f}".format(losses[i,0], num_decimals))
doc_intensity.append(int(losses[i,1]))
MS_documents.append(doc)
MS_documents_intensity.append(doc_intensity)
spectra_metadata.loc[spec_id] = [spec_id, int(spectrum.id), 0, spectrum.precursor_mz, 1, len(doc)]
return MS_documents, MS_documents_intensity, spectra_metadata
def create_modified_MS_documents(spectra,
num_decimals,
peak_loss_words = ['peak_', 'loss_'],
max_word_multiply = 10,
word_multiply_scaling = 0.5,
min_loss = 10.0,
max_loss = 200.0):
""" Create documents from peaks and losses.
Every peak and every loss will be transformed into a WORD.
Words then look like this: "peak_100.038" or "loss_59.240"
Args:
--------
spectra: list
List of all spectrum class elements = all spectra to be in corpus
num_decimals: int
Number of decimals to take into account
peak_loss_words: list of strings
Give string to add to each peak and each loss "word".
max_word_multiply: int
Add more words for higher intensity peaks/losses. Up to max_word_multiply times.
word_multiply_scaling: float
Exponent of how to scale peak intensities to translate into amount of words for documents.
min_loss: float
Lower limit of losses to take into account (Default = 10.0).
max_loss: float
Upper limit of losses to take into account (Default = 200.0).
"""
MS_documents = []
MS_documents_intensity = []
spectra_metadata = pd.DataFrame(columns=['doc_ID', 'spectrum_ID', 'sub_ID', 'parent_mz', 'parent_intensity', 'no_peaks_losses'])
for spec_id, spectrum in enumerate(spectra):
doc = []
doc_intensity = []
losses = np.array(spectrum.losses)
if len(losses) > 0:
keep_idx = np.where((losses[:,0] > min_loss) & (losses[:,0] < max_loss))[0]
losses = losses[keep_idx,:]
else:
print("No losses detected for: ", spec_id, spectrum.id)
peaks = np.array(spectrum.peaks)
# Calculate how to multiply high-intensity "words"
word_multiply = (peaks[:,1]/np.max(peaks[:,1]))
low_limit = (1/max_word_multiply)**(1/word_multiply_scaling)
word_multiply[word_multiply < low_limit] = low_limit
word_multiply = (max_word_multiply*(word_multiply**word_multiply_scaling)).astype(int)
# Sort peaks and losses by m/z
peaks = peaks[np.lexsort((peaks[:,1], peaks[:,0])),:]
if len(losses) > 0:
losses = losses[np.lexsort((losses[:,1], losses[:,0])),:]
# Calculate how to multiply high-intensity "words"
loss_multiply = (losses[:,1]/np.max(losses[:,1]))
low_limit = (1/max_word_multiply)**(1/word_multiply_scaling)
loss_multiply[loss_multiply < low_limit] = low_limit
loss_multiply = (max_word_multiply*(loss_multiply**word_multiply_scaling)).astype(int)
losses_mz = np.round(losses[:,0], decimals = num_decimals)
if (spec_id+1) % 100 == 0 or spec_id == len(spectra)-1: # show progress
print('\r', ' Created documents for ', spec_id+1, ' of ', len(spectra), ' spectra.', end="")
peaks_mz = np.round(peaks[:,0], decimals = num_decimals)
for i in range(len(peaks)):
#doc.extend(word_multiply[i]*[peak_loss_words[0] + "{:.{}f}".format(peaks[i,0], num_decimals)])
doc.extend(word_multiply[i]*[peak_loss_words[0] + str(peaks_mz[i])])
doc_intensity.extend(word_multiply[i]*[int(peaks[i,1])])
for i in range(len(losses)):
#doc.extend(loss_multiply[i]*[peak_loss_words[1] + "{:.{}f}".format(losses[i,0], num_decimals)])
doc.extend(loss_multiply[i]*[peak_loss_words[1] + str(losses_mz[i])])
doc_intensity.extend(loss_multiply[i]*[int(losses[i,1])])
MS_documents.append(doc)
MS_documents_intensity.append(doc_intensity)
spectra_metadata.loc[spec_id] = [spec_id, int(spectrum.id), 0, spectrum.parent_mz, 1, len(doc)]
return MS_documents, MS_documents_intensity, spectra_metadata
def create_subspectra_documents(spectra, num_decimals,
min_loss = 10.0, max_loss = 200.0,
main_peak_cutoff = 0.2,
min_words = 10):
""" Create documents from peaks and losses. AND documents for subspectra (from main peaks)
Every peak and every loss will be transformed into a WORD.
Words then look like this: "peak_100.038" or "loss_59.240"
Args:
--------
spectra: list
List of all spectrum class elements = all spectra to be in corpus
num_decimals: int
Number of decimals to take into account
main_peak_cutoff: float
min_loss: float
Lower limit of losses to take into account (Default = 10.0).
max_loss: float
Upper limit of losses to take into account (Default = 200.0).
"""
MS_documents = []
MS_documents_intensity = []
# sub_spectra_reg = {}
sub_spectra_metadata = pd.DataFrame(columns=['doc_ID', 'spectrum_ID', 'sub_ID', 'parent_mz', 'parent_intensity', 'no_peaks_losses'])
doc_counter = 0
for spec_id, spectrum in enumerate(spectra):
doc = []
doc_intensity = []
losses = np.array(spectrum.losses)
if len(losses) > 0:
keep_idx = np.where((losses[:,0] > min_loss) & (losses[:,0] < max_loss))[0]
losses = losses[keep_idx,:]
else:
print("No losses detected for: ", spec_id, spectrum.id)
peaks = np.array(spectrum.peaks).astype(float)
# Sort peaks and losses by m/z
peaks = peaks[np.lexsort((peaks[:,1], peaks[:,0])),:]
if len(losses) > 0:
losses = losses[np.lexsort((losses[:,1], losses[:,0])),:]
# Normalize intensities
max_peak_intens = np.max(peaks[:,1])
peaks[:,1] = peaks[:,1]/max_peak_intens
if len(losses) > 0:
losses[:,1] = losses[:,1]/max_peak_intens
# Identify main peaks for createing sub-spectra:
main_peak_idx = np.where(peaks[:,1] > main_peak_cutoff)[0]
# if peaks[main_peak_idx[-1],0] > spectrum.parent_mz
main_peaks = peaks[main_peak_idx,:]
sub_peaks_lst = []
sub_losses_lst = []
if len(main_peaks) > 0:
# sub_spectra_reg[str(spec_id)] = peaks[main_peak_idx,:]
for m in range(len(main_peaks)):
sub_peaks = peaks[(peaks[:,0] < main_peaks[m,0]),:]
sub_peaks_lst.append(sub_peaks)
# Calculate new losses with respect to main peak!
sub_losses = sub_peaks
sub_losses[:,0] = main_peaks[m,0] - sub_losses[:,0]
if len(sub_losses) > 0:
keep_idx = np.where((sub_losses[:,0] > min_loss) & (sub_losses[:,0] < max_loss))[0]
sub_losses = sub_losses[keep_idx,:]
sub_losses_lst.append(sub_losses)
if (spec_id+1) % 100 == 0 or spec_id == len(spectra)-1: # show progress
print('\r', ' Created documents for ', spec_id+1, ' of ', len(spectra), ' spectra.', end="")
# Create document from whole spectra
for i in range(len(peaks)):
doc.append("peak_" + "{:.{}f}".format(peaks[i,0], num_decimals))
doc_intensity.append(peaks[i,1])
# doc_intensity.append(int(peaks[i,1]))
for i in range(len(losses)):
doc.append("loss_" + "{:.{}f}".format(losses[i,0], num_decimals))
doc_intensity.append(losses[i,1])
# doc_intensity.append(int(losses[i,1]))
MS_documents.append(doc)
MS_documents_intensity.append(doc_intensity)
# sub_spectra_metadata.loc[doc_counter] = [doc_counter, spec_id, 0, spectrum.parent_mz, 1, len(doc)]
sub_spectra_metadata.loc[doc_counter] = [doc_counter, int(spectrum.id), 0, spectrum.parent_mz, 1, len(doc)]
doc_counter += 1
# Create document from sub-spectra
for m, sub_peaks in enumerate(sub_peaks_lst):
subdoc = []
subdoc_intensity = []
for i in range(len(sub_peaks)):
subdoc.append("peak_" + "{:.{}f}".format(sub_peaks[i,0], num_decimals))
subdoc_intensity.append(sub_peaks[i,1])