-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.nf
433 lines (321 loc) · 14.6 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
#!/usr/bin/env nextflow
sdrfFile = params.sdrf
resultsRoot = params.resultsRoot
referenceFasta = params.referenceFasta
transcriptToGene = params.transcriptToGene
transcriptomeIndex = params.transcriptomeIndex
protocol = params.protocol
experimentType = params.experimentType
manualDownloadFolder =''
if ( params.containsKey('manualDownloadFolder')){
manualDownloadFolder = params.manualDownloadFolder
}
fastqProviderConfig = ''
if ( params.containsKey('fastqProviderConfig')){
fastqProviderConfig = params.fastqProviderConfig
}
// Read ENA_RUN column from an SDRF
Channel
.fromPath(sdrfFile, checkIfExists: true)
.splitCsv(header:true, sep:"\t")
.filter{ row -> (! row.containsKey(params.fields.quality)) || ( row["${params.fields.quality}"].toLowerCase() != 'not ok') }
.into {
SDRF_FOR_FASTQS
SDRF_FOR_STRAND
SDRF_FOR_TECHREP
SDRF_FOR_COUNT
}
TRANSCRIPT_TO_GENE = Channel.fromPath( transcriptToGene, checkIfExists: true ).first()
// Read URIs from SDRF, generate target file names, and barcode locations
SDRF_FOR_FASTQS
.map{ row->
controlled_access='no'
if ( params.fields.containsKey('controlled_access')){
controlled_access=row["${params.fields.controlled_access}"]
}
tuple(row["${params.fields.run}"], row["${params.fields.cdna_uri}"], row["${params.fields.cell_barcode_uri}"], file(row["${params.fields.cdna_uri}"]).getName(), file(row["${params.fields.cell_barcode_uri}"]).getName(), row["${params.fields.cell_barcode_size}"], row["${params.fields.umi_barcode_size}"], row["${params.fields.end}"], row["${params.fields.cell_count}"], controlled_access)
}
.set { FASTQ_RUNS }
// Call the download script to retrieve run fastqs
process download_fastqs {
conda "${baseDir}/envs/atlas-fastq-provider.yml"
maxForks params.maxConcurrentDownloads
time { 10.hour * task.attempt }
memory { 20.GB * task.attempt }
errorStrategy { task.attempt<=10 & task.exitStatus != 4 ? 'retry' : 'finish' }
input:
set runId, cdnaFastqURI, barcodesFastqURI, cdnaFastqFile, barcodesFastqFile, val(barcodeLength), val(umiLength), val(end), val(cellCount), val(controlledAccess) from FASTQ_RUNS
output:
set val(runId), file("${cdnaFastqFile}"), file("${barcodesFastqFile}"), val(barcodeLength), val(umiLength), val(end), val(cellCount) into DOWNLOADED_FASTQS
"""
if ! [ -z "$ATLAS_TMPDIR" ]; then
TMPDIR=$ATLAS_TMPDIR;
else
echo "NOTE: ATLAS_TMPDIR not defined"
fi
if [ -n "$manualDownloadFolder" ] && [ -e $manualDownloadFolder/${cdnaFastqFile} ] && [ -e $manualDownloadFolder/${barcodesFastqFile} ]; then
ln -s $manualDownloadFolder/${cdnaFastqFile} ${cdnaFastqFile}
ln -s $manualDownloadFolder/${barcodesFastqFile} ${barcodesFastqFile}
elif [ -n "$manualDownloadFolder" ] && [ -e $manualDownloadFolder/${cdnaFastqFile} ] && [ ! -e $manualDownloadFolder/${barcodesFastqFile} ]; then
echo 'cDNA file $cdnaFastqFile is available locally, but barcodes file $barcodesFastqFile is not 1>&2
exit 2
elif [ -n "$manualDownloadFolder" ] && [ ! -e $manualDownloadFolder/${cdnaFastqFile} ] && [ -e $manualDownloadFolder/${barcodesFastqFile} ]; then
echo 'cDNA file $cdnaFastqFile is not available locally, but barcodes file $barcodesFastqFile is 1>&2
exit 3
elif [ "$controlledAccess" = 'yes' ]; then
echo "One or both of ${cdnaFastqFile}, ${barcodesFastqFile} are not available at $manualDownloadFolder/ for this controlled access experiment" 1>&2
exit 4
else
confPart=''
if [ -n "$fastqProviderConfig" ] && [ -e "$fastqProviderConfig" ]; then
confPart=" -c $fastqProviderConfig"
fi
# Stop fastq downloader from testing different methods -assume the control workflow has done that
export NOPROBE=1
fetchFastq.sh -f ${cdnaFastqURI} -t ${cdnaFastqFile} -m ${params.downloadMethod} \$confPart
# Allow for the first download also having produced the second output already
if [ ! -e ${barcodesFastqFile} ]; then
fetchFastq.sh -f ${barcodesFastqURI} -t ${barcodesFastqFile} -m ${params.downloadMethod} \$confPart
fi
fi
"""
}
// Group read files by run name, or by technical replicate group if specified
if ( params.fields.containsKey('techrep')){
// If technical replicates are present, create a channel containing that info
SDRF_FOR_TECHREP
.map{ row-> tuple(row["${params.fields.run}"], row["${params.fields.techrep}"]) }
.groupTuple()
.map{ row-> tuple( row[0], row[1][0]) }
.set{ TECHREPS }
// The target set of results will now be the technical replicate group number
SDRF_FOR_COUNT
.map{ row-> tuple(row["${params.fields.techrep}"]) }
.unique()
.count()
.set { TARGET_RESULT_COUNT }
// Now add the tech rep group to the run info, group by it, and create a
// tuple of files keyed by techrep group
TECHREPS.join( DOWNLOADED_FASTQS )
.groupTuple(by: 1)
.map{ row-> tuple( row[1], row[2].flatten(), row[3].flatten(), row[4][0], row[5][0], row[6][0], row[7][0]) }
.set{
FINAL_FASTQS
}
}else{
DOWNLOADED_FASTQS.set{ FINAL_FASTQS }
SDRF_FOR_COUNT
.map{ row-> tuple(row["${params.fields.run}"]) }
.unique()
.count()
.set { TARGET_RESULT_COUNT }
}
FINAL_FASTQS.into{
FINAL_FASTQS_FOR_CONFIG
FINAL_FASTQS_FOR_ALEVIN
}
// Derive Alevin barcodeconfig
process alevin_config {
input:
set val(runId), file("cdna*.fastq.gz"), file("barcodes*.fastq.gz"), val(barcodeLength), val(umiLength), val(end), val(cellCount) from FINAL_FASTQS_FOR_CONFIG
output:
set val(runId), stdout into ALEVIN_CONFIG
script:
def barcodeConfig = ''
if ( params.containsKey(protocol) ){
canonicalProtocol = params.get(protocol)
alevinType = canonicalProtocol.alevinType
// Non-standard barcode config is supplied as a custom method
if ( alevinType == 'custom' || "${canonicalProtocol.barcodeLength}" != barcodeLength || "${canonicalProtocol.umiLength}" != umiLength || "${canonicalProtocol.end}" != end ){
barcodeConfig = "--barcodeLength ${barcodeLength} --umiLength ${umiLength} --end ${end}"
}else{
barcodeConfig = "--$alevinType"
}
barcodeConfig = "-l ${canonicalProtocol.libType} $barcodeConfig"
}
"""
if [ -z "$barcodeConfig" ]; then
echo Input of $protocol results is misconfigured 1>&2
exit 1
fi
# Also check barcode read lengths and return non-0 if they're not what they should be
targetLen=\$(($umiLength + $barcodeLength))
barcodesGood=0
set +e
while read -r l; do
checkBarcodeRead.sh -r \$(readlink -f \$l) -b $barcodeLength -u $umiLength -n 1000000 1>&2
if [ \$? -ne 0 ]; then
barcodesGood=1
fi
done <<< "\$(ls barcodes*.fastq.gz)"
set -e
echo -n "$barcodeConfig"
exit \$barcodesGood
"""
}
// Run Alevin per row
// Implement alevin_fry
process alevin {
conda "${baseDir}/envs/alevin_fry.yml"
cache 'deep'
memory { 20.GB * task.attempt }
cpus 12
errorStrategy { task.exitStatus !=2 && (task.exitStatus == 130 || task.exitStatus == 137 || task.attempt < 3) ? 'retry' : 'ignore' }
maxRetries 10
input:
set val(runId), file("cdna*.fastq.gz"), file("barcodes*.fastq.gz"), val(barcodeLength), val(umiLength), val(end), val(cellCount), val(barcodeConfig) from FINAL_FASTQS_FOR_ALEVIN.join(ALEVIN_CONFIG)
file(transcriptToGene) from TRANSCRIPT_TO_GENE
output:
set val(runId), file("${runId}_ALEVIN_fry_quant") into ALEVIN_RESULTS
set val(runId), file("${runId}_ALEVIN_fry_map/aux_info/meta_info.json") into ALEVIN_STATS
script:
canonicalProtocol = params.get(protocol)
whitelist = canonicalProtocol.whitelist
"""
salmon alevin ${barcodeConfig} --sketch -1 \$(ls barcodes*.fastq.gz | tr '\\n' ' ') -2 \$(ls cdna*.fastq.gz | tr '\\n' ' ') \
-i ${transcriptomeIndex} -p ${task.cpus} -o ${runId}_ALEVIN_fry_map
if [ "${params.protocol}" = "10xv2" ]
then
alevin-fry generate-permit-list --input ${runId}_ALEVIN_fry_map -d fw --unfiltered-pl ${baseDir}/whitelist/737K-august-2016.txt --output-dir ${runId}_ALEVIN_fry_quant_tmp --min-reads 10
elif [ "${params.protocol}" = "10xv3" ]
then
alevin-fry generate-permit-list --input ${runId}_ALEVIN_fry_map -d fw --unfiltered-pl ${whitelist} --output-dir ${runId}_ALEVIN_fry_quant_tmp --min-reads 10
elif [ "${params.protocol}" = "10x5prime" ]
then
alevin-fry generate-permit-list --input ${runId}_ALEVIN_fry_map -d rc --output-dir ${runId}_ALEVIN_fry_quant_tmp --force-cells 100000 --min-reads 10
else
alevin-fry generate-permit-list --input ${runId}_ALEVIN_fry_map -d fw --output-dir ${runId}_ALEVIN_fry_quant_tmp --force-cells 100000 --min-reads 10
fi
alevin-fry collate -i ${runId}_ALEVIN_fry_quant_tmp -r ${runId}_ALEVIN_fry_map
alevin-fry quant -i ${runId}_ALEVIN_fry_quant_tmp -m ${transcriptToGene} -r cr-like-em -o ${runId}_ALEVIN_fry_quant_tmp --use-mtx
TOTAL=\$(grep "num_processed" ${runId}_ALEVIN_fry_map/aux_info/meta_info.json | awk '{split(\$0, array, ": "); print array[2]}'| sed 's/,//g')
MAPPED=\$(grep "num_mapped" ${runId}_ALEVIN_fry_map/aux_info/meta_info.json | awk '{split(\$0, array, ": "); print array[2]}'| sed 's/,//g')
min_mapping=\$(echo "scale=2;((\$MAPPED * 100) / \$TOTAL)"|bc)
if [ "\${min_mapping%.*}" -lt "${params.minMappingRate}" ]; then
echo "Minimum mapping rate (\$min_mapping) is less than the specified threshold of ${params.minMappingRate}" 1>&2
exit 1
fi
mv ${runId}_ALEVIN_fry_quant_tmp ${runId}_ALEVIN_fry_quant
"""
}
ALEVIN_RESULTS
.into{
ALEVIN_RESULTS_FOR_QC
ALEVIN_RESULTS_FOR_PROCESSING
ALEVIN_RESULTS_FOR_OUTPUT
}
// Convert Alevin output to MTX. There will be one of these for every run, or
// technical replicate group of runs
process alevin_to_mtx {
conda "${baseDir}/envs/parse_alevin_fry.yml"
memory { 10.GB * task.attempt }
errorStrategy { task.exitStatus == 130 || task.exitStatus == 137 ? 'retry' : 'finish' }
maxRetries 20
input:
set val(runId), file(alevinResult) from ALEVIN_RESULTS_FOR_PROCESSING
output:
set val(runId), file("counts_mtx") into ALEVIN_MTX
"""
alevinFryMtxTo10x.py --cell_prefix ${runId}- $alevinResult counts_mtx ${params.experimentType}
"""
}
ALEVIN_MTX
.into{
ALEVIN_MTX_FOR_QC
ALEVIN_MTX_FOR_EMPTYDROPS
ALEVIN_MTX_FOR_OUTPUT
}
// Make a diagnostic plot
ALEVIN_RESULTS_FOR_QC
.join(ALEVIN_MTX_FOR_QC)
.set{
ALEVIN_QC_INPUTS
}
process droplet_qc_plot{
conda "${baseDir}/envs/droplet-barcode.yml"
memory { 10.GB * task.attempt }
errorStrategy { task.exitStatus == 130 || task.exitStatus == 137 ? 'retry' : 'finish' }
maxRetries 20
input:
set val(runId), file(alevinResult), file(mtx) from ALEVIN_QC_INPUTS
output:
set val(runId), file("${runId}.png") into ALEVIN_QC_PLOTS
"""
dropletBarcodePlot.R --mtx-matrix counts_mtx/matrix.mtx --label $runId --output-plot ${runId}.png
"""
}
// Remove empty droplets from Alevin results
process remove_empty_drops {
conda "${baseDir}/envs/dropletutils.yml"
memory { 10.GB * task.attempt }
errorStrategy { task.exitStatus == 130 || task.exitStatus == 137 ? 'retry' : 'ignore' }
maxRetries 20
input:
set val(runId), file(countsMtx) from ALEVIN_MTX_FOR_EMPTYDROPS
output:
set val(runId), file('nonempty.rds') into NONEMPTY_RDS
"""
dropletutils-read-10x-counts.R -s counts_mtx -c TRUE -o matrix.rds
dropletutils-empty-drops.R -i matrix.rds --lower ${params.emptyDrops.lower} --niters ${params.emptyDrops.nIters} --filter-empty ${params.emptyDrops.filterEmpty} \
--filter-fdr ${params.emptyDrops.filterFdr} --ignore ${params.minCbFreq} -o nonempty.rds -t nonempty.txt
"""
}
// Convert R matrix object with filtered cells back to .mtx
process rds_to_mtx{
conda "${baseDir}/envs/dropletutils.yml"
memory { 10.GB * task.attempt }
errorStrategy { task.exitStatus == 130 || task.exitStatus == 137 ? 'retry' : 'finish' }
maxRetries 20
input:
set val(runId), file(rds) from NONEMPTY_RDS
output:
set val(runId), file("counts_mtx_nonempty") into NONEMPTY_MTX
"""
#!/usr/bin/env Rscript
suppressPackageStartupMessages(require(DropletUtils))
counts_sce <- readRDS('$rds')
write10xCounts(assays(counts_sce)[[1]], path = 'counts_mtx_nonempty', barcodes = colData(counts_sce)\$Barcode, gene.id = rownames(counts_sce))
"""
}
// Compile raw results with raw and emptyDrops-filtered MTX
ALEVIN_RESULTS_FOR_OUTPUT
.join(ALEVIN_MTX_FOR_OUTPUT)
.join(NONEMPTY_MTX)
.join(ALEVIN_QC_PLOTS)
.join(ALEVIN_STATS)
.set{ COMPILED_RESULTS }
process compile_results{
publishDir "$resultsRoot/alevin", mode: 'copy', overwrite: true
input:
set val(runId), file('raw_alevin'), file(countsMtx), file(countsMtxNonempty), file(qcPlot), file(stats_file) from COMPILED_RESULTS
output:
set val(runId), file("$runId") into RESULTS_FOR_COUNTING
"""
mkdir -p raw_alevin/alevin/mtx
cp -P $countsMtx $countsMtxNonempty raw_alevin/alevin/mtx
mkdir -p raw_alevin/alevin/qc
cp -P $qcPlot raw_alevin/alevin/qc
cp -P raw_alevin $runId
cp $stats_file $runId
"""
}
// Check the total number of runs we have
RESULTS_FOR_COUNTING
.count()
.set{ ALEVIN_RESULTS_COUNT }
process validate_results {
executor 'local'
input:
val(kallistoResultCount) from ALEVIN_RESULTS_COUNT
val(targetCount) from TARGET_RESULT_COUNT
output:
stdout DONE
"""
if [ "$kallistoResultCount" -ne "$targetCount" ]; then
echo "Alevin results count of $kallistoResultCount does not match expected results number ($targetCount)" 1>&2
exit 1
else
echo "Alevin results count of $kallistoResultCount matches expected results number ($targetCount)"
fi
"""
}