forked from gjeunen/reference_database_creator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcrabs
executable file
·1464 lines (1334 loc) · 74.9 KB
/
crabs
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 python3
################################################
################ IMPORT MODULES ################
################################################
import argparse
import subprocess as sp
import pandas as pd
import os
import shutil
import collections
from tqdm import tqdm
from itertools import islice
import matplotlib
import matplotlib.pyplot as plt
from Bio.Align.Applications import MuscleCommandline
from pathlib import Path
from collections import Counter
from Bio import SeqIO
from Bio.SeqIO import FastaIO
from Bio import AlignIO
from Bio import Phylo
from Bio.Seq import Seq
from Bio.Phylo.TreeConstruction import DistanceCalculator, DistanceMatrix, DistanceTreeConstructor
from function.module_db_download import wget_ncbi, ncbi_formatting, mitofish_download, mitofish_format, embl_download, embl_fasta_format, embl_crabs_format, bold_download, bold_format, check_accession, append_primer_seqs, generate_header, merge_databases, import_BOLD_reformatting, retrieve_species, wget_ncbi_species
from function.module_assign_tax import tax2dict, get_accession, acc_to_dict, get_lineage, final_lineage_simple
from function.module_db_cleanup import derep_strict, derep_single, derep_uniq, set_param, create_pd_cols, set_param2
from function.module_visualizations import split_db_by_taxgroup, num_spec_seq_taxgroup, horizontal_barchart, get_amp_length, amplength_figure, file_dmp_to_dict, species_to_taxid, lineage_retrieval
from function import __version__
################################################
########### MODULE DATABASE DOWNLOAD ###########
################################################
## function download data from online databases
def db_download(args):
SOURCE = args.source
DATABASE = args.database
QUERY = args.query
OUTPUT = args.output
ORIG = args.orig
EMAIL = args.email
BATCHSIZE = args.batchsize
DISCARD = args.discard
SPECIES = args.species
BOLDGAP = args.boldgap
MARKER = args.marker
## download taxonomy data from NCBI
if SOURCE == 'taxonomy':
print('\ndownloading taxonomy information')
url_acc2taxid = 'https://ftp.ncbi.nlm.nih.gov/pub/taxonomy/accession2taxid/nucl_gb.accession2taxid.gz'
url_taxdump = 'https://ftp.ncbi.nlm.nih.gov/pub/taxonomy/taxdump.tar.gz'
wget_help = sp.check_output('wget -h', shell=True)
helstr=wget_help.decode('utf-8')
if 'show-progress' in helstr:
results = sp.run(['wget', url_acc2taxid, '-q', '--show-progress'])
else:
results = sp.run(['wget', url_acc2taxid])
print('unzipping nucl_gb.accession2taxid.gz...')
results = sp.run(['gunzip', 'nucl_gb.accession2taxid.gz'])
if 'show-progress' in helstr:
results = sp.run(['wget', url_taxdump, '-q', '--show-progress'])
else:
results = sp.run(['wget', url_taxdump, '-q'])
results = sp.run(['tar', '-zxvf', 'taxdump.tar.gz'], stdout = sp.DEVNULL, stderr = sp.DEVNULL)
print('removing intermediary files\n')
files_to_remove = ['citations.dmp', 'delnodes.dmp', 'division.dmp', 'gencode.dmp', 'merged.dmp', 'gc.prt', 'readme.txt', 'taxdump.tar.gz']
for file in files_to_remove:
os.remove(file)
## download sequencing data from NCBI
elif SOURCE == 'ncbi':
if all(v is not None for v in [DATABASE, QUERY, OUTPUT, EMAIL]):
print('\ndownloading sequences from NCBI')
if SPECIES == None:
print(f'"--species" parameter not provided, downloading NCBI data based solely on "--query": {QUERY}')
ncbi_download = wget_ncbi(QUERY, DATABASE, EMAIL, BATCHSIZE, OUTPUT)
else:
specieslist = retrieve_species(SPECIES)
fullTempFileList = []
for speciesName in specieslist:
speciesTempFileList = wget_ncbi_species(QUERY, DATABASE, EMAIL, BATCHSIZE, OUTPUT, speciesName)
for item in speciesTempFileList:
fullTempFileList.append(item)
with open('CRABS_ncbi_download.fasta', 'w') as outfile:
for tempfile in fullTempFileList:
with open(tempfile, 'r') as infile:
for line in infile:
outfile.write(line)
os.remove('esearch_output.txt')
for tempfile in fullTempFileList:
os.remove(tempfile)
print('formatting the downloaded sequencing file to CRABS format')
format_seqs = ncbi_formatting(OUTPUT, ORIG, DISCARD)
print(f'written {format_seqs} sequences to {OUTPUT}\n')
else:
print('\nnot all parameters have an input value\n')
## download sequencing data from EMBL
elif SOURCE == 'embl':
if all(v is not None for v in [DATABASE, OUTPUT]):
print('\ndownloading sequences from EMBL')
dl_files = embl_download(DATABASE)
fasta_file = embl_fasta_format(dl_files)
print(f'formatting intermediary file to CRABS format')
crabs_file = embl_crabs_format(fasta_file, OUTPUT, ORIG, DISCARD)
print(f'written {crabs_file} sequences to {OUTPUT}\n')
else:
print('\nnot all parameters have an input value\n')
## download sequencing data from MitoFish
elif SOURCE == 'mitofish':
if all(v is not None for v in [OUTPUT]):
print('\ndownloading sequences from the MitoFish database')
url = 'http://mitofish.aori.u-tokyo.ac.jp/species/detail/download/?filename=download%2F/complete_partial_mitogenomes.zip'
dl_file = mitofish_download(url)
print(f'formatting {dl_file} to CRABS format')
mitoformat = mitofish_format(dl_file, OUTPUT, ORIG, DISCARD)
print(f'written {mitoformat} sequences to {OUTPUT}\n')
else:
print('\nnot all parameters have an input value\n')
## download sequencing data from BOLD
elif SOURCE == 'bold':
if all(v is not None for v in [DATABASE, OUTPUT]):
print('\ndownloading sequences from BOLD')
bold_file = bold_download(DATABASE, MARKER)
print(f'downloaded {bold_file} sequences from BOLD')
print(f'formatting {bold_file} sequences to CRABS format')
boldformat = bold_format(OUTPUT, ORIG, DISCARD, BOLDGAP)
print(f'written {boldformat} sequences to {OUTPUT}\n')
else:
print('\nnot all parameters have an input value\n')
## error message if no option was chosen
else:
print('\nno valid database was chosen for the "-s"/"--source" parameter, please specify either "ncbi", "embl", "mitofish", "bold", or "taxonomy"\n')
## function: import existing or custom database
def db_import(args):
INPUT = args.input
HEADER = args.header
OUTPUT = args.output
FWD = args.fwd
REV = args.rev
DELIM = args.delim
LEFT = args.leftdelim
## process file with accession number in header
if HEADER == 'accession':
if all(v is not None for v in [INPUT, OUTPUT, DELIM]):
print(f'\nchecking correct formatting of accession numbers in {INPUT}')
incorrect_accession = check_accession(INPUT, OUTPUT, DELIM, LEFT)
if len(incorrect_accession) != 0:
print('found incorrectly formatted accession numbers, please check file: "incorrect_accession_numbers.txt"')
with open('incorrect_accession_numbers.txt', 'w') as fout:
for item in incorrect_accession:
fout.write(item + '\n')
if all(v is not None for v in [FWD, REV]):
print(f'appending primer sequences to {OUTPUT}')
numseq = append_primer_seqs(OUTPUT, FWD, REV)
print(f'added primers to {numseq} sequences in {OUTPUT}\n')
else:
print('')
else:
print('\nnot all parameters have an input value\n')
## process file with species info in header
elif HEADER == 'species':
if all(v is not None for v in [INPUT, OUTPUT, DELIM]):
print(f'\ngenerating new sequence headers for {INPUT}')
num_header = generate_header(INPUT, OUTPUT, DELIM)
print(f'generated {num_header} headers for {OUTPUT}')
if all(v is not None for v in [FWD, REV]):
print(f'appending primer sequences to {OUTPUT}')
numseq = append_primer_seqs(OUTPUT, FWD, REV)
print(f'added primers to {numseq} sequences in {OUTPUT}\n')
else:
print('')
else:
print('\nnot all parameters have an input value\n')
## process BOLD downloaded file outside of CRABS
elif HEADER == 'BOLD':
if all(v is not None for v in [INPUT, OUTPUT]):
print(f'\nformatting BOLD downloaded sequences to CRABS format')
reformat = import_BOLD_reformatting(INPUT, OUTPUT)
if all(v is not None for v in [FWD, REV]):
print(f'appending primer sequences to {OUTPUT}')
numseq = append_primer_seqs(OUTPUT, FWD, REV)
print(f'added primers to {numseq} sequencing in {OUTPUT}\n')
else:
print('')
else:
print('\nnot all parameters have an input value\n')
## missing or miswritten header information
else:
print('\nplease specify header information: "accession" or "species" or "BOLD"\n')
## function: merge multiple databases
def db_merge(args):
INPUT = args.input
UNIQ = args.uniq
OUTPUT = args.output
if UNIQ != '':
print('\nmerging all fasta files and discarding duplicate sequence headers')
num_uniq = merge_databases(INPUT, OUTPUT)
print(f'written {num_uniq} sequences to {OUTPUT}\n')
else:
print('\nmerging all fasta files and keeping duplicate sequence headers')
with open(OUTPUT, 'w') as fout:
for file in INPUT:
num = len(list(SeqIO.parse(file, 'fasta')))
print(f'found {num} sequences in {file}')
with open(file, 'r') as fin:
for line in fin:
fout.write(line)
num = len(list(SeqIO.parse(OUTPUT, 'fasta')))
print(f'written {num} sequences to {OUTPUT}\n')
################################################
############# MODULE IN SILICO PCR #############
################################################
## function: in silico PCR
def insilico_pcr(args):
FWD = args.fwd
REV = args.rev
INPUT = args.input
ERROR = args.error
OUTPUT = args.output
THREADS = args.threads
# Change 'I' to 'N'
FWD = FWD.replace('I','N')
REV = REV.replace('I','N')
## reverse complement reverse primer sequence
REV_CORRECT = str(Seq(REV).reverse_complement())
## setting variable names using the info from user input
TRIMMED_INIT = 'init_trimmed.fasta'
UNTRIMMED_INIT = 'init_untrimmed.fasta'
REVCOMP_UNTRIMMED_INIT = 'revcomp_untrimmed.fasta'
TRIMMED_REVCOMP = 'revcomp_trimmed.fasta'
UNTRIMMED_REVCOMP = 'untrimmed_revcomp.fasta'
OVERLAP = str(min([len(FWD), len(REV_CORRECT)]))
ADAPTER = FWD + '...' + REV_CORRECT
## run cutadapt on downloaded fasta file
print(f'\nreading {INPUT} into memory')
seqcount = 0
with tqdm(total = os.path.getsize(INPUT)) as pbar:
with open(INPUT, 'r') as infile:
for line in infile:
pbar.update(len(line))
if line.startswith('>'):
seqcount = seqcount + 1
count_init = seqcount
print(f'found {count_init} sequences in {INPUT}')
print('running in silico PCR on fasta file containing {} sequences'.format(count_init))
cmnd_cutadapt_1 = ['cutadapt', '-g', ADAPTER, '-o', TRIMMED_INIT, INPUT, '--untrimmed-output', UNTRIMMED_INIT, '--no-indels', '-e', ERROR, '--overlap', OVERLAP, '--cores', THREADS, '--quiet']# '--report=minimal']
sp.call(cmnd_cutadapt_1)
print(f'counting the number of sequences found by in silico PCR')
count_trimmed_init = 0
with tqdm(total = os.path.getsize(TRIMMED_INIT)) as pbar:
with open(TRIMMED_INIT, 'r') as infile:
for line in infile:
pbar.update(len(line))
if line.startswith('>'):
count_trimmed_init = count_trimmed_init + 1
print('found primers in {} sequences'.format(count_trimmed_init))
## run vsearch to reverse complement untrimmed sequences
if count_trimmed_init < count_init:
print(f'reading sequences without primer-binding regions into memory')
count_untrimmed_init = 0
with tqdm(total = os.path.getsize(UNTRIMMED_INIT)) as pbar:
with open(UNTRIMMED_INIT, 'r') as infile:
for line in infile:
pbar.update(len(line))
if line.startswith('>'):
count_untrimmed_init = count_untrimmed_init + 1
print('reverse complementing {} untrimmed sequences'.format(count_untrimmed_init))
cmnd_vsearch_revcomp = ['vsearch', '--fastx_revcomp', UNTRIMMED_INIT, '--fastaout', REVCOMP_UNTRIMMED_INIT, '--quiet']
sp.call(cmnd_vsearch_revcomp)
## run cutadapt on reverse complemented untrimmed sequences
print('running in silico PCR on {} reverse complemented untrimmed sequences'.format(count_untrimmed_init))
cmnd_cutadapt_2 = ['cutadapt', '-g', ADAPTER, '-o', TRIMMED_REVCOMP, REVCOMP_UNTRIMMED_INIT, '--untrimmed-output', UNTRIMMED_REVCOMP, '--no-indels', '-e', ERROR, '--overlap', OVERLAP, '--cores', THREADS, '--quiet']#'--report=minimal']
sp.call(cmnd_cutadapt_2)
print(f'counting the number of sequences found by in silico PCR')
count_trimmed_second = 0
with tqdm(total = os.path.getsize(TRIMMED_REVCOMP)) as pbar:
with open(TRIMMED_REVCOMP, 'r') as infile:
for line in infile:
pbar.update(len(line))
if line.startswith('>'):
count_trimmed_second = count_trimmed_second + 1
print('found primers in {} sequences\n'.format(count_trimmed_second))
## concatenate both trimmed files
with open(OUTPUT, 'wb') as wfd:
for f in [TRIMMED_INIT, TRIMMED_REVCOMP]:
with open(f, 'rb') as fd:
shutil.copyfileobj(fd, wfd)
## remove intermediary files
files = [TRIMMED_INIT, UNTRIMMED_INIT, REVCOMP_UNTRIMMED_INIT, TRIMMED_REVCOMP, UNTRIMMED_REVCOMP]
for file in files:
os.remove(file)
## don't run reverse complement when initial in silico PCR trims all sequences
else:
print('all sequences trimmed, no reverse complement step\n')
results = sp.run(['mv', TRIMMED_INIT, OUTPUT])
os.remove(UNTRIMMED_INIT)
################################################
####### MODULE PAIRWISE GLOBAL ALIGNMENT #######
################################################
## function: retrieve the amplicon region from sequences with missing primer-binding regions
def pga(args):
INPUT = args.input
DB = args.db
OUTPUT = args.output
FWD = args.fwd
REV = args.rev
SPEED = args.speed
ID = args.id
COV = args.cov
FILTER = args.filter
## step 1: extract sequences from originally downloaded file that were not successful during in silico PCR analysis
insilico_dict = {}
non_insilico_dict = {}
non_insilico_list = []
count_orig = 0
count_insilico = 0
count_non_insilico = 0
print(f'\nreading {DB} into memory')
with tqdm(total = os.path.getsize(DB)) as pbar:
for seq_record in SeqIO.parse(DB, 'fasta'):
pbar.update(len(seq_record))
count_insilico = count_insilico + 1
id = str(seq_record.id)
seq = str(seq_record.seq)
insilico_dict[id] = seq
print(f'found {count_insilico} number of sequences in {DB}')
print(f'reading {INPUT} into memory')
with tqdm(total = os.path.getsize(INPUT)) as pbar:
for seq_record in SeqIO.parse(INPUT, 'fasta'):
pbar.update(len(seq_record))
count_orig = count_orig + 1
id = str(seq_record.id)
seq = str(seq_record.seq)
if id not in insilico_dict:
count_non_insilico = count_non_insilico + 1
non_insilico_list.append(seq_record)
non_insilico_dict[id] = seq
print(f'found {count_orig} number of sequences in {INPUT}')
print(f'analysing {count_non_insilico} number of sequences for pairwise global alignment')
non_insilico_fa = [FastaIO.as_fasta_2line(record) for record in non_insilico_list]
with open('CRABS_pga.fasta', 'w') as file:
for item in non_insilico_fa:
file.write(item)
## step 2: subset the data based on the SPEED parameter
if SPEED == 'fast':
newfile = []
count = 0
print(f'subsetting {INPUT} by discarding sequences longer than 5,000 bp')
with tqdm(total = os.path.getsize('CRABS_pga.fasta')) as pbar:
with open('CRABS_pga.fasta', 'r') as infile:
for line in infile:
pbar.update(len(line))
if line.startswith('>'):
header = line
else:
seq = line
line = line.rstrip('\n')
seqlen = len(line)
if seqlen < 5001:
count = count + 1
newfile.append(header)
newfile.append(seq)
with open('CRABS_pga_subset.fasta', 'w') as outfile:
for item in newfile:
outfile.write(item)
print(f'found {count} ({float("{:.2f}".format(count/count_non_insilico*100))}%) number of sequences in {INPUT} shorter than 5,000 bp')
elif SPEED == 'medium':
newfile = []
count = 0
with tqdm(total = os.path.getsize('CRABS_pga.fasta')) as pbar:
with open('CRABS_pga.fasta', 'r') as infile:
for line in infile:
pbar.update(len(line))
if line.startswith('>'):
header = line
else:
seq = line
line = line.rstrip('\n')
seqlen = len(line)
if seqlen < 10001:
count = count + 1
newfile.append(header)
newfile.append(seq)
with open('CRABS_pga_subset.fasta', 'w') as outfile:
for item in newfile:
outfile.write(item)
print(f'subsetting {INPUT} by discarding sequences longer than 10,000 bp')
print(f'found {count} ({float("{:.2f}".format(count/count_non_insilico*100))}%) number of sequences in {INPUT} shorter than 10,000 bp')
elif SPEED == 'slow':
newfile = []
count = 0
with open('CRABS_pga.fasta', 'r') as infile:
for line in infile:
count = count + 1
if line.startswith('>'):
header = line
else:
seq = line
line = line.rstrip('\n')
seqlen = len(line)
newfile.append(header)
newfile.append(seq)
with open('CRABS_pga_subset.fasta', 'w') as outfile:
for item in newfile:
outfile.write(item)
else:
print('please specify one of the accepted --speed options: "fast", "medium", "slow"')
## step 3: run the pairwise global alignment with vsearch
print(f'running pairwise global alignment on {count} number of sequences. This may take a while!')
cmnd_vsearch_pga = ['vsearch', '--usearch_global', 'CRABS_pga_subset.fasta', '--db', DB, '--id', ID, '--userout', 'CRABS_pga_info.txt', '--userfields', 'query+ql+qcov+qilo+qihi+target+tl+tcov+tilo+tihi+id']#, '--quiet']
result = sp.run(cmnd_vsearch_pga)#, stdout = sp.DEVNULL, stderr = sp.DEVNULL)
## step 4: extract the sequence regions that conform to parameter settings
count_align = 0
count_pga_filter = 0
pga_list = []
print(f'filtering alignments based on parameter settings')
with tqdm(total = os.path.getsize('CRABS_pga_info.txt')) as pbar:
with open('CRABS_pga_info.txt', 'r') as file:
for line in file:
pbar.update(len(line))
count_align = count_align + 1
query = line.split('\t')[0]
ql = int(line.split('\t')[1])
qilo = int(line.split('\t')[3])
qihi = int(line.split('\t')[4])
tcov = float(line.split('\t')[7])
end_pos = ql - qihi
if FILTER == 'strict':
if tcov >= float(COV) and (qilo - 1 < len(FWD) or end_pos < len(REV)):
count_pga_filter = count_pga_filter + 1
seq = non_insilico_dict[query]
seq = seq[qilo - 1 : qihi]
pga_list.append('>' + query + '\n')
pga_list.append(seq + '\n')
elif FILTER == 'relaxed':
if tcov >= float(COV):
count_pga_filter = count_pga_filter + 1
seq = non_insilico_dict[query]
seq = seq[qilo - 1 : qihi]
pga_list.append('>' + query + '\n')
pga_list.append(seq + '\n')
else:
print(f'{FILTER} not provided as an option for the METHOD parameter')
print('please choose either "strict" or "relaxed"\n')
break
print(f'{count_align} out of {count} number of sequences aligned to {DB}')
print(f'{count_pga_filter} number of sequences achieved an alignment that passed filtering thresholds')
print(f'written {count_pga_filter + count_insilico} sequences to {OUTPUT}\n')
with open('CRABS_pga_results.fasta', 'w') as file:
for item in pga_list:
file.write(item)
## step 5: combine in silico and pga files and clean up intermediary files
filenames = [DB, 'CRABS_pga_results.fasta']
with open(OUTPUT, 'w') as outfile:
for name in filenames:
with open(name) as infile:
outfile.write(infile.read())
remove_files = ['CRABS_pga_results.fasta', 'CRABS_pga_info.txt', 'CRABS_pga.fasta', 'CRABS_pga_subset.fasta']
for file in remove_files:
os.remove(file)
################################################
########## MODULE TAXONOMY ASSIGNMENT ##########
################################################
## function: get taxonomic lineage for each accession number
def assign_tax(args):
INPUT = args.input
OUTPUT = args.output
ACC2TAX = args.acc2tax
TAXID = args.taxid
NAME = args.name
WEB = args.web
RANKS = args.ranks
MISS = args.missing
## process initial files
print(f'\nretrieving accession numbers from {INPUT}')
accession = get_accession(INPUT)
print(f'found {len(accession)} accession numbers in {INPUT}')
acc2tax, taxid, name, no_acc = tax2dict(ACC2TAX, TAXID, NAME, accession)
print(f'processed {len(acc2tax)} entries in {ACC2TAX}')
print(f'processed {len(taxid)} entries in {TAXID}')
print(f'processed {len(name)} entries in {NAME}')
## get taxonomic lineage
print(f'assigning a tax ID number to {len(accession)} accession numbers from {INPUT}')
acc_taxid_dict, taxid_list, missing_taxa = acc_to_dict(accession, acc2tax, no_acc, ACC2TAX, WEB)
print(f'{len(acc_taxid_dict)} accession numbers resulted in {len(taxid_list)} unique tax ID numbers')
print(f'generating taxonomic lineages for {len(taxid_list)} tax ID numbers')
lineage = get_lineage(RANKS, taxid_list, taxid, name)
print(f'assigning a taxonomic lineage to {len(accession)} accession numbers')
#final_lineage = final_lineage_comb(acc_taxid_dict, lineage, INPUT, OUTPUT)
final_lineage = final_lineage_simple(acc_taxid_dict, lineage, INPUT, OUTPUT)
print(f'written {len(final_lineage)} entries to {OUTPUT}')
if MISS != 'no':
missing_seqs = []
with tqdm(total = os.path.getsize(INPUT)) as pbar:
for record in SeqIO.parse(INPUT, 'fasta'):
pbar.update(len(record))
acc = str(record.id).split('.')[0]
if acc in missing_taxa:
missing_seqs.append(acc + '\t' + str(record.seq))
with open(MISS, 'w') as fout:
for item in missing_seqs:
fout.write(item + '\n')
print(f'writting {len(missing_seqs)} sequences with missing taxonomic info to {MISS}\n')
else:
print()
################################################
########### MODULE DATABASE CLEAN-UP ###########
################################################
## function: dereplicating the database
def dereplicate(args):
INPUT = args.input
OUTPUT = args.output
METHOD = args.method
RANKS = args.ranks
## dereplicate strict (only unique sequences)
if METHOD == 'strict':
print(f'\nstrict dereplication of {INPUT}, only keeping unique sequences')
orig_count, derep_count = derep_strict(INPUT, OUTPUT)
print(f'found {orig_count} sequences in {INPUT}')
print(f'written {derep_count} sequences to {OUTPUT}\n')
## dereplicate single species (one sequence per species)
elif METHOD == 'single_species':
print(f'\ndereplicating {INPUT}, only keeping a single sequence per species')
fail, orig_count, derep_count = derep_single(INPUT, OUTPUT, RANKS)
if fail != 0:
print('aborting single species dereplication...')
else:
print(f'found {orig_count} sequences in {INPUT}')
print(f'written {derep_count} sequences to {OUTPUT}\n')
## dereplicate unique species (all unique sequences per species)
elif METHOD == 'uniq_species':
print(f'\ndereplicating {INPUT}, keeping all unique sequences per species')
fail, orig_count, derep_count = derep_uniq(INPUT, OUTPUT, RANKS)
if fail != 0:
print('aborting unique sequence species dereplication...')
else:
print(f'found {orig_count} sequences in {INPUT}')
print(f'written {derep_count} sequences to {OUTPUT}\n')
## unknown method specified
else:
print('\nplease specify one of the accepted dereplication methods: "strict", "single_species", "uniq_species"\n')
## function: sequence cleanup
def db_filter(args):
MINLEN = args.minlen
MAXLEN = args.maxlen
MAXNS = args.maxns
INPUT = args.input
OUTPUT = args.output
DISCARD = args.discard
ENV = args.env
SPEC = args.spec
NANS = args.nans
RANKS = args.ranks
## starting print statement
print(f'\nCRABS v{__version__}\nhttps://github.com/gjeunen/reference_database_creator\n\n')
## determine which parameters to filter on
envList, spList, nans = set_param2(ENV, SPEC, NANS, RANKS)
## read input file and parse data
keepList = []
discardList = []
minlenCount = 0
maxlenCount = 0
maxnCount = 0
envCount = 0
specCount = 0
nansCount = 0
try:
with tqdm(total = os.path.getsize(INPUT), desc = 'Filter INPUT: ', bar_format = '{desc}{percentage:.1f}%|{bar}|{elapsed}<{remaining}') as pbar:
with open(INPUT, 'r') as infile:
for line in infile:
pbar.update(len(line))
keepSeq = True
if len(line.split('\t')[-1].rstrip('\n')) < MINLEN:
keepSeq = False
minlenCount += 1
if len(line.split('\t')[-1].rstrip('\n')) > MAXLEN:
keepSeq = False
maxlenCount += 1
if line.split('\t')[-1].rstrip('\n').count('N') > MAXNS:
keepSeq = False
maxnCount += 1
if any(x in line.rpartition('\t')[0] for x in envList) == True:
keepSeq = False
envCount += 1
if any(x in line.rpartition('\t')[0] for x in spList) == True:
keepSeq = False
specCount += 1
if line.rpartition('\t')[0].count('\tnan\t') > nans:
keepSeq = False
nansCount += 1
if keepSeq == True:
keepList.append(line)
else:
discardList.append(line)
except TypeError:
print(f'FATAL ERROR: "-i", "--input" parameter not provided, aborting analysis...\n')
exit()
except FileNotFoundError:
print(f'FATAL ERROR: {INPUT} file not found, aborting analysis...\n')
exit()
## write output files
try:
if os.path.exists(OUTPUT) == True:
print(f'WARNING: the filename "{OUTPUT}" already exists in directory, not overwriting data...')
else:
with open(OUTPUT, 'w') as outfile:
for item in keepList:
outfile.write(item)
except TypeError:
print(f'WARNING: "-o", "--output" parameter not provided, not writing data to output file...\n')
try:
if os.path.exists(DISCARD) == True:
print(f'WARNING: the filename "{DISCARD}" already exists in directory, not overwriting data...')
else:
with open(DISCARD, 'w') as discardfile:
for item in discardList:
discardfile.write(item)
except TypeError:
pass
## write log
print(f'\nSUMMARY STATISTICS:\nNumber of sequences analysed: {len(keepList) + len(discardList)}')
print(f'Sequences kept: {len(keepList)} ({float("{:.2f}".format(len(keepList) / (len(keepList) + len(discardList)) * 100))}%)')
print(f'Sequences removed: {len(discardList)} ({float("{:.2f}".format(len(discardList) / (len(keepList) + len(discardList)) * 100))}%)')
print(f'Too short sequences: {minlenCount}')
print(f'Too long sequences: {maxlenCount}')
print(f'Sequences with too many "N": {maxnCount}')
print(f'Environmental sequences: {envCount}')
print(f'Sequences without proper species ID: {specCount}')
print(f'Sequences with too many undefined taxonomic levels: {nansCount}\n')
## function: db_subset
def db_subset(args):
INPUT = args.input
OUTPUT = args.output
SUBSET = args.subset
DB = args.db
## read in user-provided file with seq info
userlist = []
print(f'\nreading {DB} into memory')
with tqdm(total = os.path.getsize(DB)) as pbar:
with open(DB, 'r') as filein:
for line in filein:
pbar.update(len(line))
item = line.replace(' ', '_').rstrip('\n').upper()
userlist.append(item)
## subset the input file using "userlist"
if SUBSET == 'inclusion':
inclusionlist = []
count = 0
print(f'reading {INPUT} into memory and subsetting reference DB based on {DB}')
with tqdm(total = os.path.getsize(INPUT)) as pbar:
with open(INPUT, 'r') as infile:
for line in infile:
count = count + 1
pbar.update(len(line))
for item in userlist:
if item in line.upper():
inclusionlist.append(line)
print(f'found {count} sequences in {INPUT}')
inclusionset = set(inclusionlist)
with open(OUTPUT, 'w') as outfile:
for item in inclusionset:
outfile.write(item)
print(f'written {len(inclusionset)} sequences to {OUTPUT}\n')
elif SUBSET == 'exclusion':
exclusionlist = []
orig = []
count = 0
print(f'reading {INPUT} into memory and subsetting reference DB based on {DB}')
with tqdm(total = os.path.getsize(INPUT)) as pbar:
with open(INPUT, 'r') as infile:
for line in infile:
orig.append(line)
count = count + 1
pbar.update(len(line))
for item in userlist:
if item in line.upper():
exclusionlist.append(line)
print(f'found {count} sequences in {INPUT}')
exclusionset = set(exclusionlist)
final = [x for x in orig if x not in exclusionset]
with open(OUTPUT, 'w') as outfile:
for item in final:
outfile.write(item)
print(f'written {len(final)} sequences to {OUTPUT}\n')
else:
print(f'Invalid option for the "--subset" parameter was entered: "{SUBSET}". Please enter "inclusion" or "exclusion"\n')
################################################
############# MODULE VISUALISATION #############
################################################
## figure output
def visualization(args):
INPUT = args.input
OUTPUT = args.output
METHOD = args.method
LEVEL = args.level
SPECIES = args.species
TAXID = args.taxid
NAME = args.name
FWD = args.fwd
REV = args.rev
FWD_NAME = args.fwd_name
REV_NAME = args.rev_name
RAW = args.raw
TAXGROUP = args.taxgroup
RANKS = args.ranks
SUBSET = args.subset
## horizontal barchart
if METHOD == 'diversity':
tax_group_list, uniq_tax_group_list, species_dict, abort = split_db_by_taxgroup(INPUT, LEVEL, RANKS)
if abort == 'yes':
print('aborting visualization process...\n')
else:
sequence_counter = Counter(tax_group_list)
list_info_dict = num_spec_seq_taxgroup(uniq_tax_group_list, species_dict, sequence_counter)
sorted_info = sorted(list_info_dict, key = lambda i: (i['sequence']))
dict_len = len(sorted_info)
final_dict = sorted_info[dict_len - int(SUBSET) : dict_len]
figure = horizontal_barchart(final_dict, OUTPUT)
## length distribution
elif METHOD == 'amplicon_length':
amp_length_dict, abort = get_amp_length(INPUT, LEVEL, SUBSET, RANKS)
if abort == 'yes':
print('aborting visualization process...\n')
else:
figure = amplength_figure(amp_length_dict)
## completeness table
elif METHOD == 'db_completeness':
## check if taxonomic lineage includes species, genus, and family information
taxrank = str(RANKS).split('+')
species_position = 'n'
sp_count = 2
genus_position = 'n'
gen_count = 2
family_position = 'n'
fam_count = 2
for item in taxrank:
if item == 'species':
species_position = sp_count
else:
sp_count = sp_count + 1
for item in taxrank:
if item == 'genus':
genus_position = gen_count
else:
gen_count = gen_count + 1
for item in taxrank:
if item == 'family':
family_position = fam_count
else:
fam_count = fam_count + 1
if species_position == 'n' or genus_position == 'n' or family_position == 'n':
print(f'\ntaxonomic lineage should include species, genus, and family information for db_completeness')
print('aborting visualization process...\n')
else:
## read in the text file with species names
species_list = []
with open(SPECIES, 'r') as species_file:
for line in species_file:
species = line.rstrip('\n').replace(' ', '_')
species_list.append(species)
print(f'\nfound {len(species_list)} species of interest in {SPECIES}: {species_list}')
## retrieve taxonomic lineage
print(f'generating taxonomic lineage for {len(species_list)} species')
name, node, taxid = file_dmp_to_dict(NAME, TAXID)
species_taxid_dict, taxid_list = species_to_taxid(species_list, taxid)
lineage = lineage_retrieval(taxid_list, node, name)
final_dict = collections.defaultdict(list)
for k, v in species_taxid_dict.items():
final_dict[k] = lineage[v]
print(f'gathering data for {len(final_dict)} species\n')
## retrieve information about potential number of taxa shared with species of interest on genus and family level based on NCBI taxonomy files
table_info_dict = collections.defaultdict(dict)
for k, v in species_taxid_dict.items():
species = k
genus_count = 0
family_count = 0
## find genus taxids
if v in node:
genus = node[v][1]
## count number of species in genus
for k, v in node.items():
if v[1] == genus and v[0] == 'species':
genus_count = genus_count + 1
## find family taxids
if genus in node:
family = node[genus][1]
## count number of species in family
for k, v in node.items():
if v[1] == family and v[0] == 'genus':
genus = k
for key, value in node.items():
if value[1] == genus and value[0] == 'species':
family_count = family_count + 1
table_info_dict[species] = {'species' : species, 'genus_num_ncbi' : genus_count, 'family_num_ncbi' : family_count}
## retrieve information about number of taxa shared with species of interest on genus and family level in reference database
for k, v in final_dict.items():
species = k
genus = v[5]
family = v[4]
with open(INPUT, 'r') as file_in:
spec_db_count = []
genus_db_count = []
family_db_count = []
for line in file_in:
spec_db = line.split('\t')[species_position]
genus_db = line.split('\t')[genus_position]
family_db = line.split('\t')[family_position]
if spec_db == species:
if spec_db not in spec_db_count:
spec_db_count.append(spec_db)
if genus_db == genus:
if spec_db not in genus_db_count:
genus_db_count.append(spec_db)
if family_db == family:
if spec_db not in family_db_count:
family_db_count.append(spec_db)
for k, v in table_info_dict.items():
if k == species:
v['species_in_ref_DB'] = len(spec_db_count)
v['genus_num_ref_DB'] = len(genus_db_count)
v['family_num_ref_DB'] = len(family_db_count)
v['genus_list_ref_DB'] = genus_db_count
v['family_list_ref_DB'] = family_db_count
df = pd.DataFrame.from_dict(table_info_dict, orient = 'index')
df['Completeness_genus'] = df['genus_num_ref_DB'] / df['genus_num_ncbi'] * 100
df['Completeness_family'] = df['family_num_ref_DB'] / df['family_num_ncbi'] * 100
df = df[['species', 'species_in_ref_DB', 'genus_num_ref_DB', 'genus_num_ncbi', 'Completeness_genus', 'family_num_ref_DB', 'family_num_ncbi', 'Completeness_family', 'genus_list_ref_DB', 'family_list_ref_DB']]
df.to_csv(OUTPUT, sep = '\t', index = None)
## phylogenetic tree
elif METHOD == 'phylo':
## read in the text file with species names
species_list = []
with open(SPECIES, 'r') as species_file:
for line in species_file:
species = line.rstrip('\n').replace(' ', '_')
species_list.append(species)
print(f'\nfound {len(species_list)} species of interest in {SPECIES}: {species_list}')
## retrieve taxonomic lineage
print(f'generating taxonomic lineage for {len(species_list)} species')
name, node, taxid = file_dmp_to_dict(NAME, TAXID)
species_taxid_dict, taxid_list = species_to_taxid(species_list, taxid)
lineage = lineage_retrieval(taxid_list, node, name)
final_dict = collections.defaultdict(list)
for k, v in species_taxid_dict.items():
final_dict[k] = lineage[v]
print(f'gathering data for {len(final_dict)} species')
## gather sequences from database that share taxonomic rank
ranks = str(RANKS).split('+')
level_count = 'n'
count = 0
for item in ranks:
if item == LEVEL:
level_count = count
break
else:
count = count + 1
if level_count == 'n':
print(f'taxonomic level "{LEVEL}" not included in the taxonomic lineage')
print('aborting visualization process...\n')
else:
lin_count = 0
for item in ['superkingdom', 'phylum', 'class', 'order', 'family', 'genus', 'species']:
if item == LEVEL:
lin_pos = lin_count
break
else:
lin_count = lin_count + 1
for k, v in final_dict.items():
species = k
taxrank = v[lin_pos]
species_file = []
os.makedirs(f'phylo_visualization/{species}/{LEVEL}')
try:
os.remove(f'phylo_visualization/{species}/{LEVEL}/{species}_phylo.fasta')
except OSError:
pass
with open(INPUT, 'r') as file_in:
for line in file_in:
rank = line.split('\t')[count + 2]
print(rank)
if rank == taxrank:
species_file.append(line)
print(species_file)
for item in species_file:
if len(species_file) < 2:
abort = 'less'
elif len(species_file) > 100:
abort = 'more'
else:
abort = 'no'
header = '>' + item.split('\t')[0] + '_' + item.split('\t')[len(item.split('\t')) - 2]#.split(',')[2]
seq = item.rsplit('\t', 1)[1]
with open(f'phylo_visualization/{species}/{LEVEL}/{species}_phylo.fasta', 'a') as file_out:
file_out.write(header + '\n')
file_out.write(seq)
if abort == 'less':
print(f'only {len(species_file)} sequence in database that shares the {LEVEL} taxonomic rank with {species}, omitted from phylogenetic analysis.')
elif abort == 'more':
print(f'{len(species_file)} sequences in database that share the {LEVEL} taxonomic rank with {species}, omitted from phylogenetic analysis')
elif abort == 'no':
print(f'{len(species_file)} sequences in database that share the {LEVEL} taxonomic rank with {species}')
for species in species_list:
my_file = Path(f'phylo_visualization/{species}/{LEVEL}/{species}_phylo.fasta')
if my_file.is_file():
print(f'generating phylogenetic tree for {species}')
muscle_cline = MuscleCommandline(input = my_file, out = f'phylo_visualization/{species}/{LEVEL}/{species}_align.clw', diags = True, maxiters = 1, log = f'phylo_visualization/{species}/{LEVEL}/{species}_align_log.txt', clw = True)
muscle_cline()
with open(f'phylo_visualization/{species}/{LEVEL}/{species}_align.clw', 'r') as aln:
alignment = AlignIO.read(aln, 'clustal')
calculator = DistanceCalculator('identity')
Distance_matrix = calculator.get_distance(alignment)
constructor = DistanceTreeConstructor(calculator, 'nj')
tree = constructor.build_tree(alignment)
fig = plt.figure(figsize = (25,15), dpi = 100)
matplotlib.rc('font', size=12)
matplotlib.rc('xtick', labelsize=10)
matplotlib.rc('ytick', labelsize=10)
axes = fig.add_subplot(1, 1, 1)
Phylo.draw(tree, axes=axes, do_show = False)
fig.savefig(f'phylo_visualization/{species}/{LEVEL}/{species}_tree_figure.pdf')
print()
elif METHOD == 'primer_efficiency':
## generate dictionary of pre-in silico PCR file to search against
print(f'\ngenerating dictionary of sequences of {RAW}')
raw_dict = {}
count = 0
for record in SeqIO.parse(RAW, 'fasta'):
count = count + 1
raw_dict[record.id] = record.seq
print(f'written {count} sequences from {RAW} into a dictionary')