blib/lib/Bio/fastAPD.pm

filter: Statementstmt 92.4% 245 / 265 Branchbran 90.7% 69 / 76 Conditioncond 66.6% 2 / 3 MC/DCmcdc 0.0% 0 / 2 Subroutinesub 96.4% 27 / 28 Podpod 0.0% 0 / 13 totaltotal 88.6% 343 / 387 CC 52 SCAR 18.4
CC
52
Cov
92%
_qc_symbols
17.9
initialize
8.0
_create_alpha_mask
6.4
CRAP 6.3
↑ Summary
1 # Bio::fastAPD module
2 #
3 # Authors: Joseph D. Baugher, Phd, Fernando J. Pineda, PhD
4 # Maintainer: Joseph D. Baugher, PhD (<joebaugher@hotmail.com>)
5 #
6 # Copyright (c) 2014,2015 Joseph D. Baugher (<joebaugher@hotmail.com>). All rights reserved.
7 #
8 # This module is free software; you can redistribute it and/or
9 # modify it under the same terms as Perl itself. See L<perlartistic>.
10 #
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
14  
15 =head1 NAME
16  
17 Bio::fastAPD -- rapid calculation of average pairwise difference (APD) for multiple sequence alignments
18  
19 =head1 VERSION
20  
21 Version 1.10.0
22  
23 =head1 SYNOPSIS
24  
25 use Bio::fastAPD;
26
27 my $file_name = "example_data.fasta";
28 open(my $input_fh, '<', $file_name) or croak ("Could not open $file_name\n");
29 chomp(my @fasta_lines = <$input_fh>);
30 close $input_fh;
31  
32 # Create an array of aligned sequences
33 my @sequences;
34 my $curr_seq;
35 foreach my $line (@fasta_lines) {
36 if (substr($line, 0, 1) eq ">") {
37 if ($curr_seq) { push(@sequences, $curr_seq) }
38 $curr_seq = ();
39 }
40 else { $curr_seq .= $line }
41 }
42 if ($curr_seq) { push(@sequences, $curr_seq) }
43
44 my $fastAPD_obj = Bio::fastAPD->new();
45 $fastAPD_obj->initialize(seq_array_ref => \@sequences,
46 alphabet => 'dna');
47  
48 my $apd = $fastAPD_obj->apd('gap_base');
49
50 my $std_err = $fastAPD_obj->std_err('gap_base');
51  
52 my $num_reads = $fastAPD_obj->n_reads;
53 my $num_positions = $fastAPD_obj->width;
54
55 print join("\t", qw(File APD StdErr Positions Reads)), "\n";
56 print join("\t", $file_name, $apd, $std_err, $num_positions, $num_reads), "\n";
57  
58 # OR
59  
60 use Bio::fastAPD;
61 use Bio::AlignIO;
62  
63 my $file_name = 'example_data.fasta';
64 my $alignio_obj = Bio::AlignIO->new( -file => $file_name,
65 -format => 'fasta',
66 -alphabet => 'dna');
67 my $aln_obj = $alignio_obj->next_aln();
68
69 # Create an array of aligned sequences
70 my @sequences;
71 foreach my $seq_obj ($aln_obj->each_seq) { push(@sequences, $seq_obj->seq()) }
72
73 my $fastAPD_obj = Bio::fastAPD->new();
74 $fastAPD_obj->initialize(seq_array_ref => \@sequences,
75 alphabet => 'dna');
76
77 my $apd = $fastAPD_obj->apd('gap_base');
78
79 my $std_err = $fastAPD_obj->std_err('gap_base');
80
81 my $num_reads = $fastAPD_obj->n_reads;
82 my $num_positions = $fastAPD_obj->width;
83
84 print join("\t", qw(File APD StdErr Positions Reads)), "\n";
85 print join("\t", $file_name, $apd, $std_err, $num_positions, $num_reads), "\n";
86
87 =head1 DESCRIPTION
88  
89 The Bio::fastAPD module provides a computationally efficient method for the calculation of
90 average pairwise difference (APD), a measure of nucleotide diversity, from multiple
91 sequence alignment (MSA) data. This module also provides rapid standard error estimation
92 of the APD using an efficient jackknife resampling method. Further description of the
93 methods implemented in this module, including mathematical justification, will be
94 available in an upcoming peer-reviewed journal article.
95
96 =head1 CONSTRUCTOR
97  
98 my $fastAPD_obj = Bio::fastAPD->new();
99  
100 =head1 INITIALIZER
101  
102 The initialization subroutine accepts a reference to an array of sequence reads from a
103 multiple sequence alignment. It accepts alphabet designations of 'dna', 'rna' or
104 'protein'. In order to ignore specific positions in the sequence alignment a binary mask
105 variable may be supplied consisting of a string of 1's (evaluate) and 0's (ignore)
106 of length equal to the length of the alignment. By default, all positions in the
107 alignment are evaluated.
108  
109 Acceptable characters -
110  
111 'dna' - ACGT, 'N' for missing base, '-', '~', or '.' for gaps (alignment padding)
112  
113 'rna' - ACGU, 'N' for missing base, '-', '~', or '.' for gaps (alignment padding)
114  
115 'protein' - ACDEFGHIKLMNPQRSTVWY, '*' for stop codon, 'X' for missing amino acid,
116 '-', '~', or '.' for gaps (alignment padding)
117  
118 $fastAPD_obj->initialize(-seq_ref => \@sequences,
119 -alphabet => 'dna',
120 -mask => $mask);
121  
122 =head1 OBJECT METHODS
123  
124 Additional info in the Appendix.
125  
126 fastAPD_obj->apd('gap_base')
127
128 # Perform rapid APD calculation.
129
130 fastAPD_obj->std_err('gap_base')
131
132 # Estimate standard error of the APD result.
133
134 fastAPD_obj->gap_threshold()
135  
136 # Set or get max proportion of gap symbols (-,~,.) allowable for a valid position
137  
138 fastAPD_obj->null_threshold()
139  
140 # Set or get max proportion of N symbols allowable for a valid position
141  
142 fastAPD_obj->end_threshold()
143  
144 # Set or get max proportion of ragged end (-,~,.) symbols allowable for a valid position
145  
146 fastAPD_obj->n_reads()
147  
148 # Get the number of reads
149  
150 fastAPD_obj->n_valid_positions()
151  
152 # Get the number of positions in the alignment which meet the analysis criteria
153
154 fastAPD_obj->valid_positions()
155  
156 # Get the positions in the alignment which meet the analysis criteria
157  
158 fastAPD_obj->width()
159  
160 # Get the width of the alignment
161  
162 fastAPD_obj->freqs()
163  
164 # Get the frequencies of each symbol at each position
165  
166 fastAPD_obj->consensus_alignment()
167  
168 # Get the consensus sequence of the aligned input sequences
169  
170 =head1 AUTHORS
171  
172 Joseph D. Baugher, PhD <joebaugher@hotmail.com>
173 Fernando J. Pineda, PhD <fernando.pineda@jhu.edu>
174  
175 =head1 MAINTAINER
176  
177 Joseph D. Baugher, PhD <joebaugher@hotmail.com>
178  
179 =head1 LICENSE AND COPYRIGHT
180  
181 Copyright (c) 2014 Joseph D. Baugher (<joebaugher@hotmail.com>). All rights reserved.
182  
183 This module is free software; you can redistribute it and/or
184 modify it under the same terms as Perl itself. See L<perlartistic>.
185
186 This program is distributed in the hope that it will be useful,
187 but WITHOUT ANY WARRANTY; without even the implied warranty of
188 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
189  
190 =head1 APPENDIX
191  
192 The following documentation describes the Bio::fastAPD module implementation.
193  
194 =cut
195  
196 package Bio::fastAPD;
197  
198 2 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
199 2 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
200 2 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
201 2 ▶use 5.8.8;
Subroutine BEGIN: called CC=1 SCAR=0.0
202 2 our $VERSION = '1.10.0';
203  
204 # ----------------------------------------
205 # symbols & matrices
206 # ----------------------------------------
207  
208 2 my $_null; # null symbol
209 my $_gap; # gap symbol
210 2 my $_end; # symbol for leading or trailing gaps or nulls due to read length
211 2 my $_gap_null; # gap and null symbols
212 2 my @_residues; # residues array
213 2 my $_residues; # residues string
214 2 my @_alphabet; # alphabet array
215 2 my $_alphabet; # alphabet string
216 2 my @_observed_symbols; # all symbols found in the alignment
217 2 my $_residues_and_gap; # all symbols except null
218 2 my @_mask; # binary mask defining which positions to analyze
219 2 my %_alpha_mask; # binary mask hash defining which symbols to compare
220  
221 # ----------------------------------------
222 # diversity and error calculation variables
223 # ----------------------------------------
224 2 my $_comparison_type; # gap_base - pairwise deletion
225 # - valid comparisons = base_base and gap_base
226 # base_base - pairwise deletion
227 # - valid comparisons = base_base only
228 # complete_del - complete deletion
229 # - positions containing any missing data ignored
230 2 my $_alphabet_type; # 'dna', 'rna', or 'protein'
231  
232 2 my $_K; # number of reads in the alignment
233 2 my $_W; # width (number of columns) of the alignment
234 2 my @_freq; # symbol frequencies in the alignment
235 2 my @_valid_positions; # positions in the alignment which meet the analysis criteria
236 2 my $_gap_threshold; # max proportion of gap symbols allowable for a valid position
237 2 my $_null_threshold; # max proportion of N symbols allowable for a valid position
238 2 my $_end_threshold; # max proportion of ragged end symbols allowable for a valid position
239  
240 # ----------------------------------
241 # new -- initialize symbols and matrices
242 # ----------------------------------
243 2 my %_options=();
244  
245 =pod
246  
247 B<new>
248  
249 Title : new
250 Usage : my $fastAPD_obj = Bio::fastAPD->new()
251 Function: Creates a Bio::fastAPD object
252 Returns : A blessed reference
253 Args : No arguments
254  
255 =cut
256  
257 sub new
258 6 ▶{
Subroutine new: called CC=1 SCAR=0.0
Pod undocumented
259 6 my $self = shift;
260  
261 6 $_gap_threshold = 1;
262 6 $_null_threshold = 1;
263 6 $_end_threshold = 1;
264
265 6 return bless{};
266 }
267  
268 # ----------------------------------
269 # initialize new diversity calculation
270 # ----------------------------------
271 2 my @_read_buffer; # holds preprocessed read strings
272  
273 =pod
274  
275 B<initialize>
276  
277 Title : initialize
278 Usage : $fastAPD_obj->initialize(seq_ref => \@sequences,
279 alphabet => 'dna',
280 mask => $mask);
281 Function: Initializes a Bio::fastAPD object.
282 1. Initializes internal variables.
283 2. Prepares sequence reads for analysis.
284 3. Counts symbol frequencies.
285 4. Performs quality checks for erroneous symbols
286 5. Defines valid positions for analysis
287 Returns :
288 Args : -seq_ref => \@sequences
289 a reference to an array of sequences from an MSA
290 -alphabet => 'dna'
291 Alphabet designations of 'dna', 'rna' or 'protein'.
292
293 Acceptable characters -
294 'dna' - 'ACGT', 'N' for missing base, '-', '~', or '.' for gaps(padding)
295 'rna' - 'ACGU', 'N' for missing base, '-', '~', or '.' for gaps(padding)
296 'protein' - 'ACDEFGHIKLMNPQRSTVWY', '*' for stop codon, 'X' for missing
297 amino acid, '-', '~', or '.' for gaps (alignment padding)
298 -mask => $mask
299 In order to ignore specific positions in the sequence alignment a mask
300 variable should be created consisting of a string of 1's (evaluate) and 0's
301 (ignore) of length equal to the length of the alignment. By default, all
302 positions in the alignment are evaluated.
303 Calls : _standardize_the_read, _accumulate_symbol_frequencies, _qc_symbols,
304 _define_valid_positions
305  
306 =cut
307  
308 6 ▶sub initialize {
Subroutine initialize: called CC=8 SCAR=20.8
Pod undocumented
309 6 my $self = shift;
310 6 my %args = @_;
311 6 my $seq_array_ref = $args{seq_array_ref};
312 6 $_alphabet_type = $args{alphabet};
313 6 my $mask = $args{mask};
314  
315 6 ▶ if($_alphabet_type eq 'dna') {
Branch: 3 branches
BranchTrueFalseTotal
if ($_alphabet_type eq 'dna') { } 4 2 6
elsif ($_alphabet_type eq 'rna') { } 1 1 2
elsif ($_alphabet_type eq 'protein') { } 1 0 1
316 4 $_null = 'N';
317 4 @_residues = qw(A C G T);
318 }
319 elsif($_alphabet_type eq 'rna') {
320 1 $_null = 'N';
321 1 @_residues = qw(A C G U);
322 }
323 elsif($_alphabet_type eq 'protein') {
324 1 $_null = 'X';
325 1 @_residues = qw(A C D E F G H I K L M N P Q R S T V W Y *);
326 }
327 else {
328 0 $_alphabet_type = 'dna';
329 0 $_null = 'N';
330 0 @_residues = qw(A C G T);
331 }
332 6 $_gap = '-~.';
333 6 $_end = '#';
334 6 $_gap_null = $_gap.$_null;
335 6 $_residues = join '',@_residues;
336  
337 # reset variables
338 6 $_K = 0;
339 6 $_W = 0;
340 6 @_valid_positions = ();
341
342 # load the read buffer with standardized reads
343 # and count the positions ($_W) and rows ($_K) in the alignment
344 6 @_read_buffer = ();
345 6 foreach my $seq_string (@$seq_array_ref) {
346 72 $_read_buffer[$_K] = _standardize_the_read($seq_string);
347 72 $_K++;
348 }
349
350 6 _accumulate_symbol_frequencies();
351  
352 # detect which of the possible gap symbols is present
353 6 foreach my $symbol (@_observed_symbols) {
354 47 ▶ if($symbol =~ /[$_gap]/) { $_gap = $symbol }
Branch: 1 branch
BranchTrueFalseTotal
if ($symbol =~ /[$_gap]/) { } 4 43 47
355 43 else{ $_gap = "-" }
356 }
357  
358 6 $_gap_null = $_gap.$_null;
359 6 $_residues_and_gap = $_residues.$_gap;
360 6 @_alphabet = sort (@_residues, $_gap, $_null, $_end);
361 6 $_alphabet = join("", @_alphabet);
362  
363 6 _qc_symbols();
364  
365 # populate the analysis mask array: 0 = skip; 1 = analyze; (default = analyze all positions)
366 6 ▶ if ($mask) { @_mask = split(//,$mask) }
Branch: 1 branch
BranchTrueFalseTotal
if ($mask) { } 1 5 6
367 5 else { @_mask = (1) x $_W }
368
369 6 _define_valid_positions();
370 }
371  
372 # ----------------------------------
373 # processing and analysis functions
374 # ----------------------------------
375  
376 =pod
377  
378 B<_standardize_the_read>
379  
380 Title : _standardize_the_read
381 Usage : $standardized_seq_string = _standardize_the_read($seq_string);
382 Function: Replaces ragged end (-) padding symbols with (#) symbols to differentiate
383 between internal gaps. Converts all symbols to uppercase.
384 Returns : A variable containing the standardized sequence
385 Args : A variable containing the input sequence
386  
387 =cut
388  
389 72 ▶sub _standardize_the_read {
Subroutine _standardize_the_read: called CC=3 SCAR=11.0
390 72 my $seq_string = shift;
391 72 $_W = length($seq_string); # width of the alignment (should be the same for all reads in the alignment)
392  
393 # 1) trim leading nonresidue symbols with end symbol (because could be masked or padded with gaps)
394 72 my ($leader) = ($seq_string =~ m/^([$_gap_null]+)/);
395 72 ▶ if(defined($leader)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $leader) 17 55 72
396 17 my $len = length($leader);
397 17 $seq_string = ($_end x $len) . substr($seq_string, $len);
398 }
399  
400 # 2) trim trailing nonresidue symbols with end symbol (because could be masked or padded with gaps)
401 72 my ($trailer) = ($seq_string =~ m/([$_gap_null]+)$/);
402 72 ▶ if(defined($trailer)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $trailer) 18 54 72
403 18 my $len = length($trailer);
404 18 $seq_string = substr($seq_string, 0, -$len) . ($_end x $len);
405 }
406
407 # Convert any lowercase alphabet symbols to uppercase
408 72 $seq_string = uc $seq_string;
409
410 72 return $seq_string;
411 }
412  
413 =pod
414  
415 B<_accumulate_symbol_frequencies>
416  
417 Title : _accumulate_symbol_frequencies
418 Usage : _accumulate_symbol_frequencies();
419 Function: Counts and stores frequencies of each symbol at each position.
420 Returns : 1
421 Args : None
422  
423 =cut
424  
425 6 ▶sub _accumulate_symbol_frequencies {
Subroutine _accumulate_symbol_frequencies: called CC=4 SCAR=13.9
426 6 @_freq =();
427 6 my %counts=();
428  
429 # initialize the accumulators
430 6 ▶ for(my $i=0; $i<$_W; $i++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < $_W) 1779 6 1785
431 1779 $_freq[$i]=undef;
432 }
433
434 # accumulate symbol counts
435 6 ▶ for(my $k=0; $k<$_K; $k++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($k < $_K) 72 6 78
436 72 my @symbol_sequence = split //,$_read_buffer[$k];
437 72 ▶ for(my $i=0; $i<$_W; $i++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < $_W) 35292 72 35364
438 35292 my $symbol = $symbol_sequence[$i];
439 35292 $_freq[$i]{$symbol}++;
440 35292 $counts{$symbol}++;
441 }
442 }
443 6 @_observed_symbols = keys %counts;
444  
445 6 return(1);
446 }
447  
448 =pod
449  
450 B<_qc_symbols>
451  
452 Title : _qc_symbols
453 Usage : _qc_symbols();
454 Function: Performs error checking for acceptable symbols. May carp(warn) or croak(die).
455 Returns : 1
456 Args : None
457  
458 =cut
459  
460 6 ▶sub _qc_symbols {
Subroutine _qc_symbols: called CC=14 SCAR=28.8
461
462 # remove end symbol for printing
463 6 my (@no_end_alpha, @no_end_obs);
464 6 ▶ for (@_observed_symbols) {unless ($_ eq $_end) {push(@no_end_obs, $_)}}
Branch: 1 branch
BranchTrueFalseTotal
unless ($_ eq $_end) 45 2 47
465 6 ▶ for (@_alphabet) {unless ($_ eq $_end) {push(@no_end_alpha, $_)}}
Branch: 1 branch
BranchTrueFalseTotal
unless ($_ eq $_end) 53 6 59
466  
467 # warn if alphabet type is 'protein' but input looks like nucleic acid
468 6 ▶ if ($_alphabet_type eq 'protein' && @_observed_symbols <= length("ACGT$_gap$_null$_end")) {
Branch: 1 branch
BranchTrueFalseTotal
if ($_alphabet_type eq "protein" and @_observed_symbols <= length "ACGT$_gap$_null$_end") 0 6 6
Condition66%2/3
$_alphabet_type eq "protein" and @_observed_symbols <= length "ACGT$_gap$_null$_end"
!ll&&!rl&&r
510
MC/DC0%0/2
$_alphabet_type eq "protein" and @_observed_symbols <= length "ACGT$_gap$_null$_end"
$_alphabet_type eq "protein" @_observed_symbols <= length "ACGT$_gap$_null$_end"
Truth table66%2/3
A and B
A= $_alphabet_type eq "protein"B= @_observed_symbols <= length "ACGT$_gap$_null$_end"
ABresult
0X0
100
111
469 0 my $msg = "\nWarning: You have specified the alphabet type as 'protein', \n";
470 0 $msg .= " but the input data may be dna or rna.\n";
471 0 $msg .= "An incorrect alphabet will cause erroneous results.\n";
472 0 $msg .= "Expected alphabet: @no_end_alpha\n";
473 0 $msg .= "Found alphabet: @no_end_obs\n\n";
474 0 carp($msg);
475 }
476
477 # croak if unexpected symbols are detected
478 6 my $observed_symbols = join("", @_observed_symbols);
479 6 ▶ if ($observed_symbols =~ /[^$_alphabet]/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($observed_symbols =~ /[^$_alphabet]/) 0 6 6
480 0 my $msg = "\nUnexpected symbols detected in the input sequences!\n";
481 0 $msg .= "Expected alphabet: @no_end_alpha\n";
482 0 $msg .= "Found alphabet: @no_end_obs\n\n";
483 0 croak($msg);
484 }
485
486 # fill-in with 0 the frequency of missing symbols in positions that don't
487 # have the full complement of symbols
488 6 ▶ for(my $i=0; $i<$_W; $i++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < $_W) 1779 6 1785
489 1779 foreach my $symbol (@_observed_symbols) {
490 28052 ▶ unless(defined($_freq[$i]{$symbol})) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $_freq[$i]{$symbol}) 23054 4998 28052
491 23054 $_freq[$i]{$symbol} = 0;
492 }
493 }
494 }
495  
496 # fill-in with 0's the frequency of any alphabet symbols that did not appear
497 # in the input sequences
498 6 ▶ for(my $i=0; $i<$_W; $i++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < $_W) 1779 6 1785
499 #foreach my $alpha (@_residues) {
500 1779 foreach my $alpha (@_alphabet) {
501 32190 ▶ if(!defined($_freq[$i]{$alpha})) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $_freq[$i]{$alpha}) 4138 28052 32190
502 4138 $_freq[$i]{$alpha} = 0;
503 }
504 }
505 }
506  
507 6 return(1);
508 }
509  
510 =pod
511  
512 B<_define_valid_positions>
513  
514 Title : _define_valid_positions
515 Usage : _define_valid_positions();
516 Function: Builds array of valid alignment positions for analysis (below the null, gap,
517 and end thresholds and are not masked).
518 Returns : 1 or undef if no positions are valid
519 Args : None
520  
521 =cut
522  
523 92 ▶sub _define_valid_positions {
Subroutine _define_valid_positions: called CC=4 SCAR=14.0
524 92 @_valid_positions = ();
525 92 ▶ for(my $i=0; $i< $_W; $i++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < $_W) 34197 92 34289
526 34197 ▶ if( ($_freq[$i]{$_gap} <= $_gap_threshold * $_K)
Branch: 1 branch
BranchTrueFalseTotal
if ($_freq[$i]{$_gap} <= $_gap_threshold * $_K & $_freq[$i]{$_null} <= $_null_threshold * $_K & $_freq[$i]{$_end} <= $_end_threshold * $_K & $_mask[$i]) 34157 40 34197
527 & ($_freq[$i]{$_null} <= $_null_threshold * $_K)
528 & ($_freq[$i]{$_end} <= $_end_threshold * $_K)
529 & $_mask[$i]) {
530 34157 push @_valid_positions, $i;
531 }
532 }
533
534 # if there are no valid positions to analyze return undef
535 92 ▶ unless (@_valid_positions) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@_valid_positions) 0 92 92
536 0 return undef;
537 }
538 92 return(1);
539 }
540  
541 # ----------------------------------
542 # Fast nucleotide diversity
543 # ----------------------------------
544  
545 =pod
546  
547 B<apd>
548  
549 Title : apd
550 Usage : $apd = $fastAPD_obj->apd('gap_base');
551 Function: Returns the APD value
552 Returns : APD
553 Args : Comparison algorithm
554 Default = 'gap_base'.
555 Defines acceptable pairwise comparisons
556 'gap_base' - pairwise deletion
557 - valid comparisons = base to base and gap to base
558 'base_base' - pairwise deletion
559 - valid comparisons = base to base only
560 'complete_del' - complete deletion
561 - all positions containing any missing data ignored
562 Calls : _create_alpha_mask, _calculate_apd
563
564 =cut
565  
566 9 ▶sub apd {
Subroutine apd: called CC=1 SCAR=0.0
Pod undocumented
567 9 my $self = shift;
568 9 $_comparison_type = shift;
569
570 9 return( _calculate_apd() );
571 }
572  
573 =pod
574  
575 B<_calculate_apd>
576  
577 Title : _calculate_apd
578 Usage : _calculate_apd();
579 Function: Performs the fast APD calculation - nucleotide diversity per pair of bases
580 (ratio of sums).
581 APD ($d) = Total Mismatches ($m) / Total Pairwise comparisons ($p)
582 where $m = $p - Total Matches (%matches)
583 where matches = binomial coefficient(frequency of a given symbol, 2)
584 summed over appropriate symbols and valid positions
585 where $p = binomial coefficient(number of rows at a given position, 2)
586 summed over valid positions
587 Returns : The APD value ($d)
588 Args : None
589 Calls : _create_alpha_mask, choose_2
590
591 =cut
592  
593 77 ▶sub _calculate_apd {
Subroutine _calculate_apd: called CC=5 SCAR=16.1
594 77 my ($p, $sum_freqs);
595 77 my %matches;
596  
597 77 _create_alpha_mask();
598  
599 # sum the number of matches and pairs
600 77 foreach my $i (@_valid_positions) {
601 30879 foreach my $alpha (@_alphabet) {
602 630630 $sum_freqs += $_freq[$i]{$alpha}*$_alpha_mask{$alpha};
603 630630 $matches{$alpha} += _choose_2($_freq[$i]{$alpha}*$_alpha_mask{$alpha});
604 }
605 30879 $p += _choose_2($sum_freqs);
606 30879 $sum_freqs = 0;
607 }
608
609 # remove gap_gap comparisons
610 77 $p -= $matches{$_gap};
611
612 # calculate mismatches
613 77 my $sum_matches = 0;
614 77 foreach (@_residues) {$sum_matches += $matches{$_}}
615 77 my $m = $p - $sum_matches;
616 77 my $d = 0;
617 77 ▶ $d = $m / $p unless $m == 0;
Branch: 1 branch
BranchTrueFalseTotal
unless $m == 0 73 4 77
618 77 return($d);
619 }
620  
621 =pod
622  
623 B<std_err>
624  
625 Title : std_err
626 Usage : $se = $fastAPD_obj->std_err('gap_base');
627 Function: Iterates over the number of reads ($_K) adjusting the original frequency
628 counts to ignore one read at each iteration. Calls an APD subroutine at each
629 iteration and stores the diversity values. Calls _jackknifeSE to calculate
630 the standard error.
631 Returns : The standard error of the APD ($_seD) as estimated by jackknife resampling.
632 Args : Comparison method
633 Default = 'gap_base'.
634 Calls : _calculate_apd, _jackknifeSE
635  
636 =cut
637  
638 9 ▶sub std_err {
Subroutine std_err: called CC=4 SCAR=13.9
Pod undocumented
639 9 my $self = shift;
640 9 $_comparison_type = shift;
641
642 # Iterate over the number of reads ($_K) adjusting the original frequency
643 # counts to ignore one read at each iteration
644 9 my @_orig_freq = @_freq;
645 9 my $stop = $_K;
646 9 my @indices = 1..$_K;
647 9 $_K--;
648 9 my @diversities = (0) x $stop;
649
650 9 ▶ for(my $k=0; $k<$stop; $k++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($k < $stop) 68 9 77
651 68 my @symbol_sequence = split //,$_read_buffer[$k];
652 68 ▶ for(my $i=0; $i<$_W; $i++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < $_W) 29404 68 29472
653 29404 my $symbol = $symbol_sequence[$i];
654 29404 $_freq[$i]{$symbol}--;
655 }
656  
657 # Calculate diversity and store for each iteration
658 68 $diversities[$k] = _calculate_apd();
659 68 ▶ for(my $i=0; $i<$_W; $i++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < $_W) 29404 68 29472
660 29404 my $symbol = $symbol_sequence[$i];
661 29404 $_freq[$i]{$symbol}++;
662 }
663 }
664
665 9 $_K++;
666 9 _create_alpha_mask();
667 9 my $_seD = _jackknifeSE(@diversities);
668 9 return($_seD);
669 }
670  
671 =pod
672  
673 B<_create_alpha_mask>
674  
675 Title : _create_alpha_mask
676 Usage : _create_alpha_mask();
677 Function: Creates a binary mask (1 = valid for pairwise comparisons; 0 = invalid)
678 corresponding to all symbols, dependent on the comparison_type input.
679 Calls _define_valid_positions in case the valid positions should be
680 refined for complete_del comparison type.
681 Returns : 1
682 Args : None
683 Calls : _define_valid_positions
684
685 =cut
686  
687 86 ▶sub _create_alpha_mask {
Subroutine _create_alpha_mask: called CC=6 SCAR=18.5
688 #print $_comparison_type, "\n";
689 86 foreach my $res (@_residues) {$_alpha_mask{$res} = 1}
690  
691 86 ▶ if(!defined($_comparison_type)) {
Branch: 4 branches
BranchTrueFalseTotal
if (not defined $_comparison_type) { } 0 86 86
elsif ($_comparison_type eq 'base_base') { } 10 76 86
elsif ($_comparison_type eq 'gap_base') { } 74 2 76
elsif ($_comparison_type eq 'complete_del') { } 2 0 2
692 0 $_comparison_type = 'base_base';
693 0 @_alpha_mask{$_gap, $_null, $_end} = (0,0,0);
694 }
695 elsif($_comparison_type eq 'base_base') {
696 10 @_alpha_mask{$_gap, $_null, $_end} = (0,0,0);
697 }
698 elsif($_comparison_type eq 'gap_base') {
699 74 @_alpha_mask{$_gap, $_null, $_end} = (1,0,0);
700 }
701 elsif($_comparison_type eq 'complete_del') {
702 2 $_gap_threshold = 0;
703 2 $_null_threshold = 0;
704 2 $_end_threshold = 0;
705 2 $_comparison_type = 'base_base';
706 2 @_alpha_mask{$_gap, $_null, $_end} = (0,0,0);
707 }
708 else {
709 0 croak("Unknown comparison type: '$_comparison_type'");
710 }
711 86 _define_valid_positions();
712 86 return(1);
713 }
714  
715 # ----------------------------------
716 # math functions
717 # ----------------------------------
718  
719 =pod
720  
721 B<_choose_2>
722  
723 Title : _choose_2
724 Usage : _choose_2($number_of_pairs);
725 Function: A simplified binomial coefficient calculation - the number of ways of
726 choosing k outcomes from n possibilities, where k = 2.
727 Returns : the value of the binomial coefficient
728 Args : the number of possibilities, n
729
730 =cut
731  
732 661509 ▶sub _choose_2 {
Subroutine _choose_2: called CC=1 SCAR=0.0
733 661509 my $n = shift;
734 661509 return($n * ($n - 1) / 2);
735 }
736  
737 =pod
738  
739 B<_jackknifeSE>
740  
741 Title : _jackknifeSE
742 Usage : _jackknifeSE(@diversity_values);
743 Function: Calculates the standard error based on jackknife resampling
744 Returns : the standard error
745 Args : an array of values obtained from the iterative jackknife leave-one-out process
746 Calls : _mean
747
748 =cut
749  
750 9 ▶sub _jackknifeSE {
Subroutine _jackknifeSE: called CC=2 SCAR=6.9
751 9 my @values = @_;
752 9 my $n = scalar(@values);
753 9 my $jack_mean = _mean(@values);
754 9 my $jack_sum;
755 9 ▶ for (my $i = 0; $i < $n; $i++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < $n) 68 9 77
756 68 $jack_sum += ($values[$i] - $jack_mean)**2;
757 }
758 9 my $jack_se = sqrt((($n - 1) / $n) * $jack_sum);
759
760 9 return($jack_se);
761 }
762  
763 =pod
764  
765 B<_mean>
766
767 Title : _mean
768 Usage : _mean(@values);
769 Function: Calculates the mean of an array of values
770 Returns : the mean
771 Args : an array of values
772
773 =cut
774
775 9 ▶sub _mean {
Subroutine _mean: called CC=2 SCAR=7.1
776 9 my @values = @_;
777 0 ▶ unless(scalar(@values)) { return undef }
Branch: 1 branch
BranchTrueFalseTotal
unless (scalar @values) 0 9 9
778 9 my $sum;
779 9 map{$sum += $_} @values;
780 9 my $mean = $sum / scalar(@values);
781 9 return($mean);
782 }
783  
784 # ----------------------------------
785 # setters and getters
786 # ----------------------------------
787  
788 =pod
789  
790 B<gap_threshold>
791  
792 Title : gap_threshold
793 Usage : $fastAPD_obj->gap_threshold(0.1) or $fastAPD_obj->gap_threshold();
794 Function: If an argument is provided, this function sets the gap threshold.
795 Returns the gap threshold.
796 Returns : the gap threshold
797 Args : optional value for setting the gap threshold
798
799 =cut
800  
801 3 ▶sub gap_threshold {
Subroutine gap_threshold: called CC=2 SCAR=6.9
Pod undocumented
802 3 my $self = shift;
803 3 my $set_thresh = shift;
804 3 ▶ if ($set_thresh) {$_gap_threshold = $set_thresh}
Branch: 1 branch
BranchTrueFalseTotal
if ($set_thresh) 2 1 3
805 3 return($_gap_threshold);
806 }
807  
808 =pod
809  
810 B<null_threshold>
811  
812 Title : null_threshold
813 Usage : $fastAPD_obj->null_threshold(0.1) or $fastAPD_obj->null_threshold();
814 Function: If an argument is provided, this function sets the null threshold.
815 Returns the null threshold.
816 Returns : the null threshold
817 Args : optional value for setting the null threshold
818
819 =cut
820  
821 3 ▶sub null_threshold {
Subroutine null_threshold: called CC=2 SCAR=6.9
Pod undocumented
822 3 my $self = shift;
823 3 my $set_thresh = shift;
824 3 ▶ if ($set_thresh) {$_null_threshold = $set_thresh}
Branch: 1 branch
BranchTrueFalseTotal
if ($set_thresh) 2 1 3
825 3 return($_null_threshold);
826 }
827  
828 =pod
829  
830 B<end_threshold>
831  
832 Title : end_threshold
833 Usage : $fastAPD_obj->end_threshold(0.1) or $fastAPD_obj->end_threshold();
834 Function: If an argument is provided, this function sets the ragged end threshold.
835 Returns the ragged end threshold.
836 Returns : the ragged end threshold
837 Args : optional value for setting the ragged end threshold
838
839 =cut
840  
841 2 ▶sub end_threshold {
Subroutine end_threshold: called CC=2 SCAR=6.9
Pod undocumented
842 2 my $self = shift;
843 2 my $set_thresh = shift;
844 2 ▶ if ($set_thresh) {$_end_threshold = $set_thresh}
Branch: 1 branch
BranchTrueFalseTotal
if ($set_thresh) 1 1 2
845 2 return($_end_threshold);
846 }
847  
848 =pod
849  
850 B<n_reads>
851  
852 Title : n_reads
853 Usage : $fastAPD_obj->n_reads();
854 Function: Returns the number of reads in the input alignment
855 Returns : the number of reads
856 Args : none
857
858 =cut
859  
860 1 ▶sub n_reads {
Subroutine n_reads: called CC=1 SCAR=0.0
Pod undocumented
861 1 my $self=shift;
862 1 return $_K;
863 }
864  
865 =pod
866  
867 B<n_valid_positions>
868  
869 Title : n_valid_positions
870 Usage : $fastAPD_obj->n_valid_positions();
871 Function: Returns the number of positions in the alignment which meet the analysis
872 criteria
873 Returns : the number of valid positions
874 Args : none
875
876 =cut
877  
878 3 ▶sub n_valid_positions {
Subroutine n_valid_positions: called CC=1 SCAR=0.0
Pod undocumented
879 3 my $self=shift;
880 3 my $size = @_valid_positions;
881 3 return $size;
882 }
883  
884 =pod
885  
886 B<valid_positions>
887  
888 Title : valid_positions
889 Usage : $fastAPD_obj->valid_positions();
890 Function: Returns an array reference to the positions in the alignment which meet
891 the analysis criteria
892 Returns : an array reference to the valid positions
893 Args : none
894
895 =cut
896  
897 5 ▶sub valid_positions {
Subroutine valid_positions: called CC=1 SCAR=0.0
Pod undocumented
898 5 my $self=shift;
899 5 my @vp = @_valid_positions;
900 5 return \@vp;
901 }
902  
903 =pod
904  
905 B<width>
906  
907 Title : width
908 Usage : $fastAPD_obj->width();
909 Function: Returns the width of the alignment
910 Returns : the width of the alignment
911 Args : none
912  
913 =cut
914  
915 0 ▶sub width {
Subroutine width: not called CC=1 SCAR=6.9
Pod undocumented
916 0 my $self=shift;
917 0 return $_W;
918 }
919  
920 =pod
921  
922 B<freqs>
923  
924 Title : freqs
925 Usage : $fastAPD_obj->freqs();
926 Function: Returns frequencies of each symbol at each position
927 Returns : a reference to an array containing frequencies of each symbol at each position
928 Args : none
929  
930 =cut
931  
932 1 ▶sub freqs {
Subroutine freqs: called CC=3 SCAR=11.0
Pod undocumented
933 1 my $self=shift;
934 1 my (@freq_array, @_curr_freqs);
935 1 push(@freq_array, join("\t",@_alphabet));
936
937 1 ▶ for (my $pos = 0; $pos < $_W; $pos++){
Branch: 1 branch
BranchTrueFalseTotal
if ($pos < $_W) 10 1 11
938 10 foreach my $symbol (@_alphabet) {
939 70 push(@_curr_freqs, $_freq[$pos]{$symbol});
940 }
941 10 push(@freq_array, join("\t", @_curr_freqs));
942 10 @_curr_freqs = ();
943 }
944 1 return \@freq_array;
945 }
946  
947 # -----------------------------------------------------
948 # consensus sequences
949 # -----------------------------------------------------
950  
951 =pod
952  
953 B<consensus_alignment>
954  
955 Title : consensus_alignment
956 Usage : $fastAPD_obj->consensus_alignment();
957 Function: Returns a consensus sequence based on the aligned reads
958 Returns : a consensus sequence based on the aligned reads
959 Args : none
960 Calls : _calculate_aligned_consensus
961  
962 =cut
963  
964 1 ▶sub consensus_alignment {
Subroutine consensus_alignment: called CC=1 SCAR=0.0
Pod undocumented
965 1 my $self;
966 1 return _calculate_aligned_consensus();
967 }
968  
969 =pod
970  
971 B<_calculate_aligned_consensus>
972  
973 Title : _calculate_aligned_consensus
974 Usage : _calculate_aligned_consensus();
975 Function: Creates a consensus sequence by calling _argmax to detect the most
976 frequent symbol at each position in the alignment
977 Returns : a consensus sequence based on the aligned reads
978 Args : none
979 Calls : _argmax
980  
981 =cut
982  
983 1 ▶sub _calculate_aligned_consensus {
Subroutine _calculate_aligned_consensus: called CC=2 SCAR=6.9
984 1 my $seq_string='';
985 1 ▶ for(my $i=0; $i < $_W; $i++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < $_W) 10 1 11
986 10 my $symbol;
987 10 $symbol = _argmax($_freq[$i]);
988 10 $seq_string .= $symbol;
989 }
990 1 return $seq_string;
991 }
992  
993 =pod
994  
995 B<_argmax>
996  
997 Title : _argmax
998 Usage : _argmax($_freq[$i]);
999 Function: Detects the most frequently occurring symbol at a position
1000 Returns : the most frequently occurring symbol
1001 Args : a hash containing the frequencies of each symbol at a given position
1002  
1003 =cut
1004  
1005 10 ▶sub _argmax {
Subroutine _argmax: called CC=4 SCAR=13.9
1006 10 my $freqs = shift;
1007 10 my $argmax = ' ';
1008 10 my $max = -1;
1009 10 foreach my $symbol ($_end, $_gap, $_null, @_residues) {
1010 70 ▶ if($freqs->{$symbol} >= $max) {
Branch: 1 branch
BranchTrueFalseTotal
if ($freqs->{$symbol} >= $max) 37 33 70
1011 37 $max = $freqs->{$symbol};
1012 37 ▶ if ($symbol eq '#') {$argmax = '-'}
Branch: 1 branch
BranchTrueFalseTotal
if ($symbol eq '#') { } 10 27 37
1013 27 else {$argmax = $symbol}
1014 }
1015 }
1016 10 return $argmax;
1017 }
1018  
1019 2 1;
1020  
1021  
1022 __END__
↑ Summary