-
Notifications
You must be signed in to change notification settings - Fork 16
/
run_Wochenende.py
1775 lines (1578 loc) · 56.8 KB
/
run_Wochenende.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
"""
Wochenende: A whole genome/metagenome analysis pipeline in Python3 (2018-2021)
Author: Tobias Scheithauer
Author: Dr. Colin Davenport
Author: Fabian Friedrich
Author: Sophia Poertner
Changelog
2.0.0 allow configurable job scheduler in config.yaml
1.9.9 calculate bam.bai in paired end mode for all outputs
1.9.8 yaml config parsing from BASH environment variable defined location (need to configure and run setup.sh before starting)
1.9.7 use srun in run_Wochenende_SLURM.sh
1.9.6 add yaml config parsing in bash and python (replaces paths in run_Wochenende.py and other files)
1.9.5 add minimap2short and minimap2long modes
1.9.4 add AlignerBoost stage and jar to dependencies folder
1.9.3 do not delete unsorted BAM file, needed for testing AlignerBoost
1.9.2 add error handling for ref.tmp file creation
1.9.1 add new bacterial ref clost_bot_e_contigs.fa
1.9.0 add 2020_05 reference (masked by blacklister version of 2020_03)
1.8.9 write ref to file reporting/ref.tmp, so don't need to set the correct refseq in run_Wochenende_reporting_SLURM.sh
1.8.8 add MQ20 mapping quality option
1.8.7 add Clostridium botulinum ref
1.8.6 remove 2016 references as unused
1.8.5 add 2021_02 ref 2021_02_human_bact_fungi_vir.fa.masked.fa and 2021_02_human_bact_fungi_vir_unmasked.fa (no blacklister)
1.8.4 add new bacterial refs
1.8.3 add ecoli ref
1.8.2 Check number of uncommented lines = 1 in run_Wochenende_SLURM.sh from start script runbatch_sbatch_Wochenende.sh.
1.8.1 Move mq30 filter (makes big changes) to after mm and duplicate filtering
1.8.0 Add name sorting and fixmates for PE reads
1.7.8 Test samtools markdup as replacement for sambamba markdup because of 16k max ref seqs problem
1.7.7 update tests after moving to subdir
1.7.6 add 2020_09 massive reference with all bacterial strains.
1.7.5 add trim_galore trimmer for nextera (SE reads only so far)
1.7.4 add correct fasta files for fastp trimming
1.7.3 use bamtools more efficiently to filter mismatches (not adaptíve to read length, but parameter enabled)
1.7.2 add ngmlr --min-residues cutoff, prefer to default 0.25
1.7.1 add modified Nextera file and support for Trimmomatic trimming of Nextera adapters and transposase sequences
1.7.0 lint code with tool black
1.6.9 TODO WIP - scale allowed number of allowed mismatches to read length, 1 every 30bp ? -
1.6.8 remove --share from SLURM instructions (--share removed in modern 2019 SLURM)
1.6.7 add new viral ref EZV0_1_database2_cln.fasta
1.6.6 add new ref 2020_03 - same as 2019_10, but removed Synthetic E. coli which collided with real E. coli when using mq30 mode.
1.6.5 add new ref 2019_10_meta_human_univec, improve helper scripts
1.6.4 solve bam.txt mq30 problems
1.6.3 generalize conda to avoid specific filesystem
1.6.2 make more general for new users, improve initial error messages
1.6.1 solve ngmlr bugs, solve minimap2 @SQ problem with --split-prefix temp_name
1.6 add ngmlr aligner, --longreads now omits Picard remove_dups by default (fails)
1.5.1 improve SOLiD adapter removal with fastp - configure var adapter_fastp
1.5 restructure wochenende_reporting, requires Python3.6+
1.4 add wochenende_plot.py file plotting
1.3 add samtools flagstat to get per cent reads aligned
1.3 add --testWochenende tests to test pipeline functionality and report success on a small reference
1.2 add --no-prinseq option to cancel prinseq read exclusion
1.2 add generation of unaligned reads (function runGetUnmappedReads) in FASTQ format
1.0 add reporting
0.6 add Minimap2
0.5 improve argument parsing and checks
0.4 use on genomics and metagenomics with awk filter script
0.3 add bwa-mem
0.21 add tool functions
0.2 add references
0.1 initial commits
"""
import sys
import os
import subprocess
import shutil
import argparse
import time
import yaml
version = "2.0.0 - Nov 2021"
##############################
# CONFIGURATION
##############################
# get the config file from a BASH variable (you must configure and run setup.sh before running run_Wochenende.py)
global config_path
if os.environ["WOCHENENDE_DIR"] != None:
woch_dir_bash = os.environ["WOCHENENDE_DIR"]
config_path = woch_dir_bash + "/config.yaml"
print("INFO: Config file path: " + config_path)
else:
print("Error: could not get the config file from the BASH variable $WOCHENENDE_DIR (you must configure and run setup.sh before running run_Wochenende.py)")
with open(config_path, 'r') as stream:
try:
config_dict = yaml.safe_load(stream)
locals().update(config_dict)
except yaml.YAMLError as exc:
print(exc)
##############################
# INITIALIZATION AND ORGANIZATIONAL FUNCTIONS
##############################
print("Wochenende - Whole Genome/Metagenome Sequencing Alignment Pipeline")
print("Wochenende was created by Dr. Colin Davenport, Tobias Scheithauer, "
"Sophia Poertner and Fabian Friedrich with help from many further contributors "
"https://github.com/MHH-RCUG/Wochenende/graphs/contributors")
print("version: " + version)
print()
stage_outfile = ""
stage_infile = ""
fileList = []
global IOthreadsConstant
IOthreadsConstant = "8"
trim_galore_min_quality = "20"
global args
def check_arguments(args):
# Check argument combination
if args.aligner == "minimap2short" and args.longread:
print(
"WARNING: Usage of minimap2short not useful for long read data. Exiting."
)
sys.exit(1)
if args.readType == "PE" and args.aligner == "minimap2long":
print(
"ERROR: Usage of minimap2long optimized for ONT data only. Combination of '--readType PE' and '--aligner minimap2long' is not allowed."
)
sys.exit(1)
if args.readType == "PE" and args.longread:
print("ERROR: Combination of '--readType PE' and '--longread' is not allowed.")
sys.exit(1)
if args.fastp and args.aligner == "minimap2long":
print(
"ERROR: Combination of '--fastp' and '--aligner minimap2long' is not allowed."
)
sys.exit(1)
if args.fastp and args.longread:
print("ERROR: Combination of '--fastp' and '--longread' is not allowed.")
sys.exit(1)
if args.nextera and args.longread:
print("ERROR: Combination of '--nextera' and '--longread' is not allowed.")
sys.exit(1)
return args
def createTmpDir(path_tmpdir):
# Set the path_tmpdir variable at the top of the script, not here:
try:
os.makedirs(path_tmpdir, exist_ok=True)
except:
print(
"Error: Failed to create directory, do you have write access to the configured directory? Directory: "
+ path_tmpdir
)
sys.exit(1)
return 0
def createProgressFile(args):
# Read or create progress file
with open(progress_file, mode="a+") as f:
f.seek(0)
progress = f.readlines()
if (
progress == []
or progress[1].replace("\n", "") == "<current file>"
or args.force_restart
):
with open(progress_file, mode="w") as f:
f.writelines(["# PROGRESS FILE FOR Wochenende\n", "<current file>\n"])
return None
else:
print(
"Found progress file x.tmp, attempting to resume after last completed stage. If not desired, use --force_restart or delete the .tmp progress files."
)
return progress[1].replace("\n", "")
def addToProgress(func_name, c_file):
# Add run functions to progress file
with open(progress_file, mode="r") as f:
progress_lines = f.readlines()
progress_lines[1] = c_file + "\n"
if func_name + "\n" not in progress_lines:
progress_lines.append(func_name + "\n")
with open(progress_file, mode="w") as f:
f.writelines(progress_lines)
return progress_lines[1].replace("\n", "")
def createReftmpFile(args):
# Write refseq as one line (overwrite) in file reporting/ref.tmp and ./ref.tmp
# path_refseq_dict is filled with variables from the yaml file using the yaml parser and method "locals"
try:
with open("reporting/ref.tmp", mode="w") as f1:
f1.write(path_refseq_dict.get(args.metagenome))
except OSError as e:
print("Execution failed: Could not create reporting/ref.tmp or ref.tmp. Hint: did you run: bash get_wochenende.sh before starting?")
sys.exit(1)
try:
with open("ref.tmp", mode="w") as f2:
f2.write(path_refseq_dict.get(args.metagenome))
except OSError as e:
print("Execution failed: Could not create reporting/ref.tmp or ref.tmp. Hint: did you run: bash get_wochenende.sh before starting?")
sys.exit(1)
def runFunc(func_name, func, cF, newCurrentFile, *extraArgs):
"""
Used in the main function to compose the pipeline. Runs a function and adds
it to the progress file.
Args:
func_name (str): The function's name
func (fun): The function to run
cF (str): the current file to operate on
*extraArgs: any additional arguments for the function
Returns:
str: The new current file which is used for the next step. It is defined
by the input function.
"""
# Run function and add it to the progress file
with open(progress_file, mode="r") as f:
done = func_name in "".join(f.readlines())
if not done:
if newCurrentFile:
cF = func(cF, *extraArgs)
else:
func(cF, *extraArgs)
return addToProgress(func_name, cF)
def runStage(stage, programCommand):
"""
Run a stage of this Pipeline
Args:
stage (str): the stage's name
programCommand (str): the command to execute as new subprocess
"""
print("###### " + stage + " ######")
try:
# print(programCommand)
process = subprocess.Popen(programCommand, stdout=subprocess.PIPE)
output, error = process.communicate()
except OSError as e:
print(programCommand)
print("Execution failed:", e, file=sys.stderr)
sys.exit(1)
def deriveRead2Name(seRead):
# Get name for paired end read based on single end
read1 = seRead
if "fastq" in seRead:
if "_R1" in seRead:
read2 = seRead.replace("_R1", "_R2")
else:
print("seRead: " + str(seRead))
raise NameError("Invalid format for Paired-End-Reads 1")
elif "fq" in seRead:
if "_R1" in seRead:
read2 = seRead.replace("_R1", "_R2")
else:
raise NameError("Invalid format for Paired-End-Reads 2")
else:
raise NameError("Invalid format for Paired-End-Reads 3")
print("Read1 was: " + read1 + ", read2 derived as: " + read2)
return read2
def rejigFiles(stage, stage_infile, stage_outfile):
# Record, then prepare files for next stage
fileList.append(stage)
fileList.append(stage_infile)
fileList.append(stage_outfile)
stage_infile = stage_outfile
##############################
# TOOL FUNCTIONS
##############################
def runFastQC(stage_infile):
# quality control
stage = "FastQC"
fastqc_out = stage_infile + "_fastqc_out"
try:
os.mkdir(fastqc_out)
except OSError as e:
print("Execution failed:", e, file=sys.stderr)
fastQCcmd = [path_fastqc, "-t", "4", "-quiet", "-o", fastqc_out, stage_infile]
runStage(stage, fastQCcmd)
stage_outfile = stage_infile
rejigFiles(stage, stage_infile, stage_outfile)
return stage_outfile
def runAfterQC(stage_infile):
# automatic filtering, trimming, error removing and quality control
stage = "AfterQC"
print("###### " + stage + " ######")
afterQCcmd = ["python", path_afterqc]
runStage(stage, afterQCcmd)
stage_outfile = ""
rejigFiles(stage, stage_infile, stage_outfile)
return stage_outfile
def runTrimGaloreSE(stage_infile, noThreads, nextera):
# use for Nextera - single end reads
stage = "TrimGalore - SE"
print("###### " + stage + " ######")
prefix = stage_infile.replace(".fastq", "")
stage_outfile = prefix + ".trm.fastq"
trimNextera = ""
if nextera:
trimNextera = "--nextera"
trim_galore_cmd = [
# trim_galore --nextera --dont_gzip --cores 12 --2colour 20 x_R1.fastq > out_R1.fastq
path_trim_galore,
trimNextera,
"--dont_gzip ",
"--length 36 ",
"--suppress_warn ",
# "--adapter_fasta=" + adapter_path,
"--cores " + noThreads,
"--2colour " + trim_galore_min_quality,
stage_infile,
# " > ",
# stage_outfile,
]
rename_cmd = [
# trim_galore creates prefix_trimmed.fq . Rename this to outfile
"mv",
prefix + "_trimmed.fq",
stage_outfile,
]
# runStage(stage, trim_galore_cmd)
trimGaloreCmdStr = " ".join(trim_galore_cmd)
renameStr = " ".join(rename_cmd)
try:
# could not get subprocess.run, .call etc to work with pipes and redirect '>'
print("trimGaloreCmdStr: " + trimGaloreCmdStr)
print("renameStr: " + renameStr)
os.system(trimGaloreCmdStr)
os.system(renameStr)
except:
print("Error running trim_galore")
sys.exit(1)
rejigFiles(stage, stage_infile, stage_outfile)
return stage_outfile
# TODO !!!!!!!!!!!!!!!! Have never done this for TrimGalore AND how does it do PE output?
def runTrimGalorePE(stage_infile, noThreads, adapter_path):
# use for Nextera - paired end reads
stage = "TrimGalore - PE TODO!!"
print("###### " + stage + " ######")
prefix = stage_infile.replace(".fastq", "")
stage_outfile = prefix + ".trm.fastq"
trim_galore_cmd = [
path_trim_galore,
# trim_galore --nextera --dont_gzip --cores 12 --2colour 20 x_R1.fastq
"--nextera",
"--dont_gzip",
"--length 36",
"--suppress_warn ",
# "--adapter_fasta=" + adapter_path,
"--cores " + noThreads,
"--2colour " + trim_galore_min_quality,
stage_infile,
" > ",
stage_outfile,
]
# runStage(stage, trim_galore_cmd)
trimGaloreCmdStr = " ".join(trim_galore_cmd)
try:
# could not get subprocess.run, .call etc to work with pipes and redirect '>'
print("trimGaloreCmdStr: " + trimGaloreCmdStr)
os.system(trimGaloreCmdStr)
except:
print("Error running trim_galore")
sys.exit(1)
rejigFiles(stage, stage_infile, stage_outfile)
return stage_outfile
def runFastpSE(stage_infile, noThreads, adapter_path):
# all-in-one FASTQ-preprocessor - single end reads
stage = "fastp - SE"
print("###### " + stage + " ######")
prefix = stage_infile.replace(".fastq", "")
stage_outfile = prefix + ".trm.fastq"
fastpcmd = [
path_fastp,
"--in1=" + stage_infile,
"--out1=" + stage_outfile,
"--length_required=36",
"--adapter_fasta=" + adapter_path,
"--cut_front",
"--cut_window_size=5",
"--cut_mean_quality=15",
"--html=" + prefix + ".html",
"--json=" + prefix + ".json",
"--thread=" + noThreads,
]
runStage(stage, fastpcmd)
rejigFiles(stage, stage_infile, stage_outfile)
return stage_outfile
def runFastpPE(stage_infile_1, stage_infile_2, noThreads, adapter_path):
# all-in-one FASTQ-preprocessor - paired end reads
stage = "fastp - PE"
print("###### " + stage + " ######")
prefix = stage_infile_1.replace(".fastq", "")
stage_outfile = prefix + ".fastp.fastq"
fastpcmd = [
path_fastp,
"--in1=" + stage_infile_1,
"--out1=" + stage_outfile,
"--in2=" + stage_infile_2,
"--out2=" + deriveRead2Name(stage_outfile),
"--length_required=36",
"--adapter_fasta=" + adapter_path,
"--cut_front",
"--cut_window_size=5",
"--cut_mean_quality=15",
"--html=" + prefix + ".html",
"--json=" + prefix + ".json",
"--thread=" + noThreads,
]
runStage(stage, fastpcmd)
rejigFiles(stage, stage_infile, stage_outfile)
return stage_outfile
def runPrinseq(stage_infile):
# low complexity reads removal - single end reads
stage = "Remove low complexity reads with Prinseq"
stage_outfile = stage_infile
prefix = stage_outfile.replace(".fastq", "")
stage_outfile = prefix + ".lc.fastq"
prinseqCmd = [
path_prinseq,
"-fastq",
stage_infile,
"-lc_method",
"dust",
"-lc_threshold",
"3",
"-out_good",
stage_outfile,
"-out_bad",
prefix + ".lc_seqs.fq",
]
runStage(stage, prinseqCmd)
# prinseq adds extra .fastq by itself. Remove this by moving the file to
# the filename expected by downstream apps
prinseqOutfile = stage_outfile + ".fastq"
try:
shutil.move(prinseqOutfile, stage_outfile)
except OSError as e:
print("Execution failed:", e, file=sys.stderr)
rejigFiles(stage, stage_infile, stage_outfile)
return stage_outfile
def runPrinseqPE(stage_infile_1, stage_infile_2):
# low complexity reads removal - paired end reads
stage = "Remove low complexity reads with Prinseq"
stage_outfile = stage_infile_1
prefix = stage_outfile.replace(".fastq", "")
stage_outfile = prefix + ".lc.fastq"
prinseqCmd = [
path_prinseq,
"-fastq",
stage_infile_1,
"-fastq2",
stage_infile_2,
"-lc_method",
"dust",
"-lc_threshold",
"3",
"-out_good",
stage_outfile,
"-out_bad",
prefix + ".lc_seqs.fq",
]
runStage(stage, prinseqCmd)
# prinseq adds extra .fastq by itself. Remove this by moving the file to
# the filename expected by downstream apps
try:
shutil.move(stage_outfile + "_1.fastq", stage_outfile)
shutil.move(stage_outfile + "_2.fastq", deriveRead2Name(stage_outfile))
os.remove(stage_outfile + "_1_singletons.fastq")
os.remove(stage_outfile + "_2_singletons.fastq")
except OSError as e:
print("Execution failed:", e, file=sys.stderr)
rejigFiles(stage, stage_infile, stage_outfile)
return stage_outfile
def runPerlDup(stage_infile):
# duplicate reads removal
stage = "Remove non-unique reads with Perldup"
stage_outfile = stage_infile
prefix = stage_outfile.replace(".fastq", "")
stage_outfile = prefix + ".ndp.fastq"
runPerlDupCmd = [path_perl, path_perldup, stage_infile, stage_outfile]
runStage(stage, runPerlDupCmd)
rejigFiles(stage, stage_infile, stage_outfile)
return stage_outfile
def runFastUniq(stage_infile):
# duplicate reads removal
stage = "Remove non-unique reads with FastUniq"
stage_outfile = stage_infile
prefix = stage_outfile.replace(".fastq", "")
stage_outfile = prefix + ".ndp.fastq"
with open("readlist.tmp", "a") as readlist:
readlist.write(stage_infile.replace(os.getcwd() + "/", "") + "\n")
# readlist.write('\n')
readlist.write(
deriveRead2Name(stage_infile).replace(os.getcwd() + "/", "") + "\n"
)
runFastuniqCmd = [
path_fastuniq,
"-i",
"readlist.tmp",
"-t",
"q",
"-o",
stage_outfile,
"-p",
deriveRead2Name(stage_outfile),
"-c",
"0",
]
runStage(stage, runFastuniqCmd)
rejigFiles(stage, stage_infile, stage_outfile)
return stage_outfile
def runTMTrimming(stage_infile, adapter_file):
# adapter and quality trimming - single end
stage = "Trimming with Trimmomatic - SE"
stage_outfile = stage_infile
prefix = stage_infile.replace(".fastq", "")
stage_outfile = prefix + ".trm.fastq"
# Also trial with far more comprehensive bbmap adapters:
# /mnt/ngsnfs/tools/miniconda2/pkgs/bbmap-37.17-0/opt/bbmap-37.17/resources/adapters.fa
trimCmd = [
path_trimmomatic,
"SE",
"-threads",
IOthreadsConstant,
"-phred33",
stage_infile,
stage_outfile,
"ILLUMINACLIP:" + adapter_file + ":2:30:10",
"LEADING:3",
"TRAILING:3",
"SLIDINGWINDOW:4:15",
"MINLEN:36",
]
runStage(stage, trimCmd)
rejigFiles(stage, stage_infile, stage_outfile)
return stage_outfile
def runTMTrimmingPE(stage_infile, adapter_file):
# adapter and quality trimming - paired end
stage = "Trimming with Trimmomatic - PE"
stage_outfile = stage_infile
prefix = stage_infile.replace(".fastq", "")
stage_outfile = prefix + ".trm.fastq"
tmpfile1 = prefix + "1.tmp"
tmpfile2 = prefix + "2.tmp"
trimCmd = [
path_trimmomatic,
"PE",
"-threads",
IOthreadsConstant,
"-phred33",
stage_infile,
deriveRead2Name(stage_infile),
stage_outfile,
tmpfile1,
deriveRead2Name(stage_outfile),
tmpfile2,
"ILLUMINACLIP:" + adapter_file + ":2:30:10",
"LEADING:3",
"TRAILING:3",
"SLIDINGWINDOW:4:15",
"MINLEN:36",
]
runStage(stage, trimCmd)
os.remove(tmpfile1)
os.remove(tmpfile2)
rejigFiles(stage, stage_infile, stage_outfile)
return stage_outfile
def runEATrimming(stage_infile):
# adapter trimming
stage = "Trimming with EA-utils"
prefix = stage_infile.replace(".fastq", "")
stage_outfile = prefix + ".tre.fastq"
trimCmd = [
path_fastq_mcf,
"-f",
"-o",
stage_outfile,
ea_adapter_fasta,
stage_infile,
]
runStage(stage, trimCmd)
rejigFiles(stage, stage_infile, stage_outfile)
return stage_outfile
def runAligner(stage_infile, aligner, index, noThreads, readType):
# Alignment - Short-read single and paired end using bwa-mem or minimap2short. minimap2long or ngmlr for long reads
ngmlrMinIdentity = (
0.85 # Aligner ngmlr only: minimum identity (fraction) of read to reference
)
ngmlrMinResidues = 0.70 # Aligner ngmlr only: minimum aligned residues (fraction) of read to reference
stage = "Alignment"
print("###### " + stage + " ######")
prefix = stage_infile.replace(".fastq", "")
minimap_samfile = prefix + ".sam"
stage_outfile = prefix + ".bam"
global inputFastq
readGroup = os.path.basename(inputFastq.replace(".fastq", ""))
alignerCmd = ""
if "minimap2long" in aligner:
alignerCmd = [
path_minimap2,
"-x",
"map-ont",
"-a",
"--split-prefix",
prefix,
"-t",
str(noThreads),
str(index),
stage_infile,
">",
minimap_samfile,
]
elif "minimap2short" in aligner:
alignerCmd = [
path_minimap2,
"-x",
"sr",
"-a",
"--split-prefix",
prefix,
"-t",
str(noThreads),
str(index),
stage_infile,
">",
minimap_samfile,
]
elif "ngmlr" in aligner:
alignerCmd = [
path_ngmlr,
"-x",
"ont",
"-i",
str(ngmlrMinIdentity),
"-R",
str(ngmlrMinResidues),
"-t",
str(noThreads),
"-r",
str(index),
"-q",
stage_infile,
]
elif "PE" in readType:
stage_infile2 = deriveRead2Name(stage_infile)
alignerCmd = [
path_bwa,
"mem",
"-t",
str(noThreads),
"-R",
'"@RG\\tID:' + readGroup + "_001\\tSM:" + readGroup + '"',
str(index),
stage_infile,
stage_infile2,
]
elif "SE" in readType:
alignerCmd = [
path_bwa,
"mem",
"-t",
str(noThreads),
"-R",
'"@RG\\tID:' + readGroup + "_001\\tSM:" + readGroup + '"',
str(index),
stage_infile,
]
else:
print("Read type not defined")
sys.exit(1)
# minimap2 cannot pipe directly to samtools for bam conversion, the @SQ problem
if "minimap2" not in aligner:
samtoolsCmd = [
"|",
path_samtools,
"view",
"-@",
IOthreadsConstant,
"-bhS",
">",
stage_outfile,
]
wholeCmd = alignerCmd + samtoolsCmd
print(" ".join(wholeCmd))
wholeCmdString = " ".join(wholeCmd)
try:
# could not get subprocess.run, .call etc to work with pipes and redirect '>'
os.system(wholeCmdString)
except:
print("Error running non-minimap2 aligner")
sys.exit(1)
# minimap2 cannot pipe directly to samtools for bam conversion, the @SQ problem
elif "minimap2" in aligner:
# samtools view -@ 8 -bhS $sam > $sam.bam
samtoolsCmd = [
path_samtools,
"view",
"-@",
IOthreadsConstant,
"-bhS",
minimap_samfile,
">",
stage_outfile,
]
# wholeCmd = alignerCmd + samtoolsCmd
print(" ".join(alignerCmd))
alignerCmdString = " ".join(alignerCmd)
print(" ".join(samtoolsCmd))
minimapSamtoolsCmdString = " ".join(samtoolsCmd)
rmSamCmd = ["rm", minimap_samfile]
rmSamCmdStr = " ".join(rmSamCmd)
try:
# could not get subprocess.run, .call etc to work with pipes and redirect '>'
# run split command for minimap
os.system(alignerCmdString)
os.system(minimapSamtoolsCmdString)
# remove sam file
os.system(rmSamCmdStr)
except:
print("Error running minimap2 aligner (does not use pipe to samtools)")
sys.exit(1)
else:
print("minimap2 aligner check failed")
sys.exit(1)
"""
# Old actual run alignment block
wholeCmd = alignerCmd + samtoolsCmd
print(' '.join(wholeCmd))
wholeCmdString=' '.join(wholeCmd)
try:
# could not get subprocess.run, .call etc to work with pipes and redirect '>'
os.system(wholeCmdString)
except:
sys.exit(1)
"""
rejigFiles(stage, stage_infile, stage_outfile)
return stage_outfile
def runAlignerBoost(stage_infile, readType):
# run AlignerBoost
stage = "Run AlignerBoost to correct unsorted BAM MQ"
prefix = stage_infile.replace(".bam", "")
stage_outfile = prefix + ".ab.bam"
if readType == "SE":
filterType="filterSE"
elif readType == "PE":
filterType="filterPE"
else:
filterType="filterSE"
#$java -Xmx30g -jar $jar run filterSE -in $i -out $i.alb.bam &
alignerBoostCmd = [
"java",
"-Xmx30g",
"-jar",
path_alignerboost,
"run",
filterType,
"-in",
stage_infile,
"-out",
stage_outfile,
]
runStage(stage, alignerBoostCmd)
rejigFiles(stage, stage_infile, stage_outfile)
return stage_outfile
def runBAMsort(stage_infile, readType):
# runBAMsort
stage = "Sort BAM"
prefix = stage_infile.replace(".bam", "")
stage_outfile = prefix + ".s.bam"
samtoolsSortCmd = [
path_samtools,
"sort",
"-@",
IOthreadsConstant,
stage_infile,
"-o",
stage_outfile,
]
runStage(stage, samtoolsSortCmd)
if readType == "SE":
# Delete unsorted BAM file
rmUnsortedBamCmd = ["rm", stage_infile]
rmUnsortedBamCmdStr = " ".join(rmUnsortedBamCmd)
try:
#os.system(rmUnsortedBamCmdStr)
pass
except:
print("Error removing unsorted bam file")
sys.exit(1)
rejigFiles(stage, stage_infile, stage_outfile)
return stage_outfile
def runBAMsortByName(stage_infile, readType):
# Name sort BAM prior to fixmate, used in PE workflow
stage = "Name sort BAM"
prefix = stage_infile.replace(".bam", "")
stage_outfile = prefix + ".ns.bam"
samtoolsNameSortCmd = [
path_samtools,
"sort",
"-n",
"-@",
IOthreadsConstant,
stage_infile,
"-o",
stage_outfile,
]
runStage(stage, samtoolsNameSortCmd)
if readType == "SE":
# Delete unsorted BAM file
rmUnsortedBamCmd = ["rm", stage_infile]
rmUnsortedBamCmdStr = " ".join(rmUnsortedBamCmd)
try:
os.system(rmUnsortedBamCmdStr)
except:
print("Error removing unsorted bam file in function runBAMsortByName")
sys.exit(1)
rejigFiles(stage, stage_infile, stage_outfile)
return stage_outfile
def runFixmate(stage_infile):
# fix mates prior to PE duplicate removal, used in PE workflow
stage = "Samtools Fix mates"
prefix = stage_infile.replace(".bam", "")
stage_outfile = prefix + ".fix.bam"
samtoolsNameSortCmd = [
path_samtools,
"fixmate",
"-r",
"-m",
"-@",
IOthreadsConstant,
stage_infile,
stage_outfile,
]
runStage(stage, samtoolsNameSortCmd)
rejigFiles(stage, stage_infile, stage_outfile)
return stage_outfile
def runBAMindex(stage_infile):
# Stage output not used further in flow
stage = "Index BAM"
samtoolsIndexCmd = [path_samtools, "index", stage_infile]
runStage(stage, samtoolsIndexCmd)
# No rejigfiles needed as dead end
return 0
def runSamtoolsFlagstat(stage_infile):
# Stage output not used further in flow
stage = "samtools flagstat"
print("###### " + stage + " ######")
flagstatOutput = [stage_infile, ".flagstat.txt"]
flagstatOutputStr = ""
flagstatOutputStr = "".join(flagstatOutput)
# print(flagstatOutputStr)
samtoolsFlagstatCmd = [
path_samtools,
"flagstat",
stage_infile,
">",
flagstatOutputStr,
]
samtoolsFlagstatCmdStr = ""
samtoolsFlagstatCmdStr = " ".join(samtoolsFlagstatCmd)
print(samtoolsFlagstatCmdStr)
try:
# could not get subprocess.run, .call etc to work with pipes and redirect '>'
os.system(samtoolsFlagstatCmdStr)
except:
print("########################################")
print("##### Error with flagstat")
print("########################################")
sys.exit(1)
# No rejigfiles needed as dead end
return 0
def runGetUnmappedReads(stage_infile, readType):
# Stage output not used further in flow
stage = "Get unmapped reads from BAM"
print("###### " + stage + " ######")
unmappedFastq = [stage_infile, ".unmapped.fastq"]
unmappedFastqString = ""
unmappedFastqString = "".join(unmappedFastq)
if readType == "SE":
samtoolsGetUnmappedCmd = [
path_samtools,
"view",
"-f",
"4",
stage_infile,
"|",
path_samtools,
"bam2fq",
"-",
">",
unmappedFastqString,
]
if readType == "PE":
# complex, 3 types, only deal with cases where both PE reads unmapped -u -f 12 -F 256
samtoolsGetUnmappedCmd = [
path_samtools,
"view",
"-u",
"-f",
"12",
"-F",
"256",
stage_infile,
"|",
path_samtools,
"bam2fq",
"-0",
unmappedFastqString,
"-",
]