-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathRunner.pm
2901 lines (2558 loc) · 77.9 KB
/
Runner.pm
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
package Bio::MultiRepChIPSeq::Runner;
use strict;
use English qw(-no_match_vars);
use Carp;
use IO::File;
use File::Spec;
use File::Copy;
use File::Path qw(make_path);
use Statistics::Descriptive;
use Parallel::ForkManager;
use Bio::ToolBox 1.70;
use Bio::ToolBox::utility qw(simplify_dataset_name format_with_commas);
use Bio::MultiRepChIPSeq::Job;
use base 'Bio::MultiRepChIPSeq::options';
use base 'Bio::MultiRepChIPSeq::reporter';
our $VERSION = 20.0;
sub new {
my $class = shift;
my $options = $class->init_options();
my $self = {
opts => $options,
Jobs => [],
finished_commands => [],
pm => undef,
progress_file => undef,
sample_file => undef,
universal_control => 0,
repmean_merge_base => undef,
repmerge_merge_base => undef,
dir_suffix => q(),
};
return bless $self, $class;
}
sub version {
return $VERSION;
}
sub has_universal_control {
my $self = shift;
$self->{universal_control} = shift if @_;
return $self->{universal_control};
}
sub repmean_merge_base {
my $self = shift;
$self->{repmean_merge_base} = $_[0] if @_;
return $self->{repmean_merge_base};
}
sub repmerge_merge_base {
my $self = shift;
$self->{repmerge_merge_base} = $_[0] if @_;
return $self->{repmerge_merge_base};
}
sub dir_suffix {
my $self = shift;
$self->{dir_suffix} = $_[0] if @_;
return $self->{dir_suffix};
}
sub add_job {
my $self = shift;
my $Job = Bio::MultiRepChIPSeq::Job->new( $self->{opts}, @_ );
if ($Job) {
push @{ $self->{Jobs} }, $Job;
}
else {
confess "failed to create a Job object!";
}
# initialize peak_base values automatically, since they're dependent on user options
if ( $self->independent ) {
$self->repmean_merge_base(
File::Spec->catfile( $self->dir, $self->out . '.rep_mean' ) );
$self->repmerge_merge_base(
File::Spec->catfile( $self->dir, $self->out . '.rep_merge' ) );
}
else {
$self->repmean_merge_base( File::Spec->catfile( $self->dir, $self->out ) );
}
return $Job;
}
sub list_jobs {
return @{ shift->{Jobs} };
}
sub number_of_jobs {
return scalar @{ shift->{Jobs} };
}
sub add_command {
my ( $self, $commands ) = @_;
push @{ $self->{finished_commands} }, @{$commands};
}
sub progress_file {
my $self = shift;
unless ( defined $self->{progress_file} ) {
# generate progress file path
my $pf = File::Spec->catfile( $self->dir, $self->out . '.progress.txt' );
$self->{progress_file} = $pf;
# make the progress hash
$self->{progress} = {
control_peak => 0,
deduplication => 0,
bamfilter => 0,
mappable_size => 0,
fragment => 0,
count => 0,
lambda => 0,
bw2bdg => 0,
bdgcmp => 0,
callpeak => 0,
bdg2bw => 0,
updatepeak => 0,
peakmerge => 0,
rescore => 0,
efficiency => 0,
};
}
return $self->{progress_file};
}
sub check_progress_file {
my $self = shift;
my $pf = $self->progress_file;
if ( -e $pf ) {
my $fh = IO::File->new( $pf, '<' );
while ( my $line = $fh->getline ) {
chomp $line;
if ( $line eq 'bam2wig' ) {
# old value!? shouldn't happen but just in case
$self->{progress}{fragment} = 1;
$self->{progress}{count} = 1;
}
else {
$self->{progress}{$line} = 1 if exists $self->{progress}{$line};
}
}
$fh->close;
}
}
sub update_progress_file {
my $self = shift;
my $key = shift;
$self->{progress}{$key} = 1;
return 1 if $self->dryrun; # just pretend
my $fh = IO::File->new( $self->progress_file, '>>' )
or croak "can't write to progress file! $OS_ERROR\n";
$fh->print("$key\n");
$fh->close;
return 1;
}
sub sample_file {
my $self = shift;
if ( $self->{sample_file} ) {
return $self->{sample_file};
}
else {
# write the file if we haven't done so yet
if ( $self->number_of_jobs ) {
return $self->write_samples_file;
}
else {
confess "No Jobs to write a sample file!";
}
}
}
sub write_samples_file {
my $self = shift;
# add dataset files
# we're using count bigWig files for simplicity
my %name2done;
my @conditions = ("Replicate\tDataset\n");
foreach my $Job ( $self->list_jobs ) {
foreach my $b ( $Job->chip_count_bw ) {
my $name = simplify_dataset_name($b);
push @conditions, sprintf "%s\t%s\n", $name, $Job->job_name;
}
foreach my $b ( $Job->control_count_bw ) {
next if exists $name2done{$b};
my $name = simplify_dataset_name($b);
push @conditions, "$name\tInput\n";
$name2done{$b} = 1; # remember it's done
}
}
# write samples file
# unfortunately, we have to write the same file multiple times for each base output
# but use the replicate-mean as an example
my $samplefile = $self->repmean_merge_base . '_samples.txt';
unless ( $self->dryrun ) {
$self->_write_specific_sample_file( \@conditions, $samplefile );
if ($self->independent) {
$self->_write_specific_sample_file( \@conditions,
$self->repmerge_merge_base . '_samples.txt' );
}
if ( $self->broad ) {
$self->_write_specific_sample_file( \@conditions,
$self->repmean_merge_base . '_broad_samples.txt' );
if ($self->independent) {
$self->_write_specific_sample_file( \@conditions,
$self->repmerge_merge_base . '_broad_samples.txt' );
}
}
}
$self->{sample_file} = $samplefile;
return $samplefile;
}
sub _write_specific_sample_file {
my ($self, $conditions, $file) = @_;
my $fh = IO::File->new( $file, "w" );
foreach my $c ( @{$conditions} ) {
$fh->print($c);
}
$fh->close;
}
sub run_generate_chr_file {
my $self = shift;
# this will work regardless if example is bam or bigWig
print "\n\n======= Generating temporary chromosome file\n";
my $chromofile = $self->chromofile;
unless ($chromofile) {
$chromofile = File::Spec->catfile( $self->dir, "chrom_sizes.temp.txt" );
$self->chromofile($chromofile);
}
if ( -e $chromofile ) {
return $chromofile;
}
print " using $chromofile\n";
unless ( $self->printchr_app or $self->dryrun ) {
croak "no print_chromosome_lengths.pl application in path!\n";
}
# check all source bam and bw files to ensure seqid consistency
my @sources;
foreach my $Job ( $self->list_jobs ) {
# a job may be just a control job and not have any bam files
# also possible that no bam files are present
if ( scalar( $Job->chip_bams ) ) {
push @sources, $Job->chip_bams;
}
elsif ( $Job->chip_bw and -e $Job->chip_bw ) {
push @sources, $Job->chip_bw;
}
if ( scalar( $Job->control_bams ) ) {
push @sources, $Job->control_bams;
}
}
# command
my $command = sprintf "%s --out %s ",
$self->printchr_app || 'print_chromosome_lengths.pl', $chromofile;
if ( $self->chrskip ) {
$command .= sprintf "--chrskip '%s' ", $self->chrskip;
}
$command .= join( q( ), @sources );
my $log = $chromofile;
$log =~ s/ \.temp \.txt /.log.txt/x;
$command .= sprintf " 2>&1 > $log";
return $self->execute_commands( [ [ $command, $chromofile, $log ] ] );
}
sub execute_commands {
my $self = shift;
my $commands = shift;
printf "Excecuting %d commands\n", scalar @{$commands};
# dry run
if ( $self->dryrun ) {
# we just go through the motions here
foreach my $command ( @{$commands} ) {
printf "=== Job: %s\n", $command->[0];
}
$self->add_command($commands);
return;
}
# execute jobs
if ( $self->job > 1 ) {
# get parallel manager
my $pm;
if ( defined $self->{pm} ) {
$pm = $self->{pm}; # make it reusable
}
else {
# initialize new instance of parallel manager
$pm = Parallel::ForkManager->new( $self->job )
or confess "unable to initiate Parallel Forkmanager!";
$self->{pm} = $pm; # make it reusable
}
# run commands
foreach my $command ( @{$commands} ) {
next if $self->_check_command_finished( $command, 1 );
printf "=== Job: %s\n", $command->[0];
# check for simple rm commands
if ( $command->[0] =~ /^rm (.+)$/ ) {
# we don't need to fork a new process just to execute a rm command
unlink( split( q( ), $1 ) );
next;
}
# fork to execute
$pm->start and next;
# in child
system( $command->[0] );
$pm->finish;
}
$pm->wait_all_children;
}
else {
foreach my $command ( @{$commands} ) {
next if $self->_check_command_finished( $command, 1 );
printf "=== Job: %s\n", $command->[0];
# check for simple rm commands
if ( $command->[0] =~ /^rm (.+)$/ ) {
# we don't need to fork a new process just to execute a rm command
unlink( split( q( ), $1 ) );
next;
}
# execute
system( $command->[0] );
}
}
# check that commands actually produced something
sleep 2;
my @errors;
foreach my $command ( @{$commands} ) {
unless ( $self->_check_command_finished( $command, 0 ) ) {
# zero status indicates something went wrong
push @errors, sprintf "=== ERROR: %s\n", $command->[0];
if ( defined $command->[2] ) {
push @errors, sprintf " See log '%s' for details\n", $command->[2];
}
}
}
if (@errors) {
print "\n\n ======= Errors ======\n";
print " The following jobs did not generate expected output\n";
foreach (@errors) {
print;
}
croak "\nCheck log files for errors\n";
}
$self->add_command($commands);
}
sub _check_command_finished {
my $self = shift;
my ( $command, $talk ) = @_;
# returns true if command appears finished
# command bits
my ( $command_string, $command_out, $command_log ) = @{$command};
# check
if ( length($command_out) and length($command_log) ) {
# both
if ( -e $command_out and -e $command_log ) {
print
"=== Job: $command_string\n previously finished, have $command_out and $command_log files\n"
if $talk;
return 1;
}
elsif ( not -e $command_out and -e $command_log ) {
# special instance where there is a log file but no output
# this can occur with specific applications so check those
if ( index( $command_string, $self->bamdedup_app ) == 0 ) {
# the deduplication command will not write out a bam file if the actual
# duplication rate is below the target rate
# presume this is good
print
"=== Job: $command_string\n presumed finished, have $command_log file only\n"
if $talk;
return 2;
}
elsif ( index( $command_string, $self->printchr_app ) == 0 ) {
# the print_chromosome_lengths script will not write output if
# sequence orders are not the same
return 0;
}
else {
# something else? catchall?
return 0;
}
}
elsif ( -e $command_out and not -e $command_log ) {
# we have a output file but not a log file
print
"=== Job: $command_string\n presumed finished, have $command_out file only, no log\n"
if $talk;
return 3;
}
}
elsif ( length($command_out) ) {
if ( -e $command_out ) {
print "=== Job: $command_string\n previously finished, have $command_out\n"
if $talk;
return 4;
}
}
elsif ( length($command_out) == 0 ) {
# no output files
if ( substr( $command_string, 0, 2 ) eq 'rm' ) {
# remove command doesn't leave an output (duh!) or log file
# gotta check each one
my $check = 0;
foreach my $item ( split /\s+/, $command_string ) {
next if $item eq 'rm';
$check++ if -e $item; # check true if file is present
}
if ( $check == 0 ) {
print
"=== Job: $command_string\n previously finished, target files missing\n"
if $talk;
return 5;
}
}
elsif ( $command_string =~ /Rscript/ ) {
# plot peaks may leave lots of files or none
if ( -e $command_log ) {
# output log file exists, presume to be finished
print
"=== Job: $command_string\n presumed finished, have $command_log file\n"
if $talk;
return 2;
}
}
}
# else presume command was not finished
return 0;
}
sub run_input_peak_detection {
my $self = shift;
return unless ( $self->exclude eq 'input' );
print "\n\n======= Generating exclusion list from reference control\n";
if ( $self->{progress}{control_peak} ) {
# check that we actually have the expected file
my $exclude_file = File::Spec->catfile(
$self->dir,
sprintf( "%s.control_peak.bed", $self->out )
);
if ( -e $exclude_file ) {
$self->exclude($exclude_file);
}
else {
$self->exclude( q() );
}
print "\nStep is completed\n";
return;
}
# available reference bam files
my @refbams;
foreach my $Job ( $self->list_jobs ) {
push @refbams, $Job->control_bams;
}
my $exclude_file;
if (@refbams) {
# we have at least one reference bam file to process
# set the name of the exclusion list file
$exclude_file =
File::Spec->catfile( $self->dir, sprintf( "%s.control_peak", $self->out ) );
}
else {
# no reference bam files!
print " No control reference bam files to process. Skipping\n";
$self->exclude('none');
$self->update_progress_file('control_peak');
return;
}
# check apps
unless ( $self->bam2wig_app =~ /\w+/ or $self->dryrun ) {
croak "no bam2wig.pl application in path!\n";
}
unless ( $self->macs_app =~ /\w+/ or $self->dryrun ) {
croak "no MACS2 application in path!\n";
}
unless ( $self->peak2bed_app =~ /\w+/ or $self->dryrun ) {
croak "no peak2bed.pl application in path!\n";
}
unless ( $self->meanbdg_app =~ /\w+/ or $self->dryrun ) {
croak "no generate_mean_bedGraph.pl application in path!\n";
}
# generate bam2wig command
# very little filtering here - we basically want everything
my $command = sprintf
"%s --out %s.bdg --nosecondary --noduplicate --nosupplementary --mean --bdg --bin %s --cpu %s ",
$self->bam2wig_app || 'bam2wig.pl',
$exclude_file,
$self->chipbin,
$self->cpu * $self->job; # give it everything we've got, single job
if ( $self->paired ) {
$command .= sprintf "--span --pe --minsize %s --maxsize %s ",
$self->minsize, $self->maxsize;
}
else {
$command .= sprintf "--extend --extval %s ", $self->fragsize;
}
if ( $self->chrskip ) {
$command .= sprintf "--chrskip \'%s\' ", $self->chrskip;
}
$command .= sprintf "--in %s ", join( ',', @refbams );
my $logfile = sprintf "%s.out.txt", $exclude_file;
$command .= " 2>&1 > $logfile ";
# add the mean bedgraph file
$command .= sprintf
" && %s --in %s.bdg --genome %d --out %s.global_mean.bdg 2>&1 >> $logfile ",
$self->meanbdg_app || 'generate_mean_bedGraph.pl',
$exclude_file,
$self->genome || 0,
$exclude_file;
# add the q-value conversion
$command .= sprintf
" && %s bdgcmp -t %s.bdg -c %s.global_mean.bdg -m qpois -o %s.qvalue.bdg 2>> $logfile ",
$self->macs_app || 'macs2',
$exclude_file,
$exclude_file,
$exclude_file;
# add the peak call
# we are using hard coded parameters for now, but these should be generic enough
$command .= sprintf
" && %s bdgpeakcall -i %s.qvalue.bdg -c 3 -l 250 -g 500 --no-trackline -o %s.narrowPeak 2>> $logfile",
$self->macs_app || 'macs2',
$exclude_file,
$exclude_file;
# execute the call
$self->execute_commands( [ [ $command, "$exclude_file.narrowPeak", $logfile ], ] );
# check whether peaks were found
if ( -e "$exclude_file.narrowPeak" and -s _ ) {
# we have identified peaks
$self->exclude( $exclude_file . '.bed' ); # set the actual output file
# convert to simple bed
$command = sprintf "%s --norm --nosummit --in %s.narrowPeak 2>&1 >> $logfile ",
$self->peak2bed_app || 'peak2bed.pl', $exclude_file;
# and clean up
$command .= sprintf
"&& rm %s.bdg %s.global_mean.bdg %s.qvalue.bdg %s.narrowPeak",
$exclude_file,
$exclude_file,
$exclude_file,
$exclude_file;
$self->execute_commands( [ [ $command, $self->exclude, $logfile ], ] );
}
else {
# no peaks were identified
print "\n No peaks were found in control\n\n";
$self->exclude( q() );
# clean up
$command = sprintf "rm %s.bdg %s.global_mean.bdg %s.qvalue.bdg ",
$exclude_file,
$exclude_file,
$exclude_file;
$command .= "$exclude_file.narrowPeak " if -e "$exclude_file.narrowPeak";
$self->execute_commands( [ [ $command, q(), q() ], ] );
}
# finished
$self->update_progress_file('control_peak');
}
sub run_dedup {
my $self = shift;
return unless ( $self->dedup );
print "\n\n======= De-duplicating bam files\n";
if ( $self->{progress}{deduplication} ) {
print "\nStep is completed\n";
return;
}
### Run de-duplication
my @commands;
my %name2done;
foreach my $Job ( $self->list_jobs ) {
push @commands, $Job->generate_dedup_commands( \%name2done );
}
if (@commands) {
$self->execute_commands( \@commands );
return if $self->dryrun;
}
else {
$self->update_progress_file('deduplication');
return;
}
### Collect deduplication statistics
my @dedupstats;
push @dedupstats, join(
"\t", qw(File TotalCount OpticalDuplicateCount DuplicateCount
NonDuplicateCount DuplicationRate RetainedDuplicateCount)
);
foreach my $c (@commands) {
# initialize counts
my $total = 0; # total count
my $optdup = 0; # optical duplicate count
my $nondup = 0; # non-duplicate count
my $dup = 0; # duplicate count
my $retdup = 0; # retained duplicate count
my $duprate = 0; # duplication rate
# open log file and collect stats
next if ( not -e $c->[2] );
my $fh = IO::File->new( $c->[2], 'r' );
while ( my $line = $fh->getline ) {
if ( $line =~ /^\s+ Total \s mapped: \s+ (\d+) $/x ) {
# bam_partial_dedup
$total = $1;
}
elsif ( $line =~ /^\s+ Non\-duplicate \s count: \s+ (\d+) $/x ) {
$nondup = $1;
}
elsif ( $line =~ /^\s+ Optical \s duplicate \s count: \s+ (\d+) $/x ) {
# optical bam_partial_dedup
$optdup = $1;
}
elsif ( $line =~ /^\s+ Non\-optical \s duplicate \s count: \s+ (\d+) $/x ) {
# non-optical bam_partial_dedup
$dup = $1;
}
elsif ( $line =~
/^\s+ Non\-optical \ duplication \s rate: \s+ (\d \. \d+) $/x )
{
# non-optical bam_partial_dedup
$duprate = $1;
}
elsif ( $line =~
/^\s+ Retained \s non\-optical \s duplicate \s count: \s+ (\d+) \s* $/x )
{
# bam_partial_dedup
# oops, there may be a space at the end
# this might not be found if no deduplication occurred
$retdup = $1;
}
}
$fh->close;
# name of bam file, extracted from log file
my ( undef, undef, $name ) = File::Spec->splitpath( $c->[2] );
$name =~ s/\.dedup \.out \.txt $//x;
# store in array
push @dedupstats,
join(
"\t", $name, $total, $optdup, $dup, $nondup, $duprate,
$retdup || $dup
);
}
# print duplicate stats file
my $dedupfile = File::Spec->catfile( $self->dir, $self->out . '.dedup-stats.txt' );
my $fh = IO::File->new( $dedupfile, 'w' );
foreach (@dedupstats) {
$fh->print("$_\n");
}
$fh->close;
print "\n Wrote deduplication report $dedupfile\n";
$self->update_progress_file('deduplication');
}
sub run_bam_filter {
my $self = shift;
# filtering the bam file is only really required when not de-duplicating and
# running independent peak calls
# both bam_partial_dedup and bam2wig include these filtration steps
# but macs2 does not
return if ( $self->dedup );
return unless ( $self->independent );
print "\n\n======= Filtering bam files\n";
if ( $self->{progress}{bamfilter} ) {
print "\nStep is completed\n";
return;
}
### Generate appended exclusion list with skipped chromosomes
my $filter_file;
if ( $self->chrskip ) {
# need to collect skipped chromosomes
# but first need to get them
# use the first ChIP bam file as an example - this should've passed
# print_chromosomes test earlier so all files have identical chromosomes
unless ( $self->dryrun ) {
# only execute this during a real run
# first add existing exclusion list intervals if present
my @exclusions;
if ( $self->exclude and $self->exclude ne 'none' ) {
my $Data = Bio::ToolBox->load_file( $self->exclude );
if ($Data) {
$Data->iterate(
sub {
# generate and store a simple bed3 string
my $row = shift;
push @exclusions, $row->bed_string( bed => 3 );
}
);
}
}
# then add unwanted chromosomes
my $example_bam;
foreach my $Job ( $self->list_jobs ) {
if ( $Job->chip_bams ) {
$example_bam = ( $Job->chip_bams )[0];
last;
}
}
my $command = sprintf "%s %s", $self->printchr_app, $example_bam;
print "\n Executing '$command'\n";
my @chroms = qx($command);
my $skip = $self->chrskip;
foreach my $c (@chroms) {
chomp $c;
my ( $seqid, $length ) = split /\t/, $c;
next unless ( $seqid and $length =~ /^\d+$/ );
if ( $seqid =~ /$skip/i ) {
push @exclusions, join( "\t", $seqid, '0', $length );
}
}
# write exclusion file
$filter_file =
File::Spec->catfile( $self->dir, $self->out . '.bamfilter.bed' );
my $fh = IO::File->new( $filter_file, 'w' );
if ($fh) {
foreach my $e (@exclusions) {
$fh->print("$e\n");
}
$fh->close;
print " Wrote $filter_file\n";
}
}
}
else {
# no chromosomes to exclude
if ( $self->exclude and $self->exclude ne 'none' ) {
# still use the exclusion file to filter if present
$filter_file = $self->exclude;
}
}
### Run filter
my @commands;
my %name2done;
foreach my $Job ( $self->list_jobs ) {
push @commands, $Job->generate_bam_filter_commands( \%name2done, $filter_file );
}
if (@commands) {
$self->execute_commands( \@commands );
}
if ( $filter_file and $filter_file ne $self->exclude and -e $filter_file ) {
unlink $filter_file;
}
$self->update_progress_file('bamfilter');
}
sub run_bam_check {
my $self = shift;
print "\n\n======= Checking bam files\n";
foreach my $Job ( $self->list_jobs ) {
$Job->find_new_bams;
}
# check for independent peak call and universal control
if ( $self->independent and $self->has_universal_control ) {
my @jobs = $self->list_jobs;
# universal control is always the first job
my $control = shift @jobs;
foreach my $Job (@jobs) {
$Job->control_use_bams( $control->control_use_bams );
}
}
}
sub run_mappable_space_report {
my $self = shift;
print "\n\n======= Determining mappable genome space\n";
# first collect all available bam files - can't run without bam files
my @bamlist;
foreach my $Job ( $self->list_jobs ) {
push @bamlist, ( $Job->control_use_bams ) || ( $Job->control_bams );
push @bamlist, ( $Job->chip_use_bams ) || ( $Job->chip_bams );
}
# next get the official genome size from the chromosome file
my $genome_size = 0;
if ( not $self->dryrun ) {
my $fh = IO::File->new( $self->chromofile, 'r' );
while ( my $line = $fh->getline ) {
if ( $line =~ /\s+(\d+)$/ ) {
$genome_size += $1;
}
}
$fh->close;
}
$self->{full_genome_size} = $genome_size;
# check the user supplied value
if ( $self->genome and not $self->dryrun and not $self->{progress}{mappable_size} ) {
# double-check the user value
my $ratio = $self->genome / $genome_size;
if ( $ratio > 1.01 ) {
printf
"\n User supplied genome size (%d) is larger than actual genome size (%d)!!!\n",
$self->genome, $genome_size;
if (@bamlist) {
print " Determining actual empirical mappable size\n";
}
}
elsif ( $ratio < 0.6 ) {
printf
"\n User supplied genome size (%d) is considerably smaller than actual genome size (%d)!\n",
$self->genome, $genome_size;
if (@bamlist) {
print " Determining actual empirical mappable size\n";
}
}
else {
# ratio is somewhere between 50-100% of actual genome size, so assume ok
printf "\n Using user-specified size of %d\n", $self->genome;
return;
}
}
elsif ( $self->genome and $self->dryrun ) {
printf "\n Pretending that user supplied genome size is ok\n";
return;
}
# Check that we have bam files to continue
unless (@bamlist) {
# use a default genome size of 90% of actual size
# this should be close enough for most eukaryotic genomes
$self->genome( int( $genome_size * 0.9 ) );
printf "\n Input Bam files are not available. Using genome size of %d\n",
$self->genome;
$self->update_progress_file('mappable_size');
return;
}
# the output logfile
my $logfile =
File::Spec->catfile( $self->dir, sprintf( "%s.mappable.out.txt", $self->out ) );
# check if command is finished, otherwise run it
if ( $self->{progress}{mappable_size} ) {
print "\nStep is completed\n";
# we will read the value below
}
else {
unless ( $self->reportmap_app =~ /\w+/ or $self->dryrun ) {
croak "no report_mappable_space.pl application in path!\n";
}
my $command = sprintf "%s --cpu %d ",
$self->reportmap_app || 'report_mappable_space.pl',
$self->cpu * $self->job;
# give the cpu everything we've got, there's only one job
if ( $self->chrskip ) {
$command .= sprintf "--chrskip \'%s\' ", $self->chrskip;
}
$command .= sprintf " %s 2>&1 > %s", join( q( ), @bamlist ), $logfile;
# execute
# the log file is the output
$self->execute_commands( [ [ $command, $logfile, $logfile ] ] );
}
# Collect results from output file
# do this regardless whether this was finished previously, since we have to
# extract the value into memory anyway
if ( -e $logfile ) {
my $fh = IO::File->new( $logfile, 'r' )
or croak " unable to open mappable report file '$logfile'!";
while ( my $line = $fh->getline ) {
# we're going to use the all mappable space number
# remember these numbers for the report
if ( $line =~
/All \s mappable \s space: \s ( \d+ \. \d+ ) \s Mb \s \( (\d+) % \)/x
) {
$self->{all_map} = ( $1 * 1000000 );
$self->{all_map_fraction} = $2;
}
elsif ( $line =~
/Unique \s mappable \s space: \s ( \d+ \. \d+ ) \s Mb \s \( (\d+) % \)/x
) {
$self->{unique_map} = $1 * 1000000;
$self->{unique_map_fraction} = $2;
next;
}
}
$fh->close;
# report and record genome size to use
unless ( exists $self->{all_map} ) {
croak "\n Unable to extract genome mappable space from report '$logfile'!\n";
}
if ( $self->mapq >= 10 ) {
printf "\n Genome mappable space calculated to be %d bp (%d%%)\n",
$self->{unique_map}, $self->{unique_map_fraction};
if ( $self->{unique_map_fraction} > 75 ) {
$self->genome( $self->{unique_map} );
}
elsif ( $self->{unique_map_fraction} > 50 ) {
$self->genome( $self->{unique_map} );
print <<END;
WARNING!!! Mapped genome fraction is less than 75%!
You should consider manually setting the genome size to a more appropriate value
using the --genome option, as this may negatively affect your background estimation
and q-value calculations.
END
}
else {
printf <<END;
WARNING!!! Mapped genome fraction is less than 50%!
This will negatively affect your background estimation and q-value calculations.
You should manually set the genome size to a more appropriate value using the
--genome option. The full size of the genome minus exclusions is calculated at
$genome_size bp. Typically mappability is ~90% of genome size.
Exiting now.
END