-
Notifications
You must be signed in to change notification settings - Fork 0
/
eukfindertest.py
2084 lines (1815 loc) · 76.1 KB
/
eukfindertest.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
import os
import re
import sys
import ete3
import glob
import time
import shutil
import platform
import numpy as np
import pandas as pd
from subprocess import PIPE, run
from joblib import Parallel, delayed
# ls -lthr /home/dsalas/Shared/Eukfinder
# -rwxrwxrwx 1 dsalas roger 76K Feb 14 2021 eukfinder_Euk-Unk_v1.2.3.py
'''
[diff_v1.2.1_v1.2.3.txt]
14a15,22
> ' ' '
> 919,920c928,929
> < 'acc2tax_nucl_all.txt', 'gi_taxid_nucl.dmp',
> < 'gi_taxid_prot.dmp']
> ---
> > 'acc2tax_nucl_all.txt']#, 'gi_taxid_nucl.dmp',
> > #'gi_taxid_prot.dmp']
> ' ' '
799,800c807
< ('Misc', label, pref, Misc, reads),
< ('Euk', label, pref, Euk, reads)]
---
> ('Misc', label, pref, Misc, reads)]
920,921c927,928
< 'acc2tax_nucl_all.txt']#, 'gi_taxid_nucl.dmp',
< #'gi_taxid_prot.dmp']
---
> 'acc2tax_nucl_all.txt']#, 'gi_taxid_nucl.dmp',
> #'gi_taxid_prot.dmp']
1533c1540
< cen = glob.glob('%s*' % user_args['cdb'])
---
> cen = glob.glob('%s*.cf' % user_args['cdb'])
'''
# --- preparation ---
def trimming(bn, reads1, reads2, adapath, wsize, qscore, headcrop,
mlenght, threads, leading_trim, trail_trim):
r1_out = '%sR1PT.fq %sR1unPT.fq ' % (bn, bn)
r2_out = '%sR2PT.fq %sR2unPT.fq ' % (bn, bn)
cmd = 'trimmomatic PE -threads %s -trimlog %s.trim.log ' % (threads, bn)
cmd += '%s %s %s %s ILLUMINACLIP:%s:2:30:10 HEADCROP:%s LEADING:%s ' % (
reads1, reads2, r1_out, r2_out, adapath, headcrop, leading_trim)
cmd += 'TRAILING:%s SLIDINGWINDOW:%s:%s MINLEN:%s' % (trail_trim,
wsize, qscore,
mlenght)
ms = 'trimmomatic cmd_line:\n%s\n' % cmd
print(ms, sep=' ', end='\n', file=sys.stdout, flush=False)
_ = run(cmd, stdout=PIPE, stderr=PIPE, shell=True)
lst = r1_out.split() + r2_out.split()
catfile = '%s.catunPT.fq' % bn
os.system('cat %s %s > %s' % (lst[1], lst[-1], catfile))
R1 = os.path.abspath(lst[0])
R2 = os.path.abspath(lst[2])
cat = os.path.abspath(catfile)
return R1, R2, cat
def bowtie2build(hostg):
bn = os.path.split(hostg)[-1]
bn = re.split(r'.fasta$|.fa$|.fas$', bn, flags=re.IGNORECASE)[0]
cmd = 'bowtie2-build -f %s %s' % (hostg, bn)
ms = 'bowtie2 build cmd_line:\n%s' % cmd
print(ms, sep=' ', end='\n', file=sys.stdout, flush=False)
_ = run(cmd, stdout=PIPE, stderr=PIPE, shell=True)
if len(glob.glob('*bt2')) != 0:
return bn
else:
ms = 'bowtie indexes could not be built.\n'
ms += 'Exiting program\n'
print(ms, sep=' ', end='\n', file=sys.stdout, flush=False)
def bowtie2(bn, threads, r1, r2, catr1r2, hindex, typ):
if typ == 'fastq-host':
cmd = 'bowtie2 --local --phred33 -q --threads %s -x %s' % (threads,
hindex)
cmd += ' -1 %s -2 %s -U %s -S %s.sam ' % (r1, r2, catr1r2, bn)
cmd += '--un-conc %s_p.fastq --un %s_un.fastq --no-unal' % (bn, bn)
ms = 'bowtie2 fastq-host cmd_line:\n%s' % cmd
print(ms, sep=' ', end='\n', file=sys.stdout, flush=False)
bt2faR1 = os.path.abspath('%s_p.1.fastq' % bn)
bt2faR2 = os.path.abspath('%s_p.2.fastq' % bn)
bt2faun = os.path.abspath('%s_un.fastq' % bn)
return bt2faR1, bt2faR2, bt2faun, cmd
elif typ == 'fastq':
cmd = 'bowtie2 --local --phred33 -q --threads %s -x %s' % (threads,
hindex)
cmd += ' -1 %s -2 %s -U %s -S %s.sam ' % (r1, r2, catr1r2, bn)
cmd += '--al-conc %s_bowtie2.fastq ' % bn
cmd += '--al %s_bowtie2.un.fastq --no-unal' % bn
ms = 'bowtie2 fastq cmd_line:\n%s' % cmd
print(ms, sep=' ', end='\n', file=sys.stdout, flush=False)
bt2fqR1 = os.path.abspath('%s_bowtie2.1.fastq' % bn)
bt2fqR2 = os.path.abspath('%s_bowtie2.2.fastq' % bn)
bt2fqun = os.path.abspath('%s_bowtie2.un.fastq' % bn)
return bt2fqR1, bt2fqR2, bt2fqun, cmd
else:
cmd = 'bowtie2 --local --threads %s -x %s ' % (threads, hindex)
cmd += '-U %s -S %s.sam --al %s_bowtie2.fasta' % (catr1r2, bn, bn)
cmd += '--no-unal'
ms = 'bowtie2 fasta cmd_line:\n%s' % cmd
print(ms, sep=' ', end='\n', file=sys.stdout, flush=False)
bt2fa = os.path.abspath('%s_bowtie2.fasta' % bn)
return bt2fa, None, None, cmd
def centrifuge(bn, bn_tuple, threads, mhlen, dbpath, k, pair=True, fastq=True):
if fastq:
gline = 'centrifuge -q --phred33 --threads %s -k %s ' % (threads, k)
gline += '--min-hitlen %s -x %s ' % (mhlen, dbpath)
else:
gline = 'centrifuge -f --threads %s -k %s ' % (threads, k)
gline += '--min-hitlen %s -x %s ' % (mhlen, dbpath)
if pair:
bn_r1, bn_r2 = bn_tuple
report = os.path.join(os.getcwd(), '%s_centrifuge_P' % bn)
gline += '-1 %s -2 %s -S %s ' % (bn_r1, bn_r2, report)
gline += '--report-file %s.tsv' % report
ms = 'centrifuge pair cmd_line:\n%s' % gline
print(ms, sep=' ', end='\n', file=sys.stdout, flush=False)
return gline, report
else:
bn_r1r2 = bn_tuple
report = os.path.join(os.getcwd(),'%s_centrifuge_UP' % bn)
gline += '-U %s -S %s --report-file %s.tsv ' % (bn_r1r2,
report, report)
ms = 'centrifuge unpair cmd_line:\n%s' % gline
print(ms, sep=' ', end='\n', file=sys.stdout, flush=False)
return gline, report
def cats(b_outname):
os.chdir('..')
cwd = os.getcwd()
# up_dir = cwd.split('/Temp')[0]
outr1 = os.path.join(cwd, '%s.EUnkR1.fq' % b_outname)
outr2 = os.path.join(cwd, '%s.EUnkR2.fq' % b_outname)
outr1r2 = os.path.join(cwd, '%s.EUnk.fq' % b_outname)
return outr1, outr2, outr1r2
# --- classification ---
def reading_reports(infile):
'''
:param infile:
:return:
'''
ms = 'Processing %s ...' % infile
print(ms, sep=' ', end='\n', file=sys.stdout, flush=False)
if infile is not None:
sorting_list = ['score']
chunksize = 1000 * 10
# header must be guessed to avoid iteration issues
infox = pd.read_csv(infile, sep='\t',
chunksize=chunksize, dtype=object)
table = Parallel(n_jobs=-2)(delayed(minimal)
((chunk, sorting_list, 'report', 'None',
'None',
False)) for chunk in infox)
table = pd.concat(table).sort_values(sorting_list,
ascending=[False])
table = table.groupby('readID', as_index=False).first()
table = table.loc[:, ['readID', 'seqID', 'taxID']]
ms = 'Report has been read'
print(ms, sep=' ', end='\n', file=sys.stdout, flush=False)
return table
else:
m = 'report file has not been declared '
m += 'or the declared file is not in the directory. The file or '
m += 'a symbolic link must exist in the working directory.'
print(m, sep=' ', end='\n', file=sys.stdout, flush=False)
return pd.DataFrame()
def minimal(tupla):
'''
:param tupla:
:return:
'''
# presort... groupby will retain the relative position
chunk, sorting_list, typ, pid, cov, lr = tupla
if not lr:
cov = 0
if typ == 'plast':
nchunk = chunk.copy(deep=True)
small = nchunk.qlen < nchunk.slen # query length smaller than
# subject
nchunk.loc[small, 'sguess_cov'] = nchunk.qcov
large = nchunk.qlen >= nchunk.slen # query larger than subject
nchunk.loc[large, 'sguess_cov'] = nchunk.scov
# select entries with identities and coverages that meet
# pre-established criteria
expr = (nchunk['pidentity'] >= pid) & (nchunk['sguess_cov'] >= cov)
newchunk = nchunk.loc[expr].copy(deep=True)
asc = [True, False, False]
cols = ['query ID', 'subject ID', 'e-value',
'aln_len', 'pidentity', 'sguess_cov']
group = 'query ID'
else:
group = 'readID'
asc = False
cols = ['readID', 'seqID', 'taxID', 'score']
newchunk = chunk.copy(deep=True)
if not newchunk.empty:
dfout = newchunk.sort_values(sorting_list, ascending=asc)
# do groupby and take the top directly
dataframes = dfout.groupby(group, as_index=False, sort=False
).first()
dataframes = dataframes.reindex(columns=cols)
return dataframes
else:
ms = 'Chunk does not fullfill identity and coverage criteria. '
ms += 'This produced an empty read chunk'
print(ms, sep=' ', end='\n', flush=False)
print('empty chunk is :\n', newchunk)
return newchunk
def parseplastoutput(single_plout, ident, cov, lr):
'''
:param single_plout:
:return:
'''
colnames = ['query ID', 'subject ID', 'pidentity', 'aln_length',
'nb.misses', 'nb.gaps', 'qbegin', 'qend', 'sbegin',
'send', 'e-value', 'bit score', 'unknown', 'qlen',
'qframe', 'qtranslated', 'qcov', 'qnb.gaps', 'slen',
'sframe', 'stranslated', 'scov', 'snb.gaps', 'sguess_cov']
sorting_list = ['e-value', 'pidentity', 'sguess_cov']
types = {entry: ('float64' if entry not in ['query ID', 'subject ID']
else 'str') for entry in colnames}
# reading plast outputs by chunks using parallel parsing
chunksize = 1000 * 10
df = pd.read_csv(single_plout, sep='\t', header=None,
names=colnames, chunksize=chunksize, dtype=types)
plouts = Parallel(n_jobs=-2)(delayed(minimal)
((chunk, sorting_list, 'plast', ident,
cov, lr)) for chunk in df)
# re-sorting as some queries may appear in different chunks
plouts = pd.concat(plouts).sort_values(
sorting_list, ascending=[True, False, False])
# final best single plout
plouts = plouts.groupby('query ID', as_index=False).first()
#
temp = plouts.loc[:, ['subject ID']]
# acc2tax = acc2tax['subject ID'].str.
# split('|', 4, expand=True).loc[:, 3]
temp = temp.loc[:, 'subject ID'].tolist()
# database MUST be in ncbi format. an exception should be created here
# to capture a different ending('|')
acc2tax = [(entry, entry.rstrip('|').split('|')[-1].split('.')[0])
if '|' in entry else (entry, entry.split()[0].split(
'.')[0]) for entry in temp]
# creating a dataframe with only accessions
acc2tax = pd.DataFrame(acc2tax,
columns=['subject ID', 'Accession'])
#
acc2tax = acc2tax.groupby('Accession', as_index=False).first()
# renaming column to match that of the main dataframe and acc2tax
plouts = plouts.rename(columns={'query ID': 'readID'})
# merge main plout output with only the accession numbers
plouts = plouts.merge(acc2tax, on='subject ID',
how='outer')
# return a dataframe with all columns plus an accession id
return plouts
def cmd(CPUs, chunk, pDBpath, evalue, long=False):
'''
:param CPUs:
:param chunk:
:param pDBpath:
:param evalid:
:return:
'''
# evalue = float(evalid.split(':')[0])
line = 'plast -e %s -max-hit-per-query 1 -outfmt 2 '
line += '-a %s -p plastn -i %s -d %s -o %s.plout '
line += '-force-query-order 1000 '
if long:
line += '-F F\n'
line %= (evalue, CPUs, chunk, pDBpath, chunk)
else:
line += '\n'
line %= (evalue, CPUs, chunk, pDBpath, chunk)
ms = 'plast cmd line:\n%s ' % line
print(ms, sep=' ', end='\n', file=sys.stdout, flush=False)
return line
def my_run(cmdline):
'''
:param cmdline:
:return:
'''
run(cmdline, stderr=PIPE,
stdout=PIPE, shell=True, bufsize=1,
close_fds=True, universal_newlines=True)
def plastsearches(CPUs, pDBpath, evalue, pattern):
'''
:param CPUs:
:param pDBpath:
:param evalue:
:param pattern:
:return:
'''
abs_pattern = os.path.join(os.getcwd(), pattern)
queries = glob.glob(abs_pattern)
# queries = glob.glob(pattern): i added 2 lines above instead of this one
label = pattern[0].upper()
if queries:
ms = 'plast search in progress ...'
print(ms, sep=' ', end='\n', file=sys.stdout, flush=False)
pSubprocesses = [cmd(CPUs, chunk, pDBpath, evalue) for
chunk in queries]
_ = Parallel(n_jobs=-2)(delayed(my_run)(cmd_line)
for cmd_line in pSubprocesses)
time.sleep(5)
outpattern = pattern + '.plout'
res = glob.glob(outpattern)
res = [(e, label) for e in res]
return res
def parsingplastsearches(list_of_results, pid, cov, lr):
'''
:param list_of_results:
:return:
'''
time.sleep(5)
label = list_of_results[0][1]
ms = 'parsing plast outputs for %s ....' % label
print(ms, sep=' ', end='\n', file=sys.stdout, flush=False)
allplast_outs = []
pouts = [parseplastoutput(out[0], pid, cov, lr) for out in
list_of_results if os.stat(out[0]).st_size != 0]
if pouts:
plast_outputs = pd.concat(pouts)
allplast_outs.append((label, plast_outputs))
else:
allplast_outs.append((label, pd.DataFrame()))
return allplast_outs
def matchmaker(ncbi, regex, readid, taxid):
'''
:param ncbi:
:param regex:
:param readid:
:param taxid:
:return:
'''
lineage = ncbi.get_lineage(taxid)
Se_lineage = pd.Series(ncbi.get_taxid_translator
(lineage), name=taxid)
nl = Se_lineage.iloc[1]
match = regex.search(nl)
exc = ['archaea', 'bacteria', 'eukaryota']
if match:
if not match.group().lower() in exc:
match_word = 'Vir'
else:
match_word = match.group()
return readid, match_word
else:
return readid, np.NaN
def binningbytaxonomy(report_df):
'''
slice reports by taxonomic domain
'''
ncbi = ete3.NCBITaxa()
regex = re.compile(r'^\bBacteria\b$|^\bArchaea\b$|'
r'^\bEukaryota\b$|vir',
flags=re.IGNORECASE)
maintaxidlist = []
for entry in report_df.itertuples():
index, readid, seqid, taxid = entry
taxid = str(taxid)
if taxid != '0':
try:
m = matchmaker(ncbi, regex, readid, taxid)
if type(m) is tuple:
maintaxidlist.append(m)
except:
pass
return maintaxidlist
def taxpickup(binned_lists, main_df):
'''
:param binned_lists:
:param main_df:
:return:
'''
maintaxidlist = [tupla for sublist in
binned_lists for tupla in sublist]
# creating a df for centrifuge classified reads
if maintaxidlist:
centrifuged_taxId = pd.DataFrame(maintaxidlist,
columns=['readID', 'Group'])
main_df = main_df.merge(centrifuged_taxId, on='readID', how='left')
else:
main_df = main_df.assign(Group=np.NaN)
return main_df
def dataframe_collection(df, npartitions):
'''
:param df:
:param npartitions:
:return:
'''
df_size = len(df.index)
if npartitions > df_size:
ms = 'Number of partitions is larger '
ms += 'than dataframe size. The number of'
ms += 'partitions will be set to: %s' % df_size
print(ms, sep=' ', end='\n', file=sys.stdout, flush=False)
npartitions = df_size
df_split = np.array_split(df, npartitions)
return df_split
def directplast(new_dir_path, file_name, suffix, name, max_plast, cpus):
'''
:param new_dir_path:
:param file_name:
:param suffix:
:param name:
:param max_plast:
:param cpus:
:return:
'''
try:
cmd = 'seqkit fq2fa %s | seqkit split -p %s -j %s -' % (file_name,
max_plast,
cpus)
except:
cmd = 'seqkit split -1 %s -p %s -j %s ' % (file_name, max_plast, cpus)
ms = 'directplast cmd is:\n%s' % cmd
print(ms, sep=' ', end='\n', file=sys.stdout, flush=False)
_ = run(cmd, stdout=PIPE, stderr=PIPE, shell=True)
# change name of output and moving it to a different directory
new_name = '%s%s' % (name, suffix)
myfiles = relocating_files(new_name, new_dir_path)
return myfiles
def relocating_files(suffix, new_dir_path):
'''
:param suffix:
:param new_dir_path:
:return:
'''
splits = os.path.join(os.getcwd(), 'stdin.split')
files = glob.glob('%s/*' % splits)
count = 0
for fname in files:
count += 1
new_name = '%s_%s.query' % (suffix, count)
new_path = os.path.join(new_dir_path, new_name)
shutil.move(fname, new_path)
os.system('rm -r %s' % 'stdin.split')
myfiles = glob.glob('%s/*' % new_dir_path)
return myfiles
def isfasta(infile):
cmd = 'head -1 %s' % infile
ms = 'cmd isfasta is %s' % cmd
print(ms, sep=' ', end='\n', file=sys.stdout, flush=False)
_ = run(cmd, stdout=PIPE, stderr=PIPE, shell=True)
line1 = _.stdout.decode('utf-8')
if line1.startswith('>'):
return True
else:
return False
def split_reads(new_dir_path, reads_to_select, read_file,
suffix, name, cpus, max_plast):
'''
:param new_dir_path:
:param reads_to_select:
:param read_file:
:param suffix:
:param name:
:param cpus:
:param max_plast:
:return:
'''
path_list = os.path.join(os.getcwd(), '%s_list.tmp' % suffix)
handle = open(path_list, 'w')
for read in reads_to_select:
handle.write('%s\n' % read)
handle.close()
_ = isitready(reads_to_select, path_list)
if isfasta(read_file[0]):
cmd = 'seqkit grep -f %s %s |' % (path_list, read_file[0])
cmd += 'seqkit split2 -p %s -j %s' % (max_plast, cpus)
else:
if isinstance(read_file, list) and len(read_file) == 1:
read_file = read_file[0]
cmd = 'seqkit grep -f %s %s | seqkit ' % (path_list, read_file)
cmd += 'fq2fa -|seqkit split2 -p %s -j %s' % (max_plast, cpus)
ms = 'seqkit cmd:\n %s' % cmd
print(ms, sep=' ', end='\n', file=sys.stdout, flush=False)
_ = run(cmd, stdout=PIPE, stderr=PIPE, shell=True)
# change name of output and moving it to a different directory
# new_name = '%s%s' % (name, suffix)
myfiles = relocating_files(suffix, new_dir_path)
return myfiles
def slicing(new_dir_path, main_df, file_name, df_class_report,
suffix, name, cpus, max_plast):
'''
It creates a complete data frame containing pre-classified
columns by readId and NaN objects post centrifuge
:param new_dir_path:
:param main_df:
:param file_name:
:param df_class_report:
:param suffix:
:param name:
:param cpus:
:param max_plast:
:return:
'''
start_time = time.time()
if cpus <= 10:
n_chunks = 10
else:
n_chunks = round(cpus * 0.5) # use few to avoid memory overhead by
# taxonomy
collection = dataframe_collection(df_class_report, n_chunks)
dfs = Parallel(n_jobs=-2, verbose=1)(delayed(
binningbytaxonomy)(chunk) for chunk in collection)
#
elapsed = round(time.time() - start_time, 3)
minutes = round((elapsed / 60), 3)
hours = round((minutes / 60), 3)
ms = 'Elapsed time at taxonomy binning:\n%s seconds or %s ' % (elapsed,
minutes)
ms += 'minutes or %s hours' % hours
print(ms, sep=' ', end='\n', file=sys.stdout, flush=False)
#
full_df = taxpickup(dfs, main_df)
_ = full_df.to_csv('%sfull_df.tsv' % name, sep='\t', header=True)
slice = full_df[full_df['Group'].isnull()]
slice = set(slice['readID'].tolist())
# double - check that not-nulls go to plast
if slice:
file_names = split_reads(new_dir_path, slice, file_name, suffix,
name, cpus, max_plast)
print(file_names, sep=' ', end='\n', file=sys.stdout, flush=False)
return full_df, file_names
else:
m = 'Nothing to slice!'
print(m, sep=' ', end='\n', file=sys.stdout, flush=False)
return pd.DataFrame(), m
def Taxonomy_translation(acc2DBpath, pre_acc2tax_df, suffix, typ):
'''
Executable of acc2tax MUST be in the environmental path
:param acc2DBpath:
:param pre_acc2tax_df:
:param suffix:
:param typ:
:return:
'''
# writing acc2taxIN as input for acc2tax software
base_fname = string_out(pre_acc2tax_df, suffix, typ)
ms = 'Extracting taxonomy with acc2tax...'
print(ms, sep=' ', end='\n', file=sys.stdout, flush=False)
line = 'acc2tax -a -d %s -i %sIN%s -n -o %sOUT%s.raw'
line %= acc2DBpath, base_fname, suffix, base_fname, suffix
run(line, stdout=PIPE,
stderr=PIPE, shell=True)
time.sleep(5)
taxdump = pd.read_table('%sOUT%s.raw'
% (base_fname, suffix), header=None,
sep='\t', names=['Accession', 'Taxonomy'],
dtype=object)
# adding readIDs with taxonomy
if not taxdump.empty:
taxdump = pre_acc2tax_df.merge(taxdump,
on='Accession', how='left')
# getting only the domain
slice = taxdump['Taxonomy'].str.split(',', 2,
expand=True).loc[:, 1]
# renaming and creating the taxonomic df
virpattern = r'\b.{0, 20}vir.{0,100}\b'
viregex = re.compile(virpattern, flags=re.IGNORECASE)
slice = slice.replace(viregex, value='Vir', regex=True)
temp = taxdump.merge(pd.DataFrame(slice),
left_index=True, right_index=True).rename(
columns={1: 'Group'})
temp = temp.reindex(columns=['readID', 'Accession', 'Group'])
temp = temp.drop_duplicates()
return temp
else:
ms = 'taxdump is empty'
print(ms, sep=' ', end='\n', file=sys.stdout, flush=False)
return taxdump
def customtaxtranslation(seqidtaxid_map, parseby, plast_output):
'''
:param seqidtaxid_map:
:param parseby:
:param plast_output:
:return:
'''
# subject ID and first column of seqidtaxid_map must match
ms = 'Using custom taxonomy ...'
print(ms, sep=' ', end='\n', file=sys.stdout, flush=False)
colnames = ['subject ID', 'taxID', 'Group']
taxid_map = pd.read_table(seqidtaxid_map, sep='\t',
header=None, names=colnames,
dtype={0: str, 1: str, 2: str})
taxids = plast_output.merge(taxid_map, on='subject ID',
how='inner')
# for now make sure that is 'Group'
taxids = taxids.loc[:, ['readID', parseby]]
taxids = taxids.groupby('readID', as_index=False).first()
return taxids
def string_out(df, suffix, typ='RefSeq'):
'''
:param df:
:param suffix:
:param typ:
:return:
'''
outname = 'acc2taxIN'
if (os.path.isfile('%s%s' % (outname, suffix))
or os.path.isfile('acc2taxOUT%s.raw' % suffix)):
os.system('rm *acc2tax*')
if not typ == 'RefSeq':
string = set(df['Accession'].tolist())
else:
try:
acc = df['subject ID'].str.split('|', 4,
expand=True).loc[:, 3].str.split(
'.', 1, expand=True).loc[:, 0]
except:
acc = df['subject ID']
string = set(acc.tolist())
L = len(string)
string = '\n'.join(string) + '\n'
with open('%s%s' % (outname, suffix), 'w') as O:
O.write(string)
while True:
time.sleep(3)
c = run('wc -l %s%s' % (outname, suffix), stderr=PIPE, stdout=PIPE,
shell=True, universal_newlines=True)
lc = int(c.stdout.split()[0])
if lc == L:
break
return outname[:-2]
def other_dfs(df):
lista = ['Archaea', 'Bacteria',
'Eukaryota', 'Vir']
xdf = df[~df['Group'].isin(lista)]
return xdf['readID'].tolist()
def bin(gdf, group, label):
'''
:param gdf:
:param group:
:param label:
:return:
'''
try:
x = gdf.get_group(group)
_ = x.to_csv('%s_grouped_by_%s.tsv' % (label, group),
sep='\t', header=True)
val = set(gdf.get_group(group).loc[
:, 'readID'].tolist())
except:
ms = 'empty bin %s %s' % (label, group)
print(ms, sep=' ', end='\n', file=sys.stdout, flush=False)
val = set()
return val
def tokeep(grouped_df, group,
excludegroup, reject_set, label):
'''
Subsetting by exclusion of 'rejecting set'
:param grouped_df:
:param group:
:param excludegroup:
:param reject_set:
:param label:
:return:
'''
try:
eg = [excludegroup]
df = grouped_df.get_group(group)
_ = df.to_csv('%s_grouped_by_%s.tsv' % (label, group),
sep='\t', header=True)
ndf = df[~df['Group'].isin(eg)]
_ = df.to_csv('%s_grouped_by_%s_excl_%s.tsv' % (
label, group, excludegroup), sep='\t', header=True)
ndf = set(ndf['readID'].tolist())
ndf = ndf.difference(reject_set)
return ndf
except:
return set()
def intersects(set1, set2, set3):
'''
Checking if intersections among bins exist
:param set1:
:param set2:
:param set3:
:return:
'''
isects = [set1.intersection(set2),
set1.intersection(set3),
set2.intersection(set3)]
_ = zip(['Bact-Arch', 'Bact-NonCel', 'Arch-Noncel'], isects)
nr_inters = set([n for s in isects for n in s])
set1, set2 = [s.difference(nr_inters)
for s in [set1, set2]]
set3 = set3.union(nr_inters)
return nr_inters, set1, set2, set3
def grouper(label, pref, df, reads):
'''
Grouping by major categories and check to deduplicate dfs
:param label:
:param pref:
:param df:
:param reads:
:return:
'''
merged, pre_unknown = df
if not merged.empty:
_ = merged.to_csv('%s_merged_df.tsv' % label, sep='\t', header=True)
merged['Group'] = merged['Group'].str.strip()
grouped_df = merged.groupby('Group', as_index=False)
Euk = bin(grouped_df, 'Eukaryota', label)
Bact = tokeep(grouped_df, 'Bacteria', 'Eukaryota', Euk, label)
Arch = tokeep(grouped_df, 'Archaea', 'Eukaryota', Euk, label)
Vir = tokeep(grouped_df, 'Vir', 'Eukaryota', Euk, label)
# making sure no duplicates are present and
# enforcing eukaryota and unkown to merge
intersect, Bact, Arch, Misc = intersects(Bact, Arch, Vir)
Euk = Euk.difference(intersect)
Preset = set().union(*[Bact, Arch, Vir, Euk])
Unk = pre_unknown.union(other_dfs(merged))
Unk = Unk.difference(Preset)
EUnk = set(Euk).union(Unk)
sel_reads = [('Bact', label, pref, Bact, reads),
('Arch', label, pref, Arch, reads),
('EUnk', label, pref, EUnk, reads),
('Misc', label, pref, Misc, reads),
('Euk', label, pref, Euk, reads)]
return sel_reads
else:
Unk = pre_unknown
sel_reads = [('Unk', label, pref, Unk, reads)]
return sel_reads
def nullandmerged(df1, df2):
'''
:param df1:
:param df2:
:return:
'''
if not 'Group' in df1.columns:
df1 = df1.assign(Group=np.NaN)
df1.Group = df1.Group.astype(str)
df1 = df1.set_index('readID')
df2 = df2.set_index('readID')
combined = df2.combine_first(df1)
df1 = df1.reset_index()
combined = combined.reset_index()
merged = combined.loc[:, ['readID', 'Group']]
merged = merged.groupby('readID', as_index=False).first()
merged = merged.loc[merged['Group'].notnull()]
allreads = set(df1.loc[:, 'readID'].tolist())
m = set(merged.loc[:, 'readID'].tolist())
pre_unknown = allreads.difference(m)
return merged, pre_unknown
def empty(df):
'''
:param df:
:return:
'''
if not 'Group' in df.columns:
df = df.assign(Group=np.NaN)
pre_unknown = set(df['readID'].tolist())
merged = pd.DataFrame()
ms = 'In emtpy: pre_unknown\n %s, merged\n%s' % (pre_unknown, merged)
print(ms, sep=' ', end='\n', file=sys.stdout, flush=False)
return merged, pre_unknown
def input_check_and_setup(user_args):
'''
:param user_args: dictionary containing arguments
:return: type: list of the checked arguments
'''
# --- Global required values ---
map_id_path = user_args['plast_id_map']
plast_path = user_args['plast_database']
acc2tax_path = user_args['acc2tax_database']
pid = user_args['pid']
cov = user_args['cov']
e_value = user_args['e_value']
tax_up = True if user_args['taxonomy_update'] == 'True' else False
n_cpu = user_args['number_of_threads']
max_plast = user_args['number_of_chunks']
base_outname = user_args['out_name']
# args specific to illumina workflow
if user_args['func'].__name__ == 'long_seqs':
reads = [user_args['long_seqs']]
classification = ['Pass']
else:
reads = [user_args['r1'], user_args['r2'], user_args['un']]
if type(user_args['pclass']) is not None and type(
user_args['uclass']) is not None:
classification = [user_args['pclass'],
user_args['uclass']]
else:
classification = ['None', 'None']
# check file existence and classification
redef_reads = [it if (os.path.exists(it)
and os.stat(it).st_size != 0)
else 'None' for it in reads]
reads_paths = [os.path.abspath(it) if os.path.exists(it)
else 'None' for it in redef_reads]
redef_class = [os.path.abspath(it) if (os.path.exists(it)
and os.stat(
it).st_size != 0) else 'None' for it in
classification]
if not user_args['func'].__name__ == 'long_seqs':
declared = reads_paths + redef_class
else:
declared = reads_paths
if any(i is 'None' for i in declared):
ms = '\nIt seems that at least one declared file DOES NOT exist '
ms += 'in the directory and has been labeled as "None". \n'
ms += 'Please check your command line.\nDeclared files are:\n'
ms += '*** Reads and Classification files are : ***\n'
ms += '%s\n' % '\n'.join(declared)
ms += '--- Exiting program ---'
print(ms, sep=' ', end='\n', file=sys.stdout, flush=False)
sys.exit(0)
if not os.path.exists(plast_path):
ms = '\n\nNo plast database found. Exiting program'
print(ms, sep=' ', end='\n', file=sys.stdout, flush=False)
sys.exit(0)
if not os.path.exists(map_id_path):
format_check = plast_path
ms = '\n\nNo map for plast_database was found. Exiting program'
print(ms, sep=' ', end='\n', file=sys.stdout, flush=False)
sys.exit(0)
acc2tax_fn = ['nodes.dmp', 'names.dmp', 'acc2tax_prot_all.txt',
'acc2tax_nucl_all.txt']#, 'gi_taxid_nucl.dmp',
#'gi_taxid_prot.dmp']
for fn in acc2tax_fn:
apath = os.path.join(acc2tax_path, fn)
if not os.path.exists(apath):
ms = '\n\nSomething is wrong with the acc2tax database.\n'
ms += 'Please make sure that you are specifiying the path to a '
ms += 'directory that contains the following files: '
ms += 'nodes.dmp, names.dmp, prot_all.txt, nucl_all.txt, '
ms += 'gi_taxid_nucl.dmp, gi_taxid_prot.dmp\nExiting program..'
print(ms, sep=' ', end='\n', file=sys.stdout, flush=False)
sys.exit(0)
if e_value is None:
e_value = 1.0
if pid is None:
pid = 10.0
if cov is None:
cov = 0.0
if len(glob.glob('%s.*.cf' % user_args['cdb'])) != 4:
cdb = '\nCentrifuge database does not exist in path.\n'
cdb += 'Exiting program.\n'
print(cdb, sep=' ', end='\n', file=sys.stdout, flush=False)
sys.exit(0)
cdb_path = user_args['cdb']
minhit_len = user_args['mhlen']
if not user_args['func'].__name__ == 'long_seqs':
aplast_path = user_args['ancillary_plast_database']
amap_id_path = user_args['ancillary_plast_id_map']
# max_len = user_args['mlen']
max_mem = user_args['max_m']
# cdb_path = user_args['cdb']
if aplast_path is None or not os.path.exists(aplast_path):
aplast_path = plast_path
amap_id_path = map_id_path
ms = '\nNo ancillary plast database found. Current plast_database '
ms += 'will be used for re-classification\n'
print(ms, sep=' ', end='\n', file=sys.stdout, flush=False)
if os.path.exists(aplast_path):
if not os.path.exists(amap_id_path):
ms = '\n\nNo map for plast_database was found. Exiting program'
print(ms, sep=' ', end='\n', file=sys.stdout, flush=False)
sys.exit(0)
# if len(glob.glob('%s.*.cf' % user_args['cdb'])) != 4:
# cdb = '\nCentrifuge database does not exist in path.\n'
# cdb += 'Exiting program.\n'
# print(cdb, sep=' ', end='\n', file=sys.stdout, flush=False)