/
snv_annotation.py
1861 lines (1624 loc) · 73 KB
/
snv_annotation.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
'''
Created on 16/02/2010
@author: jose
'''
# Copyright 2009 Jose Blanca, Peio Ziarsolo, COMAV-Univ. Politecnica Valencia
# This file is part of franklin.
# franklin is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
# franklin is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
# You should have received a copy of the GNU Affero General Public License
# along with franklin. If not, see <http://www.gnu.org/licenses/>.
from __future__ import division
from operator import attrgetter
from collections import defaultdict
from copy import copy
import math, itertools
import logging
try:
import pysam
except ImportError:
pass
from Bio.SeqFeature import FeatureLocation
from Bio.Restriction import Analysis, CommOnly, RestrictionBatch
from franklin.seq.seqs import SeqFeature, get_seq_name
from franklin.utils.misc_utils import get_fhand
from franklin.sam import create_bam_index, get_read_group_info
DEFAUL_MIN_NUM_READS_PER_ALLELE = 2
DEFAULT_PLOIDY = 2
DELETION_ALLELE = '-'
UNKNOWN_NUCLEOTYDE = 'N'
NO_NUCLEOTYDE = ' '
N_ALLLELES = ('n', '?')
SNP = 0
INSERTION = 1
DELETION = 2
INVARIANT = 3
INDEL = 4
COMPLEX = 5
TRANSITION = 6
TRANSVERSION = 7
UNKNOWN = 8
VARIANT = 9 # non-invariant allele
SNV_TYPES = {SNP:'SNP', INSERTION:'insertion', DELETION:'deletion',
INVARIANT:'invariant', INDEL:'indel', COMPLEX:'complex',
TRANSITION:'transition', TRANSVERSION:'transversion',
UNKNOWN:'unknown'}
COMMON_ENZYMES = ['EcoRI', 'SmaI', 'BamHI', 'AluI', 'BglII',
'SalI', 'BglI', 'ClaI', 'TaqI',
'PstI', 'PvuII', 'HindIII', 'EcoRV',
'HaeIII', 'KpnI', 'ScaI',
'HinfI', 'DraI', 'ApaI', 'BstEII', 'ZraI', 'BanI', 'Asp718I']
UNKNOWN_RG = 'unknown'
MATCH = 0
INSERTION = 1
DELETION = 2
SKIP = 3
SOFT_CLIP = 4
HARD_CLIP = 5
PADDING = 6
IN_FIRST_POS = 1
IN_MIDDLE_POS = 2
IN_LAST_POS = 3
IN_FIRST_AND_LAST = 4
CIGAR_DECODE = 'MIDNSHP'
def _get_raw_allele_from_read(aligned_read, index):
'It returns allele, quality, is_reverse'
allele = aligned_read.seq[index].upper()
if aligned_read.qual:
try:
qual = _quality_to_phred(aligned_read.qual[index])
except ZeroDivisionError:
raise RuntimeError('mi error')
else:
qual = None
return allele, qual
SEGMENTS_CACHE = {}
MAX_CACHED_SEGMENTS = 10000
def _get_cigar_segments_from_aligned_read(aligned_read):
'It gets the cigar from an aligened_read of pysam'
begin_pos_read_in_ref = aligned_read.pos
read_len = len(aligned_read.seq)
cigar = aligned_read.cigar
return _get_segments_from_cigar(begin_pos_read_in_ref, cigar, read_len)
def _get_segments_from_cigar(begin_pos_read_in_ref, cigar, read_len):
'''It returns two lists (reference and read) in which the firsts nucleotides
of the different cigar categories are given.
67890 12345
ATCGA--GATCG
atcGATCG--CG
01234 56
CIGAR = 3H2M2I1M2D2M
ref_segments = [9, None, 11, 12, 14]
read_segments = [0, 2, 4, None, 5]
It also returns the limits of the aligned reference and the limits of the
read.
It also returns a list with the cigar category for each segment.
The position in the reference is only used for the cache
'''
cigar = tuple(cigar)
global SEGMENTS_CACHE
cache_key = read_len, begin_pos_read_in_ref, cigar
if cache_key in SEGMENTS_CACHE:
return SEGMENTS_CACHE[cache_key]['result']
#We ignore hard clipped nucleotides ('H')
cigar_elements = []
for element in range(len(cigar)):
if cigar[element][0] != HARD_CLIP:
cigar_elements.append(cigar[element])
ref_segments = []
read_segments = []
ref_pos = begin_pos_read_in_ref
read_start = 0
read_end = 0
segment_type = []
segment_lens = []
read_pos = read_start
for index, element in enumerate(cigar_elements):
if element[0] == SOFT_CLIP:
#Is the soft clip at beginning?
if index == 0:
read_pos += element[1]
read_start += element[1]
read_end = read_start
elif index == len(cigar_elements) - 1:
continue
else:
msg = 'Soft clips in the middle of the read are not supported'
raise RuntimeError(msg)
elif element[0] == MATCH:
segment_type.append(MATCH)
ref_segments.append(ref_pos)
read_segments.append(read_pos)
segment_lens.append(element[1])
ref_pos += element[1]
read_pos += element[1]
read_end += element[1]
elif element[0] == INSERTION:
segment_type.append(INSERTION)
ref_segments.append(None)
read_segments.append(read_pos)
segment_lens.append(element[1])
read_pos += element[1]
read_end += element[1]
elif element[0] == DELETION or element[0] == SKIP:
read_segments.append(None)
ref_segments.append(ref_pos)
segment_lens.append(element[1])
#We differentiate between DELETION or SKIP
if element[0] == DELETION:
segment_type.append(DELETION)
if element[0] == SKIP:
segment_type.append(SKIP)
ref_pos += element[1]
ref_end = ref_pos - 1
ref_start = ref_segments[0]
# Somethimes the first segment is an insertion and the reference por the
# start position is in the next segment
if ref_segments[0] is not None:
ref_start = ref_segments[0]
else:
ref_start = ref_segments[1]
ref_limits = [ref_start, ref_end]
read_end = read_end - 1
read_limits = [read_start, read_end]
result = (ref_segments, read_segments, sorted(ref_limits),
sorted(read_limits), segment_type, segment_lens)
if ref_pos is not None:
#store cache
SEGMENTS_CACHE[cache_key] = {'result':result, 'ref_pos':ref_pos}
#clean cache
if len(SEGMENTS_CACHE) > MAX_CACHED_SEGMENTS:
SEGMENTS_CACHE = {}
return result
def _locate_segment(ref_pos, ref_segments, segment_lens, ref_limits):
'It locates a read position in the segments'
for segment_index, segment_begin_pos in enumerate(ref_segments):
if segment_begin_pos is None:
continue
end_segment_pos = segment_begin_pos + segment_lens[segment_index] - 1
if ref_pos < segment_begin_pos:
#we're before the first segment, no read here
return None
elif ref_pos > end_segment_pos:
continue
elif ref_pos == segment_begin_pos and segment_begin_pos == end_segment_pos:
return segment_index, IN_FIRST_AND_LAST
elif ref_pos == segment_begin_pos:
return segment_index, IN_FIRST_POS
elif ref_pos == end_segment_pos:
return segment_index, IN_LAST_POS
elif segment_begin_pos < ref_pos < end_segment_pos:
return segment_index, IN_MIDDLE_POS
else:
raise RuntimeError('We should not be here, fix me')
#we're outside any segment
return None
def _get_insertion(segment_index, segment_type, read_pos, aligned_read,
segment_lens):
#TODO explain function
allele = None
kind = None
qual = None
if segment_index == len(segment_type) - 1:
#we're in the last segment
next_segment_pos = None
else:
next_segment_pos = segment_index + 1
if (next_segment_pos is not None and
segment_type[next_segment_pos] == INSERTION):
indel_length = segment_lens[next_segment_pos]
if indel_length == 0:
msg = "An insertion can't be of 0 length\n"
msg += 'next_segment_pos ' + str(next_segment_pos)
msg += '\nsegment_index ' + str(segment_index)
msg += '\nsegment_type ' + str(segment_type)
msg += '\nread_pos ' + str(read_pos)
msg += '\naligned_read ' + str(aligned_read)
raise ValueError(msg)
start = read_pos
end = start + indel_length
allele, qual = _get_raw_allele_from_read(aligned_read,
slice(start, end))
kind = INSERTION
return allele, kind, qual
def _from_ref_to_read_pos(segment_type, ref_segment_pos, read_segment_pos,
ref_pos):
'Given the segment positions it calculates the read_pos'
if segment_type != MATCH:
return None
read_pos = read_segment_pos + (ref_pos - ref_segment_pos)
return read_pos
def _read_pos_around_del(ref_segments, read_segments, segment_types,
segment_index, ref_pos):
'It returns the read positions around a deletion'
if segment_types[segment_index - 1] == MATCH:
read_pos1 = _from_ref_to_read_pos(segment_types[segment_index - 1],
ref_segments[segment_index - 1],
read_segments[segment_index - 1],
ref_segments[segment_index] - 1)
read_pos2 = read_pos1 + 1
elif segment_types[segment_index + 1] == MATCH:
read_pos2 = _from_ref_to_read_pos(segment_types[segment_index + 1],
ref_segments[segment_index + 1],
read_segments[segment_index + 1],
ref_segments[segment_index + 1])
read_pos1 = read_pos2 - 1
else:
msg = 'A deletion is surrounded by two segments that are not matches'
raise RuntimeError(msg)
return read_pos1, read_pos2
def _chop_alignment(alignment):
'it chops the alignments in lists'
ref, read = alignment
listed_ref = []
listed_read = []
inserts = ''
read_inserts = ''
for index in range(len(ref)):
if ref[index] == '-':
inserts += '-'
read_inserts += read[index]
else:
if inserts != '':
listed_ref.append(inserts)
listed_read.append(read_inserts)
inserts = ''
read_inserts = ''
listed_ref.append(ref[index])
listed_read.append(read[index])
else:
if inserts != '':
listed_ref.append(inserts)
listed_read.append(read_inserts)
return listed_ref, listed_read
def _prepare_alignments(alignments):
'It prepares the alignments for joining'
prepared_alignments = []
for name, alignment in alignments.items():
ref, read = _chop_alignment(alignment)
assert len(ref) == len(read)
alignment = {'reference':ref,
'reads':{name:read}}
prepared_alignments.append(alignment)
return prepared_alignments
def add_collumn(alignment, nalig, index, diff_length=0):
'It adds a column to the given alignment'
for name, read in alignment['reads'].items():
if name not in nalig['reads']:
nalig['reads'][name] = []
try:
to_add = read[index]
except IndexError:
to_add = diff_length * '-'
nalig['reads'][name].append(to_add)
def _join_alignments(alignment1, alignment2, snv_types_per_read):
'It joins two alignments and makes a new alignment'
def _insert_in_seq(list_seq):
for element in list_seq:
if '-' in element:
return True
return False
if len(alignment1['reference']) > len(alignment2['reference']):
align1 = alignment1
align2 = alignment2
else:
align1 = alignment2
align2 = alignment1
ref1 = align1['reference']
ref2 = align2['reference']
if (not _insert_in_seq(ref1) and not _insert_in_seq(ref2) and
len(ref1) == len(ref2)):
reads = {}
for name, read in align1['reads'].items():
reads[name] = read
for name, read in align2['reads'].items():
reads[name] = read
return {'reference':ref1,
'reads':reads}
nalig = {'reference':[], 'reads':{}}
index1_delta = 0
index2_delta = 0
for index in range(len(ref1)):
index1 = index - index1_delta
index2 = index - index2_delta
ref1_item = ref1[index1]
try:
ref2_item = ref2[index2]
except IndexError:
ref2_item = ref1_item
inser_1 = ref1_item.count('-')
inser_2 = ref2_item.count('-')
if inser_1 == inser_2:
nalig['reference'].append(ref1_item)
add_collumn(align1, nalig, index1, inser_1)
add_collumn(align2, nalig, index2, inser_2)
elif inser_1 > inser_2:
inser_diff = inser_1 - inser_2
nalig['reference'].append(ref1_item)
add_collumn(align1, nalig, index1)
just_once = True
for name, read in align2['reads'].items():
if name not in nalig['reads']:
nalig['reads'][name] = []
if inser_2 > 0:
nalig['reads'][name].append(read[index2] + inser_diff * '-')
else:
nalig['reads'][name].append(inser_diff * '-')
if just_once:
index2_delta += 1
just_once = False
else:
inser_diff = inser_2 - inser_1
nalig['reference'].append(ref2_item)
just_once = True
for name, read in align1['reads'].items():
if name not in nalig['reads']:
nalig['reads'][name] = []
if inser_1 > 0:
nalig['reads'][name].append(read[index1] + inser_diff * '-')
else:
nalig['reads'][name].append(inser_diff * '-')
if just_once:
index1_delta += 1
just_once = False
add_collumn(align2, nalig, index)
return nalig
def _make_multiple_alignment(alignments, reads=None):
'It makes the multiple alignments using ref to read sinmple alignments'
snv_types_per_read = {}
alignments = _prepare_alignments(alignments)
if not alignments:
raise RuntimeError('No alignments to create the multiple one')
alignment = alignments[0]
assert len(alignment['reads'].values()[0]) == len(alignment['reference'])
for index in range(1, len(alignments)):
assert len(alignments[index]['reads'].values()[0]) == len(alignments[index]['reference'])
alignment = _join_alignments(alignment, alignments[index],
snv_types_per_read)
assert len(alignment['reads'].values()[0]) == len(alignment['reference'])
return alignment
def _get_alignment_section(pileup_read, start, end, reference_seq=None):
'It gets a section of the alignment of the given read'
# we don't get the last position because our politic is:
# [start, end[
# [start, stop]
if start > end:
raise ValueError('Start (%i) is bigger than end (%i)' % (start, end))
stop = end - 1
aligned_read = pileup_read.alignment
read_seq = aligned_read.seq
(ref_segments, read_segments, ali_ref_limits, ali_read_limits, segment_types,
segment_lens) = _get_cigar_segments_from_aligned_read(aligned_read)
if (start < 0 or (reference_seq and len(reference_seq) < end)):
ref_len = len(reference_seq) if reference_seq else None
msg = 'Section outside the alignment: start (%d),'
msg += 'stop (%d), limits (1, %d)'
msg %= start, stop, ref_len
raise ValueError(msg)
#in which segment starts the section
start_segment = _locate_segment(start, ref_segments, segment_lens, ali_ref_limits)
start_segment = start_segment[0] if start_segment is not None else None
end_segment = _locate_segment(end, ref_segments, segment_lens, ali_ref_limits)
end_segment = end_segment[0] if end_segment is not None else None
stop_segment = _locate_segment(stop, ref_segments, segment_lens, ali_ref_limits)
if stop_segment is not None:
stop_segment, stop_segment_pos = stop_segment
else:
stop_segment, stop_segment_pos = None, None
#when does the read start and end in the reference coordinate system
ref_start_limit, ref_end_limit = ali_ref_limits
read_start_in_ref = start if start >= ref_start_limit else ref_start_limit
read_stop_in_ref = stop if stop <= ref_end_limit else ref_end_limit
# we have to look if the position of the end is in an insertion. For that
# we can look the difference between the end_segment and
# the origial_end_segment
if (stop_segment is not None and stop_segment_pos == IN_LAST_POS and
len(ref_segments) > stop_segment + 1 and
segment_types[stop_segment + 1] == INSERTION):
stop_segment += 1
cum_ref_seq, cum_read_seq = '', ''
#before alignment
len_before_segment = ref_start_limit - start
if reference_seq is None:
ref_seq_before = UNKNOWN_NUCLEOTYDE * len_before_segment
else:
ref_seq_before = str(reference_seq.seq[ref_start_limit - len_before_segment:ref_start_limit])
cum_ref_seq += ref_seq_before
cum_read_seq += NO_NUCLEOTYDE * len_before_segment
#in alignment
ssegment = 0 if start_segment is None else start_segment
esegment = len(ref_segments) - 1 if stop_segment is None else stop_segment
for isegment in range(ssegment, esegment + 1):
seg_type = segment_types[isegment]
seg_len = segment_lens[isegment]
ref_seg_start = ref_segments[isegment]
# when the segment is an insert there is no start, we have to calculate
if ref_seg_start is None:
try:
ref_seg_start = ref_segments[isegment + 1] - 1
except IndexError:
prev_seg_start = ref_segments[isegment -1]
prev_seg_len = segment_lens[isegment -1]
ref_seg_start = prev_seg_start + prev_seg_len
read_seg_start = read_segments[isegment]
if isegment == ssegment:
start_delta = read_start_in_ref - ref_seg_start
else:
start_delta = 0
if isegment == esegment:
end_delta = seg_len - read_stop_in_ref + ref_seg_start - 1
else:
end_delta = 0
if seg_type == INSERTION:
seg_ref_seq = DELETION_ALLELE * seg_len
read_start = read_seg_start + start_delta
read_end = read_start + seg_len #- end_delta
seg_read_seq = read_seq[read_start: read_end]
elif seg_type == DELETION or seg_type == SKIP:
ref_start = ref_seg_start + start_delta
ref_end = ref_start + seg_len - start_delta - end_delta
if reference_seq is not None:
seg_ref_seq = str(reference_seq.seq[ref_start: ref_end])
else:
seg_ref_seq = UNKNOWN_NUCLEOTYDE * (seg_len - start_delta - end_delta)
read_start = None
read_end = None
seg_read_seq = DELETION_ALLELE * (seg_len - start_delta - end_delta)
else:
ref_start = ref_seg_start + start_delta
ref_end = ref_start + seg_len - end_delta - start_delta
if reference_seq is not None:
seg_ref_seq = str(reference_seq.seq[ref_start: ref_end])
else:
seg_ref_seq = UNKNOWN_NUCLEOTYDE * (seg_len - end_delta - start_delta)
read_start = read_seg_start + start_delta
read_end = read_start + seg_len - end_delta - start_delta
seg_read_seq = read_seq[read_start: read_end]
cum_ref_seq += seg_ref_seq
cum_read_seq += seg_read_seq
#after alignment
len_after_alignment = stop - ali_ref_limits[1]
if reference_seq is None:
ref_seq_after = UNKNOWN_NUCLEOTYDE * len_after_alignment
else:
ref_seq_after = str(reference_seq.seq[ali_ref_limits[1] + 1:ali_ref_limits[1] + len_after_alignment + 1])
cum_ref_seq += ref_seq_after
cum_read_seq += NO_NUCLEOTYDE * len_after_alignment
assert len(cum_ref_seq) == len(cum_read_seq)
return cum_ref_seq, cum_read_seq
def _get_alleles_from_read(ref_allele, ref_pos, pileup_read):
'''It returns an allele from the read.
It returns a list with the alleles in the given position.
The returned allele can be an empty list if we're in a deletion.
If the position holds an insertion it will return two alleles, the
insertion and the nucleotide at that position.
'''
alleles = []
aligned_read = pileup_read.alignment
(ref_segments, read_segments, ref_limits, read_limits, segment_types,
segment_lens) = _get_cigar_segments_from_aligned_read(aligned_read)
located_segment = _locate_segment(ref_pos, ref_segments, segment_lens,
ref_limits)
if located_segment is None:
return []
else:
segment_index, segment_pos = located_segment
is_reverse = bool(aligned_read.is_reverse)
if segment_types[segment_index] == MATCH:
read_pos = _from_ref_to_read_pos(MATCH, ref_segments[segment_index],
read_segments[segment_index], ref_pos)
allele, qual = _get_raw_allele_from_read(aligned_read, read_pos)
if allele != ref_allele:
kind = SNP
else:
kind = INVARIANT
alleles.append((allele, kind, qual, is_reverse))
if segment_pos == IN_LAST_POS or segment_pos == IN_FIRST_AND_LAST:
#Is there an insertion in the next position?
next_read_pos = read_pos + 1
allele, kind, qual = _get_insertion(segment_index, segment_types,
next_read_pos, aligned_read,
segment_lens)
if kind is not None:
alleles.append((allele, kind, qual, is_reverse))
elif segment_types[segment_index] == DELETION:
if (segment_pos == IN_FIRST_POS or segment_pos == IN_FIRST_AND_LAST or
segment_pos == IN_LAST_POS):
read_pos1, read_pos2 = _read_pos_around_del(ref_segments,
read_segments,
segment_types,
segment_index,
ref_pos)
if segment_pos == IN_FIRST_POS or segment_pos == IN_FIRST_AND_LAST:
indel_length = segment_lens[segment_index]
allele = DELETION_ALLELE * (indel_length)
#in the deletion case the quality is the lowest of the
#bases that embrace the deletion
if aligned_read.qual:
qual0 = aligned_read.qual[read_pos1]
qual0 = _quality_to_phred(qual0)
qual1 = aligned_read.qual[read_pos2]
qual1 = _quality_to_phred(qual1)
qual = min((qual0, qual1))
else:
qual = None
kind = DELETION
alleles.append((allele, kind, qual, is_reverse))
if segment_pos ==IN_FIRST_AND_LAST or segment_pos == IN_LAST_POS:
#Is there an insertion in the next position?
allele, kind, qual = _get_insertion(segment_index, segment_types,
read_pos1, aligned_read,
segment_lens)
if kind is not None:
alleles.append((allele, kind, qual, is_reverse))
elif segment_types[segment_index] == SKIP:
#Is there an insertion in the next position?
read_pos1, read_pos2 = _read_pos_around_del(ref_segments,
read_segments,
segment_types,
segment_index,
ref_pos)
allele, kind, qual = _get_insertion(segment_index, segment_types,
read_pos1, aligned_read,
segment_lens)
if kind is not None:
alleles.append((allele, kind, qual, is_reverse))
elif segment_types[segment_index] == INSERTION:
pass #if we're in an insertion, it is returned in the last position
#of the previous match segment
return alleles, read_limits
def _quality_to_phred(quality):
'It transforms a qual chrs into a phred quality'
if quality is None:
return None
elif len(quality) == 1:
phred_qual = ord(quality) - 33
else:
phred_quals = [ord(qual) - 33 for qual in quality]
phred_qual = sum(phred_quals) / len(phred_quals)
if phred_qual == 93: #the character used for unknown qualities
phred_qual = None
return phred_qual
def _add_allele(alleles, allele, kind, read_name, read_group, is_reverse, qual,
mapping_quality, readgroup_info, pileup_read):
'It adds one allele to the alleles dict'
key = (allele, kind)
if key not in alleles:
alleles[key] = {'read_groups':[], 'orientations':[],
'qualities':[], 'mapping_qualities':[], 'reads':[]}
allele_info = alleles[key]
allele_info['read_groups'].append(read_group)
allele_info['orientations'].append(not(is_reverse))
allele_info['qualities'].append(qual)
allele_info['mapping_qualities'].append(mapping_quality)
allele_info['reads'].append(pileup_read)
def _normalize_read_edge_conf(read_edge_conf):
'It returns a dict with all valid keys'
platforms = ('454', 'sanger', 'illumina')
if read_edge_conf is None:
read_edge_conf = {}
for platform in platforms:
if platform not in read_edge_conf:
read_edge_conf[platform] = (None, None)
return read_edge_conf
def _add_pileup_reads(snv, reads):
'It adds the pileup reads for each snv_allele to the reads structure'
snv_name = snv['ref_name'] + '_' + str(snv['ref_position'])
if snv_name not in reads:
reads[snv_name] = {}
for allele, allele_info in snv['alleles'].items():
reads[snv_name][allele] = allele_info['reads']
def _check_read_length(read, position, read_edge_conf, read_groups_info,
default_bam_platform):
'If checks if the given pileup read covers all the snv extension'
aligned_read = read.alignment
read_start_in_ref, read_end_in_ref = _get_cigar_segments_from_aligned_read(aligned_read)[2]
if read_edge_conf:
platform, read_group = _get_platform_from_aligned_read(aligned_read,
read_groups_info,
default_bam_platform)
if platform in read_edge_conf:
edge_left, edge_right = read_edge_conf[platform]
if edge_left:
read_start_in_ref += edge_left
if edge_right:
read_end_in_ref -= edge_right
if read_start_in_ref <= position[0] and read_end_in_ref >= position[1] - 1:
return True
else:
return False
def _get_fixed_snv_start_vcf4(snv):
'''It corrects the start of the snv to the new vcf4 system
01234567 snp_caller vcf_format
ref atctgtag
read1 atccgtag snp in pos 3 snp in pos 3
read2 atctgcctag inser in pos 5 inser in pos 5
read3 atgcctag del in pos 2 del in pos 1
This is the result and
'''
allele_types = [allele[1] for allele in snv['alleles'].keys()]
snv_kind = _calculate_snv_kinds(allele_types)
if (snv_kind in (DELETION, INDEL) or snv_kind == COMPLEX and
DELETION in allele_types):
start = snv['ref_position'] - 1
else:
start = snv['ref_position']
return start
def _get_snv_end_position(snv):
'it returns the snv position plus the length of the allele'
end = snv['ref_position']
allele_types = [allele[1] for allele in snv['alleles'].keys()]
snv_kind = _calculate_snv_kinds(allele_types)
if (snv_kind in (INSERTION, SNP) or
(snv_kind == COMPLEX and INSERTION in allele_types)):
end += 1
else:
max_length = 0
for allele in snv['alleles'].keys():
allele, kind = allele
allele_length = len(allele)
if kind == DELETION and allele_length > max_length:
max_length = allele_length
end += max_length
return end
def _init_snv_block(snv, read_groups_info, default_bam_platform, read_edge_conf):
'It inits the data structure for the first snv of a block'
start = _get_fixed_snv_start_vcf4(snv)
end = _get_snv_end_position(snv)
reads = {}
_add_pileup_reads(snv, reads)
snv_block = {'start':start, 'end':end, 'snvs':[snv]}
if snv['ref_position'] != start:
# we're checking for the case in which a deletion increments the
# svn to the left
_remove_not_covering_reads(reads, (start, end), read_groups_info, default_bam_platform, read_edge_conf)
return snv_block, reads
def _remove_not_covering_reads(reads, position, read_groups_info,
default_bam_platform, read_edge_conf):
'''It checks that the reads in the snv cover the length of the snv.'''
for snv_name, alleles in reads.items():
for allele, pileup_reads in alleles.items():
valid_reads = [r for r in pileup_reads if _check_read_length(r, position, read_edge_conf, read_groups_info, default_bam_platform)]
if not valid_reads:
del reads[snv_name][allele]
else:
reads[snv_name][allele] = valid_reads
alleles = reads[snv_name].keys()
if not alleles or (len(alleles) == 1 and alleles[0][1] == INVARIANT):
del reads[snv_name]
def _make_snv_blocks(snvs, read_edge_conf=None, read_groups_info=None,
default_bam_platform=None):
'''It joins snvs that should be just one snv. e.g. a deletion that match
with another deletion in the same position.
'''
def add_one_to_left_if_snp(snv_block, reads):
'''It yields an snv_block,
but first it checks if we have to add
one base to the left because we have an SNP as the first snv of the
block. In that case it would check if there are enough reads covering'''
# if there are several SNPs together and the first one is an
# SNP we should add one base to the block in order to have
# a non-variant position as the first base of the new COMPLEX
# block
first_snv = snv_block['snvs'][0]
two_snps_together = (len(snv_block['snvs']) > 1 and
_is_snv_of_kind(first_snv, SNP))
# a complex allele would have an insertion and a deletion or an
# insertion and a snp in the same allele
# ref A- A-
# read GT -T
complex_kinds = [k for a, k in first_snv['alleles'].keys() if k == COMPLEX]
complex_allele_in_first_snv = True if complex_kinds else False
if (first_snv['ref_position'] == snv_block['start'] and
(two_snps_together or complex_allele_in_first_snv)):
snv_block['start'] -= 1
snv_span = (snv_block['start'], snv_block['end'])
_remove_not_covering_reads(reads, snv_span, read_groups_info,
default_bam_platform, read_edge_conf)
if not reads:
snv_block, reads = None, None
return snv_block, reads
snv_block, reads = None, None
for snv in snvs:
if snv_block is None:
snv_block, reads = _init_snv_block(snv, read_groups_info,
default_bam_platform,
read_edge_conf)
continue
snv_start = _get_fixed_snv_start_vcf4(snv)
snv_end = _get_snv_end_position(snv)
if snv_block['end'] + 1 <= snv_start:
# we do not add the snv to the block because the snv starts to the
# right of the current snv_block
snv_block, reads = add_one_to_left_if_snp(snv_block, reads)
if snv_block is not None:
yield snv_block
snv_block, reads = _init_snv_block(snv, read_groups_info,
default_bam_platform,
read_edge_conf)
else:
_remove_not_covering_reads(reads, (snv_block['start'], snv_end),
read_groups_info, default_bam_platform,
read_edge_conf)
if not reads:
if not _is_snv_of_kind(snv, SNP):
# we do not add the snv because there would be not enough reads
# covering the snv_block
snv_block, reads = add_one_to_left_if_snp(snv_block, reads)
if snv_block is not None:
yield snv_block
snv_block, reads = _init_snv_block(snv, read_groups_info,
default_bam_platform,
read_edge_conf)
else:
#we have decided to add the new snv to the block
if snv_block['end'] < snv_end:
snv_block['end'] = snv_end
snv_block['snvs'].append(snv)
else:
if snv_block:
snv_block, reads = add_one_to_left_if_snp(snv_block, reads)
if snv_block is not None:
yield snv_block
def get_insertions_in_position(reads, position):
'it returns the insertions that are found inside the given range'
insertions = set()
for segments in reads.values():
(ref_segments, read_segments, ref_limits, read_limits, segment_types,
segment_lens) = segments['segments']
for index, segment_type in enumerate(segment_types):
if segment_type == 1:
insert_start_in_ref = ref_segments[index - 1]
insert_end_in_ref = insert_start_in_ref + segment_lens[index]
if ((insert_start_in_ref > position[0] and insert_start_in_ref< position[1]) or
(insert_end_in_ref > position[0] and insert_end_in_ref< position[1])):
insertions.add((insert_start_in_ref, insert_end_in_ref))
return list(insertions)
def _is_snv_of_kind(snv, kind):
'True if it is a insertion false if not'
#This function works with the kinds used in the one column old codification
#DELETIONC, INSERTION, etc. Not in the new multicolumn kind specification
#VARIANT, INVARIANT
allele_types = [allele[1] for allele in snv['alleles'].keys()]
snv_kind = _calculate_snv_kinds(allele_types)
if snv_kind == kind:
return True
else:
return False
def _sum_snv_kinds(kind1, kind2):
'It calculates the result of the union of two kinds'
if kind1 == kind2:
return kind1
else:
if kind1 == INVARIANT:
return kind2
elif kind2 == INVARIANT:
return kind1
elif kind1 in [SNP, COMPLEX] or kind2 in [SNP, COMPLEX]:
return COMPLEX
else:
return INDEL
def _calculate_snv_kinds(kinds):
'It returns the snv kind for the given feature'
if len(kinds) == 1:
return kinds[0]
kind = kinds[0]
for index in range(1, len(kinds)):
kind = _sum_snv_kinds(kind, kinds[index])
return kind
def _remove_allele_from_alignments(alignments, min_num_reads_for_allele):
''' It removes alignments/alleles taking into account the times it appears
min_num_reads_for_allele'''
allele_count = {}
for ref, allele in alignments.values():
if allele not in allele_count:
allele_count[allele] = 0
allele_count[allele] +=1
for read_name, alignment in alignments.items():
read_allele = alignment[1]
if allele_count[read_allele] < min_num_reads_for_allele:
del alignments[read_name]
def _join_snvs(snv_block, min_num_alleles, min_num_reads_for_allele,
min_quality, reference_seq=None):
'It joins the snvs that should be together'
snvs = snv_block['snvs']
if len(snvs) == 1 and _is_snv_of_kind(snvs[0], SNP):
return snvs[0]
else:
block_start = snv_block['start']
block_end = snv_block['end']
# collect all the reads and its alignment
reads = {}
alignments = {}
allele_kinds = {}
for snv in snvs:
for allele, allele_info in snv['alleles'].items():
allele_kind = allele[1]
for index in range(len(allele_info['reads'])):
name = allele_info['reads'][index].alignment.qname
if name in reads:
continue
read = allele_info['reads'][index]
read_group = allele_info['read_groups'][index]
orientation = allele_info['orientations'][index]
quality = allele_info['qualities'][index]
mapping_quality = allele_info['mapping_qualities'][index]
reads[name] = {'read': read,
'read_group': read_group,
'orientation': orientation,
'quality': quality,
'mapping_quality': mapping_quality}
# do the multiple alignments
for read_name in reads:
if read_name not in allele_kinds:
allele_kinds[read_name] = []
allele_kinds[read_name].append(allele_kind)
if read_name not in alignments:
alignment = _get_alignment_section(reads[read_name]['read'],
block_start, block_end,
reference_seq=reference_seq)
alignments[read_name] = alignment
# we need to remove the reads that do not cover the alignment in its
# complete span
for read_name in list(reads.keys()):
aligned_read = alignments[read_name][1]
if NO_NUCLEOTYDE in aligned_read:
del alignments[read_name]
del reads[read_name]
_remove_allele_from_alignments(alignments, min_num_reads_for_allele)
if alignments:
malignment = _make_multiple_alignment(alignments, reads)
# We create the new alleles that span the complete snv_block
alleles = {}
ref_allele = ''.join(malignment['reference'])