-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathCnR-flow.nf
executable file
·2480 lines (2230 loc) · 101 KB
/
CnR-flow.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
//Daniel Stribling
//Renne Lab, University of Florida
//
//This file is part of CnR-flow.
//CnR-flow is free software: you can redistribute it and/or modify
//it under the terms of the GNU General Public License as published by
//the Free Software Foundation, either version 3 of the License, or
//(at your option) any later version.
//CnR-flow is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//You should have received a copy of the GNU General Public License
//along with CnR-flow. If not, see <https://www.gnu.org/licenses/>.
// To prevent duplication, all required parameters are listed in the bundled files:
// /CnR-flow/nextflow.config
// /CnR-flow/templates/nextflow.config.backup
// --------------- Setup Default Pipe Variables: ---------------
params.verbose = false
params.help = false
params.h = false
params.version = false
params.v = false
params.out_front_pad = 4
params.out_prop_pad = 17
// --------------- Check (and Describe) "--mode" param: ---------------
modes = ['initiate', 'validate', 'prep_fasta',
'list_refs', 'run', 'help', 'version']
usage = """\
USAGE:
nextflow [NF_OPTIONS] run CnR-flow --mode <run-mode> [PIPE_OPTIONS]
Run Modes:
initiate : Download files & copy configuration templates to current directory
validate : Validate dependency configuration
prep_fasta : Prepare alignment reference(s) from <genome>.fa[sta]
list_refs : List prepared alignment references
run : Run pipeline
help : Print help and usage information for pipeline
version : Print pipeline version
"""
help_description = """\
${workflow.manifest.name} Nextflow Pipeline, Version: ${workflow.manifest.version}
This nextflow pipeline analyzes paired-end data in .fastq[.gz] format
created from CUT&RUN Experiments.
""".stripIndent()
full_help = "\n" + help_description + usage
full_version = " -- ${workflow.manifest.name} : ${workflow.manifest.mainScript} "
full_version += ": ${workflow.manifest.version}"
if( params.help || params.h ) {
println full_help
exit 0
} else if( params.version || params.v ) {
println full_version
exit 0
} else if( !params.containsKey('mode') ) {
println ""
log.warn "--mode Keyword ('params.mode') not provided."
log.warn "Use --h, --help, --mode=help, or --mode help for more information."
log.warn "Defaulting to --mode='validate'"
log.warn ""
params.mode = 'validate'
} else if( !modes.any{it == params.mode} ) {
println ""
log.error "Unrecognized --mode Keyword ('params.mode):"
log.error " '${params.mode}'"
log.error ""
println usage
exit 1
} else if( params.mode == 'help' ) {
println full_help
exit 0
} else if( params.mode == 'version' ) {
println full_version
exit 0
} else {
log.info ""
log.info "Utilizing Run Mode: ${params.mode}"
}
print_in_files = []
// If mode is 'prep_fasta', ensure "ref_fasta" has been provided.
if( ['prep_fasta'].contains(params.mode) ) {
test_params_key(params, 'ref_fasta', 'nonblank')
if( !file("${params.ref_fasta}", checkIfExists: false).exists() ) {
message = "File for reference preparation does not exist:\n"
message += " genome_sequence: ${params['ref_fasta']}\n"
message += check_full_file_path(params['ref_fasta'])
log.error message
exit 1
}
// If 'list_refs' mode, ensure refs dir is defined.
} else if(['list_refs'].contains(params.mode)) {
test_params_key(params, 'refs_dir')
// If a run or validate mode, ensure all required keys have been provided correctly.
} else if(['run', 'validate'].contains(params.mode) ) {
// Check to ensure required keys have been provided correctly.
first_test_keys = [
'do_merge_lanes', 'do_fastqc', 'do_trim', 'do_norm_spike',
'do_norm_cpm', 'do_make_bigwig',
'peak_callers', 'java_call', 'bowtie2_build_call', 'samtools_call',
'facount_call', 'bedgraphtobigwig_call',
'fastqc_call', 'trimmomatic_call', 'bowtie2_call',
'bedtools_call', 'macs2_call',
'seacr_call', 'out_dir', 'refs_dir', 'log_dir', 'prep_bt2db_suf',
'merge_fastqs_dir', 'fastqc_pre_dir', 'trim_dir',
'fastqc_post_dir', 'aln_dir_ref', 'aln_dir_spike', 'aln_dir_mod',
'aln_dir_norm', 'aln_dir_norm_cpm',
'aln_bigwig_dir', 'peaks_dir_macs', 'peaks_dir_seacr',
'verbose', 'help', 'h', 'version', 'v', 'out_front_pad', 'out_prop_pad',
'trim_name_prefix', 'trim_name_suffix'
]
first_test_keys.each { test_params_key(params, it) }
use_tests = []
req_keys = []
req_files = []
// If Run mode, automatically set reference keys based on reference mode.
if (['run'].contains(params.mode) ) {
test_params_key(params, 'ref_mode', ['manual', 'name', 'fasta'])
ref_key = ''
norm_ref_key = ''
// If an automatic mode is enabled, get details.
if( ['name', 'fasta'].contains(params.ref_mode) ) {
if( params.verbose ) {
log.info ""
log.info "Using Automatic Reference Location Mode: ${params.ref_mode}"
log.info ""
}
ref_info = get_ref_details(params, 'ref')
if( params.verbose ) {
log.info "Identified Reference Database Details:"
ref_info.each {detail ->
log.info "- ref_${detail.key}".padRight(21) + " : ${detail.value}"
}
}
// Set database details.
ref_info.each {detail ->
if( !params.containsKey(detail.key) ) {
params["ref_${detail.key}".toString()] = detail.value
} else if( !(['name', 'fasta'].contains(detail_key) ) ) {
log.warn "Key: ref_${detail.key} already exists in params."
log.warn "- Skipping auto-setting of this params value."
println ""
}
}
params.ref_eff_genome_size = file(params.ref_eff_genome_path).text.trim()
if( params.verbose ) {
log.info 'Setting --ref_eff_genome_size (params.ref_eff_genome_size)'
log.info "- to identified value: ${params.ref_eff_genome_size}"
}
if( params.do_norm_spike ) {
ref_info = get_ref_details(params, 'norm_ref')
if( params.verbose ) {
log.info ""
log.info "Identified Normalization Reference Database Details:"
ref_info.each {detail ->
log.info "- norm_ref_${detail.key}".padRight(21) + " : ${detail.value}"
}
}
// Set database details.
ref_info.each {detail ->
if( !params.containsKey("norm_ref_${detail.key}".toString()) ) {
params["norm_ref_${detail.key}".toString()] = detail.value
} else if (!(['name', 'fasta'].contains(detail.key) ) ) {
log.warn "Key: norm_ref_${detail.key} already exists in params."
log.warn "- Skipping auto-setting of this params value."
println ""
}
}
}
} else {
if( params.verbose ) {
log.info "Using Manual Reference File Location Paramaters."
log.info ""
}
}
}
test_commands = [
//"Java": ["${params.java_call} -version", 0, *get_resources(params, 'java')],
"bowtie2-build": ["${params.bowtie2_build_call} --version", 0,
*get_resources(params, 'bowtie2')],
"faCount": ["${params.facount_call}", 255, *get_resources(params, 'facount')],
"Samtools": ["${params.samtools_call} help", 0, *get_resources(params, 'samtools')],
"FastQC": ["${params.fastqc_call} -v", 0, *get_resources(params, 'fastqc')],
"Trimmomatic": ["${params.trimmomatic_call} -version", 0, *get_resources(params, 'trimmomatic')],
"bowtie2": ["${params.bowtie2_call} --version", 0, *get_resources(params, 'bowtie2')],
"bedtools": ["${params.bedtools_call} --version", 0, *get_resources(params, 'bedtools')],
"MACS2": ["${params.macs2_call} --version", 0, *get_resources(params, 'macs2')],
"SEACR": ["${params.seacr_call}", 1, *get_resources(params, 'seacr')],
"bedGraphToBigWig": ["${params.bedgraphtobigwig_call}", 255,
*get_resources(params, 'bedgraphtobigwig')],
]
// General Keys and Params:
req_keys.add(['publish_files', ['minimal', 'default', 'all']])
req_keys.add(['publish_mode', ['symlink', 'copy']])
// Keys and Params for merging langes
if( params.do_merge_lanes ) {
null // No custom settings
}
// Keys and Params for FastQC
if( params.do_fastqc ) {
req_keys.add(['fastqc_flags'])
}
// Keys and Params for Trimmomatic trimming
if( params.do_trim ) {
//req_files.add(['trimmomatic_adapterpath'])
req_keys.add(['trimmomatic_settings'])
req_keys.add(['trimmomatic_flags'])
}
// keys and params for alignment steps
if( true ) {
req_keys.add(['ref_bt2db_path'])
req_keys.add(['ref_name'])
req_keys.add(['aln_ref_flags'])
req_keys.add(['use_aln_modes',
['all', 'all_dedup', 'less_120', 'less_120_dedup']])
req_files.add(['ref_chrom_sizes_path'])
}
// keys and params for normalization
if( params.do_norm_spike ) {
req_keys.add(['norm_scale'])
req_keys.add(['aln_norm_flags'])
req_keys.add(['norm_ref_bt2db_path'])
req_keys.add(['norm_ref_name'])
req_keys.add(['norm_mode', ['adj', 'all']])
}
// keys and params for CPM normalization
if( params.do_norm_cpm ) {
req_keys.add(['norm_cpm_scale'])
}
// keys and params for bigWig creation
if( params.do_make_bigwig ) {
req_keys.add(['norm_mode', ['adj', 'all']])
}
// keys and params for peak calling
req_keys.add(['peak_callers', ['macs', 'seacr']])
if( params.peak_callers.contains('macs') ) {
req_keys.add(['macs_qval'])
req_keys.add(['macs_flags'])
req_keys.add(['ref_eff_genome_size'])
}
if( params.peak_callers.contains('seacr') ) {
req_keys.add(['seacr_fdr_threshhold'])
req_keys.add(['seacr_norm_mode', ['auto', 'norm', 'non']])
req_keys.add(['seacr_call_stringent', [true, false]])
req_keys.add(['seacr_call_relaxed', [true, false]])
}
// For validate, test all dependencies.
if( params.mode == 'validate' ) {
use_tests = []
test_commands.each{test -> use_tests.add([test.key, *test.value]) }
}
// If a Run Mode, Test Step-Specific Keys and Required Files:
if( params.mode == 'run') {
test_params_keys(params, req_keys)
test_params_files(params, req_files)
}
}
// If run mode, ensure input files have been provided and test existence.
if( params.mode == 'run' ) {
if( params.containsKey('treat_fastqs') && params.containsKey('fastq_groups') ) {
message = "Please provide input fastq file data to either of \n"
message += " --treat_fastqs (params.treat_fastqs)\n"
message += " or --fastq_groups (params.fastq_groups)\n"
message += " (not both)\n"
log.error message
exit 1
// If Input files are via params.treat_fastqs
} else if( params.containsKey('treat_fastqs') ) {
if( !params.treat_fastqs ) {
err_message = "params.treat_fastqs cannot be empty if provided."
log.error err_message
exit 1
}
// Check Existence of treat and control fastqs if provided.
if( params.treat_fastqs instanceof List ) {
params.treat_fastqs.each{it -> print_in_files.addAll(file(it, checkIfExists: true)) }
} else {
print_in_files.addAll(file(params.treat_fastqs, checkIfExists: true))
}
if( params.containsKey('ctrl_fastqs') ) {
if( params.ctrl_fastqs instanceof List ) {
params.ctrl_fastqs.each{it -> print_in_files.addAll(file(it, checkIfExists: true)) }
} else {
print_in_files.addAll(file(params.ctrl_fastqs, checkIfExists: true))
}
}
// If Input files are via params.fastq_groups
} else if( params.containsKey('fastq_groups') ) {
if( !params.fastq_groups ) {
err_message = "params.fastq_groups cannot be empty if provided."
log.error err_message
exit 1
}
params.fastq_groups.each {group_name, group_details ->
if( !group_details.containsKey('treat') || !group_details.treat ) {
err_message = "params.fastq_groups - Group: '${group_name}\n"
err_message += " Does not contain required key 'treat' or variable is empty."
log.error err_message
exit 1
}
if( !group_details.containsKey('ctrl') || !group_details.ctrl ) {
warn_message = "params.fastq_groups - Group: '${group_name}\n"
warn_message += " Does not contain key 'ctrl' or variable is empty.\n\n"
warn_message += "(If this is intentional, please consider using '--treat_fastqs\n'"
warn_message += " parameter instead for file input as this may produce \n"
warn_message += " unexpected output)"
log.warn warn_message
}
if( group_details.treat instanceof List ) {
group_details.treat.each{it -> print_in_files.addAll(file(it, checkIfExists: true)) }
} else {
print_in_files.addAll(file(group_details.treat, checkIfExists: true))
}
if( group_details.containsKey('ctrl') ) {
if( group_details.ctrl instanceof List ) {
group_details.ctrl.each{it ->
print_in_files.addAll(file(it, checkIfExists: true))
}
} else {
print_in_files.addAll(file(group_details.ctrl, checkIfExists: true))
}
}
}
}
}
use_aln_modes = return_as_list(params['use_aln_modes'])
peak_callers = return_as_list(params['peak_callers'])
// --------------- If Verbose, Print Nextflow Command: ---------------
if( params.verbose ) { print_command(workflow.commandLine) }
// --------------- Parameter Setup ---------------
log.info ''
log.info ' -- Preparing Workflow Environment -- '
log.info ''
// --------------- Print Workflow Details ---------------
// If Verbose, Print Workflow Details:
if( params.verbose ) {
print_workflow_details(workflow, params, params.out_front_pad, params.out_prop_pad)
}
// -- If a Run Mode, Check-for and Print Input Files
if( params.mode == 'run' ) {
if( print_in_files.size() < 2 ) {
message = "No Input Files Provided.\n"
message += "Please provide valid --treat_fastqs (params.treat_fastqs) option.\n"
message += " Exiting"
log.error message
exit 1
} else if( params.verbose ) {
message = (
"-".multiply(params.out_front_pad)
+ "Input Files:".padRight(params.out_prop_pad)
+ print_in_files[0]
)
log.info message
print_in_files.subList(1, print_in_files.size()).each {
log.info "-".multiply(params.out_front_pad) + ' '.multiply(params.out_prop_pad) + it
}
} else {
log.info "${print_in_files.size()} Input Files Detected. "
}
}
// --------------- Execute Workflow ---------------
log.info ''
log.info ' -- Executing Workflow -- '
log.info ''
System.out.flush(); System.err.flush()
// -- Run Mode: validate
if( ['initiate'].contains( params.mode ) ) {
trimmomatic_dir = file("${projectDir}/ref_dbs/trimmomatic_adapters")
if( !(trimmomatic_dir.exists()) ) {
log.info "Downloading Trimmomatic Sequence Adapter Files"
println "${projectDir}/ref_dbs/get_trimmomatic_adapters.sh".execute().text
}
log.info "Copying CnR-flow nextflow task configuration into launch directory"
task_config = file("${projectDir}/nextflow.config.task")
task_config_target = file("${launchDir}/nextflow.config")
task_config_nodoc = file("${projectDir}/nextflow.config.task.nodoc")
task_config_nodoc_target = file("${launchDir}/nextflow.config.nodoc")
task_config_minimal = file("${projectDir}/nextflow.config.task.nodoc.minimal")
task_config_minimal_target = file("${launchDir}/nextflow.config.minimal")
if( task_config_target.exists() ) {
message = "Cannot overwrite existing task config file:\n"
message += " ${task_config_target}\n"
message += "Please remove and retry.\n"
log.error message
exit 1
}
task_config.copyTo("${task_config_target}")
task_config_nodoc.copyTo("${task_config_nodoc_target}")
task_config_minimal.copyTo("${task_config_minimal_target}")
log.info ""
log.info "Initialization Complete."
log.info "Please configure pipeline cluster / dependency settings (if necessary) at:"
log.info "- ${projectDir}/nextflow.config"
log.info ""
log.info "Please modify task configuration file:"
log.info "- ${task_config_target}"
log.info "Then check using 'validate' mode to test setup."
println ""
}
// -- Run Mode: validate
if( ['validate'].contains( params.mode ) ) {
process CnR_Validate {
tag { title }
// Previous step ensures only one or another (non-null) resource is provided:
container { "${test_container}" }
module { if(!("${test_container}")) { "${test_module}"} else { "" } }
conda { if(!("${test_container}") && !("${test_module}")) {
"${test_conda}" } else { "" }
}
label 'small_mem'
maxForks 1
errorStrategy 'terminate'
cpus 1
beforeScript { task_details(task) }
echo true
input:
tuple val(title), val(test_call), val(exp_code), val(test_module), val(test_conda), val(test_container) from Channel.fromList(use_tests)
output:
val('success') into validate_outs
script:
resource_string = ""
if( task.container) {
resource_string = "echo -e ' - Container: ${task.container.toString()}'"
} else if( task.module) {
resource_string = "echo -e ' - Module(s): ${task.module.join(':')}'"
} else if( task.conda) {
resource_string = "echo -e ' - Conda-env: \"${task.conda.toString()}\"'"
}
shell:
'''
echo -e "\\n!{task.tag}"
!{resource_string}
echo -e "\\nTesting System Call for dependency: !{title}"
echo -e "Using Command:"
echo -e " !{test_call}\\n"
set +e
!{test_call}
TEST_EXIT_CODE=$?
set -e
if [ "${TEST_EXIT_CODE}" == "!{exp_code}" ]; then
echo "!{title} Test Success."
PROCESS_EXIT_CODE=0
else
echo "!{title} Test Failure."
echo "Exit Code: ${TEST_EXIT_CODE}"
PROCESS_EXIT_CODE=${TEST_EXIT_CODE}
fi
exit ${PROCESS_EXIT_CODE}
'''
}
validate_outs
.collect()
.view { it -> "\nDependencies Have been Validated, Results:\n $it\n" }
}
def get_refs_locations(params) {
refs_locations = [
'refs_dir': params.refs_dir,
'pipe_refs_dir': "${projectDir}/ref_dbs"
]
if( params.containsKey('shared_refs_dir') ) {
refs_locations['shared_refs_dir'] = params.shared_refs_dir
}
refs_locations
}
def search_refs (params, only_ref_name=null) {
refs = [:]
refs_locations = get_refs_locations(params)
refs_locations.each {ref ->
loc_name = ref.key
loc_path = ref.value
ref_dir = file(loc_path)
//if( !ref_dir.exists() || !ref_dir.isDirectory() ) {
// log.error "Provided References Directory: '${loc_name}'"
// log.error "Cannot be found at location:"
// log.error " ${loc_path}"
// log.error ""
// exit 1
//}
if( ref_dir.exists() && ref_dir.isDirectory() ) {
ref_dir.eachFileMatch(~/.*\.refinfo\.txt$/) {ref_info_path ->
ref_info_name = ref_info_path.getName()
ref_name = ref_info_name - ~/\.refinfo\.txt$/
refs[ref_name] = ref_info_path
}
}
}
if( only_ref_name ) {
if( refs.containsKey(only_ref_name) ) {
refs = [(only_ref_name): refs[only_ref_name]]
} else {
log.error "Reference: '${only_ref_name}' Cannot be located."
println ''
exit 1
}
}
refs
}
// -- Run Mode: list_refs
if( params.mode == 'list_refs' ) {
ref_locations = get_refs_locations(params)
refs = search_refs(params)
if( refs.size() < 1 ) {
log.info 'No Prepared References Found at Locations:'
ref_locations.each{loc ->
use_name = loc.value - ~/\.refinfo\.txt$/
log.info '-' + "${loc.key}".padRight(15) + " : ${use_name}"
}
println ''
} else {
println ''
log.info 'Prepared References: (name : location)'
max_name_len = 0
refs.each {ref ->
max_name_len = (ref.key.size() > max_name_len) ? ref.key.size() : max_name_len
}
refs.each {ref ->
log.info "-- " + ref.key.padRight(max_name_len ) + " : ${ref.value}"
}
println ''
}
}
// -- Run Mode: prep_fasta
if( params.mode == 'prep_fasta' ) {
if( !file("${params.refs_dir}").exists() ) {
log.info "Creating Prep Directory: ${params.refs_dir}"
println ""
file("${params.refs_dir}").mkdir()
}
use_prep_sources = []
prep_sources = [params.ref_fasta]
if( params.containsKey('norm_ref_fasta') ) {
prep_sources.add(params.norm_ref_fasta)
}
prep_sources.each {source_fasta ->
if( "${source_fasta}".endsWith('.gz') ) {
temp_name = file("${source_fasta}").getBaseName()
db_name = file("${temp_name}").getBaseName()
} else {
db_name = file("${source_fasta}").getBaseName()
}
use_prep_sources.add([db_name, "${source_fasta}"])
}
Channel.fromList(use_prep_sources)
.map {db_name, full_fn ->
use_full_fn = full_fn
if( !("${full_fn}".contains('://'))
&& !("${full_fn}".startsWith('/') ) ) {
use_full_fn = "${launchDir}/${full_fn}"
}
[db_name, full_fn, file(full_fn)]
}
.set {source_fasta}
process CnR_Prep_GetFasta {
tag { name }
label 'big_mem'
beforeScript { task_details(task) }
stageInMode 'copy'
echo true
input:
tuple val(name), val(fasta_source), path(fasta) from source_fasta
output:
tuple val(name), path(use_fasta) into get_fasta_outs
tuple val(name), val(get_fasta_details) into get_fasta_detail_outs
path '.command.log' into get_fasta_log_outs
publishDir "${params.refs_dir}/logs", mode: params.publish_mode,
pattern: ".command.log", saveAs: { out_log_name }
publishDir "${params.refs_dir}", mode: params.publish_mode,
overwrite: false, pattern: "${use_fasta}*"
script:
run_id = "${task.tag}.${task.process}"
out_log_name = "${run_id}.nf.log.txt"
full_refs_dir = "${params.refs_dir}"
acq_datetime = new Date().format("yyyy-MM-dd_HH:mm:ss")
if( !(full_refs_dir.startsWith("/")) ) {
full_refs_dir = "${workflow.launchDir}/${params.refs_dir}"
}
if( "${fasta}".endsWith('.gz') ) {
use_fasta = fasta.getBaseName()
gunzip_command = "gunzip -c ${fasta} > ${use_fasta}"
} else {
use_fasta = fasta
gunzip_command = "echo 'File is not gzipped.'"
}
get_fasta_details = "name,${name}\n"
get_fasta_details += "title,${name}\n"
get_fasta_details += "fasta_source,${fasta_source}\n"
get_fasta_details += "fastq_acq,${acq_datetime}\n"
get_fasta_details += "fasta_path,./${use_fasta}"
shell:
'''
echo "Acquiring Fasta from Source:"
echo " !{fasta}"
echo ""
!{gunzip_command}
echo "Publishing Fasta to References Directory:"
echo " !{full_refs_dir}"
'''
}
get_fasta_outs.into{prep_bt2db_inputs; prep_sizes_inputs}
process CnR_Prep_Bt2db {
if( has_container(params, 'bowtie2') ) {
container get_container(params, 'bowtie2')
} else if( has_module(params, 'bowtie2') ) {
module get_module(params, 'bowtie2')
} else if( has_conda(params, 'bowtie2') ) {
conda get_conda(params, 'bowtie2')
}
tag { name }
label 'big_mem'
beforeScript { task_details(task) }
echo true
input:
tuple val(name), path(fasta) from prep_bt2db_inputs
output:
path "${bt2db_dir_name}/*" into prep_bt2db_outs
tuple val(name), val(bt2db_details) into prep_bt2db_detail_outs
path '.command.log' into prep_bt2db_log_outs
publishDir "${params.refs_dir}/logs", mode: params.publish_mode,
pattern: ".command.log", saveAs: { out_log_name }
publishDir "${params.refs_dir}", mode: params.publish_mode,
pattern: "${bt2db_dir_name}/*"
script:
run_id = "${task.tag}.${task.process}"
out_log_name = "${run_id}.nf.log.txt"
bt2db_dir_name = "${name}_${params.prep_bt2db_suf}"
refs_dir = "${params.refs_dir}"
full_out_base = "${bt2db_dir_name}/${name}"
bt2db_details = "bt2db_path,./${full_out_base}"
shell:
'''
echo "Preparing Bowtie2 Database for fasta file:"
echo " !{fasta}"
echo ""
echo "Out DB Dir: !{bt2db_dir_name}"
echo "Out DB: !{full_out_base}"
mkdir -v !{bt2db_dir_name}
set -v -H -o history
!{params.bowtie2_build_call} --quiet --threads !{task.cpus} !{fasta} !{full_out_base}
set +v +H +o history
echo "Publishing Bowtie2 Database to References Directory:"
echo " !{params.refs_dir}"
'''
}
process CnR_Prep_Sizes {
if( has_container(params, 'samtools_facount') ) {
container get_container(params, 'samtools_facount')
} else if( has_module(params, ['samtools', 'facount']) ) {
module get_module(params, ['samtools', 'facount'])
} else if( has_conda(params, ['samtools', 'facount']) ) {
conda get_conda(params, ['samtools', 'facount'])
}
tag { name }
beforeScript { task_details(task) }
label 'norm_mem'
cpus 1
echo true
input:
tuple val(name), path(fasta) from prep_sizes_inputs
output:
tuple path(faidx_name), path(chrom_sizes_name), path(fa_count_name),
path(eff_size_name) into prep_sizes_outs
tuple val(name), val(prep_sizes_details) into prep_sizes_detail_outs
path '.command.log' into prep_sizes_log_outs
publishDir "${params.refs_dir}/logs", mode: params.publish_mode,
pattern: ".command.log", saveAs: { out_log_name }
publishDir "${params.refs_dir}", mode: params.publish_mode,
pattern: "${name}*"
script:
run_id = "${task.tag}.${task.process}"
out_log_name = "${run_id}.nf.log.txt"
faidx_name = "${fasta}.fai"
chrom_sizes_name = "${name}.chrom.sizes"
fa_count_name = "${name}.faCount"
eff_size_name = "${name}.effGenome"
prep_sizes_details = "faidx_path,./${faidx_name}\n"
prep_sizes_details += "chrom_sizes_path,./${chrom_sizes_name}\n"
prep_sizes_details += "fa_count_path,./${fa_count_name}\n"
prep_sizes_details += "eff_genome_path,./${eff_size_name}"
shell:
'''
echo -e "\\nPreparing genome size information for Input Fasta: !{fasta}"
echo -e "Indexing Fasta..."
!{params.samtools_call} faidx !{fasta}
echo -e "Preparing chrom.sizes File..."
cut -f1,2 !{faidx_name} > !{chrom_sizes_name}
echo -e "Counting Reference Nucleotides..."
!{params.facount_call} !{fasta} > !{fa_count_name}
echo -e "Calculating Reference Effective Genome Size (Total - N's method )..."
TOTAL=$(tail -n 1 !{fa_count_name} | cut -f2)
NS=$(tail -n 1 !{fa_count_name} | cut -f7)
EFFECTIVE=$( expr ${TOTAL} - ${NS})
echo "${EFFECTIVE}" > !{eff_size_name}
echo "Effective Genome Size: ${TOTAL} - ${NS} = ${EFFECTIVE}"
echo "Done."
'''
}
get_fasta_detail_outs
.concat(prep_sizes_detail_outs)
.concat(prep_bt2db_detail_outs)
.collectFile(
sort: false, newLine: true,
storeDir: "${params.refs_dir}"
) {name, details ->
["${name}.refinfo.txt", details]
}
.view { "Database Prepared and published in:\n ${params.refs_dir}/${it}\nDetails:\n${it.text}" }
}
// -- Run Mode: 'run'
if( params.mode == 'run' ) {
use_ctrl_samples = false
// If Input files are via params.treat_fastqs
if( params.containsKey('treat_fastqs') ) {
Channel.fromFilePairs(params.treat_fastqs)
.map {name, fastqs -> [name, 'treat', 'main', fastqs] }
.set { treat_fastqs }
//Create Channel of Control Fastas, if existing.
if( params.containsKey('ctrl_fastqs') && params.ctrl_fastqs ) {
Channel.fromFilePairs(params.ctrl_fastqs)
.map {name, fastqs -> [name, 'ctrl', 'main', fastqs] }
.set { ctrl_fastqs }
use_ctrl_samples = true
if( params.verbose ) {
log.info "Control Samples Detected. Enabling Treatment/Control Peak-Calling Mode."
log.info ""
}
} else {
Channel.empty()
.set { ctrl_fastqs }
use_ctrl_samples = false
if( params.verbose ) {
log.info "No Control Samples Detected."
log.info ""
}
}
// If Input files are via params.fastq_groups
} else if( params.containsKey('fastq_groups') ) {
treat_channels = []
ctrl_channels = []
params.fastq_groups.each {group_name, group_details ->
treat_channels.add(
Channel
.fromFilePairs(group_details.treat, checkIfExists: true)
.map {name, fastqs -> [name, 'treat', group_name, fastqs] }
)
if( group_details.containsKey('ctrl') ) {
if( !use_ctrl_samples ) {
use_ctrl_samples = true
if( params.verbose ) {
log.info "Control Samples Detected. Enabling Treatment/Control Peak-Calling Mode."
log.info ""
}
}
ctrl_channels.add(
Channel
.fromFilePairs(group_details.ctrl, checkIfExists: true)
.map {name, fastqs -> [name, 'ctrl', group_name, fastqs] }
)
}
}
Channel.empty()
.mix(*treat_channels)
.set { treat_fastqs }
Channel.empty()
.mix(*ctrl_channels)
.set { ctrl_fastqs }
}
// Mix (Labeled) Treatment and Control Fastqs
ctrl_fastqs
.concat( treat_fastqs )
// Remove duplicate ctrl also matched as treat:
.unique { name, cond, group, fastqs -> name }
.map { name, cond, group, fastqs ->
// Remove "_R" name suffix
name = name - ~/_R$/
[name, cond, group, fastqs]
}
.into { prep_fastqs; seq_len_fastqs }
// If Merge, combine sample prefix-duplicates and catenate files.
if( params.do_merge_lanes ) {
prep_fastqs
// Remove "_L00?" name suffix
.map { name, cond, group, fastqs ->
name = name - ~/_L00\d$/
name = name - params.trim_name_prefix
name = name - params.trim_name_suffix
[name, cond, group, fastqs]
}
// Group files by common name
.groupTuple()
// Reformat grouped files so that fastqs are in lists of pairs.
.map {name, conds, groups, fastq_pairs ->
[name, conds[0], groups[0], fastq_pairs.flatten()]
}
.set { merge_fastqs }
// Step 0, Part A, Merge Lanes (If Enabled)
process CnR_S0_B_MergeFastqs {
tag { name }
label 'big_mem'
beforeScript { task_details(task) }
cpus 1
input:
tuple val(name), val(cond), val(group), path(fastq) from merge_fastqs
output:
tuple val(name), val(cond), val(group), path("${merge_fastqs_dir}/${name}_R{1,2}_001.fastq.gz") into use_fastqs
path '.command.log' into mergeFastqs_log_outs
publishDir "${params.out_dir}/${params.log_dir}", mode: params.publish_mode,
pattern: '.command.log', saveAs: { out_log_name }
// Publish merged fastq files only when publish_files == all
publishDir "${params.out_dir}", mode: params.publish_mode,
pattern: "${merge_fastqs_dir}/*",
enabled: (params.publish_files == "all")
script:
run_id = "${task.tag}.${task.process}"
out_log_name = "${run_id}.nf.log.txt"
merge_fastqs_dir = "${params.merge_fastqs_dir}"
R1_files = fastq.findAll {fn ->
"${fn}".contains("_R1_") || "${fn}".contains("_R1.")
|| "${fn}".contains("_1.f") || "${fn}".contains("_1_")
}
R2_files = fastq.findAll {fn ->
"${fn}".contains("_R2_") || "${fn}".contains("_R2.")
|| "${fn}".contains("_2.f") || "${fn}".contains("_2_")
}
R1_out_file = "${params.merge_fastqs_dir}/${name}_R1_001.fastq.gz"
R2_out_file = "${params.merge_fastqs_dir}/${name}_R2_001.fastq.gz"
if( R1_files.size() < 1 || R2_files.size() < 1 ) {
log.error "Error: Merge cannot classify .fastq[.gz] 1/2 or R1/R2 file names."
log.error "Detected R1 Files: ${R1_files}"
log.error "Detected R2 Files: ${R2_files}"
log.error "Supported schemes are '_R1_', '_R1.', '_1_', '_1.'"
exit 1
}
check_command = ""
if( "${R1_files[0]}".endsWith('.gz') ) {
check_command = "gzip -t ${R1_files.join(' ')} ${R2_files.join(' ')}"
}
if( R1_files.size() == 1 && R2_files.size() == 1 ) {
command = '''
echo "No Merge Necessary. Renaming Files..."
mkdir !{merge_fastqs_dir}
# Check File Integrity if gzipped
!{check_command}
set -v -H -o history
mv -v "!{R1_files[0]}" "!{R1_out_file}"
mv -v "!{R2_files[0]}" "!{R2_out_file}"
set +v +H +o history
R1_OUT_LEN=$(zcat -f < !{R1_out_file} | wc -l | xargs)
R2_OUT_LEN=$(zcat -f < !{R2_out_file} | wc -l | xargs)
echo "R1 Lines: ${R1_OUT_LEN}"
echo "R2 Lines: ${R2_OUT_LEN}"
if [ "${R1_OUT_LEN}" == "0" -o "${R2_OUT_LEN}" == "0" ] ; then
echo "Input file not found, or input file of zero length detected."
exit 1
fi
'''
} else {
command = '''
mkdir !{merge_fastqs_dir}
# Check File Integrity if gzipped
!{check_command}
echo -e "\\nCombining Files: !{R1_files.join(' ')}"
echo " Into: !{R1_out_file}"
set -v -H -o history
cat '!{R1_files.join("' '")}' > '!{R1_out_file}'
set +v +H +o history
echo -e "\\nCombining Files: !{R2_files.join(' ')}"
echo " Into: !{R2_out_file}"
set -v -H -o history
cat '!{R2_files.join("' '")}' > '!{R2_out_file}'
set +v +H +o history
R1_OUT_LEN=$(zcat -f < !{R1_out_file} | wc -l | xargs)
R2_OUT_LEN=$(zcat -f < !{R2_out_file} | wc -l | xargs)
echo "R1 Lines: ${R1_OUT_LEN}"
echo "R2 Lines: ${R2_OUT_LEN}"
if [ "${R1_OUT_LEN}" == "0" -o "${R2_OUT_LEN}" == "0" ] ; then
echo "Input file not found, or input file of zero length detected."
exit 1
fi
'''
}
shell:
command
}
// If Not Merge, Rename and Passthrough fastq files.
} else {
prep_fastqs
.map { name, cond, group, fastqs ->
name = name - params.trim_name_prefix
name = name - params.trim_name_suffix
[name, cond, group, fastqs]
}
.set { use_fastqs }
}
// Prepare Step 0/1 Input Channels
use_fastqs.into { fastqcPre_inputs; trim_inputs }
// Step 0, Part C, FastQC Analysis (If Enabled)
if( params.do_fastqc ) {
process CnR_S0_C_FastQCPre {
if( has_container(params, 'fastqc') ) {
container get_container(params, 'fastqc')
} else if( has_module(params, 'fastqc') ) {
module get_module(params, 'fastqc')
} else if( has_conda(params, 'fastqc') ) {
conda get_conda(params, 'fastqc')
}
tag { name }
label 'norm_mem'
beforeScript { task_details(task) }
cpus 1 //Multiple CPUS for FastQC are for multiple files.
input:
tuple val(name), val(cond), val(group), path(fastq) from fastqcPre_inputs
output: