-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathblast_parse.py
1789 lines (1497 loc) · 66.7 KB
/
blast_parse.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/python
# filename: blast_parse.py
###########################################################################
#
# Copyright (c) 2013 Bryan Briney. All rights reserved.
# Copyright (c) 2021 Rinat Mukhometzianov
# @version: 0.3.0
# @author: Bryan Briney, Rinat Mukhometzianov
# @props: IgBLAST team (http://www.ncbi.nlm.nih.gov/igblast/igblast.cgi)
# @license: MIT (http://opensource.org/licenses/MIT)
#
###########################################################################
import re
import sys
import math
import json
import traceback
import collections
import warnings
from Bio.Seq import Seq
from Bio import pairwise2
from Bio.Align import substitution_matrices
class BlastParse(object):
def __init__(self, f_input, species='human', log='', tsv=False, debug=False, uaid=None):
self.input = f_input.split('\n')
self.species = species
self.debug = debug
self.tsv = tsv
self.uaid_len = uaid
self.log = self._get_log(log)
def __str__(self):
return '\n'.join(i for i in self.input)
def get_id(self):
return self.input[0]
######################################################
#
# PARSE
#
######################################################
def parse(self):
warnings.filterwarnings("ignore")
try:
# break the input into region-defined chunks
self._get_chunks()
# parse each chunk
self._parse_chunks()
# assemble the vdj sequences
self._assemble_vdj()
# regions
self._var_regions()
# junction
self._find_junction()
# identities
self._get_identities()
# output
return self._build_output()
except Exception:
e = traceback.format_exc()
return self._exception_output(e)
######################################################
#
# SANITY CHECKS
#
######################################################
def sanity_checks(self):
try:
if self._rearrangement_alignment_check() > 0:
return 1
probs = self._gene_check()
if probs > 0:
return 1
if self._region_check() > 0:
return 1
return 0
except Exception:
return 1
def _rearrangement_alignment_check(self):
i = iter(self.input)
row = next(i)
try:
while row.find('V-(D)-J rearrangement summary') == -1:
row = next(i)
while row.find('Alignment summary') == -1:
row = next(i)
return 0
except StopIteration:
if self.debug:
print("Rearrangement check failed.")
return 1
def _gene_check(self):
i = iter(self.input)
row = next(i)
# get to the rearrangement line, grab the v-gene
while row.find('V-(D)-J rearrangement summary') == -1:
row = next(i)
line = next(i).split()
v_gene = line[0]
# heavy chains
if v_gene[:3] == 'IGH':
if line[3] != 'VH' or line[2][:2] != 'IG':
if self.debug:
print('Gene check failed.')
return 1
# light chains
elif v_gene[:3] in ('IGK', 'IGL'):
if line[2] not in ('VK', 'VL') or line[1][:2] != 'IG':
if self.debug:
print('Gene check failed.')
return 1
return 0
def _region_check(self):
regions = ['FR1-IMGT', 'CDR1-IMGT', 'FR2-IMGT', 'CDR2-IMGT', 'FR3-IMGT']
i = iter(self.input)
row = next(i)
# get to the start of the regions block
while row.find('Alignment summary') == -1:
row = next(i)
self.first_region = regions.index(next(i).split()[0])
countdown = regions.index('FR3-IMGT') - self.first_region
# check the FWR3 line
if countdown == 0:
return 0
while countdown > 0:
row = next(i)
countdown -= 1
if row.split()[0] != 'FR3-IMGT':
if self.debug:
print("Region check failed. Didn't find FR3-IMGT region. Found '{}' instead.".format(
row.split()[0]))
return 1
elif row.split()[3] == 'N/A' or int(row.split()[3]) < 25:
if self.debug:
print('Region check failed.')
return 1
# check the Total line
while row.find('Total') == -1:
row = next(i)
if row.split()[3] == 'N/A' or int(row.split()[3]) < 25:
if self.debug:
print('Region check failed.')
return 1
return 0
######################################################
#
# SPLIT INTO CHUNKS
#
######################################################
def _get_chunks(self):
self.chunks = {}
self.iter = iter(self.input)
row = self._query_chunk()
row = self._score_chunk(row)
row = self._classification_chunk(row)
row = self._rearrangement_chunk(row)
row = self._junction_chunk(row)
row = self._alignment_summary_check(row)
self._alignment_chunk(row)
def _query_chunk(self):
row = next(self.iter)
self.chunks['query'] = []
while row != '':
self.chunks['query'].append(row.strip())
row = next(self.iter)
return next(self.iter)
def _score_chunk(self, row):
self.chunks['score'] = []
while row.find('Sequences producing significant alignments:') == -1:
row = next(self.iter)
next(self.iter)
row = next(self.iter)
while row != '':
self.chunks['score'].append(row.rstrip('\n').split())
row = next(self.iter)
return row
def _classification_chunk(self, row):
while row.find('Domain classification') == -1:
row = next(self.iter)
row = next(self.iter)
self.chunks['domain_class'] = row.rstrip('\n').split()
return next(self.iter)
def _rearrangement_chunk(self, row):
while row.find('V-(D)-J rearrangement summary') == -1:
row = next(self.iter)
row = next(self.iter)
self.chunks['rearrangement_summary'] = row.rstrip('\n').split()
return next(self.iter)
def _junction_chunk(self, row):
while row.find('V-(D)-J junction details') == -1:
row = next(self.iter)
row = next(self.iter)
self.chunks['junction_details'] = row.rstrip('\n').split()
return next(self.iter)
def _alignment_summary_check(self, row):
self.chunks['alignment_summary'] = []
while row.find('Alignment summary') == -1:
row = next(self.iter)
row = next(self.iter)
while row != '':
self.chunks['alignment_summary'].append(row)
row = next(self.iter)
return next(self.iter)
def _alignment_chunk(self, row):
self.chunks['alignment'] = []
while row.find('Alignments') == -1:
row = next(self.iter)
while row.find('Lambda') == -1:
self.chunks['alignment'].append(row.rstrip('\n'))
row = next(self.iter)
while self.chunks['alignment'][0] == '':
del self.chunks['alignment'][0]
######################################################
#
# PARSE CHUNKS
#
######################################################
def _parse_chunks(self):
self._parse_query_chunk(self.chunks['query'])
self._parse_rearrangement_chunk(self.chunks['rearrangement_summary'])
self._parse_score_chunk(self.chunks['score'])
self._parse_alignment_chunk(self.chunks['alignment'])
def _parse_query_chunk(self, chunk):
c_string = ''.join(chunk)
c_string = c_string.replace('\n', '')
self.seq_id = '_'.join(c_string.split('_')[:-2])
self.raw_input = c_string.split('_')[-2]
# self.uaid = ''
# if self.uaid_len:
# self.uaid = self.raw_input[:self.uaid_len]
self.uaid = self.raw_input[:self.uaid_len] if self.uaid_len else ''
# self.seq_id = self.seq_id.split('_')[0]
if self.debug:
print('\n\n' + self.seq_id)
def _parse_classification_chunk(self, chunk):
pass
# TODO
def _parse_rearrangement_chunk(self, chunk):
chains = {'IGHV': 'heavy',
'VH': 'heavy',
'IGKV': 'kappa',
'IGLV': 'lambda'}
self.chain = chains[re.split('[1-9]', chunk[0])[0]]
self.var_gene = chunk[0]
self.join_gene = chunk[-6]
if self.chain == 'heavy':
if 'IGHD' in chunk[1]:
self.div_gene = chunk[1]
else:
self._hc_without_div()
else:
self.has_div = False
self._gene_ids()
self.productivity = chunk[-2]
def _parse_score_chunk(self, chunk):
self.var_bitscore = float(chunk[0][1])
self.var_evalue = float(chunk[0][2])
self.join_bitscore = float(chunk[-1][1])
self.join_evalue = float(chunk[-1][2])
if self.chain == 'heavy' and self.div_gene != '':
self.div_bitscore = float(chunk[1][1])
self.div_evalue = float(chunk[1][2])
def _parse_alignment_chunk(self, chunk):
self.blocks = self._build_alignment_blocks(chunk)
self._get_pretty_alignment(self.blocks)
self._v_alignment_parser(self.blocks)
self._junction_sequence_parser(self.chunks['junction_details'])
if self.has_div:
self._d_alignment_parser(self.blocks)
self._j_alignment_parser(self.blocks)
######################################################
#
# GENE IDs
#
######################################################
def _gene_ids(self):
self._v_gene_id()
self._j_gene_id()
if self.chain == 'heavy' and self.div_gene != '':
self._d_gene_id()
def _v_gene_id(self):
v_split = re.split('[-*]', self.var_gene)
self.var_gene_fam = re.sub('VH|IGHV|VK|IGKV|VL|IGLV', '', v_split[0])
if len(v_split) > 3:
self.var_gene_gene = '-'.join(v_split[1:3])
else:
self.var_gene_gene = v_split[1]
self.var_gene_allele = v_split[-1]
def _j_gene_id(self):
j_split = re.split('[-*]', self.join_gene)
self.join_gene_gene = re.sub('IGHJ|IGKJ|IGLJ', '', j_split[0])
self.join_gene_allele = j_split[1]
def _d_gene_id(self):
d_split = re.split('[-*]', self.div_gene)
self.div_gene_fam = re.sub('IGHD|IGKD|IGLD', '', d_split[0])
self.div_gene_gene = d_split[1]
self.div_gene_allele = d_split[2]
def _hc_without_div(self):
self.div_gene = ''
self.has_div = False
self.div_gene_fam = ''
self.div_gene_gene = ''
self.div_gene_allele = ''
self.div_bitscore = ''
self.div_evalue = ''
self.div_nt_identity = ''
self.div_muts_nt = ''
self.div_muts_nt_count = ''
self.div_ins = []
self.div_del = []
self.div_start = 0
self.div_germ_offset_nt = 0
######################################################
#
# ALIGNMENT PARSING
#
######################################################
def _build_alignment_blocks(self, chunk):
# define the start point for each alignment block
starts = []
for i, line in enumerate(chunk):
if 'Query_' in line:
starts.append(i - 2)
# build a list of the alignment blocks
blocks = []
for s in starts:
block = []
i = iter(chunk[s:])
row = next(i)
try:
while row.split() == '':
row = next(i)
while row != '':
block.append(row)
row = next(i)
blocks.append(block)
except StopIteration:
pass
return blocks
def _get_pretty_alignment(self, blocks):
self.pretty_alignment = '\n\n'.join(['\n'.join(b) for b in blocks])
def _get_vdj_alignment_blocks(self, blocks, gene):
a_blocks = []
for block in blocks:
for line in block:
if line[0] == gene:
a_blocks.append(block)
return a_blocks
def _align_block_position(self, block):
position = re.search('<', block[0]).start()
length = len(block[0].strip())
return position, length
# -----------------
# VARIABLE
# -----------------
def _v_alignment_parser(self, blocks):
# get the raw data out of the alignment blocks
v_blocks = self._get_vdj_alignment_blocks(blocks, 'V')
self.v_region_delims = self._var_region_delimiters(v_blocks)
position, length = self._align_block_position(v_blocks[0])
self._var_germ_aa_sequence(v_blocks, position, length)
self._var_aa_sequence(v_blocks, position, length)
self._var_nt_alignment(v_blocks)
self._var_nt_sequence(v_blocks)
self.var_readframe = self._var_reading_frame()
self._var_germ_offsets(v_blocks)
# fix ambigs and indels
if 'N' in self.var_nt_seq:
self._fix_v_ambigs()
self.var_ins = []
self.var_del = []
if self._v_indel_check():
self._fix_v_indels()
# self.var_aa_seq = self._v_retranslate()
# mutations
self._var_nt_mutations()
self._var_aa_mutations()
def _var_region_delimiters(self, blocks):
delims = ''
for block in blocks:
delims += block[0].strip()
return delims
def _var_germ_aa_sequence(self, blocks, p, ln):
self.var_germ_aa_seq_raw = ''
for block in blocks:
self.var_germ_aa_seq_raw += block[4][p:p + ln]
self.var_germ_aa_seq = ''.join(self.var_germ_aa_seq_raw.split())
def _var_aa_sequence(self, blocks, p, ln):
self.var_aa_seq_raw = ''
for block in blocks:
self.var_aa_seq_raw += block[1][p:p + ln]
self.var_aa_seq = ''.join(self.var_aa_seq_raw.split())[:len(self.var_germ_aa_seq)]
def _var_nt_alignment(self, blocks):
align = ''
for block in blocks:
align += block[3].split()[5]
while align[-1] == '-':
align = align[:-1]
self.var_nt_alignment = align
def _var_nt_sequence(self, blocks):
nt_seq = ''
for block in blocks:
nt_seq += block[2].split()[2]
self.var_nt_seq = nt_seq[:len(self.var_nt_alignment)]
def _var_reading_frame(self):
alignment_start = re.search(r'\S', self.var_aa_seq_raw).start()
return alignment_start - 1
def _var_germ_offsets(self, blocks):
self.var_germ_offset_nt = int(blocks[0][3].split()[4])
self.var_germ_offset_aa = int((self.var_germ_offset_nt - 1 + self.var_readframe) / 3)
def _var_nt_mutations(self):
self.var_muts_nt = []
for i in range(len(self.var_nt_seq)):
if self.var_nt_alignment[i] != '.':
m = i + self.var_germ_offset_nt
mut = '{0}:{1}>{2}'.format(m, self.var_nt_alignment[i], self.var_nt_seq[i])
self.var_muts_nt.append(mut)
self.var_muts_nt_count = len(self.var_muts_nt)
def _var_aa_mutations(self):
self.var_muts_aa = []
[(a1, a2, score, begin, end)] = pairwise2.align.globalxx(self.var_germ_aa_seq, self.var_aa_seq,
one_alignment_only=True)
for i in range(len(a1)):
if a1[i] == '-' or a2[i] == '-':
continue
if a1[i] != a2[i]:
m = i + self.var_germ_offset_aa
mut = '{0}:{1}>{2}'.format(m, a1[i], a2[i])
self.var_muts_aa.append(mut)
self.var_muts_aa_count = len(self.var_muts_aa)
# -----------------
# DIVERSITY
# -----------------
def _d_alignment_parser(self, blocks):
# get the raw data out of the alignment blocks
d_blocks = self._get_vdj_alignment_blocks(blocks, 'D')
d_start, d_length = self._div_nt_alignment(d_blocks)
self._div_nt_seq(d_blocks, d_start, d_length)
# fix ambigs and indels
if 'N' in self.div_nt_seq:
self._fix_d_ambigs()
self.div_ins = []
self.div_del = []
if self._d_indel_check():
self._fix_d_indels()
# mutations
self._div_nt_mutations()
def _div_nt_alignment(self, blocks):
self.div_nt_alignment = ''
for block in blocks:
i = iter(block)
row = next(i)
while row[0] != 'D':
row = next(i)
self.div_nt_alignment += row.split()[5]
return self._trim_div_nt_alignment()
def _trim_div_nt_alignment(self):
untrimmed_length = len(self.div_nt_alignment)
while self.div_nt_alignment[0] == '-':
self.div_nt_alignment = self.div_nt_alignment[1:]
start = untrimmed_length - len(self.div_nt_alignment) + self.d_trunc_start
while self.div_nt_alignment[-1] == '-':
self.div_nt_alignment = self.div_nt_alignment[:-1]
if self.d_trunc_end > 0:
self.div_nt_alignment = self.div_nt_alignment[:-self.d_trunc_end]
return start, len(self.div_nt_alignment)
def _div_nt_seq(self, blocks, s, ln):
self.div_nt_seq = ''
for block in blocks:
i = iter(block)
row = next(i)
while 'Query_' not in row:
row = next(i)
self.div_nt_seq += row.split()[2]
self.div_nt_seq = self.div_nt_seq[s:s + ln]
def _div_nt_mutations(self):
self.div_muts_nt = []
for i in range(len(self.div_nt_seq)):
if self.div_nt_alignment[i] != '.':
m = i + self.var_germ_offset_nt + (len(self.var_nt_seq + self.n1_nt))
mut = '{0}:{1}>{2}'.format(m, self.div_nt_alignment[i], self.div_nt_seq[i])
self.div_muts_nt.append(mut)
self.div_muts_nt_count = len(self.div_muts_nt)
# -----------------
# JOINING
# -----------------
def _j_alignment_parser(self, blocks):
# get the raw data out of the alignment blocks
j_blocks = self._get_vdj_alignment_blocks(blocks, 'J')
j_length = self._join_nt_alignment(j_blocks)
self._join_nt_seq(j_blocks, j_length)
# fix ambigs and indels
if 'N' in self.join_nt_seq:
self._fix_j_ambigs()
self.join_ins = []
self.join_del = []
if self._j_indel_check():
self._fix_j_indels()
# mutations
self._join_nt_mutations()
def _join_nt_alignment(self, blocks):
self.join_nt_alignment = ''
for block in blocks:
i = iter(block)
row = next(i)
while row[0] != 'J':
row = next(i)
try:
self.join_nt_alignment += row.split()[5]
except IndexError:
if row.split()[4].endswith('-.'):
self.join_nt_alignment += row.split()[4]
else:
raise Exception
while self.join_nt_alignment[0] == '-':
self.join_nt_alignment = self.join_nt_alignment[1:]
return len(self.join_nt_alignment)
def _join_nt_seq(self, blocks, ln):
self.join_nt_seq = ''
for block in blocks:
i = iter(block)
row = next(i)
while 'Query_' not in row:
row = next(i)
self.join_nt_seq += row.split()[2]
start = len(self.join_nt_seq) - ln
self.join_nt_seq = self.join_nt_seq[start:]
def _join_nt_mutations(self):
self.join_muts_nt = []
for i in range(len(self.join_nt_seq)):
if self.join_nt_alignment[i] != '.':
m = i + self.join_start
mut = '{0}:{1}>{2}'.format(m, self.join_nt_alignment[i], self.join_nt_seq[i])
self.join_muts_nt.append(mut)
self.join_muts_nt_count = len(self.join_muts_nt)
######################################################
#
# CDR3 AND JUNCTION
#
######################################################
def _junction_sequence_parser(self, j):
for i in range(len(j)):
if j[i] == 'N/A':
j[i] = ''
if self.chain == 'heavy':
self.junction_var = j[0]
self.junction_join = j[4]
self._n1_parser(j[1])
self._n2_parser(j[3])
self._div_nt_parser(j[2])
else:
self.junction_var = j[0]
self.junction_join = j[2]
self._n_parser(j[1])
self._get_join_start_position()
def _n1_parser(self, seq):
if seq.startswith('('):
self.d_trunc_start = len(seq) - 2
self.n1_nt = ''
self.junction_var = self.junction_var + re.sub('[()]', '', seq)
else:
self.d_trunc_start = 0
self.n1_nt = seq
def _n2_parser(self, seq):
if seq.startswith('('):
self.d_trunc_end = len(seq) - 2
self.n2_nt = ''
self.junction_join = re.sub('[()]', '', seq) + self.junction_join
else:
self.d_trunc_end = 0
self.n2_nt = seq
def _div_nt_parser(self, seq):
if seq == '':
self.has_div = False
self.div_nt = ''
elif seq.startswith('('):
self.has_div = False
self.div_nt = ''
if self.n1_nt == '':
self.junction_var = self.junction_var + re.sub('[()]', '', seq)
else:
self.junction_join = re.sub('[()]', '', seq) + self.junction_join
else:
self.has_div = True
self.div_nt = seq
self.junction_nt = self.junction_var + self.n1_nt + self.div_nt + self.n2_nt + self.junction_join
def _n_parser(self, seq):
if seq.startswith('('):
self.n_nt = ''
self.junction_var = self.junction_var + re.sub('[()]', '', seq)
self._j_overlap_offset = len(re.sub('[()]', '', seq))
else:
self.n_nt = seq
self._j_overlap_offset = 0
self.junction_nt = self.junction_var + self.n_nt + self.junction_join
def _get_join_start_position(self):
if self.chain == 'heavy':
self.join_start = self.var_germ_offset_nt + len(self.var_nt_seq + self.n1_nt + self.div_nt + self.n2_nt)
else:
self.join_start = self.var_germ_offset_nt + len(self.var_nt_seq + self.n_nt) + self._j_overlap_offset
def _find_junction(self):
start = self._find_junction_start()
end = self._find_junction_end(start)
self.junction_aa = self.vdj_aa[start:end]
self.CDR3_aa = self.vdj_aa[start + 1:end - 1]
def _find_junction_start(self):
scores = []
matrix = substitution_matrices.load("BLOSUM62")
fr3_start = len(self.FR1_aa + self.CDR1_aa + self.FR2_aa + self.CDR2_aa)
germ = self._get_v_chunk(self.var_gene)
for i in range(fr3_start, len(self.vdj_aa) - 5):
chunk = self.vdj_aa[i:i + 6]
if '*' in chunk:
scores.append(0.0)
continue
scores.append(pairwise2.align.globalds(germ, chunk, matrix, -100, -20, one_alignment_only=1, score_only=1))
max_score = max(scores)
max_score_positions = [i + 4 for i, j in enumerate(scores) if j == max_score]
return max_score_positions[0] + fr3_start
def _find_junction_end(self, start):
scores = []
matrix = substitution_matrices.load("BLOSUM62")
germ = self._get_j_chunk(self.join_gene)
for i in range(start, len(self.vdj_aa) - 1):
if i < len(self.vdj_aa) - 4:
chunk = self.vdj_aa[i:i + 5]
else:
chunk = self.vdj_aa[i:]
if '*' in chunk:
scores.append(0.0)
continue
scores.append(pairwise2.align.globalds(germ[:len(chunk)], chunk, matrix, -100, -20, one_alignment_only=1,
score_only=1))
max_score = max(scores)
max_score_positions = [i + 1 for i, j in enumerate(scores) if j == max_score]
return max_score_positions[-1] + start
def _get_v_chunk(self, gene):
trunc_gene = gene[:5]
germs = {
'human': {'IGHV1': 'AVYYCA',
'IGHV2': 'ATYYCA',
'IGHV3': 'AVYYCA',
'IGHV4': 'AVYYCA',
'IGHV5': 'AMYYCA',
'IGHV6': 'AVYYCA',
'IGHV7': 'AVYYCA',
'IGKV1': 'ATYYCQ',
'IGKV2': 'GVYYCM',
'IGKV3': 'AVYYCQ',
'IGKV4': 'AVYYCQ',
'IGLV1': 'ADYYCQ',
'IGLV2': 'ADYYCS',
'IGLV3': 'ADYYCQ',
'IGLV4': 'ADYYCQ',
'IGLV5': 'ADYYCM',
'IGLV6': 'ADYYCQ',
'IGLV7': 'AEYYCL',
'IGLV8': 'SDYYCV',
'IGLV9': 'SDYHCG'},
'macaque': {'IGHV1': 'AVYYCA',
'IGHV2': 'ATYYCA',
'IGHV3': 'AVYYCA',
'IGHV4': 'AVYYCA',
'IGHV5': 'ATYYCA',
'IGHV6': 'AVYYCA',
'IGHV7': 'AVYYCA',
'IGKV1': 'ATYYCQ',
'IGKV2': 'GVYYCM',
'IGKV3': 'AVYYCQ',
'IGKV4': 'AVYYCQ',
'IGKV5': 'AYYFCQ',
'IGKV6': 'ATYYCQ',
'IGKV7': 'ADYYCL',
'IGLV1': 'ADYYCQ',
'IGLV2': 'ADYYCS',
'IGLV3': 'ADYYCQ',
'IGLV4': 'ADYYCQ',
'IGLV5': 'ADYYCM',
'IGLV6': 'ADYYCQ',
'IGLV7': 'AEYYCW',
'IGLV8': 'SDYYCT',
'IGLV9': 'SDYHCG'
},
'mouse': {'IGHV1': 'AVYYCA',
'IGHV2': 'AIYYCA',
'IGHV3': 'ATYYCA',
'IGHV4': 'ALYYCA',
'IGHV5': 'AMYYCA',
'IGHV6': 'GIYYCT',
'IGHV7': 'ATYYCA',
'IGHV8': 'ATYYCA',
'IGHV9': 'ATYFCA',
'IGKV1': 'ATYYCQ',
'IGKV2': 'GVYYCA',
'IGKV3': 'ATYYCQ',
'IGKV4': 'ATYYCQ',
'IGKV5': 'GVYYCQ',
'IGKV6': 'AVYFCQ',
'IGKV7': 'THYYCA',
'IGKV8': 'AVYYCQ',
'IGKV9': 'ADYYCL',
'IGLV1': 'AIYFCA',
'IGLV2': 'AMYFCA',
'IGLV3': 'AIYICG',
'IGLV4': 'AIYFCA',
'IGLV5': 'AIYFCA',
'IGLV6': 'AIYFCA',
'IGLV7': 'AIYFCA',
'IGLV8': 'AIYFCA'},
'rabbit': {}}
return germs[self.species][trunc_gene]
def _get_j_chunk(self, gene):
trunc_gene = gene[:5]
if self.debug:
print(self.species)
print(trunc_gene)
germs = {
'human': {'IGHJ1': 'WGQGT',
'IGHJ2': 'WGRGT',
'IGHJ3': 'WGQGT',
'IGHJ4': 'WGQGT',
'IGHJ5': 'WGQGT',
'IGHJ6': 'WGQGT',
'IGKJ1': 'FGQGT',
'IGKJ2': 'FGQGT',
'IGKJ3': 'FGPGT',
'IGKJ4': 'FGGGT',
'IGKJ5': 'FGQGT',
'IGLJ1': 'FGTGT',
'IGLJ2': 'FGGGT',
'IGLJ3': 'FGGGT',
'IGLJ4': 'FGGGT',
'IGLJ5': 'FGEGT',
'IGLJ6': 'FGSGT',
'IGLJ7': 'FGGGT'},
'macaque': {'IGHJ1': 'WGQGA',
'IGHJ2': 'WGPGT',
'IGHJ3': 'WGQGL',
'IGHJ4': 'WGQGV',
'IGHJ5': 'WGPGV',
'IGHJ6': 'WGQGV',
'IGKJ1': 'FGQGT',
'IGKJ2': 'FGQGT',
'IGKJ3': 'FGPGT',
'IGKJ4': 'FGGGT',
'IGKJ5': 'FGQGT',
'IGLJ1': 'FGAGT',
'IGLJ2': 'FGGGT',
'IGLJ3': 'FGGGT',
'IGLJ4': 'FCGGT',
'IGLJ5': 'FGEGT',
'IGLJ6': 'FGSGT'},
'mouse': {'IGHJ1': 'WGAGT',
'IGHJ2': 'WGQGT',
'IGHJ3': 'WGQGT',
'IGHJ4': 'WGQGT',
'IGKJ1': 'FGGGT',
'IGKJ2': 'FGGGT',
'IGKJ4': 'FGSGT',
'IGKJ5': 'FGAGT',
'IGLJ1': 'FGGGT',
'IGLJ2': 'FGGGT',
'IGLJ3': 'FGSGT'},
'rabbit': {}}
return germs[self.species][trunc_gene]
######################################################
#
# AMBIGS AND INDELS
#
######################################################
# -----------------
# VARIABLE
# -----------------
def _fix_v_ambigs(self):
for n in re.finditer('[Nn]', self.var_nt_seq):
i = n.start()
if self.var_nt_alignment[i] != '-':
self.var_nt_seq = self.var_nt_seq[:i] + self.var_nt_alignment[i] + self.var_nt_seq[i + 1:]
self.var_nt_alignment = self.var_nt_alignment[:i] + '.' + self.var_nt_alignment[i + 1:]
def _v_indel_check(self):
i = iter(self.chunks['alignment_summary'])
row = next(i)
while row.find('Total') == -1:
row = next(i)
if int(row.split()[6]) > 0:
return True
return False
def _fix_v_indels(self):
self.var_ins = []
self.var_del = []
self._fix_combined_nfs_indels()
self._v_retranslate()
def _fix_combined_nfs_indels(self):
"""
Accounts for a quirk in IgBLAST (likely due to incorrect gap open/extend penalties) which
can result in a single non-frameshift indel being split into multiple samller, frameshift indels.
"""
full_nt_germline = self._full_v_nt_germline()
nt_seq = self.var_nt_seq.replace('-', '')
self._recalc_combined_indel_germline_alignment(nt_seq, full_nt_germline)
ins = [i for i in re.finditer('-+', self.var_nt_alignment)]
if len(ins) > 0:
self._fix_v_ins(ins)
dels = [d for d in re.finditer('-+', self.var_nt_seq)]
if len(dels) > 0:
self._fix_v_dels(dels)
def _full_v_nt_germline(self):
full_nt_germline = ''
for i, nt in enumerate(self.var_nt_alignment):
if nt == '.':
full_nt_germline += self.var_nt_seq[i]
else:
full_nt_germline += self.var_nt_alignment[i]
return full_nt_germline.replace('-', '')
def _recalc_combined_indel_germline_alignment(self, nt_seq, full_nt_alignment):
[alignment] = pairwise2.align.globalms(nt_seq, full_nt_alignment, 1, 0, -5, -1, one_alignment_only=True)