-
Notifications
You must be signed in to change notification settings - Fork 43
/
Snakefile
1645 lines (1309 loc) · 65.8 KB
/
Snakefile
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
configfile: "../config/config.yaml"
import os
import glob
def get_ids_from_path_pattern(path_pattern):
ids = sorted([os.path.basename(os.path.splitext(val)[0])
for val in (glob.glob(path_pattern))])
return ids
gemIDs = get_ids_from_path_pattern('GEMs/*.xml')
binIDs = get_ids_from_path_pattern('protein_bins/*.faa')
IDs = get_ids_from_path_pattern('dataset/*')
speciesIDs = get_ids_from_path_pattern('pangenome/speciesBinIDs/*.txt')
DATA_READS_1 = f'{config["path"]["root"]}/{config["folder"]["data"]}/{{IDs}}/{{IDs}}_R1.fastq.gz'
DATA_READS_2 = f'{config["path"]["root"]}/{config["folder"]["data"]}/{{IDs}}/{{IDs}}_R2.fastq.gz'
focal = get_ids_from_path_pattern('dataset/*')
rule all:
input:
expand(config["path"]["root"]+"/"+config["folder"]["qfiltered"]+"/{IDs}/{IDs}_R1.fastq.gz", IDs = IDs)
message:
"""
WARNING: Be very careful when adding/removing any lines above this message.
The metaGEM.sh parser is presently hardcoded to edit line 22 of this Snakefile to expand target rules accordingly,
therefore adding/removing any lines before this message will likely result in parser malfunction.
"""
shell:
"""
echo "Gathering {input} ... "
"""
rule createFolders:
input:
config["path"]["root"]
message:
"""
Very simple rule to check that the metaGEM.sh parser, Snakefile, and config.yaml file are set up correctly.
Generates folders from config.yaml config file, not strictly necessary to run this rule.
"""
shell:
"""
cd {input}
echo -e "Setting up result folders in the following work directory: $(echo {input}) \n"
# Generate folders.txt by extracting folder names from config.yaml file
paste config.yaml |cut -d':' -f2|tail -n +4|head -n 25|sed '/^$/d' > folders.txt # NOTE: hardcoded numbers (tail 4, head 25) for folder names, increase number as new folders are introduced.
while read line;do
echo "Creating $line folder ... "
mkdir -p $line;
done < folders.txt
echo -e "\nDone creating folders. \n"
rm folders.txt
"""
rule downloadToy:
input:
f'{config["path"]["root"]}/{config["folder"]["scripts"]}/{config["scripts"]["toy"]}'
message:
"""
Downloads toy samples into dataset folder and organizes into sample-specific sub-folders.
Download a real dataset by replacing the links in the download_toydata.txt file with links to files from your dataset of intertest.
Note: Make sure that the only underscores (e.g. _) that appear in the filenames are between the sample ID and R1/R2 identifier.
"""
shell:
"""
cd {config[path][root]}/{config[folder][data]}
# Download each link in download_toydata.txt
echo -e "\nBegin downloading toy dataset ... "
while read line;do
wget $line;
done < {input}
echo -e "\nDone donwloading dataset."
# Rename downloaded files, this is only necessary for toy dataset (will cause error if used for real dataset)
echo -ne "\nRenaming downloaded files ... "
for file in *;do
mv $file ./$(echo $file|sed 's/?download=1//g'|sed 's/_/_R/g');
done
echo -e " done. \n"
# Organize data into sample specific sub-folders
echo -ne "Generating list of unique sample IDs ... "
for file in *.gz; do
echo $file;
done | sed 's/_.*$//g' | sed 's/.fastq.gz//g' | uniq > ID_samples.txt
echo -e " done.\n $(less ID_samples.txt|wc -l) samples identified."
echo -ne "\nOrganizing downloaded files into sample specific sub-folders ... "
while read line; do
mkdir -p $line;
mv $line*.gz $line;
done < ID_samples.txt
echo " done."
rm ID_samples.txt
"""
rule organizeData:
input:
f'{config["path"]["root"]}/{config["folder"]["data"]}'
message:
"""
Sorts paired end raw reads into sample specific sub folders within the dataset folder specified in the config.yaml file.
Assumes all samples are present in dataset folder.
Note: This rule is meant to be run on real datasets.
downloadToy rule above sorts the downloaded data already.
Assumes file names have format: SAMPLEID_R1|R2.fastq.gz, e.g. ERR599026_R2.fastq.gz
"""
shell:
"""
cd {input}
echo -ne "\nGenerating list of unique sample IDs ... "
# Create list of unique sample IDs
for file in *.gz; do
echo $file;
done | sed 's/_[^_]*$//g' | sed 's/.fastq.gz//g' | uniq > ID_samples.txt
echo -e " done.\n $(less ID_samples.txt|wc -l) samples identified.\n"
# Create folder and move corresponding files for each sample
echo -ne "\nOrganizing dataset into sample specific sub-folders ... "
while read line; do
mkdir -p $line;
mv $line*.gz $line;
done < ID_samples.txt
echo -e " done. \n"
rm ID_samples.txt
"""
rule qfilter:
input:
R1 = DATA_READS_1,
R2 = DATA_READS_2
output:
R1 = f'{config["path"]["root"]}/{config["folder"]["qfiltered"]}/{{IDs}}/{{IDs}}_R1.fastq.gz',
R2 = f'{config["path"]["root"]}/{config["folder"]["qfiltered"]}/{{IDs}}/{{IDs}}_R2.fastq.gz'
shell:
"""
# Activate metagem environment
echo -e "Activating {config[envs][metagem]} conda environment ... "
set +u;source activate {config[envs][metagem]};set -u;
# This is just to make sure that output folder exists
mkdir -p $(dirname {output.R1})
# Make job specific scratch dir
idvar=$(echo $(basename $(dirname {output.R1}))|sed 's/_R1.fastq.gz//g')
echo -e "\nCreating temporary directory {config[path][scratch]}/{config[folder][qfiltered]}/${{idvar}} ... "
mkdir -p {config[path][scratch]}/{config[folder][qfiltered]}/${{idvar}}
# Move into scratch dir
cd {config[path][scratch]}/{config[folder][qfiltered]}/${{idvar}}
# Copy files
echo -e "Copying {input.R1} and {input.R2} to {config[path][scratch]}/{config[folder][qfiltered]}/${{idvar}} ... "
cp {input.R1} {input.R2} .
echo -e "Appending .raw to temporary input files to avoid name conflict ... "
for file in *.gz; do mv -- "$file" "${{file}}.raw.gz"; done
# Run fastp
echo -n "Running fastp ... "
fastp --thread {config[cores][fastp]} \
-i *R1*raw.gz \
-I *R2*raw.gz \
-o $(basename {output.R1}) \
-O $(basename {output.R2}) \
-j $(dirname {output.R1})/$(echo $(basename $(dirname {output.R1}))).json \
-h $(dirname {output.R1})/$(echo $(basename $(dirname {output.R1}))).html
# Move output files to root dir
echo -e "Moving output files $(basename {output.R1}) and $(basename {output.R2}) to $(dirname {output.R1})"
mv $(basename {output.R1}) $(basename {output.R2}) $(dirname {output.R1})
# Warning
echo -e "Note that you must manually clean up these temporary directories if your scratch directory points to a static location instead of variable with a job specific location ... "
# Done message
echo -e "Done quality filtering sample ${{idvar}}"
"""
rule qfilterVis:
input:
f'{config["path"]["root"]}/{config["folder"]["qfiltered"]}'
output:
text = f'{config["path"]["root"]}/{config["folder"]["stats"]}/qfilter.stats',
plot = f'{config["path"]["root"]}/{config["folder"]["stats"]}/qfilterVis.pdf'
shell:
"""
# Activate metagem env
set +u;source activate {config[envs][metagem]};set -u;
# Make sure stats folder exists
mkdir -p $(dirname {output.text})
# Move into qfiltered folder
cd {input}
# Read and summarize files
echo -e "\nGenerating quality filtering results file qfilter.stats: ... "
for folder in */;do
for file in $folder*json;do
# Define sample
ID=$(echo $file|sed 's|/.*$||g')
# Reads before filtering
readsBF=$(head -n 25 $file|grep total_reads|cut -d ':' -f2|sed 's/,//g'|head -n 1)
# Reads after filtering
readsAF=$(head -n 25 $file|grep total_reads|cut -d ':' -f2|sed 's/,//g'|tail -n 1)
# Bases before filtering
basesBF=$(head -n 25 $file|grep total_bases|cut -d ':' -f2|sed 's/,//g'|head -n 1)
# Bases after filtering
basesAF=$(head -n 25 $file|grep total_bases|cut -d ':' -f2|sed 's/,//g'|tail -n 1)
# Q20 bases before filtering
q20BF=$(head -n 25 $file|grep q20_rate|cut -d ':' -f2|sed 's/,//g'|head -n 1)
# Q20 bases after filtering
q20AF=$(head -n 25 $file|grep q20_rate|cut -d ':' -f2|sed 's/,//g'|tail -n 1)
# Q30 bases before filtering
q30BF=$(head -n 25 $file|grep q30_rate|cut -d ':' -f2|sed 's/,//g'|head -n 1)
# Q30 bases after filtering
q30AF=$(head -n 25 $file|grep q30_rate|cut -d ':' -f2|sed 's/,//g'|tail -n 1)
# Percentage of reads kept after filtering
percent=$(awk -v RBF="$readsBF" -v RAF="$readsAF" 'BEGIN{{print RAF/RBF}}' )
# Write values to qfilter.stats file
echo "$ID $readsBF $readsAF $basesBF $basesAF $percent $q20BF $q20AF $q30BF $q30AF" >> qfilter.stats
# Print values
echo "Sample $ID retained $percent * 100 % of reads ... "
done
done
echo "Done summarizing quality filtering results ... \nMoving to /stats/ folder and running plotting script ... "
mv qfilter.stats {config[path][root]}/{config[folder][stats]}
# Move to stats folder
cd {config[path][root]}/{config[folder][stats]}
# Run script for quality filter visualization
Rscript {config[path][root]}/{config[folder][scripts]}/{config[scripts][qfilterVis]}
echo "Done. "
# Remove duplicate/extra plot
rm Rplots.pdf
"""
rule megahit:
input:
R1 = rules.qfilter.output.R1,
R2 = rules.qfilter.output.R2
output:
f'{config["path"]["root"]}/{config["folder"]["assemblies"]}/{{IDs}}/contigs.fasta.gz'
benchmark:
f'{config["path"]["root"]}/{config["folder"]["benchmarks"]}/{{IDs}}.megahit.benchmark.txt'
shell:
"""
# Activate metagem environment
set +u;source activate {config[envs][metagem]};set -u;
# Make sure that output folder exists
mkdir -p $(dirname {output})
# Make job specific scratch dir
idvar=$(echo $(basename $(dirname {output})))
echo -e "\nCreating temporary directory {config[path][scratch]}/{config[folder][assemblies]}/${{idvar}} ... "
mkdir -p {config[path][scratch]}/{config[folder][assemblies]}/${{idvar}}
# Move into scratch dir
cd {config[path][scratch]}/{config[folder][assemblies]}/${{idvar}}
# Copy files
echo -n "Copying qfiltered reads to {config[path][scratch]}/${{idvar}} ... "
cp {input.R1} {input.R2} .
echo "done. "
# Run megahit
echo -n "Running MEGAHIT ... "
megahit -t {config[cores][megahit]} \
--presets {config[params][assemblyPreset]} \
--verbose \
--min-contig-len {config[params][assemblyMin]} \
-1 $(basename {input.R1}) \
-2 $(basename {input.R2}) \
-o tmp;
echo "done. "
# Rename assembly
echo "Renaming assembly ... "
mv tmp/final.contigs.fa contigs.fasta
# Remove spaces from contig headers and replace with hyphens
echo "Fixing contig header names: replacing spaces with hyphens ... "
sed -i 's/ /-/g' contigs.fasta
# Zip and move assembly to output folder
echo "Zipping and moving assembly ... "
gzip contigs.fasta
mv contigs.fasta.gz $(dirname {output})
# Done message
echo -e "Done assembling quality filtered reads for sample ${{idvar}}"
"""
rule assemblyVis:
input:
f'{config["path"]["root"]}/{config["folder"]["assemblies"]}'
message:
"""
Note that this rule is designed to read megahit assemblies with hyphens instead of
spaces in contig headers as generated by the megahit rule above.
"""
output:
text = f'{config["path"]["root"]}/{config["folder"]["stats"]}/assembly.stats',
plot = f'{config["path"]["root"]}/{config["folder"]["stats"]}/assemblyVis.pdf',
shell:
"""
# Activate metagem env
set +uo pipefail;source activate {config[envs][metagem]};set -u;
# Make sure stats folder exists
mkdir -p $(dirname {output.text})
# Move into assembly folder
cd {input}
echo -e "\nGenerating assembly results file assembly.stats: ... "
while read assembly;do
# Define sample ID
ID=$(echo $(basename $(dirname $assembly)))
# Check if assembly file is empty
check=$(zcat $assembly | head | wc -l)
if [ $check -eq 0 ]
then
N=0
L=0
else
N=$(zcat $assembly | grep -c ">");
L=$(zcat $assembly | grep ">"|cut -d '-' -f4|sed 's/len=//'|awk '{{sum+=$1}}END{{print sum}}');
fi
# Write values to stats file
echo $ID $N $L >> assembly.stats;
# Print values to terminal
echo -e "Sample $ID has a total of $L bp across $N contigs ... "
done< <(find {input} -name "*.gz")
echo "Done summarizing assembly results ... \nMoving to /stats/ folder and running plotting script ... "
mv assembly.stats {config[path][root]}/{config[folder][stats]}
# Move to stats folder
cd {config[path][root]}/{config[folder][stats]}
# Running assembly Vis R script
Rscript {config[path][root]}/{config[folder][scripts]}/{config[scripts][assemblyVis]}
echo "Done. "
# Remove unnecessary file
rm Rplots.pdf
"""
rule crossMapSeries:
input:
contigs = rules.megahit.output,
reads = f'{config["path"]["root"]}/{config["folder"]["qfiltered"]}'
output:
concoct = directory(f'{config["path"]["root"]}/{config["folder"]["concoct"]}/{{IDs}}/cov'),
metabat = directory(f'{config["path"]["root"]}/{config["folder"]["metabat"]}/{{IDs}}/cov'),
maxbin = directory(f'{config["path"]["root"]}/{config["folder"]["maxbin"]}/{{IDs}}/cov')
benchmark:
f'{config["path"]["root"]}/{config["folder"]["benchmarks"]}/{{IDs}}.crossMapSeries.benchmark.txt'
message:
"""
Cross map in seies:
Use this approach to provide all 3 binning tools with cross-sample coverage information.
Will likely provide superior binning results, but may no be feasible for datasets with
many large samples such as the tara oceans dataset.
"""
shell:
"""
# Activate metagem environment
set +u;source activate {config[envs][metagem]};set -u;
# Create output folders
mkdir -p {output.concoct}
mkdir -p {output.metabat}
mkdir -p {output.maxbin}
# Make job specific scratch dir
idvar=$(echo $(basename $(dirname {output.concoct})))
echo -e "\nCreating temporary directory {config[path][scratch]}/{config[folder][crossMap]}/${{idvar}} ... "
mkdir -p {config[path][scratch]}/{config[folder][crossMap]}/${{idvar}}
# Move into scratch dir
cd {config[path][scratch]}/{config[folder][crossMap]}/${{idvar}}
# Copy files
cp {input.contigs} .
# Define the focal sample ID, fsample:
# The one sample's assembly that all other samples' read will be mapped against in a for loop
fsampleID=$(echo $(basename $(dirname {input.contigs})))
echo -e "\nFocal sample: $fsampleID ... "
echo "Renaming and unzipping assembly ... "
mv $(basename {input.contigs}) $(echo $fsampleID|sed 's/$/.fa.gz/g')
gunzip $(echo $fsampleID|sed 's/$/.fa.gz/g')
echo -e "\nIndexing assembly ... "
bwa index $fsampleID.fa
for folder in {input.reads}/*;do
id=$(basename $folder)
echo -e "\nCopying sample $id to be mapped against the focal sample $fsampleID ..."
cp $folder/*.gz .
# Maybe I should be piping the lines below to reduce I/O ?
echo -e "\nMapping sample to assembly ... "
bwa mem -t {config[cores][crossMap]} $fsampleID.fa *.fastq.gz > $id.sam
echo -e "\nConverting SAM to BAM with samtools view ... "
samtools view -@ {config[cores][crossMap]} -Sb $id.sam > $id.bam
echo -e "\nSorting BAM file with samtools sort ... "
samtools sort -@ {config[cores][crossMap]} -o $id.sort $id.bam
echo -e "\nRunning jgi_summarize_bam_contig_depths script to generate contig abundance/depth file for maxbin2 input ... "
jgi_summarize_bam_contig_depths --outputDepth $id.depth $id.sort
echo -e "\nMoving depth file to sample $fsampleID maxbin2 folder ... "
mv $id.depth {output.maxbin}
echo -e "\nIndexing sorted BAM file with samtools index for CONCOCT input table generation ... "
samtools index $id.sort
echo -e "\nRemoving temporary files ... "
rm *.fastq.gz *.sam *.bam
done
nSamples=$(ls {input.reads}|wc -l)
echo -e "\nDone mapping focal sample $fsampleID agains $nSamples samples in dataset folder."
echo -e "\nRunning jgi_summarize_bam_contig_depths for all sorted bam files to generate metabat2 input ... "
jgi_summarize_bam_contig_depths --outputDepth $id.all.depth *.sort
echo -e "\nMoving input file $id.all.depth to $fsampleID metabat2 folder... "
mv $id.all.depth {output.metabat}
echo -e "Done. \nCutting up contigs to 10kbp chunks (default), not to be used for mapping!"
cut_up_fasta.py -c {config[params][cutfasta]} -o 0 -m $fsampleID.fa -b assembly_c10k.bed > assembly_c10k.fa
echo -e "\nSummarizing sorted and indexed BAM files with concoct_coverage_table.py to generate CONCOCT input table ... "
concoct_coverage_table.py assembly_c10k.bed *.sort > coverage_table.tsv
echo -e "\nMoving CONCOCT input table to $fsampleID concoct folder"
mv coverage_table.tsv {output.concoct}
echo -e "\nRemoving intermediate sorted bam files ... "
rm *.sort
"""
rule kallistoIndex:
input:
f'{config["path"]["root"]}/{config["folder"]["assemblies"]}/{{focal}}/contigs.fasta.gz'
output:
f'{config["path"]["root"]}/{config["folder"]["kallistoIndex"]}/{{focal}}/index.kaix'
benchmark:
f'{config["path"]["root"]}/{config["folder"]["benchmarks"]}/{{focal}}.kallistoIndex.benchmark.txt'
message:
"""
Needed for the crossMapParallel implementation, which uses kalliso for fast mapping instead of bwa.
Saves a lot of computational power/time to only create once and re-use for each job.
"""
shell:
"""
# Activate metagem environment
set +u;source activate {config[envs][metagem]};set -u;
# Create output folder
mkdir -p $(dirname {output})
# Make job specific scratch dir
sampleID=$(echo $(basename $(dirname {input})))
echo -e "\nCreating temporary directory {config[path][scratch]}/{config[folder][kallistoIndex]}/${{sampleID}} ... "
mkdir -p {config[path][scratch]}/{config[folder][kallistoIndex]}/${{sampleID}}
# Move into scratch dir
cd {config[path][scratch]}/{config[folder][kallistoIndex]}/${{sampleID}}
# Copy files
echo -e "\nCopying and unzipping sample $sampleID assembly ... "
cp {input} .
# Rename files
mv $(basename {input}) $(echo $sampleID|sed 's/$/.fa.gz/g')
gunzip $(echo $sampleID|sed 's/$/.fa.gz/g')
echo -e "\nCutting up assembly contigs >= 20kbp into 10kbp chunks ... "
cut_up_fasta.py $sampleID.fa -c 10000 -o 0 --merge_last > contigs_10K.fa
echo -e "\nCreating kallisto index ... "
kallisto index contigs_10K.fa -i index.kaix
mv index.kaix $(dirname {output})
"""
rule crossMapParallel:
input:
index = f'{config["path"]["root"]}/{config["folder"]["kallistoIndex"]}/{{focal}}/index.kaix',
R1 = f'{config["path"]["root"]}/{config["folder"]["qfiltered"]}/{{IDs}}/{{IDs}}_R1.fastq.gz',
R2 = f'{config["path"]["root"]}/{config["folder"]["qfiltered"]}/{{IDs}}/{{IDs}}_R2.fastq.gz'
output:
directory(f'{config["path"]["root"]}/{config["folder"]["kallisto"]}/{{focal}}/{{IDs}}')
benchmark:
f'{config["path"]["root"]}/{config["folder"]["benchmarks"]}/{{focal}}.{{IDs}}.crossMapParallel.benchmark.txt'
message:
"""
This rule is an alternative implementation of crossMapSeries, using kallisto
instead of bwa for mapping operations. This implementation is recommended for
large datasets.
"""
shell:
"""
# Activate metagem environment
set +u;source activate {config[envs][metagem]};set -u;
# Create output folder
mkdir -p {output}
# Make job specific scratch dir
focal=$(echo $(basename $(dirname {input.index})))
mapping=$(echo $(basename $(dirname {input.R1})))
echo -e "\nCreating temporary directory {config[path][scratch]}/{config[folder][kallisto]}/${{focal}}_${{mapping}} ... "
mkdir -p {config[path][scratch]}/{config[folder][kallisto]}/${{focal}}_${{mapping}}
# Move into tmp dir
cd {config[path][scratch]}/{config[folder][kallisto]}/${{focal}}_${{mapping}}
# Copy files
echo -e "\nCopying assembly index {input.index} and reads {input.R1} {input.R2} to $(pwd) ... "
cp {input.index} {input.R1} {input.R2} .
# Run kallisto
echo -e "\nRunning kallisto ... "
kallisto quant --threads {config[cores][crossMap]} --plaintext -i index.kaix -o . $(basename {input.R1}) $(basename {input.R2})
# Zip file
echo -e "\nZipping abundance file ... "
gzip abundance.tsv
# Move mapping file out output folder
mv abundance.tsv.gz {output}
# Cleanup temp folder
echo -e "\nRemoving temporary directory {config[path][scratch]}/{config[folder][kallisto]}/${{focal}}_${{mapping}} ... "
cd -
rm -r {config[path][scratch]}/{config[folder][kallisto]}/${{focal}}_${{mapping}}
"""
rule gatherCrossMapParallel:
input:
expand(f'{config["path"]["root"]}/{config["folder"]["kallisto"]}/{{focal}}/{{IDs}}', focal = focal , IDs = IDs)
shell:
"""
echo "Gathering cross map jobs ..."
"""
rule concoct:
input:
table = f'{config["path"]["root"]}/{config["folder"]["concoct"]}/{{IDs}}/cov/coverage_table.tsv',
contigs = rules.megahit.output
output:
directory(f'{config["path"]["root"]}/{config["folder"]["concoct"]}/{{IDs}}/{{IDs}}.concoct-bins')
benchmark:
f'{config["path"]["root"]}/{config["folder"]["benchmarks"]}/{{IDs}}.concoct.benchmark.txt'
shell:
"""
# Activate metagem environment
set +u;source activate {config[envs][metagem]};set -u;
# Create output folder
mkdir -p $(dirname {output})
# Make job specific scratch dir
sampleID=$(echo $(basename $(dirname {input.contigs})))
echo -e "\nCreating temporary directory {config[path][scratch]}/{config[folder][concoct]}/${{sampleID}} ... "
mkdir -p {config[path][scratch]}/{config[folder][concoct]}/${{sampleID}}
# Move into scratch dir
cd {config[path][scratch]}/{config[folder][concoct]}/${{sampleID}}
# Copy files
cp {input.contigs} {input.table} .
echo "Unzipping assembly ... "
gunzip $(basename {input.contigs})
echo -e "Done. \nCutting up contigs (default 10kbp chunks) ... "
cut_up_fasta.py -c {config[params][cutfasta]} -o 0 -m $(echo $(basename {input.contigs})|sed 's/.gz//') > assembly_c10k.fa
echo -e "\nRunning CONCOCT ... "
concoct --coverage_file $(basename {input.table}) \
--composition_file assembly_c10k.fa \
-b $(basename $(dirname {output})) \
-t {config[cores][concoct]} \
-c {config[params][concoct]}
echo -e "\nMerging clustering results into original contigs ... "
merge_cutup_clustering.py $(basename $(dirname {output}))_clustering_gt1000.csv > $(basename $(dirname {output}))_clustering_merged.csv
echo -e "\nExtracting bins ... "
mkdir -p $(basename {output})
extract_fasta_bins.py $(echo $(basename {input.contigs})|sed 's/.gz//') $(basename $(dirname {output}))_clustering_merged.csv --output_path $(basename {output})
# Move final result files to output folder
mv $(basename {output}) *.txt *.csv $(dirname {output})
"""
rule metabatCross:
input:
assembly = rules.megahit.output,
depth = f'{config["path"]["root"]}/{config["folder"]["metabat"]}/{{IDs}}/cov'
output:
directory(f'{config["path"]["root"]}/{config["folder"]["metabat"]}/{{IDs}}/{{IDs}}.metabat-bins')
benchmark:
f'{config["path"]["root"]}/{config["folder"]["benchmarks"]}/{{IDs}}.metabat.benchmark.txt'
shell:
"""
# Activate metagem environment
set +u;source activate {config[envs][metagem]};set -u;
# Create output folder
mkdir -p {output}
# Make job specific scratch dir
fsampleID=$(echo $(basename $(dirname {input.assembly})))
echo -e "\nCreating temporary directory {config[path][scratch]}/{config[folder][metabat]}/${{fsampleID}} ... "
mkdir -p {config[path][scratch]}/{config[folder][metabat]}/${{fsampleID}}
# Move into scratch dir
cd {config[path][scratch]}/{config[folder][metabat]}/${{fsampleID}}
# Copy files to tmp
cp {input.assembly} {input.depth}/*.all.depth .
# Unzip assembly
gunzip $(basename {input.assembly})
# Run metabat2
echo -e "\nRunning metabat2 ... "
metabat2 -i contigs.fasta -a *.all.depth -s {config[params][metabatMin]} -v --seed {config[params][seed]} -t 0 -m {config[params][minBin]} -o $(basename $(dirname {output}))
# Move result files to output dir
mv *.fa {output}
"""
rule maxbinCross:
input:
assembly = rules.megahit.output,
depth = f'{config["path"]["root"]}/{config["folder"]["maxbin"]}/{{IDs}}/cov'
output:
directory(f'{config["path"]["root"]}/{config["folder"]["maxbin"]}/{{IDs}}/{{IDs}}.maxbin-bins')
benchmark:
f'{config["path"]["root"]}/{config["folder"]["benchmarks"]}/{{IDs}}.maxbin.benchmark.txt'
shell:
"""
# Activate metagem environment
set +u;source activate {config[envs][metagem]};set -u;
# Create output folder
mkdir -p $(dirname {output})
# Make job specific scratch dir
fsampleID=$(echo $(basename $(dirname {input.assembly})))
echo -e "\nCreating temporary directory {config[path][scratch]}/{config[folder][maxbin]}/${{fsampleID}} ... "
mkdir -p {config[path][scratch]}/{config[folder][maxbin]}/${{fsampleID}}
# Move into scratch dir
cd {config[path][scratch]}/{config[folder][maxbin]}/${{fsampleID}}
# Copy files to tmp
cp -r {input.assembly} {input.depth}/*.depth .
echo -e "\nUnzipping assembly ... "
gunzip $(basename {input.assembly})
echo -e "\nGenerating list of depth files based on crossMapSeries rule output ... "
find . -name "*.depth" > abund.list
echo -e "\nRunning maxbin2 ... "
run_MaxBin.pl -thread {config[cores][maxbin]} -contig contigs.fasta -out $(basename $(dirname {output})) -abund_list abund.list
# Clean up un-needed files
rm *.depth abund.list contigs.fasta
# Move files into output dir
mkdir -p $(basename {output})
while read bin;do mv $bin $(basename {output});done< <(ls|grep fasta)
mv * $(dirname {output})
"""
rule binning:
input:
concoct = expand(config["path"]["root"]+"/"+config["folder"]["concoct"]+"/{IDs}/{IDs}.concoct-bins", IDs = IDs),
maxbin = expand(config["path"]["root"]+"/"+config["folder"]["maxbin"]+"/{IDs}/{IDs}.maxbin-bins", IDs = IDs),
metabat = expand(config["path"]["root"]+"/"+config["folder"]["metabat"]+"/{IDs}/{IDs}.metabat-bins", IDs = IDs)
rule binRefine:
input:
concoct = f'{config["path"]["root"]}/{config["folder"]["concoct"]}/{{IDs}}/{{IDs}}.concoct-bins',
metabat = f'{config["path"]["root"]}/{config["folder"]["metabat"]}/{{IDs}}/{{IDs}}.metabat-bins',
maxbin = f'{config["path"]["root"]}/{config["folder"]["maxbin"]}/{{IDs}}/{{IDs}}.maxbin-bins'
output:
directory(f'{config["path"]["root"]}/{config["folder"]["refined"]}/{{IDs}}')
benchmark:
f'{config["path"]["root"]}/{config["folder"]["benchmarks"]}/{{IDs}}.binRefine.benchmark.txt'
shell:
"""
# Activate metawrap environment
set +u;source activate {config[envs][metawrap]};set -u;
# Create output folder
mkdir -p {output}
# Make job specific scratch dir
fsampleID=$(echo $(basename $(dirname {input.concoct})))
echo -e "\nCreating temporary directory {config[path][scratch]}/{config[folder][refined]}/${{fsampleID}} ... "
mkdir -p {config[path][scratch]}/{config[folder][refined]}/${{fsampleID}}
# Move into scratch dir
cd {config[path][scratch]}/{config[folder][refined]}/${{fsampleID}}
# Copy files to tmp
echo "Copying bins from CONCOCT, metabat2, and maxbin2 to {config[path][scratch]} ... "
cp -r {input.concoct} {input.metabat} {input.maxbin} .
echo "Renaming bin folders to avoid errors with metaWRAP ... "
mv $(basename {input.concoct}) $(echo $(basename {input.concoct})|sed 's/-bins//g')
mv $(basename {input.metabat}) $(echo $(basename {input.metabat})|sed 's/-bins//g')
mv $(basename {input.maxbin}) $(echo $(basename {input.maxbin})|sed 's/-bins//g')
echo "Running metaWRAP bin refinement module ... "
metaWRAP bin_refinement -o . \
-A $(echo $(basename {input.concoct})|sed 's/-bins//g') \
-B $(echo $(basename {input.metabat})|sed 's/-bins//g') \
-C $(echo $(basename {input.maxbin})|sed 's/-bins//g') \
-t {config[cores][refine]} \
-m {config[params][refineMem]} \
-c {config[params][refineComp]} \
-x {config[params][refineCont]}
rm -r $(echo $(basename {input.concoct})|sed 's/-bins//g') $(echo $(basename {input.metabat})|sed 's/-bins//g') $(echo $(basename {input.maxbin})|sed 's/-bins//g') work_files
mv * {output}
"""
rule binReassemble:
input:
R1 = rules.qfilter.output.R1,
R2 = rules.qfilter.output.R2,
refinedBins = rules.binRefine.output
output:
directory(f'{config["path"]["root"]}/{config["folder"]["reassembled"]}/{{IDs}}')
benchmark:
f'{config["path"]["root"]}/{config["folder"]["benchmarks"]}/{{IDs}}.binReassemble.benchmark.txt'
shell:
"""
# Activate metawrap environment
set +u;source activate {config[envs][metawrap]};set -u;
# Prevents spades from using just one thread
export OMP_NUM_THREADS={config[cores][reassemble]}
# Create output folder
mkdir -p {output}
# Make job specific scratch dir
fsampleID=$(echo $(basename $(dirname {input.R1})))
echo -e "\nCreating temporary directory {config[path][scratch]}/{config[folder][reassembled]}/${{fsampleID}} ... "
mkdir -p {config[path][scratch]}/{config[folder][reassembled]}/${{fsampleID}}
# Move into scratch dir
cd {config[path][scratch]}/{config[folder][reassembled]}/${{fsampleID}}
# Copy files to tmp
cp -r {input.refinedBins}/metawrap_*_bins {input.R1} {input.R2} .
echo "Running metaWRAP bin reassembly ... "
metaWRAP reassemble_bins --parallel -o $(basename {output}) \
-b metawrap_*_bins \
-1 $(basename {input.R1}) \
-2 $(basename {input.R2}) \
-t {config[cores][reassemble]} \
-m {config[params][reassembleMem]} \
-c {config[params][reassembleComp]} \
-x {config[params][reassembleCont]}
# Cleaning up files
rm -r metawrap_*_bins
rm -r $(basename {output})/work_files
rm *.fastq.gz
# Move results to output folder
mv * $(dirname {output})
"""
rule binEvaluation:
input:
refined = expand(config["path"]["root"]+"/"+config["folder"]["refined"]+"/{IDs}", IDs = IDs),
reassembled = expand(config["path"]["root"]+"/"+config["folder"]["reassembled"]+"/{IDs}", IDs = IDs)
rule binningVis:
input:
f'{config["path"]["root"]}'
output:
text = f'{config["path"]["root"]}/{config["folder"]["stats"]}/reassembled_bins.stats',
plot = f'{config["path"]["root"]}/{config["folder"]["stats"]}/binningVis.pdf'
message:
"""
Generate bar plot with number of bins and density plot of bin contigs,
total length, completeness, and contamination across different tools.
"""
shell:
"""
# Activate metagem env
set +u;source activate {config[envs][metagem]};set -u;
# Read CONCOCT bins
echo "Generating concoct_bins.stats file containing bin ID, number of contigs, and length ... "
cd {input}/{config[folder][concoct]}
for folder in */;do
# Define sample name
var=$(echo $folder|sed 's|/||g');
for bin in $folder*concoct-bins/*.fa;do
# Define bin name
name=$(echo $bin | sed "s|^.*/|$var.bin.|g" | sed 's/.fa//g');
# Count contigs
N=$(less $bin | grep -c ">");
# Sum length
L=$(less $bin |grep ">"|cut -d '-' -f4|sed 's/len=//g'|awk '{{sum+=$1}}END{{print sum}}')
# Print values to terminal and write to stats file
echo "Reading bin $bin ... Contigs: $N , Length: $L "
echo $name $N $L >> concoct_bins.stats;
done;
done
mv *.stats {input}/{config[folder][reassembled]}
# Read MetaBAT2 bins
echo "Generating metabat_bins.stats file containing bin ID, number of contigs, and length ... "
cd {input}/{config[folder][metabat]}
for folder in */;do
# Define sample name
var=$(echo $folder | sed 's|/||');
for bin in $folder*metabat-bins/*.fa;do
# Define bin name
name=$(echo $bin|sed 's/.fa//g'|sed 's|^.*/||g'|sed "s/^/$var./g");
# Count contigs
N=$(less $bin | grep -c ">");
# Sum length
L=$(less $bin |grep ">"|cut -d '-' -f4|sed 's/len=//g'|awk '{{sum+=$1}}END{{print sum}}')
# Print values to terminal and write to stats file
echo "Reading bin $bin ... Contigs: $N , Length: $L "
echo $name $N $L >> metabat_bins.stats;
done;
done
mv *.stats {input}/{config[folder][reassembled]}
# Read MaxBin2 bins
echo "Generating maxbin_bins.stats file containing bin ID, number of contigs, and length ... "
cd {input}/{config[folder][maxbin]}
for folder in */;do
for bin in $folder*maxbin-bins/*.fasta;do
# Define bin name
name=$(echo $bin | sed 's/.fasta//g' | sed 's|^.*/||g');
# Count contigs
N=$(less $bin | grep -c ">");
# Sum length
L=$(less $bin |grep ">"|cut -d '-' -f4|sed 's/len=//g'|awk '{{sum+=$1}}END{{print sum}}')
# Print values to terminal and write to stats file
echo "Reading bin $bin ... Contigs: $N , Length: $L "
echo $name $N $L >> maxbin_bins.stats;
done;
done
mv *.stats {input}/{config[folder][reassembled]}
# Read metaWRAP refined bins
echo "Generating refined_bins.stats file containing bin ID, number of contigs, and length ... "
cd {input}/{config[folder][refined]}
for folder in */;do
# Define sample name
samp=$(echo $folder | sed 's|/||');
for bin in $folder*metawrap_*_bins/*.fa;do
# Define bin name
name=$(echo $bin | sed 's/.fa//g'|sed 's|^.*/||g'|sed "s/^/$samp./g");
# Count contigs
N=$(less $bin | grep -c ">");
# Sum length
L=$(less $bin |grep ">"|cut -d '-' -f4|sed 's/len_//g'|awk '{{sum+=$1}}END{{print sum}}')
# Print values to terminal and write to stats file
echo "Reading bin $bin ... Contigs: $N , Length: $L "
echo $name $N $L >> refined_bins.stats;
done;
done
# Compile CONCOCT, MetaBAT2, MaxBin2, and metaWRAP checkM files
echo "Generating CheckM summary files across samples: concoct.checkm, metabat.checkm, maxbin.checkm, and refined.checkm ... "
for folder in */;do
# Define sample name
var=$(echo $folder|sed 's|/||g');
# Write values to checkm files
paste $folder*concoct.stats|tail -n +2 | sed "s/^/$var.bin./g" >> concoct.checkm
paste $folder*metabat.stats|tail -n +2 | sed "s/^/$var./g" >> metabat.checkm
paste $folder*maxbin.stats|tail -n +2 >> maxbin.checkm
paste $folder*metawrap_*_bins.stats|tail -n +2|sed "s/^/$var./g" >> refined.checkm
done
mv *.stats *.checkm {input}/{config[folder][reassembled]}
# Read metaWRAP reassembled bins
echo "Generating reassembled_bins.stats file containing bin ID, number of contigs, and length ... "
cd {input}/{config[folder][reassembled]}
for folder in */;do
# Define sample name
samp=$(echo $folder | sed 's|/||');
for bin in $folder*reassembled_bins/*.fa;do
# Define bin name
name=$(echo $bin | sed 's/.fa//g' | sed 's|^.*/||g' | sed "s/^/$samp./g");
N=$(less $bin | grep -c ">");
# Check if bins are original (megahit-assembled) or strict/permissive (metaspades-assembled)
if [[ $name == *.strict ]] || [[ $name == *.permissive ]];then
L=$(less $bin |grep ">"|cut -d '_' -f4|awk '{{sum+=$1}}END{{print sum}}')
else
L=$(less $bin |grep ">"|cut -d '-' -f4|sed 's/len_//g'|awk '{{sum+=$1}}END{{print sum}}')
fi
# Print values to terminal and write to stats file
echo "Reading bin $bin ... Contigs: $N , Length: $L "
echo $name $N $L >> reassembled_bins.stats;
done;
done
echo "Done reading metawrap reassembled bins ... "