-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgeminiphage.py
1969 lines (1951 loc) · 116 KB
/
geminiphage.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
'''
┌─┐ ┌─┐ ┌┬┐ ┬ ┌┐┌ ┬
│ ┬ ├┤ │││ │ │││ │
└─┘ └─┘ ┴ ┴ ┴ ┘└┘ ┴ phage
---------------------------------------------------
-*- coding: utf-8 -*- |
title : geminiphage.py |
description : gemini phage functions |
author : dooguypapua |
lastmodification : 20210629 |
version : 0.1 |
python_version : 3.8.5 |
---------------------------------------------------
'''
import os
import sys
import re
import shutil
import filecmp
import gzip
import geminiset
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import textwrap
from ete3 import NCBITaxa
from typing import Tuple
from tqdm import tqdm
from yaspin import yaspin
from yaspin.spinners import Spinners
from Bio.Seq import Seq
from dna_features_viewer import GraphicFeature, GraphicRecord
from geminini import path_converter, get_input_files, printcolor, get_gemini_path, get_sys_info, fct_checker, cat_lstfiles, read_file
from geminini import dump_json, load_json, reverse_complement, launch_threads, title, exit_gemini, longest_common_substring
from geminiparse import unwrap_fasta, make_blast_dict, make_fasta_dict, make_hmmscan_dict, make_gff_dict
from geminiparse import make_trnascanse_dict, make_interpro_dict, make_eggnog_dict, make_gbk_from_fasta
from geminiparse import blastdict_to_annotsort, hmmscandict_to_dictlt, gbk_to_faa, make_gbk_dict, gbk_to_gff
# from geminiparse import get_refseqacc_from_dict, make_uniprotmapping_dict, make_pvogs_desc_dict
from geminiannot import phanotate, transeq, trnascan_se, pvogs, diamond_p, interproscan, eggnog # , recombinase
from geminicluster import mmseqs_rbh, make_rbhcluster_dict
from geminidl import get_etag, get_ftp_file_size, get_distant_file_tqdm
@fct_checker
def viridic(pathIN: str, pathOUT: str, ext: str = ".fna") -> Tuple[str, str, str]:
'''
------------------------------------------------------------
| VIRIDIC |
|------------------------------------------------------------|
| Phages clustering using VIRIDIC |
|------------------------------------------------------------|
|PARAMETERS |
| pathIN : path of input files or folder (required) |
| pathOUT : path of output files (required) |
| ext : extension of input files (default=.fna) |
------------------------------------------------------------
|TOOLS: viridic |
------------------------------------------------------------
'''
lstFiles, maxpathSize = get_input_files(pathIN, "viridic", [ext])
if len(lstFiles) == 0:
printcolor("[ERROR: viridic]\nAny input files found\n", 1, "212;64;89", "None", True)
exit_gemini()
if len(lstFiles) == 1:
printcolor("[ERROR: viridic]\nViridic required a minimum of two genomes\n", 1, "212;64;89", "None", True)
exit_gemini()
dicoGeminiPath, dicoGeminiModule = get_gemini_path()
if 'viridic' in dicoGeminiModule:
os.system("module load "+dicoGeminiModule['viridic'])
slurmBool, cpu, memMax, memMin = get_sys_info()
if pathOUT == "":
printcolor("[ERROR: viridic]\nMissing '-o'pathOUT\n", 1, "212;64;89", "None", True)
exit_gemini()
pathOUT = path_converter(pathOUT)
os.makedirs(pathOUT, exist_ok=True)
pathLOG = pathOUT+"/viridic.log"
# Concatenate fasta
printcolor("♊ Cat files"+"\n")
pathTMPcat = geminiset.pathTMP+"/concat_viridic.fna"
strLstError = ""
for pathFNA in lstFiles:
file = os.path.basename(pathFNA)
orgName = file.replace(ext, "").replace("."+ext, "")
dicoFNA = make_fasta_dict(pathFNA)
seq = ""
cptSeq = 0
for key in dicoFNA:
seq += dicoFNA[key]
cptSeq += 1
if cptSeq != 1:
strLstError += "[ERROR: viridic]\nNot a single contig genome for '"+file+"'\n"
TMPCAT = open(pathTMPcat, 'a')
TMPCAT.write(">"+orgName+"\n"+seq+"\n")
TMPCAT.close()
if strLstError != "":
printcolor(strLstError, 1, "212;64;89", "None", True)
exit_gemini()
# Launch viridic
spinner = yaspin(Spinners.aesthetic, text="♊ VIRIDIC", side="right")
spinner.start()
title("VIRIDIC", None)
cmdViridic = dicoGeminiPath['TOOLS']['viridic']+" in = "+pathTMPcat+" projdir = "+pathOUT+" ncor = "+str(cpu)+" > "+pathLOG+" 2>&1"
os.system(cmdViridic)
spinner.stop()
printcolor("♊ VIRIDIC"+"\n")
@fct_checker
def phage_annotation(pathIN: str, pathOUT: str, boolEMBL: bool = False, enaProject: str = "None", pathTAXO: str = "None", idEvalue: float = "0.01", idThr: int = 30, covThr: int = 50, idThrClust: int = 80, covThrClust: int = 80, ext: str = ".fna") -> Tuple[str, str, bool, str, str, float, int, int, int, int, str]:
'''
------------------------------------------------------------
| PHAGE ANNOTATION |
|------------------------------------------------------------|
| Phage syntaxic and functionnal annotation |
| (only for finished genome into one contig) |
|------------------------------------------------------------|
|PARAMETERS |
| pathIN : path of input files or folder (required) |
| pathOUT : path of output files (required) |
| boolEMBL : output .embl files (default=False) |
| enaProject : ENA project to embl files (default=None) |
| pathTAXO : path of input taxonomy file (default=None) |
| idEvalue : Evalue threshold (default=0.01) |
| idThr : %identity threshold (default=30) |
| covThr : %coverage threshold (default=50) |
| idThrClust : %identity clustering threshold (default=80)|
| covThrClust: %coverage clustering threshold (default=80)|
| ext : extension of input files (default=.fna) |
------------------------------------------------------------
all DMND databases must be formatted as : "identifier|product|organism"
'''
pathOUT = path_converter(pathOUT)
lstFiles, maxpathSize = get_input_files(pathIN, "phage_syntaxic_annotation", [ext])
if len(lstFiles) == 0:
printcolor("[ERROR: phage_annotation]\nAny input files found, check extension\n", 1, "212;64;89", "None", True)
exit_gemini()
if boolEMBL is True:
pathTAXO = path_converter(pathTAXO)
if not os.path.isfile(pathTAXO):
printcolor("[ERROR: phage_annotation]\nAny taxonomy input file found\n", 1, "212;64;89", "None", True)
exit_gemini()
if "PRJEB" not in enaProject:
printcolor("[ERROR: phage_annotation]\nMissing ENA project for .embl files\n", 1, "212;64;89", "None", True)
exit_gemini()
os.makedirs(pathOUT, exist_ok=True)
dicoGeminiPath, dicoGeminiModule = get_gemini_path()
# ***** SYNTAXIC Annotation & TRANSLATION ***** #
phanotate(pathIN=pathIN, pathOUT=pathOUT, ext=".fna")
transeq(pathIN=pathOUT, pathOUT=pathOUT, boolOrgName=False, ext=".ffn")
# ***** tRNA Annotation ***** #
trnascan_se(pathIN=pathIN, pathOUT=pathOUT, model="-B", ext=".fna")
dicoTRNA = make_trnascanse_dict(pathIN=pathOUT, pathJSON=pathOUT+"/trnascan_se.json", ext=".trnascanse")
# ***** Recombinase Annotation ***** #
# recombinase(pathIN=pathOUT, pathOUT=pathOUT, ext=".faa")
# dicoREC = make_hmmscan_dict(pathIN=pathOUT, pathJSON=pathOUT+"/recombinase.json", idEvalue=idEvalue, ext=".recomb")
# dicoREC_LT = hmmscandict_to_dictlt(dicoREC)
# ***** pVOGS profiles Annotation ***** #
pvogs(pathIN=pathOUT, pathOUT=pathOUT, ext=".faa")
dicoPVOGS = make_hmmscan_dict(pathIN=pathOUT, pathJSON=pathOUT+"/pvogs.json", idEvalue=idEvalue, ext=".pvogs")
# dicoPVOGSdescr = make_pvogs_desc_dict(pathIN=pathOUT+"/pvogs.json", pathJSON=pathOUT+"/pvogs_descr.json")
dicoPVOGS_LT = hmmscandict_to_dictlt(dicoPVOGS)
# ***** Nahant collection Annotation ***** #
diamond_p(pathIN=pathOUT, pathDB=dicoGeminiPath['DATABASES']['nahant_dmnd'], pathOUT=pathOUT, ext=".faa")
dicoNAHANT = make_blast_dict(pathIN=pathOUT, dbName="nahant", pathJSON=pathOUT+"/nahant.json", idThr=idThr, minLRthr=covThr, maxLRthr=covThr, ext=".tsv")
dicoNAHANT_ANNOTSORT = blastdict_to_annotsort(dicoNAHANT)
# ***** Refseq collection Annotation ***** #
diamond_p(pathIN=pathOUT, pathDB=dicoGeminiPath['DATABASES']['refseq212bct_dmnd'], pathOUT=pathOUT, ext=".faa")
dicoREFSEQ = make_blast_dict(pathIN=pathOUT, dbName="refseq212bct", pathJSON=pathOUT+"/refseq.json", idThr=idThr, minLRthr=covThr, maxLRthr=covThr, ext=".tsv")
dicoREFSEQ_ANNOTSORT = blastdict_to_annotsort(dicoREFSEQ)
# ***** phageDB collection Annotation ***** #
diamond_p(pathIN=pathOUT, pathDB=dicoGeminiPath['DATABASES']['phagedb_dmnd'], pathOUT=pathOUT, ext=".faa")
dicoPHAGEDB = make_blast_dict(pathIN=pathOUT, dbName="phagedb", pathJSON=pathOUT+"/phagedb.json", idThr=idThr, minLRthr=covThr, maxLRthr=covThr, ext=".tsv")
dicoPHAGEDB_ANNOTSORT = blastdict_to_annotsort(dicoPHAGEDB)
# ***** InterProScan Annotation ***** # (JSON output)
interproscan(pathIN=pathOUT, pathOUT=pathOUT, ext=".faa")
dicoIPRSCAN = make_interpro_dict(pathIN=pathOUT+"/interproscan.tsv", idEvalue=idEvalue, pathJSON=pathOUT+"/interproscan.json", ext=".tsv")["interproscan"]
# ***** EggNOG Annotation ***** #
eggnog(pathIN=pathOUT, pathOUT=pathOUT, idThr=idThr, covThr=covThr, ext=".faa")
dicoEGGNOG = make_eggnog_dict(pathIN=pathOUT, pathJSON=pathOUT+"/eggnog.json", ext=".annotations")["eggnog"]
# ***** RBH clustering ***** #
mmseqs_rbh(pathIN=pathOUT, pathOUT=pathOUT, idThrClust=idThrClust, covThrClust=covThrClust, ext=".faa")
make_rbhcluster_dict(pathIN=pathOUT, pathIN2=pathOUT, pathJSON=pathOUT+"/rbh_cluster.json", idThrClust=idThrClust, covThrClust=covThrClust, ext=".rbh", ext2=".faa")
# ***** GENERATE EMBL ***** #
if boolEMBL is True:
# ***** TAXONOMY *****#
dicoTaxo = {}
TSV = open(pathTAXO, 'r')
lstLines = TSV.read().split("\n")[:-1]
TSV.close()
for line in lstLines:
dicoTaxo[line.split("\t")[0]] = line.split("\t")[1]
# # ***** UNIPROT mapping *****#
# # Get all refseq accession
# setRefseqAcc = get_refseqacc_from_dict([dicoNAHANT, dicoREFSEQ, dicoPHAGEDB])
# # Make uniprot_mapping dictionnary
# dicoUniprotMapping = make_uniprotmapping_dict(pathIN=dicoGeminiPath['uniprot_mapping'], setRefseqAcc=setRefseqAcc, pathJSON=pathOUT+"/uniprot_mapping.json")
# ***** Make EMBL file *****#
for pathFNA in lstFiles:
orgName = os.path.basename(pathFNA).replace(ext, "").replace("."+ext, "")
# Read FASTAs
dicoFNA = make_fasta_dict(pathFNA)
if len(dicoFNA) > 1:
exit_gemini("Unable to make embl for more than one contigs FASTA")
genomeSeq = list(dicoFNA.values())[0]
dicoFAA = make_fasta_dict(pathOUT+"/"+orgName+".faa")
dicoFFN = make_fasta_dict(pathOUT+"/"+orgName+".ffn")
LTprefix = list(dicoFAA.keys())[0].split("_p")[0]+"_p"
# EMBL description header
description = orgName.replace("Vibrio_phage_", "Vibrio phage ")+" complete genome."
wrapper = textwrap.TextWrapper(width=70)
if len(description) <= 70:
descr = "DE "+description+"\n"
else:
descr_list = wrapper.wrap(text=description)
descr = "DE "+descr_list[0]+"\n"
for i in range(1, len(descr_list), 1):
descr += "DE "+descr_list[i]+"\n"
# EMBL taxonomy header
taxonomy = dicoTaxo[orgName]
wrapper = textwrap.TextWrapper(width=70)
if len(taxonomy) <= 70:
taxo = "OC "+taxonomy+"\n"
else:
taxo_list = wrapper.wrap(text=taxonomy)
taxo = "OC "+taxo_list[0]+"\n"
for i in range(1, len(taxo_list), 1):
taxo += "OC "+taxo_list[i]+"\n"
# EMBL complete header
embl_header = "ID "+LTprefix.replace("_p", "")+"; SV 1; linear; genomic DNA; STD; PHG; "+str(len(genomeSeq))+" BP.\n" +\
"XX\n" +\
"AC "+LTprefix.replace("_p", "")+"\n" +\
"XX\n" +\
"PR Project:"+enaProject+";\n" +\
"XX\n" +\
descr +\
"XX\n" +\
"KW complete genome.\n" +\
"XX\n" +\
"OS "+orgName.replace("_", " ")+"\n" +\
taxo +\
"XX\n" +\
"FH Key Location/Qualifiers\n" +\
"FH\n"
# Construct features dictionnary (key = start)
dicoFeatures = {}
# TRNA FEATURES
for trna in dicoTRNA[orgName]:
if dicoTRNA[orgName][trna]['pseudo'] is False:
if dicoTRNA[orgName][trna]['strand'] == 1:
strPos = str(dicoTRNA[orgName][trna]['start'])+".."+str(dicoTRNA[orgName][trna]['end'])
else:
strPos = "complement("+str(dicoTRNA[orgName][trna]['start'])+".."+str(dicoTRNA[orgName][trna]['end'])+")"
feature = "FT gene "+strPos+"\n" +\
"FT /locus_tag=\""+LTprefix+"tRNA"+trna.zfill(2)+"\"\n" +\
"FT tRNA "+strPos+"\n" +\
"FT /locus_tag=\""+LTprefix+"tRNA"+trna.zfill(2)+"\"\n" +\
"FT /product=\"tRNA-"+dicoTRNA[orgName][trna]['type'][:3]+"\"\n" +\
"FT /inference=\"profile:tRNAscan:2.0.9\"\n"
dicoFeatures[dicoTRNA[orgName][trna]['start']] = feature
# CDS FEATURES
for key in dicoFFN:
lt = key.split(" ")[0].split("|")[0]
# GENE POSITIONS
if dicoFFN[key] in genomeSeq:
start = genomeSeq.find(dicoFFN[key])+1
end = start+len(dicoFFN[key])-1
strPos = str(start)+".."+str(end)
else:
start = genomeSeq.find(reverse_complement(str(Seq(dicoFFN[key]))))+1
end = start+len(dicoFFN[key])-1
strPos = "complement("+str(start)+".."+str(end)+")"
# GENE PRODUCT based on blast results (order by confidence)
validateProduct = set()
validateUnprecisedProduct = set()
putativeProduct = set()
putativeUnprecisedProduct = set()
foundBlast = False
validateHitAcc = set()
for dicoBlastSort in [dicoREFSEQ_ANNOTSORT, dicoNAHANT_ANNOTSORT, dicoPHAGEDB_ANNOTSORT]:
if lt in dicoBlastSort[orgName]:
foundBlast = True
for order in dicoBlastSort[orgName][lt]:
for hit in dicoBlastSort[orgName][lt][order]:
hitProduct = hit.split("_____")[0]
hitAcc = hit.split("_____")[1]
pident = float(hit.split("_____")[2])
if "hypothetical" not in hitProduct:
if pident >= 75.0:
if "putative" not in hitProduct and "coil containing protein" not in hitProduct and "domain-containing protein" not in hitProduct:
validateProduct.add(hitProduct)
validateHitAcc.add(hitAcc)
else:
validateUnprecisedProduct.add(hitProduct)
elif pident >= 30.0:
if "putative" not in hitProduct and "coil containing protein" not in hitProduct and "domain-containing protein" not in hitProduct:
putativeProduct.add(hitProduct)
else:
putativeUnprecisedProduct.add(hitProduct.replace("putative ", ""))
if len(validateProduct) > 0:
product = list(validateProduct)[0]
elif len(validateUnprecisedProduct) > 0:
product = list(validateUnprecisedProduct)[0]
elif len(putativeProduct) > 0:
product = "putative "+list(putativeProduct)[0]
elif len(putativeUnprecisedProduct) > 0:
product = "putative "+list(putativeUnprecisedProduct)[0]
elif foundBlast is True:
product = "conserved hypothetical protein"
else:
product = "hypothetical protein"
# GENE FEATURES
feature = "FT gene "+strPos+"\n" +\
"FT /locus_tag=\""+lt+"\"\n" +\
"FT CDS "+strPos+"\n" +\
"FT /locus_tag=\""+lt+"\"\n" +\
"FT /inference=\"ab initio prediction:PHANOTATE:1.5.0\"\n" +\
"FT /transl_table=11\n"
# Format product (split if line>75kr == product>43)
wrapper = textwrap.TextWrapper(width=43)
if len(product) <= 43:
feature += "FT /product=\""+product+"\"\n"
else:
product_list = wrapper.wrap(text=product)
feature += "FT /product=\""+product_list[0]+"\n"
for i in range(1, len(product_list), 1):
if i == len(product_list)-1:
feature += "FT "+product_list[i]+"\"\n"
else:
feature += "FT "+product_list[i]+"\n"
# DB_XREF based on domain and pvogs RESULTS
if lt in dicoIPRSCAN:
for motif in dicoIPRSCAN[lt]:
if "IPR" in motif:
feature += "FT /db_xref=\"InterPro:"+motif+"\"\n"
if lt in dicoEGGNOG and dicoEGGNOG[lt]["finalOg"] != "":
feature += "FT /db_xref=\"EggNOG:"+dicoEGGNOG[lt]["finalOg"]+"\"\n"
if lt in dicoPVOGS_LT[orgName]:
for pvog in dicoPVOGS_LT[orgName][lt]:
feature += "FT /db_xref=\"pVOGs:"+pvog+"\"\n"
dicoFeatures[start] = feature
# EMBL genome sequence
embl_sequence = "SQ Sequence "+str(len(genomeSeq))+" BP; " + \
str(genomeSeq.count("A"))+" A; "+str(genomeSeq.count("C"))+" C; " + \
str(genomeSeq.count("G"))+" G; "+str(genomeSeq.count("T"))+" T; " + \
str(genomeSeq.count("N"))+" other;\n"
wrapper = textwrap.TextWrapper(width=60)
seq_list = wrapper.wrap(text=genomeSeq)
cpt = 0
for i in range(len(seq_list)):
seqLine = " "
for j in range(0, len(seq_list[i]), 10):
seqLine += seq_list[i][j:j+10].lower()+" "
finalPos = cpt+len(seq_list[i])
seqLine += " "*(80-(len(seqLine)+len(str(finalPos))))+str(finalPos)
embl_sequence += seqLine+"\n"
cpt += len(seq_list[i])
embl_sequence += "//"
# ***** WRITE .embl file ***** #
pathEMBLOUT = pathOUT+"/"+orgName+".embl"
EMBLOUT = open(pathEMBLOUT, 'w')
EMBLOUT.write(embl_header[:-1]+"\n")
for start in sorted(dicoFeatures.keys()):
EMBLOUT.write(dicoFeatures[start][:-1]+"\n")
EMBLOUT.write("XX\n")
EMBLOUT.write(embl_sequence+"\n")
EMBLOUT.close()
# # ***** CREATE GFF3 files ***** #
# printcolor("♊ Create GFF3"+"\n")
# pbar = tqdm(total=len(lstFiles), dynamic_ncols=True, ncols=50+maxpathSize, leave=False, desc="", file=sys.stdout, bar_format=" {percentage: 3.0f}%|{bar}| {n_fmt}/{total_fmt} [{desc}]")
# for pathFNA in lstFiles:
# orgName = os.path.basename(pathFNA).replace(ext, "").replace("."+ext, "")
# pathGFF = pathOUT+"/"+orgName+".gff"
# pbar.set_description_str(orgName+" ".rjust(maxpathSize-len(orgName)))
# if not os.path.isfile(pathGFF) or os.path.getsize(pathGFF) == 0:
# GFF = open(pathGFF, 'w')
# # Retrieve genome sequence
# dicoFNA = make_fasta_dict(pathFNA)
# genomeSeq = list(dicoFNA.values())[0]
# doubleGenomeSeq = list(dicoFNA.values())[0]+list(dicoFNA.values())[0]
# # Construct locusTag key pVOGS dict
# dicoPVOGS_LT = {}
# for pvog in dicoPVOGS[orgName]:
# for lt in dicoPVOGS[orgName][pvog].keys():
# if lt not in dicoPVOGS_LT:
# dicoPVOGS_LT[lt] = []
# dicoPVOGS_LT[lt].append(pvog)
# # Construct locusTag key recombinase dict
# dicoREC_LT = {}
# for rec in dicoREC[orgName]:
# for lt in dicoREC[orgName][rec].keys():
# if lt not in dicoREC_LT:
# dicoREC_LT[lt] = ""
# dicoREC_LT[lt] += rec+","
# for lt in dicoREC_LT:
# if dicoREC_LT[lt] != "":
# dicoREC_LT[lt] = dicoREC_LT[lt][: -1]
# # GFF3 header
# GFF.write("##gff-version\t3.1.26\n")
# GFF.write("##sequence-region\t"+orgName+"\t"+str(len(genomeSeq))+"\n")
# GFF.write("##species\tVibrio phage\n")
# # Add genes
# dicoFFN = make_fasta_dict(pathOUT+"/"+orgName+".ffn")
# cptGene = 0
# for header in dicoFFN:
# lt = header.split("|")[0]
# frame = header.split("|")[1]
# if frame == "1":
# seqNucl = str(Seq(dicoFFN[header]))
# strand = "+"
# else:
# seqNucl = reverse_complement(str(Seq(dicoFFN[header])))
# strand = "-"
# start = len(doubleGenomeSeq.split(seqNucl)[0])
# end = start+len(seqNucl)
# # Write gene line
# GFF.write(orgName+"\tgemini\tgene\t"+str(start)+"\t"+str(end)+"\t.\t"+strand+"\t0\tID = gene"+str(cptGene)+";locus_tag = "+lt+"\n")
# # Write tRNA and CDS line
# if header in dicoTRNA[orgName] and dicoTRNA[orgName][header]['pseudo'] is False:
# GFF.write(orgName+"\tgemini\ttRNA\t"+str(start)+"\t"+str(end)+"\t.\t"+strand+"\t0\tID = rna"+str(cptGene)+";Parent = gene"+str(cptGene)+";locus_tag = "+lt+";product = tRNA-"+dicoTRNA[orgName][header]['type']+"\n")
# else:
# pvogsRef = pvogsDescr = recombRes = nahantRes = iprscanRes = eggnogRes = ""
# GFFcdsLine = orgName+"\tgemini\tCDS\t"+str(start)+"\t"+str(end)+"\t.\t"+strand+"\t0\tID = rna"+str(cptGene)+";Parent = gene"+str(cptGene)+";locus_tag = "+lt
# # pVOGS
# if lt in dicoPVOGS_LT:
# for pvogsID in dicoPVOGS_LT[lt]:
# pvogsRef += pvogsID+","
# pvogsDescr += ",".join(dicoPVOGSdescr[pvogsID])+","
# pvogsRef = pvogsRef[: -1]
# pvogsDescr = pvogsDescr[: -1]
# # recombinase
# if lt in dicoREC_LT:
# recombRes = dicoREC_LT[lt]
# # Nahant
# if lt in dicoNAHANT[orgName]:
# for key in dicoNAHANT[orgName][lt]:
# if key != "length":
# nahantRes += key.replace(",", " ").replace(";", " ")+","
# nahantRes = nahantRes[: -1]
# # InterProScan
# if lt in dicoIPRSCAN["interproscan"]:
# for key in dicoIPRSCAN["interproscan"][lt].keys():
# iprscanRes += key+":"+dicoIPRSCAN["interproscan"][lt][key]['descr']+","
# iprscanRes = iprscanRes[: -1]
# # EggNOG
# if lt in dicoEGGNOG['eggnog'] and dicoEGGNOG['eggnog'][lt]['descr'] != "-":
# eggnogRes = dicoEGGNOG['eggnog'][lt]['descr']
# if dicoEGGNOG['eggnog'][lt]['prefName'] != "-":
# eggnogRes += "("+dicoEGGNOG['eggnog'][lt]['prefName']+")"
# # Write line
# GFFcdsLine += ";pvogsRef = "+pvogsRef+";pvogsDescr = "+pvogsDescr+";recomb = "+recombRes+";nahant = "+nahantRes+";iprscan = "+iprscanRes+";eggnog = "+eggnogRes+"\n"
# GFF.write(GFFcdsLine.replace(" ", " "))
# cptGene += 1
# GFF.close()
# pbar.update(1)
# title("Create GFF3", pbar)
# pbar.close()
# # ***** CREATE TABLE from GFF ***** #
# gff_to_table(pathIN=pathOUT, pathOUT=pathOUT, format=".xlsx", maxWidth=50, ext=".gff")
@fct_checker
def phageDB(pathIN: str, pathOUT: str, checkvHQ: float = 75.0) -> Tuple[str, str, float]:
'''
------------------------------------------------------------
| GENBANK PHAGE DATABASE |
|------------------------------------------------------------|
| Make GenBank phages database |
|------------------------------------------------------------|
|PARAMETERS |
| pathIN : path of input GV assembly folder (required) |
| pathOUT : path of output files (required) |
| checkv : checkV High/MediumQuality % (default=75) |
------------------------------------------------------------
|TOOLS: seqret, python, hmmscan |
------------------------------------------------------------
'''
pathIN = path_converter(pathIN)
pathOUT = path_converter(pathOUT)
if not os.path.isdir(pathIN):
printcolor("[ERROR: phageDB]\nAny input GV assembly folder found\n", 1, "212;64;89", "None", True)
exit_gemini()
# Create folder tree
os.makedirs(pathOUT, exist_ok=True)
os.makedirs(pathOUT+"/FNA", exist_ok=True)
os.makedirs(pathOUT+"/FNA_filtered", exist_ok=True)
os.makedirs(pathOUT+"/GBK", exist_ok=True)
os.makedirs(pathOUT+"/FFN", exist_ok=True)
os.makedirs(pathOUT+"/FAA", exist_ok=True)
os.makedirs(pathOUT+"/CHECKV", exist_ok=True)
os.makedirs(pathOUT+"/ANNOT", exist_ok=True)
# Paths
pathDBJSON = pathOUT+"/phageDB.json"
pathLOG = pathOUT+"/log.out"
pathGenomeReportVirusesTXT = pathOUT+"/genbank_genome_reports_viruses.txt"
pathGenomeReportVirusesETAG = pathOUT+"/genbank_genome_reports_viruses.etag"
pathGBKsummaryTXT = pathOUT+"/assembly_summary_genbank.txt"
pathGBKsummaryETAG = pathOUT+"/assembly_summary_genbank.etag"
pathENAsummaryTSV = pathOUT+"/assembly_summary_ena.tsv"
pathCONCATFNA = pathOUT+"/all_filtered_phages.fna"
pathCONCATFAA = pathOUT+"/all_filtered_phages.faa"
pathMAPPINGPROT = pathOUT+"/all_filtered_phages_mapping.csv"
pathExcludedGCA = pathOUT+"/excluded_gca.txt"
pathTMP = geminiset.pathTMP
# URLs
urlGBKreportVirus = "https: //ftp.ncbi.nlm.nih.gov/genomes/GENOME_REPORTS/viruses.txt"
urlGBKFTP = "ftp.ncbi.nlm.nih.gov"
urlGBKFTPreport = "genomes/GENOME_REPORTS/viruses.txt"
urlGBKFTPsummary = "genomes/ASSEMBLY_REPORTS/assembly_summary_genbank.txt"
urlGBKHTTPsummary = "https: //ftp.ncbi.nlm.nih.gov/genomes/ASSEMBLY_REPORTS/assembly_summary_genbank.txt"
# Gemini variables
dicoGeminiPath, dicoGeminiModule = get_gemini_path()
if 'seqret' in dicoGeminiModule:
os.system("module load "+dicoGeminiModule['seqret'])
if 'python' in dicoGeminiModule:
os.system("module load "+dicoGeminiModule['python'])
if 'hmmscan' in dicoGeminiModule:
os.system("module load "+dicoGeminiModule['hmmscan'])
slurmBool, cpu, memMax, memMin = get_sys_info()
lstBadKr = ["#", "'", "(", ")", ",", "/", ": ", " "]
# Summary JSON
if not os.path.isfile(pathDBJSON) or os.path.getsize(pathDBJSON) == 0:
dicoDB = {}
else:
dicoDB = load_json(pathDBJSON)
# Excluded GCA
lstExcludedGCA = []
if os.path.isfile(pathExcludedGCA):
IN = open(pathExcludedGCA, 'r')
lstLines = IN.read().split("\n")
IN.close()
for line in lstLines:
if line != "":
lstExcludedGCA.append(line)
# ***** RETRIEVE ALL VIRUS WITH BACTERIA HOST ***** #
# Get current local/distant etag (or None if empty)
previousEtag = get_etag(pathGenomeReportVirusesETAG, None)
newEtag = get_etag(None, urlGBKreportVirus)
# Download if new distant etag
if previousEtag == newEtag:
printcolor("♊ Genbank genome reports [up-to-date ]"+"\n")
else:
printcolor("♊ Genbank genome reports [downloading]"+"\n")
# Get filesize for progress bar
filesize = get_ftp_file_size(urlGBKFTP, urlGBKFTPreport)
# Download file
get_distant_file_tqdm(urlGBKreportVirus, pathGenomeReportVirusesTXT, filesize, 1024)
# Write new etag
ETAG = open(pathGenomeReportVirusesETAG, 'w')
ETAG.write(newEtag)
ETAG.close()
# Retrieve species list (containing phage or virus)
REPORT = open(pathGenomeReportVirusesTXT, 'r')
lstLines = REPORT.read().split("\n")[1: -1]
REPORT.close()
setReportPhageSpecie = set()
for line in lstLines:
splitLine = line.split("\t")
orgName = splitLine[0]
host = splitLine[8]
if host == "bacteria":
if "phage" in orgName:
specie = orgName.split("phage")[0]+"phage"
elif "virus" in orgName:
specie = orgName.split("virus")[0]+"virus"
elif "Phage" in orgName:
specie = orgName.split("Phage")[0]+"Phage"
elif "Virus" in orgName:
specie = orgName.split("Pirus")[0]+"Virus"
else:
specie = orgName
setReportPhageSpecie.add(specie)
# ***** GENBANK ASSEMBLY SUMMARY ***** #
# Get current local/distant etag (or None if empty)
previousEtag = get_etag(pathGBKsummaryETAG, None)
newEtag = get_etag(None, urlGBKHTTPsummary)
gbkUpdate = False
# Download if new distant etag
if previousEtag == newEtag:
printcolor("♊ Genbank assembly summary [up-to-date ]"+"\n")
else:
printcolor("♊ Genbank assembly summary [downloading]"+"\n")
# Get filesize for progress bar
filesize = get_ftp_file_size(urlGBKFTP, urlGBKFTPsummary)
# Download file
get_distant_file_tqdm(urlGBKHTTPsummary, pathTMP+"/assembly_summary_genbank.txt", filesize, 1024)
# Write new etag
ETAG = open(pathGBKsummaryETAG, 'w')
ETAG.write(newEtag)
ETAG.close()
gbkUpdate = True
# Filtering Genbank assembly
printcolor("♊ Filter Genbank"+"\n")
if gbkUpdate is True and not os.path.isfile(pathGBKsummaryTXT):
TMPSUMMARY = open(pathTMP+"/assembly_summary_genbank.txt", 'r')
lstLines = TMPSUMMARY.read().split("\n")
TMPSUMMARY.close()
SUMMARY = open(pathGBKsummaryTXT, 'w')
pbar = tqdm(total=len(lstLines), dynamic_ncols=True, ncols=50, leave=False, desc="", file=sys.stdout, bar_format=" Filtering {percentage: 3.0f}%|{bar}|")
# Init NCBITaxa
ncbi = NCBITaxa()
for line in lstLines:
if line == "" or line[0] == "#":
SUMMARY.write(line+"\n")
else:
isPhage = False
splitLine = line.split("\t")
taxID = int(splitLine[5])
specieID = int(splitLine[6])
# Search by organism name
if "phage" in line.lower():
try:
lineage = ncbi.get_lineage(taxID)
except ValueError:
try:
lineage = ncbi.get_lineage(specieID)
except ValueError:
if " phage " in line:
lineage = [10239]
if 10239 in lineage:
isPhage = True
# Search using genome reports
else:
for specie in setReportPhageSpecie:
if specie.lower() in line.lower():
isPhage = True
break
if isPhage is True:
SUMMARY.write(line+"\n")
pbar.update(1)
title("Filter Genbank", pbar)
pbar.close()
SUMMARY.close()
# Parse Genbank assembly
printcolor("♊ Genbank summary"+"\n")
# if gbkUpdate is True or not os.path.isfile(pathDBJSON):
SUMMARY = open(pathGBKsummaryTXT, 'r')
lstLines = SUMMARY.read().split("\n")
SUMMARY.close()
pbar = tqdm(total=len(lstLines), dynamic_ncols=True, ncols=50, leave=False, desc="", file=sys.stdout, bar_format=" Parsing {percentage: 3.0f}%|{bar}|")
for line in lstLines:
if line != "" and line[0] != "#":
splitLine = line.split("\t")
gca = splitLine[0].split(".")[0]
version = int(splitLine[0].split(".")[1])
if not gca+"."+str(version) in lstExcludedGCA:
# Format orgName
orgName = splitLine[7]
infName = splitLine[8].replace("strain = ", "")
isoName = splitLine[9]
for badKr in lstBadKr:
orgName = orgName.replace(badKr, "_")
# Add to dico
if orgName not in dicoDB:
dicoDB[orgName] = {}
if gca not in dicoDB[orgName]:
dicoDB[orgName][gca] = {}
if 'genbank' not in dicoDB[orgName][gca] or dicoDB[orgName][gca]['genbank']['version'] < version:
dicoDB[orgName][gca]['genbank'] = {'infName': infName, 'isoName': isoName, 'url': splitLine[19], 'version': version}
pbar.update(1)
title("Genbank summary", pbar)
pbar.close()
# ***** ENA ASSEMBLY SUMMARY ***** #
printcolor("♊ ENA summary"+"\n")
# Download
spinner = yaspin(Spinners.aesthetic, text="♊ ENA assembly summary ", side="right")
spinner.start()
title("ENA", None)
if not os.path.isfile(pathENAsummaryTSV) or os.path.getsize(pathENAsummaryTSV) == 0:
cmdENA = "curl -s -X POST -H \"Content-Type: application/x-www-form-urlencoded\" -d 'result = assembly&query = tax_tree(10239)&fields = accession%2Cversion%2Cscientific_name%2Cstrain%2Cstudy_name%2Ctax_id&format = tsv' \"https: //www.ebi.ac.uk/ena/portal/api/search\" | grep \"phage\" > "+pathENAsummaryTSV
os.system(cmdENA)
spinner.stop()
printcolor("♊ ENA assembly summary [downloading]"+"\n")
else:
# Compare File
cmdENA = "curl -s -X POST -H \"Content-Type: application/x-www-form-urlencoded\" -d 'result = assembly&query = tax_tree(10239)&fields = accession%2Cversion%2Cscientific_name%2Cstrain%2Cstudy_name%2Ctax_id&format = tsv' \"https: //www.ebi.ac.uk/ena/portal/api/search\" | grep \"phage\" > "+pathTMP+"/assembly_summary_ena.tsv"
os.system(cmdENA)
sameFile = filecmp.cmp(pathENAsummaryTSV, pathTMP+"/assembly_summary_ena.tsv", shallow=False)
spinner.stop()
if sameFile is True:
printcolor("♊ ENA assembly summary [up-to-date ]"+"\n")
else:
printcolor("♊ ENA assembly summary [downloading]"+"\n")
shutil.copyfile(pathTMP+"/assembly_summary_ena.tsv", pathENAsummaryTSV)
# Parse
ENA = open(pathOUT+"/assembly_summary_ena.tsv", 'r')
lstLines = ENA.read().split("\n")[: -1]
ENA.close()
# Parse
pbar = tqdm(total=len(lstLines), dynamic_ncols=True, ncols=50, leave=False, desc="", file=sys.stdout, bar_format=" Parsing {percentage: 3.0f}%|{bar}|")
for line in lstLines:
splitLine = line.split("\t")
gca = splitLine[0]
version = int(splitLine[1])
if not gca+"."+str(version) in lstExcludedGCA:
orgName = splitLine[2]
for badKr in lstBadKr:
orgName = orgName.replace(badKr, "_")
infName = splitLine[3]
isoName = splitLine[4]
taxID = int(splitLine[5])
url = "https: //www.ebi.ac.uk/ena/browser/api/fasta/"+gca+"."+str(version)+"?download = true&gzip = true"
if orgName not in dicoDB:
dicoDB[orgName] = {}
if gca not in dicoDB[orgName]:
dicoDB[orgName][gca] = {}
if 'ena' not in dicoDB[orgName][gca] or dicoDB[orgName][gca]['ena']['version'] < version:
dicoDB[orgName][gca]['ena'] = {'infName': infName, 'isoName': isoName, 'url': url, 'version': version}
pbar.update(1)
title("ENA summary", pbar)
pbar.close()
# ***** GV ASSEMBLIES ***** #
printcolor("♊ GV team genomes"+"\n")
for gvFNA in os.listdir(pathIN):
orgName = os.path.basename(gvFNA).replace(".fna", "").replace("-", ".")
if orgName not in dicoDB:
dicoDB[orgName] = {}
dicoDB[orgName]['gv'] = {'infName': "", 'isoName': "", 'url': pathIN+"/"+gvFNA, 'version': None}
pathFNA = pathOUT+"/FNA/"+orgName+".fna"
if not os.path.isfile(pathFNA) or os.path.getsize(pathFNA) == 0:
shutil.copyfile(pathIN+"/"+gvFNA, pathFNA)
# ***** CHOOSE SOURCE per organism (for not GV genomes)***** #
maxOrgNameSize = 0
for orgName in dicoDB:
maxOrgNameSize = max(maxOrgNameSize, len(orgName))
if "gv" not in dicoDB[orgName]:
for gca in dicoDB[orgName]:
if "genbank" not in dicoDB[orgName][gca]:
choice = "ena"
elif "ena" not in dicoDB[orgName][gca]:
choice = "genbank"
elif dicoDB[orgName][gca]["ena"]['version'] > dicoDB[orgName][gca]["genbank"]['version']:
choice = "ena"
else:
choice = "genbank"
# New genomes
if "source_choice" not in dicoDB[orgName][gca]:
dicoDB[orgName][gca]["source_choice"] = choice
# Update genomes
if dicoDB[orgName][gca]["source_choice"] != choice:
dicoDB[orgName][gca]["source_choice"] = choice
# delete FNA, FAA and FFN
os.system("rm -f "+pathOUT+"/F*/"+orgName+"_"+gca+".*.f*")
# Download FNA files
nbGCA = 0
for org in dicoDB:
nbGCA += len(dicoDB[org])
printcolor("♊ Retrieve FNA files"+"\n")
pbar = tqdm(total=nbGCA, dynamic_ncols=True, ncols=50+maxOrgNameSize, leave=False, desc="", file=sys.stdout, bar_format=" {percentage: 3.0f}%|{bar}| {n_fmt}/{total_fmt} [{desc}]")
cptNewFNA = 0
cptNewGBK = 0
lstFailedFNA = []
lstFailedGBK = []
for orgName in dicoDB:
if "gv" not in dicoDB[orgName]:
for gca in dicoDB[orgName]:
srcChoice = dicoDB[orgName][gca]["source_choice"]
pbar.set_description_str(orgName+" ".rjust(maxOrgNameSize-len(orgName)))
gcaVersion = dicoDB[orgName][gca][srcChoice]['version']
# check and remove previous version
if gcaVersion != 1:
for i in range(1, gcaVersion, 1):
pathFNAold = pathOUT+"/FNA/"+orgName+"_"+gca+"."+str(i)+".fna"
if os.path.isfile(pathFNAold):
os.remove(pathFNAold)
# Download FNA if required
pathFNA = pathOUT+"/FNA/"+orgName+"_"+gca+"."+str(gcaVersion)+".fna"
if not os.path.isfile(pathFNA) or os.path.getsize(pathFNA) == 0:
if srcChoice == "genbank":
pathTMPgzfna = pathTMP+"/"+orgName+"_"+gca+"."+str(gcaVersion)+".fna.gz"
cmdWGET = "wget -O - -q "+dicoDB[orgName][gca][srcChoice]['url']+"/"+os.path.basename(dicoDB[orgName][gca][srcChoice]['url'])+"_genomic.fna.gz > "+pathTMPgzfna
os.system(cmdWGET)
if os.path.isfile(pathTMPgzfna) and os.path.getsize(pathTMPgzfna) != 0:
os.system("gzip -c -d "+pathTMPgzfna+" > "+pathFNA)
else:
cmdWGET = "wget -O "+pathFNA+" -q "+dicoDB[orgName][gca][srcChoice]['url']
os.system(cmdWGET)
# Unwrap
if not os.path.isfile(pathFNA) or os.path.getsize(pathFNA) == 0:
lstFailedFNA.append(os.path.basename(pathFNA))
else:
unwrap_fasta(pathIN=pathFNA, ext=".fna")
cptNewFNA += 1
# Download GBFF if required
pathGBK = pathOUT+"/GBK/"+orgName+"_"+gca+"."+str(gcaVersion)+".gbk.gz"
if not os.path.isfile(pathGBK) or os.path.getsize(pathGBK) == 0:
if srcChoice == "genbank":
cmdWGET = "wget -O "+pathGBK+" -q "+dicoDB[orgName][gca][srcChoice]['url']+"/"+os.path.basename(dicoDB[orgName][gca][srcChoice]['url'])+"_genomic.gbff.gz"
os.system(cmdWGET)
else:
cmdWGET = "wget -O "+pathTMP+"/"+gca+"."+str(gcaVersion)+".embl -q "+dicoDB[orgName][gca][srcChoice]['url'].replace("/fasta/", "/embl/").replace("?download = true&gzip = true", "")
os.system(cmdWGET)
# Convert embl to gbk
cmdSEQRET = dicoGeminiPath['TOOLS']['seqret']+" -sequence "+pathTMP+"/"+gca+"."+str(gcaVersion)+".embl -sformat1 embl -outseq "+pathGBK.replace(".gz", "")+" -osformat2 genbank >> "+pathLOG+" 2>&1"
os.system(cmdSEQRET)
# Compress gbk
if os.path.isfile(pathGBK.replace(".gz", "")) and os.path.getsize(pathGBK.replace(".gz", "")):
os.system("gzip "+pathGBK.replace(".gz", ""))
if not os.path.isfile(pathGBK) or os.path.getsize(pathGBK) == 0:
lstFailedGBK.append(os.path.basename(pathGBK))
else:
cptNewGBK += 1
pbar.update(1)
title("Retrieve FNA", pbar)
pbar.close()
# ***** FILTER LOW QUALITY GENOME ***** #
printcolor("♊ Filter low quality genome"+"\n")
lstFNA = os.listdir(pathOUT+"/FNA")
lstFiltered = []
pbar = tqdm(total=len(lstFNA), dynamic_ncols=True, ncols=75, leave=False, desc="", file=sys.stdout, bar_format=" {percentage: 3.0f}%|{bar}| {n_fmt}/{total_fmt} [{desc}]")
for fna in lstFNA:
if fna not in lstFailedFNA:
if "GCA" in fna:
orgName = fna.split("_GCA")[0]
gcaAccession = "GCA_"+fna.replace(".fna", "").split("_")[-1].split(".")[0]
pbar.set_description_str("GCA_"+fna.replace(".fna", "").split("_")[-1])
else:
orgName = fna.replace(".fna", "")
gcaAccession = "gv"
pbar.set_description_str(fna.replace(".fna", "")[-15:])
pathFNA = pathOUT+"/FNA/"+fna
pathCHECKVOUT = pathOUT+"/CHECKV/"+fna.replace(".fna", "")
# Launch if required
if not os.path.isfile(pathCHECKVOUT+"/quality_summary.tsv") or os.path.getsize(pathCHECKVOUT+"/quality_summary.tsv") == 0:
os.system("echo \""+dicoGeminiPath['TOOLS']['python']+" "+dicoGeminiPath['TOOLS']['checkv']+" end_to_end "+pathFNA+" "+pathCHECKVOUT+" -t "+str(cpu)+" -d "+dicoGeminiPath['DATABASES']['checkv_db']+"\" >> "+pathLOG)
cmdCHECKV = dicoGeminiPath['TOOLS']['python']+" "+dicoGeminiPath['TOOLS']['checkv']+" end_to_end "+pathFNA+" "+pathCHECKVOUT+" -t "+str(cpu)+" -d "+dicoGeminiPath['DATABASES']['checkv_db']+" >> "+pathLOG+" 2>&1"
os.system(cmdCHECKV)
# Delete tmp folder
shutil.rmtree(pathCHECKVOUT+"/tmp")
# Parse quality_summary file
if "check" not in dicoDB[orgName][gcaAccession]:
TSV = open(pathCHECKVOUT+"/quality_summary.tsv", 'r')
lstLines = TSV.read().split("\n")[1:-1]
TSV.close()
# % of high-quality contig
dicoCountQuality = {}
for line in lstLines:
splitLine = line.split("\t")
checkv_quality = splitLine[7] # Complete/High-quality/Medium-quality/Low-quality/Not-determined
try:
dicoCountQuality[checkv_quality] += 1
except KeyError:
dicoCountQuality[checkv_quality] = 1
# Add to dicoDB
dicoDB[orgName][gcaAccession]['check'] = {}
for quality in dicoCountQuality:
dicoDB[orgName][gcaAccession]['check'][quality] = (dicoCountQuality[quality]*100)/len(lstLines)
# Filtering
percentQuality = 0
if "Complete" in dicoDB[orgName][gcaAccession]['check']:
percentQuality += dicoDB[orgName][gcaAccession]['check']['Complete']
if "High-quality" in dicoDB[orgName][gcaAccession]['check']:
percentQuality += dicoDB[orgName][gcaAccession]['check']['High-quality']
if "Medium-quality" in dicoDB[orgName][gcaAccession]['check']:
percentQuality += dicoDB[orgName][gcaAccession]['check']['Medium-quality']
if percentQuality < 75.0:
lstFiltered.append(gcaAccession)
elif not os.path.isfile(pathOUT+"/FNA_filtered/"+fna):
shutil.copyfile(pathFNA, pathOUT+"/FNA_filtered/"+fna)
pbar.update(1)
title("Filter lowqual", pbar)
pbar.close()
# Dump summary JSON
dump_json(dicoDB, pathDBJSON)
# ***** STATISTICS ***** #
printcolor("♊ phageDB statistics"+"\n")
printcolor("⏩ Found "+str(len(os.listdir(pathOUT+"/FNA")))+" FNA"+"\n")
printcolor("⏩ Found "+str(len(os.listdir(pathOUT+"/FNA_filtered")))+" FNA filtered"+"\n")
printcolor("⏩ Found "+str(len(os.listdir(pathOUT+"/GBK")))+" GBK"+"\n")
if cptNewFNA == 0:
printcolor("⏩ Any new FNA downloaded"+"\n")
else:
printcolor("⏩ "+str(cptNewFNA)+" new FNA downloaded"+"\n")
if cptNewGBK == 0:
printcolor("⏩ Any new GBK downloaded"+"\n")
else:
printcolor("⏩ "+str(cptNewGBK)+" new GBK downloaded"+"\n")
if len(lstFiltered) > 0:
printcolor("⛔ "+str(len(lstFiltered))+" checkV excluded genomes"+"\n")
if len(lstFailedFNA) > 0:
printcolor("⛔ "+str(len(lstFailedFNA))+" failed FNA download ("+", ".join(lstFailedFNA)+")"+"\n")
if len(lstFailedGBK) > 0:
printcolor("⛔ "+str(len(lstFailedGBK))+" failed GBK download ("+", ".join(lstFailedGBK)+")"+"\n")
# ***** CONCATENATE ALL FNA (only filtered) ***** #
printcolor("♊ Concatenate filtered FNA"+"\n")
if cptNewFNA != 0 or not os.path.isfile(pathCONCATFNA) or os.path.getsize(pathCONCATFNA) == 0:
lstFNA = os.listdir(pathOUT+"/FNA_filtered")
pbar = tqdm(total=len(lstFNA), dynamic_ncols=True, ncols=75, leave=False, desc="", file=sys.stdout, bar_format=" {percentage: 3.0f}%|{bar}| {n_fmt}/{total_fmt} [{desc}]")
CONCAT = open(pathCONCATFNA, 'w')
for fna in lstFNA:
if "GCA" in fna:
pbar.set_description_str("GCA_"+fna.replace(".fna", "").split("_")[-1])
else:
pbar.set_description_str(fna.replace(".fna", "")[-15:])
dicoFNA = make_fasta_dict(pathOUT+"/FNA_filtered/"+fna)
seq = ""
for key in dicoFNA:
seq += dicoFNA[key]+"N"*100
CONCAT.write(">"+fna.replace(".fna", "")+"\n"+seq[:-100]+"\n")
pbar.update(1)
title("Cat FNA", pbar)
pbar.close()
CONCAT.close()
# ***** SYNTAXIC Annotation & TRANSLATION ***** #
phanotate(pathIN=pathOUT+"/FNA_filtered", pathOUT=pathOUT+"/FFN", fromPhageDb=True, ext=".fna")
transeq(pathIN=pathOUT+"/FFN", pathOUT=pathOUT+"/FAA", fromPhageDb=True, ext=".ffn")
# ***** CONCATENATE ALL FAA ***** #
printcolor("♊ Concatenate all FAA"+"\n")
if cptNewFNA != 0 or not os.path.isfile(pathCONCATFAA) or os.path.getsize(pathCONCATFAA) == 0 or not os.path.isfile(pathMAPPINGPROT) or os.path.getsize(pathMAPPINGPROT) == 0:
lstFAA = os.listdir(pathOUT+"/FAA")
pbar = tqdm(total=len(lstFAA), dynamic_ncols=True, ncols=75, leave=False, desc="", file=sys.stdout, bar_format=" {percentage: 3.0f}%|{bar}| {n_fmt}/{total_fmt} [{desc}]")
CONCAT = open(pathCONCATFAA, 'w')
MAPPING = open(pathMAPPINGPROT, 'w')
MAPPING.write("protein_id, contig_id, keywords\n")
for faa in lstFAA:
if "GCA" in faa:
pbar.set_description_str("GCA_"+faa.replace(".faa", "").split("_")[-1])
else:
pbar.set_description_str(faa.replace(".faa", "")[-15:])
pbar.set_description_str("GCA_"+faa.replace(".faa", "").split("_")[-1])
dicoFAA = make_fasta_dict(pathOUT+"/FAA/"+faa)
pathFFN = pathOUT+"/FFN/"+faa.replace(".faa", ".ffn")
if os.path.isfile(pathFFN):
for key in dicoFAA:
CONCAT.write(">"+key+"\n"+dicoFAA[key]+"\n")
MAPPING.write(key.split(" [")[0]+", "+key.split(" [")[1].replace("]", "")+", "+key.split("|")[0]+"\n")
pbar.update(1)
title("Cat FAA", pbar)
pbar.close()
CONCAT.close()
MAPPING.close()
# ***** SEARCH LARGE TERMINASE SUBUNIT ***** #
spinner = yaspin(Spinners.aesthetic, text="♊ Search large terminase", side="right")
spinner.start()
title("Terminase", None)
lstFAA = os.listdir(pathOUT+"/FAA")
dicoThread = {}
for faa in lstFAA:
pathTBLOUT = pathOUT+"/ANNOT/"+faa.replace(".faa", ".tblout")
if not os.path.isfile(pathTBLOUT) or os.path.getsize(pathTBLOUT) == 0:
cmdHmmscan = dicoGeminiPath['TOOLS']['hmmscan']+" --tblout "+pathTBLOUT+" "+dicoGeminiPath['DATABASES']['terminase_hmm']+" "+pathOUT+"/FAA/"+faa
dicoThread[faa.replace(".faa", "")] = {"cmd": cmdHmmscan, "returnstatut": None, "returnlines": []}
if len(dicoThread) > 0:
launch_threads(dicoThread, "hmmscan_terminase", cpu, pathTMP)
spinner.stop()
printcolor("♊ Search large terminase"+"\n")
@fct_checker
def phageDBsearch(pathIN: str, pathOUT: str, idThr: int = 20, covThr: int = 50, dmndDB: str = "genbank") -> Tuple[str, str, int, int, str]:
'''
------------------------------------------------------------
| SEARCH IN PHAGE DATABASE |
|------------------------------------------------------------|
| Search in genbank source or phanotate phage database |
|------------------------------------------------------------|
|PARAMETERS |
| pathIN : path of query protein file (required) |
| pathOUT : path of search output dir (required) |
| idThr : %identity threshold (default=20) |
| covThr : %coverage threshold (default=50) |
| dmndDB : database genbank|phanotate (default=phanotate)|
------------------------------------------------------------
'''
pathIN = path_converter(pathIN)
pathOUT = path_converter(pathOUT)
if not os.path.isfile(pathIN):
printcolor("[ERROR: phageDBsearch]\nAny input FAA file\n", 1, "212;64;89", "None", True)
exit_gemini()
dicoGeminiPath, dicoGeminiModule = get_gemini_path()
if dmndDB == "genbank":
pathDB = dicoGeminiPath['DATABASES']['phagedb_dmnd']
elif dmndDB == "phanotate":
pathDB = dicoGeminiPath['DATABASES']['phagedb_dmnd_phanotate']
else:
printcolor("[ERROR: phageDBsearch]\nInvalid dmnd database, must be \"genbank\" or \"phanotate\"\n", 1, "212;64;89", "None", True)
exit_gemini()
pathTMP = geminiset.pathTMP
diamond_p(pathIN=pathIN, pathDB=pathDB, pathOUT=pathTMP+"/diamond.out", boolSeq=True, ext="")
lstLines = read_file(pathTMP+"/diamond.out", excludeFirstKr=None, yaspinBool=False)
if len(lstLines) <= 3:
printcolor("⛔ Any protein found"+"\n")
else:
printcolor("⏩ Found "+str(len(lstLines)-3)+" protein(s)"+"\n")
os.makedirs(pathOUT, exist_ok=True)
shutil.move(pathTMP+"/diamond.out", pathOUT+"/diamond.out")
dicoPerQuery = {}
splitHeader = lstLines[2].replace("# Fields: ", "").split(", ")
dicoHeader = {}
for i in range(len(splitHeader)):
dicoHeader[splitHeader[i]] = i
for line in lstLines[3:]:
splitLine = line.split("\t")
query = splitLine[dicoHeader["Query ID"]]
subject = splitLine[dicoHeader["Subject title"]]
pident = float(splitLine[dicoHeader["Percentage of identical matches"]])
# alen = int(splitLine[dicoHeader["Alignment length"]])
qlen = int(splitLine[dicoHeader["Query length"]])
qstart = int(splitLine[dicoHeader["Start of alignment in query"]])