forked from ambj/MuPeXI
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MuPeXI.py
executable file
·1795 lines (1411 loc) · 85.3 KB
/
MuPeXI.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
#!/usr/bin/env python
"""
MuPeXI - Mutant peptide extractor and Informer
Date: 2015-09-03
By: Anne-Mette Bjerregaard
MuPeXI.py extracts user defined peptides lengths around missense variant mutations, indels and frameshifts.
Information from each mutation is annotated together with the mutant and normal peptides in the file output.
"""
# Import modules
from collections import defaultdict, namedtuple
from datetime import datetime
from itertools import izip
from Bio.Seq import Seq
from Bio.Alphabet import generic_dna
from Bio import BiopythonWarning
from ConfigParser import SafeConfigParser
from tempfile import NamedTemporaryFile
import psutil
import sys, re, getopt, itertools, warnings, string, subprocess, os.path, math, tempfile, shutil, numpy, pandas
def main(args):
start_time = datetime.now()
# State input in variables
input_ = read_options(args)
version = '1.2.0'
# Redirect std error when run on webserver
webserver_err_redirection(input_.webserver)
# Check input file paths
species = define_species(input_.species)
peptide_length = extract_peptide_length(input_.peptide_length)
paths = check_input_paths(input_, peptide_length, species)
tmp_dir = create_tmp_dir()
www_tmp_dir = create_webserver_tmp_dir(input_.webserver)
# Read in data
print_ifnot_webserver('\nReading in data', input_.webserver)
expression = build_expression(input_.expression_file, input_.webserver, input_.expression_type, species)
proteome_reference, sequence_count = build_proteome_reference(paths.proteome_ref_file, input_.webserver, species)
genome_reference = build_genome_reference(paths.genome_ref_file, input_.webserver, species)
cancer_genes = build_cancer_genes(paths.cosmic_file, input_.webserver)
"""
VEP: Ensembls Variant effect predictor
Detecting vcf file input, extracting allele frequencies and running VEP
"""
start_time_vep = datetime.now()
print_ifnot_webserver('\nVEP: Starting process for running the Ensembl Variant Effect Predictor', input_.webserver)
variant_caller = detect_variant_caller(input_.vcf_file, input_.webserver)
vcf_file = liftover_hg19(input_.liftover, input_.webserver, input_.vcf_file, input_.keep_temp, input_.outdir, input_.prefix, tmp_dir, input_.config)
vcf_sorted_file = create_vep_compatible_vcf(vcf_file, input_.webserver, input_.keep_temp, input_.outdir, input_.prefix, tmp_dir, input_.liftover)
allele_fractions = extract_allele_frequency(vcf_sorted_file, input_.webserver, variant_caller)
vep_file = run_vep(vcf_sorted_file, input_.webserver, tmp_dir, paths.vep_path, paths.vep_dir, input_.keep_temp, input_.prefix, input_.outdir, input_.assembly, input_.fork, species)
vep_info, vep_counters, transcript_info, protein_positions = build_vep_info(vep_file, input_.webserver)
end_time_vep = datetime.now()
"""
MuPeX: Mutant peptide extraction
Extracting user defined peptides lengths around missense variant mutations, indels and frameshifts
"""
start_time_mupex = datetime.now()
print_ifnot_webserver('\nMuPeX: Starting mutant peptide extraction', input_.webserver)
# Extract reference peptides
reference_peptides, reference_peptide_counters, reference_peptide_file_names = reference_peptide_extraction(proteome_reference, peptide_length, tmp_dir, input_.webserver, input_.keep_temp, input_.prefix, input_.outdir, input_.config)
# extract mutant peptides
peptide_info, peptide_counters, fasta_printout, pepmatch_file_names = peptide_extraction(peptide_length, vep_info, proteome_reference, genome_reference, reference_peptides, reference_peptide_file_names, input_.fasta_file_name, paths.peptide_match, tmp_dir, input_.webserver, input_.print_mismatch, input_.keep_temp, input_.prefix, input_.outdir, input_.num_mismatches)
# print fasta file
fasta_file = write_fasta (tmp_dir, fasta_printout, input_.webserver)
end_time_mupex = datetime.now()
"""
MuPeI: Mutant peptide Informer
Information from each mutation is annotated together with the mutant and normal peptides in the file output
"""
start_time_mupei = datetime.now()
print_ifnot_webserver('\nMuPeI: Starting mutant peptide informer', input_.webserver)
# run netMHCpan
unique_mutant_peptide_count, peptide_file = write_peptide_file(peptide_info, tmp_dir, input_.webserver, input_.keep_temp, input_.prefix, input_.outdir)
netMHCpan_runtime, unique_alleles, netMHC_EL_file, netMHC_BA_file = run_netMHCpan(input_.HLA_alleles, paths.netMHC, peptide_file, tmp_dir, input_.webserver, input_.keep_temp, input_.prefix, input_.outdir, input_.netmhc_anal)
net_mhc_BA = build_netMHC(netMHC_BA_file, input_.webserver, 'YES') if not netMHC_BA_file == None else None
net_mhc_EL = build_netMHC(netMHC_EL_file, input_.webserver, 'NO')
# write files
output_file = write_output_file(peptide_info, expression, net_mhc_BA, net_mhc_EL, unique_alleles, cancer_genes, tmp_dir, input_.webserver, input_.print_mismatch, allele_fractions, input_.expression_type, transcript_info, reference_peptides, proteome_reference, protein_positions, version)
log_file = write_log_file(sys.argv, peptide_length, sequence_count, reference_peptide_counters, vep_counters, peptide_counters, start_time_mupex, start_time_mupei, start_time, end_time_mupex, input_.HLA_alleles, netMHCpan_runtime, unique_mutant_peptide_count, unique_alleles, tmp_dir, input_.webserver, version)
# clean up
move_output_files(input_.outdir, log_file, input_.logfile, fasta_file, input_.fasta_file_name, output_file, input_.output, input_.webserver, www_tmp_dir)
clean_up(tmp_dir)
webserver_print_output(input_.webserver, www_tmp_dir, input_.output, input_.logfile, input_.fasta_file_name)
"""
CHECK FILE PATHS
"""
def check_input_paths(input_, peptide_lengths, species):
file_names = defaultdict(dict) # empty dictionary
category_list, id_list = create_lits_for_path_checkup(peptide_lengths)
# parse files stated in config file
for category, ID in izip(category_list, id_list):
file_path = config_parse(input_.config, category, ID)
check_path(file_path)
file_names[ID] = file_path
# Exit program if genome or proteome reference is not stated
if file_names['cDNA'] == None:
usage(); sys.exit('cDNA reference file is missing!')
if file_names['pep'] == None:
usage(); sys.exit('Proteome reference file is missing!')
if not input_.expression_file == None:
check_path(input_.expression_file)
check_file_size(input_.webserver, input_.expression_file, 'expression file')
check_vcf_file(input_.vcf_file, input_.liftover, species, input_.webserver)
check_netMHC_path(file_names['MHC'])
check_path(input_.outdir)
# Create and fill named tuple
Paths = namedtuple('files', ['gene_symbol_file', 'cosmic_file', 'genome_ref_file', 'proteome_ref_file', 'netMHC', 'peptide_match', 'vep_path', 'vep_dir'])
paths = Paths(file_names['symbol'], file_names['cosmic'], file_names['cDNA'], file_names['pep'], file_names['MHC'], file_names['PM'], file_names['VEP'], file_names['VEPdir'])
return paths
def create_lits_for_path_checkup(peptide_lengths):
for length in peptide_lengths:
category_list = ['netMHC','PeptideMatch', 'EnsemblVEP', 'EnsemblVEP', 'References', 'References', 'References']
id_list = ['MHC', 'PM', 'VEP', 'VEPdir', 'cosmic', 'cDNA', 'pep']
category_list.append('References')
id_list.append('pep' + str(length))
return category_list, id_list
def config_parse(config_file, category, ID):
# check if config.ini file exists
if os.path.exists(config_file) == False :
usage(); sys.exit('ERROR: Path to OR config.ini does not exist!\nERROR: Use -c option to specify path/to/config.ini file\n')
# parse config file
config = SafeConfigParser()
config.read(config_file)
path = config.get(category, ID) if config.has_option(category, ID) else None
return path
def check_path(path):
if not path == None:
if os.path.exists(path) == False:
usage(); sys.exit('ERROR: {} path or file does not exist\n'.format(path))
def check_vcf_file(vcf_file, liftover, species, webserver):
check_path(vcf_file)
# Exit program if file size are exceeded
check_file_size(webserver, vcf_file, 'VCF file')
with open(vcf_file) as f:
first_line = f.readline()
if not first_line.startswith('##fileformat=VCF'):
usage(); sys.exit('ERROR: {} file is not a VCF file\n'.format(vcf_file))
for line in f.readlines():
if not webserver == None:
if species == 'human':
if '##reference' in line:
if 'GRCh37' in line or 'hg19' in line or 'HG19' in line:
if liftover == None and species.assembly == "GRCh38":
usage(); sys.exit('ERROR: The VCF file is aligned to HG19 / GRCh37\nINFO: {}\nINFO: Please run NGS analysis aligning to GRCh38, use the hg19 liftover option (-g/--hg19), or the GRCh37 prediction option (-a/ --assembly GRCh37)\n'.format(line.strip()))
else :
continue
if '#CHROM' in line:
break
elif not line.startswith('##'):
usage(); sys.exit('ERROR: {} file is not a VCF file, #CHROM header is missing\n'.format(vcf_file))
def check_netMHC_path(netMHC_path):
if 'netH2pan' in netMHC_path:
print '\tMouse specific MHC binding predictor netH2pan used'
elif 'netMHCpan' in netMHC_path:
if not '4.0' in netMHC_path:
usage(); sys.exit('ERROR:\tnetMHCpan version 4.0 not stated in path {}\n\tOnly this version is supported'.format(netMHC_path))
else:
usage(); sys.exit('ERROR:\tnetMHCpan / netH2pan not stated in path {} \n\t\tCheck the correct path to the netXpan binding predictor is annotated in the config.ini'.format(netMHC_path))
def check_file_size(webserver, input_file_path, file_tag):
if not webserver == None:
if os.path.getsize(input_file_path) > 20000000 :
sys.exit('STOP: The input {} size exceeds the limit of 20M\n\tPlease check your file\n\tIf correct use the command-line tool instead or contact us: [email protected] or [email protected]'.format(file_tag))
def create_tmp_dir():
tmp_dir = tempfile.mkdtemp(prefix = 'MuPeXI_')
os.system('chmod -R a+rwx {}'.format(tmp_dir))
return tmp_dir
def print_ifnot_webserver(string, webserver):
if webserver == None :
print(string)
def create_webserver_tmp_dir(webserver):
if not webserver == None :
www_tmp_dir = tempfile.mkdtemp(prefix = 'MuPeXI_', dir='/usr/opt/www/pub/CBS/services/MuPeXI-1.1/tmp')
else:
www_tmp_dir = None
return www_tmp_dir
def webserver_err_redirection(webserver):
if not webserver == None:
sys.stderr = sys.stdout
def print_mem_usage():
# total memory usage
process = psutil.Process(os.getpid())
process_mb = float(process.memory_info().rss / 1000000)
print 'Total mem usage: {} MB'.format(process_mb)
"""
READ IN DATA
"""
def build_proteome_reference(proteome_ref_file, webserver, species):
print_ifnot_webserver('\tCreating proteome reference dictionary', webserver)
proteome_reference = defaultdict(dict) # empty dictionary
sequence_count = 0 # sequence count
with open(proteome_ref_file) as f:
for line in f.readlines():
if line.startswith('>'): # fasta header (>)
# test species compatibility
if not species.gene_id_prefix in line:
usage(); sys.exit('ERROR: species prefix {} for {} not found in proteome reference file\nINFO: use --species option if another species than {} is used'.format(species.gene_id_prefix, species.species, species.species))
# Save gene and transcript Ensembl ID (re = regular expression)
geneID = re.search(r'gene:({}\d+)'.format(species.gene_id_prefix), line).group(1).strip()
transID = re.search(r'transcript:({}\d+)'.format(species.trans_id_prefix), line).group(1).strip()
# Insert gene and transcript ID in directory, assign empty value
proteome_reference[geneID][transID] = ""
sequence_count += 1
else:
# Assign amino acid sequence as value in directory (the following lines until next header)
proteome_reference[geneID][transID] += line.strip()
return proteome_reference, sequence_count
def build_genome_reference(genome_ref_file, webserver, species):
print_ifnot_webserver('\tCreating genome reference dictionary', webserver)
genome_reference = defaultdict(dict) # empty dictionary
with open(genome_ref_file) as f:
for line in f.readlines():
if line.startswith('>'): # fasta header (>)
# test species compatibility
if not species.gene_id_prefix in line:
usage(); sys.exit('ERROR: species prefix {} for {} not found in cDNA reference file\nINFO: use --species option if another species than {} is used'.format(species.gene_id_prefix, species.species, species.species))
# Save gene and transcript Ensembl ID (re = regular expression)
geneID = re.search(r'gene:({}\d+)'.format(species.gene_id_prefix), line).group(1).strip()
transID = re.search(r'>({}\d+)'.format(species.trans_id_prefix), line).group(1).strip()
# Insert gene and transcript ID in directory, assign empty value
genome_reference[geneID][transID] = ""
else:
# Assign amino acid sequence as value in directory (the following lines until next header)
genome_reference[geneID][transID] += line.strip()
return genome_reference
def build_expression(expression_file, webserver, expression_type, species):
if not expression_file == None :
print_ifnot_webserver('\tCreating expression file dictionary', webserver)
expression = defaultdict(dict) # empty dictionary
with open(expression_file) as f:
for line in f.readlines():
line = line.split()
if not line[0] == 'target_id':
check_expression_file_type(expression_type, line, species)
# save line information
if '.' in line[0] : # example: ENST00000415118.3
ensembl_id = line[0].split('.')[0]
else: # example: ENST00000415118
ensembl_id = line[0]
mean = line[1]
# fill dictionary
expression[ensembl_id] = mean
else :
expression = None
return expression
def define_species(species):
if species == 'human' :
trans_id_prefix = 'ENST'
gene_id_prefix = 'ENSG'
assembly = 'GRCh38'
species = 'homo_sapiens'
elif species == 'mouse' :
trans_id_prefix = 'ENSMUST'
gene_id_prefix = 'ENSMUSG'
assembly = 'GRCm38'
species = 'mus_musculus'
elif species == 'mouse_balbc' :
trans_id_prefix = 'MGP_BALBcJ_T'
gene_id_prefix = 'MGP_BALBcJ_G'
assembly = 'BALB_cJ_v1'
species = 'mus_musculus_balbcj'
elif species == 'mouse_black6' :
trans_id_prefix = 'MGP_C57BL6NJ_T'
gene_id_prefix = 'MGP_C57BL6NJ_G'
assembly = 'C57BL_6NJ_v1'
species = 'mus_musculus_c57bl6nj'
else :
usage(); sys.exit('ERROR:\tSpecies {} not recognized \n'.format(species))
Species = namedtuple('species', ['gene_id_prefix', 'trans_id_prefix', 'assembly', 'species'])
species = Species(gene_id_prefix, trans_id_prefix, assembly, species)
return species
def check_expression_file_type(expression_type, line, species):
if expression_type == 'gene' :
if species.trans_id_prefix in line[0]:
usage(); sys.exit('ERROR:\tEnsembl transcript id detected: {}\n\tWhile expression type option "gene" was used\n'.format(line[0]))
if expression_type == 'transcript' :
if species.gene_id_prefix in line[0]:
usage(); sys.exit('ERROR:\tEnsembl gene id detected: {}\n\tWhile expression type option "transcript" was used\n'.format(line[0]))
def build_cancer_genes(cosmic_file, webserver):
if not cosmic_file == None:
print_ifnot_webserver('\tCreating cancer genes list', webserver)
cancer_genes = set()
with open(cosmic_file) as f:
for line in f.readlines():
if not line.startswith('Gene Symbol'):
gene_symbol = line.split()[0].strip()
cancer_genes.add(gene_symbol)
else:
cancer_genes = None
return cancer_genes
def extract_peptide_length(peptide_length):
peptide_length_list = list()
if isinstance( peptide_length, int ):
peptide_length_list.append(peptide_length)
else:
if '-' in peptide_length:
length_range = map(int,peptide_length.split('-'))
assert length_range[1] > length_range[0], 'peptide length range should be stated from lowest to highest. your input: {}'.format(peptide_length)
peptide_length_list = range(length_range[0], length_range[1] + 1)
elif ',' in peptide_length:
peptide_length_list = map(int, peptide_length.split(','))
else:
peptide_length_list.append(int(peptide_length))
return peptide_length_list
"""
VEP
"""
def detect_variant_caller(vcf_file, webserver):
print_ifnot_webserver('\tDetecting variant caller', webserver)
with open(vcf_file) as f:
for line in f.readlines():
if 'ID=MuTect2,' in line:
variant_caller = 'MuTect2'
print_ifnot_webserver('\t\tMuTect2', webserver)
break
if 'ID=MuTect,' in line:
variant_caller = 'MuTect'
print_ifnot_webserver('\t\tMuTect', webserver)
break
elif not line.startswith('##'):
variant_caller = None
print_ifnot_webserver('\t\tVariant caller not detected in VCF file.\n\t\tNOTE:\tGenomic allele frequency is only taken into account\n\t\t\twith variant calls from MuTect or MuTect2!', webserver)
break
return variant_caller
def liftover_hg19(liftover, webserver, vcf_file, keep_tmp, outdir, file_prefix, tmp_dir, config_file):
if not liftover == None:
print_ifnot_webserver('\tPerforming Liftover', webserver)
chain_file = config_parse(config_file, 'LiftOver', 'chain')
fasta_file = config_parse(config_file, 'LiftOver', 'fasta')
picard_path = config_parse(config_file, 'LiftOver', 'picard')
java8 = config_parse(config_file, 'LiftOver', 'java8')
check_path(chain_file)
check_path(fasta_file)
vcf_liftover_file = NamedTemporaryFile(delete = False, dir = tmp_dir, suffix = '.vcf')
rejected_records_file = NamedTemporaryFile(delete = False, dir = tmp_dir, suffix = '.vcf')
# Run picard tools lift-over - only on web-server.
p1 = subprocess.Popen([java8, '-jar', '{}/picard.jar'.format(picard_path), 'LiftoverVcf',
'I={}'.format(vcf_file),
'O={}'.format(vcf_liftover_file.name),
'CHAIN={}'.format(chain_file),
'REJECT={}'.format(rejected_records_file.name),
'REFERENCE_SEQUENCE={}'.format(fasta_file)],
stdout = subprocess.PIPE,
stderr = subprocess.PIPE)
p1.communicate()
vcf_liftover_file.close()
keep_temp_file(keep_tmp, 'vcf', vcf_liftover_file.name, file_prefix, outdir, None, 'vcf_liftover')
keep_temp_file(keep_tmp, 'vcf', rejected_records_file.name, file_prefix, outdir, None, 'rejected_records_liftover')
vcf_final_file = vcf_liftover_file
else :
vcf_final_file = vcf_file
return vcf_final_file
def create_vep_compatible_vcf(vcf_file, webserver, keep_tmp, outdir, file_prefix, tmp_dir, liftover):
print_ifnot_webserver('\tChange VCF to the VEP compatible', webserver)
# remove chr and 0 so only integers are left, (chromosome: 1, 2, 3 instaed og chr01, chr02, chr03)
# only PASS lines are used
vcf_file_name = vcf_file if liftover == None else vcf_file.name
vcf_sorted_file = NamedTemporaryFile(delete = False, dir = tmp_dir)
p1 = subprocess.Popen(['awk', '{gsub(/^chr/,"");gsub(/^0/,"");print}', vcf_file_name], stdout = subprocess.PIPE)
p2 = subprocess.Popen(['grep', '-E', '#|PASS'], stdin = p1.stdout, stdout = vcf_sorted_file)
p2.communicate()
vcf_sorted_file.close()
keep_temp_file(keep_tmp, 'vcf', vcf_sorted_file.name, file_prefix, outdir, None, 'vep_compatible_vcf')
return vcf_sorted_file
def extract_allele_frequency(vcf_sorted_file, webserver, variant_caller):
print_ifnot_webserver('\tExtracting allele frequencies', webserver)
allele_fractions = defaultdict(dict)
if not variant_caller in ('MuTect','MuTect2'):
allele_fractions = None # no variant caller detected
else:
with open(vcf_sorted_file.name) as f:
for line in f.readlines():
if line.startswith('#'):
continue
columns = line.split('\t')
chromosome = columns[0].strip()
genomic_position = columns[1].strip()
reference_allele = columns[3].strip()
altered_allele = columns[4].strip()
format_fields = columns[8].strip().split(':')
if not len(reference_allele) == len(altered_allele):
altered_allele = altered_allele[1:] if len(reference_allele) < len(altered_allele) else altered_allele
altered_allele = '-' if len(reference_allele) > len(altered_allele) else altered_allele
if variant_caller == 'MuTect':
allele_fraction = columns[9].split(':')[format_fields.index('FA')].strip() # GT:AD:BQ:DP:FA
elif variant_caller == 'MuTect2':
allele_fraction = columns[9].split(':')[format_fields.index('AF')].strip() # GT:AD:AF:ALT_F1R2:ALT_F2R1:FOXOG:QSS:REF_F1R2:REF_F2R1
ID = '{chromosome}_{genomic_position}_{altered_allele}'.format(
chromosome = chromosome,
genomic_position = genomic_position if not altered_allele == '-' else int(genomic_position) + 1,
altered_allele = altered_allele)
allele_fractions[ID] = allele_fraction
return allele_fractions
def run_vep(vcf_sorted_file, webserver, tmp_dir, vep_path, vep_dir, keep_tmp, file_prefix, outdir, input_assembly, fork, species):
print_ifnot_webserver('\tRunning VEP', webserver)
vep_file = NamedTemporaryFile(delete = False, dir = tmp_dir)
assembly = species.assembly if input_assembly == None else input_assembly
popen_args = [
vep_path,
'-fork', str(fork),
'--offline',
'--quiet',
'--assembly', assembly,
'--species', species.species,
'--dir', vep_dir,
'-i', vcf_sorted_file.name,
'--force_overwrite',
'--symbol', # print gene symbol in output
'-o', vep_file.name]
p1 = subprocess.Popen(popen_args,
stdout = subprocess.PIPE,
stderr = subprocess.PIPE)
output, error = p1.communicate()
vep_file.close()
# Test if VEP file is empty
if os.stat(vep_file.name).st_size == 0 :
sys.exit('ERROR: VEP output file empty\nVEP {}'.format(error))
keep_temp_file(keep_tmp, 'vep', vep_file.name, file_prefix, outdir, None, 'vep')
return vep_file
def build_vep_info(vep_file, webserver):
print_ifnot_webserver('\tCreating mutation information dictionary', webserver)
vep_info = [] # empty list
# Creating named tuple
Mutation_Info = namedtuple('mutation_info', ['gene_id', 'trans_id', 'mutation_consequence','chr', 'pos', 'cdna_pos', 'prot_pos', 'prot_pos_to', 'aa_normal', 'aa_mut', 'codon_normal', 'codon_mut', 'alt_allele', 'symbol'])
transcript_info = defaultdict(dict)
protein_positions = defaultdict(lambda: defaultdict(dict))
non_used_mutation_count, misssense_variant_count, inframe_insertion_count, inframe_deletion_count, frameshift_variant_count = 0, 0, 0 ,0, 0
with open(vep_file.name) as f:
for line in f.readlines():
if line.startswith('#'): # skip lines starting with #
continue
# Go to the next line if it is not a missense variant mutations
mutation_consequence = ['missense_variant', 'inframe_insertion', 'inframe_deletion', 'frameshift_variant']
if not any(wanted_consequence in line for wanted_consequence in mutation_consequence) :
non_used_mutation_count += 1
continue
if 'stop' in line:
continue
line = line.split('\t')
# save relevant information from line
mutation_consequence = line[6].split(',')[0].strip()
chr_, genome_pos = line[1].split(':')
alt_allele = line[2].strip()
geneID = line[3].strip()
transID = line[4].strip()
prot_pos = line[9].strip()
cdna_pos = line[7].strip()
symbol = re.search(r'SYMBOL=(\d*\w*\d*\w*\d*\w*)', line[13]).group(1).strip() if not re.search(r'SYMBOL', line[13]) == None else '-'
aa_normal, aa_mutation = line[10].split('/')
codon_normal, codon_mut = line[11].split('/')
if '-' in line[9] :
prot_pos, prot_pos_to = line[9].split('-')
else :
prot_pos, prot_pos_to = line[9].strip(), None
mutation_id_vep = '{}_{}_{}/{}'.format(chr_, genome_pos, aa_normal, aa_mutation)
# Generate dict of dicts (dependent on both mutation ID and gene ID)
# then set the default value of the key to be a list and append the transcript id
transcript_info[mutation_id_vep].setdefault(geneID,[]).append(transID)
# ad protein position
protein_positions[mutation_id_vep][geneID][transID] = prot_pos
# append information from the line to the list of named tuples - fill tuple
vep_info.append(Mutation_Info(geneID, transID, mutation_consequence, chr_, genome_pos, cdna_pos, int(prot_pos), prot_pos_to, aa_normal, aa_mutation, codon_normal, codon_mut, alt_allele, symbol))
# count independent mutation mutation consequences
if mutation_consequence == 'missense_variant' :
misssense_variant_count += 1
if mutation_consequence == 'inframe_insertion' :
inframe_insertion_count += 1
if mutation_consequence == 'inframe_deletion' :
inframe_deletion_count += 1
if mutation_consequence == 'frameshift_variant' :
frameshift_variant_count += 1
if vep_info == [] :
sys.exit('\nNO RELEVANT MUTATIONS (missense variant, inframe insertion / deletion or frameshift variant) found in VEP file.\nMuPeXI run stopped\nPrint temporary files to check if this is correct (option -t)\n')
#Count unique gene and transcript IDs
gene_IDs, transcript_IDs = set(), set()
for mutation in vep_info:
gene_IDs.add(mutation.gene_id)
transcript_IDs.add(mutation.trans_id)
gene_count, transcript_Count = len(gene_IDs), len(transcript_IDs)
# Create and fill counter named tuple
VEPCounters = namedtuple('vep_counters', ['non_used_mutation_count', 'misssense_variant_count', 'gene_count', 'transcript_Count', 'inframe_insertion_count', 'inframe_deletion_count', 'frameshift_variant_count'])
vep_counters = VEPCounters(non_used_mutation_count, misssense_variant_count, gene_count, transcript_Count, inframe_insertion_count, inframe_deletion_count, frameshift_variant_count)
return vep_info, vep_counters, transcript_info, protein_positions
"""
MuPeX
"""
def reference_peptide_extraction(proteome_reference, peptide_length, tmp_dir, webserver, keep_tmp, file_prefix, outdir, config_file):
print_ifnot_webserver('\tExtracting all possible peptides from reference', webserver)
reference_peptides = set()
reference_peptide_count = 0
reference_peptide_file_names = defaultdict(dict) # empty dictionary
# loop trough the proteome reference and chop up in all peptides
for length in peptide_length:
# check if peptide references are stated in config file
reference_peptide_file_path = config_parse(config_file, 'References', 'pep' + str(length))
# Create peptide reference file if not stated in the config file
if not reference_peptide_file_path == None:
print_ifnot_webserver('\t\tPeptide reference file of {} aa are stated in config file'.format(length), webserver)
reference_peptide_file_names[length] = reference_peptide_file_path
with open(reference_peptide_file_path) as f:
for line in f.readlines():
reference_peptides.add(line.strip())
reference_peptide_count += 1
else:
reference_length_peptides = set()
print_ifnot_webserver('\t\tPeptides of {} aa are being extracted'.format(length), webserver)
reference_peptides_file = NamedTemporaryFile(delete = False, dir = tmp_dir)
for geneID in proteome_reference:
for transID in proteome_reference[geneID]:
aa_sequence = proteome_reference[geneID][transID]
peptide_list = chopchop(aa_sequence, length)
for pep in peptide_list:
if not len(pep) == length:
continue
if '*' in pep:
continue
if 'X' in pep:
continue
if 'U' in pep:
continue
reference_peptide_count += 1
reference_length_peptides.add(pep)
reference_peptides.add(pep)
reference_peptides_file.write('{}\n'.format('\n'.join(reference_length_peptides)))
reference_peptides_file.close()
reference_peptide_file_names[length] = reference_peptides_file
ReferencePetideCounters = namedtuple('reference_peptide_counters', ['total_peptide_count', 'unique_peptide_count'])
reference_peptide_counters = ReferencePetideCounters(reference_peptide_count, len(reference_peptides))
keep_temp_file(keep_tmp, 'txt', reference_peptide_file_names, file_prefix, outdir, peptide_length, 'reference_peptide')
return reference_peptides, reference_peptide_counters, reference_peptide_file_names
def chopchop(aaSeq, peptide_length):
peptides = []
for i in range(len(aaSeq)):
pep = aaSeq[i:i + peptide_length]
if len(pep) < peptide_length:
break
peptides.append(pep)
return peptides
def peptide_extraction(peptide_lengths, vep_info, proteome_reference, genome_reference, reference_peptides, reference_peptide_file_names, fasta_file_name, peptide_match, tmp_dir, webserver, print_mismatch, keep_tmp, file_prefix, outdir, num_mismatches):
print_ifnot_webserver('\tPeptide extraction begun', webserver)
peptide_count, normal_match_count, removal_count = 0, 0, 0
peptide_info = defaultdict(dict) # empty dictionary
fasta_printout = defaultdict(dict) if not fasta_file_name == None else None
pepmatch_file_names = defaultdict(dict) # empty dictionary
for p_length in peptide_lengths:
mutated_peptides_missing_normal = set()
for mutation_info in vep_info:
# create mutation counters
intermediate_peptide_counters = {'mutation_peptide_count': 0, 'mutation_normal_match_count': 0, 'peptide_removal_count': 0}
# extract sequence
peptide_sequence_info = mutation_sequence_creation(mutation_info, proteome_reference, genome_reference, p_length)
if not peptide_sequence_info == None :
if not fasta_printout == None:
fasta_printout = long_peptide_fasta_creation(peptide_sequence_info, mutation_info, fasta_printout)
normpeps, mutpeps = chopchop(peptide_sequence_info.chop_normal_sequence, p_length), chopchop(peptide_sequence_info.mutation_sequence, p_length)
peptide_mutation_position = peptide_mutation_position_annotation(mutpeps, peptide_sequence_info.mutation_position, p_length)
peptide_info, intermediate_peptide_counters = peptide_selection(normpeps, mutpeps, peptide_mutation_position, intermediate_peptide_counters, peptide_sequence_info, peptide_info, mutation_info, p_length, reference_peptides)
mutated_peptides_missing_normal = normal_peptide_identification(peptide_info, mutated_peptides_missing_normal, mutpeps, mutation_info)
# Accumulate counters
peptide_count += intermediate_peptide_counters['mutation_peptide_count']
normal_match_count += intermediate_peptide_counters['mutation_normal_match_count']
removal_count += intermediate_peptide_counters['peptide_removal_count']
peptide_info, pepmatch_file_names = normal_peptide_correction(mutated_peptides_missing_normal, mutation_info, p_length, reference_peptide_file_names, peptide_info, peptide_match, tmp_dir, pepmatch_file_names, webserver, print_mismatch, num_mismatches)
# Create and fill counter named-tuple
PeptideCounters = namedtuple('peptide_counters', ['peptide_count', 'normal_match_count', 'removal_count'])
peptide_counters = PeptideCounters(peptide_count, normal_match_count, removal_count)
keep_temp_file(keep_tmp, 'txt', pepmatch_file_names, file_prefix, outdir, peptide_lengths, 'pepmatch')
return peptide_info, peptide_counters, fasta_printout, pepmatch_file_names
# peptide_extraction
def mutation_sequence_creation(mutation_info, proteome_reference, genome_reference, peptide_length):
# Create empty named tuple
PeptideSequenceInfo = namedtuple('peptide_sequence_info', ['chop_normal_sequence', 'mutation_sequence', 'normal_sequence','mutation_position', 'consequence'])
if mutation_info.mutation_consequence == 'missense_variant' :
peptide_sequence_info = missense_variant_peptide(proteome_reference, mutation_info, peptide_length, PeptideSequenceInfo)
elif mutation_info.mutation_consequence == 'inframe_insertion' :
peptide_sequence_info = insertion_peptide(proteome_reference, mutation_info, peptide_length, PeptideSequenceInfo)
elif mutation_info.mutation_consequence == 'inframe_deletion' :
peptide_sequence_info = deletion_peptide(proteome_reference, mutation_info, peptide_length, PeptideSequenceInfo)
elif mutation_info.mutation_consequence == 'frameshift_variant' :
peptide_sequence_info = frame_shift_peptide(genome_reference, proteome_reference, mutation_info, peptide_length, PeptideSequenceInfo)
else :
peptide_sequence_info = None
return peptide_sequence_info
# peptide_extraction > mutation_sequence_creation
def missense_variant_peptide(proteome_reference, mutation_info, peptide_length, PeptideSequenceInfo):
asserted_proteome = reference_assertion(proteome_reference, mutation_info, reference_type = 'proteome')
aaseq = asserted_proteome[0]
index = index_creator(mutation_info.prot_pos, peptide_length, aaseq, cdna_pos_start = None, index_type = 'amino_acid', codon = None, frame_type = None)
normal_sequence = aaseq[index.lower_index:index.higher_index]
mutation_sequence = normal_sequence[ :index.mutation_peptide_position - 1] + mutation_info.aa_mut + normal_sequence[index.mutation_peptide_position: ]
consequence = 'M'
# Return long peptide (created) and information
return PeptideSequenceInfo(normal_sequence, mutation_sequence, normal_sequence, index.mutation_peptide_position, consequence)
# peptide_extraction > mutation_sequence_creation
def insertion_peptide(proteome_reference, mutation_info, peptide_length, PeptideSequenceInfo):
asserted_proteome = reference_assertion(proteome_reference, mutation_info, reference_type = 'proteome')
aaseq = asserted_proteome[0]
index = index_creator(mutation_info.prot_pos, peptide_length, aaseq, cdna_pos_start = None, index_type = 'amino_acid', codon = None, frame_type = None)
normal_sequence = aaseq[index.lower_index:index.higher_index]
if mutation_info.aa_normal == '-':
mutation_sequence = normal_sequence[ :index.mutation_peptide_position] + mutation_info.aa_mut + normal_sequence[index.mutation_peptide_position: ]
else:
mutation_sequence = normal_sequence[ :index.mutation_peptide_position - 1] + mutation_info.aa_mut + normal_sequence[index.mutation_peptide_position: ]
chop_normal_sequence = '-' * len(mutation_sequence)
insertion_range = '{}:{}'.format(index.mutation_peptide_position, index.mutation_peptide_position + len(mutation_info.aa_mut))
consequence = 'I'
# Return long peptide (created) and information
return PeptideSequenceInfo(chop_normal_sequence, mutation_sequence, normal_sequence, insertion_range, consequence)
# peptide_extraction > mutation_sequence_creation
def deletion_peptide(proteome_reference, mutation_info, peptide_length, PeptideSequenceInfo):
asserted_proteome = reference_assertion(proteome_reference, mutation_info, reference_type = 'proteome')
aaseq = asserted_proteome[0]
index = index_creator(mutation_info.prot_pos, peptide_length, aaseq, cdna_pos_start = None, index_type = 'amino_acid', codon = None, frame_type = None)
normal_sequence = aaseq[index.lower_index:index.higher_index]
if mutation_info.aa_mut == '-':
mutation_sequence = normal_sequence[ :index.mutation_peptide_position - 1] + normal_sequence[index.mutation_peptide_position: ]
else:
mutation_sequence = normal_sequence[ :index.mutation_peptide_position - 1] + mutation_info.aa_mut + normal_sequence[index.mutation_peptide_position + len(mutation_info.aa_mut): ]
chop_normal_sequence = '-'*len(mutation_sequence)
consequence = 'D'
# Return long peptide (created) and information
return PeptideSequenceInfo(chop_normal_sequence, mutation_sequence, normal_sequence, index.mutation_peptide_position - 1, consequence)
# peptide_extraction > mutation_sequence_creation
def frame_shift_peptide(genome_reference, proteome_reference, mutation_info, peptide_length, PeptideSequenceInfo):
asserted_genome = reference_assertion(genome_reference, mutation_info, reference_type = 'genome')
asserted_proteome = reference_assertion(proteome_reference, mutation_info, reference_type = 'proteome')
seq = asserted_genome[0]
cdna_pos_start = asserted_genome[1]
cdna_pos_end = asserted_genome[2]
aaseq = asserted_proteome[0]
aa_index = index_creator(mutation_info.prot_pos, peptide_length, aaseq, cdna_pos_start = None, index_type = 'amino_acid', codon = None, frame_type = None)
normal_sequence = aaseq[aa_index.lower_index:aa_index.higher_index]
if mutation_info.codon_mut.islower() : # frame shift deletion
n_index = index_creator(mutation_info.prot_pos, peptide_length, aaseq, mutation_info.codon_normal, cdna_pos_start, index_type = 'nucleotide', frame_type = None)
mutation_sequence = seq[n_index.lower_index :n_index.cdna_codon_position] + mutation_info.codon_mut.lower() + seq[n_index.cdna_codon_position + 3: ]
else : # frame shift insertion
n_index = index_creator(mutation_info.prot_pos, peptide_length, aaseq, mutation_info.codon_mut, cdna_pos_start, index_type = 'nucleotide', frame_type = 'frameshift_insertion')
new_codon = re.search(r'([A-Z]+)', mutation_info.codon_mut).group(1).strip()
if mutation_info.codon_normal == '-':
mutation_sequence = seq[n_index.lower_index - 3:cdna_pos_start] + new_codon.lower() + seq[cdna_pos_end - 1: ]
else:
mutation_sequence = seq[n_index.lower_index :cdna_pos_start] + new_codon.lower() + seq[cdna_pos_end - 1: ]
detect_stop_codon(mutation_sequence, mutation_info)
# BIO PYTHON:
# ignore biopython warnings (as we intentionally create sequences not multiple by three)
with warnings.catch_warnings():
warnings.simplefilter('ignore', BiopythonWarning)
# When mutation sequence is obtained, translate the sequence using biopython
dna_sequence = Seq(mutation_sequence, generic_dna)
mutation_aaseq = str(dna_sequence.translate(to_stop = True))
chop_normal_sequence = '-'*len(mutation_aaseq)
consequence = 'F'
frameshift_range = '{}:{}'.format(aa_index.mutation_peptide_position, len(mutation_aaseq))
# Return long peptides and information
return PeptideSequenceInfo(chop_normal_sequence, mutation_aaseq, normal_sequence, frameshift_range, consequence)
# peptide_extraction > mutation_sequence_creation > frame_shift_peptide
def detect_stop_codon (mutation_sequence, mutation_info):
# check if the mutation generates a stop-codon
pos = 1
for nucleotide in mutation_sequence :
# find the mutation - annotated with lowercase
if nucleotide.islower() :
for i in [0, 1, 2] :
# i identify if codon is within the reading frame
codon_value = float(pos + i - 3) / 3
if codon_value.is_integer() :
codon = mutation_sequence[pos + i - 3 : pos + i]
# see if the codon is a stop codon
if codon.upper() in ['TAA','TAG','TGA']:
print '\t\tNOTE:\tFrameshift mutation {}/{} in {} is generating the stop codon {}\n\t\t\tNo peptides generated from this mutation'.format(mutation_info.aa_normal, mutation_info.aa_mut, mutation_info.trans_id, codon)
pos = pos + 1
# peptide_extraction
def long_peptide_fasta_creation (peptide_sequence_info, mutation_info, fasta_printout):
header = '>DTU|{trans_id}_{pos}|{cons}_{mut_change}'.format(cons = peptide_sequence_info.consequence,
pos = mutation_info.pos,
mut_change = mutation_info.aa_normal + str(peptide_sequence_info.mutation_position) + mutation_info.aa_mut,
trans_id = mutation_info.trans_id)
seq = peptide_sequence_info.mutation_sequence
fasta_printout[header] = seq
return fasta_printout
# peptide_extraction
def peptide_mutation_position_annotation(mutpeps, long_peptide_position, peptide_length):
peptide_mutation_positions = []
for i in range(len(mutpeps)):
if type(long_peptide_position) is int:
pep_mut_pos = long_peptide_position - i
else:
start = int(long_peptide_position.split(':')[0])
end = int(long_peptide_position.split(':')[1])
final_end = (end - i) if (end - i) < peptide_length else peptide_length
final_start = (start - i) if (start - i) > 0 else 1
pep_mut_pos = '{}:{}'.format(int(final_start),int(final_end))
peptide_mutation_positions.append(pep_mut_pos)
return peptide_mutation_positions
# peptide_extraction
def peptide_selection (normpeps, mutpeps, peptide_mutation_position, intermediate_peptide_counters, peptide_sequence_info, peptide_info, mutation_info, p_length, reference_peptides):
if len(peptide_sequence_info.mutation_sequence) < p_length:
print '\t\tNOTE:\tMutation peptide sequence {} length is smaller than defined peptide length {}'.format(peptide_sequence_info.mutation_sequence, p_length)
for normpep, mutpep, mutpos in izip(normpeps, mutpeps, peptide_mutation_position):
if '*' in normpep or '*' in mutpep : # removing peptides from pseudogenes including a *
intermediate_peptide_counters['peptide_removal_count'] += 1
continue
if 'X' in normpep or 'X' in mutpep:
intermediate_peptide_counters['peptide_removal_count'] += 1
continue
if 'U' in normpep or 'U' in mutpep: # removing peptides with U - non normal AA
intermediate_peptide_counters['peptide_removal_count'] += 1
continue
if mutpep in reference_peptides: # Counting peptides matching a 100 % normal - Not removing
intermediate_peptide_counters['mutation_normal_match_count'] += 1
intermediate_peptide_counters['mutation_peptide_count'] += 1
pep_match_info = None # empty variable
# fill dictionary
peptide_info[mutpep][normpep] = [mutation_info, peptide_sequence_info, mutpos, pep_match_info]
return peptide_info, intermediate_peptide_counters
# peptide_extraction
def normal_peptide_identification(peptide_info, mutated_peptides_missing_normal, mutpeps, mutation_info):
if not mutation_info.mutation_consequence == 'missense_variant':
for mutpep in mutpeps:
if mutpep in peptide_info: # check that mutated peptide is in the final dictionary of wanted peptides
mutated_peptides_missing_normal.add(mutpep)
return mutated_peptides_missing_normal
# peptide_extraction
def normal_peptide_correction(mutated_peptides_missing_normal, mutation_info, peptide_length, reference_peptide_file_names, peptide_info, peptide_match, tmp_dir, pepmatch_file_names, webserver, print_mismatch, num_mismatches):
# write input file
mutpeps_file = NamedTemporaryFile(delete = False, dir = tmp_dir)
mutpeps_file.write('{}\n'.format('\n'.join(mutated_peptides_missing_normal)))
mutpeps_file.close()
pepmatch_file = run_peptide_match(mutpeps_file, peptide_length, peptide_match, reference_peptide_file_names, mutation_info, tmp_dir, webserver, print_mismatch, num_mismatches)
pep_match = build_pepmatch(pepmatch_file, peptide_length, print_mismatch)
pepmatch_file_names[peptide_length] = pepmatch_file
# insert normal in peptide info
for mutated_peptide in pep_match:
assert mutated_peptide in peptide_info, 'Mutated peptide "{}" not stated in peptide_info data structure'.format(mutated_peptide)
for normal_peptide in peptide_info[mutated_peptide].keys():
# renaming normal key, thereby inserting the normal peptide
peptide_info[mutated_peptide][pep_match[mutated_peptide].normal_peptide] = peptide_info[mutated_peptide].pop(normal_peptide)
peptide_info[mutated_peptide][pep_match[mutated_peptide].normal_peptide][3] = pep_match[mutated_peptide]
return peptide_info, pepmatch_file_names
# peptide_extraction > normal_peptide_correction
def run_peptide_match(mutpeps_file, peptide_length, peptide_match, reference_peptide_file_names, mutation_info, tmp_dir, webserver, print_mismatch, num_mismatches):
reference_peptide_file = reference_peptide_file_names[peptide_length]
print_ifnot_webserver('\t\tRunning {} aa normal peptide match'.format(peptide_length), webserver)
reference_peptide_file_name = reference_peptide_file.name if not type(reference_peptide_file) == str else reference_peptide_file
pepmatch_file = NamedTemporaryFile(delete = False, dir = tmp_dir)
if not print_mismatch == None:
process_pepmatch = subprocess.Popen([peptide_match, '-mm', '-thr' , str(num_mismatches), mutpeps_file.name, reference_peptide_file_name], stdout = pepmatch_file)
else:
process_pepmatch = subprocess.Popen([peptide_match, '-thr' , str(num_mismatches), mutpeps_file.name, reference_peptide_file_name], stdout = pepmatch_file)
process_pepmatch.communicate() # now wait
pepmatch_file.close()
return pepmatch_file
# peptide_extraction > normal_peptide_correction
def build_pepmatch(pepmatch_file, peptide_length, print_mismatch):
pep_match = defaultdict(dict) # empty dictionary
with open(pepmatch_file.name) as f:
for line in f.readlines():
if re.search(r'^Hit\s', line):
line = [x.strip() for x in line.split()]
# save information
mutated_peptide = line[2]
normal_peptide = line[3]
mismatch_peptide = line[4] if not print_mismatch == None else '-' * len(normal_peptide)
mismatch = line[5] if print_mismatch == None else line[6]
elif re.search(r'^No Hit found\s', line):
line = [x.strip() for x in line.split()]
mutated_peptide = line[3]
normal_peptide = '-' * len(mutated_peptide)
mismatch_peptide = '-' * len(mutated_peptide)
mismatch = 5
else: