-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.nf
5094 lines (3764 loc) · 161 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
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
//// List of all processes in order
// ATAC_reads__merging_reads
// ATAC_reads__trimming_reads
// ATAC_reads__aligning_reads
// ATAC_reads__removing_low_quality_reads
// ATAC_reads__marking_duplicated_reads
// ATAC_reads__removing_duplicated_reads
// ATAC_reads__removing_reads_in_mitochondria_and_small_contigs
// ATAC_reads__converting_bam_to_bed_and_adjusting_for_Tn5
// ATAC_QC_reads__running_fastqc
// ATAC_QC_reads__computing_bigwig_tracks_and_plotting_coverage
// ATAC_QC_reads__computing_and_plotting_bigwig_tracks_correlations
// ATAC_QC_reads__plotting_insert_size_distribution
// ATAC_QC_reads__sampling_aligned_reads
// ATAC_QC_reads__measuring_overlap_with_genomic_regions
// ATAC_QC_reads__estimating_library_complexity
// ATAC_QC_reads__sampling_trimmed_reads
// ATAC_QC_reads__aligning_sampled_reads
// ATAC_QC_reads__gathering_all_stat
// ATAC_QC_reads__gathering_all_samples
// ATAC_QC_reads__splitting_stat_for_multiqc
// ATAC_QC_reads__running_multiQC
// ATAC_peaks__calling_peaks
// ATAC_peaks__splitting_multi_summits_peaks
// ATAC_peaks__removing_blacklisted_regions
// ATAC_peaks__removing_input_control_peaks
// ATAC_peaks__removing_specific_regions
// ATAC_QC_peaks__computing_and_plotting_saturation_curve
// ATAC_QC_peaks__annotating_macs2_peaks
// ATAC_QC_peaks__plotting_annotated_macs2_peaks_for_each_sample
// ATAC_QC_peaks__plotting_annotated_macs2_peaks_for_all_samples_grouped
// MRNA__quantifying_transcripts_abundances
// MRNA_QC__running_fastqc
// MRNA_QC__running_MultiQC
// DA_ATAC__doing_differential_analysis
// DA_ATAC__annotating_diffbind_peaks
// DA_ATAC__plotting_differential_analysis_results
// DA_ATAC__saving_detailed_results_tables
// DA_mRNA__doing_differential_analysis
// DA_mRNA__plotting_differential_analysis_results
// DA_mRNA__saving_detailed_results_tables
// DA_split__splitting_differential_analysis_results_in_subsets
// DA_split__plotting_venn_diagrams
// Enrichment__computing_functional_annotations_overlaps
// Enrichment__computing_genes_self_overlaps
// Enrichment__computing_peaks_overlaps
// Enrichment__computing_motifs_overlaps
// Enrichment__reformatting_motifs_results
// Enrichment__computing_enrichment_pvalues
// Figures__making_enrichment_barplots
// Figures__making_enrichment_heatmap
// Tables__formatting_csv_tables
// Tables__merging_csv_tables
// Tables__saving_excel_tables
// Figures__merging_pdfs
//// shortening certain oftenly used parameters
res_dir = params.res_dir
pub_mode = params.pub_mode
out_processed = "${res_dir}/Processed_Data"
out_fig_indiv = "${res_dir}/Figures_Individual"
out_fig_merge = "${res_dir}/Figures_Merged"
out_tab_merge = "${res_dir}/Tables_Merged"
out_tab_indiv = "${res_dir}/Tables_Individual"
//// setting up parameters
save_all_fastq = params.save_fastq_type == 'all' ? true : false
save_all_bam = params.save_bam_type == 'all' ? true : false
save_all_bed = params.save_bed_type == 'all' ? true : false
save_last_fastq = params.save_fastq_type in ['last', 'all'] ? true : false
save_last_bam = params.save_bam_type in ['last', 'all'] ? true : false
save_last_bed = params.save_bed_type in ['last', 'all'] ? true : false
do_atac = params.experiment_types in ['atac', 'both']
do_mRNA = params.experiment_types in ['mRNA', 'both']
do_OSE = params.do_only_self_enrichment
di_ALL = params.disable_all_enrichments
do_peaks_self = (params.do_peaks_self_enrichment || do_OSE) && !di_ALL
do_genes_self = (params.do_genes_self_enrichment || do_OSE) && !di_ALL
do_func_anno = params.do_func_anno_enrichment && !do_OSE && !di_ALL
do_chrom_state = params.do_chrom_state_enrichment && !do_OSE && !di_ALL
do_chip = params.do_chip_enrichment && !do_OSE && !di_ALL
do_motif = params.do_motif_enrichment && !do_OSE && !di_ALL
def update_common_params(common_params, current_params) {
if(common_params == null){
new_params = current_params
} else {
new_params = [
genes_self: common_params,
peaks_self: common_params,
func_anno: common_params,
chrom_states: common_params,
CHIP: common_params,
motifs: common_params
]
}
return(new_params)
}
params_padj_bin_breaks = update_common_params(params.common__padj_bin_breaks, params.padj_bin_breaks)
params_barplots_params = update_common_params(params.common__barplots_params, params.barplots_params)
params_barplots_ggplot = update_common_params(params.common__barplots_ggplot, params.barplots_ggplot)
params_heatmaps_params = update_common_params(params.common__heatmaps_params, params.heatmaps_params)
params_heatmaps_ggplot = update_common_params(params.common__heatmaps_ggplot, params.heatmaps_ggplot)
params_heatmaps_filter = update_common_params(params.common__heatmaps_filter, params.heatmaps_filter)
params_heatmaps_filter.genes_self = "NULL"
params_heatmaps_filter.peaks_self = "NULL"
params_heatmaps_filter.chrom_states = "NULL"
//// Creating empty channels
Overlap_tables_channel = Channel.empty()
Formatting_csv_tables_channel = Channel.empty()
Exporting_to_Excel_channel = Channel.empty()
Merging_pdfs_channel = Channel.empty()
//// Creating mRNA-Seq channels
static def returnR2ifExists(r2files) {
boolean exists = r2files[1].exists();
boolean diff = r2files[0] != r2files[1];
if (exists & diff) { return(r2files)
} else { return(r2files[0]) }
}
// MRNA_reads_for_merging = Channel.create() // not yet implemented
MRNA_reads_for_kallisto = Channel.create()
fastq_files = file(params.design__mrna_fastq)
Channel
.from(fastq_files.readLines())
.map{ it.split() }
.map{ [ it[0], it[1..-1] ] }
.transpose()
.map{ [ it[0], file(it[1]), file(it[1].replace("_R1", "_R2") ) ] }
.map{ [ it[0], returnR2ifExists(it[1, 2]) ] }
.dump(tag:'mrna_fastq')
.tap{ MRNA_reads_for_running_fastqc }
.map{ it.flatten() }
.map{ [it[0], it[1..-1] ] }
.dump(tag:'mrna_kallisto') {"mRNA reads for kallisto: ${it}"}
.set { MRNA_reads_for_kallisto }
//// Creating ATAC-Seq channels
ATAC_reads_for_merging = Channel.create()
ATAC_reads_for_trimming_1 = Channel.create()
fastq_files = file(params.design__atac_fastq)
Channel
.from(fastq_files.readLines())
.map{ it.split() }
.map{ [ it[0], it[1..-1] ] }
.transpose()
.map{ [ it[0], file(it[1]), file(it[1].replace("_R1", "_R2")) ] }
.tap{ Raw_ATAC_reads_for_running_fastqc }
.map{ [ it[0], [ it[1], it[2] ] ] }
.transpose()
.groupTuple()
.dump(tag:'atac_raw') {"ATAC raw reads: ${it}"}
.branch{
ATAC_reads_for_merging: it[1].size() > 2
ATAC_reads_for_trimming_1: it[1].size() == 2
}
.set{ atac_raw }
// => if it[1] has 2 elements it means there is just the R1 and R2 files and
// thus no other file has the same sample_id, so we don't need to merge, if
// more it means there are different runs so we merge them, if less it is not
// an option since we need paired end reads
//// Let's start!
process ATAC_reads__merging_reads {
tag "${id}"
label "fastqc"
publishDir path: "${out_processed}/1_Preprocessing/ATAC__reads__fastq_merged",
mode: "${pub_mode}", enabled: save_all_fastq
when:
do_atac
input:
set id, file(files_R1_R2) from atac_raw.ATAC_reads_for_merging
output:
set id, file('*__R1_merged.fastq.gz'), file('*__R2_merged.fastq.gz') \
into ATAC_reads_for_trimming_2
script:
"""
cat `ls *R1* | sort` > ${id}__R1_merged.fastq.gz
cat `ls *R2* | sort` > ${id}__R2_merged.fastq.gz
"""
}
atac_raw.ATAC_reads_for_trimming_1
.map{ it.flatten() }
.mix( ATAC_reads_for_trimming_2 )
.dump(tag:'atac_trimming') {"ATAC reads for trimming: ${it}"}
.set { ATAC_reads_for_trimming_3 }
process ATAC_reads__trimming_reads {
tag "${id}"
label "skewer_pigz"
cpus params.pigz__nb_threads
publishDir \
path: "${out_processed}/1_Preprocessing/ATAC__reads__fastq_trimmed",
mode: "${pub_mode}", pattern: "*.log"
publishDir \
path: "${out_processed}/1_Preprocessing/ATAC__reads__fastq_trimmed",
mode: "${pub_mode}", pattern: "*.fastq.gz", enabled: save_last_fastq
when:
do_atac
input:
set id, file(read1), file(read2) from ATAC_reads_for_trimming_3
output:
set id, file("*__R1_trimmed.fastq.gz"), file("*__R2_trimmed.fastq.gz") \
into Trimmed_reads_for_aligning, Trimmed_reads_for_sampling
set val('trimmed'), id, file("*__R1_trimmed.fastq.gz"),
file("*__R2_trimmed.fastq.gz") into Trimmed_ATAC_reads_for_running_fastqc
file("*.log")
shell:
'''
R1=!{read1}
R2=!{read2}
id=!{id}
pigz__nb_threads=!{params.pigz__nb_threads}
R1TRIM=$(basename ${R1} .fastq.gz)__R1_trimmed.fastq
R2TRIM=$(basename ${R2} .fastq.gz)__R2_trimmed.fastq
skewer --quiet -x CTGTCTCTTATA -y CTGTCTCTTATA -m pe ${R1} ${R2} \
-o ${id} > trimer_verbose.txt
mv ${id}-trimmed.log ${id}__skewer_trimming.log
mv ${id}-trimmed-pair1.fastq $R1TRIM
mv ${id}-trimmed-pair2.fastq $R2TRIM
pigz -p ${pigz__nb_threads} $R1TRIM
pigz -p ${pigz__nb_threads} $R2TRIM
pigz -l $R1TRIM.gz > ${id}__pigz_compression.log
pigz -l $R2TRIM.gz >> ${id}__pigz_compression.log
'''
}
// trimming adaptors
// this line crashed the script somehow. I don't really get the grep fast here
// anyway so I changed it
// pigz -l $R2TRIM.gz | grep fastq - >> !{id}_pigz_compression.log
// cp $R1 $R1TRIM.gz
// cp $R2 $R2TRIM.gz
// touch tmp.log
// R1TRIM=$(basename ${R1} .fastq.gz)_trim.fastq
// R2TRIM=$(basename ${R2} .fastq.gz)_trim.fastq
//
// skewer potentially useful options
// -m, --mode <str> trimming mode;
// 1) single-end -- head: 5' end; tail: 3' end; any: anywhere
// 2) paired-end -- pe: paired-end; mp: mate-pair; ap: amplicon (pe)
// -q, --end-quality <int> Trim 3' end until specified or higher quality
// reached; (0). => Maybe one could later set -q 20. But on
// "https://informatics.fas.harvard.edu/atac-seq-guidelines.html" they say:
// "Other than adapter removal, we do not recommend any trimming of the
// reads. Such adjustments can complicate later steps, such as the
// identification of PCR duplicates."
// -t, --threads <int> Number of concurrent threads [1, 32]; (1)
// -A, --masked-output Write output file(s) for trimmed reads (trimmed bases
// converted to lower case) (no)
// pigz potentially useful options
// -k, --keep Do not delete original file after processing
// -0 to -9, -11 Compression level (level 11, zopfli, is much slower)
// => the default is 6
// --fast, --best Compression levels 1 and 9 respectively
// -p, --processes n Allow up to n compression threads
// (default is the number of online processors, or 8 if unknown)
// -c, --stdout Write all processed output to stdout (won't delete)
// -l, --list List the contents of the compressed input
Raw_ATAC_reads_for_running_fastqc
.map{ [ 'raw', it[0], it[1], it[2] ] }
.mix(Trimmed_ATAC_reads_for_running_fastqc)
.dump(tag:'atac_fastqc') {"ATAC reads for fastqc: ${it}"}
.set{ All_ATAC_reads_for_running_fastqc}
process ATAC_reads__aligning_reads {
tag "${id}"
label "bowtie2_samtools"
cpus params.botwie2__nb_threads
publishDir path: "${out_processed}/1_Preprocessing/ATAC__reads__bam",
mode: "${pub_mode}", pattern: "*.{txt,qc}"
publishDir path: "${out_processed}/1_Preprocessing/ATAC__reads__bam",
mode: "${pub_mode}", pattern: "*.bam", enabled: save_all_bam
when:
do_atac
input:
set id, file(read1), file(read2) from Trimmed_reads_for_aligning
output:
set id, file("*.bam") into Bam_for_removing_low_quality_reads,
Bam_for_sampling
file("*.txt")
file("*.qc")
script:
def new_bam = id + ".bam"
"""
bowtie2 -p ${params.botwie2__nb_threads} \
--very-sensitive \
--end-to-end \
--no-mixed \
-X 2000 \
--met 1 \
--met-file "${id}_bowtie2_align_metrics.txt" \
-x "${params.bowtie2_indexes}" \
-q -1 "${read1}" -2 "${read2}" \
| samtools view -bS -o ${new_bam} -
samtools flagstat ${new_bam} > "${id}.qc"
"""
}
process ATAC_reads__removing_low_quality_reads {
tag "${id}"
label "bowtie2_samtools"
publishDir path: "${out_processed}/1_Preprocessing/ATAC__reads__bam_no_lowQ",
mode: "${pub_mode}", pattern: "*.qc"
publishDir path: "${out_processed}/1_Preprocessing/ATAC__reads__bam_no_lowQ",
mode: "${pub_mode}", pattern: "*.bam", enabled: save_all_bam
when:
do_atac
input:
set id, file(bam) from Bam_for_removing_low_quality_reads
output:
set id, file("*.bam") into Bam_for_marking_duplicated_reads
file("*.qc")
script:
def key = id + "__filter_LQ"
def new_bam = key + ".bam"
"""
samtools view -F 1804 \
-b \
-q "${params.sam_MAPQ_threshold}" \
${bam} \
| samtools sort - -o ${new_bam}
samtools flagstat ${new_bam} > "${key}.qc"
"""
}
// => filtering bad quality reads: unmapped, mate unmapped,
// no primary alignment, low MAPQ
process ATAC_reads__marking_duplicated_reads {
tag "${id}"
label "picard"
when:
do_atac
input:
set id, file(bam) from Bam_for_marking_duplicated_reads
output:
set id, file("*.bam") into Bam_for_removing_duplicated_reads
file("*.qc")
script:
def key = id + "__dup_marked"
"""
picard -Xmx${params.memory_picard} MarkDuplicates \
-INPUT "${bam}" \
-OUTPUT "${key}.bam" \
-METRICS_FILE "${key}.qc" \
-VALIDATION_STRINGENCY LENIENT \
-ASSUME_SORTED true \
-REMOVE_DUPLICATES false \
-TMP_DIR "."
"""
}
process ATAC_reads__removing_duplicated_reads {
tag "${id}"
label "bowtie2_samtools"
publishDir \
path: "${out_processed}/1_Preprocessing/ATAC__reads__bam_no_lowQ_dupli",
mode: "${pub_mode}", pattern: "*.qc"
publishDir \
path: "${out_processed}/1_Preprocessing/ATAC__reads__bam_no_lowQ_dupli",
mode: "${pub_mode}", pattern: "*.bam", enabled: save_all_bam
when:
do_atac
input:
set id, file(bam) from Bam_for_removing_duplicated_reads
output:
set id, file("*.bam"), file("*.bai") \
into Bam_for_computing_bigwig_tracks_and_plotting_coverage,
Bam_for_removing_mitochondrial_reads
file("*.qc")
script:
def key = id + "__dup_rem"
def new_bam = key + ".bam"
"""
samtools view -F 1804 "${bam}" -b -o ${new_bam}
samtools index -b ${new_bam}
samtools flagstat ${new_bam} > "${key}.qc"
"""
}
// => removing duplicates, index bam files and generates final stat file
process ATAC_reads__removing_reads_in_mitochondria_and_small_contigs {
tag "${id}"
label "bowtie2_samtools"
publishDir \
path: "${out_processed}/1_Preprocessing/ATAC__reads__bam_no_lowQ_dupli_mito",
mode: "${pub_mode}", pattern: "*.{qc,txt}"
publishDir \
path: "${out_processed}/1_Preprocessing/ATAC__reads__bam_no_lowQ_dupli_mito",
mode: "${pub_mode}", pattern: "*.bam", enabled: save_last_bam
when:
do_atac
input:
set id, file(bam), file(bai) from Bam_for_removing_mitochondrial_reads
output:
set id, file("*.bam") \
into Bam_for_plotting_inserts_distribution,
Bam_for_converting_bam_to_bed_and_adjusting_for_Tn5
file "*_reads_per_chrm_before_removal.txt"
file "*_reads_per_chrm_after_removal.txt"
file("*.qc")
shell:
'''
id=!{id}
bam=!{bam}
chromosomes_sizes=!{params.chromosomes_sizes}
key="${id}__no_mito"
new_bam="${key}.bam"
samtools view ${bam} | awk " $1 !~ /@/ {print $3}" - | uniq -c \
> "${id}_reads_per_chrm_before_removal.txt"
regions_to_keep=$(cut -f1 $chromosomes_sizes | paste -sd " ")
samtools view -Sb ${bam} $regions_to_keep | tee ${new_bam} \
| samtools view - | awk '{print $3}' OFS='\t' \
| uniq -c > "${id}_reads_per_chrm_after_removal.txt"
samtools index -b ${new_bam}
samtools flagstat ${new_bam} > "${key}.qc"
'''
}
// cut -f1 $chromosomes_sizes
// samtools view ${bam} $regions_to_keep | awk '{print $3}' OFS='\t' - \
// | sort | uniq -c
// samtools view ${bam} | awk '{print $3}' OFS='\t' - | sort | uniq -c
process ATAC_reads__converting_bam_to_bed_and_adjusting_for_Tn5 {
tag "${id}"
label "samtools_bedtools_perl"
publishDir \
path: "${out_processed}/1_Preprocessing/ATAC__reads__bam_asBed_atacShift",
mode: "${pub_mode}", pattern: "*.bam", enabled: params.save_1bp_bam
when:
do_atac
input:
set id, file(bam) from Bam_for_converting_bam_to_bed_and_adjusting_for_Tn5
output:
set id, file("*.bam*") into Reads_in_bam_files_for_diffbind
set id, file("*.bed") into \
Reads_in_bed_files_for_gathering_reads_stat,
Reads_in_bed_files_for_calling_peaks,
Reads_in_bed_files_for_computing_and_plotting_saturation_curve
script:
def key = id + "__1bp_shifted_reads"
"""
bamToBed_and_atacShift.sh ${bam} ${key} ${params.chromosomes_sizes}
"""
}
// Examples of :
// input: hmg4_1__no_mito.bam
// outpus: hmg4_1__1bp_shifted_reads.bam hmg4_1__1bp_shifted_reads.bam.bai
// hmg4_1__1bp_shifted_reads.bed
// => converting bam to bed, adjusting for the shift of the transposase
// (atac seq) and keeping only a bed format compatible with macs2
// input are bam files (aligned reads) that have been filtered out of reads
// that are low quality, duplicates, and in mitochondria or small contigs
// output are bed files in which the reads have been converted to 1 base pair
// (by keeping only the 5' end) and that have been shifted to take into
// account the transposase shift
// Example of a read pair:
// input:
// samtools view n301b170_2_no_mito.bam | grep SRR11607686.9081238 - | cut -f1-9
// QNAME FLAG RNAME POS MAPQ CIGAR RNEXT PNEXT TLEN
// SRR11607686.9081238 163 211000022278033 357 31 37M = 408 88
// SRR11607686.9081238 83 211000022278033 408 31 37M = 357 -88
// output:
// grep "SRR11607686.9081238/2\|SRR11607686.9081238/1" n301b170_2_1bp_shifted_reads.bed
// 211000022278033 360 361 SRR11607686.9081238/2 88 +
// 211000022278033 438 439 SRR11607686.9081238/1 -88 -
// reads on the + strand are shifted by + 4 base pair -1
// (different coordinate system) (357 + 4 -1 = 360)
// reads on the - strand are shifted by - 5 base pair -1
// (different coordinate system) (445 -5 - 1 = 439)
// explanations for the input:
// the read has a size of 37 bp and the insert has a size of 88 bp
// ranges:
// - read 1 [357-394 -> size: 37]
// - read 2 [408-445 -> size: 37]
// - insert [357-445 -> size: 88]
// - fragment [345-457 -> size: 112] (not really sure for this. I just added
// 12 for the ATAC-Seq adapter length)
// https://www.frontiersin.org/files/Articles/77572/fgene-05-00005-HTML/image_m/fgene-05-00005-g001.jpg
// https://samtools-help.narkive.com/BpGYAdaT/isize-field-determining-insert-sizes-in-paired-end-data
// Note: here the 1 base pair long (5') transposase-shifted peaks are sent to
/// DiffBind directly for Differential Accessibility Analysis.
// https://www.nature.com/articles/nmeth.2688
// https://www.nature.com/articles/s42003-020-01403-4
// The Tn5 insertion positions were determined as the start sites of reads
// adjusted by the rule of “forward strand +4 bp, negative strand −5 bp”4.
//
process ATAC_QC_reads__running_fastqc {
tag "${id}"
label "fastqc"
cpus params.fastqc__nb_threads
publishDir \
path: "${out_processed}/1_Preprocessing", mode: "${pub_mode}",
pattern: "*.html", saveAs: {
if (reads_type == 'raw') "ATAC__reads__fastqc_raw/${it}"
else if (reads_type == 'trimmed') "ATAC__reads__fastqc_trimmed/${it}"
}
when:
do_atac
input:
set val(reads_type), id, file(read1), file(read2) \
from All_ATAC_reads_for_running_fastqc
output:
file("*.{zip, html}") into ATAC_fastqc_reports_for_multiqc
script:
"""
fastqc -t ${params.fastqc__nb_threads} ${read1} ${read2}
"""
}
process ATAC_QC_reads__computing_bigwig_tracks_and_plotting_coverage {
tag "${id}"
label "deeptools"
cpus params.deeptools__nb_threads
publishDir path: "${res_dir}", mode: "${pub_mode}", saveAs: {
if (it.indexOf(".pdf") > 0)
"Figures_Individual/1_Preprocessing/ATAC__reads__coverage/${it}"
else if (it.indexOf(".bw") > 0)
"Processed_Data/1_Preprocessing/ATAC__reads__bigwig/${it}"
}
when:
do_atac & params.do_bigwig
input:
set id, file(bam), file(bai) \
from Bam_for_computing_bigwig_tracks_and_plotting_coverage
output:
set val("ATAC__reads__coverage"), val('1_Preprocessing'), file("*.pdf") \
into ATAC_reads_coverage_plots_for_merging_pdfs
file("*.bw") into Bigwigs_for_correlation_1 optional true
script:
def key = id + "__reads_coverage"
"""
bamCoverage \
--bam ${bam} \
--binSize ${params.deeptools__binsize_bigwig_creation} \
--normalizeUsing ${params.deeptools__normalization_method} \
--numberOfProcessors ${params.deeptools__nb_threads} \
--blackListFileName ${params.blacklisted_regions} \
--effectiveGenomeSize ${params.effective_genome_size} \
--outFileName ${id}.bw
plotCoverage \
--bam ${bam} \
--numberOfSamples ${params.deeptools__nb_of_1_bp_samples} \
--numberOfProcessors ${params.deeptools__nb_threads} \
--blackListFileName ${params.blacklisted_regions} \
--plotTitle ${key} \
--plotFile ${key}.pdf
"""
}
Merging_pdfs_channel = Merging_pdfs_channel
.mix(ATAC_reads_coverage_plots_for_merging_pdfs.groupTuple(by: [0, 1]))
Bigwigs_for_correlation_1
.collect()
.into{ Bigwigs_with_input_control; Bigwigs_without_input_control_1 }
Bigwigs_without_input_control_1
.flatten()
.filter{ !(it =~ /input/) }
.collect()
.map{ [ 'without_control', it ] }
.set{ Bigwigs_without_input_control_1 }
Bigwigs_with_input_control
.map{ [ 'with_control', it ] }
.concat(Bigwigs_without_input_control_1)
.dump(tag:'bigwigs') {"bigwigs for cor and PCA: ${it}"}
.set{ Bigwigs_for_correlation_2 }
process ATAC_QC_reads__computing_and_plotting_bigwig_tracks_correlations {
tag "${input_control_present}"
label "deeptools"
publishDir \
path: "${out_fig_indiv}/${out_path}", mode: "${pub_mode}", saveAs: {
if (it.indexOf("_pca.pdf") > 0) "ATAC__reads__PCA/${it}"
else if (it.indexOf("_cor.pdf") > 0) "ATAC__reads__correlations/${it}"
}
when:
do_atac
input:
val out_path from Channel.value('1_Preprocessing')
set input_control_present, file("*") from Bigwigs_for_correlation_2
output:
set val("ATAC__reads__PCA"), out_path, file("*_pca.pdf") \
into ATAC_reads_PCA_plots_for_merging_pdfs
set val("ATAC__reads__correlations"), out_path, file("*_cor.pdf") \
into ATAC_reads_correlation_plots_for_merging_pdfs
script:
"""
plotPCAandCorMat.sh \
${input_control_present} \
${params.blacklisted_regions} \
${params.deeptools__binsize_bigwig_correlation}
"""
}
Merging_pdfs_channel = Merging_pdfs_channel
.mix(
ATAC_reads_PCA_plots_for_merging_pdfs
.groupTuple(by: [0, 1])
.map{ it.flatten() }
.map{ [ it[0], it[1], it[2..-1] ] }
)
Merging_pdfs_channel = Merging_pdfs_channel
.mix(
ATAC_reads_correlation_plots_for_merging_pdfs
.groupTuple(by: [0, 1])
.map{ it.flatten() }
.map{ [ it[0], it[1], it[2..-1] ] }
)
process ATAC_QC_reads__plotting_insert_size_distribution {
tag "${id}"
label "picard"
publishDir path: "${out_fig_indiv}/${out_path}/ATAC__reads__insert_size",
mode: "${pub_mode}"
when:
do_atac
input:
val out_path from Channel.value('1_Preprocessing')
set id, file(bam) from Bam_for_plotting_inserts_distribution
output:
set val("ATAC__reads__insert_size"), out_path, file("*.pdf") \
into ATAC_reads_insert_size_plots_for_merging_pdfs
script:
def key = id + "__insert_size"
"""
picard -Xmx${params.memory_picard} CollectInsertSizeMetrics \
-INPUT "${bam}" \
-OUTPUT "${key}.txt" \
-METRIC_ACCUMULATION_LEVEL ALL_READS \
-Histogram_FILE "${key}.pdf" \
-TMP_DIR .
"""
}
Merging_pdfs_channel = Merging_pdfs_channel
.mix(
ATAC_reads_insert_size_plots_for_merging_pdfs.groupTuple(by: [0, 1])
)
process ATAC_QC_reads__sampling_aligned_reads {
tag "${id}"
label "samtools_bedtools_perl"
when:
do_atac
input:
set id, file(bam) from Bam_for_sampling
output:
set id, file("*.sam") into Bam_for_estimating_library_complexity
set id, file("*.bam"), file("*.bai") \
into Bam_for_measuring_overlap_with_genomic_regions,
Sampled_aligned_reads_for_gathering_reads_stat
set id, file("*.NB_ALIGNED_PAIRS*"), file("*.RAW_PAIRS*") \
into Number_of_aligned_pairs_for_gathering_reads_stat
script:
def key = id + "__sampled"
def new_sam = key + ".sam"
def new_bam = key + ".bam"
"""
# saving the header
samtools view -F 0x904 -H ${bam} > ${new_sam}
# sampling a certain number of reads
samtools view -F 0x904 ${bam} \
| shuf - -n ${params.nb_sampled_aligned_reads} >> ${new_sam}
# conversion to bam, sorting and indexing of sampled reads
samtools view -Sb ${new_sam} \
| samtools sort - -o ${new_bam}
samtools index ${new_bam}
NB_ALIGNED_PAIRS=`samtools view -F 0x4 ${bam} | cut -f 1 | sort -T . \
| uniq | wc -l`
RAW_PAIRS=`samtools view ${bam}| cut -f 1 | sort -T . | uniq | wc -l`
touch \$NB_ALIGNED_PAIRS.NB_ALIGNED_PAIRS_${id}
touch \$RAW_PAIRS.RAW_PAIRS_${id}
"""
}
// The code "-F 0x904" indicates to keep only mapped alignment (flag 0x4) that
// are not secondary (flag 0x100, multimappers) or
// supplementary (flag 0x800, chimeric entries)
process ATAC_QC_reads__measuring_overlap_with_genomic_regions {
tag "${id}"
label "samtools_bedtools_perl"
when:
do_atac
input:
set id, file(bam), file(bai) \
from Bam_for_measuring_overlap_with_genomic_regions
output:
set id, file("*.txt") \
into Overlap_with_genomic_regions_results_for_gathering_reads_stat
shell:
'''
id=!{id}
bam=!{bam}
BED_PATH=!{params.bed_regions}
new_txt="${id}_reads_overlap_with_genomic_regions.txt"
getTotalReadsMappedToBedFile () {
bedtools coverage -a $1 -b $2 | cut -f 4 \
| awk '{ sum+=$1} END {print sum}'
}
PROMOTER=`getTotalReadsMappedToBedFile $BED_PATH/promoters.bed ${bam}`
EXONS=`getTotalReadsMappedToBedFile $BED_PATH/exons.bed ${bam}`
INTRONS=`getTotalReadsMappedToBedFile $BED_PATH/introns.bed ${bam}`
INTERGENIC=`getTotalReadsMappedToBedFile $BED_PATH/intergenic.bed ${bam}`
GENES=`getTotalReadsMappedToBedFile $BED_PATH/genes.bed ${bam}`
BAM_NB_READS=`samtools view -c ${bam}`
echo "PROMOTER EXONS INTRONS INTERGENIC GENES BAM_NB_READS" > ${new_txt}
echo "$PROMOTER $EXONS $INTRONS $INTERGENIC $GENES $BAM_NB_READS" \
>> ${new_txt}
awkDecimalDivision () {
awk -v x=$1 -v y=$2 'BEGIN {printf "%.2f\\n", 100 * x / y }'
}
P_PROM=$(awkDecimalDivision $PROMOTER $BAM_NB_READS)
P_EXONS=$(awkDecimalDivision $EXONS $BAM_NB_READS)
P_INTRONS=$(awkDecimalDivision $INTRONS $BAM_NB_READS)
P_INTERGENIC=$(awkDecimalDivision $INTERGENIC $BAM_NB_READS)
P_GENES=$(awkDecimalDivision $GENES $BAM_NB_READS)
P_READS=$(awkDecimalDivision $BAM_NB_READS $BAM_NB_READS)
echo "$P_PROM $P_EXONS $P_INTRONS $P_INTERGENIC $P_GENES $P_READS" \
>> ${new_txt}
'''
}
// => preparing ATAC-Seq related statistics on aligned reads
// bedtools_coverage_only () { bedtools coverage -a $1 -b $2 ;}
// bedtools_coverage_only $BED_PATH/promoters.bed ${bam} | head
// bedtools_coverage_only $BED_PATH/promoters.bed ${bam} | cut -f 4 | head
process ATAC_QC_reads__estimating_library_complexity {
tag "${id}"
label "picard"
when:
do_atac
input:
set id, file(sam) from Bam_for_estimating_library_complexity
output:
set id, file("*.txt") \
into Library_complexity_for_gathering_reads_stat