-
Notifications
You must be signed in to change notification settings - Fork 1
/
mbctools.py
2706 lines (2362 loc) · 172 KB
/
mbctools.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/python3
"""mbctools a cross-platform toolkit to make use of VSEARCH easier and interactive, thus helping analyze
metabarcoding data in the best conditions. It assumes VSEARCH is pre-installed and consists in the following MAIN MENU:
1 -> INITIAL ANALYSIS (mandatory)
merging, dereplication, clustering, chimera detection, affiliation of clusters to loci, sequence re-orientation
2 -> PRIMER REMOVAL AND SELECTION OF MINIMUM SEQUENCE ABUNDANCE LEVELS ACCORDING TO USER-DEFINED THRESHOLDS
3 -> GENERATION OF A UNIQUE SEQUENCE FILE FOR EACH LOCUS (comprising all samples' data)
4 -> EXPORTING ANALYSIS RESULTS INTO metaXplor FORMAT
Option 1 offers the following submenu:
1 -> INITIAL ANALYSIS (mandatory)
1a -> Re-analyze all loci, from the clustering step, modifying parameters
1b -> Re-analyze only one locus of paired-end amplicon (merged reads), modifying parameters
1c -> Re-analyze only one locus of single-end amplicon (R1 only), modifying parameters
1d -> Re-analyse a given sample, modifying parameters
1e -> Optional quality checking of fastq files (slow)
Option 2 offers the following submenu:
2a -> Apply the SAME size threshold for ALL SAMPLES for the loci based on PAIRED-END reads (R1/R2 merged)
2b -> Apply the SAME size threshold for ALL SAMPLES for the loci based on SINGLE-END reads (R1 only)
2c -> Apply a SPECIFIC size threshold for a given sample, for the loci based on PAIRED-END reads (R1/R2 merged)
2d -> Apply a SPECIFIC size threshold for a given sample, for the loci based on SINGLE-END reads (R1 only)
Option 4 offers the following submenu:
4a -> Generate sequence files
4b -> Generate assignment file
4c -> Build metaXplor-format sample metadata file from provided tabulated file
4d -> Compresses all metaXplor files into a final, ready to import, zip archive
VSEARCH reference:
Rognes T, Flouri T, Nichols B, Quince C, Mahe F (2016). VSEARCH: a versatile open source tool for metagenomics
PeerJ 4:e2584 doi: 10.7717/peerj.2584 https://doi.org/10.7717/peerj.2584
Usage:
=====
python3 mbctools.py
(or simply "mbctools") if installed using pip
"""
__authors__ = "Christian Barnabé, Guilhem Sempéré"
__contact__ = "[email protected]"
__date__ = "2024-10-30"
__version__ = "1.0"
__copyright__ = "Copyright (c) 2024 IRD, CIRAD"
__license__ = "This software is licensed under the MIT License. The full license text is available at https://github.com/GuilhemSempere/mbctools/blob/main/LICENSE"
import sys
import time
import datetime
from pathlib import Path
import os
import platform
import subprocess
import re
import glob
import configparser
import traceback
import io
import zipfile
import shutil
import math
winOS = "Windows" in platform.uname()
shellCmd = "powershell" if winOS else "bash"
scriptExt = "ps1" if winOS else "sh"
fileSep = "\\" if winOS else "/"
globalErrorOnStopCmd = "" if winOS else "set -e"
localErrorOnStopCmd = "; If ($LASTEXITCODE -gt 0) { exit $LASTEXITCODE }" if winOS else ""
date = datetime.datetime.now()
current_dir = os.getcwd()
errorStyle = "\033[91m"
warningStyle = "\033[93m"
normalStyle = "\033[0m"
titleStyle = "\033[94m\033[1m"
promptStyle = "\033[96m"
successStyle = "\033[92m"
citationStyle = "\033[1;33m\033[1m\033[3m"
global lociPEs, lociSEs, lociPE, lociSE, dir_fastq, fastq_R1, fastqr1s, fastq_R2, fastqr2s, Samples, \
samples, alpha, identity, loc_sel1, loc_sel2, rmenu, sam_sel, minsize, minseqlength, loc2trim, trim_left, \
trim_right, ts, ts1, sam2trim2c, sam2trim2d, all_loci, next_run, menu, ts2, loc2cat, loc2trim2a, loc2trim2b, \
loc2trim2c, loc2trim2d
metaXplorFasta = "tmp_files/metaXplor_sequences.fasta"
metaXplorSequenceComposition = "tmp_files/metaXplor_sequences.tsv"
metaXplorAssignments = "tmp_files/metaXplor_assignments.tsv"
metaXplorSamples = "tmp_files/metaXplor_samples.tsv"
def start_log_redirect(filepath):
"""Starts redirecting log messages
"""
if not winOS:
return "exec 3>&1 4>&2 >" + filepath + " 2>&1\n"
else:
return 'Clear-Content -Path "' + filepath + '" -Force -ErrorAction SilentlyContinue\n&{\n'
def end_log_redirect(filepath):
"""Stops redirecting log messages
"""
if not winOS:
return "exec 1>&3 2>&4\n"
else:
return '} 2>&1 | ForEach-Object { if ($_ -is [System.Management.Automation.ErrorRecord]) { $_.Exception.Message } else { $_ } } | Out-File -FilePath "' + filepath + '" -Append\n'
def main_stream_message(message):
"""Displays a main stream message on the console
"""
if not winOS:
return "printf \"" + message + "\" >&3\n"
else:
return "Write-Host -NoNewline \"" + message + "\"\n"
def dos2unix(file_path):
with open(file_path, 'rb') as file:
content = file.read().decode('utf-8').replace('\r\n', '\n')
with open(file_path, 'wb') as file:
file.write(content.encode('utf-8'))
def promptUser(message, defaultResponse, validResponses, inputType, backFunction, exitMessage):
"""Prompts user input until a valid response is obtained. Input types are 1:text, 2:numeric, 3:file-path, 4:folder-path
"""
firstAttempt = True
response = None
while response is None:
if firstAttempt:
response = input("\n" + promptStyle + message + (("\n(default = " + normalStyle + defaultResponse + promptStyle + ")") if defaultResponse is not None else "") + ": " + normalStyle)
firstAttempt = False
else:
response = input(errorStyle + "Wrong input, try again!" + promptStyle + " Accepted entries are " + normalStyle + ("a valid " + (("folder path" if inputType == 4 else ("file path" if inputType == 3 else "number")) + " or ") if inputType > 1 else "") + ", ".join(validResponses) + promptStyle + ": " + normalStyle)
if response not in validResponses:
if response == "" and defaultResponse is not None:
response = defaultResponse
if inputType == 1:
response = None
elif inputType == 2 and response.isnumeric() is False:
response = None
elif inputType == 3 and Path(response).is_file() is False:
response = None
elif inputType == 4 and Path(response).is_dir() is False:
response = None
if response in ["back", "home", "exit"]:
if exitMessage is not None and exitMessage != "":
print(successStyle + "\n" + exitMessage + "\n" + normalStyle)
if response != "exit":
input("Press ENTER to continue ")
if response == "back":
response = None
if backFunction is not None:
backFunction()
elif response == "home":
response = None
main()
elif response == "exit":
quit_mbctools()
if response is not None:
return response
def folders():
""" Creates folders useful for the metabarcoding analyze
"""
alreadyExisting = []
global lociPEs, lociSEs, lociPE, lociSE
sys.stdout.write("")
folder = "scripts"
path = os.path.join(current_dir, folder)
if Path(path).is_dir():
alreadyExisting.append(folder)
else:
os.mkdir(path)
sys.stdout.write("")
folder = "outputs"
path = os.path.join(current_dir, folder)
if Path(path).is_dir():
alreadyExisting.append(folder)
else:
os.mkdir(path)
sys.stdout.write("")
folder = "refs"
path = os.path.join(current_dir, folder)
if Path(path).is_dir():
alreadyExisting.append(folder)
else:
os.mkdir(path)
sys.stdout.write("")
folder = "tmp_files"
path = os.path.join(current_dir, folder)
if Path(path).is_dir():
alreadyExisting.append(folder)
else:
os.mkdir(path)
sys.stdout.write("")
folder = "results_by_locus"
path = os.path.join(current_dir, folder)
if Path(path).is_dir():
alreadyExisting.append(folder)
else:
os.mkdir(path)
sys.stdout.write("")
for locus in list(set(lociPEs) | set(lociSEs)):
path = os.path.join(current_dir + "/results_by_locus", locus)
if Path(path).is_dir():
alreadyExisting.append("results_by_locus/" + locus)
else:
os.chdir(f"{current_dir}{fileSep}results_by_locus")
os.mkdir(path)
if len(alreadyExisting) > 0:
sys.stdout.write(warningStyle + f"\nThe following folders already exist and will be used in the upcoming analysis: " + normalStyle + ", ".join(alreadyExisting))
def in_dir_fastq():
"""Input of the path containing the fastq files, option 1
"""
global dir_fastq
dir_fastq = promptUser("Enter the FULL PATH of the folder where fastq files are located", f"{current_dir}" + fileSep + "fastq", ["back", "home", "exit"], 4, main_menu1, "")
def in_fastq_R1():
"""Input of the file name containing the R1 fastq file names, option 1
"""
global fastq_R1, fastqr1s
fastq_R1 = promptUser("Enter the name of the file listing all R1 (or single-end) fastq file names", "fastqR1.txt", ["back", "home", "exit"], 3, main_menu1, "")
with open(fastq_R1, "r") as out1:
fastqr1s = out1.read().splitlines()
def in_fastq_R2():
"""Input of the file name containing the R2 fastq file names, option 1
"""
global fastq_R2, fastqr2s
fastq_R2 = promptUser("Enter the name of the file listing all R2 fastq file names (file must exist but may be empty if no R2 to process)", "fastqR2.txt", ["back", "home", "exit"], 3, main_menu1, "")
with open(fastq_R2, "r") as out2:
fastqr2s = out2.read().splitlines()
def in_lociPE():
"""Input of the file name containing the list of paired-end based loci, option 1
"""
global lociPE, lociPEs
lociPE = promptUser("Enter the name of the file listing names of loci based on paired-end reads (file may be empty if no R2 to process)", "lociPE.txt", ["back", "home", "exit"], 3, main_menu1, "")
with open(lociPE, "r") as out:
lociPEs = out.read().splitlines()
for locusName in lociPEs:
if not os.path.isfile(current_dir + "/refs/" + locusName + ".fas"):
print(errorStyle + "File does not exist: " + current_dir + "/refs/" + locusName + ".fas")
return in_lociPE()
return lociPEs
def in_lociSE():
"""Input of the file name containing the list of single-end based loci, option 1
"""
global lociSE, lociSEs
lociSE = promptUser("Enter the name of the file containing loci based on R1/single-end reads (or unmerged R1)", "lociSE.txt", ["back", "home", "exit"], 3, main_menu1, "")
with open(lociSE, "r") as out:
lociSEs = out.read().splitlines()
for locusName in lociSEs:
if not os.path.isfile(current_dir + "/refs/" + locusName + ".fas"):
print(errorStyle + "File does not exist: " + current_dir + "/refs/" + locusName + ".fas")
return in_lociSE()
return lociSEs
def in_Samples():
"""Input of the file name containing the list of samples, option 1
"""
global Samples, samples
Samples = promptUser("Enter the name of the file listing sample names", "samples.txt", ["back", "home", "exit"], 3, main_menu1, "")
with open(Samples, "r") as out5:
samples = out5.read().splitlines()
def in_minsize():
"""Input of the minimum abundance of sequences to retain for denoising/clustering, options 1, 1a, 1b, 1c and 1d
"""
global minsize
minsize = promptUser("Enter the minsize option value for clusters, i.e. the minimum sequence abundance of the retained clusters", "8", ["back", "home", "exit"], 2, main_menu1, "")
def in_minseqlength():
"""Input of the minimum length of sequences to keep for any locus, options 1, 1a, 1b, 1c and 1d
"""
global minseqlength
minseqlength = promptUser("Enter the minimum length of sequences to keep for any locus", "100", ["back", "home", "exit"], 2, main_menu1, "")
def in_alpha():
"""Input of the alpha parameter for denoising/clustering, options 1, 1a, 1b, 1c and 1d
"""
global alpha
alpha = promptUser("Enter alpha parameter (integer) for the clustering", "2", ["back", "home", "exit"], 2, main_menu1, "")
def in_identity():
"""Input of the identity parameter (0, 1.0) to match the clusters against reference sequences, for affiliating
clusters to the different loci, options 1, 1a, 1b, 1c and 1d
"""
global identity
identity = promptUser("Enter identity parameter to match the clusters against references (as a percentage), enter an integer from 0 to 100", "70", ["back", "home", "exit"], 2, main_menu1, "")
identity = int(identity) / 100
def in_loc_sel_merged():
"""Input of a selected locus based on paired-end reads to rerun for option 1b
"""
global loc_sel1
loc_sel1 = promptUser("Enter the name of the locus analysed by paired-end reads you want to rerun", None, lociPEs + ["back", "home", "exit"], 1, main_menu1, "")
def in_loc_sel_r1():
"""Input of a selected locus based on single-end read (R1) to rerun for option 1c
"""
global loc_sel2, rmenu
loc_sel2 = promptUser("Enter the name of the locus analysed by only single-end (R1) reads you want to rerun", None, lociSEs + ["back", "home", "exit"], 1, main_menu1, "")
def in_sam_sel():
"""Input of the sample name to rerun for option 1d
"""
global sam_sel, samples
sam_sel = promptUser("Enter the sample name you want to rerun", None, samples + ["back", "home", "exit"], 1, main_menu1, "")
def in_loc2trim_2x():
"""Input of the loci names for selection of minium sequence abundances according to user-defined thresholds,
options 2a, 2b, 2c and 2d
"""
global loc2trim2a, loc2trim2b, loc2trim2c, loc2trim2d, lociPEs, lociSEs
if rmenu == "2a":
loc2trim2a = promptUser("Enter a LOCUS name based on paired-end mergeable reads you want to analyze", None, lociPEs + ["back", "home", "exit"], 1, main_menu2, f"Selection of minimum sizes according to user-defined thresholds is complete.\nStatistical summary for paired-end based loci --> {current_dir}{fileSep}outputs{fileSep}Stats_option_2a.txt")
return loc2trim2a
if rmenu == "2b":
loc2trim2b = promptUser("Enter a LOCUS name based on single-end R1 reads you want to analyze ", None, lociSEs + ["back", "home", "exit"], 1, main_menu2, f"Selection of minimum sizes according to user-defined thresholds is complete.\nStatistical summary for single-end based loci --> {current_dir}{fileSep}outputs{fileSep}Stats_option_2b.txt")
return loc2trim2b
if rmenu == "2c":
loc2trim2c = promptUser("Enter a LOCUS name based on paired-end mergeable reads you want to analyze", None, lociPEs + ["back", "home", "exit"], 1, main_menu2, f"Selection of minimum sizes according to user-defined thresholds is complete.\nStatistical summary for paired-end based loci --> {current_dir}{fileSep}outputs{fileSep}Stats_option_2c.txt")
return loc2trim2c
if rmenu == "2d":
loc2trim2d = promptUser("Enter a LOCUS name based on single-end R1 reads you want to analyze", None, lociSEs + ["back", "home", "exit"], 1, main_menu2, f"Selection of minimum sizes according to user-defined thresholds is complete.\nStatistical summary for single-end based loci --> {current_dir}{fileSep}outputs{fileSep}Stats_option_2d.txt")
return loc2trim2d
def in_trim_sample2c(locus):
"""Input of sample names for option 2c
"""
global samples, sam2trim2c
sam2trim2c = promptUser("Enter the name of the sample you want to trim for locus " + locus, None, samples + ["back", "home", "exit"], 1, trim_2x, "")
return sam2trim2c
def in_trim_sample2d(locus):
"""Input of sample names for option 2d
"""
global samples, sam2trim2d
sam2trim2d = promptUser("Enter the name of the sample you want to trim for locus " + locus, None, samples + ["back", "home", "exit"], 1, trim_2x, "")
return sam2trim2d
def in_trim_left(orientFileSuffix):
"""Input of the number of bp corresponding to the forward primer to remove from the clusters,
options 2a, 2b, 2c and 2d
"""
global trim_left #, loc2trim2a, loc2trim2b, loc2trim2c
if rmenu == "2a":
trim_left = promptUser(f"Enter the number of bp of the forward primer for {loc2trim2a} (e.g. 20)", None, ["back", "home", "exit"], 2, main_menu2, "")
if rmenu == "2b":
if orientFileSuffix == "_plus":
trim_left = promptUser(f"Enter the number of bp of the forward primer for {loc2trim2b} (e.g. 20)", None, ["back", "home", "exit"], 2, main_menu2, "")
elif orientFileSuffix == "_minus":
trim_left = promptUser(warningStyle + "You chose to keep antisense (-) clusters and therefore should safely be able to use 0 here\n" + promptStyle + f"Enter the number of bp of the forward primer for {loc2trim2b} (e.g. 0)", None, ["back", "home", "exit"], 2, main_menu2, "")
else:
trim_left = promptUser(warningStyle + "Inspite of given advice, you chose to keep both sense (+) and antisense (-) clusters. Now you decide whether or no to trim forward primers ;-)\n" + promptStyle + f"Enter the number of bp of the forward primer for {loc2trim2b}", None, ["back", "home", "exit"], 2, main_menu2, "")
if rmenu == "2c":
trim_left = promptUser(f"Enter the number of bp of the forward primer for {loc2trim2c} (e.g. 20)", None, ["back", "home", "exit"], 2, main_menu2, "")
if rmenu == "2d":
if orientFileSuffix == "_plus":
trim_left = promptUser(f"Enter the number of bp of the forward primer for {loc2trim2d} (e.g. 20)", None, ["back", "home", "exit"], 2, main_menu2, "")
elif orientFileSuffix == "_minus":
trim_left = promptUser(warningStyle + "You chose to keep antisense (-) clusters and therefore should safely be able to use 0 here\n" + promptStyle + f"Enter the number of bp of the forward primer for {loc2trim2d} (e.g. 0)", None, ["back", "home", "exit"], 2, main_menu2, "")
else:
trim_left = promptUser(warningStyle + "Inspite of given advice, you chose to keep both sense (+) and antisense (-) clusters. Now you decide whether or no to trim forward primers ;-)\n" + promptStyle + f"Enter the number of bp of the forward primer for {loc2trim2d}", None, ["back", "home", "exit"], 2, main_menu2, "")
return trim_left
def in_trim_right(orientFileSuffix):
"""Input of the number of bp corresponding to the reverse primer to remove from the clusters,
options 2a, 2b, 2c and 2d
"""
global trim_right #, loc2trim2a, loc2trim2b, loc2trim2c, loc2trim2d
if rmenu == "2a":
trim_right = promptUser(f"Enter the number of bp of the reverse primer for {loc2trim2a} (e.g. 22)", None, ["back", "home", "exit"], 2, main_menu2, "")
if rmenu == "2b":
if orientFileSuffix == "_minus":
trim_right = promptUser(f"Enter the number of bp of the reverse primer for {loc2trim2b} (e.g. 20)", None, ["back", "home", "exit"], 2, main_menu2, "")
elif orientFileSuffix == "_plus":
trim_right = promptUser(warningStyle + "You chose to keep sense (+) sequences and therefore should safely be able to use 0 here\n" + promptStyle + f"Enter the number of bp of the reverse primer for {loc2trim2b} (e.g. 0)", None, ["back", "home", "exit"], 2, main_menu2, "")
else:
trim_right = promptUser(warningStyle + "Inspite of given advice, you chose to keep both sense (+) and antisense (-) clusters. Now you decide whether or no to trim reverse primers ;-)\n" + promptStyle + f"Enter the number of bp of the reverse primer for {loc2trim2b}", None, ["back", "home", "exit"], 2, main_menu2, "")
if rmenu == "2c":
trim_right = promptUser(f"Enter the number of bp of the reverse primer for {loc2trim2c} (e.g. 22)", None, ["back", "home", "exit"], 2, main_menu2, "")
if rmenu == "2d":
if orientFileSuffix == "_minus":
trim_right = promptUser(f"Enter the number of bp of the reverse primer for {loc2trim2d} (e.g. 20)", None, ["back", "home", "exit"], 2, main_menu2, "")
elif orientFileSuffix == "_plus":
trim_right = promptUser(warningStyle + "You chose to keep sense (+) sequences and therefore should safely be able to use 0 here\n" + promptStyle + f"Enter the number of bp of the reverse primer for {loc2trim2d} (e.g. 0)", None, ["back", "home", "exit"], 2, main_menu2, "")
else:
trim_right = promptUser(warningStyle + "Inspite of given advice, you chose to keep both sense (+) and antisense (-) clusters. Now you decide whether or no to trim reverse primers ;-)\n" + promptStyle + f"Enter the number of bp of the reverse primer for {loc2trim2d}", None, ["back", "home", "exit"], 2, main_menu2, "")
return trim_right
def in_ts():
"""Input of the user-defined threshold of minimum abundance of clusters to retain, options 2a, 2b, 2c and 2d
"""
global ts, ts1, loc2trim2a, loc2trim2b, loc2trim2c, loc2trim2d
if rmenu == "2a":
ts = promptUser(f"Enter the THRESHOLD (integer between 0 and 100) you want to use for locus {loc2trim2a}.\nExample: " + normalStyle + f"if you want to keep only the clusters whose abundance is greater than 5% of the sum of cluster sizes for a given sample with {loc2trim2a}, enter 5" + promptStyle, None, ["back", "home", "exit"], 2, main_menu2, "")
if rmenu == "2b":
ts = promptUser(f"Enter the THRESHOLD (integer between 0 and 100) you want to use for locus {loc2trim2b}.\nExample: " + normalStyle + f"if you want to keep only the clusters whose abundance is greater than 5% of the sum of cluster sizes for a given sample with {loc2trim2b}, enter 5" + promptStyle, None, ["back", "home", "exit"], 2, main_menu2, "")
if rmenu == "2c":
ts = promptUser(f"Enter the THRESHOLD (integer between 0 and 100) you want to use for locus {loc2trim2c}.\nExample: " + normalStyle + f"if you want to keep only the clusters whose abundance is greater than 5% of the sum of cluster sizes for a given sample with {loc2trim2c}, enter 5" + promptStyle, None, ["back", "home", "exit"], 2, main_menu2, "")
if rmenu == "2d":
ts = promptUser(f"Enter the THRESHOLD (integer between 0 and 100) you want to use for locus {loc2trim2d}.\nExample: " + normalStyle + f"if you want to keep only the clusters whose abundance is greater than 5% of the sum of cluster sizes for a given sample with {loc2trim2d}, enter 5" + promptStyle, None, ["back", "home", "exit"], 2, main_menu2, "")
ts1 = int(ts) / 100
sys.stdout.write("\n")
return ts, ts1
def param_1x():
""" Creates a file with one parameter by line, options 1, 1a, 1b, 1c and 1d
"""
global dir_fastq, Samples, minsize, rmenu
os.chdir(current_dir)
config = configparser.ConfigParser()
contents = {"date": date, "dir_fastq": dir_fastq, "fastq_R1": fastq_R1, "fastq_R2": fastq_R2,
"minsize": minsize, "minseqlength": minseqlength, "alpha": alpha, "identity": identity}
if rmenu == '1' or rmenu == '1a':
contents["lociPE"] = lociPE
contents["lociSE"] = lociSE
contents["Samples"] = Samples
contents["alpha"] = alpha
contents["identity"] = identity
elif rmenu == '1b':
contents["loc_sel1"] = lociPE
contents["Samples"] = Samples
elif rmenu == '1c':
contents["loc_sel2"] = loc_sel2
contents["Samples"] = Samples
elif rmenu == '1d':
contents["sam_sel"] = sam_sel
config['mbctools'] = contents
with open("outputs/parameters_option_" + rmenu + ".cfg", 'w') as configfile:
config.write(configfile)
def prev_param(paramConfigFile):
""" Recalls global variables for different options
"""
try:
global fastqr1s, fastqr2s, lociPEs, lociSEs, samples
os.chdir(current_dir)
fileToParse = paramConfigFile if paramConfigFile is not None else "outputs/parameters_option_1.cfg"
config = configparser.ConfigParser()
config.read(fileToParse)
contents = config['mbctools']
if paramConfigFile is not None:
global minsize
minsize = contents["minsize"]
global minseqlength
minseqlength = contents["minseqlength"]
global alpha
alpha = contents["alpha"]
global identity
identity = contents["identity"]
global dir_fastq
dir_fastq = contents["dir_fastq"]
global fastq_R1
fastq_R1 = contents["fastq_R1"]
global fastq_R2
fastq_R2 = contents["fastq_R2"]
global lociPE
lociPE = contents["lociPE"]
global lociSE
lociSE = contents["lociSE"]
global Samples
Samples = contents["Samples"]
with open(fastq_R1, "r") as out1:
fastqr1s = out1.read().splitlines()
with open(fastq_R2, "r") as out2:
fastqr2s = out2.read().splitlines()
with open(lociPE, "r") as out3:
lociPEs = out3.read().splitlines()
with open(lociSE, "r") as out4:
lociSEs = out4.read().splitlines()
with open(Samples, "r") as out5:
samples = out5.read().splitlines()
return fastqr1s, fastqr2s, lociPEs, lociSEs, samples
except KeyError:
print(errorStyle + "\nMissing parameter in configuration file " + fileToParse + " - " + normalStyle)
traceback.print_exc(limit=0)
customExit(1)
def quality():
"""Tests the quality of each 'fastq' file (option 1e) by the VSEARCH command:
vsearch --fastq_eestats2 dir_fastq/fastqF-R1 --output ../outputs/SN_R1_quality.txt
vsearch --fastq_eestats2 dir_fastq/fastqF-R2 --output ../outputs/SN_R2_quality.txt
dir_fastq = directory containing the fastq files
fastqF-R1 and fastqF-R2 = fastq file names for the sample
SN = sample name
"""
global fastqr2s, fastqr1s
with open("scripts/infor1." + scriptExt, "w") as out1:
i = 0
out1.write(globalErrorOnStopCmd + "\n" + main_stream_message(f'Quality statistical tests on R1 reads for samples:\n'))
while i < len(samples):
sample = samples[i]
fastqr1 = fastqr1s[i]
i = i + 1
out1.write(main_stream_message(f' {sample}...') + logFileMessage(f'Quality statistical tests on R1 reads for sample {sample}'))
out1.write(f"vsearch --fastq_qmax 93 --fastq_eestats2 \"{dir_fastq}{fileSep}{fastqr1}\" --output "
f"../outputs/{sample}_R1_quality.txt" + localErrorOnStopCmd + "\n")
out1.write(main_stream_message(f'\n\n'))
if len(lociPEs) > 0:
with open("scripts/infor2." + scriptExt, "w") as out2:
i = 0
out2.write(globalErrorOnStopCmd + "\n" + main_stream_message(f'Quality statistical tests on R2 reads for samples:\n'))
while i < len(samples):
sample = samples[i]
fastqr2 = fastqr2s[i]
i = i + 1
out2.write(main_stream_message(f' {sample}...') + logFileMessage(f'Quality statistical tests on R2 reads for sample {sample}'))
out2.write(f"vsearch --fastq_qmax 93 --fastq_eestats2 \"{dir_fastq}{fileSep}{fastqr2}\" --output "
f"../outputs/{sample}_R2_quality.txt" + localErrorOnStopCmd + "\n")
out2.write(main_stream_message(f'\n\n'))
def merging():
"""Merges paired-end reads into one sequence, when the length of the expected amplicon allows it (option 1)
according the VSEARCH command:
vsearch --fastq_mergepairs dir_fastq/fastqR1 --reverse dir_fastq/fastqR2 --fastaout
../tmp_files/SN_pairedEnd.fa --fastq_allowmergestagger --relabel sample=SN_merged.
dir_fastq = directory containing the fastq files
fastqR1 = complete file name of fastq R1 read
fastqR2 = fastqR2 complete name
option --fastq_allowmergestagger allows the merging of short fragments
"""
with open("scripts/merging." + scriptExt, "w") as out:
i = 0
out.write(globalErrorOnStopCmd + "\n" + main_stream_message(f'Merging paired-end reads for samples:\n'))
while i < len(samples):
sample = samples[i]
fastqr1 = fastqr1s[i]
fastqr2 = fastqr2s[i]
out.write(main_stream_message(f" {sample}...") + logFileMessage(f'Merging paired-end reads for sample {sample}') +
f"vsearch --fastq_mergepairs \"{dir_fastq}{fileSep}{fastqr1}\" --reverse \"{dir_fastq}{fileSep}{fastqr2}\" "
f"--fastaout ../tmp_files/{sample}_pairedEnd.fa --fastq_allowmergestagger --relabel "
f"sample={sample}_merged." + localErrorOnStopCmd + "\n")
i = i + 1
out.write(main_stream_message(f'\n\n'))
def logFileMessage(msg):
if not winOS:
return f"echo\necho\necho {msg}\necho " + ("-" * len(msg)) + "\necho\n"
else:
return f'Write-Output ""\nWrite-Output ""\nWrite-Output "{msg}"\nWrite-Output "' + ("-" * len(msg)) + '"\nWrite-Output ""\n'
def fastq2fas():
"""When the merging R1/R2 is impossible because of an unadapted size of amplicon, the reads R1 of 301 bp
(better than R2) are used to search the relevant sequences.
First, all R1 'fastq' files have to be transformed into 'fasta' files by the VSEARCH command:
vsearch --fastq_filter dir_fastq/fastaqR1 –fastaout ../tmp_files/SN_singleEnd.fa
Where : dir_fastq = directory containing the fastq files ; SN = sample name ; fastqR1 = name of the 'fastq' file
containing the R1 reads
"""
with open("scripts/fqtofas." + scriptExt, "w") as out:
i = 0
out.write(globalErrorOnStopCmd + "\n" + main_stream_message(f'Converting FASTQ files into FASTA format for samples:\n'))
while i < len(samples):
sample = samples[i]
fastqr1 = fastqr1s[i]
out.write(main_stream_message(f' {sample}...') + logFileMessage(f'Converting FASTQ files into FASTA format for sample {sample}') +
f"vsearch --fastq_qmax 93 --fastq_filter \"{dir_fastq}{fileSep}{fastqr1}\" --fastaout ../tmp_files/{sample}_singleEnd.fa --relabel sample={sample}_R1." + localErrorOnStopCmd + "\n")
i = i + 1
out.write(main_stream_message(f'\n\n'))
def derep_1():
"""Dereplicates merged sequences in a given 'fasta' file with the VSEARCH command:
vsearch --fastx_uniques ../tmp_files/SN_pairedEnd.fa --fastaout ../tmp_files/SN_pairedEnd_derep.fas --sizeout
--strand both
And dereplicates the R1 sequences in a given 'fasta' file with the VSEARCH command:
vsearch --fastx_uniques ../tmp_files/SN_singleEnd.fa --fastaout ../tmp_files/SN_singleEnd_derep.fas --sizeout
--strand both
Both commands dereplicate in both strands (option --strand both) and write abundance annotation (frequency)
to output (option --sizeout).
SN = sample name
"""
if len(lociPEs) > 0:
with open("scripts/derep." + scriptExt, "w") as out:
out.write(globalErrorOnStopCmd + "\n" + main_stream_message(f'Dereplicating merged reads for samples:\n'))
for sample in samples:
out.write(main_stream_message(
f' {sample}...') + logFileMessage(f'Dereplicating merged reads for sample {sample}') +
f"vsearch --fastx_uniques ../tmp_files/{sample}_pairedEnd.fa --fastaout "
f"../tmp_files/{sample}_pairedEnd_derep.fas --sizeout --strand both" + localErrorOnStopCmd + "\n")
out.write(main_stream_message(f'\n\n'))
if len(lociSEs) > 0:
with open("scripts/derep_r1." + scriptExt, "w") as out1:
out1.write(globalErrorOnStopCmd + "\n" + main_stream_message(f'Dereplicating R1/single-end reads for samples:\n'))
for sample in samples:
out1.write(main_stream_message(f' {sample}...') + logFileMessage(f'Dereplicating R1/single-end reads for sample {sample}') +
f"vsearch --fastx_uniques ../tmp_files/{sample}_singleEnd.fa --fastaout "
f"../tmp_files/{sample}_singleEnd_derep.fas --sizeout --strand both" + localErrorOnStopCmd
+ "\n")
out1.write(main_stream_message(f'\n\n'))
def cluster_1x():
"""Denoises and clusters Illumina dereplicated merged sequences and gives in output the centroids sequences
to 'fasta' files (options 1, 1a, 1b, 1c and 1d) with the following VSEARCH commands:
For loci based in paired-end reads:
vsearch --cluster_unoise ../tmp_files/SN_pairedEnd_derep.fas --sizein --centroids
../tmp_files/SN(or SS)_pairedEnd_cluster.fas --strand both --minsize int --sizeout --unoise_alph int
--minseqlength int
For loci based in R1/single-end reads:
vsearch --cluster_unoise ../tmp_files/SN_singleEnd_derep.fas --sizein --centroids
../tmp_files/SN(or SS)_singleEnd_cluster.fas --strand both --minsize int --sizeout --unoise_alph int
--minseqlength int
SN = sample name; int = integer; SS = selected sample
"""
global rmenu
if len(lociPEs) > 0 and rmenu in ["1", "1a", "1b"] and len(lociPEs) > 0:
with open("scripts/cluster." + scriptExt, "w") as out:
i = 0
if rmenu != "1":
print()
out.write(globalErrorOnStopCmd + "\n" + main_stream_message(f'Clustering merged reads for all samples:\n'))
while i < len(samples):
sample = samples[i]
out.write(main_stream_message(f' {sample}...') + logFileMessage(f'Clustering merged reads for sample {sample}') +
f"vsearch --cluster_unoise ../tmp_files/{sample}_pairedEnd_derep.fas --sizein --centroids "
f"../tmp_files/{sample}_pairedEnd_cluster.fas --strand both --minsize {minsize} --sizeout "
f"--unoise_alph {alpha} --minseqlength {minseqlength}" + localErrorOnStopCmd + "\n")
i = i + 1
out.write(main_stream_message(f'\n\n'))
if len(lociSEs) > 0 and rmenu in ["1", "1a", "1c"]:
with open("scripts/cluster_r1." + scriptExt, "w") as out:
i = 0
if rmenu == "1c":
print()
out.write(globalErrorOnStopCmd + "\n" + main_stream_message(f'Clustering R1/single-end reads for all samples:\n'))
while i < len(samples):
sample = samples[i]
out.write(main_stream_message(f' {sample}...') + logFileMessage(f'Clustering R1/single-end reads for sample {sample}') +
f"vsearch --cluster_unoise ../tmp_files/{sample}_singleEnd_derep.fas --sizein --centroids "
f"../tmp_files/{sample}_singleEnd_cluster.fas --strand both --minsize {minsize} --sizeout "
f"--unoise_alpha {alpha} --minseqlength {minseqlength}" + localErrorOnStopCmd
+ "\n")
i = i + 1
out.write(main_stream_message(f'\n\n'))
if rmenu == "1d":
with open("scripts/cluster_one_sample_1d." + scriptExt, "w") as out:
out.write(globalErrorOnStopCmd + "\n" + main_stream_message(f'\nClustering reads for selected sample {sam_sel}...'))
if len(lociPEs) > 0:
out.write(logFileMessage(f'Clustering merged reads for selected sample {sam_sel}') + f"vsearch --cluster_unoise ../tmp_files/{sam_sel}_pairedEnd_derep.fas --sizein --centroids "
f"../tmp_files/{sam_sel}_pairedEnd_cluster.fas --strand both --minsize {minsize} --sizeout "
f"--unoise_alph {alpha} --minseqlength {minseqlength}" + localErrorOnStopCmd + "\n")
if len(lociSEs) > 0:
out.write(logFileMessage(f'Clustering R1/single-end reads for selected sample {sam_sel}') + f"vsearch --cluster_unoise ../tmp_files/{sam_sel}_singleEnd_derep.fas --sizein --centroids "
f"../tmp_files/{sam_sel}_singleEnd_cluster.fas --strand both --minsize {minsize} "
f"--sizeout --unoise_alph {alpha} --minseqlength {minseqlength}" + localErrorOnStopCmd + "\n")
out.write(main_stream_message(f'\n\n'))
def chimera_remove():
"""Detects and removes potential chimeras in denoised merged sequences or single-end or selected sample
(options 1, 1a, 1b, 1c and 1d), by the VSEARCH commands:
vsearch --uchime3_denovo ../tmp_files/SN(or SS)_pairedEnd_cluster.fas --nonchimeras
../tmp_files/SN(or SS)_pairedEnd_cluster_OK.fas
vsearch --uchime3_denovo ../tmp_files/SN(or SS)_singleEnd_cluster.fas --nonchimeras
../tmp_files/SN(or SS)_singleEnd_cluster_OK.fas
SN = sample name; SS = selected sample
"""
if len(lociPEs) > 0 and rmenu in ["1", "1a", "1b"]:
with open("scripts/chimera." + scriptExt, "w") as out:
out.write(globalErrorOnStopCmd +
"\n" + main_stream_message(f'Detecting and removing chimeras within merged reads of samples:\n'))
for sample in samples:
out.write(main_stream_message(f' {sample}...') + logFileMessage(f'Detecting and removing chimeras within merged reads of sample {sample}') +
f"vsearch --uchime3_denovo ../tmp_files/{sample}_pairedEnd_cluster.fas --nonchimeras "
f"../tmp_files/{sample}_pairedEnd_cluster_OK.fas" + localErrorOnStopCmd + "\n")
out.write(main_stream_message(f'\n\n'))
if len(lociSEs) > 0 and rmenu in ["1", "1a", "1c"]:
with open("scripts/chimera_r1." + scriptExt, "w") as out:
out.write(globalErrorOnStopCmd + "\n" + main_stream_message(f'Detecting and removing chimeras within R1/single-end reads of samples:\n'))
for sample in samples:
out.write(main_stream_message(f' {sample}...') + logFileMessage(f'Detecting and removing chimeras within R1/single-end reads of sample {sample}') +
f"vsearch --uchime3_denovo ../tmp_files/{sample}_singleEnd_cluster.fas --nonchimeras"
f" ../tmp_files/{sample}_singleEnd_cluster_OK.fas" + localErrorOnStopCmd + "\n")
out.write(main_stream_message(f'\n\n'))
if rmenu == "1d":
with open("scripts/chimera_one_sample_1d." + scriptExt, "w") as out:
out.write(globalErrorOnStopCmd + "\n" + main_stream_message(f'Detecting and removing chimeras for selected sample {sam_sel}...'))
if len(lociPEs) > 0:
out.write(logFileMessage(f'Detecting and removing chimeras within merged reads of selected sample {sam_sel}') +
f"vsearch --uchime3_denovo ../tmp_files/{sam_sel}_pairedEnd_cluster.fas --nonchimeras "
f"../tmp_files/{sam_sel}_pairedEnd_cluster_OK.fas" + localErrorOnStopCmd + "\n")
if len(lociSEs) > 0:
out.write(logFileMessage(f'Detecting and removing chimeras within R1/single-end reads of selected sample {sam_sel}') +
f"vsearch --uchime3_denovo ../tmp_files/{sam_sel}_singleEnd_cluster.fas --nonchimeras "
f"../tmp_files/{sam_sel}_singleEnd_cluster_OK.fas" + localErrorOnStopCmd + "\n")
out.write(main_stream_message(f'\n\n'))
def runloc_merged():
"""Searches similarities between merged sequences, denoised and non-chimera sequences and the local reference
database (-db), options 1 and 1a, by the VSEARCH command:
vsearch --usearch_global ../tmp_files/SN_pairedEnd_cluster_OK.fas --db ../refs/L1.fas --matched
../results_by_locus/L1/SN_pairedEnd.fas --id int --strand both
L1 = locus name for amplicons based on paired-end reads
SN = sample name
id = minimum identity accepted (0-1.0)
"""
with open("scripts/results_by_locusmerged." + scriptExt, "w") as out:
out.write(globalErrorOnStopCmd + "\n" + main_stream_message(f'Affiliating clusters to loci for merged reads of samples:\n'))
for lociPEb in lociPEs:
for sample in samples:
out.write(main_stream_message(
f' {sample} vs {lociPEb}...') + logFileMessage(f'Affiliating clusters to locus {lociPEb} for merged reads of sample {sample}') +
f"vsearch --usearch_global ../tmp_files/{sample}_pairedEnd_cluster_OK.fas --db ../refs/{lociPEb}.fas"
f" --matched ../results_by_locus/{lociPEb}/{sample}_pairedEnd.fas --id {identity} --strand both"
+ localErrorOnStopCmd + "\n")
out.write(main_stream_message(f'\n\n'))
def runloc_r1():
"""Searches similarities between single-end sequences (in case of amplicons where the merging R1/R2 is impossible)
denoised and non-chimera sequences and the local reference database (-db), options 1 and 1a,
by the VSEARCH command:
vsearch --usearch_global ../tmp_files/SN_singleEnd_cluster_OK.fas --db ../refs/L2.fas --matched
../results_by_locus/L2/SN_singledEnd.fa --id int --strand both
L2 = locus for amplicons with no mergeable R1/R2
SN = sample name
id = minimum identity accepted (0-1.0)
"""
with open("scripts/results_by_locusr1." + scriptExt, "w") as out:
out.write(globalErrorOnStopCmd + "\n" + main_stream_message(f'Affiliating clusters to loci for R1/single-end reads of samples:\n'))
for locusSEb in lociSEs:
for sample in samples:
out.write(main_stream_message(f' {sample} vs {locusSEb}...') + logFileMessage(f'Affiliating clusters to locus {locusSEb} for R1/single-end reads of sample {sample}') +
f"vsearch --usearch_global ../tmp_files/{sample}_singleEnd_cluster_OK.fas --db "
f"../refs/{locusSEb}.fas --matched ../results_by_locus/{locusSEb}/{sample}_singleEnd.fas --id {identity} "
f"--strand both" + localErrorOnStopCmd + "\n")
out.write(main_stream_message(f'\n\n'))
def runlocsel_merged():
"""Searches similarities between merged sequences, denoised and non-chimera sequences and the local reference
database (-db), for a selected paired-end based locus, option 1b, by the VSEARCH command:
vsearch --usearch_global ../tmp_files/SN_pairedEnd_cluster_OK.fas --db ../refs/SL.fas --matched
../results_by_locus/SL/SN_merged.fas --id real --strand both
SN = sample name
SL = Selected locus based on paired-end reads
id = minimum identity accepted (0-1.0)
"""
with open("scripts/results_by_locus_sel." + scriptExt, "w") as out:
out.write(globalErrorOnStopCmd + "\n" + main_stream_message(f'Affiliating clusters to selected locus {loc_sel1} for merged reads of samples:\n'))
for sample in samples:
out.write(main_stream_message(f' {sample}...') + logFileMessage(f'Affiliating clusters to selected locus {loc_sel1} for merged reads of sample {sample}') +
f"vsearch --usearch_global ../tmp_files/{sample}_pairedEnd_cluster_OK.fas --db "
f"../refs/{loc_sel1}.fas --matched ../results_by_locus/{loc_sel1}/{sample}_pairedEnd.fas --id {identity} "
f"--strand both"
+ localErrorOnStopCmd + "\n")
out.write(main_stream_message(f'\n\n'))
def runlocsel_r1():
"""Searches similarities between single-end sequences (R1), denoised and non-chimera sequences and the local
reference database (-db), for a selected single-end based locus, option 1c, by the VSEARCH command:
vsearch --usearch_global ../tmp_files/SN_singleEnd_cluster_OK.fas --db ../refs/SL.fas --matched
../results_by_locus/SL/SN_singleEnd.fas --id real --strand both
SN = sample name
SL = Selected locus based on single-end read (R1)
id = minimum identity accepted (0-1.0)
"""
with open("scripts/results_by_locusr1_sel." + scriptExt, "w") as out:
out.write(globalErrorOnStopCmd + "\n" + main_stream_message(f'Affiliating clusters to selected locus {loc_sel2} for R1/single-end reads of samples:\n'))
for sample in samples:
out.write(main_stream_message(f' {sample}...') + logFileMessage(f'Affiliating clusters to selected locus {loc_sel2} for R1/single-end reads of sample {sample}') +
f"vsearch --usearch_global ../tmp_files/{sample}_singleEnd_cluster_OK.fas --db "
f"../refs/{loc_sel2}.fas --matched ../results_by_locus/{loc_sel2}/{sample}_singleEnd.fas --id {identity} "
f"--strand both"
+ localErrorOnStopCmd + "\n")
out.write(main_stream_message(f'\n\n'))
def runloc_one_sample_1d():
""" Searches similarities between denoised and non-chimera sequences and local reference database (db)
only for a selected sample (option 1d) by the VSEARCH command:
vsearch --usearch_global ../tmp_files/SS_pairedEnd_cluster_OK.fas --db ../refs/L1.fas --matched
../results_by_locus/L1/SS_pairedEnd.fas --id real --strand both
vsearch --usearch_global ../tmp_files/SS_singleEnd_cluster_OK.fas --db ../refs/L2.fas --matched
../results_by_locus/L2/SS_singleEnd.fas --id real --strand both
SS = selected sample
L1 = locus name for amplicons based on paired-end reads
L2 = locus name for amplicons with no mergeable R1/R2
id = minimum identity accepted (0-1.0)
"""
with open("scripts/results_by_locus_merged_1d." + scriptExt, "w") as out:
out.write(globalErrorOnStopCmd + "\n" + main_stream_message(f'Affiliating clusters to loci for merged reads of selected sample {sam_sel}:\n'))
for lociPEb in lociPEs:
out.write(main_stream_message(f' {lociPEb}...') + logFileMessage(f'Affiliating clusters to locus {lociPEb} for merged reads of selected sample {sam_sel}') +
f"vsearch --usearch_global ../tmp_files/{sam_sel}_pairedEnd_cluster_OK.fas --db "
f"../refs/{lociPEb}.fas --matched ../results_by_locus/{lociPEb}/{sam_sel}_pairedEnd.fas --id {identity} "
f"--strand both" + localErrorOnStopCmd + "\n")
out.write(main_stream_message(f'\n\n'))
with open("scripts/results_by_locus_R1_1d." + scriptExt, "w") as out1:
out1.write(globalErrorOnStopCmd + "\n" + main_stream_message(f'Affiliating clusters to loci for R1/single-end reads of selected sample {sam_sel}:\n'))
for locusSEb in lociSEs:
out1.write(main_stream_message(f' {locusSEb}...') + logFileMessage(f'Affiliating clusters to locus {locusSEb} for R1/single-end reads of selected sample {sam_sel}') +
f"vsearch --usearch_global ../tmp_files/{sam_sel}_singleEnd_cluster_OK.fas --db "
f"../refs/{locusSEb}.fas --matched ../results_by_locus/{locusSEb}/{sam_sel}_singleEnd.fas "
f"--id {identity} --strand both"
+ localErrorOnStopCmd + "\n")
out1.write(main_stream_message(f'\n\n'))
def orient_1x():
"""Orients all the sequences in the same direction (forward) than references, options 1, 1a, 1c and 1d,
with the following script:
For paired-end merged sequences:
vsearch --orient ../results_by_locus/L1/SN_pairedEnd.fas --db ../refs/L1.fas --fastaout ../results_by_locus/L1/SN_pairedEnd_orient.fas
For single-end R1 sequences:
vsearch --orient ../results_by_locus/L2/SN_singleEnd.fas --db ../refs/L2.fas --fastaout ../results_by_locus/L2/SN_singleEnd_orient.fas
For selected loci:
vsearch --orient ../results_by_locus/SL/SN_pairedEnd.fas --db ../refs/SL.fas --fastaout ../results_by_locus/SL/SN_pairedEnd_orient.fas
or
vsearch --orient ../results_by_locus/SL/SN_singleEnd.fas --db ../refs/SL.fas --fastaout ../results_by_locus/SL/SN_singleEnd_orient.fas
For selected sample:
vsearch --orient ../results_by_locus/L1/SS_pairedEnd.fas --db ../refs/L1.fas --fastaout ../results_by_locus/L1/SS_pairedEnd_orient.fas
and
vsearch --orient ../results_by_locus/L2/SS_singleEnd.fas --db ../refs/L2.fas --fastaout ../results_by_locus/L1/SS_singleEnd_orient.fas
SN = locus name; SS = selected sample; SL = selected locus
L1 = locus name for amplicons based on paired-end reads
L2 = locus name for amplicons with no mergeable R1/R2
"""
if rmenu in ["1", "1a"]:
if len(lociPEs) > 0:
with open("scripts/orient_merged_1a." + scriptExt, "w") as out:
out.write(globalErrorOnStopCmd + "\n" + main_stream_message(f"Orienting all merged reads according to the reference:\n"))
for locusPEb in lociPEs:
for sample in samples:
out.write(main_stream_message(f' {sample} vs {locusPEb}...') + logFileMessage(f'Orienting all merged reads according to the reference for locus {locusPEb} and sample {sample}') +
f"vsearch --orient ../results_by_locus/{locusPEb}/{sample}_pairedEnd.fas --db ../refs/{locusPEb}.fas "
f"--fastaout ../results_by_locus/{locusPEb}/{sample}_pairedEnd_orient.fas" + localErrorOnStopCmd + "\n")
out.write(main_stream_message(f'\n\n'))
if len(lociSEs) > 0:
with open("scripts/orient_R1_1a." + scriptExt, "w") as out1:
out1.write(globalErrorOnStopCmd + "\n" + main_stream_message(f"Orienting all R1/single-end reads according to the reference:\n"))
for locusSEb in lociSEs:
for sample in samples:
out1.write(main_stream_message(f' {sample} vs {locusSEb}...') + logFileMessage(f'Orienting all R1/single-end reads according to the reference for locus {locusSEb} and sample {sample}') +
f"vsearch --orient ../results_by_locus/{locusSEb}/{sample}_singleEnd.fas --db ../refs/{locusSEb}.fas "
f"--fastaout ../results_by_locus/{locusSEb}/{sample}_singleEnd_orient.fas --tabbedout ../results_by_locus/{locusSEb}/{sample}_singleEnd_orient.tsv" + localErrorOnStopCmd + "\n")
out1.write(main_stream_message(f'\n\n'))
elif rmenu == "1b":
with open("scripts/orient_merged_1b." + scriptExt, "w") as out:
out.write(globalErrorOnStopCmd + "\n" + main_stream_message(f'Orienting all merged reads according to the reference for selected locus {loc_sel1} and all samples:\n'))
for sample in samples:
out.write(main_stream_message(f' {sample}...') + logFileMessage(f'Orienting all merged reads according to the reference for selected locus {loc_sel1} and {sample}') +
f"vsearch --orient ../results_by_locus/{loc_sel1}/{sample}_pairedEnd.fas --db "
f"../refs/{loc_sel1}.fas --fastaout ../results_by_locus/{loc_sel1}/{sample}_pairedEnd_orient.fas" + localErrorOnStopCmd + "\n")
out.write(main_stream_message(f'\n\n'))
elif rmenu == "1c":
with open("scripts/orient_R1_1c." + scriptExt, "w") as out:
out.write(globalErrorOnStopCmd + "\n" + main_stream_message(f'Orienting all R1/single-end reads according to the reference for selected locus {loc_sel2} and all samples:\n'))
for sample in samples:
out.write(main_stream_message(f' {sample}...') + logFileMessage(f'Orienting all R1/single-end reads according to the reference for selected locus {loc_sel2} and {sample}') +
f"vsearch --orient ../results_by_locus/{loc_sel2}/{sample}_singleEnd.fas --db ../refs/{loc_sel2}.fas "
f"--fastaout ../results_by_locus/{loc_sel2}/{sample}_singleEnd_orient.fas --tabbedout ../results_by_locus/{loc_sel2}/{sample}_singleEnd_orient.tsv" + localErrorOnStopCmd + "\n")
out.write(main_stream_message(f'\n\n'))
if rmenu == "1d":
if len(lociPEs) > 0:
with open("scripts/orient_merged_1d." + scriptExt, "w") as out:
out.write(globalErrorOnStopCmd + "\n" + main_stream_message(f'Orienting all merged reads of selected sample {sam_sel} for all R1/R2 loci:\n'))
for locusPEb in lociPEs:
out.write(main_stream_message(f' {locusPEb}...') + logFileMessage(f'Orienting all merged reads of selected sample {sam_sel} for locus {locusPEb}') +
f"vsearch --orient ../results_by_locus/{locusPEb}/{sam_sel}_pairedEnd.fas --db ../refs/{locusPEb}.fas --fastaout "
f"../results_by_locus/{locusPEb}/{sam_sel}_pairedEnd_orient.fas" + localErrorOnStopCmd + "\n")
out.write(main_stream_message(f'\n\n'))
if len(lociSEs) > 0:
with open("scripts/orient_R1_1d." + scriptExt, "w") as out18:
out18.write(main_stream_message(f'Orienting all R1/single-end reads of selected sample {sam_sel} for all R1/single-end loci:\n'))
for locusSEb in lociSEs:
out18.write(main_stream_message(f' {locusSEb}...') + logFileMessage(f'Orienting all R1/single-end reads of selected sample {sam_sel} for locus {locusSEb}') +
f"vsearch --orient ../results_by_locus/{locusSEb}/{sam_sel}_singleEnd.fas --db ../refs/{locusSEb}.fas "
f"--fastaout ../results_by_locus/{locusSEb}/{sam_sel}_singleEnd_orient.fas --tabbedout ../results_by_locus/{locusSEb}/{sam_sel}_singleEnd_orient.tsv" + localErrorOnStopCmd + "\n")
out18.write(main_stream_message(f'\n\n'))
def getSingleSeqOrientFileSuffix(loci, samples, rmenu):
for locus in loci:
nTotalPlusOrientedReadCount = 0