forked from qLSLab/ExTaxsI
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathExTaxsI.py
3449 lines (2722 loc) · 143 KB
/
ExTaxsI.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
# -*- coding: utf-8 -*-
#
# ExTaxsI.py
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
import time
import datetime
import os
import sys
import re
import http.client as http
import io
# To parse and use setting file
from configparser import ConfigParser
# For log files
import logging
# Needed to elaborate csv files
import numpy as np
import csv
import glob
import pandas as pd
# This module implements container datatypes providing alternatives to
# Python’s general purpose built-in containers as counter
import collections
from collections import OrderedDict
from collections import Counter
# Biopython
from Bio import Entrez
from Bio.Entrez import Parser as ps
# from Bio import SeqIO
# import 1plotly.plotly as py
import plotly.graph_objects as go
from plotly.offline import plot
# Needed to search through xml files
import xml.etree.cElementTree as ET
#
from urllib.error import HTTPError
# To create a local taxonomy library to parse downloaded accessions
from ete3 import NCBITaxa
import sqlite3
# To check which OS we are using
import platform
# To give tab functionality while searching for files in bash (Not working in windows)
if platform.system() != "Windows":
import readline
# Initialize log_folder variable
try:
# In case the log folder in the tool folder doesn't exist
if not os.path.exists("./Log/"):
# It will try to create it
os.makedirs("./Log/")
# In case everything goes well, log file will be created in the log folder
# The name of the file will be the date and the time at which the tool has started
log_folder = './{0}/{1}.{2}'.format("Log", str(datetime.datetime.now().strftime("%d-%m-%y_at_%H-%M")), "log")
except OSError:
# In case of denied permissions or other cases where we can't create the log folder, the file will be in the same
# folder of the tool
# The name of the file will be the date and the time at which the tool has started
log_folder = '{0}.{1}'.format(str(datetime.datetime.now().strftime("%d-%m-%y_at_%H-%M")), "log")
# Creating the log file
logging.basicConfig(filename=log_folder, format='%(asctime)s %(levelname)s -> %(message)s', level=logging.DEBUG)
# DA CAMBIARE PRIMA DELLA PUBBLICAZIONE (DEBUG -> WARNING) !!!!!!!!!!!!!!!!!
class color:
# Colors
RED = '\033[91m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
BLUE = '\033[94m'
PURPLE = '\033[95m'
CYAN = '\033[96m'
# Text format
BOLD = '\033[1m'
ITALIC = '\33[3m'
UNDERLINE = '\033[4m'
BLINK = '\33[5m'
# Background colors
BLACKBG = '\33[40m'
REDBG = '\33[41m'
GREENBG = '\33[42m'
YELLOWBG = '\33[43m'
BLUEBG = '\33[44m'
VIOLETBG = '\33[45m'
BEIGEBG = '\33[46m'
WHITEBG = '\33[47m'
# End of format\colors
END = '\033[0m'
'''
[ACCN] Accession
[ALL] All Fields
[AUTH] Author
[GPRJ] BioProject
[ECNO] EC/RN Number
[FKEY] Feature key
[FILT] Filter
[GENE] Gene Name
[JOUR] Journal
[KYWD] Keyword
[MLWT] Molecular Weight
[ORGN] Organism
[PACC] Primary Accession
[PROP] Properties
[PROT] Protein Name
[SQID] SeqID String
[SLEN] Sequence Length
[SUBS] Substance Name
[WORD] Text Word
[TITL] Title
[UID] UID
'''
# Function for bar progress animation
def update_progress(work_needed, work_done):
# scritto da adam non funziona:
#if not is_integer(work_done) or work_done <= 0:
# return
bar_len = 40 # Modify this to change the length of the progress bar
status = "" # Initializing the string that will give us the status of the progression
progress = work_needed / work_done
if isinstance(progress, int):
progress = float(progress)
if not isinstance(progress, float):
progress = 0
status = "error: progress var must be float\r\n"
if progress < 0: # progress can't be negative
progress = 0
status = "Halt...\r\n"
if progress >= 1:
progress = 1
status = "Done...\r\n"
block = int(round(bar_len * progress)) # % value of the progress
text = '\r{6}Loading:{7} {5}[{0}]{7} {1}% || {2}/{3} {6}{4}{7}'.format('█' * block + '~' * (bar_len - block),
round(progress * 100, 1), work_needed,
work_done, status, color.GREEN, color.BOLD,
color.END)
sys.stdout.write(text)
sys.stdout.flush()
def clear():
if platform.system() == "Windows":
os.system('cls')
else:
os.system('tput reset')
# Creates the path where the files will be downloaded
def create_folder(folder_path):
logging.info(' Searching or creating the download path')
try:
if not os.path.exists(folder_path): # If the folder doesn't exist it will make it
os.makedirs(folder_path)
logging.info(' Path created!')
return True
else:
logging.info(' Path already exist')
return True
except OSError:
print('Error: Creating directory ' + folder_path, '\nFiles will be saved in the tool directory')
logging.warning(
' Error at creating directory << %s >> try to change your path in the settings file' % folder_path)
return False
# Rename files name
def rename_file(folder_path, rename_me, extension):
while "/" in rename_me:
if "/" in rename_me:
rename_me = rename_me[rename_me.find("/") + 1:]
if not os.path.exists(folder_path):
rename_me = '{0}{1}'.format(rename_me.replace(" ", "_").replace("(", "").replace(")", ""), extension)
else:
rename_me = '{0}{1}{2}'.format(folder_path, rename_me.replace(" ", "_").replace("(", "").replace(")", ""),
extension)
return rename_me
def efetch_call(start, db, counter_id, webenv, query_key, rettype):
batch_size = 200
update_progress(start, counter_id) # Download animation bar function
server_errors = 0
while server_errors < 11: # More than one attempts every time there is a network
try:
fetch_handle = Entrez.efetch(db=db,
retstart=start,
retmax=batch_size,
webenv=webenv,
query_key=query_key,
rettype=rettype)
if rettype == "fasta" or rettype == "gbc":
data = fetch_handle.read()
else:
data = Entrez.read(fetch_handle, validate=False)
fetch_handle.close()
break
except HTTPError as err:
server_errors += 1
if 500 <= err.code <= 599:
logging.warning(' Connection error to the server %s' % err)
print(color.RED + '\nConnection error: %s' % err + color.END)
logging.warning(" Attempt %i of 10" % server_errors)
print("Attempt %i of 10" % server_errors)
time.sleep(10)
if server_errors > 6:
print("Maybe NCBI's servers are too busy, if it still doesn't work, try later")
else:
print("\nError in the connection: %s" % err)
logging.error("Exception occurred", exc_info=True)
print("Attempt %i of 10" % server_errors)
time.sleep(20)
except OSError as err:
server_errors += 1
print("\nError in the connection: %s" % err)
logging.error("Exception occurred", exc_info=True)
print("Attempt %i of 10" % server_errors)
time.sleep(20)
except http.IncompleteRead as err:
print("Error: %s" % err)
time.sleep(5)
except RuntimeError as err:
print("Error: %s" % err)
print("Retrying in a few seconds")
time.sleep(10)
if server_errors >= 11:
logging.error(" Couldn't fetch part of the data list at: %i" % start)
print("\nMissing part")
logging.error("Try again starting from %i" % start)
fetch_handle.close()
return None
else:
return data
# Download dei FASTA
def download_fasta(counter_id, webenv, query_key, query, folder_path, file_input):
batch_size = 200 # Batch_size value limit our queries to NCBI so we don't get blacklisted
if file_input is None:
file_name = rename_file(folder_path, query, ".fasta") # Formatting the file name
out_handle = open(file_name, "w") # Creating the fasta file, where we will save our downloads
logging.info('Downloading Fasta files')
missing_part = 0
print("Downloading fasta sequence")
if counter_id > 400000:
#print(webenv[0])
indice = 0
div_n = counter_id / 200000
list_counter = []
if div_n.is_integer():
for num in range(0, int(div_n)):
list_counter.append(200000)
else:
for num in range(0, int(div_n)):
list_counter.append(200000)
list_counter.append(counter_id-200000*int(div_n))
#print(list_counter)
for idx, mini_counter in enumerate(list_counter):
for start in range(0, mini_counter, batch_size):
logging.info('Downloading fasta sequence: %i of %i' % (start + 1, mini_counter))
data = efetch_call(start, "nucleotide", mini_counter, webenv[indice], query_key, "fasta")
if data is None:
missing_part = 1
elif file_input is None:
out_handle.write(data)
else:
with open(file_input, 'a+') as a_writer:
a_writer.write("\n{0}".format(data))
indice += 1
else:
for start in range(0, counter_id, batch_size):
logging.info('Downloading fasta sequence: %i of %i' % (start + 1, counter_id))
data = efetch_call(start, "nucleotide", counter_id, webenv, query_key, "fasta")
if data is None:
missing_part = 1
elif file_input is None:
out_handle.write(data)
else:
with open(file_input, 'a+') as a_writer:
a_writer.write("\n{0}".format(data))
if file_input is None:
out_handle.close()
else:
a_writer.close()
update_progress(counter_id, counter_id)
if missing_part == 0:
logging.info(' Fasta file has been created')
print("\n ---- Fasta file has been created. ----\n\n")
else:
print("\n ---- Fasta file has been created but some errors occurred. ----")
print(" ---- Check log file for more details. ----\n\n")
# Create a file with ACCESSION iD and six level of Taxonomy (Phylum,Class,Order,Family,Genus,Species)
def download_accession_taxonomy(counter_id, webenv, query_key, query, folder_path, file_input):
logging.info(' Creating accession file')
if file_input is None:
file_name = input("Enter file name: ")
file_name = rename_file(folder_path, file_name, "_taxonomy.tsv")
out_handle = open(file_name, "w")
batch_size = 200
missing_part = 0
print("Downloading accession with taxonomy file")
if counter_id > 400000:
#print(webenv[0])
indice = 0
div_n = counter_id / 200000
list_counter = []
if div_n.is_integer():
for num in range(0, int(div_n)):
list_counter.append(200000)
else:
for num in range(0, int(div_n)):
list_counter.append(200000)
list_counter.append(counter_id-200000*int(div_n))
#print(list_counter)
for idx, mini_counter in enumerate(list_counter):
for start in range(0, mini_counter, batch_size):
logging.info('\nDownloading accession with taxonomy file: %i of %i' % (start + 1, mini_counter))
data = efetch_call(start, "nucleotide", mini_counter, webenv[indice], query_key, "gpc")
if data is None:
missing_part = 1
continue
else:
for n in range(len(data)): # For every downloaded entry
tax_id = None
# if taxonomy id is not found, it will give NA for every taxonomy level
try:
tax_id = ncbi.get_name_translator([data[n]["INSDSeq_organism"]])
if tax_id:
tax_id = tax_id[data[n]["INSDSeq_organism"]][0]
else:
tax_id = None
except ValueError:
logging.warning(" There is no taxonomy for %s \n" +
" searching through taxID" % data[n]["INSDSeq_organism"])
except sqlite3.OperationalError:
logging.warning(" There is no taxonomy for %s \n " +
"searching through taxID" % data[n]["INSDSeq_organism"])
if tax_id is None:
for z in range(len(data[n]["INSDSeq_feature-table"][0]["INSDFeature_quals"])):
# Searching for taxonomy id in the xml type data
try:
if "taxon" in data[n]["INSDSeq_feature-table"][0]["INSDFeature_quals"][z]["INSDQualifier_value"]:
tax_id = data[n]["INSDSeq_feature-table"][0]["INSDFeature_quals"][z][
"INSDQualifier_value"].replace("taxon:", "")
break
except KeyError:
continue
if tax_id is None:
logging.error(
" There is no taxonomy for %s, ncbi.get_lineage exception" % data[n]["INSDSeq_organism"],
exc_info=True)
taxa_list = "NA;NA;NA;NA;NA"
accession_list = "{0}\t{1};{2}{3}".format(data[n]["INSDSeq_accession-version"], taxa_list,
data[n]["INSDSeq_organism"], "\n")
if file_input is None:
out_handle.write(accession_list)
else:
with open(file_input, 'a+') as a_writer:
a_writer.write(accession_list)
continue
try:
lineage = ncbi.get_lineage(tax_id) # Getting entire taxonomy from its taxonomy id
except ValueError: # In case its id is not found
logging.error(
" There is no taxonomy for %s, ncbi.get_lineage exception" % data[n]["INSDSeq_organism"],
exc_info=True)
taxa_list = "NA;NA;NA;NA;NA"
accession_list = "{0}\t{1};{2}{3}".format(data[n]["INSDSeq_accession-version"], taxa_list,
data[n]["INSDSeq_organism"], "\n")
if file_input is None:
out_handle.write(accession_list)
else:
with open(file_input, 'a+') as a_writer:
a_writer.write(accession_list)
continue
except sqlite3.OperationalError as SQ:
print("sqlite3 error")
print(SQ)
print(str(tax_id) + "\n")
time.sleep(5)
continue
phylum = clas = order = family = genus = "NA" # Initializing
if lineage is not None:
for z in range(len(lineage)):
lineage_rank = ncbi.get_rank([lineage[z]])
# Checking the rank and getting their name
if "phylum" == lineage_rank[lineage[z]]:
rank_tmp = ncbi.get_taxid_translator([lineage[z]])
phylum = rank_tmp[lineage[z]]
if "class" == lineage_rank[lineage[z]]:
rank_tmp = ncbi.get_taxid_translator([lineage[z]])
clas = rank_tmp[lineage[z]]
if "order" == lineage_rank[lineage[z]]:
rank_tmp = ncbi.get_taxid_translator([lineage[z]])
order = rank_tmp[lineage[z]]
if "family" == lineage_rank[lineage[z]]:
rank_tmp = ncbi.get_taxid_translator([lineage[z]])
family = rank_tmp[lineage[z]]
if "genus" == lineage_rank[lineage[z]]:
rank_tmp = ncbi.get_taxid_translator([lineage[z]])
genus = rank_tmp[lineage[z]]
taxa_list = ";".join([phylum, clas, order, family, genus])
accession_list = "{0}\t{1};{2}{3}".format(data[n]["INSDSeq_accession-version"], taxa_list,
data[n]["INSDSeq_organism"], "\n")
if file_input is None:
out_handle.write(accession_list)
else:
with open(file_input, 'a+') as a_writer:
a_writer.write(accession_list)
indice += 1
if file_input is None:
out_handle.close()
else:
a_writer.close()
update_progress(counter_id, counter_id)
logging.info(' Accession with taxonomy file has been created')
else:
for start in range(0, counter_id, batch_size):
logging.info(' Downloading accession with taxonomy file: %i of %i' % (start + 1, counter_id))
data = efetch_call(start, "nucleotide", counter_id, webenv, query_key, "gpc")
if data is None:
missing_part = 1
continue
else:
for n in range(len(data)): # For every downloaded entry
tax_id = None
# if taxonomy id is not found, it will give NA for every taxonomy level
try:
tax_id = ncbi.get_name_translator([data[n]["INSDSeq_organism"]])
if tax_id:
tax_id = tax_id[data[n]["INSDSeq_organism"]][0]
else:
tax_id = None
except ValueError:
logging.warning(" There is no taxonomy for %s \n" +
" searching through taxID" % data[n]["INSDSeq_organism"])
except sqlite3.OperationalError:
logging.warning(" There is no taxonomy for %s \n " +
"searching through taxID" % data[n]["INSDSeq_organism"])
if tax_id is None:
for z in range(len(data[n]["INSDSeq_feature-table"][0]["INSDFeature_quals"])):
# Searching for taxonomy id in the xml type data
try:
if "taxon" in data[n]["INSDSeq_feature-table"][0]["INSDFeature_quals"][z]["INSDQualifier_value"]:
tax_id = data[n]["INSDSeq_feature-table"][0]["INSDFeature_quals"][z][
"INSDQualifier_value"].replace("taxon:", "")
break
except KeyError:
continue
if tax_id is None:
logging.error(
" There is no taxonomy for %s, ncbi.get_lineage exception" % data[n]["INSDSeq_organism"],
exc_info=True)
taxa_list = "NA;NA;NA;NA;NA"
accession_list = "{0}\t{1};{2}{3}".format(data[n]["INSDSeq_accession-version"], taxa_list,
data[n]["INSDSeq_organism"], "\n")
if file_input is None:
out_handle.write(accession_list)
else:
with open(file_input, 'a+') as a_writer:
a_writer.write(accession_list)
continue
try:
lineage = ncbi.get_lineage(tax_id) # Getting entire taxonomy from its taxonomy id
except ValueError: # In case its id is not found
logging.error(
" There is no taxonomy for %s, ncbi.get_lineage exception" % data[n]["INSDSeq_organism"],
exc_info=True)
taxa_list = "NA;NA;NA;NA;NA"
accession_list = "{0}\t{1};{2}{3}".format(data[n]["INSDSeq_accession-version"], taxa_list,
data[n]["INSDSeq_organism"], "\n")
if file_input is None:
out_handle.write(accession_list)
else:
with open(file_input, 'a+') as a_writer:
a_writer.write(accession_list)
continue
except sqlite3.OperationalError as SQ:
print("sqlite3 error")
print(SQ)
print(str(tax_id) + "\n")
time.sleep(5)
continue
phylum = clas = order = family = genus = "NA" # Initializing
if lineage is not None:
for z in range(len(lineage)):
lineage_rank = ncbi.get_rank([lineage[z]])
# Checking the rank and getting their name
if "phylum" == lineage_rank[lineage[z]]:
rank_tmp = ncbi.get_taxid_translator([lineage[z]])
phylum = rank_tmp[lineage[z]]
if "class" == lineage_rank[lineage[z]]:
rank_tmp = ncbi.get_taxid_translator([lineage[z]])
clas = rank_tmp[lineage[z]]
if "order" == lineage_rank[lineage[z]]:
rank_tmp = ncbi.get_taxid_translator([lineage[z]])
order = rank_tmp[lineage[z]]
if "family" == lineage_rank[lineage[z]]:
rank_tmp = ncbi.get_taxid_translator([lineage[z]])
family = rank_tmp[lineage[z]]
if "genus" == lineage_rank[lineage[z]]:
rank_tmp = ncbi.get_taxid_translator([lineage[z]])
genus = rank_tmp[lineage[z]]
taxa_list = ";".join([phylum, clas, order, family, genus])
accession_list = "{0}\t{1};{2}{3}".format(data[n]["INSDSeq_accession-version"], taxa_list,
data[n]["INSDSeq_organism"], "\n")
if file_input is None:
out_handle.write(accession_list)
else:
with open(file_input, 'a+') as a_writer:
a_writer.write(accession_list)
if file_input is None:
out_handle.close()
else:
a_writer.close()
update_progress(counter_id, counter_id)
logging.info(' Accession with taxonomy file has been created')
if missing_part == 0:
print("\n ---- Accession with taxonomy file has been created. ----\n")
else:
print("\n ---- Accession with taxonomy file has been created but some errors occurred. ----")
print(" ---- Check log file for more details. ---- \n")
if file_input is None:
return file_name
else:
return
def database_module(plot_or_not, file_pos, file, choice, output_name):
# if file_pos is more than 0 means the tool is resuming the download from that position in the file
if file_pos > 0:
search_list = [file[0]]
end = min(len(file), file_pos + 2500)
for pos in range(file_pos, end):
search_list.append(file[pos])
if search_list[0] == "accession":
search_index = [str(search_list[1])]
for i in range(2, len(search_list)):
search_index = "{0} or {1}".format(search_index, search_list[i])
else:
search_index = "(({0}) AND ({1}))".format(search_list[1], search_list[0])
for i in range(2, len(search_list)):
search_index = "{2} OR (({0}) AND ({1}))".format(search_list[i], search_list[0], search_index)
# variable to prevent the stop of esearch if you get a momentary internet problem
server_error = 0
while server_error < 11:
try:
handles = Entrez.esearch(db="nucleotide", term=search_index, usehistory="y", idtype="acc")
result = Entrez.read(handles, validate=False)
break
except HTTPError as err:
server_error += 1
if 500 <= err.code <= 599:
logging.warning(' Connection error to the server %s' % err)
print('\nConnection error to the server %s' % err)
print(search_index)
time.sleep(60)
logging.warning(" Attempt %i of 10" % server_error)
print("Attempt %i of 10" % server_error)
time.sleep(10)
if server_error > 6:
print("Maybe NCBI's servers are too busy, if it still doesn't work, try later")
else:
print("\nError in the connection: %s" % err)
logging.error("Exception occurred", exc_info=True)
print("Attempt %i of 10" % server_error)
time.sleep(20)
except OSError as err:
print("\nError in the connection: %s" % err)
logging.error("Exception occurred", exc_info=True)
print("Attempt %i of 10" % server_error)
time.sleep(20)
except http.IncompleteRead as err:
print("Error: %s" % err)
time.sleep(5)
except RuntimeError as err:
print("Error: %s" % err)
print("Retrying in a few seconds")
time.sleep(10)
if server_error >= 11:
print("Connection impossible with NCBI, can't request %s" % search_index)
logging.warning("Connection impossible with NCBI, can't request %s" % search_index)
database_module(None, pos, file, choice, output_name)
counter_queries = int(result["Count"]) # With counter_query we know how many IDs we found
# results["count"] contains the results counts found with the query
# This number is needed to define how many ID's we will search and download
# Default value is 20 so without it NCBI will let us download only a bunch of data instead of the full list
if counter_queries == 0:
print("\nNo results found with: \n", search_index, "\n")
logging.warning("No results found with: %s" % search_index)
database_module(None, pos, file, choice, output_name)
# variable to prevent the stop of esearch if you get a momentary internet problem
server_error = 0
while server_error < 11:
try:
handles = Entrez.esearch(db="nucleotide", term=search_index, retmax=counter_queries)
result = Entrez.read(handles, validate=False)
id_list = result["IdList"]
epost_xml = Entrez.epost("nucleotide", id=",".join(id_list))
result = Entrez.read(epost_xml, validate=False)
web_env = result["WebEnv"]
key = result["QueryKey"]
break
except HTTPError as err:
server_error += 1
if 500 <= err.code <= 599:
logging.warning(' Connection error to the server %s' % err)
print('\nConnection error to the server %s' % err)
print(search_index)
time.sleep(60)
logging.warning(" Attempt %i of 10" % server_error)
print("Attempt %i of 10" % server_error)
time.sleep(10)
if server_error > 6:
print("Maybe NCBI's servers are too busy, if it still doesn't work, try later")
else:
print("\nError in the connection: %s" % err)
logging.error("Exception occurred", exc_info=True)
print("Attempt %i of 10" % server_error)
time.sleep(20)
except OSError as err:
print("\nError in the connection: %s" % err)
logging.error("Exception occurred", exc_info=True)
print("Attempt %i of 10" % server_error)
time.sleep(20)
except http.IncompleteRead as err:
print("Error: %s" % err)
time.sleep(5)
except RuntimeError as err:
print("Error: %s" % err)
print("Retrying in a few seconds")
time.sleep(10)
if server_error >= 11:
print("Connection impossible with NCBI, can't request %s" % search_index)
logging.warning("Connection impossible with NCBI, can't request %s" % search_index)
if (choice == 1 or choice == 4) and counter_queries > 0:
ext = "_{0}_temporary.fasta".format(file_pos)
file_name = rename_file(directory, output_name[0], ext)
download_fasta(counter_queries, web_env, key, search_index, directory, file_name)
if (choice == 2 or choice == 4) and counter_queries > 0:
ext = "_{0}_temporary.tsv".format(file_pos)
file_name = rename_file(directory, output_name[1], ext)
download_accession_taxonomy(counter_queries, web_env, key, search_index, directory, file_name)
if end >= len(file):
if output_name[0] is not None:
print("Merging all temporary files into %s" % output_name[0])
with open(output_name[0], 'wb') as outfile:
for filename in glob.glob('{0}*_temporary.fasta'.format(directory)):
if filename == output_name[0]:
# don't want to copy the output into the output
continue
with open(filename, 'rb') as readfile:
outfile.write(readfile.read())
if output_name[1] is not None:
print("Merging all temporary files into %s" % output_name[1])
with open(output_name[1], 'wb') as outfile:
for filename in glob.glob('{0}*_temporary.tsv'.format(directory)):
if filename == output_name[1]:
# don't want to copy the output into the output
continue
with open(filename, 'rb') as readfile:
outfile.write(readfile.read())
else:
database_module(None, pos, file, choice, output_name)
# Here is how the module starts normally
else:
if plot_or_not is None: # Creating the menu for standalone module (when not called from statistical module)
print("\n--- DATABASE MODULE --- \n")
csv_manual = str(input("Do you want to use a manual search or through a file? (f > file, m > manual): "))
while len(csv_manual) <= 0 or csv_manual[0] not in ("f", "F", "m", "M"):
print("Wrong input, write <f> for csv or <m> for manual! (Without <>)\n")
csv_manual = input("Do you want to use a manual search or through a file? (f > file, m > manual) ")
if csv_manual[0] in ("f", "F"): # Considerare la tipologia di file da avere come input
# Initializing while cycle
input_list_type = None
while input_list_type not in ("A", "a", "t", "T", "o", "O"):
input_list_type = input("\nA - if your file is a list of accessions\n" +
"T - if it's a list of TaxIDs\n" +
"O - if it's a list of organism name\n" +
"All the input files must have a csv or tsv extension, please refer to example files provided and tutorial for the guidelines.\n" +
">> Enter the choice: ")
if input_list_type in ("T", "t", "O", "o"):
# POSSIBLE INPUT -> GENE IN THE COLUMN 0
file_list = [str(input(
"\nEnter <0> for all genes\nFor multiple genes use 'OR' example:\n- COX1 OR 16S\n"
"- COI or COX1 or CO1\n- 0\n>> Enter the gene name:"))]
elif input_list_type in ("A", "a"):
file_list = ["accession"]
else:
print("\nEnter a valid choice! \n")
while True:
csv_file_module_one = input("\n>> Enter your csv or tsv file path: ")
print("")
try:
logging.info("Loading csv file...")
with open(csv_file_module_one, 'r') as r:
while csv_file_module_one[-3:] not in ('tsv', 'csv'):
print("File extension not CSV or TSV, please use the right format.")
csv_file_module_one = input("Enter your csv or tsv file path: ")
if csv_file_module_one[-3:] == 'csv':
file_csv_query = csv.reader(r, delimiter=',')
if csv_file_module_one[-3:] == 'tsv':
file_csv_query = csv.reader(r, delimiter='\t')
for line in file_csv_query:
file_list.append(line[0])
logging.info("Loading completed!")
break
except IOError as err:
logging.warning('No file found or permission denied, please check your file or location: %s' % err)
print("No file found or permission denied, please check your file or location")
print("File location: ", csv_file_module_one, "\n")
while "/" in csv_file_module_one:
csv_file_module_one = csv_file_module_one[csv_file_module_one.index("/") + 1 : ]
if plot_or_not is None:
print('Choose one of the following options: \n ',
'1: Download FASTA files \n ',
'2: Download files with accession and taxonomy \n ',
'3: Retrieve DNA markers and genes \n ',
'4: All the above options \n ',
'5: Make a new query \n ',
'6: Main menu \n')
while True:
try:
menu_choice = int(input('Enter the NUMBER: '))
if menu_choice not in (1, 2, 3, 4, 5, 6):
print("Wrong input, please write only the choice number. \n")
continue
break
except ValueError:
print("Error, insert only the numeric value of your choice")
continue
if menu_choice == 5:
clear()
database_module(None, 0, None, None, [None, None])
if menu_choice == 6:
clear()
main_menu()
if menu_choice == 3 or menu_choice == 4:
first_element = True
if create_folder("./download/{0}/".format(csv_file_module_one)):
marker_folder = "./download/{0}/".format(csv_file_module_one)
else:
marker_folder = directory
for element in file_list:
if first_element:
first_element = False
continue
if input_list_type in ("o", "O"): # File list of Organism
if file_list[0] == "0":
search_index = element
else:
search_index = "({0} AND {1})".format(element, file_list[0])
elif input_list_type in ("t", "T"): # File list of TaxIDs
if file_list[0] == "0":
search_index = "{1}{0}{2}".format(element, "txid", "[Organism:noexp]")
else:
search_index = "({2} AND {1}{0}{3})".format(element,
"txid",
file_list[0],
"[Organism:noexp]")
else: # File list of ACCESSIONS
search_index = [str(element)]
# variable to prevent the stop of esearch if you get a momentary internet problem
server_error = 0
while server_error < 11:
server_error += 1
try:
handles = Entrez.esearch(db="nucleotide",