blib/lib/Bio/Tradis/CombinePlots.pm untested

filter: Statementstmt 0.0% 0 / 194 Branchbran 0.0% 0 / 32 Conditioncond 0.0% 0 / 11 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 24 Podpod 0.0% 0 / 15 totaltotal 0.0% 0 / 276 CC 17 SCAR 31.7
CC
17
Cov
0%
combine
90.0
_unzip_plots
12.0
_parse_line
6.0
CRAP 23.8
1 package Bio::Tradis::CombinePlots;
2 $Bio::Tradis::CombinePlots::VERSION = '1.4.1';
3 # ABSTRACT: Combine multiple plotfiles and generate updated statistics for the combined files
4  
5  
6 use Moose;
7 use strict;
8 use warnings;
9 use File::Temp;
10 use File::Path qw( remove_tree );
11 use Data::Dumper;
12 use Cwd;
13 use Bio::Tradis::Analysis::Exceptions;
14  
15 has 'plotfile' => ( is => 'rw', isa => 'Str', required => 1 );
16 has 'combined_dir' => ( is => 'rw', isa => 'Str', default => 'combined' );
17 has '_plot_handle' => (
18 is => 'ro',
19 isa => 'FileHandle',
20 required => 0,
21 lazy => 1,
22 builder => '_build__plot_handle'
23 );
24 has '_stats_handle' => (
25 is => 'ro',
26 isa => 'FileHandle',
27 required => 0,
28 lazy => 1,
29 builder => '_build__stats_handle'
30 );
31 has '_ordered_plot_ids' => (
32 is => 'rw',
33 isa => 'ArrayRef',
34 required => 0,
35 lazy => 1,
36 builder => '_build__ordered_plot_ids'
37 );
38 has '_destination' => (
39 is => 'rw',
40 isa => 'Str',
41 required => 0,
42 lazy => 1,
43 builder => '_build__destination'
44 );
45  
46 sub _build__destination {
47 my $tmp_dir = File::Temp->newdir( DIR=> getcwd, CLEANUP => 0 );
48 return $tmp_dir->dirname;
49 }
50  
51 sub _build__stats_handle {
52 my ($self) = @_;
53 my $filelist = $self->plotfile;
54 $filelist =~ s/([^\/]+$)//;
55 my $filename = $1;
56 $filename =~ s/[^\.]+$/stats/;
57 open( my $stats, ">", $filename );
58 return $stats;
59 }
60  
61 sub _build__plot_handle {
62 my ($self) = @_;
63 my $plot = $self->plotfile;
64 open( my $plot_h, "<", $plot );
65 return $plot_h;
66 }
67  
68 sub _build__ordered_plot_ids {
69 my ($self) = @_;
70 my $filelist = $self->plotfile;
71  
72 my @id_order = `awk '{print \$1}' $filelist`;
73 foreach my $id (@id_order) {
74 chomp($id);
75 }
76 return \@id_order;
77 }
78  
79 sub combine {
80 my ($self) = @_;
81 my $ordered_keys = $self->_ordered_plot_ids;
82 my $plot_handle = $self->_plot_handle;
83 my $combined_dir = $self->combined_dir;
84  
85 $self->_write_stats_header;
86  
87  
88 system("mkdir $combined_dir") unless ( -d "$combined_dir" );
89 my @tabix_plot;
90  
91 while ( my $line = <$plot_handle> ) {
92 #parse line into hash. keys = id, len, files. unzips files if needed.
93 my %plothash = $self->_parse_line($line);
94 my $id = $plothash{'id'};
95  
96 #create output plot file
97 my $comb_plot_name = "$combined_dir/$id.insert_site_plot";
98 my $filelen = $plothash{'len'};
99 my ( @currentlines, $this_line );
100  
101 my @full_plot;
102 foreach my $i ( 0 .. $filelen ) {
103 @currentlines = ();
104  
105 foreach my $curr_fh ( @{ $plothash{'files'} } ) {
106 $this_line = <$curr_fh>;
107 push( @currentlines, $this_line ) if( defined $line && $line ne "");
108 }
109  
110 my $comb_line = $self->_combine_lines( \@currentlines );
111  
112 my $plot_values_tabix = $comb_line;
113 $plot_values_tabix =~ s/\s/\t/ if(defined $plot_values_tabix && $plot_values_tabix ne "");
114  
115 my $tabix_line;
116 if ($id !~ m/^zip_combined/) {
117 my $tabix_line = "$id\t$i\t" . $plot_values_tabix if( defined $plot_values_tabix && $plot_values_tabix ne "");
118 push( @tabix_plot, $tabix_line ) if( $comb_line ne "");
119 }
120  
121 push(@full_plot, $comb_line) if ( $comb_line ne '' );
122 }
123  
124 open( CPLOT, '>', $comb_plot_name );
125 print CPLOT join("\n", @full_plot);
126 close(CPLOT);
127  
128 $self->_write_stats($id, $filelen);
129 system("gzip -f $comb_plot_name");
130 }
131  
132  
133 if (@tabix_plot) {
134 $self->_prepare_and_create_tabix_for_combined_plots(\@tabix_plot);
135 }
136  
137 File::Temp::cleanup();
138 # double check tmp dir is deleted. cleanup not working properly
139 remove_tree($self->_destination);
140 return 1;
141 }
142  
143 sub _prepare_and_create_tabix_for_combined_plots {
144  
145 my ($self, $tabix_plot) = @_;
146  
147 my $tabix_plot_name = "combined/tabix.insert_site_plot.gz";
148 my $sorted_tabix_plot_name = "combined/tabix_sorted.insert_site_plot.gz";
149  
150 open(my $tabix_plot_fh , '|-', " gzip >". $tabix_plot_name) or warn "Couldn't create the initial plot file for tabix";
151 print $tabix_plot_fh join( "\n", @{ $tabix_plot } );
152 close($tabix_plot_fh);
153  
154 `cat $tabix_plot_name | gunzip - | sort -k1,1 -k2,2n | bgzip > $sorted_tabix_plot_name && tabix -b 2 -e 2 $sorted_tabix_plot_name`;
155 unlink($tabix_plot_name);
156  
157 }
158  
159  
160 sub _parse_line {
161 my ( $self, $line ) = @_;
162 chomp $line;
163 my @fields = split( /\s+/, $line );
164 my $id = shift @fields;
165 my @files = @{ $self->_unzip_plots(\@fields) };
166 my $len = $self->_get_file_len( \@files );
167 if ( $len == 0 ){
168 die "\nPlots with ID $id not of equal length.\n";
169 }
170 #build file handles for each file
171 my @file_hs;
172 foreach my $f (@files){
173 open(my $fh, "<", $f);
174 push(@file_hs, $fh);
175 }
176 return ( id => $id, len => $len, files => \@file_hs );
177 }
178  
179 sub _get_file_len {
180 my ( $self, $files ) = @_;
181  
182 #check all files are of equal lens and return len if true
183 #wc misses last line - return $l++
184 my @lens;
185 for my $f ( @{$files} ) {
186 my $wc = `wc $f | awk '{print \$1}'`;
187 chomp $wc;
188 push( @lens, $wc );
189 }
190  
191 my $l = shift @lens;
192 for my $x (@lens) {
193 return 0 if ( $x != $l );
194 }
195 return $l+1;
196 }
197  
198 sub _combine_lines {
199 my ( $self, $lines ) = @_;
200  
201 my @totals = ( 0, 0 );
202 foreach my $l ( @{$lines} ) {
203 if(!defined($l)){
204 return "";
205 next;
206 }
207 my @cols = split( /\s+/, $l );
208 $totals[0] += $cols[0];
209 $totals[1] += $cols[1];
210 }
211 return join( " ", @totals );
212 }
213  
214 sub _write_stats_header {
215 my ($self) = @_;
216 my @fields =
217 ( "ID", "Sequence Length", "Unique Insertion Sites", "Seq Len/UIS" );
218 print { $self->_stats_handle } join( ",", @fields ) . "\n";
219 return 1;
220 }
221  
222 sub _write_stats {
223 my ( $self, $id, $seq_len ) = @_;
224 my $combined_dir = $self->combined_dir;
225 my $comb_plot = "$combined_dir/$id.insert_site_plot";
226  
227 #my $seq_len = `wc $comb_plot | awk '{print \$1}'`;
228 #chomp($seq_len);
229 my $uis = `grep -c -v "0 0" $comb_plot`;
230 chomp($uis);
231 my $sl_per_uis = "NaN";
232 $sl_per_uis = $seq_len / $uis if($uis > 0);
233  
234 my $stats = "$id,$seq_len,$uis,$sl_per_uis\n";
235 print { $self->_stats_handle } $stats;
236  
237 return 1;
238 }
239  
240 sub _abs_path_list {
241 my ( $self, $files ) = @_;
242 my $plot_path = $self->_get_plotfile_path;
243  
244 my @pathlist;
245 foreach my $f ( @{$files} ) {
246 if ( $f =~ /^\// ) { push( @pathlist, $f ); }
247 else { push( @pathlist, $plot_path . $f ); }
248 }
249 return \@pathlist;
250 }
251  
252 sub _get_plotfile_path {
253 my ($self) = @_;
254 my $plotfile = $self->plotfile;
255  
256 my @dirs = split( '/', $plotfile );
257 pop(@dirs);
258 my $path2plot = join( '/', @dirs );
259 return "$path2plot/";
260 }
261  
262 sub _is_gz {
263 my ( $self, $plotname ) = @_;
264  
265 if ( $plotname =~ /\.gz$/ ) {
266 return 1;
267 }
268 else {
269 return 0;
270 }
271 }
272  
273 sub _unzip_plots {
274 my ( $self, $files ) = @_;
275 my $destination_directory = $self->_destination;
276  
277 my @filelist = @{ $self->_abs_path_list($files) };
278 my @unz_plots;
279 foreach my $plotname ( @filelist ) {
280 Bio::Tradis::Analysis::Exceptions::FileNotFound->throw("Cannot find $plotname\n") unless ( -e $plotname );
281 if ( $self->_is_gz($plotname) ) {
282 $plotname =~ /([^\/]+$)/;
283 my $unz = $1;
284 $unz =~ s/\.gz//;
285 my $unzip_cmd = "gunzip -c $plotname > $destination_directory/$unz";
286 system($unzip_cmd);
287 push(@unz_plots, "$destination_directory/$unz");
288 }
289 else {
290 push(@unz_plots, $plotname);
291 }
292 }
293 return \@unz_plots;
294 }
295  
296 __PACKAGE__->meta->make_immutable;
297 no Moose;
298 1;
299  
300 __END__
301  
302 =pod
303  
304 =encoding UTF-8
305  
306 =head1 NAME
307  
308 Bio::Tradis::CombinePlots - Combine multiple plotfiles and generate updated statistics for the combined files
309  
310 =head1 VERSION
311  
312 version 1.4.1
313  
314 =head1 SYNOPSIS
315  
316 Takes a tab-delimited file with an ID as the first column followed by
317 a list of plotfiles to combine per row. The ID will be used to name the new
318 plotfile and as an identifier in the stats file, so ensure these are unique.
319  
320 For example, an input file named plots_to_combine.txt:
321  
322 tradis1 plot1.1.gz plot1.2.gz plot1.3.gz
323 tradis2 plot2.1.gz plot2.2.gz
324 tradis3 plot3.1.gz plot3.2.gz plot3.3.gz plot3.4.gz
325  
326 will produce
327  
328 =over
329  
330 1. a directory named combined with 3 files - tradis1.insertion_site_plot.gz,
331 tradis2.insertion_site_plot.gz, tradis3.insertion_site_plot.gz
332 2. a stats file named plots_to_combine.stats
333  
334 =back
335  
336 =head1 USAGE
337  
338 use Bio::Tradis::CombinePlots;
339
340 my $pipeline = Bio::Tradis::CombinePlots->new(plotfile => 'abc');
341 $pipeline->combine;
342  
343 =head1 AUTHOR
344  
345 Carla Cummins <path-help@sanger.ac.uk>
346  
347 =head1 COPYRIGHT AND LICENSE
348  
349 This software is Copyright (c) 2013 by Wellcome Trust Sanger Institute.
350  
351 This is free software, licensed under:
352  
353 The GNU General Public License, Version 3, June 2007
354  
355 =cut