-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgotcha_beta_2
More file actions
2171 lines (1819 loc) · 97.6 KB
/
gotcha_beta_2
File metadata and controls
2171 lines (1819 loc) · 97.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
#####################################################################################
# #
# gotha catch'em all (envronimental DNA baits) #
# #
#####################################################################################
#notes Kevin;
# Taxon filtering in combination with clustering sequences
# bug notes
# python3 ../gotcha_git/gotcha/gotcha.3.0.1.py -bp ./bold-cli -t "Apis,Eucera,Ceratina" -m COI-5P -c 5 -o Bees_beta_3.1 -ft species -e -v -cl 0.99
# size selection bug
# new
# tree output with branch length.
# Fixed gap problem with selecting baits (no bait should have a gap)
# Fixed problem with node selection. There is a problem that sequence close to the root are placed on tips.
# Fixed, for each tip sequence look back into the tree to the closest ancestral node.
import re
import os
import re
import sys
import glob
import shutil
import os.path
import datetime
import argparse
import operator
import subprocess
from os import path
import pandas as pd
from tqdm import tqdm
from Bio import SeqIO
from Bio import AlignIO
from Bio.Seq import Seq
from Bio.SeqIO import FastaIO
from Bio.SeqRecord import SeqRecord
from Bio.Align.Applications import MafftCommandline
import ete3 #new v2.2.2
from ete3 import Tree #new v2.2.2
from statistics import mean #new v2.2.2
import statistics #new v2.3.2
from collections import Counter #new v2.2.2
from numpy import random # new v3
import matplotlib.pyplot as plt # new v3
import numpy as np
##################################################################################################### parsing arguments and setting variables
class Range(object):
def __init__(self, start, end):
self.start = start
self.end = end
def __eq__(self, other):
return self.start <= other <= self.end
def check_positive(value):
try:
value = int(value)
if value <= 0:
raise argparse.ArgumentTypeError("{} is not a positive integer".format(value))
except ValueError:
raise Exception("{} is not an integer".format(value))
return value
parser = argparse.ArgumentParser(prog='gotcha', description='gotcha version 1.0.0 built Feb 2023\ndeveloped by Kevin Nota & Giobbe Forni\n',add_help=False)
parser.formatter_class = lambda prog: argparse.RawTextHelpFormatter(prog, max_help_position=150)
formatter_class=argparse.RawTextHelpFormatter
man = parser.add_argument_group('MARKER')
man.add_argument('-m', '--marker', metavar='\b', choices=['COI-5P', 'COI-3P', 'rbcL', 'matK', 'ITS', 'coding' , 'noncoding'], help='can be COI/rbcL/matK/ITS or coding/noncoding using custom .fna/.aln')
man.add_argument('-c', '--code', metavar='\b', help='genetic code - e.g. 1 for plastid and nuclear, 5 for mitochondrial invertebrate')
bld = parser.add_argument_group('BOLD DOWNLOAD')
bld.add_argument('-t', '--taxa', metavar='\b', help='input taxa')
bld.add_argument('-g', '--geo', metavar='\b', default="", help='geographic location of samples')
bld.add_argument('-ft', '--filter_tax', metavar='\b', default="", choices=['species', 'genus', 'family'], help='can be species/genus/family - defeault is none')
bld.add_argument("-bp", "--boldcli_path", metavar='\b', default="bold-cli", help="path to bold-cli")
ctm = parser.add_argument_group('CUSTOM INPUTS')
ctm.add_argument('-cf', '--custom_fna', metavar='\b', default="", help='custom nucleotide sequences file (.fasta format)')
ctm.add_argument('-ca', '--custom_aln', metavar='\b', default="", help='custom nucleotide alignment file (.fasta format) - gotcha will jump to size selection')
ctm.add_argument('-cn', '--custom_nwk', metavar='\b', default="", help='custom newick file - tree can be multifurcating and can lack taxa')
par = parser.add_argument_group('BAITS SEARCH PARAMETERS')
par.add_argument('-fl', '--filter_len', metavar='\b', default=100, help='minimum amminoacids / nucleotides length - default is 100', type=check_positive)
par.add_argument('-sc', '--seq_collapse', metavar='\b', type=float, default=1, help='percent identity to collapse sequences - default is 1')
par.add_argument('-bc', '--bts_collapse', metavar='\b', type=float, default=1, help='percent identity to collapse baits - defeault is 1')
par.add_argument('-bl', "--baitlength", metavar='\b', type=int, default=80, help='lenght of the bait sequences - default is 80')
par.add_argument('-tl', "--tiling", metavar='\b', default=30, type=int, help='kmer tiling for ancestral node selection - default is 30') #changed the default from 10 to 30 (think most cases ~3x coverage is alright and for a 80mer, that would be ~30)
par.add_argument('-ds', "--distance", metavar='\b', type=float, default=0.09, help='maximal distance to the ancestral node - default is 0.09')
par.add_argument('-so', "--trim_seqoverlap", metavar='\b', default="", help='trimal param between 0 and 100 - if not specified will skip')
par.add_argument('-ro', "--trim_resoverlap", metavar='\b', default="", help='trimal param between 1 and 0 - if not specified will skip')
par.add_argument('-dt', "--dust_threshold", metavar='\b', default=10, help='score threshold for low complexity region masking - default is 10')
par.add_argument('-mf', "--max_farg_lenght", metavar='\b', default=3000, type=int, help='this value can restrain the selected fragment size by choosing the optimal fragment below this value, \
\ndefault will take the highest value if number of sequences multiplied by fragment size') #new in version 2.3.2
par.add_argument('-GC', "--GC_threshold", metavar='\b', default="0.30-0.70", help='GC range for bait filtering - default is 0.30-0.70')
par.add_argument('-ks', "--keep_short_sequences", help='keep short sequences in size selection step', action='store_true')
par.add_argument('-NS', "--no_size_selection", help='preforms size selection', action='store_false', default=True)
par.add_argument('-fs', '--fast', action='store_true', help='performs the fast baits search w/out ancestral state reconstruction')
par.add_argument('-mc', '--manual_check', action='store_true', help='stops prior to tree inference for a manual check of the alignment')
fal = parser.add_argument_group('VALIDATION')
fal.add_argument('-VR', "--run_validation", help='Run bait validation with simulated data', action='store_true')
fal.add_argument('-VO', "--run_validation_only", help='Run only the bait validation with simulated data', action='store_true')
fal.add_argument('-ns', "--n_simulated",metavar='\b', default=10000, type=int, help='number of reads to simulate')
fal.add_argument('-dp', "--distribution_par",metavar='\b', default="50:50:35", help='distribution for reads simulation min_read_length:mean:sd of normal distribution')
fal.add_argument('-mo', "--min_overlap", metavar='\b', default=20, type=int, help='min overlap read to bait to be considered in calculation')
otr = parser.add_argument_group('OTHER')
otr.add_argument("-h", "--help", action="help", help="show this help message and exit")
otr.add_argument("-path", default=".", help=argparse.SUPPRESS)
otr.add_argument('-o', '--out', metavar='\b', default="probes", help='basename of output file and folders - default is probes')
otr.add_argument('-v', '--verbose', action='store_false', help='keeps temporary folder and files')
otr.add_argument('-e', '--erase', action='store_true', help='erases and rewrites a pre existing output folder')
otr.add_argument('-th', '--threads', metavar='\b', type=check_positive, default=1, help='number of threads used for tree inference - default is 1')
otr.add_argument('--version', action='store_true', help="show program's version number")
args=parser.parse_args()
# fix output path so that it can handle "../"
args.out = re.sub("/$","", args.out)
def check_if_all_is_installed():
if args.version == 1:
print('\ngotcha version 5.0.0 built March 2023\ndeveloped by Kevin Nota & Giobbe Forni\n')
exit()
if args.boldcli_path != "bold-cli" :
args.boldcli_path = args.boldcli_path
rc = subprocess.call(['which', args.boldcli_path],stderr=subprocess.DEVNULL, stdout=subprocess.DEVNULL)
if rc != 0 and not args.custom_fna:
print('bold-cli\tmissing in path')
exit()
rc = subprocess.call(['which', 'baseml'],stderr=subprocess.DEVNULL, stdout=subprocess.DEVNULL)
if rc != 0:
print('baseml\tmissing in path')
exit()
rc = subprocess.call(['which', 'transeq'],stderr=subprocess.DEVNULL, stdout=subprocess.DEVNULL)
if rc != 0:
print('transeq\tmissing in path')
exit()
rc = subprocess.call(['which', 'cd-hit'],stderr=subprocess.DEVNULL, stdout=subprocess.DEVNULL)
if rc != 0:
print('cdhit\tmissing in path')
exit()
rc = subprocess.call(['which', 'iqtree'],stderr=subprocess.DEVNULL, stdout=subprocess.DEVNULL)
if rc != 0:
print('iqtree\tmissing in path')
exit()
rc = subprocess.call(['which', 'trimal'],stderr=subprocess.DEVNULL, stdout=subprocess.DEVNULL)
if rc != 0:
print('trimal\tmissing in path')
exit()
rc = subprocess.call(['which', 'translatorx'],stderr=subprocess.DEVNULL, stdout=subprocess.DEVNULL)
if rc != 0:
print('translatorx\tmissing in path')
exit()
rc = subprocess.call(['which', 'muscle'],stderr=subprocess.DEVNULL, stdout=subprocess.DEVNULL)
if rc != 0:
print('muscle\tmissing in path')
exit()
##################################################################################################### errors !!!
if not args.custom_fna and not args.custom_aln and (args.taxa is None):
print("\n WARNING! Either a custom alignment (--custom_fna) or a lineage to download from BOLD (--taxa) is required! \n")
quit()
if args.custom_fna and args.custom_aln:
print("\n WARNING! both custom sequences and alignment have been specified! \n")
quit()
if not args.custom_fna and (args.marker is None):
print("\n WARNING! When not using custom alignment --marker flags is required! \n")
quit()
if args.custom_nwk and (args.custom_fna is None):
print("\n WARNING! When using a custom tree (--custom_nwk) either custom sequences (--custom_fna) or alignment (--custom_aln) has to be specified! \n")
quit()
if args.erase == False and path.exists(args.out):
print("\n WARNING! An output folder with the same name already exists! Use --erase to overwrite \n")
quit()
elif args.erase == True and path.exists(args.out):
shutil.rmtree(args.out)
os.makedirs(args.out)
else:
os.makedirs(args.out)
if (args.code != None):
if int(args.code) not in range (1, 33):
print("\n WARNING! Unknown geneitc code has been specified - please refer to NCBI! \n")
quit()
if not 0.01 <= args.distance <= 0.2:
print("\n WARNING! A value between 0.01 and 0.2 should be specified for parameter distance! \n")
quit()
if not 1 >= args.seq_collapse >= 0.7:
print("\n WARNING! A value between 1 and 0.7 should be specified for parameter seq_collapse! \n")
quit()
if not 1 >= args.bts_collapse >= 0.7:
print("\n WARNING! A value between 1 and 0.7 should be specified for parameter bts_collapse! \n")
quit()
gc_thresholds=args.GC_threshold.split("-")
if float(min(gc_thresholds))<=0 and float(min(gc_thresholds))>=1 :
print("\n WARNING! GC threshold should be a float between 0-1")
if args.trim_seqoverlap != "" and args.trim_resoverlap == "":
print("\n WARNING! You have to specify both seqoverlap and resoverlap parameters for the trimal step \n")
quit()
if args.trim_seqoverlap == "" and args.trim_resoverlap != "":
print("\n WARNING! You have to specify both seqoverlap and resoverlap parameters for the trimal step \n")
quit()
if args.trim_seqoverlap != "":
if not 100 >= float(args.trim_seqoverlap) >= 1:
print("\n WARNING! A value between 100 and 1 should be specified for parameter seqoverlap! \n")
quit()
if args.trim_resoverlap != "":
if not 1 >= float(args.trim_resoverlap) >= 0:
print("\n WARNING! A value between 1 and 0 should be specified for parameter resoverlap! \n")
quit()
os.makedirs(args.out + "/tmp")
os.chdir(args.out + "/tmp")
##################################################################################################### define markers
marker_list=[]
if ( args.marker == "coding" ):
coding = True
if ( args.marker == "non-coding" ):
coding = False
if ( args.marker == "COI-5P" ):
marker_list=[ "COI-5P" ]
coding = True
if ( args.code == None ):
print("\n WARNING! a genetic code has to be specified when using a coding marker! \n")
quit()
if ( args.marker == "COI-3P" ):
marker_list=[ "COI-3P" ]
coding = True
if ( args.code == None ):
print("\n WARNING! a genetic code has to be specified when using a coding marker! \n")
quit()
elif ( args.marker == "rbcL" ):
marker_list=[ "rbcL", "rbcl" , "RBCL" , "Rbcl" , "rbcla" , "rbcl-a" ]
coding = True
if ( args.code == None ):
print("\n WARNING! a genetic code has to be specified when using a coding marker! \n")
quit()
elif ( args.marker == "matK" ):
marker_list=[ "matK" , "matk" , "MATK" ]
coding = True
if ( args.code == None ):
print("\n WARNING! a genetic code has to be specified when using a coding marker! \n")
quit()
elif ( args.marker == "ITS" ):
marker_list=[ "ITS" , "its" ]
coding = False
if ( args.code != None ):
print("\n WARNING! a genetic code has been specified when using a non-coding marker! \n")
quit()
if ( args.custom_fna != "" ) and ( args.marker == "coding" ):
coding = True
if ( args.code == None ):
print("\n WARNING! a genetic code has to be specified when using a coding marker! \n")
quit()
elif ( args.custom_fna != "" ) and ( args.marker == "noncoding" ):
coding = False
if ( args.code != None ):
print("\n WARNING! a genetic code has been specified for a non-coding marker! \n")
quit()
if ( args.custom_aln != "" ) and ( args.marker == "coding" ):
coding = True
if ( args.code == None ):
print("\n WARNING! a genetic code has to be specified when using a coding marker! \n")
quit()
elif ( args.custom_aln != "" ) and ( args.marker == "noncoding" ):
coding = False
if ( args.code != None ):
print("\n WARNING! a genetic code has been specified for a non-coding marker! \n")
quit()
print("\nanalysis started on" , datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"), "\n")
return coding, marker_list
def write_log_file_01():
gc_thresholds=args.GC_threshold.split("-")
with open("log.txt", "a+") as log:
log.write("# analysis started on " + datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") + "\n")
# INPUTS
log.write("\n\n\t INPUTS:" + "\n\n")
if ( args.custom_fna != "" ):
log.write("\t BOLD TAXONOMY \t\tN" + "\n")
log.write("\t CUSTOM SEQUENCES \tY" + "\n")
log.write("\t CUSTOM ALIGNMENT \tN" + "\n")
elif ( args.custom_aln != "" ):
log.write("\t BOLD TAXONOMY \t\tN" + "\n")
log.write("\t CUSTOM SEQUENCES \tN" + "\n")
log.write("\t CUSTOM ALIGNMENT \tY" + "\n")
else:
if ( args.geo == "" ):
log.write("\t BOLD TAXONOMY \t\t" + str(args.taxa) + "\n")
log.write("\t GEOGRAPHY \t\tN" + "\n")
log.write("\t CUSTOM SEQUENCES \tN" + "\n")
log.write("\t CUSTOM ALIGNMENT \tN" + "\n")
else:
log.write("\t BOLD TAXONOMY \t\t" + str(args.taxa) + "\n")
log.write("\t GEOGRAPHY \t\t" + args.geo + "\n")
log.write("\t CUSTOM SEQUENCES \tN" + "\n")
log.write("\t CUSTOM ALIGNMENT \tN" + "\n")
if ( args.custom_nwk == "" ):
log.write("\t CUSTOM TREE \t\tN" + "\n")
else:
log.write("\t CUSTOM TREE \t\tY" + "\n")
log.write("\t MARKER \t\t" + str(args.marker) + "\n")
if (coding == True):
log.write("\t GEN CODE \t\t" + str(args.code) + "\n")
else:
log.write("\t GEN CODE \t\t" + "-" + "\n")
if (args.fast == False):
log.write("\t FAST MODE \t\t" + "N" + "\n")
else:
log.write("\t FAST MODE \t\t" + "Y" + "\n")
# PARAMETER
log.write("\n\n\t PARAMETERS:" + "\n\n")
if ( args.filter_tax == "" ):
log.write("\t TAXONOMIC FILTER \tN" + "\n")
else:
log.write("\t TAXONOMIC FILTER \t" + str(args.filter_tax) + "\n")
log.write("\t MIN MARKER LENGTH \t" + str(args.filter_len) + "\n")
log.write("\t MAX MARKER IDENTITY \t" + str(args.seq_collapse) + "\n")
log.write("\t BAITS LENGTH \t\t" + str(args.baitlength) + "\n")
log.write("\t BAITS TILING \t\t" + str(args.tiling) + "\n")
log.write("\t GC THRESHOLD \t\t" + min(gc_thresholds) + "-" + max(gc_thresholds) + "\n")
if ( args.trim_seqoverlap != "" ) and ( args.trim_resoverlap != "" ):
log.write("\t SEQ OVERLAP \t\t" + str(args.trim_seqoverlap) + "\n")
log.write("\t RES OVERLAP \t\t" + str(args.trim_resoverlap) + "\n")
else:
log.write("\t TRIMAL \t\tN" + "\n")
log.write("\t DUST TRESHOLD \t\t" + str(args.dust_threshold) + "\n")
def bold_download():
if args.boldcli_path != "bold-cli" :
args.boldcli_path = "../../" + args.boldcli_path
if ( args.geo == "" ):
print("downloading" , args.marker , "sequences for taxa" , args.taxa)
subprocess.run([args.boldcli_path , "-taxon" , args.taxa , "-marker" , args.marker , "-output" , "tmp.bold"] , stdout=subprocess.DEVNULL , stderr=subprocess.DEVNULL)
if os.path.getsize("tmp.bold") == 0 :
print("\n WARNING! The BOLD search for marker" , args.marker , "and taxa" , args.taxa , "returned nothing! \n")
quit()
else:
print("downloading" , args.marker , "sequences for taxa" , args.taxa, "from" , args.geo)
subprocess.run([args.boldcli_path , "-taxon" , args.taxa , "-marker" , args.marker , "-geo" , args.geo, "-output" , "tmp.bold"] , stdout=subprocess.DEVNULL , stderr=subprocess.DEVNULL)
if os.path.getsize("tmp.bold") == 0 :
print("\n WARNING! The BOLD search for marker" , args.marker , "and taxa" , args.taxa , "in" , args.geo , "returned nothing! \n")
quit()
num0 = sum(1 for line in open('tmp.bold', errors='ignore'))
print("# downloaded: ", num0)
with open("log.txt", "a+") as log:
log.write("\n\n\t FILTERING:" + "\n\n")
log.write("\t " + str(num0) + "\t starting sequences" + "\n")
log.close()
with open("tmp.bold", 'r', errors='ignore') as file:
if 'Fatal Error' in file.read():
print("\n WARNING! The taxonomy specified appears to be not correct! \n")
quit()
##################################################################################################### filter marker and taxonomy
tmp_1_fasta=[]
if (args.filter_tax != ""):
print("filtering sequences with" , args.filter_tax , "identification")
else:
print("skipping taxonomic filtering")
with open("tmp.bold", 'r', errors='ignore') as file:
header = file.readline()
for l in file :
sl = l.split('\t')
if (args.filter_tax == "family"):
if sl[15]:
header = (">" + sl[0])
seq = sl[71].replace('-','')
if sl[69] in marker_list:
tmp_1_line=[header, seq]
tmp_1_fasta.append(tmp_1_line)
elif (args.filter_tax == "genus"):
if sl[19]:
header = (">" + sl[0])
seq = sl[71].replace('-','')
if sl[69] in marker_list:
tmp_1_line=[header, seq]
tmp_1_fasta.append(tmp_1_line)
elif (args.filter_tax == "species"):
if sl[21]:
header = (">" + sl[0])
seq = sl[71].replace('-','')
if sl[69] in marker_list:
tmp_1_line=[header, seq]
tmp_1_fasta.append(tmp_1_line)
else:
header = (">" + sl[0])
seq = sl[71].replace('-','')
if sl[69] in marker_list:
tmp_1_line=[header, seq]
tmp_1_fasta.append(tmp_1_line)
with open('tmp1.fna', 'w') as tmp_1:
for line in tmp_1_fasta:
for element in line:
tmp_1.write(str(element) + '\n')
if os.path.getsize("tmp1.fna") == 0 :
print("\n WARNING! No sequence passed the taxonomic filter! \n")
num1 = len([1 for line in open("tmp1.fna") if line.startswith(">")]) # count tmp1.fna
print("# kept: ", num1)
with open("log.txt", "a+") as log:
log.write("\t " + str(num1) + "\t after taxonomic filtering" + "\n")
log.close()
def seq_quality_filters():
if (args.custom_fna != ""):
print("custom sequences detected\n")
custom_fna = "../../" + args.custom_fna
shutil.copy(custom_fna,"tmp1.fna")
if (args.custom_aln == ""):
print("collapsing identical sequences with a percent identitiy of", args.seq_collapse)
subprocess.run(["cd-hit","-i","tmp1.fna","-o","tmp2a.fna","-c", str(args.seq_collapse)] , stdout=subprocess.DEVNULL , stderr=subprocess.DEVNULL)
num2 = len([1 for line in open("tmp2a.fna") if line.startswith(">")]) # count tmp2.fna
print("# kept: ", num2)
with open("log.txt", "a+") as log:
log.write("\t " + str(num2) + "\t after identity collapse" + "\n")
log.close()
##################################################################################################### remove sequences with non ATGC nucleotides
print("removing sequences with non ATGC nucleotides")
selected_seqs_ns = list()
tmp2b_fna=open("tmp2b.fna",'w')
for record in SeqIO.parse("tmp2a.fna", "fasta"):
# if record.seq.count('N') == 0:
matches = ['B','D','E','F','H','I','J','K','L','M','N','O','P','Q','R','S','U','V','W','X','Y','Z','b','d','e','f','h','i','j','k','l','m','n','o','p','q','r','s','u','v','w','x','y','z']
if not any(x in record.seq.upper() for x in matches):
selected_seqs_ns.append(record)
nseq=(len(selected_seqs_ns))
SeqIO.write(selected_seqs_ns, tmp2b_fna , "fasta")
tmp2b_fna.close()
print("# kept: ", nseq)
with open("log.txt", "a+") as log:
log.write("\t " + str(nseq) + "\t removing sequences with non ATGC nucleotides" + "\n")
log.close()
##################################################################################################### length cutoff
print("filtering sequences with a minimum length of", args.filter_len)
selected_seqs_nt = list()
tmp2_fna=open("tmp2.fna",'w')
for record in SeqIO.parse("tmp2b.fna", "fasta"):
if len(record.seq) >= int(args.filter_len):
selected_seqs_nt.append(record)
nseq=(len(selected_seqs_nt))
SeqIO.write(selected_seqs_nt, tmp2_fna , "fasta")
print("# kept: ", nseq)
tmp2_fna.close()
with open("log.txt", "a+") as log:
log.write("\t " + str(nseq) + "\t after length filter" + "\n")
log.close()
##################################################################################################### too few sequences to proceed?
nseq = len([1 for line in open("tmp2.fna") if line.startswith(">")])
if nseq < 4:
print("\n WARNING! Less than 4 sequences passed the filtering steps! \n" )
quit()
##################################################################################################### if the marker is coding
if (coding == True and args.custom_aln == ""):
#print("aligning sequences")
# adjust direction with mafft
with open('tmp3.fna', 'w') as tmp3_fna, open('tmp2.fna', 'r') as tmp2_fna:
if 'MAFFT_BINARIES' in os.environ:
os.environ.pop('MAFFT_BINARIES')
subprocess.call(["mafft" , "--thread", str(args.threads), "--adjustdirection" , "--reorder" , "tmp2.fna"], stdout=tmp3_fna, stderr=subprocess.DEVNULL)
# remove "N" and "-"
with open("tmp4.fna", "w") as tmp4_fna:
for record in SeqIO.parse("tmp3.fna", "fasta"):
record.seq = record.seq.replace("-", "")
record.seq = record.seq.replace("n", "")
SeqIO.write(record, tmp4_fna, "fasta")
# protein-guided nucleotide alignment with translatorx
with open('tmp4.fna', 'r') as tmp4_fna, open('translatorx.log', 'w') as translatorx_log:
subprocess.call(["translatorx" , "-i" , "tmp4.fna", "-t", "T", "-o", "tmp", "-c", args.code], stdout=translatorx_log, stderr=translatorx_log)
os.rename("tmp.nt_ali.fasta", "tmp5.fna")
# translate sequences to find stop codons
with open('tmp5.fna', 'r') as tmp5_fna:
subprocess.call(["transeq" , "-sequence" , "tmp5.fna", "-outseq", "translated4stop.fna", "-table", args.code], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
# find sequences with stopcodons
identifiers = set()
with open('translated4stop.fna', 'r') as translated4stop_fna:
for seq_record in SeqIO.parse(translated4stop_fna, "fasta"):
if "*" in (seq_record.seq[0:(len(seq_record.seq)-2)]):
identifiers.add(seq_record.id[:-2])
print("removing sequences with stop codons")
# find sequences with stopcodons
with open('tmp5.fna', 'r') as tmp5_fna, open('tmp6.fna', 'w') as tmp6_fna:
records = SeqIO.parse(tmp5_fna, 'fasta')
for record in records:
if record.id not in identifiers:
SeqIO.write(record, tmp6_fna, 'fasta')
num6 = len([1 for line in open("tmp6.fna") if line.startswith(">")]) # count tmp6.fna
print("# kept: ", num6)
with open("log.txt", "a+") as log:
log.write("\t " + str(num6) + "\t the removal of sequences with stop codons" + "\n")
log.close()
os.rename("tmp6.fna", "tmp.aln")
##################################################################################################### if the marker is not coding
if (coding == False and args.custom_aln == ""):
print("aligning non-coding sequences")
with open('tmp.aln', 'w') as tmp_aln, open('tmp2.fna', 'r') as tmp2_fna:
if 'MAFFT_BINARIES' in os.environ:
os.environ.pop('MAFFT_BINARIES')
subprocess.call(["mafft" , "--thread", str(args.threads) , "--adjustdirection" , "tmp2.fna"], stdout=tmp_aln, stderr=subprocess.DEVNULL)
##################################################################################################### reformat after mafft adjustdirection
os.rename('tmp.aln', 'tmptmp.aln')
tmp_aln=open("tmp.aln",'w')
for record in SeqIO.parse("tmptmp.aln", "fasta"):
record.description = (record.id).replace('_R_', '')
record.id=record.description
SeqIO.write(record, tmp_aln , "fasta")
tmp_aln.close()
os.remove('tmptmp.aln')
##################################################################################################### can enter custom .aln
if (args.custom_aln != ""):
print("custom alignment detected")
custom_aln = "../../" + args.custom_aln
shutil.copy(custom_aln,"tmp.aln")
num = len([1 for line in open("tmp.aln") if line.startswith(">")])
def size_selection():
input_sequences=list(SeqIO.parse("tmp.aln", "fasta")) # path to the fasta file
fragment_selections= pd.DataFrame()
#counting the number of gaps in the alignment file
gaps = pd.DataFrame()
threshold_list=[]
number_of_sequences_list=[]
seq_length_list=[]
number_X_length_list=[]
start_position_list=[]
end_position_list=[]
position_list=[]
proportion_gaps=[]
print("\nselecting optimal fragment size based on", len(input_sequences),"sequences :")# "sequences with max length of",len(input_sequences[0].seq), "\n")
#print("\nnumber of input sequences =", len(input_sequences))
#print("max sequences lenght =", len(input_sequences[0].seq))
#print("calculating missing data")
#progress=tqdm(total=None, desc="Alignment scanner ")
for p in range(len(input_sequences[0].seq)):
gap_positions = 0
for i in range(len(input_sequences)):
if (input_sequences[i].seq[p] == "-"):
gap_positions += 1
#data = pd.Series({'position':p, 'proportion gaps':gap_positions/len(input_sequences)})
position_list.append(p)
proportion_gaps.append(gap_positions/len(input_sequences))
#gaps=gaps.append(pd.DataFrame(data), ignore_index=True)
#gaps= pd.concat([gaps, data.to_frame().T], ignore_index=True)
#progress.update()
#progress.close()
gaps=pd.DataFrame({'position':position_list, 'proportion gaps':proportion_gaps})
#progress=tqdm(total=None, desc="Calculating distance = ")
for treshold in range(0, 100):
threshold_found=False
i=0
# find the first and last position where thresholds values are met
# tressholds that are tested are 0-1 with 0.01 increments (101 loops)
while not (threshold_found==True) :
if (gaps.loc[i,"proportion gaps"]<=float(treshold/100)):
threshold_found=True
start_position=int(gaps.loc[i,"position"])
i=i+1
if(i==len(gaps)):
threshold_found=True
start_position=0
threshold_found=False
i=len(gaps)-1
while not (threshold_found==True) :
if (gaps.loc[i,"proportion gaps"]<=float(treshold/100)):
threshold_found=True
finish_position=int(gaps.loc[i,"position"])
i=i-1
if(i==0):
threshold_found=True
finish_position=0
count=0
lenght_no_gaps=[]
# this counts the number of sequences within the threshold with no gaps (-)
for i in range(len(input_sequences)):
if(len(re.findall("^-|-$|^N|N$", str(input_sequences[i].seq[start_position:finish_position])))==0):
count+=1
lenght_no_gaps.append(len(re.sub("-", "", str(input_sequences[i].seq[start_position:finish_position]))))
if len(lenght_no_gaps) == 0 :
continue
threshold_list.append(str(treshold)+"%")
number_of_sequences_list.append(count)
seq_length_list.append(int(re.sub(",.*", "", re.sub("\(", "", str(Counter(lenght_no_gaps).most_common()[0])))))
number_X_length_list.append(int(re.sub(",.*", "", re.sub("\(", "", str(Counter(lenght_no_gaps).most_common()[0]))))*count)
start_position_list.append(start_position)
end_position_list.append(finish_position)
#data = pd.Series({'threshold':str(treshold)+"%",
# 'number of sequences':count,
# 'seq_length':int(re.sub(",.*", "", re.sub("\(", "", str(Counter(lenght_no_gaps).most_common()[0])))), #statistics.mode(lenght_no_gaps),
# 'number * lenght':count*len(input_sequences[i].seq[start_position:finish_position]),
# 'start position':start_position,
# 'finish_position':finish_position})
#fragment_selections = fragment_selections.append(pd.DataFrame(data), ignore_index=True)
#fragment_selections = fragment_selections.append(pd.DataFrame(data), ignore_index=True)
#fragment_selections = pd.concat([fragment_selections, data.to_frame().T], ignore_index=True)
#progress.update()
fragment_selections = pd.DataFrame({'threshold':threshold_list,
'number of sequences':number_of_sequences_list,
'seq_length':seq_length_list,
'number * lenght':number_X_length_list,
'start position':start_position_list,
'finish_position':end_position_list})
fragment_selections.to_csv("size_selection_summary.df", sep="\t") # new version 2.3.2
#progress.close()
# loop to find the most optimal fragment lenght
find_optimal_fragment=False
i=0
fragment_selections = fragment_selections.loc[fragment_selections['seq_length'] <= args.max_farg_lenght] # new version 2.3.2 (gaps is a problem here)
while not (find_optimal_fragment==True):
if((fragment_selections.loc[i,"number * lenght"]==fragment_selections['number * lenght'].max())==True):
#optimal_threshold=fragment_selections.loc[i, 'threshold']
find_optimal_fragment=True
start_position=fragment_selections.loc[i,'start position']
finish_position=fragment_selections.loc[i,'finish_position']
selected_size=fragment_selections.loc[i,'seq_length']
seq_count=fragment_selections.loc[i, 'number of sequences']
i=i+1
print(selected_size)
while not (((finish_position-start_position)/3.0).is_integer()):
finish_position-=1
lenght=((finish_position-start_position)/3.0)
#correcting size for the triplet cutoff (prevent sequences being lost due to gaps)
#count_eng_gap=0
frag_count=0
while not (seq_count<=(frag_count)):
#count_eng_gap=0
frag_count=0
for i in range(len(input_sequences)):
#if(len(re.findall("-$", (str(input_sequences[i].seq[start_position:finish_position]))))!=0):
# count_eng_gap+=1
# ^-|-$|^N|N$
if(len(re.findall("$-|$N", (str(input_sequences[i].seq[start_position:finish_position]))))==0):
frag_count+=1
if seq_count>=frag_count :
finish_position=finish_position-3
frag_count=0
while not (seq_count<=(frag_count)):
#count_eng_gap=0
frag_count=0
for i in range(len(input_sequences)):
#if(len(re.findall("-$", (str(input_sequences[i].seq[start_position:finish_position]))))!=0):
# count_eng_gap+=1
# ^-|-$|^N|N$
if(len(re.findall("^-|^N", (str(input_sequences[i].seq[start_position:finish_position]))))==0):
frag_count+=1
if seq_count>=frag_count :
start_position=start_position+3
#Creating new fasta file with original labels but new sequence
new_fasta=list()
frag_count=0
for i in range(len(input_sequences)):
if args.keep_short_sequences == True :
new_seq=SeqRecord(Seq(str(input_sequences[i].seq[start_position:finish_position])),
id=input_sequences[i].id,
description="")
new_fasta.append(new_seq)
frag_count+=1
if args.keep_short_sequences != True :
if(len(re.findall("^-|-$|^N|N$", str(input_sequences[i].seq[start_position:finish_position])))==0): #removes all sequences that start with w gap, and sequences that contain N's
new_seq=SeqRecord(Seq(str(input_sequences[i].seq[start_position:finish_position])),
id=input_sequences[i].id,
description="")
new_fasta.append(new_seq)
frag_count+=1
#Writing the new fasta to tmp folder
SeqIO.write(new_fasta, "size_selected.fasta", "fasta") #path to the output file
os.rename("tmp.aln", "no_size_selection.fasta")
shutil.copy('size_selected.fasta', 'tmp.aln')
#os.rename("size_selected.fasta", "tmp.aln")
#print("optimal missing data threshold = "+str(optimal_threshold)) #removed v2.3.2
print("#\tkept:\t\t"+str(frag_count))
print("#\tomitted:\t "+str(len(input_sequences)-frag_count))
print("#\tfragment size:\t "+str(selected_size)+"\n")
#print("start position = "+str(start_position)) #removed v2.3.2
#print("end position = "+str(finish_position)) #removed v2.3.2
num7=str(frag_count)
with open("log.txt", "a+") as log:
log.write("\t " + str(num7) + "\t after size selection" + "\n")
log.close()
def extra_trimal_fiter():
print("Misaligned sequences removal step with seqoverlap", args.trim_seqoverlap, "and resoverlap", args.trim_resoverlap)
with open('trimal.aln', 'w') as trimal_aln, open('tmp.aln', 'r') as tmp_aln, open('trimal.log', 'w') as trimal_log:
subprocess.call(["trimal" , "-in" , "tmp.aln", "-out", "trimal.aln", "-noallgaps", "-seqoverlap",args.trim_seqoverlap, "-resoverlap", args.trim_resoverlap], stdout=trimal_log, stderr=trimal_log)
os.rename('trimal.aln' , 'tmp.aln')
if os.stat('tmp.aln').st_size == 0:
print("\nThe misaligned sequence removal step eliminated all sequences - use different sequoverlap and resoverlap parameters!")
exit()
num8 = len([1 for line in open("tmp.aln") if line.startswith(">")]) # count 8
print("# kept: ", num8)
with open("log.txt", "a+") as log:
log.write("\t " + str(num8) + "\t after the removal of misaligned sequences" + "\n")
log.close()
def standard_trimal_filter():
with open('trimal.aln', 'w') as trimal_aln, open('tmp.aln', 'r') as tmp_aln, open('trimal.log', 'w') as trimal_log:
subprocess.call(["trimal" , "-in" , "tmp.aln", "-out", "trimal.aln", "-noallgaps"], stdout=trimal_log, stderr=trimal_log)
os.rename('trimal.aln' , 'tmp.aln')
def tree_inverence():
if (args.custom_nwk != ""):
custom_tre = '../../' + args.custom_nwk
shutil.copy(custom_tre, './custom.tre')
custom_tre = './custom.tre'
brlen = re.findall(":[0-9]*.[0-9]*", custom_tre)
with open(custom_tre, 'r') as tre_file:
if brlen != "":
content = tre_file.read()
tre_file = re.sub(":[0-9]*.[0-9]*", '', content )
nwk_sp_list=tre_file.replace(',', ' ').replace('(', '').replace(')', '').replace(';', '').split()
aln_sp_list = []
for record in SeqIO.parse("tmp.aln", "fasta"):
aln_sp_list.append(record.id)
check = all(sp in aln_sp_list for sp in nwk_sp_list)
if check == False:
print("custom nwk detected with more species in the tree than sequences - these tips will be pruned.")
toprune_list = list(set(nwk_sp_list) - set(aln_sp_list))
with open('toprune.lst', 'w') as f:
for line in toprune_list:
f.write(line)
f.write('\n')
tmp_rscript_pruning=[]
tmp_rscript_pruning.append("library(phytools)")
tmp_rscript_pruning.append("tree <- read.newick(\"custom.tre\")")
tmp_rscript_pruning.append("spec <- read.table(\"toprune.lst\")")
tmp_rscript_pruning.append("ptre<-drop.tip(tree,tree$tip.label[match(spec$V1, tree$tip.label)])")
tmp_rscript_pruning.append("write.tree(ptre, file=\"custom.tre\")")
with open('tmp_rscript_pruning.R', 'w') as tmp_rscript_pruning_file:
for line in tmp_rscript_pruning:
tmp_rscript_pruning_file.write(line + '\n')
with open('tmp_rscript_pruning.R_log', 'w') as tmp_rscript_pruning_log:
subprocess.run(["Rscript" , "tmp_rscript_pruning.R"], stdout=tmp_rscript_pruning_log, stderr=tmp_rscript_pruning_log)
elif len(nwk_sp_list) == len(aln_sp_list) and check == True:
print("custom nwk detected with 1:1 species match to sequences - skipping topology inference.")
elif len(nwk_sp_list) < len(aln_sp_list) and check == True:
print("custom nwk detected with fewer species than sequences - using constrained topology.")
##################################################################################################### if the custom .nwk is coding
if (coding == True):
tmp_partitions=[]
filename = "tmp.aln"
format = "fasta"
tmp_aln = AlignIO.read("tmp.aln", "fasta")
tmp_partitions.append("DNA, st = 1-%i\\3" % tmp_aln.get_alignment_length())
tmp_partitions.append("DNA, nd = 2-%i\\3" % tmp_aln.get_alignment_length())
tmp_partitions.append("DNA, rd = 3-%i\\3" % tmp_aln.get_alignment_length())
with open('tmp.partitions', 'w') as tmp_partitions_file:
for line in tmp_partitions:
tmp_partitions_file.write(line + '\n')
subprocess.run(["iqtree" , "-s" , "tmp.aln" , "-nt" , str(args.threads) , "-spp" , "tmp.partitions" , "-g" , "custom.tre", "-fast"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
def_tre_file = args.out + ".nwk"
os.rename('tmp.partitions.treefile' , def_tre_file)
def_aln_file = args.out + ".aln"
os.rename('tmp.aln' , def_aln_file)
##################################################################################################### if the custom .nwk is not coding
if (coding == False):
with open('tmp.nwk', 'w') as tmp_nwk :
subprocess.run(["iqtree" , "-s" , "tmp.aln" , "-nt" , str(args.threads) , "-g" , custom_tre, "-fast"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
def_tre_file = args.out + ".nwk"
os.rename('tmp.aln.treefile' , def_tre_file)
def_aln_file = args.out + ".aln"
os.rename('tmp.aln' , def_aln_file)
##################################################################################################### inferring a coding marker tree
elif (args.custom_nwk == ""):
print("\ninferring tree\n")
if (coding == True):
tmp_partitions=[]
filename = "tmp.aln"
format = "fasta"
tmp_aln = AlignIO.read("tmp.aln", "fasta")
tmp_partitions.append("DNA, st = 1-%i\\3" % tmp_aln.get_alignment_length())
tmp_partitions.append("DNA, nd = 2-%i\\3" % tmp_aln.get_alignment_length())
tmp_partitions.append("DNA, rd = 3-%i\\3" % tmp_aln.get_alignment_length())
with open('tmp.partitions', 'w') as tmp_partitions_file:
for line in tmp_partitions:
tmp_partitions_file.write(line + '\n')
with open('tmp.nwk', 'w') as tmp_nwk :
subprocess.run(["iqtree" , "-s" , "tmp.aln" , "-nt" , str(args.threads) , "-spp" , "tmp.partitions", "-fast"], stdout=tmp_nwk, stderr=subprocess.DEVNULL)
def_tre_file = args.out + ".nwk"
os.rename('tmp.partitions.treefile' , def_tre_file)
def_aln_file = args.out + ".aln"
os.rename('tmp.aln' , def_aln_file)
##################################################################################################### inferring a not coding marker tree
if (coding == False):
with open('tmp.nwk', 'w') as tmp_nwk :
subprocess.run(["iqtree" , "-s" , "tmp.aln" , "-nt" , str(args.threads), "-fast"], stdout=tmp_nwk, stderr=subprocess.DEVNULL)
def_tre_file = args.out + ".nwk"
os.rename('tmp.aln.treefile' , def_tre_file)
def_aln_file = args.out + ".aln"
os.rename('tmp.aln' , def_aln_file)
##################################################################################################### ancestral sequences inference
if (coding == True):
print("inferring ancestral sequences using genetic code" , args.code , "\n")
if (coding == False):
print("inferring ancestral sequences\n")
tmp_ctl=[]
aln_line="seqfile = " + def_aln_file
tmp_ctl.append(aln_line)
tmp_ctl.append("outfile = tmp_baseml.out")
tre_line="treefile = " + def_tre_file
tmp_ctl.append(tre_line)
tmp_ctl.append("noisy = 3")
tmp_ctl.append("verbose = 1")
tmp_ctl.append("runmode = 0")
tmp_ctl.append("model = 7")
tmp_ctl.append("Mgene = 0")
tmp_ctl.append("clock = 0")
tmp_ctl.append("fix_kappa = 0")
tmp_ctl.append("kappa = 2.5")
tmp_ctl.append("fix_alpha = 1")
tmp_ctl.append("alpha = 0.")
tmp_ctl.append("Malpha = 0")
tmp_ctl.append("ncatG = 5")
tmp_ctl.append("fix_rho = 1")
tmp_ctl.append("rho = 0.")
tmp_ctl.append("nparK = 0")
tmp_ctl.append("nhomo = 0")
tmp_ctl.append("getSE = 0")
tmp_ctl.append("RateAncestor = 1")
tmp_ctl.append("Small_Diff = 1e-6")
tmp_ctl.append("cleandata = 0")
if coding == True :
icode = int(args.code) - 1
# icode_line="icode = " + str(icode)
icode_line="icode = 11"
tmp_ctl.append(icode_line)
tmp_ctl.append("fix_blength = 2")
tmp_ctl.append("method = 0")
with open('tmp.ctl', 'w') as tmp_ctl_file:
for line in tmp_ctl:
tmp_ctl_file.write(line + '\n')
with open('tmp.nwk', 'w') as tmp_nwk, open('tmp_baseml.log', 'w') as tmp_baseml_log:
subprocess.run(["baseml" , "tmp.ctl"], stdout=tmp_baseml_log, stderr=subprocess.DEVNULL)
tmp_baseml_log = './tmp_baseml.log'
baseml_error = re.findall("stop codon TAA", tmp_baseml_log)
if(len(baseml_error) >= 1):