blib/lib/Bio/ViennaNGS/Expression.pm

filter: Statementstmt 19.6% 34 / 173 Branchbran 0.0% 0 / 24 Conditioncond n/a MC/DCmcdc n/a Subroutinesub 60.0% 9 / 15 Podpod 80.0% 4 / 5 totaltotal 21.6% 47 / 217 CC 20 SCAR 37.0
CC
20
Cov
17%
write_expression_bed12
110.0
parse_readcounts_bed12
30.0
computeTPM
12.0
CRAP 40.3
« blib/lib/Bio/ViennaNGS/FeatureIO.pm ↑ Summary blib/lib/Bio/ViennaNGS/Fasta.pm »
1 # -*-CPerl-*-
2 # Last changed Time-stamp: <2017-06-10 18:59:03 michl>
3  
4 package Bio::ViennaNGS::Expression;
5  
6 1 ▶use Bio::ViennaNGS;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 1 ▶use Moose;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 1 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 1 ▶use Data::Dumper;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 1 ▶use Path::Class;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 1 ▶use Bio::ViennaNGS::Bed;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 1 ▶use Bio::ViennaNGS::Util qw(sortbed);
Subroutine BEGIN: called CC=1 SCAR=0.0
13 1 ▶use namespace::autoclean;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 1 ▶use version; our $VERSION = version->declare("$Bio::ViennaNGS::VERSION");
Subroutine BEGIN: called CC=1 SCAR=0.0
15  
16 1 has 'readcountfile' => (
17 is => 'rw',
18 predicate => 'has_readcountfile',
19 );
20  
21 has 'data' => (
22 is => 'rw',
23 isa => 'ArrayRef',
24 0 ▶ default => sub { [] },
Subroutine __ANON__: not called CC=1 SCAR=6.9
25 1 );
26  
27 1 has 'conds' => (
28 is => 'rw',
29 isa => 'Int',
30 predicate => 'has_conds',
31 );
32  
33 1 has 'nr_features' => (
34 is => 'rw',
35 isa => 'Int',
36 predicate => 'has_features',
37 );
38  
39 sub parse_readcounts_bed12 {
40 0 ▶ my ($self,$file) = @_;
Subroutine parse_readcounts_bed12: not called CC=5 SCAR=34.0
Pod documented
41 0 my @mcData = ();
42 0 my ($i,$n) = (0)x2;
43 0 my $this_function = (caller(0))[3];
44  
45 0 ▶ croak "ERROR [$this_function] readcount / multicov file $self->readcountfile not available\n"
Branch: 1 branch
BranchTrueFalseTotal
unless -e $file 0 0 0
46 unless (-e $file);
47 0 $self->readcountfile($file);
48 0 ▶ open (RC_IN, "< $file") or croak $!;
Branch: 1 branch
BranchTrueFalseTotal
open RC_IN, "< $file" or croak($!) 0 0 0
49  
50 0 ▶ while (<RC_IN>){
Branch: 1 branch
BranchTrueFalseTotal
if (defined($_ = readline RC_IN)) 0 0 0
51 0 $n++;
52 0 chomp;
53 # 0:chr|1:start|2:end|3:name|4:score|5:strand
54 # 6:thickStart|7:thickEnd|8:itemRgb|9:blockCount|
55 # 10:blockSizes|11:blockStarts
56 0 @mcData = split(/\t/);
57 0 my $conditions = (scalar @mcData)-12; # multicov extends BED12
58 0 $self->conds($conditions);
59  
60 # NOTE: Better keep BED12 entries in a hash, generating UUIDs as
61 # keys instead of storing the same BED12 entry n times (ie for
62 # each sample) in $self->data
63  
64 0 my $bedobj = Bio::ViennaNGS::Bed->new(chromosome => $mcData[0],
65 start => $mcData[1],
66 end => $mcData[2],
67 name => $mcData[3],
68 score => $mcData[4],
69 strand => $mcData[5],
70 thickStart => $mcData[6],
71 thickEnd => $mcData[7],
72 itemRgb => $mcData[8],
73 blockCount => $mcData[9],
74 blockSizes => $mcData[10],
75 blockStarts => $mcData[11],
76 );
77 0 my $len = $bedobj->length;
78 0 my $id = sprintf("%s:%d-%d_%s_%s", $mcData[0],$mcData[1],
79 $mcData[2],$mcData[3],$mcData[5]);
80 #print "\$id: $id\n";
81 0 ▶ for ($i=0;$i<$self->conds;$i++){
Branch: 1 branch
BranchTrueFalseTotal
if ($i < $self->conds) 0 0 0
82 0 ${$self->data}[$i]{$id} = {
83 bed_entry => $bedobj,
84 length => $len,
85 count => $mcData[eval(12+$i)],
86 };
87 # print "sample $i:\n";
88 # print Dumper(${$self->data}[$i]);
89 }
90 }
91 0 $self->nr_features($n);
92 0 close(RC_IN);
93 }
94  
95 sub write_expression_bed12 {
96 0 ▶ my ($self,$item,$dest,$base_name) = @_;
Subroutine write_expression_bed12: not called CC=10 SCAR=47.0
Pod documented
97 0 my ($bedname,$bedname_u,$outfile,$feat,$i);
98 0 my $this_function = (caller(0))[3];
99  
100 0 ▶ croak "ERROR [$this_function]: $dest does not exist\n"
Branch: 1 branch
BranchTrueFalseTotal
unless -d $dest 0 0 0
101 unless (-d $dest);
102  
103 0 $bedname = $base_name.".".$item.".multicov.bed12";
104 0 $bedname_u = $base_name.".".$item.".multicov.u.bed12";
105  
106 0 $outfile = file($dest,$bedname_u);
107  
108 0 ▶ croak "ERROR [$this_function]: $self->conds not available\n"
Branch: 1 branch
BranchTrueFalseTotal
unless $self->has_conds 0 0 0
109 unless ($self->has_conds);
110  
111 0 ▶ croak "ERROR [$this_function]: $self->nr_features not available\n"
Branch: 1 branch
BranchTrueFalseTotal
unless $self->has_features 0 0 0
112 unless ($self->has_features);
113  
114 #print "=====> write_multicov: writing multicov file $bedfile with ".
115 # eval($self->nr_features)." lines and ".eval($self->conds)." conditions\n";
116  
117 # check whether each element in @{$self->data} has the same amount of entries
118 0 ▶ for($i=0;$i<$self->conds;$i++){
Branch: 1 branch
BranchTrueFalseTotal
if ($i < $self->conds) 0 0 0
119 0 my $fc = scalar keys %{$self->data->[$i]}; # of keys in %{$featCount}
120 #print "condition $i => $fc keys\n";
121 0 ▶ croak "ERROR [$this_function]: unequal element count in @{$self->data}"
Branch: 1 branch
BranchTrueFalseTotal
unless $self->nr_features == $fc 0 0 0
122 unless($self->nr_features == $fc)
123 }
124  
125 0 ▶ open (MULTICOV_OUT, "> $bedname_u") or croak $!;
Branch: 1 branch
BranchTrueFalseTotal
open MULTICOV_OUT, "> $bedname_u" or croak($!) 0 0 0
126  
127 # use BED12 data stored with condition 0 here, assuming its the same for all conditions
128 0 foreach $feat (keys %{${$self->data}[0]} ){
129 0 my @mcLine = ();
130 # retrieve BED12 line first
131 0 my $bedo = ${${$self->data}[0]}{$feat}{bed_entry};
132 0 my $bedline = $bedo->as_bed_line(12);
133 0 push @mcLine, $bedline;
134  
135 # process multicov values for all samples
136 0 ▶ for($i=0;$i<$self->conds;$i++){
Branch: 1 branch
BranchTrueFalseTotal
if ($i < $self->conds) 0 0 0
137 # print "------------> "; print "processing $i th condition "; print "<-----------\n";
138 croak "Could not find item $feat in mcSample $i\n"
139 0 ▶ unless ( defined ${${$self->data}[$i]}{$feat} );
Branch: 1 branch
BranchTrueFalseTotal
unless defined do { ${$self->data;}[$i] }->{$feat} 0 0 0
140 0 push @mcLine, ${${$self->data}[$i]}{$feat}{$item};
141  
142 }
143 #print MULTICOV_OUT join("\t",@mcLine)."\n";
144 0 my @bed12 = splice @mcLine,0,1;
145 0 print MULTICOV_OUT join("\t",@bed12)."\t";
146 0 print MULTICOV_OUT join("\t", map { sprintf "%20.4f", $_ }@mcLine),"\n";
147 }
148 0 close(MULTICOV_OUT);
149  
150 0 sortbed($bedname_u,"./",$bedname,1,undef); # sort bed file
151 }
152  
153  
154 sub computeTPM {
155 0 ▶ my ($self,$sample,$rl) = @_;
Subroutine computeTPM: not called CC=3 SCAR=24.8
Pod documented
156 0 my ($TPM,$T,$totalTPM) = (0)x3;
157 0 my ($i,$meanTPM);
158  
159 # iterate through $self->data[$i] twice:
160 # 1. for computing T (denominator in TPM formula)
161 0 foreach $i (keys %{${$self->data}[$sample]}){
162 0 my $count = ${${$self->data}[$sample]}{$i}{count};
163 0 my $length = ${${$self->data}[$sample]}{$i}{length};
164 #print "count: $count\nlength: $length\n";
165 0 $T += $count * $rl / $length;
166 }
167  
168 # 2. for computng actual TPM values
169 0 foreach $i (keys %{${$self->data}[$sample]}){
170 0 my $count = ${${$self->data}[$sample]}{$i}{count};
171 0 my $length = ${${$self->data}[$sample]}{$i}{length};
172 0 $TPM = 1000000 * $count * $rl/($length * $T);
173 0 ${${$self->data}[$sample]}{$i}{TPM} = $TPM;
174 0 $totalTPM += $TPM;
175 }
176  
177 0 $meanTPM = $totalTPM/$self->nr_features;
178  
179 #print Dumper(${$self->data}[$sample]);
180 #print "totalTPM=$totalTPM | meanTPM=$meanTPM\n";
181  
182 0 return $meanTPM;
183 }
184  
185 sub computeRPKM {
186 0 ▶ my ($self,$sample) = @_;
Subroutine computeRPKM: not called CC=3 SCAR=24.8
Pod documented
187 0 my ($R,$length,$count,$totalRPKM) = (0)x4;
188 0 my ($i,$meanRPKM);
189  
190 # iterate through $self->data[$i] twice:
191 # 1. compute the total number of reads for a sample
192 0 foreach $i (keys %{${$self->data}[$sample]}){
193 0 $R += ${${$self->data}[$sample]}{$i}{count};
194 }
195  
196 # 2. for computing actual RPKM values
197 0 foreach $i (keys %{${$self->data}[$sample]}){
198 0 $count = ${${$self->data}[$sample]}{$i}{count};
199 0 $length = ${${$self->data}[$sample]}{$i}{length};
200 0 my $RPKM = ( $count * 1000000000 ) / ( $length * $R );
201 0 ${${$self->data}[$sample]}{$i}{RPKM} = $RPKM;
202 0 $totalRPKM += $RPKM;
203 }
204 0 $meanRPKM = $totalRPKM/$self->nr_features;
205 0 return $meanRPKM;
206 }
207  
208 sub computeRPKMfromTPM {
209 0 ▶ my ($self,$sample,$rl) = @_;
Subroutine computeRPKMfromTPM: not called CC=3 SCAR=24.8
Pod undocumented
210 0 my ($R,$T,$length,$count,$totalRPKM) = (0)x5;
211 0 my ($i,$meanRPKM);
212  
213 # iterate through $self->data[$i] twice:
214 # 1. compute T (denominator in TPM formula) and total number of reads
215 0 foreach $i (keys %{${$self->data}[$sample]}){
216 0 $count = ${${$self->data}[$sample]}{$i}{count};
217 0 $length = ${${$self->data}[$sample]}{$i}{length};
218 #print "count: $count\nlength: $length\n";
219 0 $T += $count * $rl / $length;
220 0 $R += $count;
221 }
222 # print "T: $T\tR: $R\n";
223  
224 # 2. compute RPKM from TPM
225 0 foreach $i (keys %{${$self->data}[$sample]}){
226 0 my $RPKMfromTPM = ${${$self->data}[$sample]}{$i}{TPM} * ( $T * 1000 ) / ( $R * $rl);
227 0 ${${$self->data}[$sample]}{$i}{RPKMfromTPM} = $RPKMfromTPM;
228 0 $totalRPKM += $RPKMfromTPM;
229 }
230 0 $meanRPKM = $totalRPKM/$self->nr_features;
231  
232 # print Dumper(${$self->data}[$sample]);
233  
234 0 return $meanRPKM;
235 }
236  
237 1 __PACKAGE__->meta->make_immutable;
238  
239 1 1;
240 __END__
241  
242  
243 =head1 NAME
244  
245 Bio::ViennaNGS::Expression - An object oriented interface for
246 computing read-count based gene expression as TPM or RPKM
247  
248 =head1 SYNOPSIS
249  
250 use Bio::ViennaNGS::Expression;
251  
252 my $expression = Bio::ViennaNGS::Expression->new();
253  
254 # parse read counts from an extended BED12 file
255 $expression->parse_readcounts_bed12("$bed12");
256  
257 # compute normalized expression of ith sample in Transcript per
258 # Million (TPM)
259 $expression->computeTPM($i, $readlength);
260  
261 # compute normalized expression of ith sample in Reads per Kilobase
262 # per Million Reads (RPKM)
263 $expression->computeRPKM($i);
264  
265 # write extended BED12 file with normalized expression in TPM for
266 # each condition past the 12th column
267 $expression->write_expression_bed12("TPM", $dest, $basename);
268  
269 =head1 DESCRIPTION
270  
271 This module provides a L<Moose> interface for computation of gene /
272 transcript expression from read counts.
273  
274 =head1 METHODS
275  
276 =over
277  
278 =item parse_readcounts_bed12
279  
280 Title : parse_readcounts_bed12
281  
282 Usage : C<$obj-E<gt>parse_readcounts_bed12($file);>
283  
284 Function : Parses a bedtools multicov (multiBamCov) file, i.e. an
285 extended BED12 file, into an Array of Hash of Hashes data
286 structure (C<@{$self-E<gt>data}>).
287  
288 Args : C<$file> is the input file, i.e. and extended BED12 file where
289 each column past the 12th lists read counts for this bedline's
290 feature(s) for a specific sample/condition.
291  
292 Returns :
293  
294 Notes : This method evaluates the number of samples/conditions present
295 in the input, i.e. the number of columns extending the
296 canonical BED12 columns in the input multicov file and
297 populates C<$self-E<gt>conds>. Also populates
298 C<$self-E<gt>nr_features> with the number of genes/features
299 present in the input (evidently, this should be the same for
300 each sample/condition in the input).
301  
302 =item computeTPM
303  
304 Title : computeTPM
305  
306 Usage : C<$obj-E<gt>computeTPM($sample, $readlength);>
307  
308 Function : Computes expression values of each gene/feature present in
309 C<$self-E<gt>data> in I<Transcript per Million (TPM)>
310 [Wagner et.al. Theory Biosci. (2012)]. C<$self-E<gt>data>
311 is a reference to a Hash of Hashes data strqucture where
312 keys are feature names and values hold a hash that must at
313 least contain length and raw read counts. Practically,
314 C<$featCount_sample> is represented by _one_ element of
315 C<@featCount>, which is populated from a multicov file by
316 C<parse_multicov()>.
317  
318 Args : C<$sample> is the sample index of C<@{$self-E<gt>data}>. This is
319 especially handy if one is only interested in computing
320 normalized expression values for a specific sample, rather
321 than all samples in multicov BED12 file. C<$readlength> is the
322 read length of the RNA-seq sequencing experiment.
323  
324 Returns : Returns the mean TPM of the processed sample, which is
325 invariant among samples. (TPM models relative molar
326 concentration and thus fulfills the invariant average
327 criterion.)
328  
329 =item computeRPKM
330  
331 Title : computeRPKM
332  
333 Usage : C<$obj-E<gt>computeRPKM($sample);>
334  
335 Function : Computes expression values of each gene/feature present in
336 C<$self-E<gt>data> in I<Reads per Kilobase per Million
337 Reads (RPKM)>. C<$self-E<gt>data> is a reference to a Hash
338 of Hashes data structure where keys are feature names and
339 values hold a hash that must at least contain length and
340 raw read counts.
341  
342 Returns: Returns the mean RPKM of the processed sample.
343  
344 =item write_expression_bed12
345  
346 Title : write_expression_bed12
347  
348 Usage : C<$obj-E<gt>write_expression_bed12($measure,$dest,$basename);>
349  
350 Function : Writes normalized expression data to a bedtools multicov
351 (multiBamCov)-type BED12 file.
352  
353 Args : C<$measure> specifies the type in which normalized expression
354 data from C<@{$self-E<gt>data}> is dumped. Allowed values are
355 'TPM' and 'RPKM'. Corresponding TPM/RPKM values must have been
356 computed and inserted into C<@{self-E<gt>data}> beforehand by
357 C<$self-E<gt>computeTPM()> and C<$self-E<gt>computeRPKM()>,
358 respectively. C<$dest> and C<$base_name> give path and base
359 name of the output file, respectively.
360  
361 Returns : None. The output is a position-sorted extended BED12 file.
362  
363 =back
364  
365 =head1 DEPENDENCIES
366  
367 =over
368  
369 =item L<Moose>
370  
371 =item L<Carp>
372  
373 =item L<Path::Class>
374  
375 =item L<namespace::autoclean>
376  
377 =back
378  
379 =head1 SEE ALSO
380  
381 =over
382  
383 =item L<Bio::ViennaNGS>
384  
385 =item L<Bio::ViennaNGS::Bed>
386  
387 =item L<Bio::ViennaNGS::Util>
388  
389 =back
390  
391 =head1 AUTHOR
392  
393 Michael T. Wolfinger, E<lt>michael@wolfinger.euE<gt>
394  
395 =head1 COPYRIGHT AND LICENSE
396  
397 Copyright (C) 2015-2017 by Michael T. Wolfinger
398  
399 This library is free software; you can redistribute it and/or modify
400 it under the same terms as Perl itself, either Perl version 5.10.0 or,
401 at your option, any later version of Perl 5 you may have available.
402  
403 This software is distributed in the hope that it will be useful, but
404 WITHOUT ANY WARRANTY; without even the implied warranty of
405 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
406  
407 =cut
« blib/lib/Bio/ViennaNGS/FeatureIO.pm ↑ Summary blib/lib/Bio/ViennaNGS/Fasta.pm »