-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmain.nf
More file actions
661 lines (609 loc) · 21.1 KB
/
main.nf
File metadata and controls
661 lines (609 loc) · 21.1 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
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
nextflow.enable.dsl=2
import groovy.json.JsonSlurper
// Load .json file into object
def loadJson(json) {
def jsonSlurper = new JsonSlurper()
return jsonSlurper.parse( json )
}
// Create a 'file()' from string 'path'
// 'path' could be null, a s3 URL, an absolute file-path or relative to 'baseDir'
def expandPath(path, baseDir) {
if (path == null) { return null}
if (path =~ /^s3/) { return file(path)}
return baseDir.resolve(path)
}
// Return 0 for null or non-integer strings
def toIntOr0(str) {
if ((str != null) && str.isInteger())
return str as int;
else
return 0
}
// Reference genome files and parameters
// Paths can be absolute or relative to location of json
def loadGenome(json) {
def baseDir = json.getParent()
genome = loadJson(json)
genome.bowtie_index = expandPath(genome.bowtie_index, baseDir)
genome.gtf = expandPath(genome.gtf, baseDir)
genome.tss = expandPath(genome.tss, baseDir)
return genome
}
// Load per-sample read-counts from bcParser output
def loadDemuxReadCounts(demuxMetrics) {
def jsonSlurper = new JsonSlurper()
def counts = []
json = jsonSlurper.parse(demuxMetrics)
for (sample in json["samples"]) {
counts.add(tuple(sample.value["name"], sample.value["reads"][0]))
}
return counts
}
def throwError(errMessage) {
log.error errMessage
sleep(200)
System.exit(1)
}
/*
Ensures that FASTQS for each lane of each sample in the @fqFilesChannel
have four labelled R1, R2, I1 and I2
*/
def validateFastqs(fqFilesChannel) {
def fastqRegexes = [/_R1/, /_R2/, /_I1/, /_I2/]
filesGroupedBySampleAndName = fqFilesChannel.map { sampleName, sampleFileList ->
readNumberRegex = /_[RI][1-2]/
[sampleName, sampleFileList.groupBy({x ->
def y = x.getName().toString().tokenize('_')
def name = x.getName().toString()
def match = (name =~ readNumberRegex)
if (match.find()) {
return name.replace(match.group(0), "<readNumber>")
} else {
throwError("FASTQ: '${name}' doesn't contain a readNumber specifying it as a read or index:\n Must contain one of: ${fastqRegexes}")
}
})]
}
filesGroupedBySampleAndName.map({ sampleName, fileNameHashMap ->
def keys = fileNameHashMap.keySet()
for (name in keys) {
fastqs = fileNameHashMap.get(name)
for (pattern in fastqRegexes) {
requiredFile = fastqs.findAll { it.getBaseName() =~ pattern }
readType = pattern.replace("_","")
if ( requiredFile.size == 0 ) {
throwError("Sample '${sampleName}' is missing FASTQ with readNumber ${readType} for FASTQs following pattern:\n ${name}")
} else if (requiredFile.size > 1) {
throwError("Sample '${sampleName}' has more than one FASTQ specified of type ${readType} for group following pattern ${name}")
}
}
}
})
}
/*
Ensures each row in params.samples(@sampleCsvRows) contains valid
values for both required and optional columns
*/
def validateSamples(sampleCsvRows) {
def requiredColumns = ['sample','libName']
def optionalNaturalNumberColumns = ['expectedCells', 'subsample']
sampleCsvRows.map{ csvRow ->
sampleName = csvRow.get('sample', "unknown")
for (column in requiredColumns) {
def val = csvRow.get(column)
def regexPattern = /[0-9a-zA-Z][0-9a-zA-Z\-\.]*/
if (val == null) {
throwError("Required column '${column}' missing from specified samples table: ${params.samples}")
} else if (!val.matches(regexPattern)) {
throwError("Invalid value specified for sample '${sampleName}' in column '${column}': `${val}`\nIn samples csv: ${params.samples}\nValues in the `${column}` column must:\n- Begin with an alphanumeric character\n- Consist of only alphanumeric and the following special characters: '-' '.'")
}
}
for (column in optionalNaturalNumberColumns) {
def val = csvRow.get(column)
// Allow 0 or '' to indicate 'default'
def regexPattern = /[0-9]*/
if (val != null && !val.matches(regexPattern)) {
throwError("Invalid value specified for sample `${sampleName}` in column `${column}`: `${val}`\n- Must be an integer >= 0")
}
}
}
}
// Prepare samples.csv with defaults, rename legacy columns, etc.
process regularizeSamplesCsv {
input:
path("samples.in.csv")
output:
path("samples.csv")
publishDir "${params.outDir}", mode: 'copy'
label 'small'
"""
regularizeSamplesCsv.py samples.in.csv > samples.csv
"""
}
// Create a bcl-convert samplessheet for 'fastq_samples' in samples.json
process makeBclConvertSamplesheet {
input:
path(samplesCsv)
path(libStructDir) // Directory containing the library type definition file (barcode sequence lists are loaded from here)
val(libStructJson) // Filename of the library definition .json
path(runinfo)
output:
path("samplesheet.csv")
publishDir "${params.outDir}/fastq", mode: 'copy'
label 'small'
script:
libStruct = "$libStructDir/$libStructJson"
"""
bclConvertSheet.py $samplesCsv $libStruct $runinfo > samplesheet.csv
"""
}
// Make TSS Regions BED from gene annoation (GTF) if not already provided as input
process makeTssRegions {
input: path(gtf)
output: path("*.bed")
label 'small'
"""
tss_regions.py $gtf
"""
}
/*Run bcl-convert, used when starting from a sequencing run-folder
Requires a separate bcl-convert samplesheet*/
process bclconvert {
input:
path(run)
path(samplesheet)
output:
path("fastq/*fastq.gz"), emit: fastq
path("fastq/Reports"), emit: stats
publishDir "${params.outDir}/", pattern: 'fastq/Reports/*', mode: 'copy'
publishDir "${params.outDir}/", pattern: 'fastq/*.fastq.gz'
script:
pthreads = ((task.cpus-4)/3).round()
"""
bcl-convert --sample-sheet $samplesheet --bcl-num-conversion-threads $pthreads --bcl-num-compression-threads $pthreads --bcl-num-decompression-threads $pthreads --bcl-input-directory $run --output-directory fastq
"""
}
/*Remove adapter sequences from ends of reads
Run for fastq input only; otherwise adapters should be removed during bcl-convert*/
process trimFq {
input:
path(fastq)
output:
path("trimmed/${basename}.fastq.gz"), emit: fastq
path("trimmed/${basename}.trim_stats"), emit: stats
tag "$basename"
script:
basename = fastq.getSimpleName()
"""
mkdir trimmed
cutadapt -j${task.cpus} -a ${params.adapter} -o trimmed/${basename}.fastq.gz $fastq > trimmed/${basename}.trim_stats
"""
}
// Run fastQC on input files inputs or from bcl-convert outputs)
// Note that these are the input fastq files, not outputs of bcParser
process fastqc {
input:
path(fq)
output:
path("fastqc/*.html"), emit: html
path("fastqc/*.zip"), emit: zip
label 'small'
"""
mkdir fastqc
fastqc -o fastqc $fq
"""
}
// Use multiQC to report a single QC report for all fastQC and bcl-convert reports
process multiqc {
input:
path(reports)
output:
path("multiqc_report.html")
publishDir "${params.outDir}/fastq", mode: 'copy'
label 'small'
"""
multiqc .
"""
}
// Run bcParser to extract and correct cell-barcodes
// Optionally demuxes fastq files based on some barcodes
process barcodeDemux {
input:
path(sheet) // Samplesheet json
path(libStructDir) // Directory containing the library type definition file (barcode sequence lists are loaded from here)
val(libStructJson) // Filename of the library definition .json
tuple(val(libName), path(fqFiles)) // Input fastq file
output:
tuple(val(libName), path("$outDir/*_S[1-9]*.fastq.gz"), emit: fastq)
path("$outDir/*_S0_*.fastq.gz"), emit: unknown optional true
path("$outDir/*.tsv")
tuple(val(libName), path("$outDir/metrics.json"), emit: metrics)
publishDir "${params.outDir}/demux/", pattern: "$outDir/*gz"
publishDir "${params.outDir}/demux/", mode: 'copy', pattern: "$outDir/*{txt,tsv,json}" //, saveAs: {"${libName}.${it.getName()}"}
tag "$libName"
script:
outDir = "${libName}.demux"
libStruct = "$libStructDir/$libStructJson"
"""
bc_parser --lib-struct $libStruct --demux $sheet --lib-name $libName -v --reads ${fqFiles.join(" ")} --write-fastq --out $outDir
"""
}
// bowtie2 alignment to the genome
process align {
input:
path(indexDir) // Bowtie2 index directory
val(indexName) // Base-name of the bowtie2 index
tuple(val(sample), path(reads)) // Input reads (fastq)
output:
tuple(val(sample), path("${sample}.bam"), emit: bam)
path("*.bam.csi")
path("*.log")
publishDir "$params.outDir/align", pattern: '*bam*'
publishDir "$params.outDir/align", pattern: '*.log', mode:'copy'
tag "$sample"
script:
index = "$indexDir/$indexName"
athreads = task.cpus - 1
sthreads = 4
"""
bowtie2 -p $athreads -x $index -1 ${reads[0]} -2 ${reads[1]} 2> ${sample}.log | samtools view -b | samtools sort --threads ${sthreads} --write-index -o ${sample}.bam
"""
}
// Subsample per-sample BAM files to a fixed depth
process subsampleBam {
input:
tuple(val(sample), path(bam), val(sampleReadCount), val(targetReadCount))
output:
tuple(val(sample), path(outFn))
publishDir "$params.outDir/align/subsample", pattern: '*bam*'
tag "$sample"
script:
fraction = targetReadCount / sampleReadCount
if ((fraction) > 0 && (fraction < 1)) {
outFn = "${sample}.subsampled.bam"
"""
samtools view -b -s $fraction -o $outFn $bam
"""
} else { // Pass entire input bam through
outFn = bam
"""
echo "Taking all reads for $bam"
"""
}
}
// Run scDedup to remove duplicate reads based on cell-barcode and mapping position
// Also generates cell and fragment statistics
process dedup {
input:
tuple(val(sample), file(bam))
output:
tuple(val(sample), path("${sample}.dedup.bam"), emit: bam)
tuple(val(sample), path("${sample}.fragments.tsv.gz"), path("${sample}.fragments.tsv.gz.tbi"), emit: fragments)
tuple(val(sample), path("${sample}.cell_stats.tsv"), path("${sample}.dedup_stats.tsv"), path("${sample}.fragment_hist.tsv"), emit: stats)
publishDir "$params.outDir/align/dedup/", pattern: '*bam*'
publishDir "$params.outDir/align/", pattern: '*.fragments.tsv.*'
publishDir "$params.outDir/align/dedup/", pattern: '*.tsv', mode:'copy'
tag "$sample"
"""
sc_dedup $bam --barcode-input Qname --write-fragments --out-prefix $sample
samtools index ${sample}.dedup.bam &
tabix -p bed ${sample}.fragments.tsv.gz &
wait
"""
}
// Convert BAM to BED with one entry for each tagmentation event (read end)
// Includes unpaired reads
process tagSites {
input:
tuple(val(sample), file(bam))
output:
tuple(val(sample), path("${sample}.bed.gz"))
tag "$sample"
"""
bedtools bamtobed -i $bam -tag XC | gzip -c >${sample}.bed.gz
"""
}
// Per-sample de-novo peak calling from tagmentation events
process callPeaks {
input:
tuple(val(sample), file(tagSites))
output:
tuple(val(sample), path("*_peaks.narrowPeak"))
publishDir "$params.outDir/peaks", mode: 'copy'
tag "$sample"
"""
macs3 callpeak -t ${tagSites} -f BED --nomodel --shift -100 --extsize 200 --keep-dup all -n $sample
"""
}
// Cell X peak count matrix
// Either using sample-specific peak calls or pre-defined peak set
process countPeaks {
input:
tuple(val(sample), path(tagSites), path(peaks))
output:
tuple(val(sample), path("${sample}.counts"))
publishDir "$params.outDir/peaks", mode: 'copy'
tag "$sample"
"""
bedtools intersect -a <(gunzip -c $tagSites) -b $peaks -loj | sc_counter --out-dir ${sample}.counts
"""
}
// Cell X gene count matrix
// Based on window around all transcript 5' ends
process countTss {
input:
path(tss)
tuple(val(sample), path(tagSites))
output:
tuple(val(sample), path("${sample}.tss_counts"))
publishDir "$params.outDir/peaks", mode: 'copy'
tag "$sample"
"""
bedtools intersect -a <(gunzip -c $tagSites) -b $tss -loj | sc_counter --out-dir ${sample}.tss_counts
"""
}
/*
Generates:
- table for each sample denoting which cells have passed set qcFilters (qc.tsv)
- calculated thresholds for set filters (qc.json)
- figures displaying the number of cells filtered at each step (Figs)
*/
process cellFilter {
// dedup_stats & fragment_hist.tsv are not currently in use by atacQcFilter but are named as they are
// passed in the same channel cell_stats.tsv is received from (dedup.out.stats) may be used in future
input:
tuple(val(sample), val(expectedCells), path("${sample}.cell_stats.tsv"), path("dedup_stats.tsv"), path("fragment_hist.tsv"), path("*"))
val(qcParams)
output:
tuple(val(sample), path("QC/${sample}/${sample}_thresholds.json"), path("QC/${sample}/${sample}_QC.tsv"), emit: qcStats)
tuple(val(sample), path("QC/${sample}/fripKneePlot.png"), path("QC/${sample}/uniqueReadsKneePlot.png"), emit: qcFigs)
publishDir "$params.outDir", mode: 'copy'
tag "$sample"
script:
expectedCells ?= 0
"""
atacQcFilter.py --sample $sample --minUniqueReads $qcParams.minUniqueReads --expectedCells $expectedCells --background $qcParams.backgroundRatio --topPercentCells $qcParams.topPercentCells
"""
}
/*
Runs automated ArchR analysis for each sample
- path("*") captures thresholds.json which is emitted along with needed QC.tsv by the cellFilter process.
It is not needed for this process
*/
process archrAnalysis {
input:
tuple(val(sample), path("${sample}.fragments.tsv.gz"), path("${sample}.fragments.tsv.gz.tbi"), path("*"), path("QC.tsv"))
path(qcAndArchRParams)
output:
path("ArchR/${sample}")
publishDir "$params.outDir"
errorStrategy 'ignore'
if (workflow.profile == 'conda'){
if (params.archrCondaEnv != null) {
conda params.archrCondaEnv
} else {
throwError("In order to run archrAnalysis process with conda profile\na custom conda environment needs to be created and specified using the\n'archrCondaEnv' field in your params file. See the Dependencies section of README for more info or disable ArchR with --runArchR false")
}
}
tag "$sample"
script:
additionalArgs=""
// Use gtf and specified BSGenome
if (genome.BSGenome != null){
additionalArgs="$additionalArgs -g ${genome.gtf} -b ${genome.BSGenome}"
}
// Use Built in ArchRGenome && hasBuiltInGenome
else if (genome.archrAlias != null) {
additionalArgs="$additionalArgs -a $genome.archrAlias"
}
"""
ArchR_analysis.R -s '${genome.speciesName}' -f ${sample}.fragments.tsv.gz -sN $sample -o $sample -r ${genome.annotationConvention} -th ${task.cpus} $additionalArgs -qc QC.tsv -q $qcAndArchRParams
"""
}
process sampleReport {
input:
tuple(val(sample), path("metrics.json"), path("${sample}.cell_stats.tsv"), path("${sample}.dedup_stats.tsv"), path("${sample}.fragment_hist.tsv"), path("*"), path("${sample}_QC.json"), path("${sample}_QC.tsv"))
path(samplesheet)
path(libJson)
output:
path("reports/${sample}.report.html")
path("reports/${sample}.reportStatistics.tsv")
publishDir "$params.outDir", mode: 'copy'
errorStrategy 'ignore'
tag "$sample"
"""
generateReport.py --sample ${sample} --samplesheet ${samplesheet} --libStruct ${libJson}
"""
}
process libraryReport {
input:
tuple(val(libName), path(files))
path(samplesheet)
path(libJson)
output:
path("reports/${libName}.report.html")
publishDir "$params.outDir", mode: 'copy'
errorStrategy 'ignore'
tag "$libName"
"""
generateReport.py --libName ${libName} --samplesheet ${samplesheet} --libStruct ${libJson}
"""
}
//// Sub-Workflows
// Fastq generation, trimming, QC, barcode extraction and sample demux
workflow inputReads {
take:
samples // samples.csv parsed into a channel
samplesCsv // samples.csv file
libJson // library definition json
runDir // Path to sequencing run-folder (BCLs); empty if running from fastq input
fqDir // Path to directory with input fastqs; empty if running from BCL
main:
runInfo = runDir.map{it.resolve("RunInfo.xml")}
if (params.fastqSamplesheet == null) {
makeBclConvertSamplesheet(samplesCsv, libJson.getParent(), libJson.getName(), runInfo)
fqSheet = makeBclConvertSamplesheet.out
} else {
fqSheet = file(params.fastqSamplesheet)
}
bclconvert(runDir, fqSheet)
fqs = fqDir.flatMap{file(it).listFiles()}.filter{it.name =~ /.fastq.gz$/}
fqs.dump(tag:'fqs')
if (params.trimFastq) {
readFqs = fqs.filter { it.getBaseName() =~ /_R\d_/ }
indexFqs = fqs.filter { it.getBaseName() =~ /_I\d_/ }
trimFq(readFqs)
fqs = trimFq.out.fastq.mix(indexFqs)
}
fqs = bclconvert.out.fastq.flatten().mix(fqs)
// Organize fastq files by sample
fqs.dump(tag:'fqs2')
fqFiles = fqs.map { file ->
def ns = file.getName().toString().tokenize('_')
return tuple(ns.get(0), file)
}.groupTuple()
fqSamples = samples.map({it.libName}).unique().join(fqFiles)
validateFastqs(fqSamples)
fqSamples.dump(tag:'fqSamples')
// Process cell-barcodes and (optionally) split fastqs into samples based on tagmentation barcode
barcodeDemux(samplesCsv, libJson.getParent(), libJson.getName(), fqSamples)
demuxFqs = barcodeDemux.out.fastq.flatMap({it[1]}).map { file ->
def ns = file.getName().toString().tokenize('_')
return tuple(ns.get(0), file)
}.groupTuple(size:2)
demuxFqs.dump(tag:'demuxFqs')
if (params.fastqc) {
fastqc(demuxFqs.flatMap({it.get(1)}))
reports = fastqc.out.zip
if (runDir != null) {
reports = reports.mix(bclconvert.out.stats)
}
if (params.trimFastq) {
reports = reports.mix(trimFq.out.stats)
}
multiqc(reports.collect())
}
emit:
fqs = demuxFqs
metrics = barcodeDemux.out.metrics
}
// Alignments, fragments, peaks and quantification
workflow scATAC {
take:
samples
sampleFqs // Fastq files for each sample for all reads (including index reads)
demuxMetrics
tssBed
main:
align(genome.bowtie_index.getParent(), genome.bowtie_index.getName(), sampleFqs)
if (params.subsample) {
readCounts = demuxMetrics
.flatMap{loadDemuxReadCounts(it[1])}
.join(samples.map{[it.sample, toIntOr0(it.subsample)]})
readCounts.dump(tag:'readCounts')
subsampleBam(align.out.bam.combine( readCounts, by:0))
bams = subsampleBam.out
} else {
bams = align.out.bam
}
dedup(bams)
tagSites(dedup.out.bam)
if (params.peaks == null) {
callPeaks(tagSites.out)
peaks = callPeaks.out
} else {
peaks = samples.map{[it.sample, file(params.peaks)]}
}
peakInput = tagSites.out.join(peaks)
peakInput.dump(tag:'peakInput')
countPeaks(peakInput)
if (tssBed != null) {
tssBed.dump(tag:'tssBed')
countTss(tssBed, tagSites.out)
tssCounts = countTss.out
} else {
tssCounts = Channel.empty()
}
counts = countPeaks.out.join(tssCounts, remainder: true).map { [it[0], it[1..-1].findAll {it}] }
// Using cross instead of join to multimatch samples to their libName
// Only getting sampleName, libName and demuxPath using map
sampleDemuxMetrics = demuxMetrics.cross(samples.map{[it.libName,it.sample]}).map({[it[1][1], it[0][0], it[0][1]]})
sampleDemuxMetrics.dump(tag:'sampleDemuxMetrics')
emit:
sampleDemuxMetrics = sampleDemuxMetrics
sampleDedupMetrics = dedup.out.stats
counts = counts
fragments = dedup.out.fragments
}
// QC, reporting and preliminary analysis
workflow atacReport {
take:
samples
demuxMetrics
dedupMetrics
counts
fragments
samplesheet
libJson
main:
expectedCells = samples.map{[it.sample, toIntOr0(it.expectedCells)]}
qcAndArchRParams = Helper.loadYmlParams(file(params.qcAndArchRParams))
dedupStatsAndCounts = dedupMetrics.join(counts)
cellFilter(expectedCells.join(dedupStatsAndCounts), qcAndArchRParams)
canUseBuiltInGenome = (genome.archrAlias != null)
canUseCustomGenome = (genome.BSGenome != null)
if ( params.runArchR && (canUseBuiltInGenome || canUseCustomGenome)) {
archrAnalysis(fragments.join(cellFilter.out.qcStats), params.qcAndArchRParams)
}
if (params.generateReport) {
// Removing libName from demuxMetrics as not needed for cellFilter or sampleReport
demuxAndDedup = demuxMetrics.map({[it[0], it[2]]}).join(dedupMetrics)
allStats = demuxAndDedup.join(counts)
allStats.dump(tag:'allStats')
allStatsAndQC = allStats.join(cellFilter.out.qcStats)
sampleReport(allStatsAndQC, samplesheet, libJson)
// Creating a seperate channel from allStats since library-report only needs QC and demux metrics
multiReportData = demuxMetrics.join(cellFilter.out.qcStats)
// by:[1,2] where 1 and 2 are libName and demux metrics.json path respectively
// .map grouped into [libName, [all needed metrics files for all samples originating from this library]]
multiReportDataFormatted = multiReportData.groupTuple(by:[1,2]).map({[it[1], it[2..-1].flatten()]})
libraryReport(multiReportDataFormatted, samplesheet, libJson)
}
}
//// Main entry point
// Run the workflow for one or multiple samples
// either from one runFolder or one / multiple sets of fastq files
workflow {
Helper.initialise(workflow, params, log)
//// Inputs
regularizeSamplesCsv(file(params.samples))
samplesCsv = regularizeSamplesCsv.out
samples = samplesCsv.splitCsv(header:true, strip:true)
samples.dump(tag:'samples')
validateSamples(samples)
libJson = expandPath(params.libStructure, file("${projectDir}/references/"))
// Input reads from runfolder xor fastq directory
// runDir or fqDir can either be set as parameter or as a column in samples.csv
if (params.runFolder) {
runDir = Channel.fromPath(params.runFolder, checkIfExists:true)
fqDir = Channel.empty()
} else if (params.fastqDir) {
fqDir = Channel.fromPath(params.fastqDir, checkIfExists:true)
runDir = Channel.empty()
} else {
//todo should ensure only one of the two is set
runDir = samples.map{it.runFolder}.filter{it}.first().map{file(it,checkIfExists:true)}
fqDir = samples.map{it.runFolder}.filter{it}.first().map{file(it,checkIfExists:true)}
}
inputReads(samples, samplesCsv, libJson, runDir, fqDir)
// Reference Genome
genome = loadGenome(file(params.genome))
if ((genome.tss == null) && (genome.gtf != null)) {
makeTssRegions(genome.gtf)
tssBed = makeTssRegions.out
} else {
tssBed = genome.tss
}
//// scATAC Analysis and reporting
scATAC(samples, inputReads.out.fqs, inputReads.out.metrics, tssBed)
atacReport(samples, scATAC.out.sampleDemuxMetrics, scATAC.out.sampleDedupMetrics, scATAC.out.counts, scATAC.out.fragments, samplesCsv, libJson)
}