-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathONTbarcoder.py
More file actions
4055 lines (3878 loc) · 193 KB
/
ONTbarcoder.py
File metadata and controls
4055 lines (3878 loc) · 193 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
import subprocess32 as subprocess
from Bio import SeqIO
from Bio import Application
from Bio import Entrez
from Bio.Seq import Seq
from Bio.Alphabet import IUPAC,generic_dna
from collections import Counter
from itertools import izip_longest
from PyQt5 import QtWidgets,QtCore,QtGui
from PyQt5.QtWidgets import QPushButton
import re
import csv
import datetime
import edlib
import seqpy
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,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
def run(self):
def crmutant_m2(tfile,nbp):
tagdict={}
sampledict={}
with open(tfile) as tagfile:
t=tagfile.readlines()
for each in t:
tagdict[each.split(',')[1]]=''
tagdict[each.split(',')[2]]=''
counter=1
typedict={}
for each in tagdict.keys():
tagdict[each]="t"+str(counter)
typedict[each]=0
counter+=1
with open(tfile) as tagfile:
t=tagfile.readlines()
for each in t:
sampledict[(tagdict[each.split(',')[1]],tagdict[each.split(',')[2]])]=each.split(',')[0]
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 2>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
basename=os.path.basename(self.infastq)
self.sampleids={}
primerlensum=0
with open(self.demfile) as demulfile:
demullines=demulfile.readlines()
for each in demullines:
self.sampleids[each.split(',')[0]]=''
primerf=demullines[0].split(',')[3]
primerr=demullines[0].split(',')[4].strip()
self.taglen=len(demullines[0].split(',')[1])
self.primerfset=[primerf]
primerlensum+=len(primerf)+len(primerr)
self.primerrset=[primerr]
self.nseqspasslen=0
self.totalseqs=0
self.logfile.write("<br><br>Read demultiplexing file. There are "+str("{:,}".format(len(self.sampleids))) + " in your experiment.\n")
with open(self.infastq) as infile:
with open(os.path.join(self.outdir,basename+"_reformat_out"),'w') as outfile:
n=1
for line1,line2,line3,line4 in itertools.izip_longest(*[infile]*4):
if len(line1.strip())!=0:
seqid=">"+str(n)+'\n'
sequence=line2.strip()
if len(sequence)>self.minlen:
outfile.write(seqid+line2)
self.nseqspasslen+=1
n+=1
self.totalseqs+=1
self.logfile.write(" Generated length filtered file. Your raw file contains "+str(n-1) + " sequences.\n")
self.nseqsfordemultiplexingpresplit1=0
self.nseqsfordemultiplexingpresplit2=0
self.nwronglengthwindow=0
self.nseqsfordemultiplexing=0
with open(os.path.join(self.outdir,basename+"_reformat_out_1pdt"),'w') as file1:
with open(os.path.join(self.outdir,basename+"_reformat_out_2pdt"),'w') as file2:
with open(os.path.join(self.outdir,basename+"_reformat_out")) as infile:
for line1,line2 in itertools.izip_longest(*[infile]*2):
if len(line1.strip())!=0:
seqid=line1
sequence=line2.strip()
if len(sequence)<self.explen+self.taglen*2+primerlensum+self.demlen:
file1.write(seqid+line2)
self.nseqsfordemultiplexing+=1
self.nseqsfordemultiplexingpresplit1+=1
elif len(sequence)>(self.explen+self.taglen*2+primerlensum)*2 - self.demlen and len(sequence)<(self.explen+self.taglen*2+primerlensum+self.demlen)*2 :
file2.write(seqid.strip()+"p1\n"+sequence[:self.explen+self.taglen*2+primerlensum+self.demlen]+'\n')
file2.write(seqid.strip()+"p2\n"+sequence[(self.explen+self.taglen*2+primerlensum-self.demlen):]+'\n')
self.nseqsfordemultiplexing+=2
self.nseqsfordemultiplexingpresplit2+=1
else:
self.nwronglengthwindow+=1
self.notifyMessage.emit("<br>Your raw file contains "+str("{:,}".format(self.totalseqs)) + " reads.<br>You have "+str("{:,}".format(self.nseqspasslen))+" reads passing the length filter. <br> Of these, "+str("{:,}".format(self.nseqsfordemultiplexingpresplit1)) +" reads are of the correct length for containing one barcode, while " + str("{:,}".format(self.nseqsfordemultiplexingpresplit2)) +" may contain two ligated barcodes<br>Total reads of expected length ="+str("{:,}".format(self.nseqsfordemultiplexingpresplit1+self.nseqsfordemultiplexingpresplit2)) +"<br>After splitting the long products, a total of "+str("{:,}".format(self.nseqsfordemultiplexing)) +" reads are used for demultiplexing.")
self.logfile.write(str(round(time.time())) +": Split files into correct product length. There are "+str("{:,}".format(self.nseqspasslen)) + " single product sequences.\n")
self.lastbitn=self.nseqspasslen%40000
# print self.lastbitn
self.tagdict,self.muttags_fr,self.sampledict,self.typedict=crmutant_m2(self.demfile,2)
def grouper(n, iterable, fillvalue=None):
args = [iter(iterable)] * n
return izip_longest(fillvalue=fillvalue, *args)
n = 40000
self.maxid=0
with open(os.path.join(self.outdir,basename+"_reformat_out_1pdt")) as f:
for i, g in enumerate(grouper(n, f, fillvalue=''), 1):
with open(os.path.join(self.outdir,basename+"_reformat_out_1pdt_p"+str(i*n)), 'w') as fout:
fout.writelines(g)
self.maxid=basename+"_reformat_out_1pdt_p"+str(i*n)
with open(os.path.join(self.outdir,basename+"_reformat_out_2pdt")) as f:
for i, g in enumerate(grouper(n, f, fillvalue=''), 1):
with open(os.path.join(self.outdir,basename+"_reformat_out_2pdt_p"+str(i*n)), 'w') as fout:
fout.writelines(g)
self.taskFinished.emit(0)
class mergedemfiles(QtCore.QThread):
taskFinished=QtCore.pyqtSignal(int)
notifyProgress=QtCore.pyqtSignal(int)
def __init__(self,sampleids,indir,outdir,parent=None):
super(mergedemfiles, self).__init__(parent)
self.sampleids=sampleids
self.indir=indir
self.outdir=outdir
def run(self):
def mergefiles(inlist, outfilename):
o = open(outfilename, 'w')
for each in inlist:
for line in fileinput.input([each]):
o.write(line)
fileinput.close()
o.close()
c=1
for each in self.sampleids.keys():
# print each
n=0
eachlist=[]
while n<4:
dirlist=os.listdir(os.path.join(self.indir,str(n)))
if each+"_all.fa" in dirlist:
eachlist.append(os.path.join(self.indir,str(n),each+"_all.fa"))
n+=1
if len(eachlist)>0:
mergefiles(eachlist,os.path.join(self.outdir,each+"_all.fa"))
self.notifyProgress.emit(c)
c+=1
shutil.rmtree(self.indir)
self.taskFinished.emit(0)
class calculatecoverage(QtCore.QThread):
taskFinished=QtCore.pyqtSignal(int)
def __init__(self,indir,parent=None):
super(calculatecoverage, self).__init__(parent)
self.indir=indir
def run(self):
dirlist=os.listdir(self.indir)
self.dirdict={}
self.counter={}
for i,fname in enumerate(dirlist):
with open(os.path.join(self.indir,fname)) as infile:
if fname.endswith("_all.fa")==True:
self.dirdict[fname]=fname
else:
self.dirdict[fname.split(".")[0]+"_all.fa"]=fname
l=infile.readlines()
for i,j in enumerate(l):
if ">" in j:
try:
self.counter[fname.split("_all.fa")[0]]+=1
except KeyError:
self.counter[fname.split("_all.fa")[0]]=1
self.taskFinished.emit(0)
class runpaircomparisons(QtCore.QThread):
taskFinished=QtCore.pyqtSignal(list)
notifyProgress=QtCore.pyqtSignal(int)
def __init__(self,inseqdict,inseqnamedict,outdir,filelist,reffilename,parent=None):
super(runpaircomparisons, self).__init__(parent)
self.inseqdict=inseqdict
self.inseqnamedict=inseqnamedict
self.outdir=outdir
self.filelist=filelist
self.reffilename=reffilename
def run(self):
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")]
# print os.path.join(self.outdir,"identicalbarcodes_658chosen.fa")
filenamepairs=[]
self.filelist.remove(self.reffilename)
for each in self.filelist:
if each!=self.reffilename:
filenamepairs.append([self.reffilename,each])
os.mkdir(os.path.join(self.outdir,"pairwise_comparisons"))
wb=xlsxwriter.Workbook(os.path.join(self.outdir,"statistics.xlsx"))
allsheet=wb.add_worksheet("Pairwise Multisample comparison")
goodsheet=wb.add_worksheet("Correct")
errsheet=wb.add_worksheet("Erroneous")
multisamplegood,multisamplebad=0,0
multisampleincompatible={}
counterdict,sheetdict,pstatdict={},{},{}
for each in filenamepairs:
each1=each[0].split(".")[0]
each2=each[1].split(".")[0]
os.mkdir(os.path.join(self.outdir,"pairwise_comparisons",each2+"_comps"))
os.mkdir(os.path.join(self.outdir,"pairwise_comparisons",each2+"_comps","badbarcodes"))
sheetdict[each2]=wb.add_worksheet(each2[:31])
uniqlist={}
filenamedict={}
for i,each in enumerate(self.filelist):
filenamedict[each]=i
uniqlist[each.split(".")[0]]=0
counterdict[each.split(".")[0]]=[0,0,0,0,0,0,0,0]
inseqdict=self.inseqdict
inseqnamedict=self.inseqnamedict
goodbarcodefile=open(os.path.join(self.outdir,"identical_compatible_barcodes.fa"),'w')
onlyfilelist=[]
os.mkdir(os.path.join(self.outdir,"badbarcodes"))
counter=0
refcounter=0
inlistorder=[]
for k in inseqdict.keys():
subfilelist=inseqdict[k].keys()
if len(subfilelist)>1:
inlistorder=subfilelist
break
identicalcounts,compatiblecounts,incompatiblecounts=0,0,0
for k in inseqdict.keys():
identicalpairs=[]
compatiblepairs=[]
incompatiblepairs=[]
incompatiblecounter=[]
incompatiblecounter1=[]
incompatiblecounter2=[]
incompatiblecounter3=[]
incompatibleseqs=[]
subfilelist=inseqdict[k].keys()
try:
subfilelist.remove(self.reffilename)
for i,fname in enumerate(self.filelist):
if fname in subfilelist:
incompatiblecounter.append(0)
incompatiblecounter1.append(0)
incompatiblecounter2.append(0)
incompatiblecounter3.append(0)
else:
incompatiblecounter.append("NA")
incompatiblecounter1.append(0)
incompatiblecounter2.append(0)
incompatiblecounter3.append(0)
if len(subfilelist)>0:
for p,mk in enumerate(inseqdict[k].keys()):
if mk==self.reffilename:
refcounter+=1
for q,id in enumerate(subfilelist):
if id!=self.reffilename:
counterdict[id.split(".")[0]][3]+=1
counterdict[id.split(".")[0]][4]+=1
seq1=inseqdict[k][mk]
seq2=inseqdict[k][id]
if len(seq1)==len(seq2):
noambgcodealn= edlib.align(seq1, seq2, mode='NW',task='path')
ambgcodealn= edlib.align(seq1, seq2, mode='NW',task='path',additionalEqualities=ambiguity_codes)
if len(seq1)<len(seq2):
ambgcodealn= edlib.align(seq1, seq2, mode='HW',task='path',additionalEqualities=ambiguity_codes)
noambgcodealn= edlib.align(seq1, seq2, mode='HW',task='path')
if len(seq1)>len(seq2):
ambgcodealn= edlib.align(seq2, seq1, mode='HW',task='path',additionalEqualities=ambiguity_codes)
noambgcodealn= edlib.align(seq2, seq1, mode='HW',task='path')
d1 = noambgcodealn['editDistance']
d2 = ambgcodealn['editDistance']
if d2==0:
if d1>d2:
compatiblepairs.append([mk,id])
compatiblecounts+=1
each1=mk.split(".")[0]
each2=id.split(".")[0]
with open(os.path.join(self.outdir,"pairwise_comparisons",each2+"_comps","compatiblebarcodes.fa"),'a') as pcompfile:
pcompfile.write(self.inseqnamedict[k][id]+self.inseqdict[k][id]+'\n')
counterdict[each2][1]+=1
elif d1==d2:
identicalpairs.append([mk,id])
identicalcounts+=1
each1=mk.split(".")[0]
each2=id.split(".")[0]
with open(os.path.join(self.outdir,"pairwise_comparisons",each2+"_comps","goodbarcodes.fa"),'a') as pgoodfile:
pgoodfile.write(self.inseqnamedict[k][id]+self.inseqdict[k][id]+'\n')
counterdict[each2][0]+=1
else:
compseq1=seqpy.revcomp(seq1)
if len(seq1)==len(seq2):
noambgcodealn= edlib.align(compseq1, seq2, mode='NW',task='path')
ambgcodealn= edlib.align(compseq1, seq2, mode='NW',task='path',additionalEqualities=ambiguity_codes)
if len(seq1)<len(seq2):
ambgcodealn= edlib.align(compseq1, seq2, mode='HW',task='path',additionalEqualities=ambiguity_codes)
noambgcodealn= edlib.align(compseq1, seq2, mode='HW',task='path')
if len(seq1)>len(seq2):
ambgcodealn= edlib.align(seq2, compseq1, mode='HW',task='path',additionalEqualities=ambiguity_codes)
noambgcodealn= edlib.align(seq2, compseq1, mode='HW',task='path')
cd1 = noambgcodealn['editDistance']
cd2 = ambgcodealn['editDistance']
if cd2==0:
if cd1>cd2:
compatiblepairs.append([mk,id])
compatiblecounts+=1
each1=mk.split(".")[0]
each2=id.split(".")[0]
with open(os.path.join(self.outdir,"pairwise_comparisons",each2+"_comps","compatiblebarcodes.fa"),'a') as pcompfile:
pcompfile.write(self.inseqnamedict[k][id]+self.inseqdict[k][id]+'\n')
counterdict[each2][1]+=1
elif cd1==cd2:
identicalpairs.append([mk,id])
identicalcounts+=1
each1=mk.split(".")[0]
each2=id.split(".")[0]
with open(os.path.join(self.outdir,"pairwise_comparisons",each2+"_comps","goodbarcodes.fa"),'a') as pgoodfile:
pgoodfile.write(self.inseqnamedict[k][id]+self.inseqdict[k][id]+'\n')
counterdict[each2][0]+=1
else:
incompatiblepairs.append([mk,id])
incompatiblecounts+=1
if cd2>d2:
incompatibleseqs.append([seq1,seq2])
each1=mk.split(".")[0]
each2=id.split(".")[0]
# incompatiblecounter[filenamedict[mk]]+=1
incompatiblecounter[filenamedict[id]]=d2
with open(os.path.join(self.outdir,"pairwise_comparisons",each2+"_comps","badbarcodes",str(d2)+"_"+k+".fa"),'a') as incompatiblefile:
incompatiblefile.write(self.inseqnamedict[k][mk]+self.inseqdict[k][mk]+'\n'+self.inseqnamedict[k][id]+self.inseqdict[k][id]+'\n')
try:
pstatdict[each2].append([k,d2])
except KeyError:
pstatdict[each2]=[[k,d2]]
counterdict[each2][2]+=1
if d2==1:
counterdict[each2][5]+=1
elif d2==2:
counterdict[each2][6]+=1
elif d2>2:
counterdict[each2][7]+=1
else:
incompatibleseqs.append([compseq1,seq2])
incompatiblecounter[filenamedict[id]]=cd2
each1=mk.split(".")[0]
each2=id.split(".")[0]
with open(os.path.join(self.outdir,"pairwise_comparisons",each2+"_comps","badbarcodes",str(cd2)+"_"+k+".fa"),'a') as incompatiblefile:
incompatiblefile.write(self.inseqnamedict[k][mk]+self.inseqdict[k][mk]+'\n'+self.inseqnamedict[k][id]+self.inseqdict[k][id]+'\n')
try:
pstatdict[each2].append([k,cd2])
except KeyError:
pstatdict[each2]=[[k,cd2]]
counterdict[each2][2]+=1
if cd2==1:
counterdict[each2][5]+=1
elif cd2==2:
counterdict[each2][6]+=1
elif cd2>2:
counterdict[each2][7]+=1
fuseidenticalscompatible=self.fusesets(identicalpairs+compatiblepairs)
if len(incompatiblepairs)==0:
if len(fuseidenticalscompatible)>0:
goodbarcodefile.write(self.inseqnamedict[k][fuseidenticalscompatible[0][0]]+self.inseqdict[k][fuseidenticalscompatible[0][0]]+'\n')
multisamplegood+=1
else:
with open(os.path.join(self.outdir,"badbarcodes",k+".fa"),'w') as badfile:
for inlistcount,inlist in enumerate(incompatiblepairs):
badfile.write(self.inseqnamedict[k][inlist[0]]+incompatibleseqs[inlistcount][0]+'\n'+self.inseqnamedict[k][inlist[1]]+incompatibleseqs[inlistcount][1]+'\n')
multisamplebad+=1
multisampleincompatible[k]=incompatiblecounter
else:
for i,each in enumerate(subfilelist):
with open(os.path.join(self.outdir,subfilelist[i].split(".")[0]+"_onlybarcodes.fa"),'a') as uniquefile:
uniquefile.write(self.inseqnamedict[k][subfilelist[i]]+self.inseqdict[k][subfilelist[i]]+'\n')
uniqlist[subfilelist[i].split(".")[0]]+=1
counterdict[subfilelist[i].split(".")[0]][4]+=1
except ValueError:
for i,each in enumerate(subfilelist):
with open(os.path.join(self.outdir,subfilelist[i].split(".")[0]+"_onlybarcodes.fa"),'a') as uniquefile:
uniquefile.write(self.inseqnamedict[k][subfilelist[i]]+self.inseqdict[k][subfilelist[i]]+'\n')
uniqlist[subfilelist[i].split(".")[0]]+=1
counterdict[subfilelist[i].split(".")[0]][4]+=1
self.notifyProgress.emit(counter+1)
counter+=1
for each in sheetdict.keys():
sheetdict[each].write(0,0,"Overview")
sheetdict[each].write(1,0,"Number of specimens with identical barcodes")
sheetdict[each].write(1,1,counterdict[each.replace(self.reffilename.split(".")[0]+"_","")][0])
sheetdict[each].write(2,0,"Number of specimens with compatible barcodes")
sheetdict[each].write(2,1,counterdict[each.replace(self.reffilename.split(".")[0]+"_","")][1])
sheetdict[each].write(3,0,"Number of specimens with incompatible barcodes")
sheetdict[each].write(3,1,counterdict[each.replace(self.reffilename.split(".")[0]+"_","")][2])
sheetdict[each].write(5,0,"Sample")
sheetdict[each].write(5,1,"Distance")
r=6
if each in pstatdict.keys():
for row in pstatdict[each]:
# print row
sheetdict[each].write_url(r,0,os.path.join(self.outdir,"pairwise_comparisons",each,"badbarcodes",str(row[1])+"_"+row[0]+".fa"),string=row[0])
sheetdict[each].write(r,1,row[1])
r+=1
allsheet.write(0,0,"Overview")
allsheet.write(1,0,"Number of samples in the reference")
allsheet.write(1,1,refcounter)
allsheet.write(5,0,"Total Number of Barcodes in the dataset")
allsheet.write(6,0,"Number of barcodes compared to the reference")
allsheet.write(7,0,"Number of identical barcodes")
allsheet.write(8,0,"Number of compatible barcodes")
allsheet.write(9,0,"Number of incompatible barcodes")
allsheet.write(10,0,"Number of incompatible barcodes with 1 error")
allsheet.write(11,0,"Number of incompatible barcodes with 2 errors")
allsheet.write(12,0,"Number of incompatible barcodes with >2 errors")
goodsheet.write(1,0,"Total Number of Barcodes in the dataset")
goodsheet.write(2,0,"Number of barcodes compared to the reference")
goodsheet.write(3,0,"Number of identical barcodes")
goodsheet.write(4,0,"Number of compatible barcodes")
errsheet.write(1,0,"Total Number of Barcodes in the dataset")
errsheet.write(2,0,"Number of barcodes compared to the reference")
errsheet.write(3,0,"Number of incompatible barcodes")
errsheet.write(4,0,"Number of incompatible barcodes with 1 error")
errsheet.write(5,0,"Number of incompatible barcodes with 2 errors")
errsheet.write(6,0,"Number of incompatible barcodes with >2 errors")
c=1
for fname in self.filelist:
allsheet.write(4,c,fname)
each=fname.split(".")[0]
allsheet.write(5,c,counterdict[each][4])
allsheet.write(6,c,counterdict[each][3])
allsheet.write(7,c,counterdict[each][0])
allsheet.write(8,c,counterdict[each][1])
allsheet.write(9,c,counterdict[each][2])
allsheet.write(10,c,counterdict[each][5])
allsheet.write(11,c,counterdict[each][6])
allsheet.write(12,c,counterdict[each][7])
goodsheet.write(0,c,fname)
goodsheet.write(1,c,counterdict[each][4])
goodsheet.write(2,c,counterdict[each][3])
goodsheet.write(3,c,counterdict[each][0])
goodsheet.write(4,c,counterdict[each][1])
errsheet.write(0,c,fname)
errsheet.write(1,c,counterdict[each][4])
errsheet.write(2,c,counterdict[each][3])
errsheet.write(3,c,counterdict[each][2])
errsheet.write(4,c,counterdict[each][5])
errsheet.write(5,c,counterdict[each][6])
errsheet.write(6,c,counterdict[each][7])
c+=1
r=5
for row in multisampleincompatible.keys():
templist=filter(lambda a: a != "NA", multisampleincompatible[row])
totaldistance=sum(templist)
if totaldistance==0:
goodsheet.write(r,0,row)
c=1
for v in multisampleincompatible[row]:
goodsheet.write(r,c,v)
c+=1
r+=1
r=7
for row in multisampleincompatible.keys():
templist=filter(lambda a: a != "NA", multisampleincompatible[row])
totaldistance=sum(templist)
if totaldistance!=0:
errsheet.write_url(r,0,os.path.join(self.outdir,"badbarcodes",row+'.fa'),string=row)
c=1
for v in multisampleincompatible[row]:
errsheet.write(r,c,v)
c+=1
r+=1
wb.close()
self.taskFinished.emit([refcounter,counterdict])
def fusesets(self,inlist):
flag=0
while flag==0:
new=[]
flag=1
while inlist:
cur,comp=inlist[0],inlist[1:]
inlist=[]
for q in comp:
if len(list(set(cur)&set(q)))>0:
flag=0
cur=tuple(set(cur)|set(q))
else:
inlist.append(q)
new.append(cur)
inlist=new
return new
class runtwocomparisons(QtCore.QThread):
taskFinished=QtCore.pyqtSignal(list)
notifyProgress=QtCore.pyqtSignal(int)
def __init__(self,inseqdict,inseqnamedict,outdir,parent=None):
super(runtwocomparisons, self).__init__(parent)
self.inseqdict=inseqdict
self.inseqnamedict=inseqnamedict
self.outdir=outdir
def run(self):
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")]
print os.path.join(self.outdir,"identicalbarcodes_658chosen.fa")
inseqdict=self.inseqdict
inseqnamedict=self.inseqnamedict
goodbarcodefile=open(os.path.join(self.outdir,"identicalbarcodes_658chosen.fa"),'w')
compatiblebarcodefile=open(os.path.join(self.outdir,"compatiblebarcodes_658chosen_or_lowern.fa"),'w')
statsfile=open(os.path.join(self.outdir,"statsfile.csv"),'w')
onlyfilelist=[]
os.mkdir(os.path.join(self.outdir,"badbarcodes"))
counter=0
inlistorder=[]
for k in inseqdict.keys():
subfilelist=inseqdict[k].keys()
if len(subfilelist)>1:
inlistorder=subfilelist
break
uniqlist={}
statslines=''
identicalcounts,compatiblecounts,incompatiblecounts=0,0,0
for k in inseqdict.keys():
identicalpairs=[]
compatiblepairs=[]
incompatiblepairs=[]
incompatiblealns=[]
incompatibleseqs=[]
incompatibledists=[]
subfilelist=inseqdict[k].keys()
if len(subfilelist)>1:
for p,mk in enumerate(inseqdict[k].keys()):
if p!=len(subfilelist)-1:
for q,id in enumerate(subfilelist[p+1:]):
seq1=inseqdict[k][mk]
seq2=inseqdict[k][id]
if len(seq1)==len(seq2):
noambgcodealn= edlib.align(seq1, seq2, mode='NW',task='path')
ambgcodealn= edlib.align(seq1, seq2, mode='NW',task='path',additionalEqualities=ambiguity_codes)
# nice = edlib.getNiceAlignment(ambgcodealn, seq1, seq2)
if len(seq1)<len(seq2):
ambgcodealn= edlib.align(seq1, seq2, mode='HW',task='path',additionalEqualities=ambiguity_codes)
noambgcodealn= edlib.align(seq1, seq2, mode='HW',task='path')
if len(seq1)>len(seq2):
ambgcodealn= edlib.align(seq2, seq1, mode='HW',task='path',additionalEqualities=ambiguity_codes)
noambgcodealn= edlib.align(seq2, seq1, mode='HW',task='path')
d1 = noambgcodealn['editDistance']
d2 = ambgcodealn['editDistance']
if d2==0:
if d1>d2:
compatiblepairs.append([mk,id])
compatiblecounts+=1
compatiblebarcodefile.write(self.inseqnamedict[k][mk]+self.inseqdict[k][mk]+'\n')
elif d1==d2:
identicalpairs.append([mk,id])
identicalcounts+=1
goodbarcodefile.write(self.inseqnamedict[k][mk]+self.inseqdict[k][mk]+'\n')
else:
compseq1=seqpy.revcomp(seq1)
if len(seq1)==len(seq2):
noambgcodealn= edlib.align(compseq1, seq2, mode='NW',task='path')
ambgcodealn= edlib.align(compseq1, seq2, mode='NW',task='path',additionalEqualities=ambiguity_codes)
if len(seq1)<len(seq2):
ambgcodealn= edlib.align(compseq1, seq2, mode='HW',task='path',additionalEqualities=ambiguity_codes)
noambgcodealn= edlib.align(compseq1, seq2, mode='HW',task='path')
if len(seq1)>len(seq2):
ambgcodealn= edlib.align(seq2, compseq1, mode='HW',task='path',additionalEqualities=ambiguity_codes)
noambgcodealn= edlib.align(seq2, compseq1, mode='HW',task='path')
cd1 = noambgcodealn['editDistance']
cd2 = ambgcodealn['editDistance']
if cd2==0:
if cd1>cd2:
compatiblepairs.append([mk,id])
compatiblecounts+=1
compatiblebarcodefile.write(self.inseqnamedict[k][mk]+self.inseqdict[k][mk]+'\n')
elif cd1==cd2:
identicalpairs.append([mk,id])
identicalcounts+=1
goodbarcodefile.write(self.inseqnamedict[k][mk]+self.inseqdict[k][mk]+'\n')
else:
incompatiblepairs.append([mk,id])
incompatiblecounts+=1
if cd2>d2:
string=k+','+str(d2)+'\n'
statslines+=string
# incompatibleseqs.append([seq1,seq2])
# incompatibledists.append(str(d2))
with open(os.path.join(self.outdir,"badbarcodes",str(d2)+"_"+k+".fa"),'w') as badfile:
badfile.write(self.inseqnamedict[k][mk]+seq1+'\n'+self.inseqnamedict[k][id]+seq2+'\n')
else:
string=k+','+str(cd2)+'\n'
statslines+=string
# incompatibleseqs.append([compseq1,seq2])
# incompatibledists.append(str(cd2))
with open(os.path.join(self.outdir,"badbarcodes",str(cd2)+"_"+k+".fa"),'w') as badfile:
badfile.write(self.inseqnamedict[k][mk]+compseq1+'\n'+self.inseqnamedict[k][id]+seq2+'\n')
# if len(incompatiblepairs)==1:
# with open(os.path.join(self.outdir,"badbarcodes",incompatibledists[0]+"_"+k+".fa"),'w') as badfile:
# badfile.write(self.inseqnamedict[k][incompatibleseqs[0][0]]+incompatibleseqs[0][0]+'\n'+self.inseqnamedict[k][incompatibleseqs[0][1]]+incompatibleseqs[0][1]+'\n')
else:
with open(os.path.join(self.outdir,subfilelist[0].split(".")[0]+"_onlybarcodes.fa"),'a') as uniquefile:
uniquefile.write(self.inseqnamedict[k][subfilelist[0]]+self.inseqdict[k][subfilelist[0]]+'\n')
try:
uniqlist[subfilelist[0].split(".")[0]]+=1
except KeyError:
uniqlist[subfilelist[0].split(".")[0]]=1
self.notifyProgress.emit(counter+1)
counter+=1
statsfile.write("Overview\nNumber of specimens with identical barcodes,"+str(identicalcounts)+"\n")
statsfile.write("Number of specimens with compatible barcodes,"+str(compatiblecounts)+"\n")
statsfile.write("Number of specimens with incompatible barcodes,"+str(incompatiblecounts)+"\n")
strdictlens=""
for each in uniqlist.keys():
strdictlens+="Number of barcodes in "+ each+" only,"+str(uniqlist[each])+"\n"
statsfile.write("\n\nOverview of incompatible barcodes\nSampleID,Distance\n")
statsfile.write(statslines)
self.taskFinished.emit([identicalcounts,compatiblecounts,incompatiblecounts,uniqlist])
class runmulticomparisons(QtCore.QThread):
taskFinished=QtCore.pyqtSignal(list)
notifyProgress=QtCore.pyqtSignal(int)
def __init__(self,inseqdict,inseqnamedict,outdir,filelist,parent=None):
super(runmulticomparisons, self).__init__(parent)
self.inseqdict=inseqdict
self.inseqnamedict=inseqnamedict
self.outdir=outdir
self.filelist=filelist
def run(self):
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")]
# print os.path.join(self.outdir,"identicalbarcodes_658chosen.fa")
filenamepairs=list(itertools.combinations(self.filelist, 2))
# print filenamepairs
os.mkdir(os.path.join(self.outdir,"pairwise_comparisons"))
wb=xlsxwriter.Workbook(os.path.join(self.outdir,"statistics.xlsx"))
allsheet=wb.add_worksheet("Multisample comparison")
multisamplegood,multisamplebad=0,0
multisampleincompatible={}
counterdict,sheetdict,pstatdict={},{},{}
for each in filenamepairs:
each1=each[0].split(".")[0]
each2=each[1].split(".")[0]
os.mkdir(os.path.join(self.outdir,"pairwise_comparisons",each1+"_"+each2+"_comps"))
os.mkdir(os.path.join(self.outdir,"pairwise_comparisons",each1+"_"+each2+"_comps","badbarcodes"))
counterdict[each1+"_"+each2]=[0,0,0,0,0,0,0,0]
sheetdict[each1+"_"+each2]=wb.add_worksheet(each1[:15]+"_"+each2[:15])
uniqlist={}
filenamedict={}
for i,each in enumerate(self.filelist):
filenamedict[each]=i
uniqlist[each.split(".")[0]]=0
inseqdict=self.inseqdict
inseqnamedict=self.inseqnamedict
goodbarcodefile=open(os.path.join(self.outdir,"identical_compatible_barcodes.fa"),'w')
onlyfilelist=[]
os.mkdir(os.path.join(self.outdir,"badbarcodes"))
counter=0
inlistorder=[]
for k in inseqdict.keys():
subfilelist=inseqdict[k].keys()
if len(subfilelist)>1:
inlistorder=subfilelist
break
identicalcounts,compatiblecounts,incompatiblecounts=0,0,0
for k in inseqdict.keys():
combodone=[]
identicalpairs=[]
compatiblepairs=[]
incompatiblepairs=[]
incompatiblecounter=[]
incompatiblecounter1=[]
incompatiblecounter2=[]
incompatiblecounter3=[]
incompatibleseqs=[]
subfilelist=inseqdict[k].keys()
try:
for i,fname in enumerate(self.filelist):
if fname in subfilelist:
incompatiblecounter.append(0)
incompatiblecounter1.append(0)
incompatiblecounter2.append(0)
incompatiblecounter3.append(0)
else:
incompatiblecounter.append("NA")
incompatiblecounter1.append(0)
incompatiblecounter2.append(0)
incompatiblecounter3.append(0)
if len(subfilelist)>0:
for p,mk in enumerate(inseqdict[k].keys()):
subfilelist.remove(mk)
#refcounter+=1
for q,id in enumerate(subfilelist):
if mk!=id:
if id.split(".")[0]+"_"+mk.split(".")[0] in counterdict.keys():
comboname=id.split(".")[0]+"_"+mk.split(".")[0]
elif mk.split(".")[0]+"_"+id.split(".")[0] in counterdict.keys():
comboname=mk.split(".")[0]+"_"+id.split(".")[0]
counterdict[comboname][3]+=1
counterdict[comboname][4]+=1
seq1=inseqdict[k][mk]
seq2=inseqdict[k][id]
if len(seq1)==len(seq2):
noambgcodealn= edlib.align(seq1, seq2, mode='NW',task='path')
ambgcodealn= edlib.align(seq1, seq2, mode='NW',task='path',additionalEqualities=ambiguity_codes)
if len(seq1)<len(seq2):
ambgcodealn= edlib.align(seq1, seq2, mode='HW',task='path',additionalEqualities=ambiguity_codes)
noambgcodealn= edlib.align(seq1, seq2, mode='HW',task='path')
if len(seq1)>len(seq2):
ambgcodealn= edlib.align(seq2, seq1, mode='HW',task='path',additionalEqualities=ambiguity_codes)
noambgcodealn= edlib.align(seq2, seq1, mode='HW',task='path')
d1 = noambgcodealn['editDistance']
d2 = ambgcodealn['editDistance']
if d2==0:
if d1>d2:
compatiblepairs.append([mk,id])
compatiblecounts+=1
each1=mk.split(".")[0]
each2=id.split(".")[0]
with open(os.path.join(self.outdir,"pairwise_comparisons",comboname+"_comps","compatiblebarcodes.fa"),'a') as pcompfile:
pcompfile.write(self.inseqnamedict[k][id]+self.inseqdict[k][id]+'\n')
counterdict[comboname][1]+=1
elif d1==d2:
identicalpairs.append([mk,id])
identicalcounts+=1
each1=mk.split(".")[0]
each2=id.split(".")[0]
with open(os.path.join(self.outdir,"pairwise_comparisons",comboname+"_comps","goodbarcodes.fa"),'a') as pgoodfile:
pgoodfile.write(self.inseqnamedict[k][id]+self.inseqdict[k][id]+'\n')
counterdict[comboname][0]+=1
else:
compseq1=seqpy.revcomp(seq1)
if len(seq1)==len(seq2):
noambgcodealn= edlib.align(compseq1, seq2, mode='NW',task='path')
ambgcodealn= edlib.align(compseq1, seq2, mode='NW',task='path',additionalEqualities=ambiguity_codes)
if len(seq1)<len(seq2):
ambgcodealn= edlib.align(compseq1, seq2, mode='HW',task='path',additionalEqualities=ambiguity_codes)
noambgcodealn= edlib.align(compseq1, seq2, mode='HW',task='path')
if len(seq1)>len(seq2):
ambgcodealn= edlib.align(seq2, compseq1, mode='HW',task='path',additionalEqualities=ambiguity_codes)
noambgcodealn= edlib.align(seq2, compseq1, mode='HW',task='path')
cd1 = noambgcodealn['editDistance']
cd2 = ambgcodealn['editDistance']
if cd2==0:
if cd1>cd2:
compatiblepairs.append([mk,id])
compatiblecounts+=1
each1=mk.split(".")[0]
each2=id.split(".")[0]
with open(os.path.join(self.outdir,"pairwise_comparisons",comboname+"_comps","compatiblebarcodes.fa"),'a') as pcompfile:
pcompfile.write(self.inseqnamedict[k][id]+self.inseqdict[k][id]+'\n')
counterdict[comboname][1]+=1
elif cd1==cd2:
identicalpairs.append([mk,id])
identicalcounts+=1
each1=mk.split(".")[0]
each2=id.split(".")[0]
with open(os.path.join(self.outdir,"pairwise_comparisons",comboname+"_comps","goodbarcodes.fa"),'a') as pgoodfile:
pgoodfile.write(self.inseqnamedict[k][id]+self.inseqdict[k][id]+'\n')
counterdict[comboname][0]+=1
else:
incompatiblepairs.append([mk,id])
incompatiblecounts+=1
if cd2>d2:
incompatibleseqs.append([seq1,seq2])
each1=mk.split(".")[0]
each2=id.split(".")[0]
incompatiblecounter[filenamedict[mk]]+=1
incompatiblecounter[filenamedict[id]]+=1
with open(os.path.join(self.outdir,"pairwise_comparisons",comboname+"_comps","badbarcodes",str(d2)+"_"+k+".fa"),'a') as incompatiblefile:
incompatiblefile.write(self.inseqnamedict[k][mk]+self.inseqdict[k][mk]+'\n'+self.inseqnamedict[k][id]+self.inseqdict[k][id]+'\n')
try:
pstatdict[comboname].append([k,d2])
except KeyError:
pstatdict[comboname]=[[k,d2]]
counterdict[comboname][2]+=1
if d2==1:
counterdict[comboname][5]+=1
elif d2==2:
counterdict[comboname][6]+=1
elif d2>2:
counterdict[comboname][7]+=1
else:
incompatibleseqs.append([compseq1,seq2])
incompatiblecounter[filenamedict[mk]]+=1
incompatiblecounter[filenamedict[id]]+=1
each1=mk.split(".")[0]
each2=id.split(".")[0]
with open(os.path.join(self.outdir,"pairwise_comparisons",comboname+"_comps","badbarcodes",str(cd2)+"_"+k+".fa"),'a') as incompatiblefile:
incompatiblefile.write(self.inseqnamedict[k][mk]+self.inseqdict[k][mk]+'\n'+self.inseqnamedict[k][id]+self.inseqdict[k][id]+'\n')
try:
pstatdict[comboname].append([k,cd2])
except KeyError:
pstatdict[comboname]=[[k,cd2]]
counterdict[comboname][2]+=1
if cd2==1:
counterdict[comboname][5]+=1
elif cd2==2:
counterdict[comboname][6]+=1
elif cd2>2:
counterdict[comboname][7]+=1
fuseidenticalscompatible=self.fusesets(identicalpairs+compatiblepairs)
if len(incompatiblepairs)==0:
if len(fuseidenticalscompatible)>0:
goodbarcodefile.write(self.inseqnamedict[k][fuseidenticalscompatible[0][0]]+self.inseqdict[k][fuseidenticalscompatible[0][0]]+'\n')
multisamplegood+=1
else:
with open(os.path.join(self.outdir,"badbarcodes",k+".fa"),'w') as badfile:
for inlistcount,inlist in enumerate(incompatiblepairs):
badfile.write(self.inseqnamedict[k][inlist[0]]+incompatibleseqs[inlistcount][0]+'\n'+self.inseqnamedict[k][inlist[1]]+incompatibleseqs[inlistcount][1]+'\n')
multisamplebad+=1
multisampleincompatible[k]=incompatiblecounter
else:
for i,each in enumerate(subfilelist):
with open(os.path.join(self.outdir,subfilelist[i].split(".")[0]+"_onlybarcodes.fa"),'a') as uniquefile:
uniquefile.write(self.inseqnamedict[k][subfilelist[i]]+self.inseqdict[k][subfilelist[i]]+'\n')
uniqlist[subfilelist[i].split(".")[0]]+=1
# counterdict[subfilelist[i].split(".")[0]][4]+=1
except ValueError:
for i,each in enumerate(subfilelist):
with open(os.path.join(self.outdir,subfilelist[i].split(".")[0]+"_onlybarcodes.fa"),'a') as uniquefile:
uniquefile.write(self.inseqnamedict[k][subfilelist[i]]+self.inseqdict[k][subfilelist[i]]+'\n')
uniqlist[subfilelist[i].split(".")[0]]+=1
# counterdict[subfilelist[i].split(".")[0]][4]+=1
self.notifyProgress.emit(counter+1)
counter+=1
for each in sheetdict.keys():
sheetdict[each].write(0,0,"Overview")
sheetdict[each].write(1,0,"Number of specimens with identical barcodes")
sheetdict[each].write(1,1,counterdict[each][0])
sheetdict[each].write(2,0,"Number of specimens with compatible barcodes")
sheetdict[each].write(2,1,counterdict[each][1])
sheetdict[each].write(3,0,"Number of specimens with incompatible barcodes")
sheetdict[each].write(3,1,counterdict[each][2])
sheetdict[each].write(5,0,"Sample")
sheetdict[each].write(5,1,"Distance")
r=6
for row in pstatdict[each]:
sheetdict[each].write(r,0,row[0])
sheetdict[each].write(r,1,row[1])
r+=1
allsheet.write(0,0,"Overview")
allsheet.write(1,0,"Number of samples with completely compatible/identical barcodes across all sets")
allsheet.write(1,1,multisamplegood)
allsheet.write(2,0,"Number of samples with incompatible barcodes in at least one set")
allsheet.write(2,1,multisamplebad)
c=1
for fname in counterdict:
allsheet.write(4,c,fname)
each=fname.split(".")[0]
allsheet.write(5,c,counterdict[each][4])
allsheet.write(6,c,counterdict[each][3])
allsheet.write(7,c,counterdict[each][0])
allsheet.write(8,c,counterdict[each][1])
allsheet.write(9,c,counterdict[each][2])
allsheet.write(10,c,counterdict[each][5])
allsheet.write(11,c,counterdict[each][6])
allsheet.write(12,c,counterdict[each][7])
c+=1
r=5
for row in multisampleincompatible.keys():
allsheet.write(r,0,row)
c=1
for v in multisampleincompatible[row]:
allsheet.write(r,c,v)
c+=1
r+=1
wb.close()
self.taskFinished.emit([multisamplegood,multisamplebad,uniqlist])
def fusesets(self,inlist):
flag=0
while flag==0:
new=[]
flag=1
while inlist:
cur,comp=inlist[0],inlist[1:]
inlist=[]
for q in comp:
if len(list(set(cur)&set(q)))>0:
flag=0
cur=tuple(set(cur)|set(q))
else:
inlist.append(q)
new.append(cur)
inlist=new
return new
class copyfiles(QtCore.QThread):
taskFinished=QtCore.pyqtSignal(int)
def __init__(self,indir,outdir,inlist,indir2,dirdict,inputmode,parent=None):
super(copyfiles, self).__init__(parent)
self.indir=indir
self.outdir=outdir
self.inlists=inlist
self.dirdict=dirdict
self.indir2=indir2
self.inputmode=inputmode
def run(self):