Repository navigation
Expand file tree
/
Copy pathRepeatMasker_Nextflow.nf
More file actions
executable file
·428 lines (351 loc) · 13.3 KB
/
Copy pathRepeatMasker_Nextflow.nf
File metadata and controls
executable file
·428 lines (351 loc) · 13.3 KB
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
#!/usr/bin/env nextflow
/*
vim: syntax=groovy
RepeatMasker_Nextflow : Run RepeatMasker on a cluster using Nextflow (DSL2)
Parameters:
Required:
- profile : Which profile to use from the config
--inputSequence : FASTA file optionally compressed with gzip.
--assembly : Metadata value
--species : Dfam species library ( or use inputLibrary for custom lib )
--inputLibrary : Uncompressed FASTA file containing consensi. ( or use species )
Optional:
--nolow : Use RepeatMasker '-nolow' option. Not recommended under normal
circumstances. Gives a major boost to false positives.
--xsmall : Use RepeatMasker '-xsmall' option.
--s : Use RepeatMasker -s option -- not a big impact for RMBlast.
--engine : Specify engine to use [ default: rmblast ]
--batchSize : Size of each cluster job in bp [ default: 50mb ]
--repbase_ver : Metadata value
Examples:
NOTE: On some clusters it will be necessary to use full paths to
all files specified as parameters.
o Run with standard libraries and a specified species:
nextflow run /path/RepeatMasker_Nextflow.nf \
--inputSequence /full_path_required/GCA_003113815.1.fna.gz \
--species "human" \
--cluster nocona
o Run with a custom library:
nextflow run /path/RepeatMasker_Nextflow.nf \
--inputSequence /full_path_required/GCA_003113815.1.fna.gz \
--inputLibrary /full_path_required/GCA_003113815.1-consensi.fa \
--cluster griz
Robert Hubley, 2020-2025
*/
//////////////////////////////////////////////////////////////////////////////////////////////////////
/////// CUSTOMIZE CLUSTER ENVIRONMENT HERE BY ADDING YOUR OWN PROFILE TO nextflow.config
/////// USE '-profile local' TO RUN ON THE CURRENT MACHINE
//////////////////////////////////////////////////////////////////////////////////////////////////////
process generate_metadata {
publishDir path: "${outputDir}/${assembly}", mode: 'copy', saveAs: { f ->
def fname = f.toString().split('/').last()
if (fname.endsWith("run_data.json")) {
return "run_data.json"
}
return fname
}
input:
path metadataScript
path outputDir
val assembly
val repbase_ver
val algorithm
val otherOptions
val key
val lib
path libOpt
// this needs to be here to ensure that the library file is accessible in the work dir
output:
path "${assembly}_${algorithm}-run_data.json"
script:
"""
python3 ${metadataScript} -a ${assembly} -${key} -r ${repbase_ver} -d ${params.repeatMaskerDir} -g ${algorithm} -c "${otherOptions} ${lib}"
"""
}
process warmupRepeatMasker {
input:
path small_seq
val repeatMaskerDir
val otherOptions
val species
output:
val true
script:
"""
#
# Run RepeatMasker with "-species" option on a small sequence in order to
# force it to initialize the cached libraries. Do not want to do this on the
# cluster ( in parallel ) as it may cause each job to attempt the build at once.
#
# hostname > node
${repeatMaskerDir}/RepeatMasker ${otherOptions} ${species} ${small_seq.baseName}.fa >& ${small_seq.baseName}.rmlog
"""
}
process genTwoBitFile {
input:
path inSeqFile
val ucscToolsDir
output:
path '*.2bit'
script:
"""
# Generate 2bit files if necessary
if [ ${inSeqFile.extension} == "gz" ]; then
gunzip -c ${inSeqFile} | ${ucscToolsDir}/faToTwoBit -long stdin ${inSeqFile.baseName}.2bit
elif [ ${inSeqFile.extension} == "2bit" ]; then
# renaming the link includes it in the output. Nextflow seems to exclude inputs from the blobbed output
mv ${inSeqFile} processed.${inSeqFile}
else
${ucscToolsDir}/faToTwoBit -long ${inSeqFile} processed.${inSeqFile.baseName}.2bit
fi
"""
}
process genBatches {
input:
path twoBitFile
val batchSize
val ucscToolsDir
path genBEDBatches
output:
path 'batch*.bed'
script:
"""
# This can magically accept FASTA, Gzip'd FASTA, or 2BIT...but 2Bit is prob. fastest
export UCSCTOOLSDIR=${ucscToolsDir}
perl ${genBEDBatches} ${twoBitFile} ${batchSize}
"""
}
process RepeatMasker {
input:
val warmupComplete
path batch_file
val lib
path libOpt
// this needs to be here to ensure that the library file is accessible in the work dir
val species
path inSeqTwoBitFile
val ucscToolsDir
val repeatMaskerDir
path adjCoordinates
val otherOptions
output:
tuple path("${batch_file.baseName}.fa.out"), path("${batch_file.baseName}.fa.align")
script:
"""
#
# Run RepeatMasker and readjust coordinates
#
${ucscToolsDir}/twoBitToFa -bed=${batch_file} ${inSeqTwoBitFile} ${batch_file.baseName}.fa
${repeatMaskerDir}/RepeatMasker -a ${otherOptions} ${lib} ${species} ${batch_file.baseName}.fa >& ${batch_file.baseName}.rmlog
touch ${batch_file.baseName}.fa.align
export REPEATMASKER_DIR=${repeatMaskerDir}
perl ${adjCoordinates} ${batch_file} ${batch_file.baseName}.fa.out
perl ${adjCoordinates} ${batch_file} ${batch_file.baseName}.fa.align
cp ${batch_file.baseName}.fa.out ${batch_file.baseName}.fa.out.unadjusted
mv ${batch_file.baseName}.fa.out.adjusted ${batch_file.baseName}.fa.out
mv ${batch_file.baseName}.fa.align.adjusted ${batch_file.baseName}.fa.align
"""
}
process combineRMOUTOutput {
publishDir path: "${outputDir}/${params.assembly}", mode: 'copy', saveAs: { f ->
def fname = f instanceof java.nio.file.Path ? f.getFileName().toString() : f.toString().split('/').last()
def base = file(twoBitFile).baseName
if (fname.endsWith(".rmout.gz")) {
return "${base}.out.gz"
}
if (fname == "combOutSorted-translation.tsv") {
return null
}
return fname
}
input:
tuple path(combinedFile), path(twoBitFile), path(outputDir), val(ucscToolsDir), val(repeatMaskerDir)
output:
tuple path('*.rmout.gz'), path('*.summary'), path('combOutSorted-translation.tsv')
script:
"""
echo " SW perc perc perc query position in query matching repeat position in repeat" > combOutSorted
echo "score div. del. ins. sequence begin end (left) repeat class/family begin end (left) ID" >> combOutSorted
grep -v -e "^\$" ${combinedFile} | sort -k5,5 -k6,6n -T ${workflow.workDir} >> combOutSorted
${workflow.projectDir}/renumberIDs.pl combOutSorted > combOutSortedRenumbered
mv translation-out.tsv combOutSorted-translation.tsv
export PATH=${ucscToolsDir}:\$PATH
${repeatMaskerDir}/util/buildSummary.pl -genome ${twoBitFile} -useAbsoluteGenomeSize combOutSortedRenumbered > ${twoBitFile.baseName}.summary
gzip -c combOutSortedRenumbered > ${twoBitFile.baseName}.rmout.gz
"""
}
process combineRMAlignOutput {
publishDir path: "${outputDir}/${params.assembly}", mode: 'copy', saveAs: { f ->
def fname = f instanceof java.nio.file.Path ? f.getFileName().toString() : f.toString().split('/').last()
def base = file(twoBitFile).baseName
if (fname.endsWith('.rmalign.gz')) {
return "${base}.align.gz"
}
return fname
}
input:
path translationFile
path combinedFile
path twoBitFile
path outputDir
val ucscToolsDir
val repeatMaskerDir
output:
path '*.rmalign.gz'
script:
"""
####${workflow.projectDir}/alignToBed.pl -fullAlign ${combinedFile} | ${ucscToolsDir}/bedSort stdin stdout | ${workflow.projectDir}/bedToAlign.pl > combAlign-sorted
${workflow.projectDir}/alignToBed.pl -fullAlign ${combinedFile} > tmp.bed
# Be mindful of this buffer size...should probably make this a parameter
sort -k1,1V -k2,2n -k3,3nr -S 3G -T ${workflow.workDir} tmp.bed > tmp.bed.sorted
${workflow.projectDir}/bedToAlign.pl tmp.bed.sorted > combAlign-sorted
${workflow.projectDir}/renumberIDs.pl -translation ${translationFile} combAlign-sorted > combAlign-sorted-renumbered
gzip -c combAlign-sorted-renumbered > ${twoBitFile.baseName}.rmalign.gz
"""
}
workflow {
// Check Nextflow Version
if (!nextflow.version.matches('>=24.10')) {
println("This workflow requires Nextflow version 24.10 or higher -- You are running version ${nextflow.version}")
exit(1)
}
version = "3.0"
// meta params
def assembly = params.assembly ?: null
def repbase_ver = params.repbase_ver ?: 'null'
if (!assembly) {
error("Please provide an assembly accession with --assembly for this run.")
}
// HPC Parameters
def max_cpus = params.cpus ?: 12
if (max_cpus < 2 ) {
log.warn "Requested CPUs (${max_cpus}) < 2; forcing to 2 so RepeatMasker can use -pa 1 safely."
max_cpus = 2
}
def inputSequence = params.inputSequence ?: null
def outputDir = params.outputDir ?: workflow.launchDir
// def thisExecutor = params.thisExecutor
def thisQueue = params.thisQueue
def ucscToolsDir = params.ucscToolsDir
def repeatMaskerDir = params.repeatMaskerDir
def batchSize = params.batchSize ?: 50000000
// process params TODO resolve this
def libOpt = null
def species = params.species ?: ''
def inputLibrary = params.inputLibrary ?: null
if (species && !inputLibrary) {
species = "-species '" + species + "'"
}
else if (inputLibrary && !species) {
libOpt = file(inputLibrary)
}
else if (inputLibrary && species) {
error("The --species and --inputLibrary parameters are mutually exclusive")
}
else if (!inputLibrary && !species) {
error("Either --species or --inputLibrary are required")
}
def lib = ''
if (libOpt) {
lib = '-lib ' + libOpt.name
libOpt = Channel.value(libOpt)
}
else {
libOpt = Channel.value([])
}
String engine = params.engine ?: 'rmblast'
int aligner_threads
switch (engine) {
case 'hmmer':
aligner_threads = 2
break
case 'crossmatch':
aligner_threads = 1
break
case 'rmblast':
aligner_threads = 4
break
default:
error("Could not identify search engine ${engine}!")
break
}
// Choose -pa so that (aligner_threads * pa) + 1 <= max_cpus
int pa = (int) ((max_cpus - 1).intdiv(aligner_threads))
if (pa < 1 ) pa = 1
def otherOptions = " -engine ${engine} -pa ${pa}"
def nolow = params.nolow ?: null
if (nolow != null) {
otherOptions += " -nolow"
}
def s = params.s ?: null
if (s != null) {
otherOptions += " -s"
}
def xsmall = params.xsmall ?: null
if (xsmall != null) {
otherOptions += " -xsmall"
}
// Print out the configuration
log.info("RepeatMasker_Nextflow : RepeatMasker Cluster Runner ver " + version)
log.info("====================================================================")
log.info("working directory : " + workflow.workDir)
log.info("RepeatMaskerDir : " + repeatMaskerDir)
log.info("UCSCToolsDir : " + ucscToolsDir)
log.info("Output Directory : " + outputDir)
log.info("Cluster : " + workflow.profile)
log.info("Queue/Partititon : " + thisQueue)
log.info("Batch size : " + batchSize)
log.info("Max cpus per task : " + max_cpus)
log.info("RepeatMasker Options: " + otherOptions)
log.info("Input Sequence : " + inputSequence)
if (inputLibrary != null) {
log.info("Library File : " + inputLibrary)
}
if (params.species != null) {
log.info("Species : " + species)
}
//log.info("CPUs Per Task : " + proc)
log.info("\n")
def algorithm = params.engine ?: "rmblast"
def metadataFile = file("${workflow.projectDir}/gen_run_metadata.py")
def key = species ?: lib
generate_metadata(metadataFile, outputDir, assembly, repbase_ver, algorithm, otherOptions, key, lib, libOpt)
def small_seq = file("${workflow.projectDir}/sample/small-seq.fa")
warmupComplete = warmupRepeatMasker(small_seq, repeatMaskerDir, otherOptions, species)
twoBitFile = genTwoBitFile(inputSequence, ucscToolsDir)
def genBEDBatches = file("${workflow.projectDir}/genBEDBatches.pl")
batchChan = genBatches(twoBitFile, batchSize, ucscToolsDir, genBEDBatches) | flatten
def adjCoordinates = file("${workflow.projectDir}/adjCoordinates.pl")
rmskResults = RepeatMasker(warmupComplete, batchChan, lib, libOpt, species, twoBitFile, ucscToolsDir, repeatMaskerDir, adjCoordinates, otherOptions) | flatten
rmskResults
.branch {
rmskAlignChan: it.name.contains(".align")
rmskOutChan: it.name.contains(".out")
}
.set { rmskBranchedResults }
def outputDirCh = Channel.value(outputDir)
def ucscToolsDirCh = Channel.value(ucscToolsDir)
def repeatMaskerDirCh = Channel.value(repeatMaskerDir)
translationFile = rmskBranchedResults.rmskOutChan
| collectFile(name: "combOut")
| combine(twoBitFile)
| combine(outputDirCh)
| combine(ucscToolsDirCh)
| combine(repeatMaskerDirCh)
| combineRMOUTOutput
| first
| map { v -> v[2] }
combAlignFile = rmskBranchedResults.rmskAlignChan
| collectFile(name: "combAlign")
combineRMAlignOutput(translationFile, combAlignFile, twoBitFile, outputDir, ucscToolsDir, repeatMaskerDir)
workflow.onComplete = {
log.info("Pipeline execution summary")
log.info("---------------------------")
log.info("Completed at : ${workflow.complete}")
log.info("Duration : ${workflow.duration}")
log.info("Success : ${workflow.success}")
log.info("workDir : ${workflow.workDir}")
log.info("exit status : ${workflow.exitStatus}")
log.info("Error report : ${workflow.errorReport ?: '-'}")
}
}