This repository has been archived by the owner on Mar 10, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 11
/
main.nf
1871 lines (1612 loc) · 73.3 KB
/
main.nf
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env nextflow
/*
========================================================================================
nf-core/kmermaid
========================================================================================
nf-core/kmermaid Analysis Pipeline.
#### Homepage / Documentation
https://github.com/nf-core/kmermaid
----------------------------------------------------------------------------------------
*/
def helpMessage() {
log.info nfcoreHeader()
log.info """
=========================================
nf-core/kmermaid v${workflow.manifest.version}
=========================================
Usage:
The typical command for running the pipeline is as follows.
With a samples.csv file containing the columns sample_id,read1,read2:
nextflow run nf-core/kmermaid \
--outdir s3://olgabot-maca/nf-kmer-similarity/ --samples samples.csv
With read pairs in one or more semicolon-separated s3 directories:
nextflow run nf-core/kmermaid \
--outdir s3://olgabot-maca/nf-kmer-similarity/ \
--read_pairs s3://olgabot-maca/sra/homo_sapiens/smartseq2_quartzseq/*{R1,R2}*.fastq.gz;s3://olgabot-maca/sra/danio_rerio/smart-seq/whole_kidney_marrow_prjna393431/*{R1,R2}*.fastq.gz
With plain ole fastas in one or more semicolon-separated s3 directories:
nextflow run nf-core/kmermaid \
--outdir s3://olgabot-maca/nf-kmer-similarity/choanoflagellates_richter2018/ \
--fastas /home/olga/data/figshare/choanoflagellates_richter2018/1_choanoflagellate_transcriptomes/*.fasta
With SRA ids (requires nextflow v19.03-edge or greater):
nextflow run nf-core/kmermaid \
--outdir s3://olgabot-maca/nf-kmer-similarity/ --sra SRP016501
With BAM file:
nextflow run main.nf \
--outdir ./results \
--bam possorted_genome_bam.bam
Mandatory Arguments:
--input [file] Path to input data (must be surrounded with quotes)
-profile [str] Configuration profile to use. Can use multiple (comma separated)
Available: conda, docker, singularity, test, awsbatch, <institute> and more
--outdir [file] Local or S3 directory to output the comparison matrix to
Sample Arguments -- One or more of:
--read_pairs Local or s3 directories containing *R{1,2}*.fastq.gz
files, separated by commas
--read_singles Local or s3 directories of single-end read files, separated by commas
--csv_pairs CSV file with columns id, read1, read2 for each sample
--csv_singles CSV file with columns id, read1, read2 for each sample
--fastas Path to FASTA sequence files. Can be semi-colon-separated
--protein_fastas Path to protein fasta inputs
--bam Path to 10x BAM file
--save_fastas For bam files, Path relative to outdir to save unique barcodes to {CELL_BARCODE}.fasta
--save_intermediate_files save temporary fastas and chunks of bam files
in the absolute path given by this flag
By default, they are saved in temp directory.
An important note is This might cause
not enough space on the device left depending on the size of your bam file and harddisk space allocated for tmp folder on your machine, so its better to specify a directory.
These files are deleted automatically at the end of the program.
--sra SRR, ERR, SRP IDs representing a project. Only compatible with
Nextflow 19.03-edge or greater
Options:
--ksizes Which nucleotide k-mer sizes to use. Multiple are
separated by commas. Default is '21,27,33,51'
--molecules Which molecule to compare on. Default is both DNA
and protein, i.e. 'dna,protein,dayhoff'
--track_abundance Track abundance of each hashed k-mer, could be useful for cancer RNA-seq or ATAC-seq analyses
--skip_trimming If provided, skip fastp trimming of reads
--skip_compare If provided, skip comparison of hashes using sourmash compare
--skip_compute If provided, skip computing of signatures using sourmash compute
--skip_sig_merge If provided, skip merging of aligned/unaligned signatures created from bam files or tenx tgz files
Sketch size options:
--sketch_num_hashes Number of hashes to use for making the sketches.
Mutually exclusive with --sketch_num_hashes_log2
--sketch_num_hashes_log2 Which log2 sketch sizes to use. Multiple are separated by commas.
Default is '10,12,14,16'. Mutually exclusive with --sketch_num_hashes
--sketch_scaled Observe every 1/N hashes per sample, rather than a "flat rate" of N hashes
per sample. This way, the number of hashes scales by the sequencing depth.
Mutually exclusive with --sketch_scaled_log2
--sketch_scaled_log2 Same as --sketch_scaled, but instead of specifying the true number of hashes,
specify the power to take 2 to. Mutually exlusive with --sketch_scaled
Split K-mer options:
--split_kmer If provided, use SKA to compute split k-mer sketches instead of
sourmash to compute k-mer sketches
--subsample Integer value to subsample reads from input fastq files
Bam file options:
--write_barcode_meta_csv For bam files, Csv file name relative to outdir/barcode_metadata to write number of reads and number of umis per barcode.
This csv file is empty with just header when the tenx_min_umi_per_cell is zero i.e
Reads and umis per barcode are calculated only when the barcodes are filtered
based on tenx_min_umi_per_cell
--tenx_min_umi_per_cell A barcode is only considered a valid barcode read
and its signature is written if number of umis are greater than tenx_min_umi_per_cell
--barcodes_file For bam files, Optional absolute path to a .tsv barcodes file if the input is unfiltered 10x bam file
--rename_10x_barcodes For bam files, Optional absolute path to a .tsv Tab-separated file mapping 10x barcode name
to new name, e.g. with channel or cell annotation label
Translate RNA-seq reads into protein-coding sequences options:
--reference_proteome_fasta Path to a well-curated fasta file of protein sequences. Used to filter for coding reads
--translate_peptide_ksize K-mer size to use for translating RNA into protein.
Default: 9, which is good for 'protein'. If using dayhoff, suggest 15
--translate_peptide_molecule Which molecular encoding to use for translating. Default: "protein"
If your reference proteome is quite different from your species of interest,
suggest using "dayhoff" encoding
--translate_jaccard_threshold Minimum fraction of overlapping translated k-mers from the read to match to the reference. Default: 0.95
--bloomfilter_tablesize Maximum table size for bloom filter creation
Other options:
--outdir [file] The output directory where the results will be saved
--publish_dir_mode [str] Mode for publishing results in the output directory. Available: symlink, rellink, link, copy, copyNoFollow, move (Default: copy)
--email [email] Set this parameter to your e-mail address to get a summary e-mail with details of the run sent to you when the workflow exits
--email_on_fail [email] Same as --email, except only send mail if the workflow is not successful
--max_multiqc_email_size [str] Threshold size for MultiQC report to be attached in notification email. If file generated by pipeline exceeds the threshold, it will not be attached (Default: 25MB)
-name [str] Name for the pipeline run. If not specified, Nextflow will automatically generate a random mnemonic
AWSBatch options:
--awsqueue [str] The AWSBatch JobQueue that needs to be set when running on AWSBatch
--awsregion [str] The AWS Region for your AWS Batch job to run on
--awscli [str] Path to the AWS CLI tool
""".stripIndent()
}
// Show help emssage
if (params.help){
helpMessage()
exit 0
}
/*
* SET UP CONFIGURATION VARIABLES
*/
output_docs = file("$baseDir/docs/output.md")
// Has the run name been specified by the user?
// this has the bonus effect of catching both -name and --name
custom_runName = params.name
if( !(workflow.runName ==~ /[a-z]+_[a-z]+/) ){
custom_runName = workflow.runName
}
// input_paths is only used for testing
input_paths_ch = Channel.empty()
// Samples from SRA
sra_ch = Channel.empty()
// R1, R2 pairs from a samples.csv file
csv_pairs_ch = Channel.empty()
// Single-enede reads from a samples.csv file
csv_singles_ch = Channel.empty()
// Extract R1, R2 pairs from a directory
read_pairs_ch = Channel.empty()
// Extract single-ended from a directory
read_singles_ch = Channel.empty()
// vanilla fastas
fastas_ch = Channel.empty()
// 10X Genomics .tgz file containing possorted_genome_bam file
tenx_tgz_ch = Channel.empty()
// Boolean for if an nucleotide input exists anywhere
have_nucleotide_fasta_input = params.fastas || params.fasta_paths
have_nucleotide_fastq_input = params.input_paths || params.sra || params.csv_pairs || params.csv_singles || params.read_pairs || params.read_singles || params.bam || params.tenx_tgz
have_nucleotide_input = have_nucleotide_fasta_input || have_nucleotide_fastq_input
if (!params.split_kmer){
have_sketch_num_hashes = params.sketch_num_hashes || params.sketch_num_hashes_log2 || params.sketch_scaled || params.sketch_scaled_log2
if (!have_sketch_num_hashes) {
exit 1, "Must provide one of --sketch_num_hashes, --sketch_num_hashes_log2, --sketch_scaled, --sketch_scaled_log2 for Sourmash!"
}
}
// Parameters for testing
if (params.input_paths) {
input_paths_ch = Channel
.from(params.input_paths)
.map { row -> if (row[1].size() == 2) [ row[0], [file(row[1][0]), file(row[1][1])]]
else [row[0], [file(row[1][0])]]}
.ifEmpty { exit 1, "params.input_paths (${params.input_paths}) was empty - no input files supplied" }
} else {
// Provided SRA ids
if (params.sra){
sra_ch = Channel
.fromSRA( params.sra?.toString()?.tokenize(';') )
.ifEmpty { exit 1, "params.sra ${params.sra} was not found - no input files supplied" }
}
// Provided a samples.csv file of read pairs
if (params.csv_pairs){
csv_pairs_ch = Channel
.fromPath(params.csv_pairs)
.splitCsv(header:true)
.map{ row -> tuple(row[0], tuple(file(row[1]), file(row[2])))}
.ifEmpty { exit 1, "params.csv_pairs (${params.csv_pairs}) was empty - no input files supplied" }
}
// Provided a samples.csv file of single-ended reads
if (params.csv_singles){
csv_singles_ch = Channel
.fromPath(params.csv_singles)
.splitCsv(header:true)
.map{ row -> tuple(row[0], tuple(file(row[1])))}
.ifEmpty { exit 1, "params.csv_singles (${params.csv_singles}) was empty - no input files supplied" }
}
// Provided fastq gz paired-end reads
if (params.read_pairs){
read_pairs_ch = Channel
.fromFilePairs(params.read_pairs?.toString()?.tokenize(';'), size: 2)
.ifEmpty { exit 1, "params.read_pairs (${params.read_pairs}) was empty - no input files supplied" }
}
// Provided fastq gz single-end reads
if (params.read_singles){
read_singles_ch = Channel
.fromFilePairs(params.read_singles?.toString()?.tokenize(';'), size: 1)
.ifEmpty { exit 1, "params.read_singles (${params.read_singles}) was empty - no input files supplied" }
}
// Provided vanilla fastas
if (params.fastas){
fastas_ch = Channel
.fromPath(params.fastas?.toString()?.tokenize(';'))
.map{ f -> tuple(f.baseName, tuple(file(f))) }
.dump ( tag: 'fastas_ch' )
.ifEmpty { exit 1, "params.fastas (${params.fastas}) was empty - no input files supplied" }
} else if (params.fasta_paths) {
fastas_ch = Channel
.from(params.fasta_paths)
.map { row -> if (row[1].size() == 2) [ row[0], [file(row[1][0]), file(row[1][1])]]
else [row[0], [file(row[1][0])]]}
.dump ( tag: 'fastas_ch' )
.ifEmpty { exit 1, "params.fasta_paths (${params.fastas}) was empty - no input files supplied" }
}
if (params.bam) {
Channel.fromPath(params.bam, checkIfExists: true)
.map{ f -> tuple(f.baseName, tuple(file(f))) }
.ifEmpty { exit 1, "Bam file not found: ${params.bam}" }
.dump( tag: 'bam' )
.into{ tenx_bam_for_unaligned_fastq_ch; tenx_bam_for_aligned_fastq_ch}
}
// If barcodes is as expected, check if it exists and set channel
if (params.barcodes_file) {
Channel.fromPath(params.barcodes_file, checkIfExists: true)
.ifEmpty { exit 1, "Barcodes file not found: ${params.barcodes_file}" }
.set{barcodes_ch}
}
else {
Channel.from(false)
.set{barcodes_ch}
}
// If renamer barcode file is as expected, check if it exists and set channel
if (params.rename_10x_barcodes) {
Channel.fromPath(params.rename_10x_barcodes, checkIfExists: true)
.ifEmpty { exit 1, "Barcodes file not found: ${params.rename_10x_barcodes}" }
.set{rename_10x_barcodes_ch}
}
else {
Channel.from(false)
.set{rename_10x_barcodes_ch}
}
if (params.tenx_tgz) {
have_nucleotide_input = true
Channel.fromPath(params.tenx_tgz, checkIfExists: true)
.dump(tag: 'tenx_tgz_before_mri_filter')
.filter{ ~/.+[^mri]\.tgz/ }
.ifEmpty { exit 1, "10X .tgz file not found: ${params.tenx_tgz}" }
.dump(tag: 'tenx_tgz_after_mri_filter')
.set{ tenx_tgz_ch }
}
}
////////////////////////////////////////////////////
/* -- Parse protein fastas -- */
////////////////////////////////////////////////////
if (params.protein_fastas){
Channel.fromPath(params.protein_fastas?.toString()?.tokenize(';'))
.map{ f -> tuple(f.baseName, tuple(file(f))) }
.ifEmpty { exit 1, "params.protein_fastas was empty - no input files supplied" }
.set { ch_protein_fastas }
} else if (params.protein_fasta_paths){
Channel
.from(params.protein_fasta_paths)
.map { row -> [ row[0], [ file(row[1][0], checkIfExists: true)] ] }
.ifEmpty { exit 1, "params.protein_fasta_paths was empty - no input files supplied" }
.dump(tag: "protein_fasta_paths")
.set { ch_protein_fastas }
} else {
ch_protein_fastas = Channel.empty()
}
if (params.reference_proteome_fasta) {
Channel.fromPath(params.reference_proteome_fasta, checkIfExists: true)
.ifEmpty { exit 1, "Reference proteome file not found: ${params.reference_proteome_fasta}" }
.set{ ch_reference_proteome_fasta }
}
////////////////////////////////////////////////////
/* -- Concatenate all nucleotide inputs -- */
////////////////////////////////////////////////////
// Add _unchecked suffix because have not yet checked if these files are not empty
if (params.subsample) {
if (params.bam){
exit 1, "Cannot provide both a bam file with --bam and specify --subsample"
} else {
if (params.skip_trimming){
sra_ch.concat(csv_pairs_ch, csv_singles_ch, read_pairs_ch,
read_singles_ch, fastas_ch, input_paths_ch)
.set{ subsample_reads_ch_unchecked }
} else {
sra_ch.concat(
csv_pairs_ch, csv_singles_ch, read_pairs_ch,
read_singles_ch, input_paths_ch)
// .ifEmpty{ exit 1, "No reads provided! Check read input files"}
.set{ ch_read_files_trimming_unchecked }
}
}
} else {
if (!(params.tenx_tgz || params.bam)) {
if(params.skip_trimming){
sra_ch.concat(
csv_pairs_ch, csv_singles_ch, read_pairs_ch,
read_singles_ch, fastas_ch, input_paths_ch)
.set{ reads_ch_unchecked }
} else {
if (have_nucleotide_fasta_input) {
// With fasta files - combine everything that can be trimmed
sra_ch.concat(
csv_pairs_ch, csv_singles_ch, read_pairs_ch,
read_singles_ch, input_paths_ch)
.dump ( tag: 'ch_read_files_trimming_unchecked__with_fastas' )
.into { ch_read_files_trimming_to_trim; ch_read_files_trimming_to_check_size }
} else {
// No fasta files - combine everything and error out
sra_ch.concat(
csv_pairs_ch, csv_singles_ch, read_pairs_ch,
read_singles_ch, input_paths_ch)
.dump ( tag: 'ch_read_files_trimming_unchecked__no_fastas' )
.set{ ch_read_files_trimming_unchecked }
}
}
} else {
sra_ch.concat(
csv_pairs_ch, csv_singles_ch, read_pairs_ch,
read_singles_ch, input_paths_ch)
.dump ( tag: 'ch_non_bam_reads_unchecked__concatenated' )
.set{ ch_non_bam_reads_unchecked }
}
}
protein_input = params.protein_fastas || params.protein_fasta_paths
if (!protein_input) {
if (params.subsample && params.skip_trimming ) {
subsample_reads_ch_unchecked
.ifEmpty{ exit 1, "No reads provided! Check read input files" }
.set { subsample_ch_reads_for_ribosomal_removal }
}
if (params.skip_trimming && !(params.bam || params.tenx_tgz)) {
reads_ch_unchecked
.ifEmpty{ exit 1, "No reads provided! Check read input files" }
.set { ch_reads_for_ribosomal_removal }
ch_read_files_trimming_to_check_size = Channel.empty()
} else if (params.bam || params.tenx_tgz) {
ch_non_bam_reads_unchecked
// No need to check if empty since there is bam input
.set { ch_non_bam_reads }
} else if (!have_nucleotide_fasta_input) {
// if no fastas, then definitely trimming the remaining reads
ch_read_files_trimming_unchecked
.ifEmpty{ exit 1, "No reads provided! Check read input files" }
.into { ch_read_files_trimming_to_trim; ch_read_files_trimming_to_check_size }
}
} else {
// Since there exists protein input, don't check if these are empty
if (params.subsample) {
subsample_reads_ch_unchecked
.set { subsample_ch_reads_for_ribosomal_removal }
}
if (params.skip_trimming) {
reads_ch_unchecked
.set { ch_reads_for_ribosomal_removal }
ch_read_files_trimming_to_check_size = Channel.empty()
} else if (!have_nucleotide_fasta_input) {
ch_read_files_trimming_unchecked
.into { ch_read_files_trimming_to_trim; ch_read_files_trimming_to_check_size }
}
if (params.bam) {
ch_non_bam_reads_unchecked
.set { ch_non_bam_reads }
}
}
if (params.split_kmer){
params.ksizes = '15,9'
params.molecules = 'dna'
} else {
params.ksizes = '21,27,33,51'
}
// Get rRNA databases
// Default is set to bundled DB list in `assets/rrna-db-defaults.txt`
rRNA_database = file(params.rrna_database_manifest)
if (rRNA_database.isEmpty()) {exit 1, "File ${rRNA_database.getName()} is empty!"}
Channel
.from( rRNA_database.readLines() )
.map { row -> file(row) }
.set { sortmerna_fasta }
// --- Parse Translate parameters ---
save_translate_csv = params.save_translate_csv
save_translate_json = params.save_translate_json
// --- Parse the Sourmash parameters ----
ksizes = params.ksizes?.toString().tokenize(',')
Channel.from(params.ksizes?.toString().tokenize(','))
.into { ch_ksizes_for_compare_peptide; ch_ksizes_for_compare_nucleotide }
molecules = params.molecules?.toString().tokenize(',')
peptide_molecules = molecules.findAll { it != "dna" }
peptide_molecules_comma_separated = peptide_molecules.join(",")
peptide_molecule_flags = peptide_molecules.collect { it -> "--${it}" }.join ( " " )
Channel.from( molecules )
.set { ch_molecules }
Channel.from( peptide_molecules )
.into { ch_peptide_molecules; ch_peptide_molecules_for_compare }
// Parse sketch value and style parameters
sketch_num_hashes = params.sketch_num_hashes
sketch_num_hashes_log2 = params.sketch_num_hashes_log2
sketch_scaled = params.sketch_scaled
sketch_scaled_log2 = params.sketch_scaled_log2
have_sketch_value = params.sketch_num_hashes || params.sketch_num_hashes_log2 || params.sketch_scaled || params.sketch_scaled_log2
if (!have_sketch_value && !params.split_kmer) {
exit 1, "None of --sketch_num_hashes, --sketch_num_hashes_log2, --sketch_scaled, --sketch_scaled_log2 was provided! Provide one (1) and only one to specify the style and amount of hashes per sourmash sketch"
}
// added "_for_id" to all variables to avoid variable scoping errors
def make_sketch_id (
molecule_for_id, ksizes_for_id, sketch_value_for_id, track_abundance_for_id, sketch_style_for_id
) {
if (sketch_style_for_id == 'size') {
style_value = "num_hashes-${sketch_value_for_id}"
} else {
style_value = "scaled-${sketch_value_for_id}"
}
this_sketch_id = "molecule-${molecule_for_id}__ksize-${ksizes_for_id}__${style_value}__track_abundance-${track_abundance_for_id}"
return this_sketch_id
}
// Create the --num-hashes or --scaled flag for sourmash
// added "_for_flag" to all variables to avoid variable scoping errors
def make_sketch_value_flag(sketch_style_for_flag, sketch_value_for_flag) {
if (sketch_style_for_flag == "size") {
number_flag = "--num-hashes ${sketch_value_for_flag}"
} else if (sketch_style_for_flag == "scaled" ) {
number_flag = "--scaled ${sketch_value_for_flag}"
} else {
exit 1, "${sketch_style_for_flag} is not a valid sketch counting style! Only 'scaled' and 'size' are valid"
}
return number_flag
}
int bloomfilter_tablesize = Math.round(Float.valueOf(params.bloomfilter_tablesize))
translate_peptide_ksize = params.translate_peptide_ksize
translate_peptide_molecule = params.translate_peptide_molecule
translate_jaccard_threshold = params.translate_jaccard_threshold
track_abundance = params.track_abundance
// Tenx parameters
tenx_tags = params.tenx_tags
tenx_cell_barcode_pattern = params.tenx_cell_barcode_pattern
tenx_molecular_barcode_pattern = params.tenx_molecular_barcode_pattern
tenx_min_umi_per_cell = params.tenx_min_umi_per_cell
if (params.split_kmer && 'protein' in molecules){
exit 1, "Cannot specify 'protein' in `--molecules` if --split_kmer is set"
}
// For bam files, set a folder name to save the optional barcode metadata csv
if (!params.write_barcode_meta_csv) {
barcode_metadata_folder = ""
}
else {
barcode_metadata_folder = "barcode_metadata"
}
// Has the run name been specified by the user?
// this has the bonus effect of catching both -name and --name
custom_runName = params.name
if (!(workflow.runName ==~ /[a-z]+_[a-z]+/)) {
custom_runName = workflow.runName
}
// Check AWS batch settings
if (workflow.profile.contains('awsbatch')) {
// AWSBatch sanity checking
if (!params.awsqueue || !params.awsregion) exit 1, "Specify correct --awsqueue and --awsregion parameters on AWSBatch!"
// Check outdir paths to be S3 buckets if running on AWSBatch
// related: https://github.com/nextflow-io/nextflow/issues/813
if (!params.outdir.startsWith('s3:')) exit 1, "Outdir not on S3 - specify S3 Bucket to run on AWSBatch!"
// Prevent trace files to be stored on S3 since S3 does not support rolling files.
if (params.tracedir.startsWith('s3:')) exit 1, "Specify a local tracedir or run without trace! S3 cannot be used for tracefiles."
}
// Stage config files
projectDir = workflow.projectDir
ch_multiqc_config = file("${workflow.projectDir}/assets/multiqc_config.yaml", checkIfExists: true)
ch_multiqc_custom_config = params.multiqc_config ? Channel.fromPath(params.multiqc_config, checkIfExists: true) : Channel.empty()
ch_output_docs = file("${workflow.projectDir}/docs/output.md", checkIfExists: true)
ch_output_docs_images = file("${workflow.projectDir}/docs/images/", checkIfExists: true)
// Header log info
log.info nfcoreHeader()
def summary = [:]
if(workflow.revision) summary['Pipeline Release'] = workflow.revision
summary['Run Name'] = custom_runName ?: workflow.runName
// Input reads
if(params.read_pairs) summary['Read Pairs'] = params.read_pairs
if(params.read_singles) summary['Single-end reads'] = params.read_singles
if(params.csv_pairs) summary['Paired-end samples.csv'] = params.csv_pairs
if(params.csv_singles) summary['Single-end samples.csv'] = params.csv_singles
if(params.sra) summary['SRA'] = params.sra
if(params.fastas) summary["FASTAs"] = params.fastas
if(params.protein_fastas) summary["Protein FASTAs"] = params.protein_fastas
if(params.bam) summary["BAM"] = params.bam
if(params.barcodes_file) summary["Barcodes"] = params.barcodes_file
if(params.rename_10x_barcodes) summary["Renamer barcodes"] = params.rename_10x_barcodes
if(params.input_paths) summary['Read paths (paired-end)'] = params.input_paths
// Sketch parameters
summary['Skip trimming?'] = params.skip_trimming
summary['Skip compare?'] = params.skip_compare
summary['Skip compute?'] = params.skip_compute
summary['Skip multiqc?'] = params.skip_multiqc
summary['K-mer sizes'] = params.ksizes
summary['Molecule'] = params.molecules
summary['Track Abundance'] = params.track_abundance
// -- Sketch size parameters --
if (params.sketch_num_hashes) summary['Sketch Sizes'] = params.sketch_num_hashes
if (params.sketch_num_hashes_log2) summary['Sketch Sizes (log2)'] = params.sketch_num_hashes_log2
if (params.sketch_scaled) summary['Sketch scaled'] = params.sketch_scaled
if (params.sketch_scaled_log2) summary['Sketch scaled (log2)'] = params.sketch_scaled_log2
// 10x parameters
if(params.tenx_tgz) summary["10x .tgz"] = params.tenx_tgz
if(params.tenx_tgz) summary["10x SAM tags"] = params.tenx_tags
if(params.tenx_tgz) summary["10x Cell pattern"] = params.tenx_cell_barcode_pattern
if(params.tenx_tgz) summary["10x UMI pattern"] = params.tenx_molecular_barcode_pattern
if(params.tenx_tgz) summary['Min UMI/cell'] = params.tenx_min_umi_per_cell
// Extract coding parameters
if(params.reference_proteome_fasta) summary["Peptide fasta"] = params.reference_proteome_fasta
if(params.reference_proteome_fasta) summary['Peptide ksize'] = params.translate_peptide_ksize
if(params.reference_proteome_fasta) summary['Peptide molecule'] = params.translate_peptide_molecule
if(params.reference_proteome_fasta) summary['Bloom filter table size'] = params.bloomfilter_tablesize
// Resource information
summary['Max Resources'] = "$params.max_memory memory, $params.max_cpus cpus, $params.max_time time per job"
if(workflow.containerEngine) summary['Container'] = "$workflow.containerEngine - $workflow.container"
summary['Output dir'] = params.outdir
summary['Launch dir'] = workflow.launchDir
summary['Working dir'] = workflow.workDir
summary['Script dir'] = workflow.projectDir
summary['User'] = workflow.userName
if (workflow.profile.contains('awsbatch')) {
summary['AWS Region'] = params.awsregion
summary['AWS Queue'] = params.awsqueue
summary['AWS CLI'] = params.awscli
}
summary['Config Profile'] = workflow.profile
if (params.config_profile_description) summary['Config Description'] = params.config_profile_description
if (params.config_profile_contact) summary['Config Contact'] = params.config_profile_contact
if (params.config_profile_url) summary['Config URL'] = params.config_profile_url
if (params.email || params.email_on_fail) {
summary['E-mail Address'] = params.email
summary['E-mail on failure'] = params.email_on_fail
summary['MultiQC maxsize'] = params.max_multiqc_email_size
}
log.info summary.collect { k,v -> "${k.padRight(18)}: $v" }.join("\n")
log.info "-\033[2m--------------------------------------------------\033[0m-"
// Check the hostnames against configured profiles
checkHostname()
Channel.from(summary.collect{ [it.key, it.value] })
.map { k,v -> "<dt>$k</dt><dd><samp>${v ?: '<span style=\"color:#999999;\">N/A</a>'}</samp></dd>" }
.reduce { a, b -> return [a, b].join("\n ") }
.map { x -> """
id: 'nf-core-kmermaid-summary'
description: " - this information is collected when the pipeline is started."
section_name: 'nf-core/kmermaid Workflow Summary'
section_href: 'https://github.com/nf-core/kmermaid'
plot_type: 'html'
data: |
<dl class=\"dl-horizontal\">
$x
</dl>
""".stripIndent() }
.set { ch_workflow_summary }
/*
* Parse software version numbers
*/
process get_software_versions {
publishDir "${params.outdir}/pipeline_info", mode: params.publish_dir_mode,
saveAs: { filename ->
if (filename.indexOf(".csv") > 0) filename
if (filename.indexOf(".yaml") > 0) filename
else null
}
output:
file 'software_versions_mqc.yaml' into ch_software_versions_yaml
file "software_versions.csv"
script:
"""
echo $workflow.manifest.version > v_pipeline.txt
echo $workflow.nextflow.version > v_nextflow.txt
bam2fasta info &> v_bam2fasta.txt
fastp --version &> v_fastp.txt
samtools --version &> v_samtools.txt
ska version &> v_ska.txt
sortmerna --version &> v_sortmerna.txt
sourmash -v &> v_sourmash.txt
pip show orpheum &> v_orpheum.txt
scrape_software_versions.py &> software_versions_mqc.yaml
"""
}
if ( !params.split_kmer && have_sketch_value ) {
// Only use this for sourmash sketches, not split k-mer sketches
/*
* Validate sketch sizes
*/
process validate_sketch_value {
publishDir "${params.outdir}/pipeline_info", mode: params.publish_dir_mode,
saveAs: {filename ->
if (filename.indexOf(".txt") > 0) filename
else null
}
input:
val sketch_num_hashes
val sketch_num_hashes_log2
val sketch_scaled
val sketch_scaled_log2
output:
file sketch_value into ch_sketch_value_unparsed
file sketch_style into ch_sketch_style_unparsed
script:
sketch_style = "sketch_style.txt"
sketch_value = 'sketch_value.txt'
"""
validate_sketch_value.py \\
--sketch_num_hashes ${sketch_num_hashes} \\
--sketch_num_hashes_log2 ${sketch_num_hashes_log2} \\
--sketch_scaled ${sketch_scaled} \\
--sketch_scaled_log2 ${sketch_scaled_log2} \\
--output ${sketch_value} \\
--sketch_style ${sketch_style}
"""
}
// Parse sketch style into value
sketch_style_parsed = ch_sketch_style_unparsed
.splitText()
.dump ( tag: 'ch_sketch_style' )
.map { it -> it.replaceAll('\\n', '' ) }
.first()
.dump ( tag: 'sketch_style_parsed' )
.collect ()
// get first item of returned array from .collect()
// sketch_style_parsed = sketch_style_parsed[0]
// .into { ch_sketch_style_for_nucleotides; ch_sketch_style_for_proteins }
// sketch_style = sketch_styles[0]
// println "sketch_style_parsed: ${sketch_style_parsed}"
// println "sketch_style: ${sketch_style}"
// Parse file into values
sketch_value_parsed = ch_sketch_value_unparsed
.splitText()
.map { it -> it.replaceAll('\\n', '')}
.first()
.dump ( tag : 'sketch_value_parsed' )
.collect()
// get first item of returned array from .collect()
// sketch_value_parsed = sketch_value_parsed[0]
// .into { ch_sketch_value_for_proteins; ch_sketch_value_for_dna }
}
// Combine sketch values with ksize and molecule types
if (params.reference_proteome_fasta){
process make_protein_index {
tag "${peptides}__${bloom_id}"
label "low_memory"
publishDir "${params.outdir}/protein_index", mode: params.publish_dir_mode
input:
file(peptides) from ch_reference_proteome_fasta
translate_peptide_ksize
translate_peptide_molecule
output:
set val(bloom_id), val(translate_peptide_molecule), file("${peptides.simpleName}__${bloom_id}.bloomfilter") into ch_orpheum_bloom_filter
script:
bloom_id = "molecule-${translate_peptide_molecule}_ksize-${translate_peptide_ksize}"
"""
orpheum index \\
--tablesize ${bloomfilter_tablesize} \\
--molecule ${translate_peptide_molecule} \\
--peptide-ksize ${translate_peptide_ksize} \\
--save-as ${peptides.simpleName}__${bloom_id}.bloomfilter \\
${peptides}
"""
}
}
if (params.tenx_tgz) {
process tenx_tgz_extract_bam {
tag "$sample_id"
publishDir "${params.outdir}/10x-bams", mode: params.publish_dir_mode
input:
file(tenx_tgz) from tenx_tgz_ch
output:
set val(sample_id), file(bam) into tenx_bam_for_unaligned_fastq_ch, tenx_bam_for_aligned_fastq_ch
file(bai)
set val(sample_id), file(barcodes) into tenx_bam_barcodes_ch
script:
sample_id = "${tenx_tgz.simpleName}"
bam = "${sample_id}__possorted_genome_bam.bam"
bai = "${sample_id}__possorted_genome_bam.bam.bai"
barcodes = "${sample_id}__barcodes.tsv"
"""
tar xzvf ${tenx_tgz} \\
${sample_id}/outs/possorted_genome_bam.bam.bai \\
${sample_id}/outs/possorted_genome_bam.bam \\
${sample_id}/outs/filtered_gene_bc_matrices
# Rename the files so there aren't conflicting duplicate filenames for the future
mv ${sample_id}/outs/possorted_genome_bam.bam ${bam}
mv ${sample_id}/outs/possorted_genome_bam.bam.bai ${bai}
mv ${sample_id}/outs/filtered_gene_bc_matrices/*/barcodes.tsv ${barcodes}
"""
}
}
if (params.tenx_tgz || params.bam) {
process samtools_fastq_aligned {
tag "${channel_id}"
publishDir "${params.outdir}/10x-fastqs/per-channel/aligned", mode: params.publish_dir_mode
label "mid_cpu"
input:
set val(channel_id), file(bam) from tenx_bam_for_unaligned_fastq_ch
output:
set val(channel_id), val("aligned"), file(reads) into tenx_reads_aligned_counting_ch, tenx_reads_aligned_concatenation_ch
script:
reads = "${channel_id}__aligned.fastq.gz"
"""
samtools view -ub -F 4 ${bam} \\
| samtools fastq --threads ${task.cpus} -T ${tenx_tags} - \\
| gzip -c - \\
> ${reads}
"""
}
process samtools_fastq_unaligned {
tag "${channel_id}"
publishDir "${params.outdir}/10x-fastqs/per-channel/unaligned", mode: params.publish_dir_mode
label "mid_cpu"
input:
set val(channel_id), file(bam) from tenx_bam_for_aligned_fastq_ch
output:
set val(channel_id), val("unaligned"), file(reads) into tenx_reads_unaligned_ch
script:
reads = "${channel_id}__unaligned.fastq.gz"
"""
samtools view -f4 ${bam} \\
| grep -E '${tenx_cell_barcode_pattern}' \\
| samtools fastq --threads ${task.cpus} -T ${tenx_tags} - \\
| gzip -c - \\
> ${reads} \\
|| touch ${reads}
"""
// The '||' means that if anything in the previous step fails, do the next thing
// It's bash magic from: https://stackoverflow.com/a/3822649/1628971
}
// Put fastqs from aligned and unaligned reads into a single channel
tenx_reads_aligned_concatenation_ch
.mix( tenx_reads_unaligned_ch )
.dump(tag: "tenx_ch_reads_for_ribosomal_removal")
.set{ tenx_ch_reads_for_ribosomal_removal }
if ((params.tenx_min_umi_per_cell > 0) || !params.barcodes_file) {
process count_umis_per_cell {
tag "${is_aligned_channel_id}"
label 'low_memory_long'
publishDir "${params.outdir}/10x-fastqs/umis-per-cell/", mode: params.publish_dir_mode
input:
set val(channel_id), val(is_aligned), file(reads) from tenx_reads_aligned_counting_ch
output:
file(umis_per_cell)
set val(channel_id), file(good_barcodes) into good_barcodes_unfiltered_ch
script:
is_aligned_channel_id = "${channel_id}__${is_aligned}"
umis_per_cell = "${is_aligned_channel_id}__n_umi_per_cell.csv"
good_barcodes = "${is_aligned_channel_id}__barcodes.tsv"
"""
bam2fasta count_umis_percell \\
--filename ${reads} \\
--min-umi-per-barcode ${tenx_min_umi_per_cell} \\
--cell-barcode-pattern '${tenx_cell_barcode_pattern}' \\
--molecular-barcode-pattern '${tenx_molecular_barcode_pattern}' \\
--write-barcode-meta-csv ${umis_per_cell} \\
--barcodes-significant-umis-file ${good_barcodes}
"""
}
// Make sure good barcodes file is nonempty so next step doesn't start
// it[0] = channel id
// it[1] = good_barcodes file
good_barcodes_unfiltered_ch.filter{ it -> it[1].size() > 0 }
.ifEmpty{ exit 1, "No cell barcodes found with at least ${tenx_min_umi_per_cell} molecular barcodes (UMIs) per cell"}
.set{ good_barcodes_ch }
} else if (params.barcodes) {
good_barcodes_ch = barcodes_ch
}
else {
// Use barcodes extracted from the tenx .tgz file
good_barcodes_ch = tenx_bam_barcodes_ch
}
tenx_ch_reads_for_ribosomal_removal
.combine( good_barcodes_ch, by: 0 )
.dump( tag: 'tenx_ch_reads_for_ribosomal_removal__combine__good_barcodes_ch' )
.map{ it -> [it[0], it[1], it[2], it[3].splitText()] }
.transpose()
.dump( tag: 'tenx_ch_reads_for_ribosomal_removal__combine__good_barcodes_ch__transpose' )
.map{ it -> [it[0], it[1], it[2], it[3].replaceAll("\\s+", "") ] }
.dump( tag: 'tenx_ch_reads_for_ribosomal_removal__combine__good_barcodes_ch__transpose__no_newlines' )
.set{ tenx_reads_with_good_barcodes_ch }
process extract_per_cell_fastqs {
tag "${fastq_id}"
label "low_memory"
errorStrategy { task.exitStatus in [143,137,104,134,139] ? 'retry' : 'ignore' }
publishDir "${params.outdir}/10x-fastqs/per-cell/${channel_id}/", mode: 'copy', pattern: '*.fastq.gz', saveAs: { filename -> "${filename.replace("|", "-")}"}
input:
// Example input:
// ['mouse_lung', 'aligned', mouse_lung__aligned.fastq.gz, CTGAAGTCAATGGTCT]
set val(channel_id), val(is_aligned), file(reads), val(cell_barcode) from tenx_reads_with_good_barcodes_ch
output:
set val(fastq_id), file(this_cell_fastq_gz) into per_cell_fastqs_ch_possibly_empty
set val(fastq_id), val(cell_id), val(is_aligned) into ch_fastq_id_to_cell_id_is_aligned
script:
this_cell_barcode = tenx_cell_barcode_pattern.replace('([ACGT]+)', cell_barcode)
fastq_id = "${channel_id}__${is_aligned}__${cell_barcode}"
cell_id = "${channel_id}__${cell_barcode}"
this_cell_fastq_gz = "${fastq_id}.fastq.gz"
"""
rg \\
--search-zip \\
--after-context 3 \\
--threads ${task.cpus} \\
'${this_cell_barcode}' \\
${reads} \\
| gzip -c - \\
> ${this_cell_fastq_gz} || touch ${this_cell_fastq_gz}
"""
}
per_cell_fastqs_ch_possibly_empty
// Empty gzipped files are 20 bytes
.filter { it -> it[1].size() > 20 }
.set { per_cell_fastqs_ch }
// // Make per-cell fastqs into a flat channel that matches the read channels of yore
// // Filtering out fastq.gz files less than 200 bytes (arbitary number)
// // ~200 bytes is about the size of a file with a single read or less
// // We can't use .size() > 0 because it's fastq.gz is gzipped content
// per_channel_cell_ch_reads_for_ribosomal_removal
// .dump(tag: 'per_channel_cell_ch_reads_for_ribosomal_removal')
// .flatten()
// .filter{ it -> it.size() > 200 } // each item is just a single file, no need to do it[1]
// .map{ it -> tuple(it.simpleName, file(it)) }
// .dump(tag: 'per_cell_fastqs_ch')
// .set{ per_cell_fastqs_ch }
if (params.skip_trimming) {
ch_non_bam_reads
.concat(per_cell_fastqs_ch)
.set { ch_reads_for_ribosomal_removal }
} else {
ch_non_bam_reads
.mix ( per_cell_fastqs_ch )
.dump ( tag: 'ch_non_bam_reads__per_cell_fastqs_ch' )
.into{ ch_read_files_trimming_to_trim; ch_read_files_trimming_to_check_size }
}
}
if ( have_nucleotide_input ) {
if (!params.skip_trimming && have_nucleotide_fastq_input){
process fastp {
label 'process_low'
tag "$name"
publishDir "${params.outdir}/fastp", mode: params.publish_dir_mode,
saveAs: {filename ->
if (filename.indexOf(".fastq.gz") == -1) "logs/$filename"
else if (reads[1] == null) "single_end/$filename"
else if (reads[1] != null) "paired_end/$filename"
else null
}
input:
set val(name), file(reads) from ch_read_files_trimming_to_trim
output:
set val(name), file("*trimmed.fastq.gz") into ch_reads_all_trimmed
file "*fastp.json" into ch_fastp_results
file "*fastp.html" into ch_fastp_html
script:
// One set of reads --> single end
if (reads[1] == null) {
"""
fastp \\
--in1 ${reads} \\
--out1 ${name}_R1_trimmed.fastq.gz \\