This repository has been archived by the owner on Jul 18, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsummarise_snps.py
executable file
·1451 lines (1093 loc) · 43.2 KB
/
summarise_snps.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
#/usr/bin/env python
##################
# Import modules #
##################
import string, re
import os, sys, getopt, math
from random import *
from Bio import SeqIO
from Bio.Seq import Seq
from Bio.Alphabet import IUPAC, Gapped
from Bio.SeqRecord import SeqRecord
from Bio import AlignIO
from Bio.Align import Generic
from modules.Si_nexus import *
from modules.Si_SeqIO import *
#from scipy import stats
import fisher
#from guppy import hpy
from optparse import OptionParser, OptionGroup
##########################
# Error message function #
##########################
def DoError(errorstring):
print "\nError:", errorstring
print "\nFor help use -h or --help\n"
sys.exit()
##########################################
# Function to Get command line arguments #
##########################################
def get_user_options():
usage = "usage: %prog [options]"
version="%prog 1.0. Written by Simon Harris, Wellcome Trust Sanger Institute, 2010"
parser = OptionParser(usage=usage, version=version)
group = OptionGroup(parser, "Required")
group.add_option("-i", "--input", action="store", dest="inputfile", help="Input file name", default="")
group.add_option("-r", "--reference", action="store", dest="ref", help="Name of reference strain", default="")
parser.add_option_group(group)
group = OptionGroup(parser, "Optional")
group.add_option("-e", "--embl", action="store", dest="embl", help="Embl/genbank annotation file for reference strain (for dN/dS etc.)", default="")
group.add_option("-o", "--output", action="store", dest="outfile", help="Output file prefix", default="")
group.add_option("-t", "--tab", action="store_true", dest="tabfile", help="Produce tab files of snp locations", default=False)
group.add_option("-a", "--align", action="store_true", dest="align", help="Produce snp alignment file (in phylip format)", default=False)
group.add_option("-E", "--exclude", action="store", dest="exclude", help="Exclude sequences from SNP alignment if they are less thanINT% mapped [Default= %default]", default=50, type="float", metavar="int")
group.add_option("-p", "--phylogeny", action="store_true", dest="raxml", help="Run phylogeny with RAxML", default=False)
group.add_option("-v", "--asrv", action="store", dest="asrv", help="Method of correction for among site rate variation (optional) [Choices = GAMMA, CAT, CAT_GAMMA, MIX] [Default = %default]", default="GAMMA", type="choice", choices=["GAMMA","CAT", "CAT_GAMMA", "MIX"])
group.add_option("-I", "--pinvar", action="store_true", dest="pinvar", help="Use correction for proportion of invariant sites", default=False)
group.add_option("-F", "--frequencies", action="store_true", dest="f", help="Use empirical base frequencies (protein models only)", default=False)
group.add_option("-w", "--overwrite", action="store_true", dest="overwrite", help="Overwrite old RAxML files without warning", default=False)
group.add_option("-b", "--bootstrap", action="store", dest="bootstrap", help="Number of bootstrap replicates (0 = do not run bootstrap). [Default= %default]", default=100, type="int", metavar="int")
group.add_option("-f", "--fast", action="store_true", dest="fast", help="Use fast bootstrap method", default=False)
group.add_option("-l", "--LSF", action="store_true", dest="LSF", help="Run bootstrap replicates over LSF (does not apply with fast bootstrap method)", default=False)
group.add_option("-g", "--gaps", action="store_true", dest="gaps", help="Gaps (-) are real", default=False)
group.add_option("-G", "--genetic_code", action="store", dest="genetic_code_number", help="Genetic code number to use. Choose from 1: Standard, 4: Mycoplasma. Default is 1", default=False, type="choice", choices=[1, 4])
parser.add_option_group(group)
return parser.parse_args()
################################
# Check command line arguments #
################################
def check_input_validity(options, args):
if options.ref=='':
DoError('No reference selected')
elif options.inputfile=='':
DoError('No input file selected')
elif not os.path.isfile(options.inputfile):
DoError('Cannot find file '+options.inputfile)
elif options.embl!='' and not os.path.isfile(options.embl):
DoError('Cannot find file '+options.embl)
elif options.bootstrap>10000 or options.bootstrap<0:
DoError('Number of bootstrap replicates (-b) must be between 0 (do not run bootstrap) and 10,000')
elif options.exclude>=100 or options.exclude<0:
DoError('Exclude percentage must be an float between 0 and 100')
if options.outfile=='':
options.outfile=options.ref.split("/")[-1].split(".")[0]
if options.raxml and not options.align:
options.align=True
while os.path.isfile(options.outfile+".out") and options.overwrite==False:
outopt=""
outopt=raw_input('\nOutput files with chosen prefix already exist.\n\nWould you like to overwrite (o), choose a new output file prefix (n) or quit (Q): ')
if outopt=='Q':
sys.exit()
elif outopt=="o":
break
elif outopt=="n":
options.outfile=raw_input('Enter a new output file prefix: ')
return
def split_len(seq, length):
return [seq[i:i+length] for i in range(0, len(seq), length)]
#############################################
# Function to create and embl style ID line #
#############################################
def embl_style_id(sequence):
emblstring="ID XX000001; SV 1; circular; genomic DNA; STD; PRO; "+str(len(sequence.strip()))+" BP.\nXX"
return emblstring
#############################################
# Function to create and embl style ID line #
#############################################
def embl_style_header(sequence):
emblstring="FH Key Location/Qualifiers"
emblstring=emblstring+"\nFH"
emblstring=emblstring+"\nFT source 1.."+str(len(sequence.strip()))
return emblstring
####################################################
# Function to create an embl style sequence format #
####################################################
def embl_style_sequence(sequence):
emblstring="XX\n"
sequence=sequence.strip().lower()
basehash={"a":0,"c":0,"g":0,"t":0,"Other":0}
for x in sequence:
if basehash.has_key(x):
basehash[x]=basehash[x]+1
else:
basehash["Other"]=basehash["Other"]+1
emblstring=emblstring+"SQ Sequence "+str(len(sequence))+" BP; "+str(basehash["a"])+" A; "+str(basehash["c"])+" C; "+str(basehash["g"])+" G; "+str(basehash["t"])+" T; "+str(basehash["Other"])+" other;\n"
currentposition=0
for x in range(0,len(sequence), 60):
emblstring=emblstring+" "
charactersadded=0
for y in range(0,60,10):
if x+y+10<len(sequence):
emblstring=emblstring+sequence[x+y:x+y+10]+" "
charactersadded=charactersadded+11
currentposition=currentposition+10
elif x+y<len(sequence):
emblstring=emblstring+sequence[x+y:]+" "
charactersadded=charactersadded+(1+len(sequence))-(x+y)
currentposition=currentposition+len(sequence)-(x+y)
emblstring=emblstring+" "*(75-(charactersadded+len(str(currentposition))))+str(currentposition)+"\n"
emblstring=emblstring+"//"
return emblstring
#def embl_style_sequence(sequence):
#
# emblstring="XX\n"
# sequence=sequence.strip().upper()
# basehash={"A":0,"C":0,"G":0,"T":0,"Other":0}
#
# for x in sequence:
# if basehash.has_key(x):
# basehash[x]=basehash[x]+1
# else:
# basehash["Other"]=basehash["Other"]+1
#
#
# split_seq=split_len(sequence, 10)
#
# emblstring=emblstring+"SQ Sequence "+str(len(sequence))+" BP; "+str(basehash["A"])+" A; "+str(basehash["C"])+" C; "+str(basehash["G"])+" G; "+str(basehash["T"])+" T; "+str(basehash["Other"])+" other;\n"
#
# currentposition=0
# for x in range(0,len(split_seq), 6):
# emblstring=emblstring+" "
# charactersadded=0
#
# for y, subseq in enumerate(split_seq[x:x+6]):
# if len(subseq)==10:
# emblstring=emblstring+subseq+" "
# charactersadded=charactersadded+11
# currentposition=currentposition+10
# else:
# emblstring=emblstring+subseq+" "
# charactersadded=charactersadded+(1+len(sequence))-(x+y)
# currentposition=currentposition+len(sequence)-(x+y)
# emblstring=emblstring+" "*(68-charactersadded)+str(currentposition)+"\n"
#
# emblstring=emblstring+"\\\\"
#
# testout=open("test.embl","w")
# print >> testout, emblstring
##################################################################
# Function to count the minimum number of changes between codons #
##################################################################
def countcodonchanges(codon, SNPcodon, geneticcode, sd, nd, loopsd=0, loopnd=0, pathcount=0):
for x in range(3):
if codon[x]!=SNPcodon[x]:
newSNPcodon=SNPcodon[:x]+codon[x]+SNPcodon[x+1:]
#print SNPcodon, newSNPcodon, geneticcode[SNPcodon], geneticcode[newSNPcodon]
if geneticcode[newSNPcodon]=='*':
continue
elif geneticcode[SNPcodon]==geneticcode[newSNPcodon]:
newloopnd=loopnd
newloopsd=loopsd+1
else:
newloopnd=loopnd+1
newloopsd=loopsd
#print SNPcodon, newSNPcodon, codon, sd, nd, newloopsd, newloopnd, pathcount
if newSNPcodon!=codon:
sd, nd, pathcount=countcodonchanges(codon, newSNPcodon, geneticcode, sd, nd, newloopsd, newloopnd, pathcount)
else:
sd=sd+newloopsd
nd=nd+newloopnd
pathcount=pathcount+1
return sd, nd, pathcount
#####################################################
# Function to calculate dN/dS between two sequences #
#####################################################
def dnbyds(CDS, SNPseq, CDSbasenumbers, genetic_code_number=1):
#standard genetic code
geneticcode_1={'TTT':'F', 'TTC':'F', 'TTA':'L', 'TTG':'L', 'TCT': 'S', 'TCC': 'S','TCA': 'S','TCG': 'S', 'TAT': 'Y','TAC': 'Y', 'TAA': '*', 'TAG': '*', 'TGT': 'C', 'TGC': 'C', 'TGA': '*', 'TGG': 'W', 'CTT': 'L','CTC': 'L','CTA': 'L','CTG': 'L', 'CCT': 'P', 'CCC': 'P', 'CCA': 'P', 'CCG': 'P', 'CAT': 'H', 'CAC': 'H', 'CAA': 'Q', 'CAG': 'Q', 'CGT': 'R', 'CGC': 'R', 'CGA': 'R', 'CGG': 'R', 'ATT': 'I', 'ATC': 'I', 'ATA': 'I', 'ATG': 'M', 'ACT': 'T', 'ACC': 'T', 'ACA': 'T', 'ACG': 'T', 'AAT': 'N', 'AAC': 'N', 'AAA': 'K', 'AAG': 'K', 'AGT': 'S', 'AGC': 'S', 'AGA': 'R', 'AGG': 'R', 'GTT': 'V', 'GTC': 'V', 'GTA': 'V', 'GTG': 'V', 'GCT': 'A', 'GCC': 'A', 'GCA': 'A', 'GCG': 'A', 'GAT': 'D', 'GAC': 'D', 'GAA': 'E', 'GAG': 'E', 'GGT': 'G', 'GGC': 'G', 'GGA': 'G', 'GGG': 'G'}
#mycoplasma genetic code
geneticcode_4={'TTT':'F', 'TTC':'F', 'TTA':'L', 'TTG':'L', 'TCT': 'S', 'TCC': 'S','TCA': 'S','TCG': 'S', 'TAT': 'Y','TAC': 'Y', 'TAA': '*', 'TAG': '*', 'TGT': 'C', 'TGC': 'C', 'TGA': 'W', 'TGG': 'W', 'CTT': 'L','CTC': 'L','CTA': 'L','CTG': 'L', 'CCT': 'P', 'CCC': 'P', 'CCA': 'P', 'CCG': 'P', 'CAT': 'H', 'CAC': 'H', 'CAA': 'Q', 'CAG': 'Q', 'CGT': 'R', 'CGC': 'R', 'CGA': 'R', 'CGG': 'R', 'ATT': 'I', 'ATC': 'I', 'ATA': 'I', 'ATG': 'M', 'ACT': 'T', 'ACC': 'T', 'ACA': 'T', 'ACG': 'T', 'AAT': 'N', 'AAC': 'N', 'AAA': 'K', 'AAG': 'K', 'AGT': 'S', 'AGC': 'S', 'AGA': 'R', 'AGG': 'R', 'GTT': 'V', 'GTC': 'V', 'GTA': 'V', 'GTG': 'V', 'GCT': 'A', 'GCC': 'A', 'GCA': 'A', 'GCG': 'A', 'GAT': 'D', 'GAC': 'D', 'GAA': 'E', 'GAG': 'E', 'GGT': 'G', 'GGC': 'G', 'GGA': 'G', 'GGG': 'G'}
geneticcodes=[geneticcode_1,geneticcode_1,geneticcode_1,geneticcode_4]
geneticcode=geneticcodes[genetic_code_number-1]
codonsynonyms={}
for codon in geneticcode.keys():
thiscodon={}
codonsynonyms[codon]=0.0
for x in range(3):
numsyn=0.0
numnotstop=3
for y in ['A', 'C', 'G', 'T']:
if codon[x]!=y:
newcodon=codon[:x]+y+codon[x+1:]
if geneticcode[newcodon]==geneticcode[codon]:
numsyn=numsyn+1
elif geneticcode[newcodon]=='*':
numnotstop=numnotstop-1
codonsynonyms[codon]=codonsynonyms[codon]+(numsyn/numnotstop)
S=0.0
N=0.0
S1=0.0
N1=0.0
S2=0.0
N2=0.0
Sd=0.0
Nd=0.0
pS=0.0
pN=0.0
gapcount=0
numcodons=0
varianceS=0.0
varianceN=0.0
z=0.0
dN=0.0
dS=0.0
SNPtype={}
AAfromtype={}
AAtotype={}
Fisher=-0
#if len(CDS)!=len(SNPseq):
# print "Error: sequences must be the same length to calculate dN/dS!"
# [N, S, dN, dS, pN, pS, varianceS, varianceN, z, (len(CDS)-gapcount), Nd, Sd, Fisher], SNPtype, AAfromtype, AAtotype
for x in range(0,len(CDS),3):
if len(CDS)<x+3:
continue
numcodons=numcodons+1
codon=CDS[x:x+3]
SNPcodon=SNPseq[x:x+3]
codonposn=[CDSbasenumbers[x], CDSbasenumbers[x+1], CDSbasenumbers[x+2]]
if codon!=SNPcodon:
for y,z in enumerate(codon):
if SNPcodon[y]!=z:
newSNPcodon=codon[:y]+SNPcodon[y]+codon[y+1:]
if 'N' in codon or 'N' in newSNPcodon or '-' in codon or '-' in newSNPcodon:
SNPtype[codonposn[y]]='-'
elif geneticcode[newSNPcodon]=='*':
SNPtype[codonposn[y]]='2'
elif geneticcode[newSNPcodon]=='*':
SNPtype[codonposn[y]]='3'
elif geneticcode[newSNPcodon] == geneticcode[codon]:
SNPtype[codonposn[y]]='S'
else:
SNPtype[codonposn[y]]='N'
if not 'N' in codon and not 'N' in SNPcodon and geneticcode[codon]!=geneticcode[SNPcodon]:
AAfromtype[codonposn[y]]=geneticcode[codon]
AAtotype[codonposn[y]]=geneticcode[SNPcodon]
if 'N' in codon or 'N' in SNPcodon or '-' in codon or '-' in SNPcodon:
gapcount=gapcount+3
continue
# if geneticcode[codon]=='*' or geneticcode[SNPcodon]=='*':
# continue
# print codon, x
#s=float(codonsynonyms[codon])/3
#n=float(3-s)
S1=S1+(float(codonsynonyms[codon]))
S2=S2+(float(codonsynonyms[SNPcodon]))
sd=0.0
nd=0.0
pathcount=0
if codon!=SNPcodon:
sd, nd, pathcount=countcodonchanges(codon, SNPcodon, geneticcode, sd, nd)
#if nochanges==2:
# sd=float(sd)/2
# nd=float(nd)/2
#elif nochanges==3:
# sd=float(sd)/6
# nd=float(nd)/6
if pathcount>0:
sd=float(sd)/pathcount
nd=float(nd)/pathcount
#elif codon!= SNPcodon:
# print codon, SNPcodon, "All paths lead to early stop codon in SNP sequence."
#return
Sd=Sd+sd
Nd=Nd+nd
#pS=pS+(sd/s)
#pN=pN+(nd/n)
#print codon, SNPcodon
S=(S1+S2)/2
N=len(CDS)-gapcount-S
#pNb=pN/numcodons
#pSb=pS/numcodons
if N!=0:
pN=Nd/N
if S!=0:
pS=Sd/S
if pS==0:
#print "No sites are synonymous."
return [N, S, dN, dS, pN, pS, varianceS, varianceN, z, (len(CDS)-gapcount), Nd, Sd, Fisher], SNPtype, AAfromtype, AAtotype
if pS<0.75 and pN<0.75:
dS=(-3*(math.log(1-((pS*4)/3))))/4
dN=(-3*(math.log(1-((pN*4)/3))))/4
varianceS=(9 * pS * (1 -pS))/(((3 - 4 *pS) **2) * (len(CDS)-gapcount));
varianceN=(9 * pN * (1 -pN))/(((3 - 4 *pN) **2) * (len(CDS)-gapcount));
z=(dN - dS) / math.sqrt(varianceS + varianceN)
#Fisher exact test of S and N
#oddsratio, Fisher = stats.fisher_exact([[N, S], [Nd, Sd]])
Fisher=fisher.pvalue(N,S,Nd,Sd).two_tail
else:
#print "Too divergent for JC! Using pN/pS instead."
dS=pS
dN=pN
#print dN, dS, S, N, S+N, Sd, Nd, pS, pN#, pSb, pNb, dS, dN, pN/pS, dN/dS
#print "N =", N
#print "S =", S
#print "dN/dS =", dN/dS
#print [N, S, dN, dS, pN, pS, varianceS, varianceN, z, (len(CDS)-gapcount), Nd, Sd, Fisher], SNPtype, AAfromtype, AAtotype
return [N, S, dN, dS, pN, pS, varianceS, varianceN, z, (len(CDS)-gapcount), Nd, Sd, Fisher], SNPtype, AAfromtype, AAtotype
#########################################################
# Function to concatenate CDSs for one of the sequences #
#########################################################
def concatenate_CDS_sequences(record, sequence, ref):
def add_feature_seq(feature):
#start=ref_pos_to_aln_pos[feature.location.start.position]
#end=ref_pos_to_aln_pos[feature.location.end.position-1]
#my_seq= Seq(sequences[sequence][start : end+1])
#if feature.strand==-1:
# my_seq=my_seq.reverse_complement()
#print len(my_seq),
#my_seq=str(feature.extract(sequences[sequence]))
#my_ref= Seq(sequences[ref][start : end+1])
#if feature.strand==-1:
# my_ref=my_ref.reverse_complement()
# #print len(my_ref)
#my_ref=str(my_ref)
my_ref=str(feature.extract(sequences[ref]))
#for base in xrange(len(my_ref)):
# if my_ref[base]=="-" and my_seq[base]=="-":
# continue
# elif my_ref[base]=="-" or my_seq[base]=="-":
# return
#
# if len(str(my_seq.replace("-",""))) % 3 or len(str(my_ref.replace("-",""))) % 3:
# return
#if len(str(my_seq)) % 3 or len(str(my_ref)) % 3:
# return
x=0
#for y in feature:
# if my_ref[x]!="-":
# CDSbasenumbers.append(ref_pos_to_aln_pos[y])
# x+=1
my_seq=[]
my_ref=[]
tCDSbasenumbers=[]
for part in feature.location.parts:
start=ref_pos_to_aln_pos[part.start]
end=ref_pos_to_aln_pos[part.end]
tmy_seq= Seq(sequences[sequence][start : end])
if feature.strand==-1:
tmy_seq=tmy_seq.reverse_complement()
my_seq.append(str(tmy_seq))
tref_seq= Seq(sequences[ref][start : end])
if feature.strand==-1:
tref_seq=tref_seq.reverse_complement()
my_ref.append(str(tref_seq))
rmed=[]
if part.strand==-1:
for x, y in enumerate(xrange(end-1, start-1, -1)):
if str(tref_seq)[x]!="-":
tCDSbasenumbers.append(y)
else:
rmed.append([x,y,str(tref_seq)[x], my_ref[-1][x], my_seq[-1][x]])
else:
for x, y in enumerate(xrange(start, end)):
if str(tref_seq)[x]!="-":
tCDSbasenumbers.append(y)
else:
rmed.append([x,y,str(tref_seq)[x], my_ref[-1][x], my_seq[-1][x]])
#print start, end, tCDSbasenumbers, part.strand
#if part.strand==-1:
# sys.exit()
toprint=[len(my_seq)]
my_seq=''.join(my_seq)
my_ref=''.join(my_ref)
toprint+=[str(tref_seq), rmed, len(my_seq), len(my_ref), len(tCDSbasenumbers), feature.strand, start, end, end-start, x]
#print feature.id, feature.strand, len(str(my_seq.replace("-",""))) % 3, len(str(my_ref.replace("-",""))) % 3
for base in xrange(len(my_ref)):
if my_ref[base]=="-" and my_seq[base]=="-":
continue
elif my_ref[base]=="-" or my_seq[base]=="-":
return "", "", []
if len(str(my_seq.replace("-",""))) % 3 or len(str(my_ref.replace("-",""))) % 3:
return "", "", []
my_ref=my_ref.replace("-","")
my_seq=my_seq.replace("-","")
if len(my_seq)!=len(tCDSbasenumbers):
print ' '.join(map(str,toprint))
print len(my_seq), len(my_ref), len(tCDSbasenumbers), feature.strand
print my_seq
print my_ref
sys.exit()
return my_seq, my_ref, tCDSbasenumbers
concatenated_sequence=[]
concatenated_ref=[]
CDSbasenumbers=[]
for feature in record.features:
if feature.type=="CDS" and not "pseudo" in feature.qualifiers:
ms, mr, tc=add_feature_seq(feature)
#print len(ms), len(concatenated_sequence)
concatenated_sequence.append(ms)
concatenated_ref.append(mr)
CDSbasenumbers=CDSbasenumbers+tc
#print len(ms), len(concatenated_sequence)
#print len(''.join(concatenated_sequence)), len(''.join(concatenated_ref)), len(CDSbasenumbers)
#print CDSbasenumbers
return ''.join(concatenated_sequence), ''.join(concatenated_ref), CDSbasenumbers
########################################
# Function to get a name for a feature #
########################################
def get_best_feature_name(feature):
name_types=["gene", "primary_name", "systematic_id", "locus_tag"]
for name in name_types:
if feature.qualifiers.has_key(name):
return feature.qualifiers[name][0]
return ""
###########################################
# Function to get a product for a feature #
###########################################
def get_feature_product(feature):
if feature.qualifiers.has_key("product"):
return feature.qualifiers["product"][0]
return ""
class SNPanalysis:
def __init__(self, fastq='', directory='', mapped={}, runmaq='n', CDSseq=''):
self.fastq=fastq
self.directory=directory
self.mapped=mapped
self.runmaq=runmaq
self.CDSseq=CDSseq
self.N=0.0
self.S=0.0
self.dN=0.0
self.dS=0.0
self.pN=0.0
self.pS=0.0
self.varianceN=0.0
self.varianceS=0.0
self.z=0.0
self.Nd=0.0
self.Ns=0.0
self.goodlen=0
self.CDSseq=''
self.snpsummary={}
self.nummapped=0
self.percentmapped=0.0
self.intragenic=0
self.intergenic=0
self.SNPs={}
if __name__ == "__main__":
#argv=sys.argv[1:]
#ref, inputfile, outfile, tabfile, align, embl, raxml, graphs, bootstrap, model, chisquare, recomb=getOptions(argv)
(options, args)=get_user_options()
check_input_validity(options, args)
snps={}
refbases={}
bases={}#0=A 1=C 2=G 3=T
nostates=0
converter={}
convertback={}
snpbases={}
snpstructs=[]
count=0
runpileups='n'
print '\nReading input alignment...',
sys.stdout.flush()
#else:
lines=[]
count=-1
sequences={}
names=set([])
curseqlist=[]
append=curseqlist.append
for linea in open(options.inputfile, "rU"):
linea=linea.strip()
if len(linea)==0:
continue
if linea[0]==">":
if count>-1:
sequence=''.join(curseqlist)
sequences[name]=sequence
count=count+1
curseqlist=[]
append=curseqlist.append
name=linea.split()[0][1:]
lines.append(linea.split()[0][1:]+'\n')
else:
append(linea)
if count>-1:
sequence=''.join(curseqlist)
sequences[name]=sequence
#for line in lines:
# words=line.strip().split('\n')
# sequences[words[0].split()[0]]=''.join(words[1:])
snpstructs.append(SNPanalysis())
ref=options.ref
reflen=len(sequences[sequences.keys()[0]])
for sequence in sequences.keys():
if len(sequences[sequence])!=reflen:
print "\nERROR!: sequences are not all of the same length!!!\n"
sys.exit()
# if sequence!=ref:
# sequences[sequence]=sequences[sequence].upper().replace('N','-')
# else:
# sequences[sequence]=sequences[sequence].upper()
if not options.gaps:
sequences[sequence]=sequences[sequence].upper().replace('-','N')
else:
sequences[sequence]=sequences[sequence].upper()
#replace uncertainties in each sequence
for x in ["R", "S", "B", "Y", "W", "D", "K", "H", "M", "V"]:
sequences[sequence]=sequences[sequence].replace(x,"N")
#print sequences.keys()
print "Found", len(sequences.keys()), "sequences of length", reflen
sys.stdout.flush()
if not ref in sequences.keys():
print "Error!!!: Reference ("+ref+") not in alignment"
sys.exit()
count=0
if ref!='':
aln_pos_to_ref_pos={}
ref_pos_to_aln_pos={}
#print reflen
refseq=sequences[ref].replace('-','')
reflennogaps=len(refseq)
for x, y in enumerate(sequences[ref]):
if y!='-':
aln_pos_to_ref_pos[x]=count#use aln_pos_to_ref_pos to convert alignment positions to positions in ref sequence
ref_pos_to_aln_pos[count]=x#opposite to aln_pos_to_ref_pos. Use this to convert reference positions to alignment positions
count=count+1
snplocations=[]
snpbases=[]
basecounts=[]
###################
# Open embl files #
###################
if options.embl!='':
print "\nReading EMBL file(s)...",
try:
record = open_annotation(options.embl)
except StandardError:
print "\nCannot open annotation file"
sys.exit()
print "Done"
if len(record.seq)!=reflennogaps:
DoError("embl file ("+str(len(record.seq))+") and alignment ("+str(reflennogaps)+") have different reference lengths")
sys.exit()
#Identify snps in the alignment
print "\nIdentifying SNPs...",
sys.stdout.flush()
constants={"A":0, "C":0, "G":0, "T":0}
for x in range(reflen):
numbases=0
foundbases={}
if sequences[ref][x].upper()=="N":
continue
for key in sequences.keys():
base=sequences[key][x].upper()
if base not in foundbases.keys() and base not in ['-', "N"]:
foundbases[base]=1
numbases=numbases+1
elif base not in ['-', "N"]:
foundbases[base]+=1
if numbases>1:
snplocations.append(x)
snpbases.append(foundbases)
basecounts.append(numbases)
elif numbases==1:
constants[foundbases.keys()[0]]+=1
print "Done"
print "Found", len(snplocations), "sites with a SNP"
print "Constant bases:"
for base in ["A","C","G","T"]:
print base+":", constants[base]
print
sys.stdout.flush()
seqsort=sequences.keys()
seqsort.sort()
allsnps={}
refbases={}
alssnpsummary={}
tempsnps={}
tempsnpsummary={'A':{'C':0, 'G':0, 'T':0}, 'C':{'A':0, 'G':0, 'T':0}, 'G':{'C':0, 'A':0, 'T':0}, 'T':{'C':0, 'G':0, 'A':0}}
olddone=-1
if options.embl!='' and ref!='':
def add_subfeature_positions(feature, pseudo, featurenum):
if feature.type in ['CDS', 'rRNA', 'tRNA']:
#print feature.id, feature.strand, feature.type, feature.location, len(embldata)
for part in feature.location.parts:
#print part.start, part.end
start=ref_pos_to_aln_pos[part.start]
end=ref_pos_to_aln_pos[part.end]
for x in xrange(start,end):
embldata[x]=featurenum
print "\nCalculating dN/dS values...",# NEEDS FIXING!!!
sys.stdout.flush()
#dndsout=open('dNdS_by_CDS.out','w')
sys.stdout.flush()
dnbydsstats={}
comp={'A':'T','T':'A','G':'C','C':'G', 'N':'N', '-':'-'}
embldata=[]
for i in range(0,reflen):
embldata.append(-1)
for y, feature in enumerate(record.features):
if feature.type in ['CDS', 'rRNA', 'tRNA']:
if "pseudo" in feature.qualifiers:
pseudo=True
else:
pseudo=False
add_subfeature_positions(feature, pseudo, y)
#print embldata
#refCDSseq=concatenate_CDS_sequences(record, ref)
print 'Done'
sys.stdout.flush()
tmpseqs={}
snptypes={}
AAfromtypes={}
AAtotypes={}
for sequence in seqsort:
if sequence==ref:
continue
print sequence+'...',
sys.stdout.flush()
tmpCDSseq, refCDSseq, CDSbasenumbers=concatenate_CDS_sequences(record, sequence, ref)
#print len(tmpCDSseq), len(refCDSseq), len(CDSbasenumbers)
dnbydsstats[sequence], snptypes[sequence], AAfromtypes[sequence], AAtotypes[sequence]=dnbyds(refCDSseq, tmpCDSseq, CDSbasenumbers, genetic_code_number=options.genetic_code_number)
#print dnbydsstats[sequence]
#N, S, dN, dS, pN, pS, varianceS, varianceN, z, (len(CDS)-gapcount), Nd, Sd
if dnbydsstats[sequence][3]!=0:
print "dNdS = %.2f, p-value = %.2f" % (dnbydsstats[sequence][2]/dnbydsstats[sequence][3], dnbydsstats[sequence][12])
#print >> dndsout, '\t'+str(dnbydsstats[sequence][2]/dnbydsstats[sequence][3]),
sys.stdout.flush()
else:
print "-"
#dndsout.close()
#print summary file and alignment file
print "\nWriting output file(s)...",
sys.stdout.flush()
output=open(options.outfile+'.out','w')
#if len(allsnps.keys())>1:
# print >> output, 'Ref_sequence\tPosition_in_ref',
#else:
print >> output, 'Position_in_alignment',
if ref!='':
print >> output, '\tPosition_in_'+ref,
if options.embl!='':
print >> output, '\tCDS/rRNA/tRNA/Intergenic\tstrand\tCDS_name\tproduct\tSynonymous/Non-synonymous',
print >> output, '\tRef_base\tSNP_base\tTotal',
for name in seqsort:
if name!=ref:
print >> output, '\t'+name,
print >> output, '\n',
#
if options.tabfile==True:
tabout=open(options.outfile+'_snps.tab','w')
#covgraph=open(outfile+'_cov.txt','w')
#covcountgraph=open(outfile+'_covcount.txt','w')
#minquality=10
#minqualityperdepth=4
snpsequence={}
for name in seqsort:
snpsequence[name]=''
refsequence=''
if ref=='':
ref=sequences.keys()[0]
if options.tabfile==True:
print >> tabout, 'ID SNP'
poscount=1
#for key in sequences.keys():
#snpsort=allsnps[key].keys()
#snpsort.sort()
strainsnpsummary={}
for name in seqsort:
if name!=ref:
strainsnpsummary[name]={}
strainsnpsummary[name]['count']=0
for x in ['A', 'C', 'G', 'T']:
strainsnpsummary[name][x]={}
for y in ['A', 'C', 'G', 'T']:
strainsnpsummary[name][x][y]=0
for x, j in enumerate(snplocations):
outstring=''
tabstring=''
#if len(allsnps.keys())>1:
# outstring=outstring+key+'\t'+str(j)
#else:
outstring=outstring+str(j+1)
snpcolour='1'
if sequences[ref][j]!='-':
outstring=outstring+'\t'+str(aln_pos_to_ref_pos[j]+1)
if options.embl!='':
# if embldata[aln_pos_to_ref_pos[j]]<0:
# outstring=outstring+'\tIntergenic\t-\t-\t'
# else:
# outstring=outstring+'\t'+record.features[embldata[aln_pos_to_ref_pos[j]]].type+'\t'+str(record.features[embldata[aln_pos_to_ref_pos[j]]].strand)+'\t'+get_best_feature_name(record.features[embldata[aln_pos_to_ref_pos[j]]])+'\t'+get_feature_product(record.features[embldata[aln_pos_to_ref_pos[j]]])
# snptype='-'
if embldata[j]<0:
outstring=outstring+'\tIntergenic\t-\t-\t-'
else:
outstring=outstring+'\t'+record.features[embldata[j]].type+'\t'+str(record.features[embldata[j]].strand)+'\t'+get_best_feature_name(record.features[embldata[j]])+'\t'+get_feature_product(record.features[embldata[j]])
snptype='-'
for name in seqsort:
if name==ref:
continue
# if snptypes[name].has_key(aln_pos_to_ref_pos[j]):
# if snptypes[name][aln_pos_to_ref_pos[j]]=='S':
# snpcolour='3'
# elif snptypes[name][aln_pos_to_ref_pos[j]]=='N':
# snpcolour='2'
# elif snptypes[name][aln_pos_to_ref_pos[j]]=='2':
# snpcolour='4'
# elif snptypes[name][aln_pos_to_ref_pos[j]]=='3':
# snpcolour='4'
# if snptype=='-' and snptypes[name][aln_pos_to_ref_pos[j]]!='-':
# snptype=snptypes[name][aln_pos_to_ref_pos[j]]
# elif snptypes[name][aln_pos_to_ref_pos[j]] not in snptype and snptypes[name][aln_pos_to_ref_pos[j]]!='-':