This repository has been archived by the owner on Mar 7, 2023. It is now read-only.
forked from caspargross/nf-core-denovohybrid
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathmain.nf
792 lines (661 loc) · 27.1 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
#!/usr/bin/env nextflow
/*
========================================================================================
nf-core/denovohybrid
========================================================================================
nf-core/denovohybrid Analysis Pipeline.
#### Homepage / Documentation
https://github.com/nf-core/denovohybrid
----------------------------------------------------------------------------------------
*/
def helpMessage() {
//log.info nfcoreHeader()
log.info"""
Usage:
The typical command for running the pipeline is as follows:
nextflow run nf-core/denovohybrid --input 'read_locations.tsv' -profile docker
Mandatory arguments:
--input Path to tsv file with read locations (must be surrounded with quotes)
--profile Configuration profile to use. Can use multiple (comma separated)
Available: conda, docker, singularity, awsbatch, test and more.
Options:
--mode One of the following assemblers: [unicycler, miniasm, wtdbg2]
--minContigLength Filter for minimum contig lenght in output
--genomeSize Estimated final genome size (Default 5300000bp)
--targetShortReadCov Target short read coverage after subsampling
--tartgetLongReadCov Target long read coverage after subsampling
Other options:
--outdir The output directory where the results will be saved
--saveIntermediate Write intermediate files to the output folder (Default false)
--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
--maxMultiqcEmailFileSize Theshold 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 Name for the pipeline run. If not specified, Nextflow will automatically generate a random mnemonic.
AWSBatch options:
--awsqueue The AWSBatch JobQueue that needs to be set when running on AWSBatch
--awsregion The AWS Region for your AWS Batch job to run on
""".stripIndent()
}
// Show help emssage
if (params.help){
helpMessage()
exit 0
}
// 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
}
if( workflow.profile == '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 (workflow.tracedir.startsWith('s3:')) exit 1, "Specify a local tracedir or run without trace! S3 cannot be used for tracefiles."
}
// Stage config files
ch_multiqc_config = Channel.fromPath(params.multiqc_config)
ch_output_docs = Channel.fromPath("$baseDir/docs/output.md")
// Header log info
log.info nfcoreHeader()
def summary = [:]
if(workflow.revision) summary['Pipeline Release'] = workflow.revision
summary['Run Name'] = custom_runName ?: workflow.runName
// TODO nf-core: Report custom parameters here
summary['Input File'] = params.input
summary['Genome Size'] = params.genomeSize
summary['Longread Cov'] = params.targetLongReadCov
summary['Shortread Cov'] = params.targetShortReadCov
summary['Save Intermediates'] = params.saveIntermediate
summary['Assembler'] = params.mode
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
summary['Cont Engine'] = workflow.containerEngine
summary['Containers'] = workflow.container
if(workflow.profile == 'awsbatch'){
summary['AWS Region'] = params.awsregion
summary['AWS Queue'] = params.awsqueue
}
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) {
summary['E-mail Address'] = params.email
summary['MultiQC maxsize'] = params.maxMultiqcEmailFileSize
}
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()
def create_workflow_summary(summary) {
def yaml_file = workDir.resolve('workflow_summary_mqc.yaml')
yaml_file.text = """
id: 'nf-core-denovohybrid-summary'
description: " - this information is collected when the pipeline is started."
section_name: 'nf-core/denovohybrid Workflow Summary'
section_href: 'https://github.com/nf-core/denovohybrid'
plot_type: 'html'
data: |
<dl class=\"dl-horizontal\">
${summary.collect { k,v -> " <dt>$k</dt><dd><samp>${v ?: '<span style=\"color:#999999;\">N/A</a>'}</samp></dd>" }.join("\n")}
</dl>
""".stripIndent()
return yaml_file
}
/*
* Parse software version numbers
*/
process get_software_versions {
publishDir "${params.outdir}/pipeline_info", mode: 'copy',
saveAs: {filename ->
if (filename.indexOf(".csv") > 0) filename
else null
}
output:
file 'software_versions_mqc.yaml' into software_versions_yaml
file "software_versions.csv"
script:
"""
echo $workflow.manifest.version > v_pipeline.txt
echo $workflow.nextflow.version > v_nextflow.txt
Bandage --version > v_bandage.txt
fastqc --version > v_fastqc.txt
filtlong --version > v_filtlong.txt
miniasm -V > v_miniasm.txt
minimap2 --version > v_minimap2.txt
multiqc --version > v_multiqc.txt
pilon --version > v_pilon.txt
porechop --version > v_porechop.txt
quast --version > v_quast.txt
racon --version > v_racon.txt
seqtk 2>&1| grep Version > v_seqtk.txt
unicycler --version > v_unicycler.txt
wtdbg2 -V > v_wtdbg2.txt
scrape_software_versions.py &> software_versions_mqc.yaml
"""
}
/*
------------------------------------------------------------------------------
C O N F I G U R A T I O N
------------------------------------------------------------------------------
*/
// Show help messange when not correct input
if (params.help) exit 0, helpMessage()
if (!params.input) exit 0, helpMessage()
// Define valid run modes:
validModes = ['unicycler', 'miniasm', 'wtdbg2', 'all']
validModesLR = ['unicycler', 'miniasm', 'wtdbg2', 'all_lr']
// Set values from parameters:
sampleFile = file(params.input)
modes = params.mode.tokenize(',')
// Set long read only execution flag
longReadOnly = checkLongReadOnly(sampleFile);
// Setup channels
files=Channel.create()
// check if mode input is valid and create channel
if (longReadOnly) {
if (!modes.every{validModesLR.contains(it)}) {
log.info "Wrong execution mode, should be one of " + validModesLR
exit 1
}
files = extractFastq(sampleFile);
} else {
if (!modes.every{validModes.contains(it)}) {
log.info "Wrong execution mode, should be one of " + validModes
exit 1
}
files = extractFastq(sampleFile);
}
target_lr_length = params.targetLongReadCov * params.genomeSize
/*
------------------------------------------------------------------------------
P R O C E S S E S
------------------------------------------------------------------------------
*/
process porechop {
// Trim adapter sequences on long read nanopore files
tag{id}
input:
set id, file(lr), file(sr1), file(sr2) from files
output:
set id, file('lr_porechop.fastq'), file(sr1), file(sr2) into files_porechop
set id, file('lr_porechop.fastq'), val("raw") into files_nanoplot_raw
script:
// Join multiple longread files if possible
"""
cat ${lr} > nanoreads.fastq
porechop -i nanoreads.fastq -t ${task.cpus} -o lr_porechop.fastq
"""
}
process filtlong {
// Quality filter long reads focus on quality instead of length to preserve shorter reads for plasmids
tag{id}
input:
set id, lr, sr1, sr2 from files_porechop
output:
set id, file("lr_filtlong.fastq"), sr1, sr2 into files_lr_filtered
set id, file("lr_filtlong.fastq"), val('filtered') into files_nanoplot_filtered
script:
"""
filtlong \
--min_length 1000 \
--keep_percent 90 \
--length_weight 0.5\
--target_bases ${target_lr_length} \
${lr} > lr_filtlong.fastq
"""
}
// Junction: Include short read preprocessing only when sr available
files_to_fastqc = Channel.create()
files_preprocessed = Channel.create()
files_filtered = Channel.create()
files_lr_filtered
.choice(files_preprocessed, files_to_fastqc){
longReadOnly ? 0 : 1
}
// Combine channels after preprocessing and distribute to different assemblers
files_preprocessed
.mix(files_filtered)
.into{
files_pre_unicycler;
files_pre_miniasm;
files_pre_wtdbg2;
}
process nanoplot {
// Quality check for nanopore reads and Quality/Length Plots
tag{id}
publishDir "${params.outdir}/${id}/qc/longread_${type}/", mode: 'copy'
input:
set id, lr, type from files_nanoplot_raw.mix(files_nanoplot_filtered)
output:
file '*.png'
file '*.html'
file '*.txt'
set id, file("*_NanoStats.txt"), type into stats_lr
script:
"""
NanoPlot -t ${task.cpus} -p ${type}_ --title ${id}_${type} -c darkblue --fastq ${lr}
"""
}
process fastqc {
// Short read quality control
tag "$id"
publishDir "${params.outdir}/${id}/qc/shortread/fastqc", mode: 'copy',
saveAs: {filename -> filename.indexOf(".zip") > 0 ? "zips/$filename" : "$filename"}
input:
set id, lr, sr1, sr2 from files_to_fastqc
output:
file "*_fastqc.{zip,html}" into fastqc_results
set id, lr, sr1, sr2 into files_to_seqpurge
script:
"""
fastqc -q $sr1 $sr2 -o .
"""
}
process seqpurge {
// Trim adapters on short read files
publishDir "${params.outdir}/${id}/qc/shortread/", mode: 'copy', pattern: "${id}_readQC.qcml"
tag{id}
input:
set id, lr, sr1, sr2 from files_to_seqpurge
output:
set id, lr, file('sr1.fastq.gz'), file('sr2.fastq.gz') into files_purged
set id, file("${id}_readQC.qcml"), val("read_qc") into stats_sr
script:
"""
SeqPurge -in1 ${sr1} -in2 ${sr2} -threads ${task.cpus} -out1 sr1.fastq.gz -out2 sr2.fastq.gz -qc ${id}_readQC.qcml
"""
}
process sample_shortreads {
// Subset short reads to reach target coverage
tag{id}
input:
set id, lr, sr1, sr2 from files_purged
output:
set id, lr, file('sr1_filt.fastq'), file('sr2_filt.fastq') into files_filtered
shell:
'''
readLength=$(zcat !{sr1} | awk 'NR % 4 == 2 {s += length($1); t++} END {print s/t}')
srNumber=$(echo "(!{params.genomeSize} * !{params.targetShortReadCov})/${readLength}" | bc)
seqtk sample -s100 !{sr1} ${srNumber} > sr1_filt.fastq
seqtk sample -s100 !{sr2} ${srNumber} > sr2_filt.fastq
'''
}
process miniasm{
// Long read assembly using minimap2 and miniasm
tag{id}
if (params.saveIntermediate) publishDir "${params.outdir}/${id}/assembly/miniasm", mode: 'copy'
input:
set id, lr, sr1, sr2 from files_pre_miniasm
output:
set id, lr, sr1, sr2, file("${id}_assembly_miniasm.fasta"), val('miniasm') into files_nocon_miniasm
set id, val('miniasm'), file("${id}_graph_miniasm.gfa") into assembly_graph_miniasm
when:
isMode(['miniasm', 'all', 'all_lr'])
script:
"""
minimap2 -x ava-ont -t ${task.cpus} ${lr} ${lr} > ovlp.paf
miniasm -f ${lr} ovlp.paf > ${id}_graph_miniasm.gfa
awk '/^S/{print ">"\$2"\\n"\$3}' ${id}_graph_miniasm.gfa | fold > ${id}_assembly_miniasm.fasta
"""
}
process unicycler{
// complete bacterial hybrid assembly pipeline
// accepts both hybrid data and longread only
tag{id}
if (params.saveIntermediate) publishDir "${params.outdir}/${id}/assembly/", mode: 'copy'
input:
set id, lr, sr1, sr2 from files_pre_unicycler
output:
set id, file("unicycler/assembly.fasta"), val('unicycler') into assembly_unicycler
set id, val('unicycler'), file("unicycler/assembly.gfa") into assembly_graph_unicycler
file("unicycler/assembly.fasta")
file("unicycler/unicycler.log")
when:
isMode(['unicycler', 'all', 'all_lr'])
script:
if (!longReadOnly)
"""
unicycler -1 ${sr1} -2 ${sr2} -l ${lr} -o unicycler -t ${task.cpus}
"""
else
"""
unicycler -l ${lr} -o unicycler -t ${task.cpus}
"""
}
process wtdbg{
// Long read assembly with wtdbg2 assembler
tag{id}
if (params.saveIntermediate) publishDir "${params.outdir}/${id}/assembly/wtdbg2", mode: 'copy'
input:
set id, lr, sr1, sr2 from files_pre_wtdbg2
output:
set id, lr, sr1, sr2, file("${id}_assembly_wtdbg2.fasta"), val('wtdb2') into files_nocon_wtdbg2
when:
isMode(['wtdb2', 'all', 'all_lr'])
script:
"""
wtdbg2 -x rs -g ${params.genomeSize} -i ${lr} -t ${task.cpus} -fo ${id}
wtpoa-cns -t ${task.cpus} -i ${id}.ctg.lay.gz -fo ${id}_assembly_wtdbg2.fasta
"""
}
process racon {
// Find consensus in miniasm assembly by realigning long reads
// Reiterate 3 times
tag{id}
if (params.saveIntermediate) publishDir "${params.outdir}/${id}/assembly_processed/racon", mode: 'copy'
input:
set id, lr, sr1, sr2, assembly, type from files_nocon_miniasm.mix(files_nocon_wtdbg2)
output:
set id, lr, sr1, sr2, file("${id}_consensus_racon.fasta"), type into files_unpolished_racon
file("${id}_consensus_racon.fasta")
script:
"""
minimap2 -x map-ont -t ${task.cpus} ${assembly} ${lr} > map1.paf
racon -m 8 -x -6 -g -8 -w 500 -t ${task.cpus} ${lr} map1.paf ${assembly} > cons1.fasta
minimap2 -x map-ont -t ${task.cpus} cons1.fasta ${lr} > map2.paf
racon -m 8 -x -6 -g -8 -w 500 -t ${task.cpus} ${lr} map2.paf cons1.fasta > cons2.fasta
minimap2 -x map-ont -t ${task.cpus} cons2.fasta ${lr} >map3.paf
racon -m 8 -x -6 -g -8 -w 500 -t ${task.cpus} ${lr} map3.paf cons2.fasta > ${id}_consensus_racon.fasta
"""
}
// Junction! Create channel for all unpolished files to be cleaned with Pilon
// Execute pilon only when short reads are available
files_pilon = Channel.create()
assembly_nopilon = Channel.create()
assembly_pilon = Channel.create()
assembly_merged = Channel.create()
files_unpolished_racon //.mix(
//files_unpolished_flye)
.choice(files_pilon, assembly_nopilon){
longReadOnly ? 1 : 0}
assembly_merged = assembly_nopilon
.map{it -> [it[0], it[4], it[5]]}
.mix(
assembly_unicycler,
assembly_pilon
)
.into{asm_quast; asm_format}
process pilon{
// Polishes long read assemly with short reads
tag{id}
publishDir "${params.outdir}/${id}/assembly_processed/pilon", mode: 'copy'
input:
set id, lr, sr1, sr2, contigs, type from files_pilon
output:
set id, file("${id}_${type}_pilon.fasta"), type into assembly_pilon
script:
"""
bowtie2-build ${contigs} contigs_index.bt2
bowtie2 --local --very-sensitive-local -I 0 -X 2000 -x contigs_index.bt2 \
-1 ${sr1} -2 ${sr2} | samtools sort -o alignments.bam -T reads.tmp
samtools index alignments.bam
pilon -Xmx16384m --genome ${contigs} --frags alignments.bam --changes \
--output ${id}_${type}_pilon --fix all
"""
}
process draw_assembly_graph {
// Use Bandage to draw a picture of the assembly graph
tag{id}
publishDir "${params.outdir}/${id}/assembly/graph_plot/", mode: 'copy'
input:
set id, type, gfa from assembly_graph_unicycler.mix(assembly_graph_miniasm)
output:
file("${id}_${type}_graph.svg")
script:
"""
Bandage image ${gfa} ${id}_${type}_graph.svg
"""
}
process quast{
// Assembly quality control
tag{id}
publishDir "${params.outdir}/${id}/qc/assembly", mode: 'copy'
input:
set id, assembly, type from asm_quast
output:
file("${id}_${type}/report.tsv") into quast_results
file("${id}_${type}/*")
script:
"""
quast -o ${id}_${type} -l ${id}_${type} -t ${task.cpus} ${assembly}
#cp ${id}_${type}/report.tsv quast_${id}_${type}.tsv
"""
}
process format_final_output {
// Filter contigs by length and give consistenc contig naming
publishDir "${params.outdir}/${id}/genomes/", mode: 'copy'
tag{id}
input:
set id, contigs, type from asm_format
output:
//set id, type into complete_status
set id, type, file("${id}_${type}_genome.fasta") into final_files
set id, type, val("${params.outdir}/${id}/genomes/${id}_${type}_genome.fasta") into final_files_plasmident
script:
data_source = longReadOnly ? "nanopore" : "hybrid"
"""
format_output.py ${contigs} ${id} ${type} ${params.minContigLength} ${data_source}
"""
}
process multiqc {
// Generate summary report
publishDir "${params.outdir}/MultiQC", mode: 'copy'
input:
file multiqc_config from ch_multiqc_config
file ('fastqc/*') from fastqc_results.collect().ifEmpty([])
file ('software_versions/*') from software_versions_yaml.collect()
file ('*/report.tsv') from quast_results.collect().ifEmpty([])
file workflow_summary from create_workflow_summary(summary)
output:
file "*multiqc_report.html" into multiqc_report
file "*_data"
file "multiqc_plots"
script:
rtitle = custom_runName ? "--title \"$custom_runName\"" : ''
rfilename = custom_runName ? "--filename " + custom_runName.replaceAll('\\W','_').replaceAll('_+','_') + "_multiqc_report" : ''
"""
multiqc -f $rtitle $rfilename --config $multiqc_config .
"""
}
process output_documentation {
publishDir "${params.outdir}/pipeline_info", mode: 'copy'
input:
file output_docs from ch_output_docs
output:
file "results_description.html"
script:
"""
markdown_to_html.r $output_docs results_description.html
"""
}
/*
* Input file handling functions
*/
def isMode(it) {
// returns whether a given list of arguments contains at least one valid mode
it.any {modes.contains(it)}
}
def returnFile(it) {
// Return file if it exists
inputFile = file(it)
if (!file(inputFile).exists()) exit 1, "The following file from the TSV file was not found: ${inputFile}, see --help for more information"
return inputFile
}
def extractFastq(tsvFile) {
// Extracts Read Files from TSV
Channel.from(tsvFile)
.ifEmpty {exit 1, log.info "Cannot find path file ${tsvFile}"}
.splitCsv(sep:'\t')
.map { row ->
if (longReadOnly) {
// long read only
def id = row[0]
def lr = returnFile(row[1])
[id, lr, "", ""]
} else {
// hybrid assembly
def id = row[0]
def sr1 = returnFile(row[2])
def sr2 = returnFile(row[3])
def lr = returnFile(row[1])
[id, lr, sr1, sr2]
}
}
}
def checkLongReadOnly(tsvFile) {
// Checks if tsv files contains only longreads or lr + illumina
row = tsvFile.readLines().get(0)
ncol = row.split('\t').size()
if (ncol < 3) {
true
} else {
false
}
}
/*
* Completion e-mail notification
*/
workflow.onComplete {
// Set up the e-mail variables
def subject = "[nf-core/denovohybrid] Successful: $workflow.runName"
if(!workflow.success){
subject = "[nf-core/denovohybrid] FAILED: $workflow.runName"
}
def email_fields = [:]
email_fields['version'] = workflow.manifest.version
email_fields['runName'] = custom_runName ?: workflow.runName
email_fields['success'] = workflow.success
email_fields['dateComplete'] = workflow.complete
email_fields['duration'] = workflow.duration
email_fields['exitStatus'] = workflow.exitStatus
email_fields['errorMessage'] = (workflow.errorMessage ?: 'None')
email_fields['errorReport'] = (workflow.errorReport ?: 'None')
email_fields['commandLine'] = workflow.commandLine
email_fields['projectDir'] = workflow.projectDir
email_fields['summary'] = summary
email_fields['summary']['Date Started'] = workflow.start
email_fields['summary']['Date Completed'] = workflow.complete
email_fields['summary']['Pipeline script file path'] = workflow.scriptFile
email_fields['summary']['Pipeline script hash ID'] = workflow.scriptId
if(workflow.repository) email_fields['summary']['Pipeline repository Git URL'] = workflow.repository
if(workflow.commitId) email_fields['summary']['Pipeline repository Git Commit'] = workflow.commitId
if(workflow.revision) email_fields['summary']['Pipeline Git branch/tag'] = workflow.revision
if(workflow.container) email_fields['summary']['Docker image'] = workflow.container
email_fields['summary']['Nextflow Version'] = workflow.nextflow.version
email_fields['summary']['Nextflow Build'] = workflow.nextflow.build
email_fields['summary']['Nextflow Compile Timestamp'] = workflow.nextflow.timestamp
// On success try attach the multiqc report
def mqc_report = null
try {
if (workflow.success) {
mqc_report = multiqc_report.getVal()
if (mqc_report.getClass() == ArrayList){
log.warn "[nf-core/denovohybrid] Found multiple reports from process 'multiqc', will use only one"
mqc_report = mqc_report[0]
}
}
} catch (all) {
log.warn "[nf-core/denovohybrid] Could not attach MultiQC report to summary email"
}
// Render the TXT template
def engine = new groovy.text.GStringTemplateEngine()
def tf = new File("$baseDir/assets/email_template.txt")
def txt_template = engine.createTemplate(tf).make(email_fields)
def email_txt = txt_template.toString()
// Render the HTML template
def hf = new File("$baseDir/assets/email_template.html")
def html_template = engine.createTemplate(hf).make(email_fields)
def email_html = html_template.toString()
// Render the sendmail template
def smail_fields = [ email: params.email, subject: subject, email_txt: email_txt, email_html: email_html, baseDir: "$baseDir", mqcFile: mqc_report, mqcMaxSize: params.maxMultiqcEmailFileSize.toBytes() ]
def sf = new File("$baseDir/assets/sendmail_template.txt")
def sendmail_template = engine.createTemplate(sf).make(smail_fields)
def sendmail_html = sendmail_template.toString()
// Send the HTML e-mail
if (params.email) {
try {
if( params.plaintext_email ){ throw GroovyException('Send plaintext e-mail, not HTML') }
// Try to send HTML e-mail using sendmail
[ 'sendmail', '-t' ].execute() << sendmail_html
log.info "[nf-core/denovohybrid] Sent summary e-mail to $params.email (sendmail)"
} catch (all) {
// Catch failures and try with plaintext
[ 'mail', '-s', subject, params.email ].execute() << email_txt
log.info "[nf-core/denovohybrid] Sent summary e-mail to $params.email (mail)"
}
}
// Write summary e-mail HTML to a file
def output_d = new File( "${params.outdir}/pipeline_info/" )
if( !output_d.exists() ) {
output_d.mkdirs()
}
def output_hf = new File( output_d, "pipeline_report.html" )
output_hf.withWriter { w -> w << email_html }
def output_tf = new File( output_d, "pipeline_report.txt" )
output_tf.withWriter { w -> w << email_txt }
c_reset = params.monochrome_logs ? '' : "\033[0m";
c_purple = params.monochrome_logs ? '' : "\033[0;35m";
c_green = params.monochrome_logs ? '' : "\033[0;32m";
c_red = params.monochrome_logs ? '' : "\033[0;31m";
if (workflow.stats.ignoredCountFmt > 0 && workflow.success) {
log.info "${c_purple}Warning, pipeline completed, but with errored process(es) ${c_reset}"
log.info "${c_red}Number of ignored errored process(es) : ${workflow.stats.ignoredCountFmt} ${c_reset}"
log.info "${c_green}Number of successfully ran process(es) : ${workflow.stats.succeedCountFmt} ${c_reset}"
}
if(workflow.success){
log.info "${c_purple}[nf-core/denovohybrid]${c_green} Pipeline completed successfully${c_reset}"
} else {
checkHostname()
log.info "${c_purple}[nf-core/denovohybrid]${c_red} Pipeline completed with errors${c_reset}"
}
}
def nfcoreHeader(){
// Log colors ANSI codes
c_reset = params.monochrome_logs ? '' : "\033[0m";
c_dim = params.monochrome_logs ? '' : "\033[2m";
c_black = params.monochrome_logs ? '' : "\033[0;30m";
c_green = params.monochrome_logs ? '' : "\033[0;32m";
c_yellow = params.monochrome_logs ? '' : "\033[0;33m";
c_blue = params.monochrome_logs ? '' : "\033[0;34m";
c_purple = params.monochrome_logs ? '' : "\033[0;35m";
c_cyan = params.monochrome_logs ? '' : "\033[0;36m";
c_white = params.monochrome_logs ? '' : "\033[0;37m";
return """ ${c_dim}----------------------------------------------------${c_reset}
${c_green},--.${c_black}/${c_green},-.${c_reset}
${c_blue} ___ __ __ __ ___ ${c_green}/,-._.--~\'${c_reset}
${c_blue} |\\ | |__ __ / ` / \\ |__) |__ ${c_yellow}} {${c_reset}
${c_blue} | \\| | \\__, \\__/ | \\ |___ ${c_green}\\`-._,-`-,${c_reset}
${c_green}`._,._,\'${c_reset}
${c_purple} nf-core/denovohybrid v${workflow.manifest.version}${c_reset}
${c_dim}----------------------------------------------------${c_reset}
""".stripIndent()
}
def checkHostname(){
def c_reset = params.monochrome_logs ? '' : "\033[0m"
def c_white = params.monochrome_logs ? '' : "\033[0;37m"
def c_red = params.monochrome_logs ? '' : "\033[1;91m"
def c_yellow_bold = params.monochrome_logs ? '' : "\033[1;93m"
if(params.hostnames){
def hostname = "hostname".execute().text.trim()
params.hostnames.each { prof, hnames ->
hnames.each { hname ->
if(hostname.contains(hname) && !workflow.profile.contains(prof)){
log.error "====================================================\n" +
" ${c_red}WARNING!${c_reset} You are running with `-profile $workflow.profile`\n" +
" but your machine hostname is ${c_white}'$hostname'${c_reset}\n" +
" ${c_yellow_bold}It's highly recommended that you use `-profile $prof${c_reset}`\n" +
"============================================================"
}
}
}
}
}