-
Notifications
You must be signed in to change notification settings - Fork 2
/
pughlab_fragmentomics_pipeline.pl
executable file
·1861 lines (1553 loc) · 56.5 KB
/
pughlab_fragmentomics_pipeline.pl
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 perl
### pughlab_fragmentomics_pipeline.pl ##############################################################
use AutoLoader 'AUTOLOAD';
use strict;
use warnings;
use Carp;
use Getopt::Std;
use Getopt::Long;
use POSIX qw(strftime);
use File::Basename;
use File::Path qw(make_path);
use YAML qw(LoadFile);
use List::Util qw(any);
use File::Find;
use Data::Dumper;
use IO::Handle;
my $cwd = dirname(__FILE__);
require "$cwd/scripts/utilities.pl";
# define path to fragmentomics code location(s)
our ($fragmentomics_code_dir, $griffin_code_dir) = undef;
# define some global variables
our ($reference, $reference_peaks) = undef;
our ($delfi_healthy, $delfi_gaps, $delfi_vntrs, $delfi_tiles, $delfi_filters) = undef;
our ($tfbs_sites, $tcga_sites, $dhs_sites, $hk_sites) = undef;
our $griffin_sites;
our ($griffin_mappable, $griffin_mappable_name) = undef;
####################################################################################################
# version author comment
# 1.0 sprokopec wrapper to run Derek's fragmentomics code
### DEFINE SUBROUTINES #############################################################################
# run downsample bam
sub create_downsample_command {
my %args = (
bam => undef,
id => undef,
n_reads => undef,
factor => undef,
outdir => undef,
tmpdir => undef,
@_
);
my $downsample_command;
if (defined($args{n_reads})) {
$downsample_command = join("\n",
"N_READS=" . $args{n_reads},
"TOTAL_READS=\$(samtools view -c $args{bam})",
"SCALE_FACTOR=\$(printf '%.4f\\n' \$(echo \"\$N_READS/\$TOTAL_READS\" | bc -l))"
);
} elsif (defined($args{factor})) {
$downsample_command = join("\n",
"SCALE_FACTOR=$args{factor}",
"TOTAL_READS=\$(samtools view -c $args{bam})",
"N_READS=\$(printf '%.0f\\n' \$(echo \"\$SCALE_FACTOR*\$TOTAL_READS\" | bc -l))"
);
}
$downsample_command .= "\n" . join("\n",
'echo "downsampling to $N_READS from $TOTAL_READS (scale factor = $SCALE_FACTOR)"' . "\n",
'if (( $(echo "$SCALE_FACTOR < 1" | bc -l) )); then'
);
$downsample_command .= "\n " . join(' ',
'java -Xmx1g',
'-Djava.io.tmpdir=' . $args{tmpdir},
'-jar $picard_dir/picard.jar DownsampleSam',
'I=' . $args{bam},
'O=' . $args{outdir} . '/' . $args{id} . '_downsampled.bam',
'P=$SCALE_FACTOR',
'VALIDATION_STRINGENCY=LENIENT;'
);
$downsample_command .= "\nelse\n " . join(' ',
'ln -s',
$args{bam},
$args{outdir} . '/' . $args{id} . '_downsampled.bam;'
);
$downsample_command .= "\nfi";
$downsample_command .= "\n" . join(' ',
'samtools index',
$args{outdir} . '/' . $args{id} . '_downsampled.bam;'
);
return($downsample_command);
}
# run DELFI fragmentomics ratio
sub create_ratio_command {
my %args = (
bam => undef,
id => undef,
outdir => undef,
@_
);
my $delfi_command = join(' ',
"Rscript $fragmentomics_code_dir/ratio/runFrag.R",
"--id", $args{id},
"--bam", $args{bam},
"--outdir", $args{outdir},
"--libdir $fragmentomics_code_dir/ratio",
"--filters $delfi_filters",
"--gaps $delfi_gaps",
"--VNTRs $delfi_vntrs",
"--tiles $delfi_tiles",
"--healthy $delfi_healthy"
);
return($delfi_command);
}
# run VESSIES fragment score
sub create_fragmentscore_command {
my %args = (
id => undef,
bam => undef,
outdir => undef,
@_
);
my $score_command = join(' ',
"Rscript $fragmentomics_code_dir/fragment_score/scripts/04_patient_score.R",
"--id", $args{id},
"--bam", $args{bam},
"--outdir", $args{outdir},
"--ref $fragmentomics_code_dir/fragment_score/ref/vessies_reference_set.txt",
"--libdir $fragmentomics_code_dir/fragment_score/scripts"
);
return($score_command);
}
# format command to create de-duplicated BAM
sub get_deduplicate_command {
my %args = (
id => undef,
bam => undef,
outdir => undef,
tmp_dir => undef,
java_mem => undef,
dedup_tool => 'picard',
@_
);
my $output_stem = join('/', $args{outdir}, $args{id});
# deduplicate BAM
my $dedup_command = "# deduplicate bam";
if ('picard' eq $args{dedup_tool}) {
$dedup_command .= "\n" . join(' ',
'java -Xmx' . $args{java_mem},
'-Djava.io.tmpdir=' . $args{tmp_dir},
'-jar $picard_dir/picard.jar MarkDuplicates',
'I=' . $args{bam},
'O=' . $output_stem . '_deduped.bam',
'M=' . $output_stem . '_deduped.metrics',
'REMOVE_DUPLICATES=true',
'REMOVE_SEQUENCING_DUPLICATES=true'
);
} else {
$dedup_command .= "\n" . join(' ',
'sambamba markdup',
'-t 1 -r',
$args{bam},
$output_stem . '_deduped.bam',
'--tmpdir=' . $args{tmp_dir},
'--overflow-list-size 5000000'
);
}
# sort deduplicated BAM
$dedup_command .= "\n\n# sort deduplicated bam";
$dedup_command .= "\n" . join(' ',
'samtools sort -n',
$output_stem . '_deduped.bam',
'-o', $output_stem . '_deduped_sorted.bam'
);
# convert to bedpe (all reads)
$dedup_command .= "\n\n# convert deduplicated bam to bedpe";
$dedup_command .= "\n" . join(' ',
'samtools view -bf 0x2',
$output_stem . '_deduped_sorted.bam',
'| bedtools bamtobed -i stdin -bedpe',
'>', $output_stem . '_all.bedpe'
);
# convert to bedpe (high quality reads)
$dedup_command .= "\n\n# select high-quality reads and convert to bedpe";
$dedup_command .= "\n" . join(' ',
'samtools view -bf 0x2 -q 30',
$output_stem . '_deduped_sorted.bam',
'| bedtools bamtobed -i stdin -bedpe',
'>', $output_stem . '_q30.bedpe'
);
# remove intermediates
$dedup_command .= "\n\n# check for completeness and remove intermediates";
$dedup_command .= "\n" . join("\n",
'if [[ -f ' . $output_stem . '_q30.bedpe ]]; then',
' rm ' . $output_stem . '*deduped*',
'fi'
);
return($dedup_command);
}
# format command to create size-selected and de-duplicated BAM
sub get_sized_deduplicate_command {
my %args = (
id => undef,
bam => undef,
outdir => undef,
size => 'genome',
tmp_dir => undef,
java_mem => undef,
@_
);
my $output_stem = join('/', $args{outdir}, $args{id});
my ($dedup_command, $new_bam);
# select fragments of 167bp length (ie, 'normal' cfDNA)
$dedup_command = "# extracting desired fragments: ($args{size})";
if ('genome' eq $args{size}) {
$new_bam = $output_stem . "_len167_sorted.bam";
$output_stem = join('/', $args{outdir}, $args{id} . '_len167');
$dedup_command .= "\n" . join(' ',
"samtools view -h $args{bam}",
"| awk 'substr(\$0,1,1)==\"@\" || (\$9==167) || (\$9==-167)'",
"| samtools view -b",
"> $output_stem.bam;"
);
# select fragments of 150bp length (ie, 'short' cfDNA)
} elsif ('short' eq $args{size}) {
$new_bam = $output_stem . "_len150_sorted.bam";
$output_stem = join('/', $args{outdir}, $args{id} . '_len150');
$dedup_command .= "\n" . join(' ',
"samtools view -h $args{bam}",
"| awk 'substr(\$0,1,1)==\"@\" || (\$9<=150 && \$9>=10) || (\$9>=-150 && \$9<=-10)'",
"| samtools view -b",
"> $output_stem.bam;"
);
}
$dedup_command .= "\n\n# sort and index size-selected bam";
$dedup_command .= "\nsamtools index $output_stem.bam";
$dedup_command .= "\nsamtools sort $output_stem.bam -o $output_stem\_sorted.bam";
$dedup_command .= "\nsamtools index $output_stem\_sorted.bam";
# deduplicate BAM
$dedup_command .= "\n\n# deduplicate size-selected bam";
$dedup_command .= "\n" . join(' ',
'java -Xmx' . $args{java_mem},
'-Djava.io.tmpdir=' . $args{tmp_dir},
'-jar $picard_dir/picard.jar MarkDuplicates',
'I=' . $new_bam,
'O=' . $output_stem . '_deduped.bam',
'M=' . $output_stem . '_deduped.metrics',
'REMOVE_DUPLICATES=true',
'REMOVE_SEQUENCING_DUPLICATES=true'
);
# sort deduplicated BAM
$dedup_command .= "\n\n# sort deduplicated size-selected bam";
$dedup_command .= "\n" . join(' ',
'samtools sort -n',
$output_stem . '_deduped.bam',
'-o', $output_stem . '_deduped_sorted.bam'
);
# convert to bedpe (all reads)
$dedup_command .= "\n\n# convert bam to bedpe";
$dedup_command .= "\n" . join(' ',
'samtools view -bf 0x2',
$output_stem . '_deduped_sorted.bam',
'| bedtools bamtobed -i stdin -bedpe',
'>', $output_stem . '.bedpe'
);
# remove intermediates
$dedup_command .= "\n\n# check for completeness and remove intermediates";
$dedup_command .= "\n" . join("\n",
"if [[ -f $output_stem.bedpe ]]; then",
' rm ' . $output_stem . '*bam*',
' rm ' . $output_stem . '*metrics',
'fi'
);
return($dedup_command);
}
# run nucleosome positioning
sub create_nucleosome_position_command {
my %args = (
id => undef,
bedpe => undef,
outdir => undef,
@_
);
my $output_stem = join('/', $args{outdir}, $args{id});
my $linked_bedpe = join('/', $args{outdir}, $args{id} . '.bedpe' );
my $nuc_pos_command = "ln -s $args{bedpe} $linked_bedpe";
$nuc_pos_command .= "\n\n# split bedpe by chromosome";
$nuc_pos_command .= "\necho '>>> Running splitBedpe.sh <<<'";
$nuc_pos_command .= "\n\n" . join(' ',
"$fragmentomics_code_dir/nucleosome_peak/scripts/splitBedpe.sh",
$linked_bedpe
);
$nuc_pos_command .= "\n\n# calculate distance to nucleosome peaks";
$nuc_pos_command .= "\necho '>>> Running nucleosome_peaks_distance.R <<<'";
$nuc_pos_command .= "\n\n" . join(' ',
"Rscript $fragmentomics_code_dir/nucleosome_peak/scripts/nucleosome_peaks_distance.R",
"--id", $args{id},
"--path", $args{outdir},
"--peaks", $reference_peaks,
"--outdir", $args{outdir}
);
$nuc_pos_command .= "\n\n# check for completeness and remove intermediates";
$nuc_pos_command .= "\n" . join("\n",
'if [[ -f ' . $output_stem . '_peak_distance.txt ]]; then',
" echo '>>> Nucleosome Position Profiling completed successfully! <<<'",
' rm ' . $output_stem . '*.bed*',
'fi'
);
return($nuc_pos_command);
}
# format command to extract insert size metrics
sub get_insert_sizes_command {
my %args = (
id => undef,
bam => undef,
outdir => undef,
java_mem => undef,
tmp_dir => undef,
@_
);
my $output_stem = join('/', $args{outdir}, $args{id});
my $fs_command = join(' ',
'java -Xmx' . $args{java_mem},
'-Djava.io.tmpdir=' . $args{tmp_dir},
'-jar $picard_dir/picard.jar CollectInsertSizeMetrics',
'I=' . $args{bam},
'O=' . $output_stem . '_picard.txt',
'H=' . $output_stem . '.pdf',
'M=0 W=600'
);
return($fs_command);
}
# format command to run Griffin GC functions
sub get_griffin_gc_command {
my %args = (
id => undef,
bam => undef,
outdir => undef,
tmpdir => undef,
n_cpus => 8,
@_
);
my $gc_command;
# using Griffin v0.1.0 (version provided with Pipeline-Suite)
unless ($griffin_code_dir =~ m/v0.2.0/) {
$gc_command = join(' ',
"$griffin_code_dir/scripts/griffin_GC_counts.py",
'--bam_file', $args{bam},
'--bam_file_name', $args{id},
'--mapable_regions', $griffin_mappable,
'--ref_seq', $reference,
'--chrom_sizes', "$griffin_code_dir/Ref/hg38.standard.chrom.sizes",
'--out_dir', $args{outdir},
'--map_q 20 --size_range 15 500 --CPU', $args{n_cpus}
);
$gc_command .= "\n\n" . join(' ',
"$griffin_code_dir/scripts/griffin_GC_bias.py",
'--bam_file_name', $args{id},
'--mapable_name', $griffin_mappable_name,
'--genome_GC_frequency', "$griffin_code_dir/Ref/genome_GC_frequency",
'--out_dir', $args{outdir},
'--size_range 15 500'
);
} else {
# using Griffin v0.2.0 (currently doesn't work; testing in progress)
$gc_command = "source activate base";
$gc_command .= "\nconda activate griffin2";
my $map_stem = join('/', $args{outdir}, 'mappability_bias', $args{id} . '.mappability_bias');
$gc_command .= "\n\n" . join(' ',
"$griffin_code_dir/scripts/griffin_mappability_correction.py",
'--bam_file', $args{bam},
'--bam_file_name', $args{id},
'--output', $map_stem . '.txt',
'--output_plot', $map_stem . '.pdf',
'--mappability', "$griffin_code_dir/Ref/k50.Umap.MultiTrackMappability.hg38.bw",
'--exclude_paths', "$griffin_code_dir/Ref/encode_unified_GRCh38_exclusion_list.bed",
'--chrom_sizes', "$griffin_code_dir/Ref/hg38.standard.chrom.sizes",
'--tmp_dir', $args{tmpdir},
'--map_quality 20 --CPU', $args{n_cpus}
);
$gc_command .= "\n\n" . join(' ',
"$griffin_code_dir/scripts/griffin_GC_counts.py",
'--bam_file', $args{bam},
'--bam_file_name', $args{id},
'--mappable_regions_path', "$griffin_code_dir/Ref/k100_minus_exclusion_lists.mappable_regions.hg38.bed",
'--ref_seq', $reference,
'--chrom_sizes', "$griffin_code_dir/Ref/hg38.standard.chrom.sizes",
'--out_dir', $args{outdir},
'--map_q 20 --size_range 15 500 --CPU', $args{n_cpus}
);
$gc_command .= "\n\n" . join(' ',
"$griffin_code_dir/scripts/griffin_GC_bias.py",
'--bam_file_name', $args{id},
'--mappable_name k100_minus_exclusion_lists.mappable_regions.hg38',
'--genome_GC_frequency', "$griffin_code_dir/Ref/genome_GC_frequency",
'--out_dir', $args{outdir},
'--size_range 15 500'
);
}
return($gc_command);
}
# format command to run Griffin nucleosome profiling
sub get_griffin_profiling_command {
my %args = (
id => undef,
bam => undef,
gc_bias => undef,
map_bias => undef,
n_cpus => 8,
tmpdir => undef,
outdir => undef,
sites => undef,
@_
);
my $griffin_command;
# using Griffin v0.1.0 (version provided with Pipeline-Suite)
unless ($griffin_code_dir =~ m/v0.2.0/) {
$griffin_command = join(' ',
"$griffin_code_dir/scripts/griffin_calc_coverage.py",
'--sample_name', $args{id},
'--bam', $args{bam},
'--reference_genome', $reference,
'--GC_bias', $args{gc_bias},
'--background_normalization None',
'--sites_yaml', $args{sites},
'--results_dir', $args{outdir},
'--chrom_column Chrom',
'--strand_column Strand',
'--chroms chr1 chr2 chr3 chr4 chr5 chr6 chr7 chr8 chr9 chr10 chr11 chr12 chr13 chr14 chr15 chr16 chr17 chr18 chr19 chr20 chr21 chr22',
'--norm_window -5000 5000',
'--plot_window -1000 1000',
'--fragment_length 165',
'--step 15 --size_range 90 220 --map_quality 20',
'--individual False --smoothing True --num_sites none',
'--sort_by none --ascending none --cpu', $args{n_cpus},
'--erase_intermediates True'
);
} else {
# using Griffin v0.2.0 (currently doesn't work; testing in progress)
$griffin_command = "source activate base";
$griffin_command .= "\nconda activate griffin2";
$griffin_command .= "\n\n" . join(' ',
"$griffin_code_dir/scripts/griffin_coverage.py",
'--sample_name', $args{id},
'--bam', $args{bam},
'--reference_genome', $reference,
'--GC_bias', $args{gc_bias},
'--mappability_bias', $args{map_bias},
'--mappability_correction True',
'--mappability_bw', "$griffin_code_dir/Ref/k50.Umap.MultiTrackMappability.hg38.bw",
'--chrom_sizes_path', "$griffin_code_dir/Ref/hg38.standard.chrom.sizes",
'--tmp_dir', $args{tmpdir},
'--griffin_scripts', "$griffin_code_dir/scripts",
'--sites_yaml', $args{sites},
'--position_column position',
'--size_range 90 220 --map_quality 20 --number_of_sites none',
'--CPU', $args{n_cpus}
);
my $uncorrected_bw = join('/', $args{tmpdir}, $args{id}, 'tmp_bigWig', $args{id} . '.uncorrected.bw');
my $corrected_bw = join('/', $args{tmpdir}, $args{id}, 'tmp_bigWig', $args{id} . '.GC_corrected.bw');
my $map_corrected_bw = join('/', $args{tmpdir}, $args{id}, 'tmp_bigWig', $args{id} . '.GC_map_corrected.bw');
my $exclude_encode = join('/', $griffin_code_dir, 'Ref', 'encode_unified_GRCh38_exclusion_list.bed');
my $exclude_centromeres = join('/', $griffin_code_dir, 'Ref', 'hg38_centromeres.bed');
my $exclude_gaps = join('/', $griffin_code_dir, 'Ref', 'hg38_gaps.bed');
my $exclude_patches = join('/', $griffin_code_dir, 'Ref', 'hg38_fix_patches.bed');
my $exclude_alts = join('/', $griffin_code_dir, 'Ref', 'hg38_alternative_haplotypes.bed');
$griffin_command .= "\n\n" . join(' ',
"$griffin_code_dir/scripts/griffin_merge_sites.py",
'--sample_name', $args{id},
'--uncorrected_bw_path', $uncorrected_bw,
'--GC_corrected_bw_path', $corrected_bw,
'--GC_map_corrected_bw_path', $map_corrected_bw,
'--mappability_correction False',
'--mappability_bw', "$griffin_code_dir/Ref/k50.Umap.MultiTrackMappability.hg38.bw",
'--chrom_sizes_path', "$griffin_code_dir/Ref/hg38.standard.chrom.sizes",
'--sites_yaml', $args{sites},
'--griffin_scripts_dir', "$griffin_code_dir/scripts",
'--tmp_dir', $args{tmpdir},
'--results_dir', $args{outdir},
'--position_column position',
'--exclude_paths', $exclude_encode, $exclude_centromeres, $exclude_gaps, $exclude_patches, $exclude_alts,
'--exclude_outliers True',
'--exclude_zero_mappability True',
'--step 15',
'--CNA_normalization False',
'--CPU', $args{n_cpus},
'--individual False',
'--smoothing True'
);
}
$griffin_command .= "\n\n" . join(' ',
"echo 'Griffin nucleosome profiling completed successfully' >",
$args{outdir} . '/griffin_profiling.COMPLETE'
);
return($griffin_command);
}
# format command to run End Motif profiling
sub get_end_motif_command {
my %args = (
id => undef,
bedpe => undef,
outdir => undef,
@_
);
my $output_stem = join('/', $args{outdir}, $args{id});
my $linked_bedpe = join('/', $args{outdir}, $args{id} . '.bedpe' );
my $motif_command = "ln -s $args{bedpe} $linked_bedpe";
# format bedpe to bed
$motif_command .= "\n\n# convert bedpe to bed";
$motif_command .= "\necho '>>> Running motif_format_bedpe.R <<<'";
$motif_command .= "\n\n" . join(' ',
"Rscript $fragmentomics_code_dir/end_motif/scripts/motif_format_bedpe.R",
'--id', $args{id},
'--bedpe', $linked_bedpe,
'--outdir', $args{outdir}
);
# get fasta sequences
$motif_command .= "\n\n# extract fasta sequences";
$motif_command .= "\necho '>>> Running bedtools getfasta <<<'";
$motif_command .= "\n\n" . join(' ',
'bedtools getfasta',
'-bedOut -fi', $reference,
'-bed', $output_stem . '_5.bed',
'>', $output_stem . '_fasta_5.bed'
);
$motif_command .= "\n\n" . join(' ',
'bedtools getfasta',
'-bedOut -fi', $reference,
'-bed', $output_stem . '_3.bed',
'>', $output_stem . '_fasta_3.bed'
);
# convert fasta to end motif context frequencies
$motif_command .= "\n\n# run end motif context profiling";
$motif_command .= "\necho '>>> Running motif_get_contexts.R <<<'";
$motif_command .= "\n\n" . join(' ',
"Rscript $fragmentomics_code_dir/end_motif/scripts/motif_get_contexts.R",
"--id", $args{id},
"--fasta_5", $output_stem . '_fasta_5.bed',
"--fasta_3", $output_stem . '_fasta_3.bed',
"--outdir", $args{outdir}
);
# remove intermediate files
$motif_command .= "\n\n# check for completeness and remove intermediates";
$motif_command .= "\n" . join("\n",
'if [[ -f ' . $output_stem . '_motifs.txt ]]; then',
" echo '>>> End Motif Profiling completed successfully! <<<'",
' rm ' . $output_stem . '*.bed*',
'fi'
);
return($motif_command);
}
# format command to run breakpoint profiling
sub get_profile_breakpoints_command {
my %args = (
id => undef,
bedpe => undef,
outdir => undef,
@_
);
my $output_stem = join('/', $args{outdir}, $args{id});
my $linked_bedpe = join('/', $args{outdir}, $args{id} . '.bedpe' );
my $bkpt_command = "ln -s $args{bedpe} $linked_bedpe";
# format bedpe to bed
$bkpt_command .= "\n\n# convert bedpe to bed";
$bkpt_command .= "\necho '>>> Running breakpoint_format_bedpe.R <<<'";
$bkpt_command .= "\n\n" . join(' ',
"Rscript $fragmentomics_code_dir/breakpoint/scripts/breakpoint_format_bedpe.R",
'--id', $args{id},
'--bedpe', $linked_bedpe,
'--outdir', $args{outdir}
);
# get fasta sequences
$bkpt_command .= "\n\n# extract fasta sequences";
$bkpt_command .= "\necho '>>> Running bedtools getfasta <<<'";
$bkpt_command .= "\n\n" . join(' ',
'bedtools getfasta',
'-bedOut -fi', $reference,
'-bed', $output_stem . '_5.bed',
'>', $output_stem . '_fasta_5.bed'
);
$bkpt_command .= "\n\n" . join(' ',
'bedtools getfasta',
'-bedOut -fi', $reference,
'-bed', $output_stem . '_3.bed',
'>', $output_stem . '_fasta_3.bed'
);
# convert fasta to end motif context frequencies
$bkpt_command .= "\n\n# run breakpoint context profiling";
$bkpt_command .= "\necho '>>> Running breakpoint_get_contexts.R <<<'";
$bkpt_command .= "\n\n" . join(' ',
"Rscript $fragmentomics_code_dir/breakpoint/scripts/breakpoint_get_contexts.R",
"--id", $args{id},
"--fasta_5", $output_stem . '_fasta_5.bed',
"--fasta_3", $output_stem . '_fasta_3.bed',
"--outdir", $args{outdir}
);
# remove intermediate files
$bkpt_command .= "\n\n# check for completeness and remove intermediates";
$bkpt_command .= "\n" . join("\n",
'if [[ -f ' . $output_stem . '_ratio.txt ]]; then',
" echo '>>> Breakpoint Profiling completed successfully! <<<'",
' rm ' . $output_stem . '*.bed*',
'fi'
);
return($bkpt_command);
}
# format command to run dinucleotide profiling
sub get_dinucleotide_profiling_command {
my %args = (
id => undef,
bedpe => undef,
outdir => undef,
@_
);
my $output_stem = join('/', $args{outdir}, $args{id});
# format bedpe to bed
my $din_command = "# convert bedpe to bed";
$din_command .= "\necho '>>> Running dinucleotide_format_bedpe.R <<<'";
$din_command .= "\n\n" . join(' ',
"Rscript $fragmentomics_code_dir/dinucleotide/scripts/dinucleotide_format_bedpe.R",
'--id', $args{id},
'--bedpe', $args{bedpe},
'--outdir', $args{outdir}
);
# get fasta sequences
$din_command .= "\n\n# extract fasta sequences";
$din_command .= "\necho '>>> Running bedtools getfasta <<<'";
$din_command .= "\n\n" . join(' ',
'bedtools getfasta',
'-bedOut -fi', $reference,
'-bed', $output_stem . '.bed',
'>', $output_stem . '_fasta.bed'
);
# convert fasta to end motif context frequencies
$din_command .= "\n\n# run dinucleotide context profiling";
$din_command .= "\necho '>>> Running dinucleotide_get_contexts.R <<<'";
$din_command .= "\n\n" . join(' ',
"Rscript $fragmentomics_code_dir/dinucleotide/scripts/dinucleotide_get_contexts.R",
"--id", $args{id},
"--fasta", $output_stem . '_fasta.bed',
"--outdir", $args{outdir}
);
# remove intermediate files
$din_command .= "\n\n# check for completeness and remove intermediates";
$din_command .= "\n" . join("\n",
'if [[ -f ' . $output_stem . '_contexts.txt ]]; then',
" echo '>>> Dinucleotide Profiling completed successfully! <<<'",
' rm ' . $output_stem . '*.bed*',
'fi'
);
return($din_command);
}
### MAIN ###########################################################################################
sub main {
my %args = (
tool_config => undef,
data_config => undef,
output_directory => undef,
hpc_driver => undef,
dry_run => undef,
no_wait => undef,
@_
);
my $tool_config = $args{tool_config};
my $data_config = $args{data_config};
### PREAMBLE ######################################################################################
unless($args{dry_run}) {
print "Initiating Fragmenomics pipeline...\n";
}
# load tool config
my $tool_data = LoadFile($tool_config);
# organize output and log directories
my $output_directory = $args{output_directory};
$output_directory =~ s/\/$//;
my $log_directory = join('/', $output_directory, 'logs');
unless(-e $log_directory) { make_path($log_directory); }
my $log_file = join('/', $log_directory, 'run_Fragmentomics_pipeline.log');
# create a file to hold job metrics
my (@files, $run_count, $outfile, $touch_exit_status);
unless ($args{dry_run}) {
# initiate a file to hold job metrics
opendir(LOGFILES, $log_directory) or die "Cannot open $log_directory";
@files = grep { /slurm_job_metrics/ } readdir(LOGFILES);
$run_count = scalar(@files) + 1;
closedir(LOGFILES);
$outfile = $log_directory . '/slurm_job_metrics_' . $run_count . '.out';
$touch_exit_status = system("touch $outfile");
if (0 != $touch_exit_status) { Carp::croak("Cannot touch file $outfile"); }
$log_file = join('/', $log_directory, 'run_Fragmentomics_pipeline_' . $run_count . '.log');
}
# start logging
open (my $log, '>', $log_file) or die "Could not open $log_file for writing.";
$log->autoflush;
print $log "---\n";
print $log "Running Fragmentomics pipeline.\n";
print $log "\n Tool config used: $tool_config";
print $log "\n Sample config used: $data_config";
print $log "\n Output directory: $output_directory";
print $log "\n Reference used: $tool_data->{reference}";
print $log "\n---";
# get user-specified tool parameters
my $parameters = $tool_data->{parameters};
# set tools and versions
my $picard = 'picard/' . $tool_data->{picard_version};
my $sambamba = 'sambamba/' . $tool_data->{sambamba_version};
my $samtools = 'samtools/' . $tool_data->{samtools_version};
my $bedtools = 'bedtools/' . $tool_data->{bedtools_version};
my $python3 = 'python3/' . $tool_data->{python3_version};
my $r_version = 'R/' . $tool_data->{r_version};
if (defined($tool_data->{fragmentomics_dir})) {
$fragmentomics_code_dir = $tool_data->{fragmentomics_dir};
} else {
$fragmentomics_code_dir = "$cwd/scripts/fragmentomics";
}
if (defined($tool_data->{griffin_dir})) {
$griffin_code_dir = $tool_data->{griffin_dir};
} else {
$griffin_code_dir = "$cwd/scripts/fragmentomics/griffin";
}
# set reference files
$reference = $tool_data->{reference};
$reference_peaks = defined($tool_data->{nucleosome_peaks}) ? $tool_data->{nucleosome_peaks} : "$fragmentomics_code_dir/nucleosome_peak/ref/hg38";
$delfi_filters = defined($tool_data->{delfi_filters}) ? $tool_data->{delfi_filters} : "$fragmentomics_code_dir/ratio/extdata/filters.hg38.rda";
$delfi_gaps = defined($tool_data->{delfi_gaps}) ? $tool_data->{delfi_gaps} : "$fragmentomics_code_dir/ratio/extdata/gaps.hg38.rda";
$delfi_vntrs = defined($tool_data->{delfi_vntrs}) ? $tool_data->{delfi_vntrs} : "$fragmentomics_code_dir/ratio/extdata/VNTRs.hg38.rda";
$delfi_tiles = defined($tool_data->{delfi_tiles}) ? $tool_data->{delfi_tiles} : "$fragmentomics_code_dir/ratio/extdata/hg38_tiles.bed";
$delfi_healthy = defined($tool_data->{delfi_pon}) ? $tool_data->{delfi_pon} : "$fragmentomics_code_dir/ratio/extdata/healthy.median.hg38.rda";
if (defined($tool_data->{griffin_ref_mappable})) {
$griffin_mappable = $tool_data->{griffin_ref_mappable};
} else {
$griffin_mappable = "$cwd/scripts/fragmentomics/griffin/Ref/repeat_masker.mapable.k50.Umap.hg38.bedGraph.gz";
}
$griffin_mappable_name = basename $griffin_mappable;
$griffin_mappable_name =~ s/\.[^.]+$//;
# use custom list of griffin sites
if (defined($tool_data->{griffin_sites})) {
$griffin_sites = $tool_data->{griffin_sites};
}
# or use default options (will always run TFBS/TCGA/DHS/housekeeping
if (!defined($griffin_sites->{TFBS})) {
$griffin_sites->{TFBS} = "$griffin_code_dir/site_configs/TFBS_sites.yaml";
}
if (!defined($griffin_sites->{TCGA})) {
$griffin_sites->{TCGA} = "$griffin_code_dir/site_configs/TCGA_sites.yaml";
}
if (!defined($griffin_sites->{DHS})) {
$griffin_sites->{DHS} = "$griffin_code_dir/site_configs/DHS_sites.yaml";
}
if (!defined($griffin_sites->{housekeeping})) {
$griffin_sites->{housekeeping} = "$griffin_code_dir/site_configs/housekeeping_sites.yaml";
}
# get optional HPC group
my $hpc_group = defined($tool_data->{hpc_group}) ? "-A $tool_data->{hpc_group}" : undef;
### RUN ###########################################################################################
# first, determine which steps/fragmentomics analyses to run
my %tool_set = (
'downsample' => 'Y', #defined($parameters->{downsample}) ? 'Y' : 'N',
'deduplicate' => 'N', #defined($parameters->{dedup}) ? 'Y' : 'N',
'ratio' => defined($parameters->{ratio}) ? 'Y' : 'N',
'score' => defined($parameters->{score}) ? 'Y' : 'N',
'insertsize' => defined($parameters->{insertsize}) ? 'Y' : 'N',
'griffin' => defined($parameters->{griffin}) ? 'Y' : 'N',,
'nucleosome' => defined($parameters->{nucleosome_position}) ? 'Y' : 'N',
'dinucleotide' => defined($parameters->{dinucleotide}) ? 'Y' : 'N',
'end_motifs' => defined($parameters->{end_motifs}) ? 'Y' : 'N',
'breakpoints' => defined($parameters->{breakpoints}) ? 'Y' : 'N'
);
if ( ('Y' eq $tool_set{'nucleosome'}) ||
('Y' eq $tool_set{'end_motifs'}) || ('Y' eq $tool_set{'breakpoints'}) ) {
$tool_set{'deduplicate'} = 'Y';
}
print $log "\nTools/steps to run:\n";
print $log Dumper \%tool_set;
# get sample data
my $smp_data = LoadFile($data_config);
unless($args{dry_run}) {
print "Processing " . scalar(keys %{$smp_data}) . " patients.\n";
}
# extract downsample parameters
my ($n_reads, $scale_factor);
if (defined($parameters->{downsample}->{n_reads})) {
$n_reads = $parameters->{downsample}->{n_reads};
} elsif (defined($parameters->{downsample}->{scale_factor})) {
$scale_factor = $parameters->{downsample}->{scale_factor};
} else {
$n_reads = 50000000;
print "\nNo scaling parameters defined for downsampling; will default to 50M reads. Alternatively, you can specifiy these (number of reads (n_reads) or scaling factor (scale_factor)) in your tool config.";
}
# initialize objects
my ($run_script, $run_id);
my @all_jobs;
# process each patient in $smp_data
foreach my $patient (sort keys %{$smp_data}) {
print $log "\n---\nInitiating process for PATIENT: $patient";
# find bams
my @tumour_ids = sort keys %{$smp_data->{$patient}->{'tumour'}};
if (scalar(@tumour_ids) == 0) {
print $log "\n>> No tumour BAM provided, skipping patient.\n";
next;
}
# create some directories
my $patient_directory = join('/', $output_directory, $patient);
my $tmp_directory = join('/', $patient_directory, 'TEMP');
unless(-e $patient_directory) { make_path($patient_directory); }
unless(-e $tmp_directory) { make_path($tmp_directory); }
my (@final_outputs, @patient_jobs);
my $cleanup_cmd = " rm -rf $tmp_directory;";
# process each sample provided for this patient
foreach my $tumour (@tumour_ids) {
# initiate some variables
my $tumour_stem = $tumour;
my $tumour_bam = $smp_data->{$patient}->{tumour}->{$tumour};
my ($downsample_run_id, $dedup_run_id, $griffin_id) = '';
# set up directory structure
my $sample_directory = join('/', $patient_directory, $tumour);
my $downsample_directory = join('/', $sample_directory, 'downsample');
my $ratio_directory = join('/', $sample_directory, 'fragment_ratio');
my $score_directory = join('/', $sample_directory, 'fragment_score');
my $insertsize_directory = join('/', $sample_directory, 'insert_size');
my $nucleosome_directory = join('/', $sample_directory, 'nucleosome_peaks');
my $griffin_directory = join('/', $sample_directory, 'griffin');
my $motif_directory = join('/', $sample_directory, 'end_motifs');
my $breakpoint_directory = join('/', $sample_directory, 'breakpoints');
my $di_directory = join('/', $sample_directory, 'dinucleotide');
unless(-e $sample_directory) { make_path($sample_directory); }
if ('Y' eq $tool_set{'downsample'}) {
unless(-e $downsample_directory) { make_path($downsample_directory); }
}
if ('Y' eq $tool_set{'ratio'}) {
unless(-e $ratio_directory) { make_path($ratio_directory); }
}
if ('Y' eq $tool_set{'score'}) {
unless(-e $score_directory) { make_path($score_directory); }
}
if ('Y' eq $tool_set{'insertsize'}) {
unless(-e $insertsize_directory) { make_path($insertsize_directory); }
}
if ('Y' eq $tool_set{'nucleosome'}) {
unless(-e $nucleosome_directory) { make_path($nucleosome_directory); }
}
if ('Y' eq $tool_set{'griffin'}) {
unless(-e $griffin_directory) { make_path($griffin_directory); }
}
if ('Y' eq $tool_set{'end_motifs'}) {
unless(-e $motif_directory) { make_path($motif_directory); }
}
if ('Y' eq $tool_set{'breakpoints'}) {
unless(-e $breakpoint_directory) { make_path($breakpoint_directory); }
}
if ('Y' eq $tool_set{'dinucleotide'}) {
unless(-e $di_directory) { make_path($di_directory); }
}
# run downsample
if ('Y' eq $tool_set{'downsample'}) {
my $downsample_cmd = create_downsample_command(
bam => $smp_data->{$patient}->{tumour}->{$tumour},
id => $tumour,