This repository has been archived by the owner on Apr 13, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
aDNA_Toolbox.py
1834 lines (1334 loc) · 75.2 KB
/
aDNA_Toolbox.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 python3
'''
Author: Gustaw Eriksson
Date: 2019-06-03
aDNA Toolbox is a program including a variation of functions with which allows the user run a limited set of analysis
on BAM/SAM-files. The program is to be used when running a proof-of-concept analysis on ancient DNA when studying the
prevelance of CT-substitution on aDNA sequence end, determining distance shortest distance between 3' and 5' ends of
overlapping sequences, outputting a graphical outline of sequence alignment between read and reference sequence as well
as reconstructing reference sequences of the ancient DNA molecule from the MD-tag and CIGAR-string.
The script requires a BAM-file, the Samtools program installed locally or in an environment and it is runned by using
argparse. For further information on how to run the program using argparse, please write "./aDNA_Toolbox -h" in the
command terminal.
In case of further questions or bugs, please contact me at [email protected]
'''
### Import sys to be able to exit script during error
import sys
### Import collection to set up OrderedDict and calculate frequence of distance to closest 3' on reverse strand
import collections
### Importing argparse for command line interface and subprocess to run samtools
import argparse, subprocess
### Importing numpy and matplotlib to create plots
import matplotlib.pyplot as plt
import numpy as np
### ARGPARS BLOCK ###
### Args.parse to input/output files as well as showing info to user
usage ='Run the program by adding flags and arguments for the desired function. \
For information about each function, see information about each flag.'
parser = argparse.ArgumentParser(description=usage)
parser.add_argument(
'-v', '--version',
action='version',
version='%(prog)s 1.0'
)
parser.add_argument(
'-b', '--b',
help='User BAM input file',
metavar='[BAM_FILE]',
dest='bam_file',
)
parser.add_argument(
'-rr', '--rr',
help='Output reconstructed reference seq. If output file is not supplied, output is printed in terminal window',
dest='output_reconstruct_ref',
action='store_true'
)
parser.add_argument(
'-c', '--c',
help='Output consensus sequence of reads. If output file is not supplied, output is printed in terminal window',
dest='output_consensus_seq',
action='store_true'
)
parser.add_argument(
'-ct', '--ct',
help='Output plot illustrating C to T substitution frequeny close to read ends. Outputs plot in user window',
dest='call_CT_substitution',
action='store_true'
)
parser.add_argument(
'-ag', '--ag',
help='Output plot illustrating A to G substitution frequeny close to read ends. Outputs plot in user window',
dest='call_AG_substitution',
action='store_true'
)
parser.add_argument(
'-freq', '--freq',
help='Output plot illustrating nucleotide frequeny close to read ends. Outputs plot in user window',
dest='call_nt_freq',
action='store_true'
)
parser.add_argument(
'-frw', '--frw',
help='Allow forward reads to construct consensus sequence',
dest='forward_reads_allow',
action='store_true'
)
parser.add_argument(
'-acl', '--acl',
help='Allow all consensus sequence lengths, i.e allow not fully covered consensus sequences',
dest='all_cons_lengths',
action='store_true'
)
parser.add_argument(
'-rf', '--rf',
help='Allow reads with insertions and deletions in analysis',
dest='remove_filter',
action='store_true'
)
parser.add_argument(
'-over', '--over',
help="Output figure of 3'-5' distance of overlapping sequences. Outputs plot in user window",
dest='output_figure',
action='store_true'
)
parser.add_argument(
'-r', '--r',
help="X-axis range of output 3'-5' distance of overlapping sequences histogram. Default is -100-100",
metavar='[X-AXIS_RANGE]',
dest='range_overlap',
)
parser.add_argument(
'-o', '--o',
help='Output file',
metavar='[OUTPUT_FILE]',
dest='output_file',
)
args = parser.parse_args()
### FUNCTIONS BLOCK #####
### Function to seperate letters and numbers
def seperate_letters_numbers(cigar_md):
## String variables to store digits and letters
digit = ''
alpha = ''
## List to store seperated digits and letters char
cigar_md_list = []
## Excludes 'MD:Z:'
if cigar_md[:5] == 'MD:Z:':
cigar_md = cigar_md[5:]
## Looping over each character in the MD-tag string
for char in cigar_md:
## Seperate and store digits in digit as string
if char.isdigit() == True:
digit += char
## '0' means zero matches and is excluded
if digit[0] == '0':
digit = ''
## Seperate and store letters '^' in alpha
elif char.isalpha() == True or char == '^':
alpha += char
alpha = str(alpha)
## Letters fall after digits, therefore append to MD-list
## is done after letter seperation
if digit != '':
## Digit is turned to integer for future analysis
digit = int(digit)
## Appending to MD-list and cleaning variable
cigar_md_list.append(digit)
digit = ''
cigar_md_list.append(alpha)
alpha = ''
## If no digit is found before the letter
else:
## Appending to MD-list and cleaning variable
cigar_md_list.append(alpha)
alpha = ''
## If the last character of the md is a digit, it is turned to a integer
## and appended to the MD-list
if digit != '':
digit = int(digit)
cigar_md_list.append(digit)
## Function returns the MD-list
return cigar_md_list
### Function to iterate over list of seperated MD-tag and read sequence to return a reconstructed
### reference sequence
def reference_seq(sep_md, sep_cigar, read_seq):
## Setting up variables. ref_seq is a empty string for the created sequence, while
## start- and end_seq_position are position variables when creating the sequence.
ref_seq = ''
start_seq_position = 0
end_seq_position = 0
item_index = 0
ref_seq_extension_count = 0
## Variables to handle insertions.
insertion_seq_position_count = 0
insertion_seq_position = []
insertion_seq_count = []
insertion = False
insertions_present = 0
insertions_inserted = 0
## Deletion is a flag used when deletion tag '^' is detected in list loop
deletion = False
deletion_seq_count = []
deletion_inserted = 0
#If an insertion is present and found in the CIGAR string:
if 'I' in sep_cigar:
## Make insertion flag True
insertion = True
## Loop over each item in CIGAR list
for item in sep_cigar:
## If digit is found
if isinstance(item, int) == True:
## The digit is assigned to the digit variable
digit = item
## The sequence position is defined by the sum of digit values
insertion_seq_position_count += item
## If a letter is found and it is a insertion 'I'
elif item == 'I':
## Count the number of insertions found
insertions_present += 1
## The qurrent insertion_seq_count is appended to a list if insertion if found
insertion_seq_position.append(insertion_seq_position_count)
## The number of insertion, i.e. digit before 'I' is appended to a list
insertion_seq_count.append(digit)
for count in insertion_seq_count:
ref_seq_extension_count += count
#If an deletion is present and found in the CIGAR string:
if 'D' in sep_cigar:
## Make deletion flag True
## Loop over each item in CIGAR list
for item in sep_cigar:
## If digit is found
if isinstance(item, int) == True:
## The digit is assigned to the digit variable
digit = item
## If a letter is found and it is a deletion 'D'
elif item == 'D':
## The number of deletions, i.e. digit before 'D' is appended to a list
deletion_seq_count.append(digit)
## Loop over each item in MD-list
for item in sep_md:
item_index += 1
## The digits in the list are integers, so true if digit in item. The digits
## also imply that the reference and read sequences are matching
if isinstance(item, int) == True:
## The end_seq_position will be the current item
end_seq_position += item
if item_index == len(sep_md):
end_seq_position += ref_seq_extension_count
## The ref_seq string will be extended with the matched read sequence
## from the start to end position which are are applied on read sequence string
ref_seq += read_seq[start_seq_position:end_seq_position]
## The start position is updated by adding the item
start_seq_position += item
## The deletion flag is turned back to False because it goes from letter to digit
deletion = False
## If the '^' deletion tag is detected, the deletion flag is turned to True
elif item == '^':
deletion = True
## The Indels in the list are string, so true if letter in item. The letters
## imply that the nucleotide will be in the reference sequprint(item_index, sep_md[len(sep_md)-1])ence but not in read sequence
elif item.isalpha() == True:
## If there is a deletion, the flag is true. The nucleotide is in the reference but not
## in the read sequence
if deletion == True:
ref_seq += item
## Check CIGAR if number of deletions match it of the MD-tag. If it does not match. The next
## letter will also be treated as if being a deletion. If they do match, the deletion flag
## is turned to False and the number of deletion positions is extended by 1.
if deletion_seq_count[deletion_inserted] == 1:
deletion = False
deletion_inserted += 1
deletion_flag_working = 'OK'
## The deletion is False so the nucleotide is a insertion. The nucleotide is in the reference
## but does not match the nucleotide found in the read sequence. Start and end sequence
## are added with 1.
elif deletion == False:
if insertion == True and start_seq_position >= insertion_seq_position[insertions_inserted]:
#Extend the start and end seq position with number of insertions
end_seq_position += insertion_seq_count[insertions_inserted]
ref_seq += read_seq[start_seq_position:end_seq_position]
start_seq_position += insertion_seq_count[insertions_inserted]
insertions_inserted += 1
if insertions_inserted == len(insertion_seq_count):
insertion = False
start_seq_position += 1
end_seq_position += 1
ref_seq += item
return ref_seq
## Function to edit the reference sequence with the CIGAR string
def cigar_modification_ref(sep_cigar, ref_seq):
## Setting up variable to keep count of CIGAR position
seq_position = 0
mod_ref_seq = ref_seq
## Loop over each item in the CIGAR list
for item in sep_cigar:
## The digits in the list are integers, so true if digit in item. The digits
## are found both before matches, insertions and deletions. Therefore they are
## stored in a variable till letter is identified.
if isinstance(item, int) == True:
digit = item
## The if statement checks if the item is a letter.
elif item.isalpha() == True:
## If the item is either M or D, the sequence position is extended with the digit
## found before the M or D letter
if item == 'M' or item == 'D':
seq_position += digit
## If the item is I i.e. insertion
elif item == 'I':
#To be able to edit the mod_ref_seq, it is turned to a list
mod_ref_seq = list(mod_ref_seq)
#If the digit before the I
if digit == 1:
## The current position in the reference seq, which is where the insertion is,
## will be changed from current nucleotide to '*' to show insertion
mod_ref_seq[seq_position] = '*'
## The edited list is returned to being a string
mod_ref_seq = ''.join(mod_ref_seq)
## The seq position if extended with 1
seq_position += digit
elif digit > 1:
## end_insertion_position is used because if there is >1 insertions, a range of
## nucleotides have to be changed from nucleotide to '*'
end_insertion_position = seq_position + digit
## The reference sequence positions that will be changed are set in the variable
## target position which is a list of position from seq to end insertion position
target_position = list(range(seq_position, end_insertion_position))
## Looping over target position list
for seq_position in target_position:
## For each position in target position list, the same position in the mod ref seq list
## will be changed from nucleotide to '*' to mark the insertion
mod_ref_seq[seq_position] = '*'
## The edited list is returned to being a string
mod_ref_seq = ''.join(mod_ref_seq)
## The seq position if extended with the number of insertions
seq_position += digit
return mod_ref_seq
def cigar_modification_read(sep_cigar, read_seq):
## Setting up variable to keep count of CIGAR position
seq_position = 0
mod_read_seq = read_seq
## Loop over each item in the CIGAR list
for item in sep_cigar:
## The digits in the list are integers, so true if digit in item. The digits
## are found both before matches, insertions and deletions. Therefore they are
## stored in a variable till letter is identified.
if isinstance(item, int) == True:
digit = item
## Check is item is alphabetic
elif item.isalpha() == True:
## Check CIGAR tag
if item == 'M' or item == 'I':
seq_position += digit
elif item == 'D':
mod_read_seq = list(mod_read_seq)
if digit == 1:
mod_read_seq.insert(seq_position, '*')
mod_read_seq = ''.join(mod_read_seq)
seq_position += digit
elif digit > 1:
insertion_list = ['*'] * digit
mod_read_seq[seq_position:seq_position] = insertion_list
mod_read_seq = ''.join(mod_read_seq)
seq_position += digit
return mod_read_seq
## Function to output graphical alignment between reference and read sequence after
## MD-tag and CIGAR-string modification
def graphic_match_seq(mod_ref_seq, mod_read_seq):
graphic_match_seq = ''
mod_read_seq = list(mod_read_seq)
mod_ref_seq = list(mod_ref_seq)
## Parsing over sequences and matching nucleotides
for ref, read in zip(mod_ref_seq, mod_read_seq):
if ref == read:
graphic_match_seq += '.'
elif ref == '*':
graphic_match_seq += read
elif read == '*':
graphic_match_seq += '*'
elif ref != read:
graphic_match_seq += read
return graphic_match_seq
## Function to calculate the shortest distance between 3' and 5' ends of overlapping sequences
def calculate_distance_closest_3(samfile, range_overlap):
### Set length of samfile list
len_samfile = len(samfile)
### Creating list to store reads of same chromosome
same_chr_reads = []
### Creating two list to store forward and reverse reads
frw_reads = []
rev_reads = []
### List to store the distance to closest 3' on the reverse strand
distance_closest_3 = []
#########number_of_0 = 0
### Setting flags and variables to seperate reads and control first instances
first_chr = True
first_read = False
seperate_by_flag = False
new_chr_read = ''
n_same_chr_reads = 0
n_f_read = 0
len_same_chr_reads = 0
len_frw_reads = 0
stop_script = False
first_start_pos_frw_read = 0
first_frw_read = True
first_end_pos_rev_read = 0
first_rev_read = True
### Iterating over the list
for read in samfile:
### When last relevant chromosome has been, flag is turned to False and
### script is terminated. Script only handles autosomal, sex and mt chromosome
if stop_script == False:
### Setting list item to string and spliting item in list after '\\tt'.
read = str(read)
read = read.split('\\t')
### Assigning the chromosome to a variable called chr
chr = read[2]
## Seperate reads according to chromosome
if first_read == True or first_chr == True or chr == current_chr:
## Append new_chr_read to list, i.e. the first read with the new chr
if first_read == True:
same_chr_reads.append(new_chr_read)
new_chr_read = ''
## Turning first_read flag to False
first_read = False
## Setting current chr which is seperated
current_chr = chr
## Appending the read to list which stores reads of same chr
## Filter out empty items
same_chr_reads.append(read)
## Turning first_chr flag to False
first_chr = False
## When the next chromosome is reached in the bam, the former chromosome is seperated by flag
elif chr != current_chr:
## Save the read in a variable which is then appended to the same_chr_reads list when currenct chr changes
new_chr_read = read
## Turning first_read flag to True
first_read = True
## Change current_chr to new chr
current_chr = chr
## Set length of same_chr_reads list
len_same_chr_reads = len(same_chr_reads)
## When chr has changed, start looping over the
for chr_read in same_chr_reads:
## Filter out empty items
if chr_read != '':
if len(current_chr) > 2:
stop_script = True
## Keep count on number of reads
n_same_chr_reads += 1
## Assigning the start position and seq to seperate variables
flag = int(chr_read[1])
start_pos_seq = int(chr_read[3])
seq = chr_read[9]
### Length of the sequence is determined
length_seq = len(seq)
### Depending on if the read is forward or reverse read, which is seen by the flag (read[1]),
### the end position of the sequence will be (-) the start position sequence in reverse reads.
### The end position of the sequence is later used to determine the distance to closest 3'
### on reverse strand.
## If it is the last read of the same chr read list, then next step is to parse thorugh the seperate frw and rev lists
if n_same_chr_reads == len_same_chr_reads:
## Restore n_same_chr_reads and len_same_chr_reads to 0
n_same_chr_reads = 0
len_same_chr_reads = 0
## Last read also have to be seperated
if flag is 0:
## Append forward reads to seperate list
frw_reads.append(chr_read)
elif flag is 16:
## Seperate reverse from forward reads by appending to reverse list
rev_reads.append(chr_read)
### Loop over every forward read in the forward list and match it to a reverse read which differs
### the least in regard to distance to 3' on the reverse read. Furthermore, save the distance to
### to later output this in an histogram.
## Set length of frw_reads list
len_frw_reads = len(frw_reads)
for f_read in frw_reads:
## Variables to count distance to 3' on reverse strand
current_distance = None
shortest_distance = None
shortest_abs_distance = None
first_match = True
## Count number of f_reads
n_f_read += 1
## Store the start position and chromosome in variables
f_chr = f_read[2]
start_pos_seq = int(f_read[3])
## For every f_read we loop over the reverse list
for r_read in rev_reads:
## Store the chromosome in variables
r_chr = r_read[2]
## Store the end position in a variable
end_pos_seq = int(r_read[3])
## The distance is calculated bu substracting end position with start position.
#current_distance = int(start_pos_seq - end_pos_seq)
current_distance = int(end_pos_seq - start_pos_seq)
## Abs is used to turn eventuall negative numbers to positive.
current_abs_distance = abs(current_distance)
if current_distance <= -range_overlap:
rev_reads.remove(r_read)
elif current_distance >= range_overlap:
break
else:
## The first match flag lets the first read be the shortest_distance until shorter is found
if first_match == True or current_abs_distance <= shortest_abs_distance:
## First match flag is turned to false
first_match = False
## If the current read distance is shorter than current shortest, then it will be assigned
## as the current shortest.
shortest_distance = current_distance
## Turn shortest distance to positive numbers so it can be used in the if-statement
shortest_abs_distance = abs(shortest_distance)
if n_f_read == len_frw_reads:
print('CHROMOSOME', f_chr)
## Restore n_same_chr_reads and len_same_chr_reads to 0:
n_f_read = 0
len_frw_reads = 0
## Restore first_frw_read flag to True
first_frw_read = True
## Restore the same_chr, frw and rev list to empty states. This is done to decrease memory and increase speed
same_chr_reads.clear()
frw_reads.clear()
rev_reads.clear()
## Append the shortest distance to 3' on reverse strand to the list of shortest distance to 3'
if shortest_distance != None:
distance_closest_3.append(shortest_distance)
## First check if flag is 0 (frw read) or 16 (rev read) to filter out unmapped reads (Flag = 4)
elif flag is 0:
frw_reads.append(chr_read)
elif flag is 16:
## Seperate reverse from forward reads by appending to reverse list
rev_reads.append(chr_read)
return(distance_closest_3)
## Function to call IUPAC nucleotide codes and construct consensus sequence between
## two overlapping reads
def consensus_seq_2_reads(read_nt, overlap_nt):
if read_nt == overlap_nt:
consensus_nt = read_nt
elif overlap_nt == ' ':
consensus_nt = ' '
elif read_nt == '*' or overlap_nt == '*':
if read_nt == '*':
consensus_nt = overlap_nt
elif overlap_nt == '*':
consensus_nt = read_nt
else:
consensus_nt = '*'
elif read_nt != overlap_nt:
non_matching_nt = read_nt + overlap_nt
if non_matching_nt == 'AG' or non_matching_nt == 'GA':
consensus_nt = 'R'
elif non_matching_nt == 'CT' or non_matching_nt == 'TC':
consensus_nt = 'Y'
elif non_matching_nt == 'GC' or non_matching_nt == 'CG':
consensus_nt = 'S'
elif non_matching_nt == 'AT' or non_matching_nt == 'TA':
consensus_nt = 'W'
elif non_matching_nt == 'GT' or non_matching_nt == 'TG':
consensus_nt = 'K'
elif non_matching_nt == 'AC' or non_matching_nt == 'CA':
consensus_nt = 'M'
elif 'N' in non_matching_nt:
consensus_nt = 'N'
return(consensus_nt)
## Function to call IUPAC nucleotide codes and construct consensus sequence between
## more than two overlapping reads by allowing more IUPAC codes. Uses the function
## above which creates a consensus sequence of the two first overlapping sequences.
def consensus_seq_many_reads(consensus_nt, overlap_nt, first_read_seq, nt_position):
if consensus_nt == overlap_nt:
new_consensus_nt = consensus_nt
elif overlap_nt == ' ' and consensus_nt == ' ':
new_consensus_nt = first_read_seq[nt_position-1]
elif overlap_nt == ' ':
new_consensus_nt = consensus_nt
elif consensus_nt == ' ':
new_consensus_nt = consensus_seq_2_reads(first_read_seq[nt_position-1], overlap_nt)
elif consensus_nt != overlap_nt:
non_matching_nt = consensus_nt + overlap_nt
if non_matching_nt == 'AG' or non_matching_nt == 'GA':
new_consensus_nt = 'R'
elif non_matching_nt == 'CT' or non_matching_nt == 'TC':
new_consensus_nt = 'Y'
elif non_matching_nt == 'GC' or non_matching_nt == 'CG':
new_consensus_nt = 'S'
elif non_matching_nt == 'AT' or non_matching_nt == 'TA':
new_consensus_nt = 'W'
elif non_matching_nt == 'GT' or non_matching_nt == 'TG':
new_consensus_nt = 'S'
elif non_matching_nt == 'AC' or non_matching_nt == 'CA':
new_consensus_nt = 'M'
elif non_matching_nt == 'ST' or non_matching_nt == 'YG' or non_matching_nt == 'KC':
new_consensus_nt = 'B'
elif non_matching_nt == 'RT' or non_matching_nt == 'WG' or non_matching_nt == 'KA':
new_consensus_nt = 'D'
elif non_matching_nt == 'MT' or non_matching_nt == 'WC' or non_matching_nt == 'YA':
new_consensus_nt = 'H'
elif non_matching_nt == 'MG' or non_matching_nt == 'RC' or non_matching_nt == 'SA':
new_consensus_nt = 'V'
elif 'B' in non_matching_nt or 'D' in non_matching_nt or 'H' in non_matching_nt or 'V' in non_matching_nt:
new_consensus_nt = 'N'
else:
new_consensus_nt = consensus_nt
return(new_consensus_nt)
## Function to output a consensus sequence from overlapping sequences.
def output_consencus_seq(overlapping_reads, len_overlap_reads):
## Setting variables and flags
first_overlap = True
first_consensus = True
n_overlap_reads = 0
edited_seq = None
nr_overlap_read = 0
## Creating lists for modified overlapping reads and consensus list
overlapping_seq = []
overlapping_seq_edited = []
consensus_seq_list = []
## Creating OrderedDict to output read ID and sequence as dictionary
reads_consensus_dict = collections.OrderedDict()
for overlap_read in overlapping_reads:
## Count number of loops of overlapping reads
n_overlap_reads += 1
read = overlap_read
### Assining variable to each needed element of the item
cigar = read[5]
read_seq = read[9]
### Run CIGAR through a function which seperates letters and digits and return a list
sep_cigar = seperate_letters_numbers(cigar)
### Modify the read sequence with CIGAR, i.e. add '-' for deletion position in CIGAR
mod_read_seq = cigar_modification_read(sep_cigar, read_seq)
### Append the modified read seq to list of overlapping seq
overlapping_seq.append(mod_read_seq)
## When the loop has finished, start looping over overlapping_seq and read list
## and restore overlapping read count variables
if len_overlap_reads == n_overlap_reads:
## Restoring counting variables
##len_overlap_reads = 0
n_overlap_reads = 0
## Looping over overlapping_seq and overlapping_reads lists
for read, seq in zip(overlapping_reads, overlapping_seq):
## If it is the first overlap read/seq, then it is the current target read/seq
if first_overlap == True:
## Turn flag to false
first_overlap = False
## Save the read and seq to two seperate variables to be used later
first_read_head = read
first_read_seq = seq
## Assing start and end position of the target read
first_read_start = int(first_read_head[3])
first_read_end = first_read_start + len(first_read_seq)
## Appending first read head and seq to reads_consensus_dict
reads_consensus_dict['TARGET SEQ'] = first_read_seq
## If it is not the first overlap read/seq, i.e. read which overlaps the target read
elif first_overlap == False:
## Counting number of overlaps to add in reads_consensus_dict
n_overlap_reads += 1
## Calculating difference between start/end position of target and overlap read
overlap_diff_start = (first_read_start - int(read[3]))
overlap_diff_end = (first_read_end - (int(read[3]) + len(seq)))
## Editing the sequence string using overlap diff variables
## Checking overlap diff at start position,
## If overlap diff at start is >0, then edit overlapping seq
if overlap_diff_start > 0:
## Cut out seq before overlap positon
edited_seq = seq[overlap_diff_start:]
## If overlap diff at start is <0 then edit the target seq.
## The editing happens in later stage when all other seq have been edited,
## therefore the overlap is appended to a list.
elif overlap_diff_start < 0:
edited_seq = (' ' * abs(overlap_diff_start)) + seq
## Checking overlap diff at end position
## If overlap diff at the end is >0 then edit the target seq.
## The editing happens in later stage when all other seq have been edited,
## therefore the overlap is appended to a list.
if overlap_diff_end > 0:
###overlap_diff_end_first_read.append(overlap_diff_end)
if edited_seq == None:
edited_seq = seq + (' ' * overlap_diff_end)
elif edited_seq != None:
edited_seq = edited_seq + (' ' * overlap_diff_end)
## If overlap diff at end is <0, then edit overlapping seq
elif overlap_diff_end < 0:
## If the seq has not been edited at its start
if edited_seq == None:
## Cut out seq after overlap position
edited_seq = seq[:(len(seq) + overlap_diff_end)]
## If the seq has been edited at its start
elif edited_seq != None:
## Cut out seq after overlap position
edited_seq = edited_seq[:len(edited_seq) + overlap_diff_end]
if overlap_diff_start == 0 and overlap_diff_end == 0:
edited_seq = seq
## Appending edited sequence to second list of edited sequences
overlapping_seq_edited.append(edited_seq)
## Appending seq to reads_consensus_dict
overlap_nr = str(n_overlap_reads)
overlap_id = 'OVERLAP SEQ' + overlap_nr
reads_consensus_dict[overlap_id] = edited_seq
## After appending the edited seq to list of edited seq, reset the edited seq variable
edited_seq = None
for overlap_seq in overlapping_seq_edited:
if first_consensus == True:
first_consensus = False
for read_nt, overlap_nt in zip(first_read_seq, overlap_seq):
consensus_nt = consensus_seq_2_reads(read_nt, overlap_nt)
consensus_seq_list.append(consensus_nt)
elif first_consensus == False:
## Nucleotide position counter set to 0
nt_position = 0
for consensus_nt, overlap_nt in zip(consensus_seq, overlap_seq):
## Count nucleotide position in seq
nt_position += 1
new_consensus_nt = consensus_seq_many_reads(consensus_nt, overlap_nt, first_read_seq, nt_position)
consensus_seq_list.append(new_consensus_nt)
consensus_seq = ''.join(consensus_seq_list)
consensus_seq_list *= 0
## Add consensus seq to reads_consensus_dict
reads_consensus_dict['CONSENSUS SEQ'] = consensus_seq
return(reads_consensus_dict)
## Determining shortest distance between overlapping reads to output in file
def set_shortest_3_distance(overlapping_reads):
first_read = True
first_distance = True
for read in overlapping_reads:
if first_read == True:
five_end = int(read[3])
first_read = False
elif first_read == False:
three_end = int(read[3])
distance = three_end - five_end
if first_distance == True:
first_distance = False
shortest_distance = distance
elif first_distance == False:
abs_shortest_distance = abs(shortest_distance)
abs_distance = abs(distance)
if abs_distance < abs_shortest_distance:
shortest_distance = distance
else:
continue
return(shortest_distance)
### SCRIPT BLOCK ###
if args.bam_file == None or '.bam' not in args.bam_file:
print('PLEASE ADD BAM FILE')
sys.exit()
### Subprocess to for BAM to SAM conversion
samfile = subprocess.check_output(['samtools', 'view', args.bam_file])