-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcore.py
2776 lines (2315 loc) · 125 KB
/
core.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
''' Core script containing all the code for searches, rescoring, and quantification '''
import os
import re
import sys
import logging
import glob
import shutil
import pandas as pd
import pymzml
import pickle
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
import logomaker as lm
import subprocess
from typing import Tuple
from pyteomics import mgf
from pyteomics import proforma
from collections import Counter
from venny4py.venny4py import venny4py
from matplotlib.gridspec import GridSpec
from io import StringIO
logging.getLogger('matplotlib').setLevel(logging.WARNING) # Otherwise font type spam.
logger = logging.getLogger(__name__)
# HLA dictionary for netMHCpan-4.1 and netMHCIIpan-4.3 alleles per cell type.
hla_dict = {
"netMHCpan_human": "HLA-A01:01,HLA-B15:01,HLA-A02:01,HLA-A03:01,HLA-A24:02,HLA-A26:01,HLA-B07:02,HLA-B08:01,HLA-B27:05,HLA-B39:01,HLA-B40:01,HLA-B58:01",
"netMHCpan_mouse": "H-2-Db,H-2-Dd,H-2-Dq,H-2-Kb,H-2-Kd,H-2-Kk,H-2-Kq,H-2-Ld,H-2-Lq",
"netMHCpan_C57Bl6": "H-2-Kb,H-2-Db",
"netMHCpan_JY": "HLA-A02:01,HLA-B07:02,HLA-C07:02",
"netMHCpan_HeLa": "HLA-A03:19,HLA-A68:02,HLA-B15:03,HLA-C12:03",
"netMHCpan_U937": "HLA-A03:01,HLA-A31:01,HLA-B18:01,HLA-B51:01,HLA-C01:02,HLA-C07:01",
"netMHCpan_H1650": "HLA-A02:01,HLA-B15:18,HLA-C07:04",
"netMHCpan_HCT116": "HLA-A01:01,HLA-A02:01,HLA-B45:01,HLA-B18:01,HLA-C07:01,HLA-C05:01",
"netMHCpan_THP1": "HLA-A02:01,HLA-B15:11,HLA-C03:03",
"netMHCpan_HEK293": "HLA-A02:01,HLA-A03:01,HLA-B07:02,HLA-C07:02",
"netMHCpan_A549": "HLA-A25:01,HLA-A30:01,HLA-B18:01,HLA-B44:03,HLA-C12:03,HLA-C16:01",
"netMHCpan_H9": "HLA-A02:01,HLA-A03:01,HLA-B35:03,HLA-B44:02,HLA-C04:01,HLA-C07:04",
"netMHCIIpan_JY": "HLA-DPA10103-DPB10201,HLA-DPA10103-DPB10402,HLA-DQA10103-DQB10302,HLA-DQA10103-DQB10603,HLA-DQA10301-DQB10302,HLA-DQA10301-DQB10603,DRB1_0404,DRB1_1301,DRB4_0104,DRB5_0105",
"netMHCIIpan_U937": "DRB1_1601,DRB1_0101,DRB1_1501,DRB5_0101,HLA-DQA10101-DQB10501,HLA-DQA10102-DQB10501,HLA-DQA10101-DQB10602,HLA-DPA10202-DPB10402,HLA-DPA10202-DPB10201,HLA-DPA10103-DPB10201,HLA-DPA10103-DPB10401",
"netMHCIIpan_THP1": "DRB1_0101,DRB1_1501,DRB5_0101,HLA-DQA10101-DQB10501,HLA-DQA10102-DQB10501,HLA-DQA10102-DQB10602,HLA-DQA10101-DQB10602,HLA-DPA10202-DPB10402,HLA-DPA10202-DPB10201,HLA-DPA10103-DPB10201,HLA-DPA10103-DPB10402",
"netMHCIIpan_human": "DRB1_0101,DRB3_0101,DRB4_0101,DRB5_0101",
"netMHCIIpan_HeLa": "DRB1_0101,DRB3_0101,DRB4_0101,DRB5_0101",
"netMHCIIpan_mouse": "H-2-IAb",
"netMHCIIpan_C57Bl6": "H-2-IAb",
"netMHCIIpan_H9": "DRB1_1501,DRB1_1601",
"netMHCIIpan_HCT116": "DRB1_0305,DRB1_1102,HLA-DQA10502-DQB10202",
"netMHCIIpan_HEK293": "DRB1_1501,HLA-DQA10102-DQB10602",
"netMHCIIpan_A549": "DRB1_0701,DRB1_1104,HLA-DQA10201-DQB10202,HLA-DQA10201-DQB10301,HLA-DQA10505-DQB10202,HLA-DQA10505-DQB10301"
}
def detect_instrument_from_mzml(mzml_file: str) -> str:
"""
Detect the instrument type from an mzML file by reading its contents.
Parameters:
----------
mzml_file : str
Path of mzML file to read in.
Returns:
-------
A string indicating the instrument type, either 'orbitrap' or 'timsTOF'.
"""
with open(mzml_file, 'r') as f:
for i, line in enumerate(f):
if i >= 20000:
return 'orbitrap'
if "ion mobility" in line:
return 'timsTOF'
return 'orbitrap'
# Determine the input file types.
def determine_runs(args):
"""
Determine MS input files, their filetype and provided annotation.
This function checks the input files (.RAW, .d, .mzML) and identifies the instrument type
(Orbitrap or timsTOF) based on the provided MS files. If provided by the user, an annotation
file will be parsed to add sample names and condition. If the condition is 'uninfected',
this is used later on for bacterial peptide filtering.
Parameters:
----------
args : argparse.Namespace
The arguments parsed by the argparse module.
Returns:
-------
instrument : str
A string indicating the instrument type, either 'Orbitrap' or 'timsTOF'.
runs : pd.DataFrame
A pandas DataFrame containing information about the MS input files/runs.
"""
logger.info(f'Determining input file types and possible annotation.')
indir = args.in_dir
ms_data = {} # Store MS file info here.
# Check directory for input files.
raw_files = list(glob.iglob(os.path.join(indir,'*raw'))) # Orbitrap files
mzml_files = list(glob.iglob(os.path.join(indir,'*mzML'))) # Preprocessed mzML files
mzml_files = [mzml for mzml in mzml_files if 'calibrated.mzML' not in mzml] # Ignore intermediary files
d_folders = [ f.path for f in os.scandir(indir) if f.is_dir() and f.path.endswith('.d') ] # timsTOF file directories
# Check for valid input files.
if not any([d_folders, mzml_files, raw_files]):
logging.critical("No orbitrap (.raw), timsTOF (.d) or preprocessed data (.mzML) found in input directory.")
raise FileNotFoundError("No MS files found in the input directory.")
# Check for mixed instrument types.
if raw_files and d_folders:
logging.critical("Orbitrap and timsTOF input data found in input directory! Should be single instrument data as input.")
raise ValueError("Mixed instrument data detected.")
# Determine instrument type.
if d_folders:
ms_data.update({'MS_files': sorted(d_folders)})
instrument = 'timsTOF'
elif raw_files:
ms_data.update({'MS_files': sorted(raw_files)})
instrument = 'orbitrap'
else: instrument = None
# Preprocessed (.mzML) data found, double check if conform to raw MS data.
if mzml_files:
#There is no raw MS data: determine file type from mzML.
if not instrument:
instrument = detect_instrument_from_mzml(mzml_files[0])
# If also raw MS data found, compare to raw data (if any).
else:
ms_basenames = [os.path.splitext(f)[0] for f in (raw_files or d_folders)]
mzml_basenames = [os.path.splitext(f)[0] for f in mzml_files]
for filename in mzml_basenames:
if filename not in ms_basenames:
logging.critical(f'mzML file {filename} does not matching a raw MS file in the input directory.')
raise ValueError(f"mzML file mismatch: {filename}.")
#Add mzML files as raw data.
if 'MS_files' not in ms_data:
ms_data.update({'MS_files': sorted(mzml_files)})
# Initiate pandas dataframe with runs and add the basename.
runs = pd.DataFrame(ms_data)
runs['Filenames'] = runs.iloc[:,0].apply(lambda x: os.path.splitext(os.path.basename(x))[0]) # Filenames.
runs['mzML_files'] = runs['MS_files'].apply(lambda x: os.path.splitext(x)[0] + '.mzML') # Preprocessed mzML.
logging.info(f"Found {len(runs)} {instrument} file(s).")
# Append annotation.
annotation_f = os.path.join(indir, 'annotation.txt')
if os.path.exists(annotation_f):
logging.info('Annotation file found, will append to runs.')
annotation = pd.read_csv(annotation_f, sep='\t')
annotation.columns = ['MS_file','name','condition']
annotation['Filenames'] = annotation['MS_file'].apply(lambda x: os.path.splitext(x)[0]) #Remove extension to match by filename
# If our MS files are specified within the annotation file its good to go.
if runs['Filenames'].isin(annotation['Filenames']).all():
runs = pd.merge(runs,annotation, on='Filenames', how='inner')
if len(annotation) > len(runs):
logging.warning('There were more MS files specified in the annotation file than there were MS files in the input directory.')
else:
logging.warning('Some of the MS files were not specified in annotation file, no annotation will be added.')
return instrument, runs
def parse_protein_header(header, args):
"""
Parse FASTA protein header line to extract relevant fields such as protein ID, description, gene name,
accession number, and respective species. Recommended to use UniProtKB!
Parameters:
header : str
FASTA protein header.
args : argparse.Namespace
The arguments parsed by the argparse module.
Returns:
dict
A dictionary containing the description, gene, UniProtKB accession and species.
"""
# Get Protein ID, description, gene and accession from UniProtKB formatted headers.
prot_id = header.split()[0][1:]
descr = re.search(r"^\S+ (.+)", header).group(1) if re.search(r"^\S+ (.+)", header) else prot_id
gene = re.search(r"GN=(\S+)", header).group(1) if re.search(r"GN=(\S+)", header) else prot_id
accession = prot_id.split('|')[1] if prot_id.count('|') == 2 else prot_id
# Assign species/contaminant protein. Contaminant tag default 'CON__' (MaxQuant).
if 'OS=' in header:
species = prot_id.split('_')[-1]
elif args.contaminant in header:
species = 'contaminant'
else:
species = 'unknown'
return {'description': descr, 'gene': gene, 'acc': accession, 'species': species}
def make_folder(folder):
"""
Creates a directory if it does not exist and give full read/write/execute permissions.
Parameters:
folder (str): The path to the folder to be created.
Returns:
None
"""
if not os.path.exists(folder):
os.mkdir(folder)
os.chmod(folder, 0o777) # Give user permissions
def check_file(file):
"""
Checks whether the specified file exists.
Parameters:
file (str): The path to the file to check.
Returns:
None
"""
if not os.path.exists(file):
logging.critical(f"Path {file} not found!")
raise SystemExit
def prepare_fasta(args):
"""
Check target/decoy numbers and parse protein information from specified FASTA file.
If no decoys are found a concatenated target-decoy databse will be made.
Parameters:
args : argparse.Namespace
The arguments parsed by the argparse module.
Returns:
tuple: (fasta, prot_info)
fasta: The path to the FASTA file (modified if decoys are generated).
prot_info: A dictionary containing protein information (description, gene, accession, species).
"""
# First check existence specified FASTA file.
fasta = str(args.fasta)
check_file(fasta)
# Initiate dictionaries and counts.
target, decoy = [0]*2 # Count how many target and decoy sequences present.
prot_info = {} # Here all protein information is stored.
target_seq = {} # If no decoys, we need to revert these and append.
# Read FASTA file and gather protein information
with open(fasta, 'r') as in_f:
prot_id = None
for line in in_f:
line = line.rstrip()
if line.startswith('>rev_'):
decoy += 1
elif line.startswith('>'):
target += 1
# Save protein info (description, species, ..) and initiate sequence storage.
prot_id = line.split()[0][1:] # Extract protein ID without '>'.
prot_id_peaks = line.split()[0][4:] # For PEAKS, which chops off 'sp|' or 'tr|'
header_info = parse_protein_header(line, args)
prot_info[prot_id] = header_info
prot_info[prot_id_peaks] = header_info
target_seq[prot_id] = ''
elif prot_id:
target_seq[prot_id] += line
logging.info(f'{os.path.basename(args.fasta)} contains {decoy} decoy and {target} target proteins.')
# Generate and concatenate decoys if none are found
if decoy == 0:
fasta = re.sub(r'\.\w+$', '_tda.fasta', fasta)
logging.warning('No decoys found, generating reverse target-decoy database.')
with open(fasta, 'w') as out_fasta:
for prot_id, seq in target_seq.items():
rev_seq = seq[::-1] # Reverse
out_fasta.write(f'>{prot_id} {prot_info[prot_id]["description"]} GN={prot_info[prot_id]["gene"]}\n'
f'{seq}\n' # Target
f'>rev_{prot_id} decoy_{prot_id}\n'
f'{rev_seq}\n') # Decoy
logging.info(f'Generated {os.path.basename(fasta)}!')
return fasta, prot_info
def run_mokapot(pin_folder, args) -> None:
"""
Concatenates PIN files from a specified folder, performs engine-specific adjustments,
and runs mokapot on search engine features.
Parameters:
pin_folder : str
Path to the folder containing engine-specific PIN files.
args : argparse.Namespace
Command-line arguments.
Returns:
None
"""
mokapot_folder = os.path.join(args.in_dir, 'report', 'mokapot')
make_folder(mokapot_folder)
engine = os.path.split(pin_folder)[-1]
logging.info(f'Running mokapot for {engine} results - see log at report/mokapot/{engine}_search_log.txt.')
# Concatenate all PIN files and keep the header of the first file.
pin_file = f'{mokapot_folder}/{engine}_search_combined.pin'
concat_cmd = f"awk 'NR == 1 || FNR > 1' {pin_folder}/*.pin > {pin_file}"
subprocess.run(concat_cmd, shell=True, check=True)
# Search engine-specific adjustments PIN file (Comet and MSFragger).
if engine == 'Comet': # Merge trailing tab-delimited alternative proteins.
with open(pin_file, 'r') as pin, open(f'{mokapot_folder}/tmp.pin', 'w') as out:
for i, line in enumerate(pin):
splitted = line.split('\t')
if i == 0:
columns = len(splitted)-1 # Number of columns in the header.
out.write('\t'.join(splitted[:columns]) + '\t' + ';'.join(splitted[columns:]))
shutil.move(f'{mokapot_folder}/tmp.pin', pin_file)
elif engine == 'MSFragger': # Remove trailing semicolon.
os.system(f"awk '{{sub(/;$/, \"\"); print}}' {pin_file} > {mokapot_folder}/tmp.pin")
shutil.move(f'{mokapot_folder}/tmp.pin', pin_file)
# Run mokapot. We use a test FDR of 5% as this is sometimes required for samples with low peptide identifications.
mokapot_log = f'{mokapot_folder}/{engine}_search_log.txt'
try:
mokapot_cmd = f"mokapot --keep_decoys --test_fdr 0.05 -d {mokapot_folder} -r {engine}_search {pin_file} > {mokapot_log} 2>&1"
subprocess.run(mokapot_cmd, shell=True, check=True)
except subprocess.CalledProcessError as e:
logging.critical(f"Mokapot failed for {engine}: {e}")
raise
def run_MSFragger(args, fasta_file, instrument, runs) -> None:
"""
Executes MSFragger search with the specified parameters, processes search results.
Pre-made parameter files are present in tools/MSFragger-4.1/params/.
Parameters:
args : argparse.Namespace
Command-line arguments.
fasta_file : str
Path to the FASTA file to use for the MSFragger search.
instrument : str
Instrument being orbitrap/timsTOF, important for parameter file selection.
runs : pd.DataFrame
DataFrame containing information about the runs/files to be searched.
Returns:
None
"""
logging.info('Starting MSFragger-4.1 search!')
# Prepare folder and check executable!
indir = args.in_dir
msfragger_folder = f'{indir}/report/search_res/MSFragger'
make_folder(msfragger_folder)
exe = 'external_tools/MSFragger-4.1/MSFragger-4.1.jar'
check_file(exe)
# Check parameter file and copy to output folder with correct FASTA specified.
param_file = f'external_tools/MSFragger-4.1/params/{instrument}_{args.mod}.params'
check_file(param_file)
os.system(f"sed 's#your_fasta#{fasta_file}#g' {param_file} > {msfragger_folder}/used.params")
# Construct command
cmd = f'java -Dfile.encoding=UTF-8 -Xmx490g -jar {exe} {msfragger_folder}/used.params '
# Always use raw MS files if available - otherwise mzMLs.
if 'MS_files' in runs: cmd += ' '.join(runs['MS_files'].tolist())
else: cmd += ' '.join(runs['mzML_files'].tolist())
# Execute
log_file = os.path.join(msfragger_folder, 'search_log.txt')
logging.info(f'Executing MSFragger - see full log in {log_file}')
try:
subprocess.run(f'{cmd} > {log_file} 2>&1', shell=True, check=True)
except subprocess.CalledProcessError as e:
logging.critical(f"MSFragger failed: {e}")
raise
# Clean-up pepindices and pepXML generated.
map(os.remove, glob.glob(f'{fasta_file}*pepindex'))
map(os.remove, glob.glob(f'{indir}/*pepXML'))
# Move percolator input files to search results folder.
for pin_file in glob.glob(f'{indir}/*.pin'):
shutil.move(pin_file, f'{msfragger_folder}/{os.path.basename(pin_file)}')
# Keep calibrated mzMLs or otherwise uncalibrated ones (sometimes not enough data for calibration).
for mzml in glob.glob(f'{indir}/*_calibrated.mzML'):
final_mzml = mzml.replace('_calibrated','')
shutil.move(mzml, final_mzml)
for mzml in glob.glob(f'{indir}/*_uncalibrated.mzML'):
final_mzml = mzml.replace('_uncalibrated','')
if os.path.exists(final_mzml): # We have a calibrated version - remove.
os.remove(mzml)
else:
shutil.move(mzml, final_mzml)
# Run mokapot on combined PIN file.
run_mokapot(msfragger_folder, args)
def run_Comet(args, fasta_file, instrument, runs) -> None:
"""
Executes a Comet search using specified parameters and mzML files.
Parameters:
args : argparse.Namespace
Command-line arguments.
fasta_file : str
Path to the FASTA file to use for the MSFragger search.
instrument : str
Instrument being orbitrap/timsTOF, important for parameter file selection.
runs : pd.DataFrame
DataFrame containing information about the runs/files to be searched.
Returns:
None.
"""
logging.info('Starting Comet v2024.01.0 search!')
indir = args.in_dir
# Check if mzMLs were generated by MSFragger.
mzML_files = runs['mzML_files']
for mzML in mzML_files:
if not os.path.exists(mzML):
logging.critical(f"{mzML} not found - first run MSFragger.")
raise SystemExit
# Prepare folder and check executable!
comet_folder = f'{indir}/report/search_res/Comet'
make_folder(comet_folder)
exe = 'external_tools/Comet/comet.linux.exe'
check_file(exe)
# Check parameter file and copy to output folder with correct FASTA specified.
param_file = f'external_tools/Comet/params/{instrument}_{args.mod}.params'
check_file(param_file)
shutil.copy(param_file,f'{comet_folder}/used.params')
# Construct and execute command.
log_file = f'{comet_folder}/search_log.txt'
logging.info(f'Executing Comet - see full log in {log_file}.')
cmd = f'{exe} -D{fasta_file} -P{param_file} ' + ' '.join(mzML_files)
try:
subprocess.run(f'{cmd} > {log_file} 2>&1', shell=True, check=True)
except subprocess.CalledProcessError as e:
logging.critical(f"Comet failed: {e}")
raise
# Move output PIN files to report folder and run mokapot
for pin_file in glob.glob(f'{indir}/*.pin'):
shutil.move(pin_file, f'{comet_folder}/{os.path.basename(pin_file)}')
# Run mokapot.
run_mokapot(comet_folder, args)
def run_Sage(args, fasta_file, instrument, runs) -> None:
"""
Executes a Sage search using specified parameters and mzML files.
Parameters:
args : argparse.Namespace
Command-line arguments.
fasta_file : str
Path to the FASTA file to use for the MSFragger search.
instrument : str
Instrument being orbitrap/timsTOF, important for parameter file selection.
runs : pd.DataFrame
DataFrame containing information about the runs/files to be searched.
Returns:
None.
"""
logging.info('Starting Sage v0.14.7 search!')
indir = args.in_dir
# Check if mzMLs were generated by MSFragger.
mzML_files = runs['mzML_files']
for mzML in mzML_files:
if not os.path.exists(mzML):
logging.critical(f"{mzML} not found - first run MSFragger.")
raise SystemExit
# Prepare folder and check software!
sage_folder = f'{indir}/report/search_res/Sage'
make_folder(sage_folder)
exe = 'external_tools/Sage/sage'
check_file(exe)
# Retrieve calibrated MS2 tolerance and TopN peaks settings from MSFragger search
log_path = f'{indir}/report/search_res/MSFragger/search_log.txt'
if os.path.exists(log_path):
with open(log_path, 'r') as in_file:
for line in in_file:
if 'New fragment_mass_tolerance' in line: ms2_tol = line.rstrip().split()[3]
elif 'New use_topN_peaks' in line: max_peaks = line.rstrip().split()[3]
# Check parameter file and copy to output folder with correct FASTA specified.
param_file = f'external_tools/Sage/params/{instrument}_{args.mod}.json'
check_file(param_file)
# Adapt search configuration with calibrate search settings if found.
if ms2_tol is not None:
logging.info(f'Using MSFragger calibrated search settings: fragment ion tolerance of {ms2_tol} ppm and top {max_peaks} peaks in spectrum.')
with open(param_file, 'r') as in_f, open(f'{sage_folder}/used_params.json', 'w') as out_f:
for line in in_f:
if 'fragment_tol' in line: out_f.write(f' "fragment_tol": {{"ppm": [-{ms2_tol},{ms2_tol}]}},\n')
elif 'max_peaks' in line: out_f.write(f' "max_peaks": {max_peaks},\n')
else: out_f.write(line)
else:
shutil.copy(param_file,f'{sage_folder}/used_params.json')
# Construct and execute command.
cpus = int(os.cpu_count() / 2)
cmd = f'{exe} --batch-size {cpus} --write-pin -o {sage_folder} -f {fasta_file} {sage_folder}/used_params.json ' + ' '.join(mzML_files)
os.environ['RUST_MIN_STACK'] = '4194304' # Set to stack size 4 MB to avoid overflow error.
log_file = f'{sage_folder}/search_log.txt'
logging.info(f'Executing Sage - see full log in {sage_folder}.')
try:
subprocess.run(f'{cmd} > {log_file} 2>&1', shell=True, check=True)
except subprocess.CalledProcessError as e:
logging.critical(f"Sage failed: {e}")
raise
# Sage combines a single PIN output file for all runs, so just run mokapot here.
run_mokapot(sage_folder, args)
# Convert db.psms.csv to mokapot input file.
def run_PEAKS(args, index2scan) -> None:
"""
Generate a percolator input file for PEAKS from exported PSM report (db.psms.csv).
This db.psms.csv has to placed manually in the correct folder!
Parameters:
args : argparse.Namespace
Command-line arguments.
index2scan : dict
Spectrum index to scan title, parsed before by mzML reading.
Returns:
None.
"""
# PEAKS Studio PSM report should be exported (db.psms.csv) - this only tested for PEAKS 12 with decoys exported!
peaks_folder = f'{args.in_dir}/report/search_res/PEAKS'
csv_file = f'{peaks_folder}/db.psms.csv'
check_file(csv_file)
# Make additional columns for correct PIN format.
df = pd.read_csv(csv_file,sep=',')
df['Run'] = df['Source File'].apply(lambda x: x.replace('.mzML','')) # PEAKS should be ran on preprocessed mzML!
df['scan_id'] = df['Run'] + '_' + df['Scan'].astype(str)
# PEAKS works with spectrum indices, we convert here as we saved this during mzML reading with pyteomics.
df['ScanNr'] = df['scan_id'].apply(lambda x: index2scan.get(x))
missing_scans = df['ScanNr'].isna().sum()
converted_scans = df['ScanNr'].notna().sum()
if (converted_scans / len(df)) < 0.98: # Likely something wrong if less than 98% of the scans are converted!
raise ValueError("PEAKS scan indices were not matched to a stored scan title! Did you search mzML in PEAKS Studio? Try re-run.")
elif missing_scans > 0:
logging.warning(f'{missing_scans} / {len(df)} scan results from PEAKS not assigned to saved ScanNr parsed from mzMLs.')
df = df[df['ScanNr'].notna()]
# Append additional columns.
df['SpecId'] = df['Run'] + '_' + df['ScanNr']
df['Label'] = df['decoy'].map({True: -1, False: 1})
df['Proteins'] = df['Accession'].apply(lambda x: x.replace('#DECOY#','rev_')) # Change decoy prefix to be consistent.
# Ion mobility scoring feature will only be present for timsTOF data.
selected_columns = ['SpecId', 'Label', 'ScanNr', '-10LgP', 'Tag Length', 'Delta RT', 'MS2 Correlation', 'ppm', 'Peptide', 'Proteins']
if 'Delta 1/k0' in df.columns:
selected_columns.append('Delta 1/k0')
mokapot_input = df[selected_columns]
# Save input and run mokapot.
mokapot_input.to_csv(f'{peaks_folder}/db.psms.converted.pin',sep='\t',index=False)
run_mokapot(f'{args.in_dir}/report/search_res/PEAKS', args)
def parse_precursor(spectrum) -> Tuple[float, str]:
"""
Parses the precursor information from a given spectrum object.
This function attempts to extract the m/z value and charge state of the selected precursor.
If the normal method of extraction fails due to missing precursor information,
it falls back to parsing the string representation of the spectrum using regular expressions.
Parameters:
spectrum
Pyteomics spectrum object containing spectral data.
Returns:
tuple: A tuple containing:
prec_mz : float
The m/z value of the precursor.
charge : str
The charge state of the precursor.
"""
try: # Normal syntax.
precursor = spectrum.selected_precursors[0]
prec_mz = precursor['mz']
charge = precursor['charge']
except: # Sometimes precursor not found - regex fix.
spectrum_string = spectrum.to_string().decode('utf-8')
prec_mz_match = re.search(r'name="selected ion m/z" value="([\d.]+)"', spectrum_string)
charge_match = re.search(r'name="charge state" value="(\d+)"', spectrum_string)
if prec_mz_match and charge_match:
prec_mz = float(prec_mz_match.group(1))
charge = charge_match.group(1)
else:
logging.warning("Problem with mzML parsing of spectra in run {run} scan {scan}.")
raise SystemExit
return prec_mz, charge
def write_MGF(args, mzml, run) -> None:
"""
Converts an mzML file to MGF format and writes it to disk.
This function reads a specified mzML file, extracts the precursor information
and spectral data for each spectrum, and writes it to a MGF file in the scans directory.
These are handy for MS2Rescore, spectrum plotting and data backup.
Parameters:
args : argparse.Namespace
Command-line arguments.
mzml : str
The path to the mzML file to be converted.
run: str
Basename of mzML file.
Returns:
None.
"""
with open(f'{args.in_dir}/report/scans/{run}.mgf','w') as mgf_out:
mzml_run = pymzml.run.Reader(mzml)
for spectrum in mzml_run:
# Get precursor info.
prec_mz, charge = parse_precursor(spectrum)
#Write the MGF
mgf_out.write(
f"BEGIN IONS\n"
f"TITLE={run}_scan={str(spectrum.id_dict['scan'])}_z={charge}\n"
f"RTINSECONDS={(spectrum.scan_time_in_minutes()*60):.6f}\n"
f"PEPMASS={prec_mz:.4f}\n"
f"CHARGE={charge}+\n"
)
for mz, intensity in zip(spectrum.mz,spectrum.i):
mgf_out.write(f"{mz:.6f}\t{intensity}\n") # Six digits to reduce file size
mgf_out.write('END IONS\n')
def read_mzML(args, runs) -> dict:
"""
Reads scan information from mzML files and save MGF files.
This function parses each mzML file generated by MSFragger. It extracts spectrum index, titles,
MS2-level scan data, precursor information, and ion mobility.
It saves the scan and index2scan dictionaries as pickle files to bypass this lengthy step if the
script is repeated. The index2scan is used to convert PEAKS results only.
Parameters:
runs: dict
A dictionary containing 'mzML_files', which lists the paths to mzML files.
args : argparse.Namespace
Command-line arguments.
Returns:
dict: A tuple containing two dictionaries:
scans
Dictionary of spectra (run_scanNumber) and associated scan information.
index2scan
Dictionary of spectrum index to scan number (for PEAKS results later).
"""
logging.info('Reading scan info from mzML files and generating MGFs.')
scans = {}
index2scan = {}
# Making MGF files for simplified MS2Rescore spectrum parsing.
scan_folder = f'{args.in_dir}/report/scans/'
make_folder(scan_folder)
# Read through mzML files - anticipating MSFragger generated mzML file format.
for mzml in runs['mzML_files']:
run = os.path.splitext(os.path.basename(mzml))[0]
logging.info(f'Now doing {run}..')
# Write MGF for simplified parsing MS2Rescore and plots later.
if not os.path.exists(f'{scan_folder}/{run}.mgf'):
write_MGF(args, mzml, run)
# Read mzML for the scans dictionary.
mzml_run = pymzml.run.Reader(mzml)
for spectrum in mzml_run:
if spectrum['ms level'] != 2: continue # Only MS2-level scans.
scan = str(spectrum.ID)
specid = f"{run}_{scan}"
ion_mobility = spectrum.get('MS:1002815',0) # Default to zero if missing.
prec_mz, charge = parse_precursor(spectrum)
# PEAKS scan dict: (index+1) --> Scan
index2scan.update({f'{run}_{(spectrum.index + 1)}': scan})
# Update scans dict.
scans.update({specid: {
'run': run,
'scan': scan,
'spectrum_index': spectrum.index,
'rt': str(spectrum.scan_time_in_minutes()),
'mz': str(prec_mz),
'z': str(charge),
'im': str(ion_mobility),
'rescore': f'{run}_scan={scan}_z={charge}_seq='} # Seq append later for unique PSM identifier.
})
# Save this so this can be parsed immediately upon next run of the script if necessary.
with open(f'{args.in_dir}/report/scans/scans.pkl', 'wb') as scans_file: pickle.dump(scans, scans_file)
with open(f'{args.in_dir}/report/scans/index2scan.pkl', 'wb') as index_file: pickle.dump(index2scan, index_file)
return scans, index2scan
def get_peptidoform(peptide) -> str:
"""
Converts modified peptide sequence of search engines to PSI-MOD peptidoform notation.
These peptidoform notations are compatible with MS2Rescore/TIMS2Rescore.
A variety of modification tags were encountered dependent per search engine, although
the mod_mapping dictionary has to be extended if additional PTMs are considered in the search.
It also handles N-terminal modifications by reformatting them appropriately.
Parameters:
peptide : str
Modified peptide sequence outputted by search engine
Returns:
peptide : str
Peptide adapted to PSI-MOD peptidoform notation.
"""
# Modification specifications vary according search engine.
mod_mapping = {
'[+57.0215]': '[Carbamidomethyl]',
'+57.021465': 'Carbamidomethyl',
'[+15.9949]': '[Oxidation]',
'[+42.010567]': '[Acetyl]',
'[+119.0041]': '[Cysteinylation]',
'n[304.2072]': '[TMTpro]-',
'n[+304.20715]': '[TMTpro]-',
'[304.2072]': '[TMTpro]',
'[+304.20715]': '[TMTpro]',
'n[229.1629]': '[TMT6plex]-',
'[229.1629]': '[TMT6plex]',
'[+229.16293]': '[TMT6plex]',
'(+229.16)': '[TMT6plex]',
'n[+229.1629]': '[TMT6plex]-',
'[+229.1629]': '[TMT6plex]',
'[15.9949]': '[Oxidation]',
'[57.0215]': '[Carbamidomethyl]',
'[119.0041]': '[Cysteinylation]',
'[-17.0265]': '[Gln->pyro-Glu]',
'[-18.0106]': '[Glu->pyro-Glu]',
'n[42.0106]': '[Acetyl]-',
'[-17.026548]': '[Gln->pyro-Glu]',
'[-18.010565]': '[Glu->pyro-Glu]',
'(+15.99)': '[Oxidation]',
'(+42.01)': '[Acetyl]',
'(-17.03)': '[Gln->pyro-Glu]',
'(-18.01)': '[Glu->pyro-Glu]',
'(+119.00)': '[Cysteinylation]',
}
# Replace the modification names using dict.
for mod, psimod in mod_mapping.items():
peptide = peptide.replace(mod, psimod)
# Replace N-terminal modifications as A[TMT6plex]XX to [TMT6plex]-AXX.
for nt_mod in ['TMT6plex', 'TMTpro', 'Acetyl']:
pattern = rf'^([A-Z])\[({nt_mod})\]'
peptide = re.sub(pattern, r'[\2]-\1', peptide)
return peptide
def prepare_tsv(psms, scans):
"""
Prepares a DataFrame containing TSV input to be used for MS2Rescore/TIMS2Rescore.
This function constructs a DataFrame containing various basic PSM metrics (RT, IM, mz, etc.).
Parameters:
psms : pd.DataFrame
DataFrame containing peptide spectrum match data.
scans : dict
Dictionary containing scan information indexed by spectrum ID.
Returns:
tsv_df : pd.DataFrame
A DataFrame with TSV input for rescoring.
"""
# Initiate tsv_df dataframe.
columns = ['peptidoform','peptide','spectrum_id','run','is_decoy','score','qvalue',
'pep','precursor_mz','retention_time','protein_list','rank']
tsv_df = pd.DataFrame(columns=columns)
# Get charge from saved scans dict.
psms['z'] = psms['specid'].apply(lambda x: scans[x]['z'])
# Populate the dataframe.
tsv_df['peptidoform'] = psms['Peptide'].apply(lambda x: get_peptidoform(x)) + '/' + psms['z'] # e.g. AAM[Oxidation]ADSAA/2
tsv_df['peptide'] = psms['Peptide'].apply(lambda x: re.sub('[^A-Z]+', '', x)) # e.g. AAMADSAAA
tsv_df['spectrum_id'] = psms['specid'].apply(lambda x: scans[x]['rescore']) + tsv_df['peptide'] #Filename_scan=xx_z=2_seq=AAMADSAA
tsv_df['run'] = psms['run']
tsv_df['is_decoy'] = ~psms['Label']
tsv_df['score'] = psms['mokapot score']
tsv_df['qvalue'] = psms['mokapot q-value']
tsv_df['pep'] = psms['mokapot PEP']
tsv_df['ion_mobility'] = psms['specid'].apply(lambda x: scans[x]['im']) # Get ion mobility.
tsv_df['precursor_mz'] = psms['specid'].apply(lambda x: scans[x]['mz']) # Get m/z.
tsv_df['retention_time'] = psms['specid'].apply(lambda x: scans[x]['rt']) # Get RT.
tsv_df['protein_list'] = psms['Proteins'].apply(lambda x: x.split(';'))
tsv_df['rank'] = 1
return tsv_df
# Read mokapot PSMs from target and decoys
def read_mokapot_search(args, engine: str) -> pd.DataFrame:
"""
Read and combine mokapot target and decoy mokapot PSM outputs.
Parameters:
in_dir : str
The input directory containing the mokapot report files.
engine : str
The name of the search engine used (e.g. 'Comet').
Returns:
pd.DataFrame
A combined DataFrame containing both target and decoy PSMs.
"""
# File paths.
mokapot_dir = f'{args.in_dir}/report/mokapot'
target_file = f'{mokapot_dir}/{engine}_search.mokapot.psms.txt'
decoy_file = f'{mokapot_dir}/{engine}_search.mokapot.decoy.psms.txt'
# Read target PSMs
check_file(target_file)
psms_target = pd.read_csv(target_file,sep='\t')
# Read decoy PSMs
check_file(decoy_file)
psms_decoy = pd.read_csv(decoy_file,sep='\t')
#Concatenate and return.
psms = pd.concat([psms_target, psms_decoy], ignore_index=True)
return psms
def run_MS2Rescore(tsv_df: pd.DataFrame, features: pd.DataFrame, instrument:str, args, engine: str) -> None:
"""
Run MS2Rescore, the following steps are followed:
1. Extend mokapot PSM info with search engine scoring features.
2. Prepare input and configuration file.
3. Run MS2Rescore (or TIMS2Rescore for timsTOF data).
4. Log output and move output files.
Parameters:
tsv_df : pd.DataFrame
DataFrame containing the mokapot results.
features : pd.DataFrame
DataFrame containing the search engine scoring features.
args : argparse.Namespace
Command-line arguments.
instrument : str
The MS instrument, either orbitrap or timsTOF.
engine : str
The name of the search engine used.
Returns:
None.
"""
ms2rescore_folder = f'{args.in_dir}/report/ms2rescore/'
# Re-shuffle indices and join the mokapot results with PIN features.
features.set_index('spectrum_id', inplace=True)
features = features.add_prefix('rescoring:')
tsv_df['spectrum_id_index'] = tsv_df['spectrum_id']
tsv_df.set_index('spectrum_id_index', inplace=True)
tsv_joint = tsv_df.join(features, how='inner')
# Specify the rank of the search engine if within scoring features (otherwise defaults to 1).
if 'rescoring:rank' in tsv_joint:
tsv_join = tsv_joint.pop('rescoring:rank')
# Print out MS2Rescore input file.
ms2rescore_input = f'{ms2rescore_folder}/{engine}_rescore_input.tsv'
tsv_joint.to_csv(ms2rescore_input,sep='\t',index=False)
# Configuration file.
config_file = f'external_tools/ms2rescore/{instrument}_{args.mod}.json'
check_file(config_file)
# Construct command and run.
log_file = f'{ms2rescore_folder}/{engine}_pipeline_log.txt'
cmd = f'ms2rescore -t tsv -s {args.in_dir}/report/scans/ -p {ms2rescore_input} -c {config_file} -o {ms2rescore_folder}/{engine}'
logging.info(f'Running MS2Rescore for {engine} - see log {log_file}.\nExecuted command: {cmd}')
try:
subprocess.run(f'{cmd} > {log_file} 2>&1', shell=True, check=True)
except subprocess.CalledProcessError as e:
logging.critical(f"MS2Rescore failed: {e}")
raise
# Print to log
with open(log_file, 'r') as log_in:
for line in log_in:
if 'core // Identified' in line:
gain = line.rstrip().split('// ')[-1]
logging.info(f'{gain} PSMs at 1% FDR after rescoring.')
# Move the mokapot output files: add ms2rescore to avoid confusion with files before rescoring.
for mokapot_file in glob.glob(f'{ms2rescore_folder}/{engine}.mokapot*txt'):
destination = f'{args.in_dir}/report/mokapot/' + os.path.basename(mokapot_file.replace(engine,engine + '_ms2rescore'))
shutil.move(mokapot_file, destination)
def rescore_MSFragger(args, instrument: str, scans: dict) -> None:
"""
Prepares and executes MS2Rescore for MSFragger search engine results.
This function processes mokapot PSM output from MSFragger, prepares input files for MS2Rescore,
appends rescoring features from the corresponding PIN file, and then runs MS2Rescore.
Parameters:
args : argparse.Namespace
Command-line arguments.
instrument : str
The MS instrument, either orbitrap or timsTOF.
scans : dict
Dictionary containing scan information.
Returns:
None.
"""
logging.info('Preparing MS2Rescore input for MSFragger results.')
indir = args.in_dir
# Check and read mokapot target PSM output.
psms = read_mokapot_search(args,'MSFragger')
psms['run'] = psms['SpecId'].apply(lambda x: '.'.join(x.split('.')[:-3])) # e.g. H083972_uPAC_10_CMB-623_FRIMP_ImPep_LFQ_HCT116-1.12141.12141.3_1
psms['specid'] = psms['run'] + '_' + psms['ScanNr'].astype(str) # To retrieve from scans dictionary.
psms['Peptide'] = psms['Peptide'].apply(lambda x: x[2:-3]) # e.g. R.SHYEEGPGKNLPFSVENKWS3.L
# Prepare initial columns for TSV input.
tsv_df = prepare_tsv(psms, scans)
# Now append search engine features from the percolator input file.
pin_file = f'{indir}/report/mokapot/MSFragger_search_combined.pin'
check_file(pin_file)
features = pd.read_csv(pin_file,sep='\t',dtype=str)
features['run'] = features['SpecId'].apply(lambda x: '.'.join(x.split('.')[:-3])) # e.g. H083972_uPAC_10_CMB-623_FRIMP_ImPep_LFQ_HCT116-1.12141.12141.3_1
features['Peptide'] = features['Peptide'].apply(lambda x: re.sub('[^A-Z]+', '', x[2:-3])) # e.g. R.SHYEEGPGKNLPFSVENKWS3.L
features['specid'] = features['run'] + '_' + features['ScanNr'] # To retrieve from scans dictionary.
features['spectrum_id'] = features['specid'].apply(lambda x: scans[x]['rescore']) + features['Peptide']
features = features.drop(['run','specid','ScanNr','SpecId','Label','Peptide','Proteins'], axis=1) # Unnecessary columns
# Run MS2Rescore
run_MS2Rescore(tsv_df,features,instrument,args,'MSFragger')
def rescore_Comet(args, instrument: str, scans: dict) -> None:
"""
Prepares and executes MS2Rescore for Comet search engine results.
This function processes mokapot PSM output from Comet, prepares input files for MS2Rescore,
appends rescoring features from the corresponding PIN file, and then runs MS2Rescore.
Parameters:
args : argparse.Namespace
Command-line arguments.
instrument : str
The MS instrument, either orbitrap or timsTOF.
scans : dict
Dictionary containing scan information.
Returns:
None.
"""
logging.info('Preparing MS2Rescore input for Comet results.')
indir = args.in_dir