script/cai_codon.pl untested

filter: Statementstmt 0.0% 0 / 199 Branchbran 0.0% 0 / 62 Conditioncond 0.0% 0 / 46 MC/DCmcdc 0.0% 0 / 26 Subroutinesub 0.0% 0 / 20 Podpod 0.0% 0 / 9 totaltotal 0.0% 0 / 362 CC 17 SCAR 27.4
CC
17
Cov
0%
choose_ids
42.0
read_codons
30.0
_detect_format
20.0
CRAP 15.4
1 #!/usr/bin/env perl
2  
3 use strict;
4 use warnings;
5 use lib '../lib';
6 use Bio::CUA::CUB::Builder;
7 use Bio::CUA::CodonTable;
8 use Getopt::Long;
9 use Fcntl qw/:seek/;
10 use File::Sort qw/sort_file/;
11 use File::Temp qw/ tempfile tempdir /;
12 our $VERSION = 0.02;
13  
14 my $seqIO_pkg;
15  
16 BEGIN{
17 eval { require Bio::SeqIO; };
18  
19 if($@) # bioperl is not installed
20 {
21 require Bio::CUA::SeqIO;
22 $seqIO_pkg = 'Bio::CUA::SeqIO';
23 }else
24 {
25 $seqIO_pkg = 'Bio::SeqIO';
26 }
27 }
28  
29 my $sep = "\t"; # field separator
30 my $seqFile;
31 my $expFile;
32 my $gcId;
33 my $outFile;
34 my $select;
35 my $background;
36 my $normMethod;
37 my $minTotal; # the minimal count of an amino acid for being
38 # considered to calculate CAI parameters
39 my $help;
40  
41 GetOptions(
42 'i|seq-file=s' => \$seqFile,
43 'e|exp-file:s' => \$expFile,
44 's|select:s' => \$select,
45 'b|background:s' => \$background,
46 'o|out-file:s' => \$outFile,
47 'g|gc-id:i' => \$gcId,
48 'm|method:s' => \$normMethod,
49 'h|help!' => \$help
50 );
51  
52 &usage() if($help or !defined($seqFile));
53  
54 if($select)
55 {
56 die "option '--exp-file' is needed as option '--select' is provided:$!"
57 unless($expFile);
58 }
59  
60 $gcId ||= 1;
61 $outFile ||= '-';
62 $select ||= 'all';
63 $select = lc($select);
64 $normMethod ||= 'max';
65  
66 warn "# Step 1: tabulate codons from sequences\n";
67 my $table = Bio::CUA::CodonTable->new(-id => $gcId)
68 or die "Creating codon table failed:$!";
69 my $builder = Bio::CUA::CUB::Builder->new(
70 -codon_table => $table
71 )
72 or die "Creating analyzer failed:$!";
73  
74 # check the format of input sequences
75 my $isInputCodons = &_detect_format($seqFile);
76 my $codonListRef;
77 my ($sortedFh, $sortedExpFile);
78 if(!$isInputCodons and $expFile)
79 {
80 # sort this $expFile first
81 ($sortedFh, $sortedExpFile) = tempfile();
82 #warn "$sortedExpFile\n";
83 sort_file({
84 I => $expFile,
85 o => $sortedExpFile,
86 k => '2,2n',
87 t => "\t" # field separator
88 });
89 my $idsRef;
90 if($select eq 'all')
91 {
92 $idsRef = choose_ids($sortedFh, 'all');
93 }elsif($select < 1) # a fraction
94 {
95 my $total = num_of_lines($expFile);
96 $select = int($total * $select);
97 # largest is at the end, -r option for sort does not work
98 $idsRef = choose_ids($sortedFh, 'high', $select);
99 }elsif($select > 1) # number of genes
100 {
101 $select = int($select);
102 $idsRef = choose_ids($sortedFh, 'high', $select);
103 }else
104 {
105 die "Unknown option '$select' for --select:$!";
106 }
107
108 $codonListRef = &read_codons($seqFile,$idsRef);
109 # output_ids($idsRef,'positive');
110 }else # consider codons in all input sequences
111 {
112 $codonListRef = &read_codons($seqFile, undef, $isInputCodons);
113 }
114  
115 # now consider background data
116  
117 my $backCodonListRef;
118 if($background)
119 {
120 if(is_numeric($background))
121 {
122 die "option '--exp-file' is needed for selecting background data:$!"
123 unless($sortedFh);
124  
125 my $idsRef;
126 if($background < 1) # a fraction
127 {
128 my $total = num_of_lines($expFile);
129 $background = int($total * $background);
130 # largest is at the end, -r option for sort does not work
131 $idsRef = choose_ids($sortedFh, 'low', $background);
132 }elsif($background > 1) # number of genes
133 {
134 $background = int($background);
135 $idsRef = choose_ids($sortedFh, 'low', $background);
136 }else
137 {
138 die "Unknown option '$background' for --background:$!";
139 }
140
141 $backCodonListRef = &read_codons($seqFile,$idsRef);
142  
143 #output_ids($idsRef,'negative');
144 }elsif(-f $background) # a sequence file
145 {
146 my $isBackCodons = &_detect_format($background);
147 $backCodonListRef = &read_codons($background, undef,
148 $isBackCodons) or
149 die "reading codons from $background failed:$!";
150 }else
151 {
152 die "Unknown data '$background' for option --background:$!";
153 }
154 }
155  
156 warn "# Step 2: calculate CAIs for codons\n";
157 if($background)
158 {
159 $builder->build_b_cai($codonListRef, $backCodonListRef,
160 $minTotal, $outFile) or die "building codons' b_CAI failed:$!";
161 }else
162 {
163 $builder->build_cai($codonListRef, $minTotal, $normMethod,
164 $outFile) or
165 die "building codons' CAI failed:$!";
166 }
167  
168 # remove temporary files
169 if($sortedExpFile)
170 {
171 close $sortedFh;
172 unlink $sortedExpFile;
173 }
174  
175 warn "Work done!!\n";
176  
177 exit 0;
178  
179 sub output_ids
180 {
181 my ($hash, $name) = @_;
182  
183 open(O,"> tmp_$name") or die $!;
184 print O join("\n", keys %$hash), "\n";
185 close O;
186 }
187  
188 sub is_numeric
189 {
190 my $num = shift;
191 if($num =~ /^[+-]?[eE\d\.\-]+$/)
192 {
193 return 1;
194 }else
195 {
196 return 0;
197 }
198 }
199  
200 # get the number of lines in a file
201 sub num_of_lines
202 {
203 my ($file) = @_;
204 my $totalNum;
205 if(ref($file) eq 'GLOB')
206 {
207 $. = 0; # reset number to 0
208 my $currPos = tell($file);
209 seek($file, 0, SEEK_SET); # set to beginning
210 1 while(<$file>);
211 $totalNum = $.; # a special variable
212 seek($file,$currPos,SEEK_SET); # set back the pointer
213 }else
214 {
215 my $fh;
216 open($fh, "< $file") or die "Can not open $file:$!";
217 1 while(<$fh>);
218 $totalNum = $.; # a special variable
219 close $fh;
220 }
221 return $totalNum;
222 }
223  
224 # read codons from given sequence IDs
225 sub read_codons
226 {
227 my ($seqFile,$idsRef,$isCodons) = @_;
228 # if $idsRef is not a hash reference, all the sequences in the
229 # input file will be scanned.
230 # $isCodons tells whether $seqFile stores codon counts or not
231
232 my %codonList; # store all the codons of selected sequences
233 if($isCodons) # read codons directly
234 {
235 my $fh;
236 open($fh, "< $seqFile") or die "Can not open $seqFile:$!";
237 while(<$fh>)
238 {
239 chomp;
240 next if /^#/ or /^\s*$/;
241 my ($codon, $cnt) = split $sep;
242 $codon = uc($codon);
243 $codon =~ tr/U/T/;
244 $codonList{uc($codon)} += $cnt; # sum up the same codons
245 }
246 close $fh;
247  
248 return \%codonList;
249 }
250  
251 unless(defined($idsRef) and ref($idsRef) eq 'HASH') # no selected IDs
252 {
253 return $builder->get_codon_list($seqFile);
254 }
255  
256 my $io = $seqIO_pkg->new(-file => $seqFile, -format => 'fasta');
257 my $seqCnt = 0;
258  
259 while(my $seq = $io->next_seq)
260 {
261 next unless($idsRef->{$seq->id});
262 my $localCodons = $builder->get_codon_list($seq) or
263 (warn "Counting codons in ".$seq->id." failed\n" and next);
264 while(my ($codon, $cnt) = each %$localCodons)
265 {
266 $codonList{$codon} += $cnt;
267 }
268 $seqCnt++;
269 }
270  
271 return \%codonList;
272 }
273  
274 # choose IDs from an input file
275 sub choose_ids
276 {
277 my ($fh, $method, $cnt) = @_;
278 $method = lc($method);
279 # set the filehandle to the beginning
280 seek($fh,0,SEEK_SET);
281 my %data;
282 my $counter = 0;
283 if($method eq 'all')
284 {
285 while(<$fh>)
286 {
287 chomp;
288 my @fields = split $sep;
289 $data{$fields[0]}++;
290 }
291 # return _read_column($fh, 1);
292 }elsif($method eq 'low')
293 {
294 while(<$fh>)
295 {
296 chomp;
297 my @fields = split $sep;
298 $data{$fields[0]}++;
299 last unless(++$counter < $cnt);
300 }
301 }elsif($method eq 'high')
302 {
303 my $toSkip = num_of_lines($fh) - $cnt;
304 while(<$fh>)
305 {
306 next unless(++$counter > $toSkip);
307 chomp;
308 my @fields = split $sep;
309 $data{$fields[0]}++;
310 }
311 }else
312 {
313 die "Unknown method $method for choosing IDs in 'choose_ids':$!";
314 }
315  
316 return \%data;
317 }
318  
319 sub _read_column
320 {
321 # the $fh may not be at the beginning
322 my ($fh, $colNum, $cnt) = @_;
323 my %data;
324 while(<$fh>)
325 {
326 last if(defined($cnt) and $cnt == 0);
327 chomp;
328 my @fields = split $sep;
329 $data{$fields[$colNum - 1]}++;
330 }
331  
332 return \%data;
333 }
334  
335 sub _detect_format
336 {
337 my $file = shift;
338  
339 my $isCodons = 0;
340 my $fh;
341 open($fh, "< $file") or die "Can not open $file:$!";
342 while(<$fh>)
343 {
344 next if /^#/; # comment line
345 next if /^\s*$/;
346 $isCodons = 1 unless(/^>/); # not fasta format
347 last; # only first line is checked
348 }
349 close $fh;
350  
351 warn "# $file is in codon-count format\n";
352 return $isCodons;
353 }
354  
355 sub usage
356 {
357 print <<USAGE;
358 Usage: $0 [options]
359  
360 This program reads into fasta-formatted sequences or codon counts
361 and ouput CAI values for each codon.
362  
363 Mandatory options:
364  
365 -i/--seq-file: a file containing protein-coding sequences in fasta
366 format or a list of codon counts. The latter lists the counts of
367 codons in the format 'codon1<tab>#1' with each codon per line and
368 <tab> as the field delimiter. The program distinguishes these two
369 formats based on the first non-empty/non-comment line: if it starts
370 with '>', then the format is regarded as 'fasta', otherwise codon
371 counts are expected.
372  
373 Auxiliary options:
374  
375 -e/--exp-file: a file containing sequence IDs and their expression
376  
377 -s/--select: how many sequences are chosen for CAI calculation.
378 all = all IDs in the expression file given by --exp-file
379 0.## = the top fraction of highly expressed genes, say 0.30, then top
380 30% highly expressed genes.
381 ### = an integer such as 200, then the top 200 highly expressed
382 genes.
383 Default is 'all'.
384 This option is ignored if the input by --seq-file is codon counts.
385  
386 -b/--background: data for background codon usage estimation.
387 0.## = a fraction (e.g.,0.30) of most lowly expressed genes in the
388 expression file by --exp-file
389 ### = a number (say 200) of most lowly expressed genes in the
390 expression file.
391 filename = a file containing protein-coding sequences or a list of
392 codon counts which will be anlyzed for background codon usage. See the
393 option --seq-file for format details.
394 When this option is given, bCAI is calculated.
395  
396 -g/--gc-id: ID of genetic code table. Default is 1, i.e., the
397 standard genetic code table.
398  
399 -m/--method: method to calculate CAI. Available values are 'max'
400 (default) and 'mean'. The former calculates the standard CAI while the
401 latter calcualtes mCAI.
402  
403 -o/--out-file: the file to store the result. Default is standard output.
404  
405 -h/--help: show this help message. For more detailed information, run
406 'perldoc cai_codon.pl'
407  
408 Author: Zhenguo Zhang
409 Contact: zhangz.sci\@gmail.com
410 Created:
411 Wed Mar 4 16:42:24 EST 2015
412  
413 USAGE
414
415 exit 1;
416 }
417  
418 =pod
419  
420 =head1 NAME
421  
422 cai_codon.pl - a program to calculate CAI for each codon
423  
424 =head1 VERSION
425  
426 VERSION = 0.02
427  
428 =head1 SYNOPSIS
429  
430 This is a program to compute CAI at codon level with different
431 methods. It is part of distribution
432 L<http://search.cpan.org/dist/Bio-CUA/>
433  
434 # calculate codon CAI by choosing the top 200 highly expressed genes
435 cai_codon.pl -i seqs.fasta -e gene_expression.tsv -s 200 -o CAI_top200
436  
437 # the same as above but normalize RSCUs with expected RSCUs under even
438 # codon usage
439 cai_codon.pl -i seqs.fasta -e gene_expression.tsv -s 200 -o CAI_top200.by_mean -m mean
440  
441 # normalize RSCUs by RSCUs derived from bottom 1000 lowely expressed genes
442 cai_codon.pl -i seqs.fasta -e gene_expression.tsv -s 200 -o CAI_top200.b1000 -b 1000
443  
444 =head1 OPTIONS
445  
446 All options have a short and a long forms, e.g., -i and --seq-file for
447 first option.
448  
449 In the following text, RSCU stands for relative synonymous codon
450 usage.
451  
452 =head3 Mandatory options
453  
454 =over
455  
456 =item -i/--seq-file
457  
458 a file containing protein-coding sequences in fasta
459 format or a list of codon counts. The latter lists the counts of
460 codons in the format 'codon1<tab>#1' with each codon per line and
461 <tab> as the field delimiter. The program distinguishes these two
462 formats based on the first non-empty/non-comment line: if it starts
463 with '>', then the format is regarded as 'fasta', otherwise codon
464 counts are expected.
465  
466 =back
467  
468 =head3 Auxiliary options
469  
470 =over
471  
472 =item -e/--exp-file
473  
474 a file containing sequence IDs and their expression in the forllowing
475 format:
476  
477 seq-id1E<lt>tabE<gt>0.67
478 seq-id2E<lt>tabE<gt>2.57
479 ... ...
480  
481 each line contains one sequence ID and the sequence's gene expression
482 level (RNA, protein, or else), separated by tab. The sequence IDs
483 must match the IDs in the sequence file specified above.
484  
485 From this file, highly expressed genes will be selected according to
486 the gene expression rank. See below options.
487  
488 If this option is omitted, all the sequences in the above sequence
489 file would be used for calculating CAIs.
490  
491 =item -s/--select
492  
493 determine how many sequences are chosen from the above expression
494 file (by option --exp-file). Available formats are:
495  
496 I<all>, all IDs in the expression file are chosen.
497  
498 I<0.##>, a fraction of top highly expressed genes, say 0.30, then top
499 30% highly expressed genes are chosen.
500  
501 I<###>, an integer, say 200, then the top 200 highly expressed genes
502 are chosen.
503  
504 Default is I<all>. If the option --exp-file is omitted, this option
505 has no effect.
506  
507 =item -b/--background
508  
509 specify background data (e.g., lowly expressed
510 genes) from which the background codon usage is derived. Then each
511 codon's RSCU from highly expressed genes is divided by the codon's
512 RSCU from the background data; these normalized RSCUs are used for CAI
513 calculation. This method is termed 'background-normalization'.
514  
515 How to specify background data: I<0.##>, I<###>, or I<filename>, the
516 former two formats choose a fraction
517 of or a number of genes from the most lowly expressed genes specified
518 in the expression file by --exp-file. See option --select for details
519 of the two specification formats. The last format specifies a
520 fasta-formatted sequence file containing protein-coding sequences or a list of
521 codon counts which will be anlyzed for background codon usage. See the
522 option --seq-file for format details.
523 When this option is given, bCAI is calculated.
524  
525 =item -g/--gc-id
526  
527 ID of genetic code table. See L<NCBI genetic code|
528 http://www.ncbi.nlm.nih.gov/Taxonomy/taxonomyhome.html/index.cgi?chapter=cgencodes>
529 for valid IDs. Default is 1, i.e., standard genetic code.
530  
531 =item -m/--method
532  
533 method to calculated CAI: I<max> or I<mean>.
534 The former is used by <Sharp and Li, 1987, NAR>, in which each codon's
535 RSCU is divided by the maximum of all synonymous codons to derive CAI.
536 The 'mean' method divides each codon's RSCU by the expected RSCU under
537 even codon usage to get CAI. For example, for an amino acid with four synonymous
538 codons, the expected RSCU is 0.25 for each codon, so all observed
539 RSCUs of this amino acid's codons are divided by 0.25. These two
540 choices produce CAI and mCAI, respectively.
541  
542 If option C<--background> is activated, the 'background-normalization'
543 method always uses the I<max> method to get final CAIs.
544  
545 =item -o/--out-file
546  
547 file to store the result. Default is standard output, usually screen.
548  
549 =back
550  
551 =head1 AUTHOR
552  
553 Zhenguo Zhang, C<< <zhangz.sci at gmail.com> >>
554  
555 =head1 BUGS
556  
557 Please report any bugs or feature requests to C<bug-bio-cua at
558 rt.cpan.org> or through the web interface at
559 L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Bio-CUA>. I will be
560 notified, and then you'll automatically be notified of progress on
561 your bug as I make changes.
562  
563 =cut
564  
565 =head1 SUPPORT
566  
567 You can find documentation for this class with the perldoc command.
568  
569 perldoc Bio::CUA
570  
571 You can also look for information at:
572  
573 =over 4
574  
575 =item * RT: CPAN's request tracker (report bugs here)
576  
577 L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Bio-CUA>
578  
579 =item * AnnoCPAN: Annotated CPAN documentation
580  
581 L<http://annocpan.org/dist/Bio-CUA>
582  
583 =item * CPAN Ratings
584  
585 L<http://cpanratings.perl.org/d/Bio-CUA>
586  
587 =item * Search CPAN
588  
589 L<http://search.cpan.org/dist/Bio-CUA/>
590  
591 =back
592  
593  
594 =head1 ACKNOWLEDGEMENTS
595  
596  
597 =head1 LICENSE AND COPYRIGHT
598  
599 Copyright 2015 Zhenguo Zhang.
600  
601 This program is free software: you can redistribute it and/or modify
602 it under the terms of the GNU General Public License as published by
603 the Free Software Foundation, either version 3 of the License, or
604 (at your option) any later version.
605  
606 This program is distributed in the hope that it will be useful,
607 but WITHOUT ANY WARRANTY; without even the implied warranty of
608 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
609 GNU General Public License for more details.
610  
611 You should have received a copy of the GNU General Public License
612 along with this program. If not, see L<http://www.gnu.org/licenses/>.
613  
614 =cut
615