-
Notifications
You must be signed in to change notification settings - Fork 7
/
ScanNeo_utils.py
4667 lines (4478 loc) · 152 KB
/
ScanNeo_utils.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
__version__ = "2.1"
import argparse
import numpy as np
import vcf
import csv
import sys
import re
import math
import yaml
from collections import OrderedDict
from pathlib import Path
import subprocess
import os
import tempfile
import shutil
from collections import defaultdict
import configparser
def config_getter():
this_dir = os.path.dirname(os.path.realpath(__file__))
config_default = os.path.join(this_dir, "config.ini")
config = configparser.ConfigParser(os.environ)
config.read(config_default)
hg38_ref = config.get("fasta", "hg38")
hg19_ref = config.get("fasta", "hg19")
mm10_ref = config.get("fasta", "mm10")
mm39_ref = config.get("fasta", "mm39")
hg38_anno = config.get("annotation", "hg38")
hg19_anno = config.get("annotation", "hg19")
mm10_anno = config.get("annotation", "mm10")
mm39_anno = config.get("annotation", "mm39")
yara_index = config.get("yara", "index")
threads = config.get("yara", "threads")
return {
"hg38_ref": hg38_ref,
"hg19_ref": hg19_ref,
"mm10_ref": mm10_ref,
"mm39_ref": mm39_ref,
"hg38_anno": hg38_anno,
"hg19_anno": hg19_anno,
"mm10_anno": mm10_anno,
"mm39_anno": mm39_anno,
"yara_index": yara_index,
"threads": threads,
}
def is_insertion(ref, alt):
return len(alt) > len(ref)
def is_deletion(ref, alt):
return len(alt) < len(ref)
def simplify_indel_allele(ref, alt):
while len(ref) > 0 and len(alt) > 0 and ref[-1] == alt[-1]:
ref = ref[0:-1]
alt = alt[0:-1]
while len(ref) > 0 and len(alt) > 0 and ref[0] == alt[0]:
ref = ref[1:]
alt = alt[1:]
return ref, alt
def parse_csq_format(vcf_reader):
info_fields = vcf_reader.infos
if info_fields["CSQ"] is None:
sys.exit("Failed to extract format string from info description for tag (CSQ)")
else:
csq_header = info_fields["CSQ"]
format_pattern = re.compile("Format: (.*)")
match = format_pattern.search(csq_header.desc)
return match.group(1)
def resolve_alleles(entry):
alleles = {}
if entry.is_indel:
for alt in entry.ALT:
alt = str(alt)
if alt[0:1] != entry.REF[0:1]:
alleles[alt] = alt
elif alt[1:] == "":
alleles[alt] = "-"
else:
alleles[alt] = alt[1:]
elif "SVTYPE" in entry.INFO:
if (
entry.INFO["SVTYPE"] == "DEL" or entry.INFO["SVTYPE"] == "INS"
): # PyVCF bug TYW
for alt in entry.ALT:
alt = str(alt)
if alt[0:1] != entry.REF[0:1]:
alleles[alt] = alt
elif alt[1:] == "":
alleles[alt] = "-"
else:
alleles[alt] = alt[1:]
else:
for alt in entry.ALT:
alt = str(alt)
alleles[alt] = alt
return alleles
def parse_csq_entries_for_allele(csq_entries, csq_format, csq_allele):
csq_format_array = csq_format.split("|")
transcripts = []
for entry in csq_entries:
values = entry.split("|")
transcript = {}
for key, value in zip(csq_format_array, values):
transcript[key] = value
if transcript["Allele"] == csq_allele:
transcripts.append(transcript)
return transcripts
def resolve_consequence(consequence_string):
consequences = {
consequence.lower() for consequence in consequence_string.split("&")
}
if "start_lost" in consequences:
consequence = None
elif "frameshift_variant" in consequences:
consequence = "frameshift"
elif "missense_variant" in consequences:
consequence = "missense"
elif "inframe_insertion" in consequences:
consequence = "inframe_ins"
elif "inframe_deletion" in consequences:
consequence = "inframe_del"
else:
consequence = None
return consequence
def calculate_coverage(ref, var):
return ref + var
def calculate_vaf(ref, var):
return (var / (calculate_coverage(ref, var) + 0.00001)) * 100
def convert_vcf(args_input=sys.argv[1:]):
parser = argparse.ArgumentParser("convert_vcf")
parser.add_argument(
"input_file",
type=argparse.FileType("r"),
help="input VCF",
)
parser.add_argument(
"output_file", type=argparse.FileType("w"), help="output list of variants"
)
args = parser.parse_args(args_input)
vcf_reader = vcf.Reader(args.input_file)
if len(vcf_reader.samples) > 1:
sys.exit("ERROR: VCF file contains more than one sample")
output_headers = [
"chromosome_name",
"start",
"stop",
"reference",
"variant",
"gene_name",
"transcript_name",
"amino_acid_change",
"ensembl_gene_id",
"wildtype_amino_acid_sequence",
"downstream_amino_acid_sequence",
"variant_type",
"protein_position",
"index",
]
tsv_writer = csv.DictWriter(
args.output_file, delimiter="\t", fieldnames=output_headers
)
tsv_writer.writeheader()
csq_format = parse_csq_format(vcf_reader)
transcript_count = {}
for entry in vcf_reader:
chromosome = entry.CHROM
start = entry.affected_start
stop = entry.affected_end
reference = entry.REF
alts = entry.ALT
if len(vcf_reader.samples) == 1:
genotype = entry.genotype(vcf_reader.samples[0])
if genotype.gt_type is None or genotype.gt_type == 0:
# The genotype is uncalled or hom_ref
continue
alleles_dict = resolve_alleles(entry)
for alt in alts:
alt = str(alt)
if entry.is_indel:
if is_deletion(reference, alt):
bam_readcount_position = start + 1
(simplified_reference, simplified_alt) = simplify_indel_allele(
reference, alt
)
ref_base = reference[1:2]
var_base = "-" + simplified_reference
elif is_insertion(reference, alt):
bam_readcount_position = start
(simplified_reference, simplified_alt) = simplify_indel_allele(
reference, alt
)
ref_base = reference
var_base = "+" + simplified_alt
variant_type = "indels"
else:
bam_readcount_position = entry.POS
variant_type = "snvs"
ref_base = reference
var_base = alt
csq_allele = alleles_dict[alt]
transcripts = parse_csq_entries_for_allele(
entry.INFO["CSQ"], csq_format, csq_allele
)
for transcript in transcripts:
transcript_name = transcript["Feature"]
if transcript_name in transcript_count:
transcript_count[transcript_name] += 1
else:
transcript_count[transcript_name] = 1
consequence = resolve_consequence(transcript["Consequence"])
if consequence is None:
continue
elif consequence == "frameshift":
if transcript["DownstreamProtein"] == "":
continue
else:
amino_acid_change_position = transcript["Protein_position"]
else:
amino_acid_change_position = (
transcript["Protein_position"] + transcript["Amino_acids"]
)
gene_name = transcript["SYMBOL"]
index = f"{gene_name}_{transcript_name}_{transcript_count[transcript_name]}.{consequence}.{amino_acid_change_position}"
ensembl_gene_id = transcript["Gene"]
output_row = {
"chromosome_name": entry.CHROM,
"start": entry.affected_start,
"stop": entry.affected_end,
"reference": entry.REF,
"variant": alt,
"gene_name": gene_name,
"transcript_name": transcript_name,
"amino_acid_change": transcript["Amino_acids"],
"ensembl_gene_id": ensembl_gene_id,
"wildtype_amino_acid_sequence": transcript["WildtypeProtein"],
"downstream_amino_acid_sequence": transcript["DownstreamProtein"],
"variant_type": consequence,
"protein_position": transcript["Protein_position"],
"index": index,
}
if transcript["Amino_acids"]:
output_row["amino_acid_change"] = transcript["Amino_acids"]
else:
output_row["amino_acid_change"] = "NA"
tsv_writer.writerow(output_row)
args.input_file.close()
args.output_file.close()
###################################################################
# generate fasta functions
csv.field_size_limit(sys.maxsize)
def position_out_of_bounds(position, sequence):
return position > len(sequence) - 1
# This subroutine is a bit funky but it was designed that way to mirror
# distance_from_end to increase code readability from the caller's perspective
def distance_from_start(position, string):
return position
def distance_from_end(position, string):
return len(string) - 1 - position
def determine_peptide_sequence_length(
full_wildtype_sequence_length, peptide_sequence_length, line
):
actual_peptide_sequence_length = peptide_sequence_length
# If the wildtype sequence is shorter than the desired peptide sequence
# length we use the wildtype sequence length instead so that the extraction
# algorithm below works correctly
if full_wildtype_sequence_length < actual_peptide_sequence_length:
actual_peptide_sequence_length = full_wildtype_sequence_length
print(
"Wildtype sequence length is shorter than desired peptide sequence length at position ({}, {}, {}). Using wildtype sequence length ({}) instead.".format(
line["chromosome_name"],
line["start"],
line["stop"],
actual_peptide_sequence_length,
)
)
return actual_peptide_sequence_length
def determine_flanking_sequence_length(
full_wildtype_sequence_length, peptide_sequence_length, line
):
actual_peptide_sequence_length = determine_peptide_sequence_length(
full_wildtype_sequence_length, peptide_sequence_length, line
)
if actual_peptide_sequence_length % 2 == 0:
return (actual_peptide_sequence_length - 2) / 2
else:
return (actual_peptide_sequence_length - 1) / 2
def get_wildtype_subsequence(
position,
full_wildtype_sequence,
wildtype_amino_acid_length,
peptide_sequence_length,
line,
):
one_flanking_sequence_length = int(
determine_flanking_sequence_length(
len(full_wildtype_sequence), peptide_sequence_length, line
)
)
peptide_sequence_length = min(
2 * one_flanking_sequence_length + wildtype_amino_acid_length,
len(full_wildtype_sequence),
)
# We want to extract a subset from full_wildtype_sequence that is
# peptide_sequence_length long so that the position ends
# up in the middle of the extracted sequence.
# If the position is too far toward the beginning or end of
# full_wildtype_sequence there aren't enough amino acids on one side
# to achieve this.
if (
distance_from_start(position, full_wildtype_sequence)
< one_flanking_sequence_length
):
wildtype_subsequence = full_wildtype_sequence[:peptide_sequence_length]
mutation_position = position
elif (
distance_from_end(position, full_wildtype_sequence)
< one_flanking_sequence_length
):
start_position = len(full_wildtype_sequence) - peptide_sequence_length
wildtype_subsequence = full_wildtype_sequence[start_position:]
mutation_position = (
peptide_sequence_length
- distance_from_end(position, full_wildtype_sequence)
- 1
)
elif (
distance_from_start(position, full_wildtype_sequence)
>= one_flanking_sequence_length
and distance_from_end(position, full_wildtype_sequence)
>= one_flanking_sequence_length
):
start_position = position - one_flanking_sequence_length
end_position = start_position + peptide_sequence_length
wildtype_subsequence = full_wildtype_sequence[start_position:end_position]
mutation_position = one_flanking_sequence_length
else:
sys.exit(
"ERROR: Something went wrong during the retrieval of the wildtype sequence at position(%s, %s, %s)"
% line["chromsome_name"],
line["start"],
line["stop"],
)
return mutation_position, wildtype_subsequence
def get_frameshift_subsequences(
position, full_wildtype_sequence, peptide_sequence_length, line
):
one_flanking_sequence_length = determine_flanking_sequence_length(
len(full_wildtype_sequence), peptide_sequence_length, line
)
if position < one_flanking_sequence_length:
start_position = 0
else:
start_position = int(position - one_flanking_sequence_length)
wildtype_subsequence_stop_position = int(position + one_flanking_sequence_length)
mutation_subsequence_stop_position = int(position)
wildtype_subsequence = full_wildtype_sequence[
start_position:wildtype_subsequence_stop_position
]
mutation_start_subsequence = full_wildtype_sequence[
start_position:mutation_subsequence_stop_position
]
return start_position, wildtype_subsequence, mutation_start_subsequence
def combine_conflicting_variants(codon_changes):
codon = list(codon_changes[0].split("/")[0].lower())
modified_positions = []
for codon_change in codon_changes:
(old_codon, new_codon) = codon_change.split("/")
change_positions = [
i for i in range(len(old_codon)) if old_codon[i] != new_codon[i]
]
for position in change_positions:
if position in modified_positions:
print("Warning: position has already been modified")
codon[position] = new_codon[position].lower()
modified_positions.append(position)
return translate("".join(codon))
def generate_fasta(args_input=sys.argv[1:]):
parser = argparse.ArgumentParser("generate_fasta")
parser.add_argument(
"input_file",
type=argparse.FileType("r"),
help="input list of variants",
)
parser.add_argument(
"peptide_sequence_length", type=int, help="length of the peptide sequence"
)
parser.add_argument(
"epitope_length", type=int, help="length of subpeptides(epitopes) to predict"
)
parser.add_argument(
"output_file", type=argparse.FileType("w"), help="output FASTA file"
)
parser.add_argument(
"output_key_file", type=argparse.FileType("w"), help="output FASTA key file"
)
parser.add_argument(
"downstream_sequence_length",
type=int,
help="Cap to limit the downstream sequence length for frameshifts when creating the fasta file.",
)
args = parser.parse_args(args_input)
peptide_sequence_length = args.peptide_sequence_length
tsvin = csv.DictReader(args.input_file, delimiter="\t")
fasta_sequences = OrderedDict()
for line in tsvin:
variant_type = line["variant_type"]
full_wildtype_sequence = line["wildtype_amino_acid_sequence"]
if variant_type == "frameshift":
if (
line["amino_acid_change"] is not None
and line["amino_acid_change"].split("/")[0] == "-"
):
position = int(line["protein_position"].split("-", 1)[0])
else:
position = int(line["protein_position"].split("-", 1)[0]) - 1
elif variant_type == "missense" or variant_type == "inframe_ins":
wildtype_amino_acid, mutant_amino_acid = line["amino_acid_change"].split(
"/"
)
# deal with stop codon
if "*" in wildtype_amino_acid:
wildtype_amino_acid = wildtype_amino_acid.split("*")[0]
elif "X" in wildtype_amino_acid:
wildtype_amino_acid = wildtype_amino_acid.split("X")[0]
if "*" in mutant_amino_acid:
mutant_amino_acid = mutant_amino_acid.split("*")[0]
stop_codon_added = True
elif "X" in mutant_amino_acid:
mutant_amino_acid = mutant_amino_acid.split("X")[0]
stop_codon_added = True
else:
stop_codon_added = False
if wildtype_amino_acid == "-":
position = int(line["protein_position"].split("-", 1)[0])
wildtype_amino_acid_length = 0
else:
if "-" in line["protein_position"]:
position = int(line["protein_position"].split("-", 1)[0]) - 1
wildtype_amino_acid_length = len(wildtype_amino_acid)
else:
position = int(line["protein_position"]) - 1
wildtype_amino_acid_length = len(wildtype_amino_acid)
elif variant_type == "inframe_del":
variant_type = "inframe_del"
wildtype_amino_acid, mutant_amino_acid = line["amino_acid_change"].split(
"/"
)
# deal with stop codon
if "*" in wildtype_amino_acid:
wildtype_amino_acid = wildtype_amino_acid.split("*")[0]
elif "X" in wildtype_amino_acid:
wildtype_amino_acid = wildtype_amino_acid.split("X")[0]
if "*" in mutant_amino_acid:
mutant_amino_acid = mutant_amino_acid.split("*")[0]
stop_codon_added = True
elif "X" in mutant_amino_acid:
mutant_amino_acid = mutant_amino_acid.split("X")[0]
stop_codon_added = True
else:
stop_codon_added = False
position = int(line["protein_position"].split("-", 1)[0]) - 1
wildtype_amino_acid_length = len(wildtype_amino_acid)
if mutant_amino_acid == "-":
mutant_amino_acid = ""
else:
continue
if position_out_of_bounds(position, full_wildtype_sequence):
continue
if variant_type == "frameshift":
(
mutation_start_position,
wildtype_subsequence,
mutant_subsequence,
) = get_frameshift_subsequences(
position, full_wildtype_sequence, peptide_sequence_length, line
)
downstream_sequence = line["downstream_amino_acid_sequence"]
if (
args.downstream_sequence_length != 0
and len(downstream_sequence) > args.downstream_sequence_length
):
downstream_sequence = downstream_sequence[
0 : args.downstream_sequence_length
]
mutant_subsequence += downstream_sequence
else:
mutation_start_position, wildtype_subsequence = get_wildtype_subsequence(
position,
full_wildtype_sequence,
wildtype_amino_acid_length,
peptide_sequence_length,
line,
)
mutation_end_position = mutation_start_position + wildtype_amino_acid_length
if (
wildtype_amino_acid != "-"
and wildtype_amino_acid
!= wildtype_subsequence[mutation_start_position:mutation_end_position]
):
if line["amino_acid_change"].split("/")[0].count("*") > 1:
print(
"Warning: Amino acid change is not sane - contains multiple stops. Skipping entry {}".format(
line["index"]
)
)
continue
else:
print(
"Warning: There was a mismatch between the actual wildtype amino acid and the expected amino acid. Did you use the same reference build version for VEP that you used for creating the VCF?\n%s"
% line
)
continue
if stop_codon_added:
mutant_subsequence = (
wildtype_subsequence[:mutation_start_position] + mutant_amino_acid
)
else:
mutant_subsequence = (
wildtype_subsequence[:mutation_start_position]
+ mutant_amino_acid
+ wildtype_subsequence[mutation_end_position:]
)
if "*" in wildtype_subsequence or "*" in mutant_subsequence:
continue
if "X" in wildtype_subsequence or "X" in mutant_subsequence:
continue
if "U" in wildtype_subsequence or "U" in mutant_subsequence:
print(
"Warning. Sequence contains unsupported amino acid U. Skipping entry {}".format(
line["index"]
)
)
continue
if mutant_subsequence in wildtype_subsequence:
# This is not a novel peptide
continue
if (
len(wildtype_subsequence) < args.epitope_length
or len(mutant_subsequence) < args.epitope_length
):
continue
variant_id = line["index"]
for designation, subsequence in zip(
["WT", "MT"], [wildtype_subsequence, mutant_subsequence]
):
# for designation, subsequence in zip(['MT'], [mutant_subsequence]):
key = f"{designation}.{variant_id}"
if subsequence in fasta_sequences:
fasta_sequences[subsequence].append(key)
else:
fasta_sequences[subsequence] = [key]
count = 1
for (subsequence, keys) in list(fasta_sequences.items()):
args.output_file.writelines(">%s\n" % count)
args.output_file.writelines("%s\n" % subsequence)
yaml.dump({count: keys}, args.output_key_file, default_flow_style=False)
count += 1
args.input_file.close()
args.output_file.close()
args.output_key_file.close()
#############parse output###########
csv.field_size_limit(sys.maxsize)
def parse_input_tsv_file(input_tsv_file):
tsv_reader = csv.DictReader(input_tsv_file, delimiter="\t")
tsv_entries = {}
for line in tsv_reader:
tsv_entries[line["index"]] = line
return tsv_entries
def min_match_count(peptide_length):
return math.ceil(peptide_length / 2)
def determine_consecutive_matches_from_left(mt_epitope_seq, wt_epitope_seq):
consecutive_matches = 0
for a, b in zip(mt_epitope_seq, wt_epitope_seq):
if a == b:
consecutive_matches += 1
else:
break
return consecutive_matches
def determine_consecutive_matches_from_right(mt_epitope_seq, wt_epitope_seq):
consecutive_matches = 0
for a, b in zip(reversed(mt_epitope_seq), reversed(wt_epitope_seq)):
if a == b:
consecutive_matches += 1
else:
break
return consecutive_matches
def determine_total_matches(mt_epitope_seq, wt_epitope_seq):
matches = 0
for a, b in zip(mt_epitope_seq, wt_epitope_seq):
if a == b:
matches += 1
return matches
def find_mutation_position(wt_epitope_seq, mt_epitope_seq):
for i, (wt_aa, mt_aa) in enumerate(zip(wt_epitope_seq, mt_epitope_seq)):
if wt_aa != mt_aa:
return i + 1
return 0
def match_wildtype_and_mutant_entry_for_missense(
result, mt_position, wt_results, previous_result
):
# The WT epitope at the same position is the match
match_position = mt_position
mt_epitope_seq = result["mt_epitope_seq"]
wt_result = wt_results[match_position]
wt_epitope_seq = wt_result["wt_epitope_seq"]
total_matches = determine_total_matches(mt_epitope_seq, wt_epitope_seq)
if total_matches >= min_match_count(int(result["peptide_length"])):
result["wt_epitope_seq"] = wt_epitope_seq
result["wt_scores"] = wt_result["wt_scores"]
else:
result["wt_epitope_seq"] = "NA"
result["wt_scores"] = dict.fromkeys(list(result["mt_scores"].keys()), "NA")
if mt_epitope_seq == wt_epitope_seq:
result["mutation_position"] = "NA"
else:
if previous_result:
previous_mutation_position = previous_result["mutation_position"]
if previous_mutation_position == "NA":
result["mutation_position"] = find_mutation_position(
wt_epitope_seq, mt_epitope_seq
)
elif previous_mutation_position > 0:
result["mutation_position"] = previous_mutation_position - 1
else:
result["mutation_position"] = 0
else:
result["mutation_position"] = find_mutation_position(
wt_epitope_seq, mt_epitope_seq
)
def match_wildtype_and_mutant_entry_for_frameshift(
result, mt_position, wt_results, previous_result
):
# The WT epitope at the same position is the match
match_position = mt_position
# Since the MT sequence is longer than the WT sequence, not all MT epitopes have a match
if match_position not in wt_results:
result["wt_epitope_seq"] = "NA"
result["wt_scores"] = dict.fromkeys(list(result["mt_scores"].keys()), "NA")
if previous_result["mutation_position"] == "NA":
result["mutation_position"] = "NA"
elif previous_result["mutation_position"] > 0:
result["mutation_position"] = previous_result["mutation_position"] - 1
else:
result["mutation_position"] = 0
return
mt_epitope_seq = result["mt_epitope_seq"]
wt_result = wt_results[match_position]
wt_epitope_seq = wt_result["wt_epitope_seq"]
if mt_epitope_seq == wt_epitope_seq:
# The MT epitope does not overlap the frameshift mutation
result["wt_epitope_seq"] = wt_result["wt_epitope_seq"]
result["wt_scores"] = wt_result["wt_scores"]
result["mutation_position"] = "NA"
else:
# Determine how many amino acids are the same between the MT epitope and its matching WT epitope
total_matches = determine_total_matches(mt_epitope_seq, wt_epitope_seq)
if total_matches >= min_match_count(int(result["peptide_length"])):
# The minimum amino acid match count is met
result["wt_epitope_seq"] = wt_result["wt_epitope_seq"]
result["wt_scores"] = wt_result["wt_scores"]
else:
# The minimum amino acid match count is not met
# Even though there is a matching WT epitope there are not enough overlapping amino acids
# We don't include the matching WT epitope in the output
result["wt_epitope_seq"] = "NA"
result["wt_scores"] = dict.fromkeys(list(result["mt_scores"].keys()), "NA")
mutation_position = find_mutation_position(wt_epitope_seq, mt_epitope_seq)
# print('mu_pos', mutation_position)
if mutation_position == 1 and int(previous_result["mutation_position"]) <= 1:
# The true mutation position is to the left of the current MT eptiope
mutation_position = 0
result["mutation_position"] = mutation_position
def match_wildtype_and_mutant_entry_for_inframe_indel(
result,
mt_position,
wt_results,
previous_result,
iedb_results_for_wt_iedb_result_key,
):
# If the previous WT epitope was matched "from the right" we can just use that position to infer the mutation position and match direction
if previous_result is not None and previous_result["match_direction"] == "right":
best_match_position = previous_result["wt_epitope_position"] + 1
result["wt_epitope_position"] = best_match_position
result["match_direction"] = "right"
if previous_result["mutation_position"] > 0:
result["mutation_position"] = previous_result["mutation_position"] - 1
else:
result["mutation_position"] = 0
# We need to ensure that the matched WT eptiope has enough overlapping amino acids with the MT epitope
best_match_wt_result = wt_results[str(best_match_position)]
total_matches = determine_total_matches(
result["mt_epitope_seq"], best_match_wt_result["wt_epitope_seq"]
)
if total_matches and total_matches >= min_match_count(
int(result["peptide_length"])
):
# The minimum amino acid match count is met
result["wt_epitope_seq"] = best_match_wt_result["wt_epitope_seq"]
result["wt_scores"] = best_match_wt_result["wt_scores"]
else:
# The minimum amino acid match count is not met
# Even though there is a matching WT epitope there are not enough overlapping amino acids
# We don't include the matching WT epitope in the output
result["wt_epitope_seq"] = "NA"
result["wt_scores"] = dict.fromkeys(list(result["mt_scores"].keys()), "NA")
return
# In all other cases the WT epitope at the same position is used as the baseline match
baseline_best_match_position = mt_position
# For an inframe insertion the MT sequence is longer than the WT sequence
# In this case not all MT epitopes might have a baseline match
if baseline_best_match_position not in wt_results:
result["wt_epitope_seq"] = "NA"
result["wt_scores"] = dict.fromkeys(list(result["mt_scores"].keys()), "NA")
# We then infer the mutation position and match direction from the previous MT epitope
result["match_direction"] = previous_result["match_direction"]
if previous_result["mutation_position"] > 0:
result["mutation_position"] = previous_result["mutation_position"] - 1
else:
result["mutation_position"] = 0
return
mt_epitope_seq = result["mt_epitope_seq"]
baseline_best_match_wt_result = wt_results[baseline_best_match_position]
baseline_best_match_wt_epitope_seq = baseline_best_match_wt_result["wt_epitope_seq"]
# The MT epitope does not overlap the indel mutation
if baseline_best_match_wt_epitope_seq == mt_epitope_seq:
result["wt_epitope_seq"] = baseline_best_match_wt_result["wt_epitope_seq"]
result["wt_scores"] = baseline_best_match_wt_result["wt_scores"]
result["wt_epitope_position"] = int(baseline_best_match_position)
result["mutation_position"] = "NA"
result["match_direction"] = "left"
# If there is no previous result or the previous WT epitope was matched "from the left" we start by comparing to the baseline match
if previous_result is None or previous_result["match_direction"] == "left":
best_match_count = determine_consecutive_matches_from_left(
mt_epitope_seq, baseline_best_match_wt_epitope_seq
)
# The alternate best match candidate "from the right" is inferred from the baseline best match position and the indel length
if result["variant_type"] == "inframe_ins":
insertion_length = len(
list(iedb_results_for_wt_iedb_result_key.keys())
) - len(list(wt_results.keys()))
alternate_best_match_position = (
int(baseline_best_match_position) - insertion_length
)
elif result["variant_type"] == "inframe_del":
deletion_length = len(list(wt_results.keys())) - len(
list(iedb_results_for_wt_iedb_result_key.keys())
)
alternate_best_match_position = (
int(baseline_best_match_position) + deletion_length
)
if alternate_best_match_position > 0:
alternate_best_match_wt_result = wt_results[
str(alternate_best_match_position)
]
alternate_best_match_wt_epitope_seq = alternate_best_match_wt_result[
"wt_epitope_seq"
]
consecutive_matches_from_right = determine_consecutive_matches_from_right(
mt_epitope_seq, alternate_best_match_wt_epitope_seq
)
# We then check if the alternate best match epitope has more matching amino acids than the baseline best match epitope
# If it does, we pick it as the best match
if consecutive_matches_from_right > best_match_count:
match_direction = "right"
best_match_position = alternate_best_match_position
best_match_wt_result = alternate_best_match_wt_result
else:
match_direction = "left"
best_match_position = baseline_best_match_position
best_match_wt_result = baseline_best_match_wt_result
else:
match_direction = "left"
best_match_position = baseline_best_match_position
best_match_wt_result = baseline_best_match_wt_result
# Now that we have found the matching WT epitope we still need to ensure that it has enough overlapping amino acids
total_matches = determine_total_matches(
mt_epitope_seq, best_match_wt_result["wt_epitope_seq"]
)
if total_matches and total_matches >= min_match_count(
int(result["peptide_length"])
):
# The minimum amino acid match count is met
result["wt_epitope_seq"] = best_match_wt_result["wt_epitope_seq"]
result["wt_scores"] = best_match_wt_result["wt_scores"]
else:
# The minimum amino acid match count is not met
# Even though there is a matching WT epitope there are not enough overlapping amino acids
# We don't include the matching WT epitope in the output
result["wt_epitope_seq"] = "NA"
result["wt_scores"] = dict.fromkeys(list(result["mt_scores"].keys()), "NA")
result["mutation_position"] = find_mutation_position(
baseline_best_match_wt_epitope_seq, mt_epitope_seq
)
result["match_direction"] = match_direction
result["wt_epitope_position"] = best_match_position
def match_wildtype_and_mutant_entries(iedb_results, wt_iedb_results):
new_iedb_results = {}
for key in sorted(list(iedb_results.keys()), key=lambda x: int(x.split("|")[-1])):
result = iedb_results[key]
(wt_iedb_result_key, mt_position) = key.split("|", 1)
previous_mt_position = str(int(mt_position) - 1)
previous_key = "|".join([wt_iedb_result_key, previous_mt_position])
if previous_key in iedb_results:
previous_result = iedb_results[previous_key]
else:
previous_result = None
wt_results = wt_iedb_results[wt_iedb_result_key]
if result["variant_type"] == "missense":
match_wildtype_and_mutant_entry_for_missense(
result, mt_position, wt_results, previous_result
)
elif result["variant_type"] == "frameshift":
match_wildtype_and_mutant_entry_for_frameshift(
result, mt_position, wt_results, previous_result
)
elif (
result["variant_type"] == "inframe_ins"
or result["variant_type"] == "inframe_del"
):
iedb_results_for_wt_iedb_result_key = {
key: value
for key, value in list(iedb_results.items())
if key.startswith(wt_iedb_result_key)
}
match_wildtype_and_mutant_entry_for_inframe_indel(
result,
mt_position,
wt_results,
previous_result,
iedb_results_for_wt_iedb_result_key,
)
mt_scores = result["mt_scores"]
if min(mt_scores.values()) < 1000.0:
new_iedb_results[key] = result
return new_iedb_results
def parse_iedb_file(input_iedb_files, tsv_entries, key_file):
protein_identifiers_from_label = yaml.safe_load(key_file)
# print(protein_identifiers_from_label)
iedb_results = {}
wt_iedb_results = {}
for input_iedb_file in input_iedb_files:
iedb_tsv_reader = csv.DictReader(input_iedb_file, delimiter="\t")
(method, remainder) = os.path.basename(input_iedb_file.name).split(".", 1)
for line in iedb_tsv_reader:
protein_label = int(line["seq_num"])
if "core_peptide" in line and int(line["end"]) - int(line["start"]) == 8:
# Start and end refer to the position of the core peptide
# Infer the (start) position of the peptide from the positions of the core peptide
position = str(
int(line["start"]) - line["peptide"].find(line["core_peptide"])
)
else:
position = line["start"]
epitope = line["peptide"]
score = line["ic50"]
allele = line["allele"]
peptide_length = len(epitope)
if protein_identifiers_from_label[protein_label] is not None:
protein_identifiers = protein_identifiers_from_label[protein_label]
for protein_identifier in protein_identifiers:
(protein_type, tsv_index) = protein_identifier.split(".", 1)
if protein_type == "MT":
if float(score) > 0.0:
tsv_entry = tsv_entries[tsv_index]
key = f"{tsv_index}|{position}"
if key not in iedb_results:
iedb_results[key] = {}
iedb_results[key]["mt_scores"] = {}
iedb_results[key]["mt_epitope_seq"] = epitope
iedb_results[key]["gene_name"] = tsv_entry["gene_name"]
iedb_results[key]["amino_acid_change"] = tsv_entry[
"amino_acid_change"
]
iedb_results[key]["variant_type"] = tsv_entry[
"variant_type"
]
iedb_results[key]["position"] = position
iedb_results[key]["tsv_index"] = tsv_index
iedb_results[key]["allele"] = allele
iedb_results[key]["peptide_length"] = peptide_length
iedb_results[key]["mt_scores"][method] = float(score)
if protein_type == "WT":
if tsv_index not in wt_iedb_results:
wt_iedb_results[tsv_index] = {}
if position not in wt_iedb_results[tsv_index]:
wt_iedb_results[tsv_index][position] = {}
wt_iedb_results[tsv_index][position]["wt_scores"] = {}