-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathONTbarcoder2.py
More file actions
6999 lines (6572 loc) · 403 KB
/
ONTbarcoder2.py
File metadata and controls
6999 lines (6572 loc) · 403 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python
# -*- coding: utf-8 -*-
#A few attributions to community in StackOverflow that helped with the little tricks on GUI building: including selection of table and copying to excel: https://stackoverflow.com/questions/40225270/copy-paste-multiple-items-from-qtableview-in-pyqt4 by user learncode, path expansion by https://stackoverflow.com/questions/56712979/expand-item-in-qtreeview-with-qfilesystemmodel by eyllanesc.
import sys,fileinput,os,time,copy,itertools,fnmatch,shutil,random,multiprocessing,xlsxwriter,tempfile,io,warnings
warnings.filterwarnings(action='ignore',module='.*paramiko.*')
import subprocess32 as subprocess
from datetime import datetime
from copy import deepcopy
import gzip
import paramiko,base64
from Bio import SeqIO
from Bio import Application
from Bio import Entrez
from Bio.Seq import Seq
#from Bio.Alphabet import IUPAC
from collections import Counter
from itertools import zip_longest
from PyQt5 import QtWidgets,QtCore,QtGui
from PyQt5.QtWidgets import QPushButton
from pyqtgraph.Qt import QtGui, QtCore
import pyqtgraph as pg
import re
import csv
import datetime
import edlib
import seqpy
import openpyxl,uuid
from numpy import *
import numpy as np
client = paramiko.SSHClient()
class livedetector(QtCore.QThread):
taskFinished=QtCore.pyqtSignal(int)
notifyProgress=QtCore.pyqtSignal(int)
notifyMessage=QtCore.pyqtSignal(str)
def __init__(self,indir,parent=None):
super(livedetector, self).__init__(parent)
self.livedir=indir
def run(self):
while True:
interval = 1
old_f = os.listdir(self.livedir)
old_f=[x for x in old_f if ".fastq" in x]
time.sleep(interval)
new_f = os.listdir(self.livedir)
new_f=[x for x in new_f if ".fastq" in x]
# print old_f,new_f
self.new_files = list(set(new_f) - set(old_f))
if len(self.new_files)>0:
time.sleep(5)
if self.new_files[0].endswith(".gz"):
self.notifyProgress.emit(1)
elif self.new_files[0].endswith(".fastq"):
self.notifyProgress.emit(0)
# print "changed",self.new_files
break
class liveremotedetector(QtCore.QThread):
taskFinished=QtCore.pyqtSignal(int)
notifyProgress=QtCore.pyqtSignal(int)
notifyMessage=QtCore.pyqtSignal(str)
def __init__(self,indir,hostname,username,password,parent=None):
super(liveremotedetector, self).__init__(parent)
self.remotepath=indir
self.hostname=hostname
self.username=username
self.password=password
def run(self):
def readremotedir(remotepath):
stdin, stdout, stderr = client.exec_command('ls '+remotepath)
newlist=[]
for line in stdout:
newlist.append(line.encode(encoding="utf-8").strip())
return newlist
while True:
try:
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(self.hostname, username=self.username, password=self.password)
# print "remote transfer running"
old_f = readremotedir(self.remotepath)
interval = 1
time.sleep(interval)
new_f = readremotedir(self.remotepath)
# print old_f,new_f
self.new_files = list(set(new_f) - set(old_f))
client.close()
if len(self.new_files)>0:
self.notifyProgress.emit(1)
# print "changed",self.new_files
break
except Exception as e:
print (e)
class liveremotetransfer(QtCore.QThread):
taskFinished=QtCore.pyqtSignal(int)
notifyProgress=QtCore.pyqtSignal(int)
notifyMessage=QtCore.pyqtSignal(str)
def __init__(self,indir,localpath,inlist,hostname,username,password,parent=None):
super(liveremotetransfer, self).__init__(parent)
self.remotepath=indir
self.localpath=localpath
self.inlist=inlist
self.hostname=hostname
self.username=username
self.password=password
def run(self):
# client=self.client
# print "transferring",self.remotepath,self.localpath,self.inlist,self.client
def transferfile(inlist,client):
ftp_client=client.open_sftp()
for f in inlist:
ftp_client.get(self.remotepath+"/"+f,os.path.join(self.localpath,f))
ftp_client.close()
try:
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(self.hostname, username=self.username, password=self.password)
transferfile(self.inlist,client)
client.close()
except Exception as e:
print (e, "couldn't transfer", self.inlist)
# transferfile(self.inlist)
self.taskFinished.emit(1)
class livefast5detector(QtCore.QThread):
taskFinished=QtCore.pyqtSignal(int)
notifyProgress=QtCore.pyqtSignal(int)
notifyMessage=QtCore.pyqtSignal(str)
def __init__(self,indir,parent=None):
super(livefast5detector, self).__init__(parent)
self.fast5dir=indir
def run(self):
while True:
interval = 1
old_f = os.listdir(self.fast5dir)
time.sleep(interval)
new_f = os.listdir(self.fast5dir)
# print "olf_f",old_f,new_f
self.new_files = list(set(new_f) - set(old_f))
if len(self.new_files)>0:
with open("inlistfast5.txt",'w') as outfile:
outfile.write("\n".join(self.new_files))
self.notifyProgress.emit(1)
# print "new fast5",self.new_files
break
class livepod5detector(QtCore.QThread):
taskFinished=QtCore.pyqtSignal(int)
notifyProgress=QtCore.pyqtSignal(int)
notifyMessage=QtCore.pyqtSignal(str)
def __init__(self,indir,parent=None):
super(livepod5detector, self).__init__(parent)
self.pod5dir=indir
def run(self):
while True:
interval = 1
old_f = os.listdir(self.pod5dir)
old_f=[x for x in old_f if x.endswith(".pod5")]
time.sleep(interval)
new_f = os.listdir(self.pod5dir)
new_f=[x for x in new_f if x.endswith(".pod5")]
# print("olf_f",old_f,new_f)
self.new_files = list(set(new_f) - set(old_f))
if len(self.new_files)>0:
with open("inlistpod5.txt",'w') as outfile:
outfile.write("\n".join(self.new_files))
self.notifyProgress.emit(1)
# print("new pod5",self.new_files)
break
class livesamplecount(QtCore.QThread):
taskFinished=QtCore.pyqtSignal(int)
notifyProgress=QtCore.pyqtSignal(int)
notifyMessage=QtCore.pyqtSignal(str)
def __init__(self,indir,sampleids,mincoverage,largecoverage,largecoveragestep,maxcoverage,parent=None):
super(livesamplecount, self).__init__(parent)
self.livedir=indir
self.localsampleids=deepcopy(sampleids)
self.mincoverage=mincoverage
self.largecoverage=largecoverage
self.largecoveragestep=largecoveragestep
self.maxcoverage=maxcoverage
self.flag=True
def update_sampleids(self,sampleids2):
if self.flag==True:
oldsampleids=self.localsampleids
# print "length of old-sampleids is",len(oldsampleids),len(sampleids2)
self.todolist=[]
for k in sampleids2:
d=sampleids2[k]-oldsampleids[k]
if d>=1:
if self.maxcoverage==0:
if sampleids2[k]>=self.mincoverage:
if sampleids2[k]<=self.largecoverage:
self.todolist.append(k)
else:
if d>=self.largecoveragestep:
self.todolist.append(k)
else:
if sampleids2[k]>=self.mincoverage:
if sampleids2[k]<=self.largecoverage:
self.todolist.append(k)
else:
if d>=self.largecoveragestep:
if sampleids2[k]<=self.maxcoverage:
self.todolist.append(k)
if len(self.todolist)>0:
# print 'sampledetected',self.todolist
self.flag=False
self.localsampleids=deepcopy(sampleids2)
self.taskFinished.emit(1)
else:
# print 'livetector running no sample detected'
self.flag=True
def run(self):
while True:
interval = 1
time.sleep(interval)
if self.flag==True:
# print "consensus not running"
self.notifyProgress.emit(1)
else:
pass
# print "consensus running"
# if self.flag==True:
# print "running live sample count"
# self.flag=False
# else:
# break
class liveguppyrun(QtCore.QThread):
taskFinished=QtCore.pyqtSignal(int)
notifyProgress=QtCore.pyqtSignal(int)
notifyMessage=QtCore.pyqtSignal(str)
def __init__(self,guppyparams,outpath,guppyoutpath,iternum,parent=None):
super(liveguppyrun, self).__init__(parent)
self.outpath=outpath
self.guppyparams=guppyparams
self.guppyoutpath=guppyoutpath
self.iternum=iternum
def run(self):
time.sleep(30)
stdout=subprocess.check_output(self.guppyparams,shell=True)
with open(os.path.join(self.outpath,"guppylog"), "wb") as handle:
handle.write(stdout)
fastqlist = os.listdir(os.path.join(self.guppyoutpath,"temp"))
fastqlist=[x for x in fastqlist if x.endswith(".fastq")]
for fname in fastqlist:
os.rename(os.path.join(self.guppyoutpath,"temp",fname), os.path.join(self.guppyoutpath,str(self.iternum)+"_"+fname))
self.taskFinished.emit(1)
class livedoradorun(QtCore.QThread):
taskFinished=QtCore.pyqtSignal(int)
notifyProgress=QtCore.pyqtSignal(int)
notifyMessage=QtCore.pyqtSignal(str)
def __init__(self,doradoparams,outpath,doradooutpath,iternum,inlist,inpath,outpathfastq,parent=None):
super(livedoradorun, self).__init__(parent)
self.outpath=outpath
self.doradoparams=doradoparams
self.doradooutpath=doradooutpath
self.iternum=iternum
self.inlist=inlist
self.doradoinpath=inpath
self.outpathfastq=outpathfastq
def run(self):
time.sleep(30)
os.mkdir(os.path.join(self.doradoinpath,"temp"+str(self.iternum)))
for f in self.inlist:
shutil.copyfile(os.path.join(self.doradoinpath,f), os.path.join(self.doradoinpath,"temp"+str(self.iternum),f))
self.doradoparams=self.doradoparams.replace("ignorethis","temp"+str(self.iternum))
stdout=subprocess.check_output(self.doradoparams,shell=True)
with open(os.path.join(self.doradooutpath,str(self.iternum)+".fastq"), "wb") as handle:
handle.write(stdout)
fastqlist = os.listdir(os.path.join(self.doradooutpath,"temp"))
fastqlist=[x for x in fastqlist if x.endswith(".fastq")]
for fname in fastqlist:
os.rename(os.path.join(self.doradooutpath,"temp",fname), os.path.join(self.doradooutpath,str(self.iternum)+"_"+fname))
self.taskFinished.emit(1)
class runconsensuslive(QtCore.QThread):
taskFinished=QtCore.pyqtSignal(list)
notifyProgress=QtCore.pyqtSignal(int)
notifyMessage=QtCore.pyqtSignal(int)
notifyMessage2=QtCore.pyqtSignal(int)
def __init__(self,outpath,todolist,consensesfreqfixed,consensesfreqrange,consensesfreqstep,gencode,plen,ndone,maxcoverage,subsetmax,sampleids,parent=None):
super(runconsensuslive, self).__init__(parent)
self.outpath=outpath
self.todolist=todolist
self.fixthresh=consensesfreqfixed
self.rangefreq=consensesfreqrange
self.stepsize=consensesfreqstep
self.ingencode=gencode
self.plen=plen
self.ndone=ndone
self.maxcoverage=maxcoverage
self.subsetmax=subsetmax
self.sampleids=sampleids
def run(self):
fixthresh=self.fixthresh
rangefreq=self.rangefreq
stepsize=self.stepsize
ingencode=self.ingencode
maxcoverage=self.maxcoverage
plen=self.plen
def consensus(indict,perc_thresh,abs_thresh):
if len(indict.keys())>=abs_thresh:
poslist=[]
n=0
while n<len(list(indict.values())[0]):
newlist=[]
for i,each in enumerate(indict.keys()):
try:
newlist.append(indict[each][n])
except IndexError:
break
poslist.append(newlist)
n+=1
sequence=[]
countpos=1
for character in poslist:
charcounter=Counter(character)
baseset={}
for k,v in charcounter.items():
percbp=float(v)/float(len(character))
if percbp>perc_thresh:
baseset[k]=v
if len(baseset)==0:
bp='N'
if len(baseset)==1:
bp=list(baseset.keys())[0]
if len(baseset)>1:
try:
del baseset["-"]
if len(baseset)==1:
bp=list(baseset.keys())[0]
else:
bp='N'
except KeyError:
bp="N"
sequence.append(bp)
countpos+=1
return ''.join(sequence)
else:
return ''
def subset_bylength (infile,outfile,n,plen):
samplesize=0
with open(infile) as fulldata:
with open(outfile,'w') as subsetdata:
l=fulldata.readlines()
tseqdict={}
tlendict={}
for i,j in enumerate(l):
if ">" in j:
samplesize+=1
tlendict[j]=abs(plen-len(l[i+1].strip()))
tseqdict[j]=l[i+1]
d=sorted(tlendict.items(), key=lambda x: x[1])
v=0
ntosubset=min(len(tseqdict),n)
while v<ntosubset:
subsetdata.write(d[v][0]+tseqdict[d[v][0]])
v+=1
return samplesize
def translate_corframe(seq,gencode):
translatedset=[]
each=seq
corframe=get_cor_frame(each.replace("-",""),gencode)
if corframe==1:
translation=Seq(each.replace('-','')).translate(table=gencode,to_stop=True).__str__()
explen=len(each.replace('-',''))
if corframe==2:
translation=Seq(each[1:].replace('-','')).translate(table=gencode,to_stop=True).__str__()
explen=len(each[1:].replace('-',''))
if corframe==3:
translation=Seq(each[2:].replace('-','')).translate(table=gencode,to_stop=True).__str__()
explen=len(each[2:].replace('-',''))
if corframe==4:
translation=Seq(each.replace('-','')).reverse_complement().translate(table=gencode,to_stop=True).__str__()
explen=len(Seq(each.replace('-','')).__str__())
if corframe==5:
translation=Seq(each[:-1].replace('-','')).reverse_complement().translate(table=gencode,to_stop=True).__str__()
explen=len(Seq(each[:-1].replace('-','')).__str__())
if corframe==6:
translation=Seq(each[:-2].replace('-','')).reverse_complement().translate(table=gencode,to_stop=True).__str__()
explen=len(Seq(each[:-2].replace('-','')).__str__())
if len(translation)<int(explen/3):
return "0"
elif len(translation)==int(explen/3):
return "1"
def get_cor_frame(seq,gencode):
seqset=[Seq(seq),Seq(seq[1:]),Seq(seq[2:]),Seq(seq).reverse_complement(),Seq(seq[:-1]).reverse_complement(),Seq(seq[:-2]).reverse_complement()]
aminoset=[]
for each in seqset:
a=each.translate(table=gencode,to_stop=True)
aminoset.append(a.__str__())
maxlen,corframe=0,0
for i,each in enumerate(aminoset):
if len(each)>maxlen:
maxlen=len(each)
corframe=i+1
return corframe
def callconsensus(i,perc_thresh,abs_thresh,name):
with open(i) as infile:
l=infile.readlines()
seqdict,poslist={},[]
for i,j in enumerate(l):
if ">" in j:
poslist.append(i)
for i,j in enumerate(poslist):
ambcounts=0
k01=l[j].strip().split('>')[1]
if i!=len(poslist)-1:
k3=l[j+1:poslist[i+1]]
if i==len(poslist)-1:
k3=l[j+1:]
k4=''.join(k3).replace('\n','')
seqdict[k01]=k4.replace("E","A").replace("F","G").replace("Q","C").replace("P","T")
conseq=consensus(seqdict,perc_thresh,abs_thresh)
conseq=conseq.replace("-",'')
flag=False
if len(conseq)!=0:
transcheck=translate_corframe(conseq,ingencode)
coverage=len(seqdict.keys())
if len(conseq)==plen:
if conseq.count("N")==0:
if translate_corframe(conseq,ingencode)=="1":
flag=True
else:
transcheck="NA"
coverage="NA"
return transcheck,conseq,flag,coverage
transcheck={}
conseqs={}
flags={}
coverages={}
sampleids={}
parstring=''
with open("parfile") as parfile:
l=parfile.readlines()
parstring=l[0].strip()
self.todolist=[x+"_all.fa" for x in self.todolist]
for c,name in enumerate(self.todolist):
if self.subsetmax==True:
if self.sampleids[name.split("_all.fa")[0].split(".")[0]]<=maxcoverage:
indir2="Demultiplexed"
else:
indir="Demultiplexed"
indir2="Subsets"
else:
indir2="Demultiplexed"
try:
if self.subsetmax==False:
cmd='disttbfast.exe '+parstring+' -i '+os.path.join(self.outpath,indir2,name)
else:
if self.sampleids[name.split("_all.fa")[0].split(".")[0]]<=maxcoverage:
cmd='disttbfast.exe '+parstring+' -i '+os.path.join(self.outpath,indir2,name)
else:
sampleids[name.split("_all.fa")[0].split(".")[0]]=subset_bylength(os.path.join(self.outpath,indir,name),os.path.join(self.outpath,indir2,name),maxcoverage,plen)
cmd='disttbfast.exe '+parstring+' -i '+os.path.join(self.outpath,indir2,name)
with open(os.devnull, 'w') as devnull:
stdout=subprocess.check_output(cmd,shell=True, stderr=devnull)
with open(os.path.join(self.outpath,"Aligned",name + '_aln.fasta'), "wb") as handle:
handle.write(stdout)
transcheckeach,conseq,flag,cov=callconsensus(os.path.join(self.outpath,"Aligned",name+"_aln.fasta"),fixthresh,5,name)
otherconseqs=[]
if flag==True:
transcheck[name.split("_all.fa")[0].split(".")[0]]=transcheckeach
conseqs[name.split("_all.fa")[0].split(".")[0]]=conseq
flags[name.split("_all.fa")[0].split(".")[0]]=flag
if cov!="NA":
coverages[name.split("_all.fa")[0].split(".")[0]]=cov
self.ndone+=1
self.notifyMessage.emit(self.ndone)
else:
n=rangefreq[1]
while n>=rangefreq[0]:
if n!=fixthresh:
transcheckeach2,conseq2,flag2,cov2=callconsensus(os.path.join(self.outpath,"Aligned",name+"_aln.fasta"),n,5,name)
if flag2==True:
if conseq2 not in otherconseqs:
otherconseqs.append(conseq2)
n-=stepsize
if len(otherconseqs)==1:
transcheck[name.split("_all.fa")[0].split(".")[0]]="1"
conseqs[name.split("_all.fa")[0].split(".")[0]]=otherconseqs[0]
flags[name.split("_all.fa")[0].split(".")[0]]=True
if cov!="NA":
coverages[name.split("_all.fa")[0].split(".")[0]]=cov
coverages[name.split("_all.fa")[0].split(".")[0]]=cov
self.ndone+=1
self.notifyMessage.emit(self.ndone)
else:
transcheck[name.split("_all.fa")[0].split(".")[0]]=transcheckeach
conseqs[name.split("_all.fa")[0].split(".")[0]]=conseq
flags[name.split("_all.fa")[0].split(".")[0]]=flag
if cov!="NA":
coverages[name.split("_all.fa")[0].split(".")[0]]=cov
except Application.ApplicationError:
transcheck[name.split("_all.fa")[0].split(".")[0]]="NA"
conseqs[name.split("_all.fa")[0].split(".")[0]]=""
flags[name.split("_all.fa")[0].split(".")[0]]=False
if cov!='NA':
coverages[name.split("_all.fa")[0].split(".")[0]]="NA"
self.result=[transcheck,conseqs,flags,coverages]
self.donelist=[]
with open(os.path.join(self.outpath,"consensus_good.fa"),'a') as outfile:
for each in self.result[2].keys():
if flags[each]==True:
outfile.write(">"+each+";"+str(coverages[each])+'\n'+conseqs[each]+'\n')
self.donelist.append(each)
with open(os.path.join(self.outpath,"Consensus",each),'w') as o:
o.write(">"+each+";"+str(coverages[each])+'\n'+conseqs[each]+'\n')
else:
with open(os.path.join(self.outpath,"Consensus",each),'w') as o:
o.write(">"+each+";"+str(coverages[each])+'\n'+conseqs[each]+'\n')
with open(os.path.join(self.outpath,"consensus_all.fa"),'w') as outfile:
for filename in os.listdir(os.path.join(self.outpath,"Consensus")):
with open(os.path.join(self.outpath,"Consensus",filename)) as readfile:
shutil.copyfileobj(readfile,outfile)
self.taskFinished.emit(self.donelist)
# print "running consensus complete",self.ndone
class rundemultiplexlive(QtCore.QThread):
taskFinished=QtCore.pyqtSignal(int)
notifyProgress=QtCore.pyqtSignal(int)
notifyMessage=QtCore.pyqtSignal(int)
notifyMessage2=QtCore.pyqtSignal(int,int)
def __init__(self,livedir,newfiles,outpath,tagdict,muttags_fr,sampledict,typedict,primerfset,primerrset,taglen,primerlensum,samplecounts,totalseqs,ndemultiplexed,ndemultiplexedused,minlen,explen,demlen,primersearchlen,tagmm,compression,primermismatch,parent=None):
super(rundemultiplexlive, self).__init__(parent)
self.livedir=livedir
self.newfiles=newfiles
self.outpath=outpath
self.tagdict=tagdict
self.muttags_fr=muttags_fr
self.sampledict=sampledict
self.typedict=typedict
self.primerfset=primerfset
self.primerrset=primerrset
self.taglen=taglen
self.primerlensum=primerlensum
self.samplecounts=samplecounts
self.totalseqs=totalseqs
self.ndemultiplexed=ndemultiplexed
self.ndemultiplexedused=ndemultiplexedused
self.minlen=minlen
self.explen=explen
self.demlen=demlen
self.primersearchlen=primersearchlen
self.tagmm=tagmm
self.compression=compression
self.primermismatch=primermismatch
def run(self):
minlen=self.minlen
explen=self.explen
demlen=self.demlen
primersearchlen=self.primersearchlen
# self.totalseqs=0
self.nseqspasslen=0
self.nseqsfordemultiplexing=0
self.nseqsfordemultiplexingpresplit1=0
self.nseqsfordemultiplexingpresplit2=0
self.nwronglengthwindow=0
# print "Totalseqs before dem",self.totalseqs
# print "Demultiplexed before dem",self.ndemultiplexed
def findmatch_m2(taglist,muttags_fr,indict,seqdict,sampledict,typedict,samplecounts,filename):
# print taglist
# print "sample",sampledict
dmpfile=open(os.path.join(self.outpath,"dmpfile"),'a')
idcombs={}
cumscores={}
for each in indict.keys():
try:
idcombs[each]=(taglist[indict[each][0]], taglist[indict[each][1]])
cumscore=typedict[indict[each][0]]+typedict[indict[each][1]]
cumscores[each]=[str(typedict[indict[each][0]]),str(typedict[indict[each][1]]),str(cumscore)]
except KeyError:
pass
matched_idcombs={}
for each in idcombs.keys():
try:
sampledict[idcombs[each]]
self.ndemultiplexed+=1
with open(os.path.join(self.outpath,"Demultiplexed",sampledict[idcombs[each]]+"_all.fa"),'a') as outfile:
outfile.write(">"+filename+"_"+each+" _"+"_".join(cumscores[each])+"\n"+seqdict[each]+"\n")
self.samplecounts[sampledict[idcombs[each]]]+=1
self.ndemultiplexedused+=1
except KeyError:
pass
dmpfile.close()
def readprimertagfasta(filef,filer):
indict2,indict1,indict={},{},{}
with open(filef) as infile1:
with open(filer) as infile2:
l1=infile1.readlines()
l2=infile2.readlines()
for i,j in enumerate(l1):
if ">" in j:
indict1[j.strip().replace(">","")]=l1[i+1].strip()
indict[j.strip().replace(">","")]=[0,0]
for i,j in enumerate(l2):
if ">" in j:
indict2[j.strip().replace(">","")]=l2[i+1].strip()
indict[j.strip().replace(">","")]=[0,0]
return indict1,indict2,indict
def builddict_sequences(infile):
seqdict={}
with open(infile) as inseqs:
l=inseqs.readlines()
for i,j in enumerate(l):
if ">" in j:
seqdict[j.strip().replace(">","")]=l[i+1].strip()
return seqdict
def modseq(seq):
for bp in ["A","T","G","C"]:
n=20
while n>2:
seq=seq.replace(bp*n,bp*2)
n-=1
return seq
def demultiplexfunc(pf,pr,seqdict,tagdict,muttags_fr,sampledict,typedict,num_row,filename):
indict1,indict2,indict=readprimertagfasta(pf,pr)
for each in list(indict.keys()):
try:
indict[each][0]=indict1[each]
indict[each][1]=indict2[each]
except KeyError:
del indict[each]
try:
with open(os.path.join(self.outpath,"dmpfile_tagfr"),'w') as tagfrdmp:
for tag in muttags_fr.keys():
tagfrdmp.write(str(tag)+'\t'+muttags_fr[tag]+'\n')
findmatch_m2(tagdict, muttags_fr,indict,seqdict,sampledict,typedict,num_row,filename)
except UnboundLocalError:
findmatch_m2(tagdict, {},indict,seqdict,sampledict,typedict,num_row,filename)
def cleantagfile(infile):
with open(infile) as primertagfile:
with open(infile+"cleaned",'w') as primertagfile_cleaned:
taglines=primertagfile.readlines()
ids=[]
seqs={}
for n,line in enumerate(taglines):
if ">" in line:
ids.append(line)
seqs[line]=modseq(taglines[n+1])[-(taglen+1):]
idcounts=Counter(ids)
nseqs=0
for id in ids:
if idcounts[id]==1:
nseqs+=1
primertagfile_cleaned.write(id+seqs[id])
for newfile in self.newfiles:
if self.compression==0:
# print "uncompressed"
with open(os.path.join(self.livedir,newfile)) as infile:
with open(os.path.join(self.outpath,"Processing",newfile+"_reformat_out"),'w') as outfile:
n=1
for line1,line2,line3,line4 in itertools.zip_longest(*[infile]*4):
if line1[0]=="@":
seqid=">"+line1[1:]
sequence=line2.strip()
if len(sequence)>minlen:
outfile.write(seqid+line2)
self.nseqspasslen+=1
n+=1
self.totalseqs+=1
elif self.compression==1:
# print "compressed"
with gzip.open(os.path.join(self.livedir,newfile),'rb') as infile:
with open(os.path.join(self.outpath,"Processing",newfile+"_reformat_out"),'w') as outfile:
n=1
for line1,line2,line3,line4 in itertools.zip_longest(*[infile]*4):
if line1[0]=="@":
seqid=">"+line1[1:].strip()
sequence=line2.strip()
if len(sequence)>minlen:
outfile.write(seqid+'\n'+sequence+'\n')
self.nseqspasslen+=1
n+=1
self.totalseqs+=1
self.notifyMessage.emit(self.totalseqs)
with open(os.path.join(self.outpath,"Processing",newfile+"_reformat_out_1pdt"),'w') as file1:
with open(os.path.join(self.outpath,"Processing",newfile+"_reformat_out_2pdt"),'w') as file2:
with open(os.path.join(self.outpath,"Processing",newfile+"_reformat_out")) as infile:
for line1,line2 in itertools.zip_longest(*[infile]*2):
if len(line1.strip())!=0:
seqid=line1
sequence=line2.strip()
if len(sequence)<explen+self.taglen*2+self.primerlensum+demlen:
file1.write(seqid+line2)
self.nseqsfordemultiplexing+=1
self.nseqsfordemultiplexingpresplit1+=1
elif len(sequence)>(explen+self.taglen*2+self.primerlensum)*2 - demlen and len(sequence)<(explen+self.taglen*2+self.primerlensum+demlen)*2 :
file2.write(seqid.strip()+" p1\n"+sequence[:explen+self.taglen*2+self.primerlensum+demlen]+'\n')
file2.write(seqid.strip()+" p2\n"+sequence[(explen+self.taglen*2+self.primerlensum-demlen):]+'\n')
self.nseqsfordemultiplexing+=2
self.nseqsfordemultiplexingpresplit2+=1
else:
self.nwronglengthwindow+=1
typedict2={newfile+"_reformat_out_1pdt":primersearchlen,newfile+"_reformat_out_2pdt":primersearchlen*2}
c=0
nseqs=0
for infile2 in [newfile+"_reformat_out_1pdt",newfile+"_reformat_out_2pdt"]:
ambiguity_codes=[("R", "A"), ("R", "G"),("M", "A"), ("M", "C"),("S", "C"), ("S", "G"),("Y", "C"), ("Y", "T"),("K", "G"), ("K", "T"),("W", "A"), ("W", "T"),("V", "A"), ("V", "C"),("V", "G"),("H", "A"),("H", "C"),("H", "T"),("D", "A"), ("D", "G"),("D", "T"), ("B", "C"),("B", "G"), ("B", "T"),("N", "A"), ("N", "G"), ("N", "C"), ("N", "T")]
inputseqs=builddict_sequences(os.path.join(self.outpath,"Processing",infile2))
seqlens=[len(i.strip()) for i in inputseqs.values()]
with open(os.path.join(self.outpath,"Processing",infile2+"_all_glsearch1.parsed.lencutoff5parsed_f"),'w') as tagfoutfile:
with open(os.path.join(self.outpath,"Processing",infile2+"_all_glsearchR.parsed.lencutoff5parsed_r"),'w') as tagroutfile:
with open(os.path.join(self.outpath,"Processing",infile2+"_all_glsearchR.parsed.lencutoff5endr"),'w') as fprimercleanfile:
for pf in self.primerfset:
for pr in self.primerrset:
pr=seqpy.revcomp(pr)
for n,inseq in enumerate(inputseqs.keys()):
c+=1
if n%1000==0:
progress = float(c)
compseq=seqpy.revcomp(inputseqs[inseq])
k1 = edlib.align(pf, inputseqs[inseq][:typedict2[infile2]], mode='HW',task='path',additionalEqualities=ambiguity_codes)
k2 = edlib.align(pf, compseq[:typedict2[infile2]], mode='HW',task='path',additionalEqualities=ambiguity_codes)
d1 = k1['editDistance']
d2 = k2['editDistance']
orient=0
revseq=''
if d1<=d2:
if d1<=self.primermismatch:
loc=k1['locations'][0]
tagseq=inputseqs[inseq][loc[0]-self.taglen:loc[0]]
if len(tagseq)!=0:
# print "pf",inseq,d1,loc,len(rev_comp(compseq[loc[1]+1:]))
tagfoutfile.write(">"+inseq+'\n'+tagseq+'\n')
revseq=inputseqs[inseq][loc[1]+1:]
else:
if d2<=self.primermismatch:
loc=k2['locations'][0]
tagseq=compseq[loc[0]-self.taglen:loc[0]]
if len(tagseq)!=0:
# print "pfR",inseq,d2,loc,len(rev_comp(compseq[loc[1]+1:]))
tagfoutfile.write(">"+inseq+'\n'+tagseq+'\n')
revseq=compseq[loc[1]+1:]
orient=1
if revseq!='':
k = edlib.align(pr, revseq[-typedict2[infile2]:], mode='HW',task='path',additionalEqualities=ambiguity_codes)
d = k['editDistance']
if d<=self.primermismatch:
loc=k['locations'][0]
startpoint=len(revseq)-typedict2[infile2]
tagseq=seqpy.revcomp(revseq[startpoint+loc[1]+1:startpoint+loc[1]+self.taglen+1])
if len(tagseq)!=0:
tagroutfile.write(">"+inseq+'\n'+tagseq+'\n')
if orient==0:
fprimercleanfile.write(">"+inseq+'\n'+revseq[:startpoint+loc[0]]+'\n')
else:
fprimercleanfile.write(">"+inseq+'\n'+revseq[:startpoint+loc[0]].replace("A","E").replace("G","F").replace("C","Q").replace("T","P")+'\n')
#cleantagfile(outpath+"/"+infile+"_all_glsearch1.parsed.lencutoff5parsed_f")
#cleantagfile(outpath+"/"+ infile+"_all_glsearchR.parsed.lencutoff5parsed_r")
inputseqs=builddict_sequences(os.path.join(self.outpath,"Processing",infile2+"_all_glsearchR.parsed.lencutoff5endr"))
demultiplexfunc(os.path.join(self.outpath,"Processing",infile2+"_all_glsearch1.parsed.lencutoff5parsed_f"),os.path.join(self.outpath,"Processing",infile2+"_all_glsearchR.parsed.lencutoff5parsed_r"), inputseqs,self.tagdict,self.muttags_fr,self.sampledict,self.typedict,0,infile2)
# self.ndemultiplexed+=subdemultiplexedn
# print infile2,self.ndemultiplexedused,self.ndemultiplexed
self.notifyMessage2.emit(self.ndemultiplexedused,self.ndemultiplexed)
self.taskFinished.emit(0)
class prepdemultiplexlive(QtCore.QThread):
taskFinished=QtCore.pyqtSignal(int)
notifyProgress=QtCore.pyqtSignal(int)
notifyMessage=QtCore.pyqtSignal(str)
def __init__(self,demfile,logfile,tagmm,parent=None):
super(prepdemultiplexlive, self).__init__(parent)
self.demfile=demfile
self.logfile=logfile
self.tagmm=tagmm
def run(self):
def crmutant_m2(tfile,nbp):
tagdict={}
sampledict={}
with open(tfile,'rb') as tagfile:
t=tagfile.readlines()
for each in t:
each=each.decode("utf-8-sig")
tagdict[each.split(',')[1].upper()]=''
tagdict[each.split(',')[2].upper()]=''
counter=1
typedict={}
for each in tagdict.keys():
tagdict[each]="t"+str(counter)
typedict[each]=0
counter+=1
with open(tfile,'rb') as tagfile:
t=tagfile.readlines()
for each in t:
each=each.decode("utf-8-sig")
sampledict[(tagdict[each.split(',')[1].upper()],tagdict[each.split(',')[2].upper()])]=each.split(',')[0].replace(" ","_")
n=1
while n<=nbp:
muttags_fr,newtags_fr=create_all_mutants(tagdict)
# newtags_fr_counts=Counter(newtags_fr)
with open("conflicts",'w') as conflictfile:
for k in newtags_fr.keys():
if len(newtags_fr[k])>1:
conflictfile.write(k+'\t'+",".join(newtags_fr[k])+'\n')
del muttags_fr[k]
ntagset=list(set(muttags_fr.keys())-set(tagdict.keys()))
# print len(tagdict),len(muttags_fr),len(ntagset)
for k in ntagset:
tagdict[k]=muttags_fr[k]
typedict[k]=n
n+=1
# with open(self.outdir+"/temp1.fas",'w') as outfile:
# for k in tagdict.keys():
# outfile.write(k+'\t'+tagdict[k]+'\n')
if nbp>0:
return tagdict,muttags_fr,sampledict,typedict
else:
return tagdict,tagdict,sampledict,typedict
def create_all_mutants(tagdict):
muttags,newtags={},{}
for tag in tagdict.keys():
submutant=createsubmutant(tag)
delmutant=createdelmutant(tag)
insmutant=createinsmutant(tag)
mutantset=list(set(submutant)|set(delmutant)|set(insmutant))
mutantset[:]=[x for x in mutantset if x != tag]
for mutant in mutantset:
try:
if tagdict[tag] not in newtags[mutant]:
newtags[mutant].append(tagdict[tag])
except:
newtags[mutant]=[tagdict[tag]]
muttags[mutant]= tagdict[tag]
return muttags,newtags
def createsubmutant(tag):
newlist=[]
bpset=["A","T","G","C"]
for i,v in enumerate(tag):
for bp in [x for x in bpset if x != v]:
if i==0:
newlist.append(bp+tag[i+1:])
if i>0 and i<len(tag)-1:
newlist.append(tag[0:i]+bp+tag[i+1:])
if i==len(tag)-1:
newlist.append(tag[0:i]+bp)
return newlist
def createdelmutant(tag):
newlist=[]
bpset=["A","T","G","C"]
for i,v in enumerate(tag):
for bp in bpset:
if i>0 and i<len(tag)-1:
newlist.append(bp+tag[0:i]+tag[i+1:])
if i==len(tag)-1:
newlist.append(bp+tag[0:i])
return newlist
def createinsmutant(tag):
newlist=[]
bpset=["A","T","G","C"]
for i,v in enumerate(tag):
for bp in bpset:
if i>0 and i<len(tag)-1:
newlist.append(tag[1:i]+bp+tag[i:])
if i==len(tag)-1:
newlist.append(tag[1:]+bp)
return newlist
self.sampleids={}
self.primerlensum=0
with open(self.demfile,'rb') as demulfile:
demullines=demulfile.readlines()
demullines=[x.decode("utf-8-sig") for x in demullines]
for each in demullines:
self.sampleids[each.split(',')[0].replace(" ","_")]=0
primerf=demullines[0].split(',')[3].upper()
primerr=demullines[0].split(',')[4].strip().upper()
self.taglen=len(demullines[0].split(',')[1])
self.primerfset=[primerf]
self.primerlensum+=len(primerf)+len(primerr)
self.primerrset=[primerr]
self.logfile.write("<br><br>Read demultiplexing file. There are "+str("{:,}".format(len(self.sampleids))) + " in your experiment.\n")
self.tagdict,self.muttags_fr,self.sampledict,self.typedict=crmutant_m2(self.demfile,self.tagmm)
self.taskFinished.emit(0)
class prepdemultiplex(QtCore.QThread):
taskFinished=QtCore.pyqtSignal(int)
notifyProgress=QtCore.pyqtSignal(int)
notifyMessage=QtCore.pyqtSignal(str)
def __init__(self,demfile,infastq,outdir,minlen,explen,demlen,logfile,tagmm,parent=None):
super(prepdemultiplex, self).__init__(parent)
self.demfile=demfile
self.infastq=infastq
self.outdir=outdir
self.minlen=minlen
self.explen=explen
self.logfile=logfile
self.demlen=demlen
self.tagmm=tagmm
def run(self):
def crmutant_m2(tfile,nbp):
tagdict={}
sampledict={}
with open(tfile,'rb') as tagfile:
t=tagfile.readlines()
for each in t:
each=each.decode("utf-8-sig")
tagdict[each.split(',')[1].upper()]=''
tagdict[each.split(',')[2].upper()]=''
counter=1
typedict={}
for each in tagdict.keys():
tagdict[each]="t"+str(counter)
typedict[each]=0
counter+=1
with open(tfile,'rb') as tagfile:
t=tagfile.readlines()
for each in t:
each=each.decode("utf-8-sig")
sampledict[(tagdict[each.split(',')[1].upper()],tagdict[each.split(',')[2].upper()])]=each.split(',')[0].replace(" ","_")
n=1
while n<=nbp:
muttags_fr,newtags_fr=create_all_mutants(tagdict)
# newtags_fr_counts=Counter(newtags_fr)
with open("conflicts",'w') as conflictfile:
for k in newtags_fr.keys():
if len(newtags_fr[k])>1:
conflictfile.write(k+'\t'+",".join(newtags_fr[k])+'\n')
del muttags_fr[k]
ntagset=list(set(muttags_fr.keys())-set(tagdict.keys()))
# print len(tagdict),len(muttags_fr),len(ntagset)
for k in ntagset:
tagdict[k]=muttags_fr[k]
typedict[k]=n
n+=1
with open(self.outdir+"/temp1.fas",'w') as outfile:
for k in tagdict.keys():
outfile.write(k+'\t'+tagdict[k]+'\n')
if nbp>0:
return tagdict,muttags_fr,sampledict,typedict
else:
return tagdict,tagdict,sampledict,typedict
def create_all_mutants(tagdict):
muttags,newtags={},{}
for tag in tagdict.keys():
submutant=createsubmutant(tag)
delmutant=createdelmutant(tag)
insmutant=createinsmutant(tag)
mutantset=list(set(submutant)|set(delmutant)|set(insmutant))
mutantset[:]=[x for x in mutantset if x != tag]
for mutant in mutantset:
try: