forked from mengqvist/DNApy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
seqfiles5.py
1007 lines (775 loc) · 31.7 KB
/
seqfiles5.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
###
# name : seqfiles.py
# description : Script for analyzing sequencing results
#
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# LICENSE:
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
# This program 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 Library General Public License for more details.
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
#Copyright (C) 2014 Martin K. M. Engqvist |
###
##### Json style data structure used for this script #####
# [{
# "reference":
# {
# "name": "reference_dna",
# "dna": "CACCGG",
# "aln_dna": "C-ACCG-G",
# },
# "samples":
# [
# {
# "name": "rrnb_primer1.seq",
# "dna": "CTACGTG",
# "orientation": "forward",
# "aln_dna": "CTA-CGTG",
# "sign_missmatches": " * * * ",
# },
# {
# "name": "rrnb_primer2.seq",
# "dna": "CACGTAG",
# "aln_dna": "CTA-CGTG",
# "sign_missmatches": " * * * ",
# }
# ],
# "contig":
# {
# "name": "rrnb_contig"
# "dna": "CTACGTG",
# "aln_dna": "CTA-CGTG",
# "sign_missmatches": " * * * ",
# "dna_missmatches": "list of dna missmatches",
# "aa_missmatches": "list of aa missmatches",
# }
#
#
# },
# {
# "reference":
# {
# "name": "referene_dna",
# "dna": "CACCGG",
# "aln_dna": "C-ACCG-G",
# },
# "samples":
# [
# {
# "name": "ccdb_primer1.seq",
# "dna": "CTACGTG",
# "orientation": "forward",
# "aln_dna": "CTA-CGTG",
# "sign_missmatches": " * * * ",
# },
# {
# "name": "ccdb_primer2.seq",
# "dna": "CACGTAG",
# "orientation": "reverse",
# "aln_dna": "CTA-CGTG",
# "sign_missmatches": " * * * ",
# }
# ],
# "contig":
# {
# "name": "ccdb_contig"
# "dna": "CTACGTG",
# "aln_dna": "CTA-CGTG",
# "sign_missmatches": " * * * ",
# "dna_missmatches": "list of dna missmatches"
# "aa_missmatches": "list of aa missmatches",
# }
#
#
# }
# ]
#######################################################
import os
import fnmatch
import dna as DNA
from StringIO import StringIO
import pprint
import copy
import string
#import difflib
import ABIreader #parser
#import scf #parser
#import abi #parser
#import ztr #parser
import fastq #parser
import fasta #parser
import NeedlemanWunsch as NW #alignment
class SeqObj:
'''
Sequencing object for storing data related to a single Sanger sequencing run.
filepath is the complete path to the file, including the file name
'''
def __init__(self, filepath):
self.filepath = string.replace(filepath, "\\", "/") #replace slashes and hold the input filepath
self.input_type = False #type of input file
self.name = False #name of sequence
self.orientation = False #fw or rv orientation of the dna
self.dna = False #complete DNA sequence
self.qual_val = False #contains the qualifier values for the sequence (if derived from an .ab1 or .scf file)
self.trace = False #sequencing trace
self.RC = False #keep track of whether the sequence has been reverse-complemented
self.dna_clipped = False #clipped DNA sequence (removal of poor sequence (based on qual_val))
self.reference = False #reference to a SeqObj that holds the reference sequence
self.sign_missmatches = False #sign (* * * *) mismatches vs the reference
self.dna_missmatches = False #nucleotide mismatches vs the reference
self.aa_missmatches = False #amino acid mismatches vs the reference
self.consensus = False #reference to a SeqObj that represents the consensus sequence of which this sequence is a part
self.next = False #reference to a SeqObj that is sequentially before this one
self.previous = False #reference to a SeqObj that is sequentially after this one
# x = '!"#$%%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~' #without escape characters: '!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~'
self.getInput() #open the file
return
def setName(self, name):
self.name = name #string
def getName(self):
return self.name #string
def setOrientation(self, orientation):
self.orientation = orientation #string
def getOrientation(self):
return self.orientation #string
def setDNA(self, dna):
self.dna = dna #string
def getDNA(self):
return self.dna #string
def setQualVal(self, qual_val):
self.qual_val = qual_val #string
def getQualVal(self):
return self.qual_val #string
def setTrace(self, trace):
self.trace = trace #list [G, A, T, C]
def getTrace(self):
return self.trace #list [G, A, T, C]
def setRC(self, bool):
self.RC = bool #true or false
def getRC(self):
return self.RC #true or false
def setDNAClipped(self, dna):
self.dna_clipped = dna #string
def getDNAClipped(self):
return self.dna_clipped #string
def setReference(self, dna):
self.reference = dna #string
def getReference(self):
return self.refrence #string
def setSignMissmatch(self, string):
self.sign_missmatches = string #string
def getSignMissmatch(self):
return self.sign_missmatches #string
def setDNAMissmatch(self, string):
self.dna_missmatches = string #string
def getDNAMissmatch(self):
return self.dna_missmatches #string
def setAAMissmatch(self, string):
self.aa_missmatches = string #string
def getAAMissmatch(self):
return self.aa_missmatches #string
def setContig(self, dna):
self.contig = dna #string
def getContig(self):
return self.contig #string
def setNext(self, seqobj):
self.next = seqobj #SeqObj object
def getNext(self):
return self.next #SeqObj object
def setPrevious(self, seqobj):
self.previous = seqobj #SeqObj object
def getPrevious(self):
return self.previous #SeqObj object
def getInput(self):
'''Open a single .seq, .fasta, .fastq, .ztr, .scf, .ab1 file (or even a text file with a DNA sequence) and set variables accordingly.'''
parts = self.filepath.split('/')
filename = parts.pop() #get filename
path = '/'.join(parts)+'/' #path to file
#establish type of input file
if '.' in filename:
self.input_type = filename.split('.')[-1].upper()
print('type', self.input_type)
else:
self.input_type = None
#read the input
if self.input_type in ['TXT', 'SEQ', None] and filename not in ['allseqs.txt']:
#establish orientation of DNA
if filename.split('.')[0][-2:].upper() == 'FW':
self.setOrientation('fw')
elif filename.split('.')[0][-2:].upper() == 'RV':
self.setOrientation('rv')
else:
raise TypeError, 'The last two characters of the filename (before the .) must specify whether the sequence is fw or rv. Pleace rename file %s accordingly' % filename
self.setName(filename)
f = open(self.filepath, 'r')
input = f.read()
f.close()
if self.getOrientation() == 'fw':
self.setDNA(input.replace('\n', ''))
elif self.getOrientation() == 'rv':
self.setDNA(DNA.RC(input.replace('\n', '')))
self.setRC(True)
elif self.input_type in ['AB1', 'ABI', 'ABIF']:
#establish orientation of DNA
if filename.split('.')[0][-2:].upper() == 'FW':
self.setOrientation('fw')
elif filename.split('.')[0][-2:].upper() == 'RV':
self.setOrientation('rv')
else:
raise TypeError, 'The last two characters of the filename (before the .) must specify whether the sequence is fw or rv. Pleace rename file %s accordingly' % filename
self.setName(filename)
ab1 = ABIreader.Trace(self.filepath, trimming=True) #optionally ', trimming=True'
if self.getOrientation() == 'fw':
self.setDNA(ab1.seq)
self.setQualVal(ab1.qual_val) #need to RC this too
self.setTrace([ab1.data['raw1'], ab1.data['raw2'], ab1.data['raw3'], ab1.data['raw4']]) #need to RC this too
#abi=dict(baseorder=ab1.data['baseorder'], qual_val=ab1.qual_val, G=str(AB1Trace.data['raw1']), A=str(AB1Trace.data['raw2']), T=str(AB1Trace.data['raw3']), C=str(AB1Trace.data['raw4']))
elif self.getOrientation() == 'rv':
self.setDNA(DNA.RC(ab1.seq))
self.setQualVal(ab1.qual_val) #need to RC this too
self.setTrace([ab1.data['raw1'], ab1.data['raw2'], ab1.data['raw3'], ab1.data['raw4']]) #need to RC this too
#abi=dict(baseorder=ab1.data['baseorder'], qual_val=ab1.qual_val, G=str(AB1Trace.data['raw1']), A=str(AB1Trace.data['raw2']), T=str(AB1Trace.data['raw3']), C=str(AB1Trace.data['raw4']))
self.setRC(True)
# elif self.input_type == 'ZTR':
# print('Support for .ztr files has not yet been implemented')
# elif self.input_type == 'SCF':
# print('Support for .scf files has not yet been implemented')
elif fnmatch.fnmatch(filename, '*.fasta'):
self.setName(filename)
id, dna = fasta.parseFile(self.filepath) #parse the fasta file. File should contain ONE entry
self.setDNA(dna)
#establish orientation of DNA
if filename.split('.')[0][-2:].upper() == 'FW':
self.setOrientation('fw')
elif filename.split('.')[0][-2:].upper() == 'RV':
self.setOrientation('rv')
else:
raise TypeError, 'The last two characters of the filename (before the .) must specify whether the sequence is fw or rv. Pleace rename file %s accordingly' % filename
elif fnmatch.fnmatch(filename, '*.fastq'):
self.setName(filename)
id, dna, id2, qual_val = fastq.parse(self.filepath) #parse the fastq file. File should contain ONE entry
self.setDNA(dna)
self.setQualVal(qual_val)
#establish orientation of DNA
if filename.split('.')[0][-2:].upper() == 'FW':
self.setOrientation('fw')
elif filename.split('.')[0][-2:].upper() == 'RV':
self.setOrientation('rv')
else:
raise TypeError, 'The last two characters of the filename (before the .) must specify whether the sequence is fw or rv. Pleace rename file %s accordingly' % filename
else:
pass
print('"%s" is not a .txt, .seq, .scf, .fasta, .fastq, .abif, .ab1, .abi or .ztr file' % filename)
class SeqAnalysis:
'''
Sequencing analysis object for assembling and analysing data from many Sanger sequencing runs.
'''
def __init__(self):
self.seqdata = [] #this is where all the sequence info gets stored
def addSeq(self, seqobject):
'''
Adds a single SeqObj sequencing object to the data structure.
'''
if len(self.seqdata) == 0:
self.seqdata.append(dict(samples = [seqobject]))
elif len(self.seqdata) > 0:
#this workaround works for construct names with _ in it. But it fails when the primer name has _ in it....
### this is overly complicated to deal with filenames that has more than one '_' in the filename
# nameparts = dictionary['name'].split('_')
# nameparts.pop() #remove last
# name = ''
# for item in nameparts: #stitch them together
# name += '%s_' % item
###
#construct name and primer name MUST be separated by _ . Construct name CANNOT contain _ .
name = seqobject.getName().split('_')[0] #get first part of name
for i in range(len(self.seqdata)):
if name in self.seqdata[i]['samples'][0].getName():
self.seqdata[i]['samples'].append(seqobject)
break
elif i == len(self.seqdata)-1:
self.seqdata.append(dict(samples = [seqobject]))
else:
print('Error adding sequence to self.seqdata')
def addFolder(self, path):
'''Opens many .Seq or .ab1 file and returns id and sequence into a list of dictionaries'''
#Here I move all the sequence data from all .Seq or .ab1 files in one folder into a list of dictionaries
file_list = sorted(os.listdir(path))
for filename in file_list:
print(filename)
#check if there is an ab1 file for this name in the folder. I will also add support for .fasta, .scf and .fastq files
#I need to change this to an internal ranking. For each name it should just pick the 'best' file
if filename.split('.')[-1].upper() == 'SEQ':
if [filename.split('.')[0]+'.ab1' in s for s in file_list] is False: #if it's not present, add the .seq file
seqobject = SeqObj(path+'/'+filename) #make a SeqObj object
print('if if', seqobject)
else:
seqobject = SeqObj(path+'/'+filename) #make a SeqObj object
if seqobject.getDNA() is not False and seqobject.getName() is not False: #a seqobject is only made if the input file is the appropriate file type
self.addSeq(seqobject)
def getOverlap(self, seq1, seq2):
'''
Find and return the maximum overlap length of two sequences.
This only works when using the NeedlemanWunsch algorithm to get the overlap. (The algorithm is much too promiscous otherwise.
If there is no overlap, return empty string.
'''
alignment = NW.PairwiseAlignment(seq1, seq2)
seq1aln = alignment.seq1aligned.upper()
seq2aln = alignment.seq2aligned.upper()
assert len(seq1aln) == len(seq2aln), 'Error, the sequences are not of the same length'
overlap = False
start = False
end = len(seq1aln)
length = False
first = False
#get start, end and length of overlap. Any number of N is tolerated and a double -- is tolerated.
for i in range(len(seq1aln)):
if overlap is False and seq1aln[i] in 'ATCGN' and seq2aln[i] in 'ATCGN': #first nucleotide of overlap
start = copy.copy(i)
overlap = True
elif overlap is True and (seq1aln[i] == '-' or seq2aln[i] == '-'):
if seq1aln[i+1:i+3] == '--' or seq2aln[i+1:i+3] == '--': #allow for two missing bases, but not more
end = copy.copy(i)
break
a = open('test.txt', 'a') #open it for writing
a.write(seq1aln)
a.write(seq2aln)
a.close()
#Find which sequence is the first (the leftmost)
#possible topologies:
#AAAAAAAAAAAAAATTTTT-----------
#--------------AAAAACCCCCCCCCCC
if (seq1aln[0] in 'ATCGN' and seq2aln[0] == '-') and (seq1aln[end+1] == '-' and seq2aln[end+1] in 'ATCGN'):
first = 1 #seq1 first
#--------------AAAAACCCCCCCCCCC
#AAAAAAAAAAAAAATTTTT-----------
elif (seq1aln[0] == '-' and seq2aln[0] in 'ATCGN') and (seq1aln[end+1] in 'ATCGN' and seq2aln[end+1] == '-'):
first = 2 #seq2 first
#CCCCCCAAAAAAAAAAAAAATTTTTCCCCCCCCCCC
#------AAAAAAAAAAAAAATTTTT-----------
elif (seq1aln[0] in 'ATCGN' and seq2aln[0] == '-') and (seq1aln[end+1] in 'ATCGN' and seq2aln[end+1] == '-'):
overlap = False #mark this as not an overlap
#------AAAAAAAAAAAAAATTTTT-----------
#CCCCCCAAAAAAAAAAAAAATTTTTCCCCCCCCCCC
elif (seq1aln[0] == '-' and seq2aln[0] in 'ATCGN') and (seq1aln[end+1] == '-' and seq2aln[end+1] in 'ATCGN'):
overlap = False #mark this as not an overlap
#CCCCCCAAAAAAAAAAAAAATTTTTCC---------
#CCCCCCAAAAAAAAAAAAAATTTTTCCCCCCCCCCC
elif (seq1aln[0] in 'ATCGN' and seq2aln[0] in 'ATCGN') and (seq1aln[end+1] == '-' and seq2aln[end+1] in 'ATCGN'):
first = 1 #seq1 first
#CCCCCCAAAAAAAAAAAAAATTTTTCCCCCCCCCCC
#CCCCCCAAAAAAAAAAAAAATTTTTCC---------
elif (seq1aln[0] in 'ATCGN' and seq2aln[0] in 'ATCGN') and (seq1aln[end+1] in 'ATCGN' and seq2aln[end+1] == '-'):
first = 2 #seq2 first
#-----CAAAAAAAAAAAAAATTTTTCCCCCCCCCCC
#CCCCCCAAAAAAAAAAAAAATTTTTCCCCCCCCCCC
elif (seq1aln[0] == '-' and seq2aln[0] in 'ATCGN') and (seq1aln[end+1] in 'ATCGN' and seq2aln[end+1] in 'ATCGN'):
first = 2 #seq2 first
#CCCCCCAAAAAAAAAAAAAATTTTTCCCCCCCCCCC
#-----CAAAAAAAAAAAAAATTTTTCCCCCCCCCCC
elif (seq1aln[0] in 'ATCGN' and seq2aln[0] == '-') and (seq1aln[end+1] in 'ATCGN' and seq2aln[end+1] in 'ATCGN'):
first = 1 #seq1 first
#CCCCCCAAAAAAAAAAAAAATTTTTCCCCCCCCCCC
#CCCCCCAAAAAAAAAAAAAATTTTTCCCCCCCCCCC
elif (seq1aln[0] in 'ATCGN' and seq2aln[0] in 'ATCGN') and (seq1aln[len(seq1aln)] in 'ATCGN' and seq2aln[len(seq2aln)] in 'ATCGN'):
first = 1 #it does not matter which one is first, but let's pick seq1
if overlap is False:
return False, False, False, False
else:
return seq1aln, seq2aln, seq1aln[start:end], first #return aligned seq1 (str), seq2 (str), the overlap (str), and an integer (1 or 2 ) that indicates which sequence is first in the alignment.
def findFirst(self, alnscores):
'''
Find the leftmost sequence of alignment pairs.
'''
#find the leftmost sequence
keys = alnscores.keys() #seqs with overlaps to the right
leftmost = []
for i in keys:
present = False
for j in keys:
if i in alnscores[j]: #they cannot be present as the 'right' sequence of any other sequence
present = True
break
if present is False and i not in leftmost:
leftmost.append(i)
print('leftmost', leftmost)
return leftmost # a list
def sortSeqs(self):
'''
Align each sequence with each other sequence.
Save the alignment scores in a matrix where the index (in the list) for each SeqObj is used as the identifier.
'''
alnscores = {} #store the alignment overlaps
alnseqs = {} #store the alignment sequences
for group in self.seqdata:
for i in range(len(group['samples'])-1):
for j in range(i+1, len(group['samples'])):
seqobj1 = group['samples'][i]
seqobj2 = group['samples'][j]
alnseq1, alnseq2, overlap, first = self.getOverlap(seqobj1.getDNA(), seqobj2.getDNA()) #get the overlap and which sequence is first
# print('%s and %s' % (seqobj1.getName(), seqobj2.getName()), overlap)
if overlap is not False and first == 1:
if i in alnscores:
alnscores[i].update({j:len(overlap)})
alnseqs[i].update({j:(alnseq1, alnseq2)})
else:
alnscores[i] = {j:len(overlap)}
alnseqs[i] = {j:(alnseq1, alnseq2)}
elif overlap is not False and first == 2:
if j in alnscores:
alnscores[j].update({i:len(overlap)})
alnseqs[j].update({i:(alnseq2, alnseq1)})
else:
alnscores[j] = {i:len(overlap)}
alnseqs[j] = {i:(alnseq2, alnseq1)}
print(alnscores)
#get the leftmost (the first) sequence
leftmost = self.findFirst(alnscores)[0]
#determine the order of sequences
sequence = [leftmost]
keys = alnscores.keys()
while sequence[-1] in keys:
sequence.append(max(alnscores[sequence[-1]], key=alnscores[sequence[-1]].get)) #get the max value for the dictionary under the key
print('sequence', sequence)
def printAlnScores(self):
pass
def setConsensus(self):
'''
Build a consensus sequence from sorted sequence reads.
'''
pass
################ Generating outputs ######################
def writeseqfiles(self, path):
'''Write all sequence entries from a list of dictionaries to textfile'''
a = open(path + 'allseqs.txt', 'w') #open it for writing
for i in range(len(self.seqdata)):
for n in range(len(self.seqdata[i]['samples'])):
a.write(self.seqdata[i]['samples'][n].getName())
a.write('\n')
a.write(self.seqdata[i]['samples'][n].getDNA())
a.write('\n')
a.close()
##########################################################
def RemoveN(Seq):
Seq = Seq.upper()
BeginningCounter = 0
EndCounter = len(Seq)
for i in range(int(len(Seq)/2)):
if 'N' in Seq[i]:
BeginningCounter = i+1
for i in range(int(len(Seq)/2)+1, len(Seq)):
if 'N' in Seq[i]:
EndCounter = i
break
Seq = Seq[BeginningCounter:EndCounter]
#print(Seq)
return Seq
#End of RemoveN function
def findoverlap(Seq1, Seq2, min_overlap=20):
"""Function for finding overlaps of two sequences.
Returns start of overlap on Seq1, start of overlap on Seq2, and length of overlap"""
Seq1 = Seq1.upper()
Seq1 = Seq1.replace('\n','')
Seq2 = Seq2.upper()
Seq2 = Seq2.replace('\n','')
seq_matcher = difflib.SequenceMatcher(None, Seq1, Seq2)
seq1_loc, seq2_loc, match_len = seq_matcher.find_longest_match(0, len(Seq1), 0, len(Seq2))
if match_len < min_overlap: #the match is shorter than the minimum specified
return False
else:
return seq1_loc, seq2_loc, match_len #return overlap DNA, overlap start on first seq, overlap start on second seq
def M_align_iterative(seqdata):
'''This function aligns many sequences to a reference, one sequence at a time, then makes sure that all gaps match'''
#prepare input as a 'virtual' FASTA file
#first entry should be the reference
temp_dictlist = []
for n in range(len(seqdata[index]['samples'])): #make sure each dna has an empty aln_dna entry
seqdata[index]['samples'][n]['aln_dna'] = ''
for n in range(len(seqdata[index]['samples'])):
records = ''
if seqdata[index]['reference']['name'][0] != '>':
records += '>%s\n%s\n' % (seqdata[index]['reference']['name'], seqdata[index]['reference']['dna']) #reference
elif seqdata[index]['reference']['name'][0] == '>':
records += '%s\n%s\n' % (seqdata[index]['reference']['name'], seqdata[index]['reference']['dna'])
else:
print('Muscle name error')
if seqdata[index]['samples'][n]['name'][0] != '>':
records += '>%s\n%s\n' % (seqdata[index]['samples'][n]['name'], seqdata[index]['samples'][n]['dna']) #sample
elif seqdata[index]['samples'][n]['name'][0] == '>':
records += '%s\n%s\n' % (seqdata[index]['samples'][n]['name'], seqdata[index]['samples'][n]['dna'])
else:
print('Muscle name error')
records_handle = StringIO(records) #turn string into a handle
tempdata = records_handle.getvalue()
#for seperate fasta entries
muscle_cline = MuscleCommandline()
stdout, stderr = muscle_cline(stdin=tempdata)
stdout = parse_fasta(stdout)
#sort so that ref is first
#is that needed? seems to be working fine
if n == 0:
seqdata[index]['reference']['aln_dna'] = stdout[0]['dna']
seqdata[index]['samples'][n]['aln_dna'] = stdout[1]['dna']
else:
#compare sequences with temp dictlist, check for - in one and not the other. Make changes to all.
temp_dictlist.append(stdout[0])
temp_dictlist.append(stdout[1])
i = 0
while i <= len(seqdata[index]['reference']['aln_dna']):
#check if reference sequences have the same spaces
if len(seqdata[index]['reference']['aln_dna']) == i and len(temp_dictlist[0]['dna']) == i:
i += 1
elif len(seqdata[index]['reference']['aln_dna']) == i and len(temp_dictlist[0]['dna']) > i: #for dealing with end of sequence
seqdata[index]['reference']['aln_dna'] = seqdata[index]['reference']['aln_dna'] + '-'
for x in range(len(seqdata[index]['samples'])): #make change in all sequences present
if seqdata[index]['samples'][x]['aln_dna'] != '':
seqdata[index]['samples'][x]['aln_dna'] += '-'
i = 0
elif len(temp_dictlist[0]['dna']) == i and len(seqdata[index]['reference']['aln_dna']) > i: #for dealing with end of sequence
for entry in temp_dictlist:
entry['dna'] = entry['dna'] + '-'
i = 0
elif seqdata[index]['reference']['aln_dna'][i] == '-' and temp_dictlist[0]['dna'][i] != '-': # if gap in old alignment, but not in new
for entry in temp_dictlist:
entry['dna'] = entry['dna'][:i] + '-' + entry['dna'][i:]
i = 0
elif seqdata[index]['reference']['aln_dna'][i] != '-' and temp_dictlist[0]['dna'][i] == '-': #if gap in new alignment, but not in old
seqdata[index]['reference']['aln_dna'] = seqdata[index]['reference']['aln_dna'][:i] + '-' + seqdata[index]['reference']['aln_dna'][i:]
for x in range(len(seqdata[index]['samples'])): #make change in all sequences present
if seqdata[index]['samples'][x]['aln_dna'] != '':
seqdata[index]['samples'][x]['aln_dna'] = seqdata[index]['samples'][x]['aln_dna'][:i] + '-' + seqdata[index]['samples'][x]['aln_dna'][i:]
i = 0
else:
i += 1
seqdata[index]['samples'][n]['aln_dna'] = temp_dictlist[1]['dna']
#I should probably add someting to go through and check that I don't have '-' for all sequences at some position
def join(Seq1, Seq2):
"""joins two sequences that have an overlap.
Seq1 is assumed to come before Seq2.
Both are assumed to be in the same orientation."""
vars = findoverlap(Seq1, Seq2) #vars contains the start of overlap on seq1, start of overlap on seq2, and length of overlap
#print(vars)
if vars == False:
print('No overlap')
return False
elif type(var[0]) == int and type(var[1]) == int and type(var[2]) == int:
print('Overlap')
JointSeq = Seq1[0:vars[0]] + Seq2[vars[1]:len(Seq2)]
return JointSeq
else:
print('error while joining')
#align function
def align(Seq1, Seq2): #aligns two sequences that have an overlap
Seq1 = Seq1.replace('\n','')
Seq2 = Seq2.replace('\n','')
Seq1 = Seq1.upper()
Seq2 = Seq2.upper()
vars = findoverlap(Seq1, Seq2)
#print(vars)
if vars == False:
#print('No overlap')
return False
elif type(vars[0]) == int and type(vars[1]) == int and type(vars[2]) == int:
dash = '-'
dash = dash * (var[1]-var[2]) #putting dashes in front of seq2 to fill up until the alignment
Seq2 = dash + Seq2
alnvar = ''
if len(Seq1) < len(Seq2):
Seq1 = Seq1 + (len(Seq2) - len(Seq1)) * '-' #fill up the back
#print(len(Seq1))
#print(len(Seq2))
elif len(Seq1) > len(Seq2):
Seq2 = Seq2 + (len(Seq1) - len(Seq2)) * '-' #fill up the back
#print(len(Seq1))
#print(len(Seq2))
for i in range(len(Seq1)):
if Seq1[i] == Seq2[i]:
alnvar = alnvar + '|'
elif Seq1[i] != Seq2[i]:
alnvar = alnvar + 'x'
else:
print('error making alnvar')
return (Seq1, alnvar, Seq2)
else:
print('error while aligning')
#end of align function
#Function for finding a certain sequence in a string and delete everything in front. Used for finding beginning of gene in seqfile.
#Currently uses 10 nucleotides for the search
#Also deletes everything after the stop codon of the RefSeq
def findstart(RefSeq, Seq):
RefSeq = RefSeq.upper()
Seq = Seq.upper()
for i in range(len(RefSeq)):
if RefSeq[i:(i+3)] == 'ATG':
RefSeq = RefSeq[i:len(RefSeq)]
#print(RefSeq[0:10])
break
for i in range(len(Seq)):
if RefSeq[0:10] == Seq[i:(i+10)]: #Find the start here
Seq = Seq[i:len(Seq)]
if RefSeq[len(RefSeq)-11:len(RefSeq)-1] == Seq[i:(i+10)]: #find the end. Had to add an extra -1 since last character was \n
Seq = Seq[0:(i+10)]
#print(Seq[0:10])
return(RefSeq, Seq)
#End of findstart function
#Function for comparing the sequencing reaction to a reference sequence, one triplet at a time
def tripletalign(RefSeq, Seq):
RefSeq = RefSeq.upper()
Seq = Seq.upper()
counter = 0
for i in range(len(Seq)):
if i%3==0 or i == 0:
#print(RefSeq[i:i+3])
#print(Seq[i:i+3])
if RefSeq[i:(i+3)] == Seq[i:(i+3)]:
counter = 0
pass
elif i+3>len(Seq): #to make sure it's a complete codon... i.e. leave out last codon if it is shorter than 3
pass
else:
if counter <= 5:
print('DNA pos %d, %s mutated to %s --- %s%d%s' % (i+3-1, RefSeq[i:(i+3)], Seq[i:(i+3)], DNA.translate(RefSeq[i:(i+3)]), int((i+3)/3), DNA.translate(Seq[i:(i+3)])))
counter += 1
else:
print('over %d consecutive mismatches, rest of construct is likely out of frame' % (counter-1))
break
print('\n')
#End of triplet align function
def check(seqdataentry):
#for entry in Sequences:
print(seqdataentry['contig']['name'])
dna = findstart(seqdataentry['reference']['dna'], seqdataentry['contig']['dna'])
tripletalign(dna[0], dna[1]) #(RefSeq, dna)
### Add a Seqalign function here that analyzes the current sequence vs refseq and spits out missmatches independent of codons...
#########
def getreference(path, index):
'''Get the reference sequence for each group of sequences'''
#open the RefSeq file
#RefSeq file should contain the gene of interest, starting with ATG
filepath = path + 'RefSeq.txt' #Open reference sequence file
f = open(filepath, 'r') #open content of current file
seqdata[index]['reference'] = dict(name = 'reference_sequence', dna = f.read())
f.close() #close current file
#######################################################
#I don't think this is needed any more
def group_sequences():
'''grups sequences based on name'''
Sequences = []
Currentsequence = []
filepath = path + '/allseqs.txt' #Open reference sequence file
f = open(filepath, 'r') #open content of current file
for line in f:
line = line.replace('\n', '')
if line[0] == '>':
if Currentsequence == []:
name, rest = line.split('_')
Currentsequence.append(name)
elif Currentsequence[0] in line:
Sequences.append(Currentsequence)
else:
Currentsequence = []
name, rest = line.split('_')
Currentsequence.append(name)
elif line[0] == 'A' or line[0] == 'T' or line[0] == 'C' or line[0] == 'G':
Currentsequence.append(line)
elif line[0] == 'N':
print('Sequence starts with N')
else:
print('Something is wrong')
f.close()
return Sequences
#write a function for de-novo assembly without refseq
def assemble():
'''Assembles all of the sequences in every group (if possible)'''
#take one seq, find the best match, combine them. Start over.
for i in range(len(seqdata)): #for all of the sequence groups
fw_list = []
rv_list = []
seqdata[i]['contig']['dna'] = ''
samples = copy.deepcopy(seqdata[i]['samples']) #copy samples so that I can delete them as I go
overlap_found = False #has overlap been found?
whole_list = False #did we traverse the whole list?
while overlap_found is False and whole_list is False:
overlap_found = False #has overlap been found?
whole_list = False #did we traverse the whole list?
for n in range(len(samples)):
for o in range(n, len(samples)):
fw_dict = {}
seq1 = seqdata[i]['samples'][0]['dna']
seq2 = seqdata[i]['samples'][n]['dna']
forward = findoverlap(seq1, seq2)
if forward is not False:
overlap_found = True
fw_list.append(forward[2])
seq1 = seqdata[i]['samples'][0]['dna']
seq2 = seqdata[i]['samples'][n]['dna']
reverse = findoverlap(seq1, DNA.reversecomplement(seq2))
if reverse is not False:
overlap_found = True
rv_list.append(forward[2])
if overlap_found is True:
if max(fw_list) >= max(rv_list):
index, value = max(enumerate(fw_list))
elif max(fw_list) < max(rv_list):
index, value = max(enumerate(fw_list))
whole_list = True
def analyze():
###### here I call the functions #########
alnresults = path + '/' + 'alnresults.txt' #get the path for the results file (output file)
f = open(alnresults, 'w') #open it for writing
results = path + '/' + 'results.txt' #get the path for the results file (output file)
a = open(results, 'w') #open it for writing
for i in range(len(seqdata)):
f.write('>%str\n' % seqdata[i]['reference']['name'])
f.write('%s\n' % seqdata[i]['reference']['aln_dna'])
n = 1
while n < len(seqdata[i]['samples']):
f.write('%s\n' % seqdata[i]['samples'][n]['name'])
f.write('%s\n' % seqdata[i]['samples'][n]['aln_dna'])
####### fix the assembly method
####### save it in 'contig'
assembled = join(entry[n], entry[i])
if assembled==False:
n = i
else:
entry[i] = ''
entry[n] = assembled
# for i in range(len(entry)):
# if i == 0:
# a.write('>' + entry[i])
# a.write('\n')
# else:
# a.write(entry[i])
# a.write('\n')
#
#check whether any mutations are present
#this is a shortcut for now
seqdata[i]['contig'] = {'name': seqdata[i]['samples'][0]['name']}
seqdata[i]['contig']['dna'] = seqdata[i]['samples'][0]['dna']
check(seqdata[i])
f.close()
a.close()
if __name__ == '__main__': #if script is run by itself and not loaded
import sys
assert len(sys.argv) == 2, 'Error, this script requires a path to a folder containing the sequencing files as an argument.'
print('Opening %s' % str(sys.argv[1]))
path = str(sys.argv[1]) #Path to folder that contains the sequences
FindSingleGeneMissmatch = 'Y' #Test for one gene whether missmatches occur or not. It is expected that RefSeq starts with ATG
#this grabs all sequences from a folder, removes N, joins them, and checks for mutations
all_files_from_path(path) #to get all files from a folder
writeseqfiles(path) #writes sequences to allseqs
# pprint.pprint(seqdata)
# #for making alignment
# for i in range(len(seqdata)): #for all entries (groups of sequences)
# getreference(path, i)
# M_align_iterative(i)