Bio/Align/DNAStatistics.pm

filter: Statementstmt 81.2% 521 / 641 Branchbran 67.6% 142 / 210 Conditioncond 48.0% 25 / 52 MC/DCmcdc 28.1% 9 / 32 Subroutinesub 86.6% 39 / 45 Podpod 66.6% 20 / 30 totaltotal 74.8% 756 / 1010 CC 160 SCAR 26.9
CC
160
Cov
76%
D_Kimura_variance
72.0
D_F84
56.0
analyse_mutations
37.0
CRAP 14.8
« Bio/SeqIO.pm ↑ Summary Bio/PrimarySeq.pm »
1 #
2 # BioPerl module for Bio::Align::DNAStatistics
3 #
4 # Please direct questions and support issues to <bioperl-l@bioperl.org>
5 #
6 # Cared for by Jason Stajich <jason-AT-bioperl.org>
7 #
8 # Copyright Jason Stajich
9 #
10 # You may distribute this module under the same terms as perl itself
11  
12 # POD documentation - main docs before the code
13  
14 =head1 NAME
15  
16 Bio::Align::DNAStatistics - Calculate some statistics for a DNA alignment
17  
18 =head1 SYNOPSIS
19  
20 use Bio::AlignIO;
21 use Bio::Align::DNAStatistics;
22  
23 my $stats = Bio::Align::DNAStatistics->new();
24 my $alignin = Bio::AlignIO->new(-format => 'emboss',
25 -file => 't/data/insulin.water');
26 my $aln = $alignin->next_aln;
27 my $jcmatrix = $stats->distance(-align => $aln,
28 -method => 'Jukes-Cantor');
29  
30 print $jcmatrix->print_matrix;
31 ## and for measurements of synonymous /nonsynonymous substitutions ##
32  
33 my $in = Bio::AlignIO->new(-format => 'fasta',
34 -file => 't/data/nei_gojobori_test.aln');
35 my $alnobj = $in->next_aln;
36 my ($seq1id,$seq2id) = map { $_->display_id } $alnobj->each_seq;
37 my $results = $stats->calc_KaKs_pair($alnobj, $seq1id, $seq2id);
38 print "comparing ".$results->[0]{'Seq1'}." and ".$results->[0]{'Seq2'}."\n";
39 for (sort keys %{$results->[0]} ){
40 next if /Seq/;
41 printf("%-9s %.4f \n",$_ , $results->[0]{$_});
42 }
43  
44 my $results2 = $stats->calc_all_KaKs_pairs($alnobj);
45 for my $an (@$results2){
46 print "comparing ". $an->{'Seq1'}." and ". $an->{'Seq2'}. " \n";
47 for (sort keys %$an ){
48 next if /Seq/;
49 printf("%-9s %.4f \n",$_ , $an->{$_});
50 }
51 print "\n\n";
52 }
53  
54 my $result3 = $stats->calc_average_KaKs($alnobj, 1000);
55 for (sort keys %$result3 ){
56 next if /Seq/;
57 printf("%-9s %.4f \n",$_ , $result3->{$_});
58 }
59  
60 =head1 DESCRIPTION
61  
62 This object contains routines for calculating various statistics and
63 distances for DNA alignments. The routines are not well tested and do
64 contain errors at this point. Work is underway to correct them, but
65 do not expect this code to give you the right answer currently! Use
66 dnadist/distmat in the PHLYIP or EMBOSS packages to calculate the
67 distances.
68  
69  
70 Several different distance method calculations are supported. Listed
71 in brackets are the pattern which will match
72  
73 =over 3
74  
75 =item *
76  
77 JukesCantor [jc|jukes|jukescantor|jukes-cantor]
78  
79 =item *
80  
81 Uncorrected [jcuncor|uncorrected]
82  
83 =item *
84  
85 F81 [f81|felsenstein]
86  
87 =item *
88  
89 Kimura [k2|k2p|k80|kimura]
90  
91 =item *
92  
93 Tamura [t92|tamura|tamura92]
94  
95 =item *
96  
97 F84 [f84|felsenstein84]
98  
99 =item *
100  
101 TajimaNei [tajimanei|tajima\-nei]
102  
103 =item *
104  
105 JinNei [jinnei|jin\-nei] (not implemented)
106  
107 =back
108  
109 There are also three methods to calculate the ratio of synonymous to
110 non-synonymous mutations. All are implementations of the Nei-Gojobori
111 evolutionary pathway method and use the Jukes-Cantor method of
112 nucleotide substitution. This method works well so long as the
113 nucleotide frequencies are roughly equal and there is no significant
114 transition/transversion bias. In order to use these methods there are
115 several pre-requisites for the alignment.
116  
117 =over 3
118  
119 =item 1
120  
121 DNA alignment must be based on protein alignment. Use the subroutine
122 L<Bio::Align::Utilities/aa_to_dna_aln> to achieve this.
123  
124 =item 2
125  
126 Therefore alignment gaps must be in multiples of 3 (representing an aa
127 deletion/insertion) and at present must be indicated by a '-' symbol.
128  
129 =item 3
130  
131 Alignment must be solely of coding region and be in reading frame 0 to
132 achieve meaningful results
133  
134 =item 4
135  
136 Alignment must therefore be a multiple of 3 nucleotides long.
137  
138 =item 5
139  
140 All sequences must be the same length (including gaps). This should be
141 the case anyway if the sequences have been automatically aligned using
142 a program like Clustal.
143  
144 =item 6
145  
146 Only the standard codon alphabet is supported at present.
147  
148 =back
149  
150 calc_KaKs_pair() calculates a number of statistics for a named pair of
151 sequences in the alignment.
152  
153 calc_all_KaKs_pairs() calculates these statistics for all pairwise
154 comparisons in an MSA. The statistics returned are:
155  
156 =over 3
157  
158 =item *
159  
160 S_d - Number of synonymous mutations between the 2 sequences.
161  
162 =item *
163  
164 N_d - Number of non-synonymous mutations between the 2 sequences.
165  
166 =item *
167  
168 S - Mean number of synonymous sites in both sequences.
169  
170 =item *
171  
172 N - mean number of synonymous sites in both sequences.
173  
174 =item *
175  
176 P_s - proportion of synonymous differences in both sequences given by
177 P_s = S_d/S.
178  
179 =item *
180  
181 P_n - proportion of non-synonymous differences in both sequences given
182 by P_n = S_n/S.
183  
184 =item *
185  
186 D_s - estimation of synonymous mutations per synonymous site (by
187 Jukes-Cantor).
188  
189 =item *
190  
191 D_n - estimation of non-synonymous mutations per non-synonymous site (by
192 Jukes-Cantor).
193  
194 =item *
195  
196 D_n_var - estimation of variance of D_n .
197  
198 =item *
199  
200 D_s_var - estimation of variance of S_n.
201  
202 =item *
203  
204 z_value - calculation of z value.Positive value indicates D_n E<gt> D_s,
205 negative value indicates D_s E<gt> D_n.
206  
207 =back
208  
209 The statistics returned by calc_average_KaKs are:
210  
211 =over 3
212  
213 =item *
214  
215 D_s - Average number of synonymous mutations/synonymous site.
216  
217 =item *
218  
219 D_n - Average number of non-synonymous mutations/non-synonymous site.
220  
221 =item *
222  
223 D_s_var - Estimated variance of Ds from bootstrapped alignments.
224  
225 =item *
226  
227 D_n_var - Estimated variance of Dn from bootstrapped alignments.
228  
229 =item *
230  
231 z_score - calculation of z value. Positive value indicates D_n E<gt>D_s,
232 negative values vice versa.
233  
234 =back
235  
236 The design of the code is based around the explanation of the
237 Nei-Gojobori algorithm in the excellent book "Molecular Evolution and
238 Phylogenetics" by Nei and Kumar, published by Oxford University
239 Press. The methods have been tested using the worked example 4.1 in
240 the book, and reproduce those results. If people like having this sort
241 of analysis in BioPerl other methods for estimating Ds and Dn can be
242 provided later.
243  
244 Much of the DNA distance code is based on implementations in EMBOSS
245 (Rice et al, www.emboss.org) [distmat.c] and PHYLIP (J. Felsenstein et
246 al) [dnadist.c]. Insight also gained from Eddy, Durbin, Krogh, &
247 Mitchison.
248  
249 =head1 REFERENCES
250  
251 =over 3
252  
253 =item *
254  
255 D_JukesCantor
256  
257 "Phylogenetic Inference", Swoffrod, Olsen, Waddell and Hillis, in
258 Mol. Systematics, 2nd ed, 1996, Ch 11. Derived from "Evolution of
259 Protein Molecules", Jukes & Cantor, in Mammalian Prot. Metab., III,
260 1969, pp. 21-132.
261  
262 =item *
263  
264 D_Tamura
265  
266 K Tamura, Mol. Biol. Evol. 1992, 9, 678.
267  
268 =item *
269  
270 D_Kimura
271  
272 M Kimura, J. Mol. Evol., 1980, 16, 111.
273  
274 =item *
275  
276 JinNei
277  
278 Jin and Nei, Mol. Biol. Evol. 82, 7, 1990.
279  
280 =item *
281  
282 D_TajimaNei
283  
284 Tajima and Nei, Mol. Biol. Evol. 1984, 1, 269.
285  
286 =back
287  
288 =head1 FEEDBACK
289  
290 =head2 Mailing Lists
291  
292 User feedback is an integral part of the evolution of this and other
293 Bioperl modules. Send your comments and suggestions preferably to
294 the Bioperl mailing list. Your participation is much appreciated.
295  
296 bioperl-l@bioperl.org - General discussion
297 http://bioperl.org/wiki/Mailing_lists - About the mailing lists
298  
299 =head2 Support
300  
301 Please direct usage questions or support issues to the mailing list:
302  
303 I<bioperl-l@bioperl.org>
304  
305 rather than to the module maintainer directly. Many experienced and
306 reponsive experts will be able look at the problem and quickly
307 address it. Please include a thorough description of the problem
308 with code and data examples if at all possible.
309  
310 =head2 Reporting Bugs
311  
312 Report bugs to the Bioperl bug tracking system to help us keep track
313 of the bugs and their resolution. Bug reports can be submitted via the
314 web:
315  
316 https://github.com/bioperl/bioperl-live/issues
317  
318 =head1 AUTHOR - Jason Stajich
319  
320 Email jason-AT-bioperl.org
321  
322 =head1 CONTRIBUTORS
323  
324 Richard Adams, richard.adams@ed.ac.uk
325  
326 =head1 APPENDIX
327  
328 The rest of the documentation details each of the object methods.
329 Internal methods are usually preceded with a _
330  
331 =cut
332  
333  
334 # Let the code begin...
335  
336  
337 package Bio::Align::DNAStatistics;
338 3 $Bio::Align::DNAStatistics::VERSION = '1.7.8';
339 3 ▶use vars qw(%DNAChanges @Nucleotides %NucleotideIndexes
Subroutine BEGIN: called CC=1 SCAR=0.0
340 $GapChars $SeqCount $DefaultGapPenalty %DistanceMethods
341 3 $CODONS %synchanges $synsites $Precision $GCChhars);
342 3 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
343 3 ▶use Bio::Align::PairwiseStatistics;
Subroutine BEGIN: called CC=1 SCAR=0.0
344 3 ▶use Bio::Matrix::PhylipDist;
Subroutine BEGIN: called CC=1 SCAR=0.0
345 3 ▶use Bio::Tools::IUPAC;
Subroutine BEGIN: called CC=1 SCAR=0.0
346  
347 3 ▶BEGIN {
Subroutine BEGIN: called CC=1 SCAR=0.0
348 3 $GapChars = '[\.\-]';
349 3 $GCChhars = '[GCS]';
350 3 @Nucleotides = qw(A G T C);
351 3 $SeqCount = 2;
352 3 $Precision = 5;
353
354 # these values come from EMBOSS distmat implementation
355 3 %NucleotideIndexes = ( 'A' => 0,
356 'T' => 1,
357 'C' => 2,
358 'G' => 3,
359  
360 'AT' => 0,
361 'AC' => 1,
362 'AG' => 2,
363 'CT' => 3,
364 'GT' => 4,
365 'CG' => 5,
366  
367 # these are wrong now
368 # 'S' => [ 1, 3],
369 # 'W' => [ 0, 4],
370 # 'Y' => [ 2, 3],
371 # 'R' => [ 0, 1],
372 # 'M' => [ 0, 3],
373 # 'K' => [ 1, 2],
374 # 'B' => [ 1, 2, 3],
375 # 'H' => [ 0, 2, 3],
376 # 'V' => [ 0, 1, 3],
377 # 'D' => [ 0, 1, 2],
378 );
379  
380 3 $DefaultGapPenalty = 0;
381 # could put ambiguities here?
382 3 %DNAChanges = ( 'Transversions' => { 'A' => [ 'T', 'C'],
383 'T' => [ 'A', 'G'],
384 'C' => [ 'A', 'G'],
385 'G' => [ 'C', 'T'],
386 },
387 'Transitions' => { 'A' => [ 'G' ],
388 'G' => [ 'A' ],
389 'C' => [ 'T' ],
390 'T' => [ 'C' ],
391 },
392 );
393 3 %DistanceMethods = ( 'jc|jukes|jukescantor|jukes\-cantor' => 'JukesCantor',
394 'jcuncor|uncorrected' => 'Uncorrected',
395 'f81|felsenstein81' => 'F81',
396 'k2|k2p|k80|kimura' => 'Kimura',
397 't92|tamura|tamura92' => 'Tamura',
398 'f84|felsenstein84' => 'F84',
399 'tajimanei|tajima\-nei' => 'TajimaNei',
400 'jinnei|jin\-nei' => 'JinNei');
401  
402 }
403 3 ▶use base qw(Bio::Root::Root Bio::Align::StatisticsI);
Subroutine BEGIN: called CC=1 SCAR=0.0
404  
405 ## generate look up hashes for Nei_Gojobori methods##
406 3 $CODONS = get_codons();
407 3 my @t = split '', "FFLLSSSSYY**CC*WLLLLPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG";
408 #create look up hash of number of possible synonymous mutations per codon
409 3 $synsites = get_syn_sites();
410 #create reference look up hash of single basechanges in codons
411 3 %synchanges = get_syn_changes();
412  
413  
414  
415 =head2 new
416  
417 Title : new
418 Usage : my $obj = Bio::Align::DNAStatistics->new();
419 Function: Builds a new Bio::Align::DNAStatistics object
420 Returns : Bio::Align::DNAStatistics
421 Args : none
422  
423  
424 =cut
425  
426 2 ▶sub new {
Subroutine new: called CC=1 SCAR=0.0
Pod documented
427 2 my ($class,@args) = @_;
428 2 my $self = $class->SUPER::new(@args);
429
430 2 $self->pairwise_stats( Bio::Align::PairwiseStatistics->new());
431  
432 2 return $self;
433 }
434  
435  
436 =head2 distance
437  
438 Title : distance
439 Usage : my $distance_mat = $stats->distance(-align => $aln,
440 -method => $method);
441 Function: Calculates a distance matrix for all pairwise distances of
442 sequences in an alignment.
443 Returns : L<Bio::Matrix::PhylipDist> object
444 Args : -align => Bio::Align::AlignI object
445 -method => String specifying specific distance method
446 (implementing class may assume a default)
447 See also: L<Bio::Matrix::PhylipDist>
448  
449 =cut
450  
451 12 ▶sub distance{
Subroutine distance: called CC=8 SCAR=24.5
Pod documented
452 12 my ($self,@args) = @_;
453 12 my ($aln,$method) = $self->_rearrange([qw(ALIGN METHOD)],@args);
454 12 ▶ if( ! defined $aln || ! ref ($aln) || ! $aln->isa('Bio::Align::AlignI') ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $aln and ref $aln and $aln->isa("Bio::Align::AlignI")) 0 12 12
Condition33%2/6
defined $aln and ref $aln and $aln->isa("Bio::Align::AlignI")
!ll&&!rl&&r
0012
defined $aln and ref $aln
!ll&&!rl&&r
0012
MC/DC0%0/3
defined $aln and ref $aln and $aln->isa("Bio::Align::AlignI")
defined $aln ref $aln $aln->isa("Bio::Align::AlignI")
Truth table25%1/4
A and B and C
A= defined $alnB= ref $alnC= $aln->isa("Bio::Align::AlignI")
ABCresult
0XX0
10X0
1100
1111
455 0 $self->throw("Must supply a valid Bio::Align::AlignI for the -align parameter in distance");
456 }
457 12 ▶ $method ||= 'JukesCantor';
Condition50%1/2
$method ||= "JukesCantor"
l!l
120
MC/DC0%0/1
$method ||= "JukesCantor"
$method
Truth table50%1/2
A
A= $method
Aresult
11
00
458 12 foreach my $m ( keys %DistanceMethods ) {
459 58 ▶ if(defined $m && $method =~ /$m/i ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $m and $method =~ /$m/i) 12 46 58
Condition66%2/3
defined $m and $method =~ /$m/i
!ll&&!rl&&r
04612
MC/DC50%1/2
defined $m and $method =~ /$m/i
defined $m $method =~ /$m/i
Truth table66%2/3
A and B
A= defined $mB= $method =~ /$m/i
ABresult
0X0
100
111
460 12 my $mtd = "D_$DistanceMethods{$m}";
461 12 return $self->$mtd($aln);
462 }
463 }
464 0 $self->warn("Unrecognized distance method $method must be one of [".
465 join(',',$self->available_distance_methods())."]");
466 0 return;
467 }
468  
469 =head2 available_distance_methods
470  
471 Title : available_distance_methods
472 Usage : my @methods = $stats->available_distance_methods();
473 Function: Enumerates the possible distance methods
474 Returns : Array of strings
475 Args : none
476  
477  
478 =cut
479  
480 0 ▶sub available_distance_methods{
Subroutine available_distance_methods: not called CC=1 SCAR=6.9
Pod documented
481 0 my ($self,@args) = @_;
482 0 return values %DistanceMethods;
483 }
484  
485 =head2 D - distance methods
486  
487  
488 =cut
489  
490  
491 =head2 D_JukesCantor
492  
493 Title : D_JukesCantor
494 Usage : my $d = $stat->D_JukesCantor($aln)
495 Function: Calculates D (pairwise distance) between 2 sequences in an
496 alignment using the Jukes-Cantor 1 parameter model.
497 Returns : L<Bio::Matrix::PhylipDist>
498 Args : L<Bio::Align::AlignI> of DNA sequences
499 double - gap penalty
500  
501  
502 =cut
503  
504 2 ▶sub D_JukesCantor{
Subroutine D_JukesCantor: called CC=6 SCAR=17.9
Pod documented
505 2 my ($self,$aln,$gappenalty) = @_;
506 2 ▶ return 0 unless $self->_check_arg($aln);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_check_arg($aln) 0 2 2
507 2 ▶ $gappenalty = $DefaultGapPenalty unless defined $gappenalty;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $gappenalty 2 0 2
508 # ambiguities ignored at this point
509 2 my (@seqs,@names,@values,%dist);
510 2 my $seqct = 0;
511 2 foreach my $seq ( $aln->each_seq) {
512 4 push @names, $seq->display_id;
513 4 push @seqs, uc $seq->seq();
514 4 $seqct++;
515 }
516 2 my $precisionstr = "%.$Precision"."f";
517 2 ▶ for(my $i = 0; $i < $seqct-1; $i++ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < $seqct - 1) 2 2 4
518 # (diagonals) distance is 0 for same sequence
519 2 $dist{$names[$i]}->{$names[$i]} = [$i,$i];
520 2 $values[$i][$i] = sprintf($precisionstr,0);
521  
522 2 ▶ for( my $j = $i+1; $j < $seqct; $j++ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($j < $seqct) 2 2 4
523 2 my ($matrix,$pfreq,$gaps) = $self->_build_nt_matrix($seqs[$i],
524 $seqs[$j]);
525 # just want diagonals
526 2 my $m = ( $matrix->[0]->[0] + $matrix->[1]->[1] +
527 $matrix->[2]->[2] + $matrix->[3]->[3] );
528 2 my $D = 1 - ( $m / ($aln->length - $gaps + ( $gaps * $gappenalty)));
529 2 my $d = (- 3 / 4) * log ( 1 - (4 * $D/ 3));
530 # fwd and rev lookup
531 2 $dist{$names[$i]}->{$names[$j]} = [$i,$j];
532 2 $dist{$names[$j]}->{$names[$i]} = [$i,$j];
533 2 $values[$j][$i] = $values[$i][$j] = sprintf($precisionstr,$d);
534 # (diagonals) distance is 0 for same sequence
535 2 $dist{$names[$j]}->{$names[$j]} = [$j,$j];
536 2 $values[$j][$j] = sprintf($precisionstr,0);
537 }
538 }
539 2 return Bio::Matrix::PhylipDist->new(-program => 'bioperl_DNAstats',
540 -matrix => \%dist,
541 -names => \@names,
542 -values => \@values);
543 }
544  
545 =head2 D_F81
546  
547 Title : D_F81
548 Usage : my $d = $stat->D_F81($aln)
549 Function: Calculates D (pairwise distance) between 2 sequences in an
550 alignment using the Felsenstein 1981 distance model.
551 Relaxes the assumption of equal base frequencies that is
552 in JC.
553 Returns : L<Bio::Matrix::PhylipDist>
554 Args : L<Bio::Align::AlignI> of DNA sequences
555  
556  
557 =cut
558  
559 2 ▶sub D_F81{
Subroutine D_F81: called CC=6 SCAR=17.9
Pod documented
560 2 my ($self,$aln,$gappenalty) = @_;
561 2 ▶ return 0 unless $self->_check_arg($aln);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_check_arg($aln) 0 2 2
562 2 ▶ $gappenalty = $DefaultGapPenalty unless defined $gappenalty;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $gappenalty 2 0 2
563 # ambiguities ignored at this point
564 2 my (@seqs,@names,@values,%dist);
565 2 my $seqct = 0;
566 2 foreach my $seq ( $aln->each_seq) {
567 4 push @names, $seq->display_id;;
568 4 push @seqs, uc $seq->seq();
569 4 $seqct++;
570 }
571 2 my $precisionstr = "%.$Precision"."f";
572 2 ▶ for(my $i = 0; $i < $seqct-1; $i++ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < $seqct - 1) 2 2 4
573 # (diagonals) distance is 0 for same sequence
574 2 $dist{$names[$i]}->{$names[$i]} = [$i,$i];
575 2 $values[$i][$i] = sprintf($precisionstr,0);
576  
577 2 ▶ for( my $j = $i+1; $j < $seqct; $j++ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($j < $seqct) 2 2 4
578
579 2 my ($matrix,$pfreq,$gaps) = $self->_build_nt_matrix($seqs[$i],
580 $seqs[$j]);
581 # just want diagonals
582 2 my $m = ( $matrix->[0]->[0] + $matrix->[1]->[1] +
583 $matrix->[2]->[2] + $matrix->[3]->[3] );
584 2 my $D = 1 - ( $m / ($aln->length - $gaps + ( $gaps * $gappenalty)));
585 2 my $d = (- 3 / 4) * log ( 1 - (4 * $D/ 3));
586 # fwd and rev lookup
587 2 $dist{$names[$i]}->{$names[$j]} = [$i,$j];
588 2 $dist{$names[$j]}->{$names[$i]} = [$i,$j];
589 2 $values[$j][$i] = $values[$i][$j] = sprintf($precisionstr,$d);
590 # (diagonals) distance is 0 for same sequence
591 2 $dist{$names[$j]}->{$names[$j]} = [$j,$j];
592 2 $values[$j][$j] = sprintf($precisionstr,0);
593 }
594 }
595 2 return Bio::Matrix::PhylipDist->new(-program => 'bioperl_DNAstats',
596 -matrix => \%dist,
597 -names => \@names,
598 -values => \@values);
599 }
600  
601 =head2 D_Uncorrected
602  
603 Title : D_Uncorrected
604 Usage : my $d = $stats->D_Uncorrected($aln)
605 Function: Calculate a distance D, no correction for multiple substitutions
606 is used. In rare cases where sequences may not overlap, 'NA' is
607 substituted for the distance.
608 Returns : L<Bio::Matrix::PhylipDist>
609 Args : L<Bio::Align::AlignI> (DNA Alignment)
610 [optional] gap penalty
611  
612 =cut
613  
614 2 ▶sub D_Uncorrected {
Subroutine D_Uncorrected: called CC=9 SCAR=22.1
Pod documented
615 2 my ($self,$aln,$gappenalty) = @_;
616 2 ▶ $gappenalty = $DefaultGapPenalty unless defined $gappenalty;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $gappenalty 2 0 2
617 2 ▶ return 0 unless $self->_check_arg($aln);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_check_arg($aln) 0 2 2
618 # ambiguities ignored at this point
619 2 my (@seqs,@names,@values,%dist);
620 2 my $seqct = 0;
621 2 foreach my $seq ( $aln->each_seq) {
622 6 push @names, $seq->display_id;
623 6 push @seqs, uc $seq->seq();
624 6 $seqct++;
625 }
626  
627 2 my $precisionstr = "%.$Precision"."f";
628 2 my $len = $aln->length;
629 2 ▶ for( my $i = 0; $i < $seqct-1; $i++ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < $seqct - 1) 4 1 5
630 # (diagonals) distance is 0 for same sequence
631 4 $dist{$names[$i]}->{$names[$i]} = [$i,$i];
632 4 $values[$i][$i] = sprintf($precisionstr,0);
633
634 4 ▶ for( my $j = $i+1; $j < $seqct; $j++ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($j < $seqct) 7 3 10
635 7 my ($matrix,$pfreq,$gaps) = $self->_build_nt_matrix($seqs[$i],
636 $seqs[$j]);
637 7 my $m = ( $matrix->[0]->[0] +
638 $matrix->[1]->[1] +
639 $matrix->[2]->[2] +
640 $matrix->[3]->[3] );
641 7 my $denom = ( $len - $gaps + ( $gaps * $gappenalty));
642
643 7 ▶ $self->warn("No distance calculated between $names[$i] and $names[$j], inserting -1")
Branch: 1 branch
BranchTrueFalseTotal
unless $denom 1 6 7
644 unless $denom;
645
646 6 ▶ my $D = $denom ? 1 - ( $m / $denom) : -1;
Branch: 1 branch
BranchTrueFalseTotal
$denom ? : 6 0 6
647 # fwd and rev lookup
648 6 $dist{$names[$i]}->{$names[$j]} = [$i,$j];
649 6 $dist{$names[$j]}->{$names[$i]} = [$i,$j];
650 6 ▶ $values[$j][$i] = $values[$i][$j] = $denom ? sprintf($precisionstr,$D)
Branch: 1 branch
BranchTrueFalseTotal
$denom ? : 6 0 6
651 : sprintf("%-*s", $Precision + 2, $D);
652 # (diagonals) distance is 0 for same sequence
653 6 $dist{$names[$j]}->{$names[$j]} = [$j,$j];
654 6 $values[$j][$j] = sprintf($precisionstr,0);
655 }
656 }
657 1 return Bio::Matrix::PhylipDist->new(-program => 'bioperl_DNAstats',
658 -matrix => \%dist,
659 -names => \@names,
660 -values => \@values);
661 }
662  
663  
664 # M Kimura, J. Mol. Evol., 1980, 16, 111.
665  
666 =head2 D_Kimura
667  
668 Title : D_Kimura
669 Usage : my $d = $stat->D_Kimura($aln)
670 Function: Calculates D (pairwise distance) between all pairs of sequences
671 in an alignment using the Kimura 2 parameter model.
672 Returns : L<Bio::Matrix::PhylipDist>
673 Args : L<Bio::Align::AlignI> of DNA sequences
674  
675  
676 =cut
677  
678 2 ▶sub D_Kimura {
Subroutine D_Kimura: called CC=9 SCAR=22.5
Pod documented
679 2 my ($self,$aln) = @_;
680 2 ▶ return 0 unless $self->_check_arg($aln);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_check_arg($aln) 0 2 2
681 # ambiguities ignored at this point
682 2 my (@names,@values,%dist);
683 2 my $seqct = 0;
684 2 foreach my $seq ( $aln->each_seq) {
685 4 push @names, $seq->display_id;
686 4 $seqct++;
687 }
688  
689 2 my $precisionstr = "%.$Precision"."f";
690  
691 2 ▶ for( my $i = 0; $i < $seqct-1; $i++ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < $seqct - 1) 2 2 4
692 # (diagonals) distance is 0 for same sequence
693 2 $dist{$names[$i]}->{$names[$i]} = [$i,$i];
694 2 $values[$i][$i] = sprintf($precisionstr,0);
695  
696 2 ▶ for( my $j = $i+1; $j < $seqct; $j++ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($j < $seqct) 2 2 4
697 2 my $pairwise = $aln->select_noncont($i+1,$j+1);
698 2 my $L = $self->pairwise_stats->number_of_comparable_bases($pairwise);
699 2 ▶ unless( $L ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($L) 0 2 2
700 0 $L = 1;
701 }
702 2 my $P = $self->transitions($pairwise) / $L;
703 2 my $Q = $self->transversions($pairwise) / $L;
704 2 my $K = 0;
705 2 my $denom = ( 1 - (2 * $P) - $Q);
706 2 ▶ if( $denom == 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($denom == 0) 0 2 2
707 0 $self->throw("cannot find distance for ",$i+1,
708 ",",$j+1," $P, $Q\n");
709 }
710 2 my $a = 1 / ( 1 - (2 * $P) - $Q);
711 2 my $b = 1 / ( 1 - 2 * $Q );
712 2 ▶ if( $a < 0 || $b < 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($a < 0 or $b < 0) { } 0 2 2
Condition33%1/3
$a < 0 or $b < 0
l!l&&r!l&&!r
002
MC/DC0%0/2
$a < 0 or $b < 0
$a < 0 $b < 0
Truth table33%1/3
A or B
A= $a < 0B= $b < 0
ABresult
1X1
011
000
713 0 $K = -1;
714 } else{
715 2 $K = (1/2) * log ( $a ) + (1/4) * log($b);
716 }
717 # fwd and rev lookup
718 2 $dist{$names[$i]}->{$names[$j]} = [$i,$j];
719 2 $dist{$names[$j]}->{$names[$i]} = [$i,$j];
720 2 $values[$j][$i] = $values[$i][$j] = sprintf($precisionstr,$K);
721 # (diagonals) distance is 0 for same sequence
722 2 $dist{$names[$j]}->{$names[$j]} = [$j,$j];
723 2 $values[$j][$j] = sprintf($precisionstr,0);
724 }
725 }
726 2 return Bio::Matrix::PhylipDist->new(-program => 'bioperl_DNAstats',
727 -matrix => \%dist,
728 -names => \@names,
729 -values => \@values);
730 }
731  
732  
733 =head2 D_Kimura_variance
734  
735 Title : D_Kimura
736 Usage : my $d = $stat->D_Kimura_variance($aln)
737 Function: Calculates D (pairwise distance) between all pairs of sequences
738 in an alignment using the Kimura 2 parameter model.
739 Returns : array of 2 L<Bio::Matrix::PhylipDist>,
740 the first is the Kimura distance and the second is
741 a matrix of variance V(K)
742 Args : L<Bio::Align::AlignI> of DNA sequences
743  
744  
745 =cut
746  
747 0 ▶sub D_Kimura_variance {
Subroutine D_Kimura_variance: not called CC=8 SCAR=42.8
Pod documented
748 0 my ($self,$aln) = @_;
749 0 ▶ return 0 unless $self->_check_arg($aln);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_check_arg($aln) 0 0 0
750 # ambiguities ignored at this point
751 0 my (@names,@values,%dist,@var);
752 0 my $seqct = 0;
753 0 foreach my $seq ( $aln->each_seq) {
754 0 push @names, $seq->display_id;
755 0 $seqct++;
756 }
757  
758 0 my $precisionstr = "%.$Precision"."f";
759  
760 0 ▶ for( my $i = 0; $i < $seqct-1; $i++ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < $seqct - 1) 0 0 0
761 # (diagonals) distance is 0 for same sequence
762 0 $dist{$names[$i]}->{$names[$i]} = [$i,$i];
763 0 $values[$i][$i] = sprintf($precisionstr,0);
764  
765 0 ▶ for( my $j = $i+1; $j < $seqct; $j++ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($j < $seqct) 0 0 0
766 0 my $pairwise = $aln->select_noncont($i+1,$j+1);
767 0 my $L = $self->pairwise_stats->number_of_comparable_bases($pairwise);
768 0 ▶ unless( $L ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($L) 0 0 0
769 0 $L = 1;
770 }
771 0 my $P = $self->transitions($pairwise) / $L;
772 0 my $Q = $self->transversions($pairwise) / $L;
773 0 my ($a,$b,$K,$var_k);
774 0 my $a_denom = ( 1 - (2 * $P) - $Q);
775 0 my $b_denom = 1 - 2 * $Q;
776 0 ▶ unless( $a_denom > 0 && $b_denom > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($a_denom > 0 and $b_denom > 0) { } 0 0 0
Condition0%0/3
$a_denom > 0 and $b_denom > 0
!ll&&!rl&&r
000
MC/DC0%0/2
$a_denom > 0 and $b_denom > 0
$a_denom > 0 $b_denom > 0
Truth table0%0/3
A and B
A= $a_denom > 0B= $b_denom > 0
ABresult
0X0
100
111
777 0 $a = 1;
778 0 $b = 1;
779 0 $K = -1;
780 0 $var_k = -1;
781 } else {
782 0 $a = 1 / $a_denom;
783 0 $b = 1 / $b_denom;
784 0 $K = (1/2) * log ( $a ) + (1/4) * log($b);
785 # from Wu and Li 1985 which in turn is from Kimura 1980
786 0 my $c = ( $a - $b ) / 2;
787 0 my $d = ( $a + $b ) / 2;
788 0 $var_k = ( $a**2 * $P + $d**2 * $Q - ( $a * $P + $d * $Q)**2 ) / $L;
789 }
790  
791 # fwd and rev lookup
792 0 $dist{$names[$i]}->{$names[$j]} = [$i,$j];
793 0 $dist{$names[$j]}->{$names[$i]} = [$i,$j];
794 0 $values[$j][$i] = $values[$i][$j] = sprintf($precisionstr,$K);
795 # (diagonals) distance is 0 for same sequence
796 0 $dist{$names[$j]}->{$names[$j]} = [$j,$j];
797 0 $values[$j]->[$j] = sprintf($precisionstr,0);
798
799 0 $var[$j]->[$i] = $var[$i]->[$j] = sprintf($precisionstr,$var_k);
800 0 $var[$j]->[$j] = $values[$j]->[$j];
801 }
802 }
803 0 return ( Bio::Matrix::PhylipDist->new(-program => 'bioperl_DNAstats',
804 -matrix => \%dist,
805 -names => \@names,
806 -values => \@values),
807 Bio::Matrix::PhylipDist->new(-program => 'bioperl_DNAstats',
808 -matrix => \%dist,
809 -names => \@names,
810 -values => \@var)
811 );
812 }
813  
814  
815 # K Tamura, Mol. Biol. Evol. 1992, 9, 678.
816  
817 =head2 D_Tamura
818  
819 Title : D_Tamura
820 Usage : Calculates D (pairwise distance) between 2 sequences in an
821 alignment using Tamura 1992 distance model.
822 Returns : L<Bio::Matrix::PhylipDist>
823 Args : L<Bio::Align::AlignI> of DNA sequences
824  
825  
826 =cut
827  
828 2 ▶sub D_Tamura {
Subroutine D_Tamura: called CC=12 SCAR=24.9
Pod documented
829 2 my ($self,$aln) = @_;
830 2 ▶ return 0 unless $self->_check_arg($aln);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_check_arg($aln) 0 2 2
831 # ambiguities ignored at this point
832 2 my (@seqs,@names,@values,%dist,$i,$j);
833 2 my $seqct = 0;
834 2 my $length = $aln->length;
835 2 foreach my $seq ( $aln->each_seq) {
836 4 push @names, $seq->display_id;;
837 4 push @seqs, uc $seq->seq();
838 4 $seqct++;
839 }
840  
841 2 my $precisionstr = "%.$Precision"."f";
842 2 my (@gap,@gc,@trans,@tranv,@score);
843 2 $i = 0;
844 2 for my $t1 ( @seqs ) {
845 4 $j = 0;
846 4 for my $t2 ( @seqs ) {
847 8 $gap[$i][$j] = 0;
848 8 ▶ for( my $k = 0; $k < $length; $k++ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($k < $length) 1532 8 1540
849 1532 my ($c1,$c2) = ( substr($seqs[$i],$k,1),
850 substr($seqs[$j],$k,1) );
851 1532 ▶ if( $c1 =~ /^$GapChars$/ ||
Branch: 2 branches
BranchTrueFalseTotal
if ($c1 =~ /^$Bio::Align::DNAStatistics::GapChars$/ or $c2 =~ /^$Bio::Align::DNAStatistics::GapChars$/) { } 120 1412 1532
elsif ($c2 =~ /^$Bio::Align::DNAStatistics::GCChhars$/i) { } 960 452 1412
Condition100%3/3
$c1 =~ /^$Bio::Align::DNAStatistics::GapChars$/ or $c2 =~ /^$Bio::Align::DNAStatistics::GapChars$/
l!l&&r!l&&!r
80401412
MC/DC100%2/2
$c1 =~ /^$Bio::Align::DNAStatistics::GapChars$/ or $c2 =~ /^$Bio::Align::DNAStatistics::GapChars$/
$c1 =~ /^$Bio::Align::DNAStatistics::GapChars$/ $c2 =~ /^$Bio::Align::DNAStatistics::GapChars$/
Truth table100%3/3
A or B
A= $c1 =~ /^$Bio::Align::DNAStatistics::GapChars$/B= $c2 =~ /^$Bio::Align::DNAStatistics::GapChars$/
ABresult
1X1
011
000
852 $c2 =~ /^$GapChars$/ ) {
853 120 $gap[$i][$j]++;
854 } elsif( $c2 =~ /^$GCChhars$/i ) {
855 960 $gc[$i][$j]++;
856 }
857 }
858 8 $gc[$i][$j] = ( $gc[$i][$j] /
859 ($length - $gap[$i][$j]) );
860 8 $j++;
861 }
862 4 $i++;
863 }
864
865 2 ▶ for( $i = 0; $i < $seqct-1; $i++ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < $seqct - 1) 2 2 4
866 # (diagonals) distance is 0 for same sequence
867 2 $dist{$names[$i]}->{$names[$i]} = [$i,$i];
868 2 $values[$i][$i] = sprintf($precisionstr,0);
869
870 2 ▶ for( $j = $i+1; $j < $seqct; $j++ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($j < $seqct) 2 2 4
871
872 2 my $pairwise = $aln->select_noncont($i+1,$j+1);
873 2 my $L = $self->pairwise_stats->number_of_comparable_bases($pairwise);
874 2 my $P = $self->transitions($pairwise) / $L;
875 2 my $Q = $self->transversions($pairwise) / $L;
876 2 my $C = $gc[$i][$j] + $gc[$j][$i]-
877 ( 2 * $gc[$i][$j] * $gc[$j][$i] );
878 2 ▶ if( $P ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($P) 2 0 2
879 2 $P = $P / $C;
880 }
881 2 my $d = -($C * log(1- $P - $Q)) -(0.5* ( 1 - $C) * log(1 - 2 * $Q));
882 # fwd and rev lookup
883 2 $dist{$names[$i]}->{$names[$j]} = [$i,$j];
884 2 $dist{$names[$j]}->{$names[$i]} = [$i,$j];
885 2 $values[$j][$i] = $values[$i][$j] = sprintf($precisionstr,$d);
886 # (diagonals) distance is 0 for same sequence
887 2 $dist{$names[$j]}->{$names[$j]} = [$j,$j];
888 2 $values[$j][$j] = sprintf($precisionstr,0);
889 }
890 }
891 2 return Bio::Matrix::PhylipDist->new(-program => 'bioperl_DNAstats',
892 -matrix => \%dist,
893 -names => \@names,
894 -values => \@values);
895  
896 }
897  
898 =head2 D_F84
899  
900 Title : D_F84
901 Usage : my $d = $stat->D_F84($aln)
902 Function: Calculates D (pairwise distance) between 2 sequences in an
903 alignment using the Felsenstein 1984 distance model.
904 Returns : L<Bio::Matrix::PhylipDist>
905 Args : L<Bio::Align::AlignI> of DNA sequences
906 [optional] double - gap penalty
907  
908 =cut
909  
910 0 ▶sub D_F84 {
Subroutine D_F84: not called CC=7 SCAR=40.3
Pod documented
911 0 my ($self,$aln,$gappenalty) = @_;
912 0 ▶ return 0 unless $self->_check_arg($aln);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_check_arg($aln) 0 0 0
913 0 $self->throw_not_implemented();
914 # ambiguities ignored at this point
915 0 my (@seqs,@names,@values,%dist);
916 0 my $seqct = 0;
917 0 foreach my $seq ( $aln->each_seq) {
918 # if there is no name,
919 0 my $id = $seq->display_id;
920 0 ▶ if( ! length($id) || # deal with empty names
Branch: 1 branch
BranchTrueFalseTotal
if (not length $id or $id =~ /^\s+$/) 0 0 0
Condition0%0/3
not length $id or $id =~ /^\s+$/
l!l&&r!l&&!r
000
MC/DC0%0/2
not length $id or $id =~ /^\s+$/
not length $id $id =~ /^\s+$/
Truth table0%0/3
not(A) or B
A= not length $idB= $id =~ /^\s+$/
ABresult
1X1
011
000
921 $id =~ /^\s+$/ ) {
922 0 $id = $seqct+1;
923 }
924 0 push @names, $id;
925 0 push @seqs, uc $seq->seq();
926 0 $seqct++;
927 }
928  
929 0 my $precisionstr = "%.$Precision"."f";
930  
931 0 ▶ for( my $i = 0; $i < $seqct-1; $i++ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < $seqct - 1) 0 0 0
932 # (diagonals) distance is 0 for same sequence
933 0 $dist{$names[$i]}->{$names[$i]} = [$i,$i];
934 0 $values[$i][$i] = sprintf($precisionstr,0);
935  
936 0 ▶ for( my $j = $i+1; $j < $seqct; $j++ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($j < $seqct) 0 0 0
937 }
938 }
939 }
940  
941 # Tajima and Nei, Mol. Biol. Evol. 1984, 1, 269.
942 # Tajima-Nei correction used for multiple substitutions in the calc
943 # of the distance matrix. Nucleic acids only.
944 #
945 # D = p-distance = 1 - (matches/(posns_scored + gaps)
946 #
947 # distance = -b * ln(1-D/b)
948 #
949  
950 =head2 D_TajimaNei
951  
952 Title : D_TajimaNei
953 Usage : my $d = $stat->D_TajimaNei($aln)
954 Function: Calculates D (pairwise distance) between 2 sequences in an
955 alignment using the TajimaNei 1984 distance model.
956 Returns : L<Bio::Matrix::PhylipDist>
957 Args : Bio::Align::AlignI of DNA sequences
958  
959  
960 =cut
961  
962 2 ▶sub D_TajimaNei{
Subroutine D_TajimaNei: called CC=14 SCAR=26.6
Pod documented
963 2 my ($self,$aln) = @_;
964 2 ▶ return 0 unless $self->_check_arg($aln);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_check_arg($aln) 0 2 2
965 # ambiguities ignored at this point
966 2 my (@seqs,@names,@values,%dist);
967 2 my $seqct = 0;
968 2 foreach my $seq ( $aln->each_seq) {
969 # if there is no name,
970 4 push @names, $seq->display_id;
971 4 push @seqs, uc $seq->seq();
972 4 $seqct++;
973 }
974 2 my $precisionstr = "%.$Precision"."f";
975 2 my ($i,$j,$bs);
976 # pairwise
977 2 ▶ for( $i =0; $i < $seqct -1; $i++ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < $seqct - 1) 2 2 4
978 2 $dist{$names[$i]}->{$names[$i]} = [$i,$i];
979 2 $values[$i][$i] = sprintf($precisionstr,0);
980  
981 2 ▶ for ( $j = $i+1; $j <$seqct;$j++ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($j < $seqct) 2 2 4
982 2 my ($matrix,$pfreq,$gaps) = $self->_build_nt_matrix($seqs[$i],
983 $seqs[$j]);
984 2 my $pairwise = $aln->select_noncont($i+1,$j+1);
985 2 my $slen = $self->pairwise_stats->number_of_comparable_bases($pairwise);
986 2 my $fij2 = 0;
987 2 ▶ for( $bs = 0; $bs < 4; $bs++ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($bs < 4) 8 2 10
988 8 my $fi = 0;
989 8 map {$fi += $matrix->[$bs]->[$_] } 0..3;
990 8 my $fj = 0;
991 # summation
992 8 map { $fj += $matrix->[$_]->[$bs] } 0..3;
993 8 ▶ my $fij = ( $fi && $fj ) ? ($fi + $fj) /( 2 * $slen) : 0;
Branch: 1 branch
BranchTrueFalseTotal
$fi && $fj ? : 8 0 8
Condition33%1/3
$fi and $fj
!ll&&!rl&&r
008
MC/DC0%0/2
$fi and $fj
$fi $fj
Truth table33%1/3
A and B
A= $fiB= $fj
ABresult
0X0
100
111
994 8 $fij2 += $fij**2;
995 }
996
997 2 my ($pair,$h) = (0,0);
998 2 ▶ for( $bs = 0; $bs < 3; $bs++ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($bs < 3) 6 2 8
999 6 ▶ for(my $bs1 = $bs+1; $bs1 <= 3; $bs1++ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($bs1 <= 3) 12 6 18
1000 12 my $fij = $pfreq->[$pair++] / $slen;
1001 12 ▶ if( $fij ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($fij) 10 2 12
1002
1003 10 my ($ci1,$ci2,$cj1,$cj2) = (0,0,0,0);
1004  
1005 10 map { $ci1 += $matrix->[$_]->[$bs] } 0..3;
1006 10 map { $cj1 += $matrix->[$bs]->[$_] } 0..3;
1007 10 map { $ci2 += $matrix->[$_]->[$bs1] } 0..3;
1008 10 map { $cj2 += $matrix->[$bs1]->[$_] } 0..3;
1009
1010 10 ▶ if( $fij ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($fij) 10 0 10
1011 10 $h += ( ($fij**2) / 2 ) /
1012 ( ( ( $ci1 + $cj1 ) / (2 * $slen) ) *
1013 ( ( $ci2 + $cj2 ) / (2 * $slen) )
1014 );
1015 }
1016 10 $self->debug( "slen is $slen h is $h fij = $fij ci1 =$ci1 cj1=$cj1 ci2=$ci2 cj2=$cj2\n");
1017 }
1018 }
1019 }
1020 # just want diagonals which are matches (A matched A, C -> C)
1021  
1022 2 my $m = ( $matrix->[0]->[0] + $matrix->[1]->[1] +
1023 $matrix->[2]->[2] + $matrix->[3]->[3] );
1024 2 my $D = 1 - ( $m / $slen);
1025 2 my $d;
1026 2 ▶ if( $h == 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($h == 0) { } 0 2 2
1027 0 $d = -1;
1028 } else {
1029 2 my $b = (1 - $fij2 + (($D**2)/$h)) / 2;
1030 2 my $c = 1- $D/ $b;
1031  
1032 2 ▶ if( $c < 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($c < 0) { } 0 2 2
1033 0 $d = -1;
1034 } else {
1035 2 $d = (-1 * $b) * log ( $c);
1036 }
1037 }
1038 # fwd and rev lookup
1039 2 $dist{$names[$i]}->{$names[$j]} = [$i,$j];
1040 2 $dist{$names[$j]}->{$names[$i]} = [$i,$j];
1041 2 $values[$j][$i] = $values[$i][$j] = sprintf($precisionstr,$d);
1042  
1043 # (diagonals) distance is 0 for same sequence
1044 2 $dist{$names[$j]}->{$names[$j]} = [$j,$j];
1045 2 $values[$j][$j] = sprintf($precisionstr,0);
1046 }
1047 }
1048 2 return Bio::Matrix::PhylipDist->new(-program => 'bioperl_DNAstats',
1049 -matrix => \%dist,
1050 -names => \@names,
1051 -values => \@values);
1052  
1053 }
1054  
1055 # Jin and Nei, Mol. Biol. Evol. 82, 7, 1990.
1056  
1057 =head2 D_JinNei
1058  
1059 Title : D_JinNei
1060 Usage : my $d = $stat->D_JinNei($aln)
1061 Function: Calculates D (pairwise distance) between 2 sequences in an
1062 alignment using the Jin-Nei 1990 distance model.
1063 Returns : L<Bio::Matrix::PhylipDist>
1064 Args : L<Bio::Align::AlignI> of DNA sequences
1065  
1066  
1067 =cut
1068  
1069 0 ▶sub D_JinNei{
Subroutine D_JinNei: not called CC=1 SCAR=6.9
Pod documented
1070 0 my ($self,@args) = @_;
1071 0 $self->warn("JinNei implementation not completed");
1072 0 return;
1073 }
1074  
1075 =head2 transversions
1076  
1077 Title : transversions
1078 Usage : my $transversions = $stats->transversion($aln);
1079 Function: Calculates the number of transversions between two sequences in
1080 an alignment
1081 Returns : integer
1082 Args : Bio::Align::AlignI
1083  
1084  
1085 =cut
1086  
1087 6 ▶sub transversions{
Subroutine transversions: called CC=1 SCAR=0.0
Pod documented
1088 6 my ($self,$aln) = @_;
1089 6 return $self->_trans_count_helper($aln, $DNAChanges{'Transversions'});
1090 }
1091  
1092 =head2 transitions
1093  
1094 Title : transitions
1095 Usage : my $transitions = Bio::Align::DNAStatistics->transitions($aln);
1096 Function: Calculates the number of transitions in a given DNA alignment
1097 Returns : integer representing the number of transitions
1098 Args : Bio::Align::AlignI object
1099  
1100  
1101 =cut
1102  
1103 6 ▶sub transitions{
Subroutine transitions: called CC=1 SCAR=0.0
Pod documented
1104 6 my ($self,$aln) = @_;
1105 6 return $self->_trans_count_helper($aln, $DNAChanges{'Transitions'});
1106 }
1107  
1108  
1109 12 ▶sub _trans_count_helper {
Subroutine _trans_count_helper: called CC=8 SCAR=20.9
1110 12 my ($self,$aln,$type) = @_;
1111 12 ▶ return 0 unless( $self->_check_arg($aln) );
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_check_arg($aln) 0 12 12
1112 0 ▶ if( ! $aln->is_flush ) { $self->throw("must be flush") }
Branch: 1 branch
BranchTrueFalseTotal
unless ($aln->is_flush) 0 12 12
1113 12 my (@tcount);
1114 12 my ($first,$second) = ( uc $aln->get_seq_by_pos(1)->seq(),
1115 uc $aln->get_seq_by_pos(2)->seq() );
1116 12 my $alen = $aln->length;
1117 12 ▶ for (my $i = 0;$i<$alen; $i++ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < $alen) 2298 12 2310
1118 2298 my ($c1,$c2) = ( substr($first,$i,1),
1119 substr($second,$i,1) );
1120 2298 ▶ if( $c1 ne $c2 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($c1 ne $c2) 480 1818 2298
1121 480 foreach my $nt ( @{$type->{$c1}} ) {
1122 477 ▶ if( $nt eq $c2) {
Branch: 1 branch
BranchTrueFalseTotal
if ($nt eq $c2) 120 357 477
1123 120 $tcount[$i]++;
1124 }
1125 }
1126 }
1127 }
1128 12 my $sum = 0;
1129 12 ▶ map { if( $_) { $sum += $_} } @tcount;
Branch: 1 branch
BranchTrueFalseTotal
if ($_) 120 1905 2025
1130 12 return $sum;
1131 }
1132  
1133 # this will generate a matrix which records across the row, the number
1134 # of DNA subst
1135 #
1136 13 ▶sub _build_nt_matrix {
Subroutine _build_nt_matrix: called CC=6 SCAR=18.0
1137 13 my ($self,$seqa,$seqb) = @_;
1138
1139  
1140 13 my $basect_matrix = [ [ qw(0 0 0 0) ], # number of bases that match
1141 [ qw(0 0 0 0) ],
1142 [ qw(0 0 0 0) ],
1143 [ qw(0 0 0 0) ] ];
1144 13 my $gaps = 0; # number of gaps
1145 13 my $pfreq = [ qw( 0 0 0 0 0 0)]; # matrix for pair frequency
1146 13 my $len_a = length($seqa);
1147 13 ▶ for( my $i = 0; $i < $len_a; $i++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < $len_a) 1656 13 1669
1148 1656 my ($ti,$tj) = (substr($seqa,$i,1),substr($seqb,$i,1));
1149 1656 $ti =~ tr/U/T/;
1150 1656 $tj =~ tr/U/T/;
1151  
1152 1656 ▶ if( $ti =~ /^$GapChars$/) { $gaps++; next; }
Branch: 1 branch
BranchTrueFalseTotal
if ($ti =~ /^$Bio::Align::DNAStatistics::GapChars$/) 121 1535 1656
1153 1535 ▶ if( $tj =~ /^$GapChars$/) { $gaps++; next }
Branch: 1 branch
BranchTrueFalseTotal
if ($tj =~ /^$Bio::Align::DNAStatistics::GapChars$/) 183 1352 1535
1154  
1155 1352 my $ti_index = $NucleotideIndexes{$ti};
1156 1352 my $tj_index = $NucleotideIndexes{$tj};
1157  
1158 1352 ▶ if( ! defined $ti_index ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $ti_index) 0 1352 1352
1159 0 $self->warn("ti_index not defined for $ti\n");
1160 0 next;
1161 }
1162
1163 1352 $basect_matrix->[$ti_index]->[$tj_index]++;
1164
1165 1352 ▶ if( $ti ne $tj ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ti ne $tj) 153 1199 1352
1166 153 $pfreq->[$NucleotideIndexes{join('',sort ($ti,$tj))}]++;
1167 }
1168 }
1169 13 return ($basect_matrix,$pfreq,$gaps);
1170 }
1171  
1172 0 ▶sub _check_ambiguity_nucleotide {
Subroutine _check_ambiguity_nucleotide: not called CC=4 SCAR=30.0
1173 0 my ($base1,$base2) = @_;
1174 0 my %iub = Bio::Tools::IUPAC->iupac_iub();
1175 0 my @amb1 = @{ $iub{uc($base1)} };
1176 0 my @amb2 = @{ $iub{uc($base2)} };
1177 0 my ($pmatch) = (0);
1178 0 for my $amb ( @amb1 ) {
1179 0 ▶ if( grep { $amb eq $_ } @amb2 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (grep {$amb eq $_;} @amb2) 0 0 0
1180 0 $pmatch = 1;
1181 0 last;
1182 }
1183 }
1184 0 ▶ if( $pmatch ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($pmatch) { } 0 0 0
1185 0 return (1 / scalar @amb1) * (1 / scalar @amb2);
1186 } else {
1187 0 return 0;
1188 }
1189 }
1190  
1191  
1192 24 ▶sub _check_arg {
Subroutine _check_arg: called CC=4 SCAR=19.4
1193 24 my($self,$aln ) = @_;
1194 24 ▶ if( ! defined $aln || ! $aln->isa('Bio::Align::AlignI') ) {
Branch: 2 branches
BranchTrueFalseTotal
if (not defined $aln && $aln->isa('Bio::Align::AlignI')) { } 0 24 24
elsif ($aln->get_seq_by_pos(1)->alphabet ne 'dna') { } 0 24 24
Condition33%1/3
defined $aln && $aln->isa('Bio::Align::AlignI')
!ll&&!rl&&r
0024
MC/DC0%0/2
defined $aln && $aln->isa('Bio::Align::AlignI')
defined $aln $aln->isa('Bio::Align::AlignI')
Truth table33%1/3
A && B
A= defined $alnB= $aln->isa('Bio::Align::AlignI')
ABresult
0X0
100
111
1195 0 $self->warn("Must provide a Bio::Align::AlignI compliant object to Bio::Align::DNAStatistics");
1196 0 return 0;
1197 } elsif( $aln->get_seq_by_pos(1)->alphabet ne 'dna' ) {
1198 0 $self->warn("Must provide a DNA alignment to Bio::Align::DNAStatistics, you provided a " . $aln->get_seq_by_pos(1)->alphabet);
1199 0 return 0;
1200 }
1201 24 return 1;
1202 }
1203  
1204 =head2 Data Methods
1205  
1206 =cut
1207  
1208 =head2 pairwise_stats
1209  
1210 Title : pairwise_stats
1211 Usage : $obj->pairwise_stats($newval)
1212 Function:
1213 Returns : value of pairwise_stats
1214 Args : newvalue (optional)
1215  
1216  
1217 =cut
1218  
1219 18 ▶sub pairwise_stats{
Subroutine pairwise_stats: called CC=2 SCAR=6.9
Pod documented
1220 18 my ($self,$value) = @_;
1221 18 ▶ if( defined $value) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $value) 2 16 18
1222 2 $self->{'_pairwise_stats'} = $value;
1223 }
1224 18 return $self->{'_pairwise_stats'};
1225  
1226 }
1227  
1228 =head2 calc_KaKs_pair
1229  
1230 Title : calc_KaKs_pair
1231 Useage : my $results = $stats->calc_KaKs_pair($alnobj,
1232 $name1, $name2).
1233 Function : calculates Nei-Gojobori statistics for pairwise
1234 comparison.
1235 Args : A Bio::Align::AlignI compliant object such as a
1236 Bio::SimpleAlign object, and 2 sequence name strings.
1237 Returns : a reference to a hash of statistics with keys as
1238 listed in Description.
1239  
1240 =cut
1241  
1242 1 ▶sub calc_KaKs_pair {
Subroutine calc_KaKs_pair: called CC=4 SCAR=14.6
Pod documented
1243 1 my ( $self, $aln, $seq1_id, $seq2_id) = @_;
1244 1 ▶ $self->throw("Needs 3 arguments - an alignment object, and 2 sequence ids")
Branch: 1 branch
BranchTrueFalseTotal
if @_ != 4 0 1 1
1245 if @_!= 4;
1246 1 ▶ $self->throw ("This calculation needs a Bio::Align::AlignI compatible object, not a [ " . ref($aln) . " ]object") unless $aln->isa('Bio::Align::AlignI');
Branch: 1 branch
BranchTrueFalseTotal
unless $aln->isa("Bio::Align::AlignI") 0 1 1
1247 1 my @seqs = (
1248 #{id => $seq1_id, seq =>($aln->each_seq_with_id($seq1_id))[0]->seq},
1249 #{id => $seq2_id, seq =>($aln->each_seq_with_id($seq2_id))[0]->seq}
1250 {id => $seq1_id, seq => uc(($aln->each_seq_with_id($seq1_id))[0]->seq)},
1251 {id => $seq2_id, seq => uc(($aln->each_seq_with_id($seq2_id))[0]->seq)}
1252 ) ;
1253 1 ▶ if (length($seqs[0]{'seq'}) != length($seqs[1]{'seq'})) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $seqs[0]{"seq"} != length $seqs[1]{"seq"}) 0 1 1
1254 0 $self->throw(" aligned sequences must be of equal length!");
1255 }
1256 1 my $results = [];
1257 1 $self->_get_av_ds_dn(\@seqs, $results);
1258 1 return $results;
1259  
1260 }
1261  
1262 =head2 calc_all_KaKs_pairs
1263  
1264 Title : calc_all_KaKs_pairs
1265 Useage : my $results2 = $stats->calc_KaKs_pair($alnobj).
1266 Function : Calculates Nei_gojobori statistics for all pairwise
1267 combinations in sequence.
1268 Arguments: A Bio::Align::ALignI compliant object such as
1269 a Bio::SimpleAlign object.
1270 Returns : A reference to an array of hashes of statistics of
1271 all pairwise comparisons in the alignment.
1272  
1273 =cut
1274  
1275  
1276  
1277 1 ▶sub calc_all_KaKs_pairs {
Subroutine calc_all_KaKs_pairs: called CC=3 SCAR=11.0
Pod documented
1278 #returns a multi_element_array with all pairwise comparisons
1279 1 my ($self,$aln) = @_;
1280 1 ▶ $self->throw ("This calculation needs a Bio::Align::AlignI compatible object, not a [ " . ref($aln) . " ]object") unless $aln->isa('Bio::Align::AlignI');
Branch: 1 branch
BranchTrueFalseTotal
unless $aln->isa("Bio::Align::AlignI") 0 1 1
1281 1 my @seqs;
1282 1 for my $seq ($aln->each_seq) {
1283 3 push @seqs, {id => $seq->display_id, seq=>$seq->seq};
1284 }
1285 1 my $results ;
1286 1 $results = $self->_get_av_ds_dn(\@seqs, $results);
1287 1 return $results;
1288 }
1289  
1290 =head2 calc_average_KaKs
1291  
1292 Title : calc_average_KaKs.
1293 Useage : my $res= $stats->calc_average_KaKs($alnobj, 1000).
1294 Function : calculates Nei_Gojobori stats for average of all
1295 sequences in the alignment.
1296 Args : A Bio::Align::AlignI compliant object such as a
1297 Bio::SimpleAlign object, number of bootstrap iterations
1298 (default 1000).
1299 Returns : A reference to a hash of statistics as listed in Description.
1300  
1301 =cut
1302  
1303 1 ▶sub calc_average_KaKs {
Subroutine calc_average_KaKs: called CC=4 SCAR=14.0
Pod documented
1304 #calculates global value for sequences in alignment using bootstrapping
1305 #this is quite slow (~10 seconds per 3 X 200nt seqs);
1306 1 my ($self, $aln, $bootstrap_rpt) = @_;
1307 1 ▶ $bootstrap_rpt ||= 1000;
Condition50%1/2
$bootstrap_rpt ||= 1000
l!l
10
MC/DC0%0/1
$bootstrap_rpt ||= 1000
$bootstrap_rpt
Truth table50%1/2
A
A= $bootstrap_rpt
Aresult
11
00
1308 1 ▶ $self->throw ("This calculation needs a Bio::Align::AlignI compatible object, not a [ " . ref($aln) . " ]object") unless $aln->isa('Bio::Align::AlignI');
Branch: 1 branch
BranchTrueFalseTotal
unless $aln->isa("Bio::Align::AlignI") 0 1 1
1309 1 my @seqs;
1310 1 for my $seq ($aln->each_seq) {
1311 3 push @seqs, {id => $seq->display_id, seq=>$seq->seq};
1312 }
1313 1 my $results ;
1314 1 my ($ds_orig, $dn_orig) = $self->_get_av_ds_dn(\@seqs);
1315 #print "ds = $ds_orig, dn = $dn_orig\n";
1316 1 $results = {D_s => $ds_orig, D_n => $dn_orig};
1317 1 $self->_run_bootstrap(\@seqs, $results, $bootstrap_rpt);
1318 1 return $results;
1319 }
1320  
1321 ############## primary internal subs for alignment comparisons ########################
1322  
1323 1 ▶sub _run_bootstrap {
Subroutine _run_bootstrap: called CC=4 SCAR=13.9
1324 ### generates sampled sequences, calculates Ds and Dn values,
1325 ### then calculates variance of sampled sequences and add results to results hash
1326 ###
1327 1 my ($self,$seq_ref, $results, $bootstrap_rpt) = @_;
1328 1 my @seqs = @$seq_ref;
1329 1 my @btstrp_aoa; # to hold array of array of nucleotides for resampling
1330 1 my %bootstrap_values = (ds => [], dn =>[]); # to hold list of av values
1331  
1332 #1st make alternative array of codons;
1333 1 my $c = 0;
1334 1 ▶ while ($c < length $seqs[0]{'seq'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($c < length $seqs[0]{"seq"}) 57 1 58
1335 57 for (0..$#seqs) {
1336 171 push @{$btstrp_aoa[$_]}, substr ($seqs[$_]{'seq'}, $c, 3);
1337 }
1338 57 $c+=3;
1339 }
1340  
1341 1 for (1..$bootstrap_rpt) {
1342 100 my $sampled = _resample (\@btstrp_aoa);
1343 100 my ($ds, $dn) = $self->_get_av_ds_dn ($sampled) ; # is array ref
1344 100 push @{$bootstrap_values{'ds'}}, $ds;
1345 100 push @{$bootstrap_values{'dn'}}, $dn;
1346 }
1347  
1348 1 $results->{'D_s_var'} = sampling_variance($bootstrap_values{'ds'});
1349 1 $results->{'D_n_var'} = sampling_variance($bootstrap_values{'dn'});
1350 $results->{'z_score'} = ($results->{'D_n'} - $results->{'D_s'}) /
1351 1 sqrt($results->{'D_s_var'} + $results->{'D_n_var'} );
1352 #print "bootstrapped var_syn = $results->{'D_s_var'} \n" ;
1353 #print "bootstrapped var_nc = $results->{'D_n_var'} \n";
1354 #print "z is $results->{'z_score'}\n"; ### end of global set up of/perm look up data
1355 }
1356  
1357 100 ▶sub _resample {
Subroutine _resample: called CC=4 SCAR=13.9
1358 100 my $ref = shift;
1359 100 my $codon_num = scalar (@{$ref->[0]});
1360 100 my @altered;
1361 100 for (0..$codon_num -1) { #for each codon
1362 5700 my $rand = int (rand ($codon_num));
1363 5700 for (0..$#$ref) {
1364 17100 push @{$altered[$_]}, $ref->[$_][$rand];
1365 }
1366 }
1367 100 my @stringed = map {join '', @$_}@altered;
1368 100 my @return;
1369 #now out in random name to keep other subs happy
1370 100 for (@stringed) {
1371 300 push @return, {id=>'1', seq=> $_};
1372 }
1373 100 return \@return;
1374 }
1375  
1376 103 ▶sub _get_av_ds_dn {
Subroutine _get_av_ds_dn: called CC=15 SCAR=27.8
1377 # takes array of hashes of sequence strings and ids #
1378 103 my $self = shift;
1379 103 my $seq_ref = shift;
1380 103 ▶ my $result = shift if @_;
Branch: 1 branch
BranchTrueFalseTotal
if @_ 2 101 103
1381 103 my @caller = caller(1);
1382 103 my @seqarray = @$seq_ref;
1383 103 my $bootstrap_score_list;
1384 #for a multiple alignment considers all pairwise combinations#
1385 103 my %dsfor_average = (ds => [], dn => []);
1386 103 ▶ for (my $i = 0; $i < scalar @seqarray; $i++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < scalar @seqarray) 308 103 411
1387 308 ▶ for (my $j = $i +1; $j<scalar @seqarray; $j++ ){
Branch: 1 branch
BranchTrueFalseTotal
if ($j < scalar @seqarray) 307 308 615
1388 # print "comparing $i and $j\n";
1389 307 ▶ if (length($seqarray[$i]{'seq'}) != length($seqarray[$j]{'seq'})) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $seqarray[$i]{"seq"} != length $seqarray[$j]{"seq"}) 0 307 307
1390 0 $self->warn(" aligned sequences must be of equal length!");
1391 0 next;
1392 }
1393  
1394 307 my $syn_site_count = count_syn_sites($seqarray[$i]{'seq'}, $synsites);
1395 307 my $syn_site_count2 = count_syn_sites($seqarray[$j]{'seq'}, $synsites);
1396 # print "syn 1 is $syn_site_count , syn2 is $syn_site_count2\n";
1397 307 my ($syn_count, $non_syn_count, $gap_cnt) = analyse_mutations($seqarray[$i]{'seq'}, $seqarray[$j]{'seq'});
1398 #get averages
1399 307 my $av_s_site = ($syn_site_count + $syn_site_count2)/2;
1400 307 my $av_ns_syn_site = length($seqarray[$i]{'seq'}) - $gap_cnt- $av_s_site ;
1401  
1402 #calculate ps and pn (p54)
1403 307 my $syn_prop = $syn_count / $av_s_site;
1404 307 my $nc_prop = $non_syn_count / $av_ns_syn_site ;
1405  
1406 #now use jukes/cantor to calculate D_s and D_n, would alter here if needed a different method
1407 307 my $d_syn = $self->jk($syn_prop);
1408 307 my $d_nc = $self->jk($nc_prop);
1409  
1410 #JK calculation must succeed for continuation of calculation
1411 #ret_value = -1 if error
1412 307 ▶ next unless $d_nc >=0 && $d_syn >=0;
Branch: 1 branch
BranchTrueFalseTotal
unless $d_nc >= 0 and $d_syn >= 0 0 307 307
Condition33%1/3
$d_nc >= 0 and $d_syn >= 0
!ll&&!rl&&r
00307
MC/DC0%0/2
$d_nc >= 0 and $d_syn >= 0
$d_nc >= 0 $d_syn >= 0
Truth table33%1/3
A and B
A= $d_nc >= 0B= $d_syn >= 0
ABresult
0X0
100
111
1413  
1414  
1415 307 push @{$dsfor_average{'ds'}}, $d_syn;
1416 307 push @{$dsfor_average{'dn'}}, $d_nc;
1417  
1418 #if not doing bootstrap, calculate the pairwise comparisin stats
1419 307 ▶ if ($caller[3] =~ /calc_KaKs_pair/ || $caller[3] =~ /calc_all_KaKs_pairs/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($caller[3] =~ /calc_KaKs_pair/ or $caller[3] =~ /calc_all_KaKs_pairs/) 4 303 307
Condition100%3/3
$caller[3] =~ /calc_KaKs_pair/ or $caller[3] =~ /calc_all_KaKs_pairs/
l!l&&r!l&&!r
13303
MC/DC100%2/2
$caller[3] =~ /calc_KaKs_pair/ or $caller[3] =~ /calc_all_KaKs_pairs/
$caller[3] =~ /calc_KaKs_pair/ $caller[3] =~ /calc_all_KaKs_pairs/
Truth table100%3/3
A or B
A= $caller[3] =~ /calc_KaKs_pair/B= $caller[3] =~ /calc_all_KaKs_pairs/
ABresult
1X1
011
000
1420 #now calculate variances assuming large sample
1421 4 my $d_syn_var = jk_var($syn_prop, length($seqarray[$i]{'seq'}) - $gap_cnt );
1422 4 my $d_nc_var = jk_var($nc_prop, length ($seqarray[$i]{'seq'}) - $gap_cnt);
1423 #now calculate z_value
1424 #print "d_syn_var is $d_syn_var,and d_nc_var is $d_nc_var\n";
1425 #my $z = ($d_nc - $d_syn) / sqrt($d_syn_var + $d_nc_var);
1426 4 ▶ my $z = ($d_syn_var + $d_nc_var) ?
Branch: 1 branch
BranchTrueFalseTotal
$d_syn_var + $d_nc_var ? : 4 0 4
1427 ($d_nc - $d_syn) / sqrt($d_syn_var + $d_nc_var) : 0;
1428 # print "z is $z\n";
1429 push @$result , {S => $av_s_site, N=>$av_ns_syn_site,
1430 S_d => $syn_count, N_d =>$non_syn_count,
1431 P_s => $syn_prop, P_n=>$nc_prop,
1432 4 D_s => @{$dsfor_average{'ds'}}[-1],
1433 4 D_n => @{$dsfor_average{'dn'}}[-1],
1434 D_n_var =>$d_nc_var, D_s_var => $d_syn_var,
1435 Seq1 => $seqarray[$i]{'id'},
1436 4 Seq2 => $seqarray[$j]{'id'},
1437 z_score => $z,
1438 };
1439 4 ▶ $self->warn (" number of mutations too small to justify normal test for $seqarray[$i]{'id'} and $seqarray[$j]{'id'}\n- use Fisher's exact, or bootstrap a MSA")
Branch: 1 branch
BranchTrueFalseTotal
if $syn_count < 10 || $non_syn_count < 10 and $self->verbose > -1 0 4 4
Condition33%2/6
$syn_count < 10 || $non_syn_count < 10 and $self->verbose > -1
!ll&&!rl&&r
040
$syn_count < 10 or $non_syn_count < 10
l!l&&r!l&&!r
400
MC/DC0%0/3
$syn_count < 10 || $non_syn_count < 10 and $self->verbose > -1
$syn_count < 10 $non_syn_count < 10 $self->verbose > -1
Truth table20%1/5
A or B and C
A= $syn_count < 10B= $non_syn_count < 10C= $self->verbose > -1
ABCresult
00X0
1X00
0100
1X11
0111
1440 if ($syn_count < 10 || $non_syn_count < 10 ) && $self->verbose > -1 ;
1441 }#endif
1442 }
1443 }
1444  
1445 #warn of failure if no results hashes are present
1446 #will fail if Jukes Cantor has failed for all pairwise combinations
1447 #$self->warn("calculation failed!") if scalar @$result ==0;
1448  
1449 #return results unless bootstrapping
1450 103 ▶ return $result if $caller[3]=~ /calc_all_KaKs/ || $caller[3] =~ /calc_KaKs_pair/;
Branch: 1 branch
BranchTrueFalseTotal
if $caller[3] =~ /calc_all_KaKs/ or $caller[3] =~ /calc_KaKs_pair/ 2 101 103
Condition100%3/3
$caller[3] =~ /calc_all_KaKs/ or $caller[3] =~ /calc_KaKs_pair/
l!l&&r!l&&!r
11101
MC/DC100%2/2
$caller[3] =~ /calc_all_KaKs/ or $caller[3] =~ /calc_KaKs_pair/
$caller[3] =~ /calc_all_KaKs/ $caller[3] =~ /calc_KaKs_pair/
Truth table100%3/3
A or B
A= $caller[3] =~ /calc_all_KaKs/B= $caller[3] =~ /calc_KaKs_pair/
ABresult
1X1
011
000
1451 #else if getting average for bootstrap
1452 101 return( mean ($dsfor_average{'ds'}),mean ($dsfor_average{'dn'})) ;
1453 }
1454  
1455  
1456 614 ▶sub jk {
Subroutine jk: called CC=2 SCAR=8.4
Pod undocumented
1457 614 my ($self, $p) = @_;
1458 614 ▶ if ($p > 0.75) {
Branch: 1 branch
BranchTrueFalseTotal
if ($p > "0.75") 0 614 614
1459 0 $self->warn( " Jukes Cantor won't work -too divergent!");
1460 0 return -1;
1461 }
1462 614 return -1 * (3/4) * (log(1 - (4/3) * $p));
1463 }
1464  
1465 #works for large value of n (50?100?)
1466 8 ▶sub jk_var {
Subroutine jk_var: called CC=1 SCAR=0.0
Pod undocumented
1467 8 my ($p, $n) = @_;
1468 8 return (9 * $p * (1 -$p))/(((3 - 4 *$p) **2) * $n);
1469 }
1470  
1471  
1472 # compares 2 sequences to find the number of synonymous/non
1473 # synonymous mutations between them
1474  
1475 307 ▶sub analyse_mutations {
Subroutine analyse_mutations: called CC=16 SCAR=36.1
Pod undocumented
1476 307 my ($seq1, $seq2) = @_;
1477 307 my %mutator = ( 2=> {0=>[[1,2], # codon positions to be altered
1478 [2,1]], # depend on which is the same
1479 1=>[[0,2],
1480 [2,0]],
1481 2=>[[0,1],
1482 [1,0]],
1483 },
1484 3=> [ [0,1,2], # all need to be altered
1485 [1,0,2],
1486 [0,2,1],
1487 [1,2,0],
1488 [2,0,1],
1489 [2,1,0] ],
1490 );
1491 307 my $TOTAL = 0; # total synonymous changes
1492 307 my $TOTAL_n = 0; # total non-synonymous changes
1493 307 my $gap_cnt = 0;
1494  
1495 307 my %input;
1496 307 my $seqlen = length($seq1);
1497 307 ▶ for (my $j=0; $j< $seqlen; $j+=3) {
Branch: 1 branch
BranchTrueFalseTotal
if ($j < $seqlen) 17499 307 17806
1498 17499 $input{'cod1'} = substr($seq1, $j,3);
1499 17499 $input{'cod2'} = substr($seq2, $j,3);
1500  
1501 #ignore codon if beeing compared with gaps!
1502 17499 ▶ if ($input{'cod1'} =~ /\-/ || $input{'cod2'} =~ /\-/){
Branch: 1 branch
BranchTrueFalseTotal
if ($input{"cod1"} =~ /\-/ or $input{"cod2"} =~ /\-/) 0 17499 17499
Condition33%1/3
$input{"cod1"} =~ /\-/ or $input{"cod2"} =~ /\-/
l!l&&r!l&&!r
0017499
MC/DC0%0/2
$input{"cod1"} =~ /\-/ or $input{"cod2"} =~ /\-/
$input{"cod1"} =~ /\-/ $input{"cod2"} =~ /\-/
Truth table33%1/3
A or B
A= $input{"cod1"} =~ /\-/B= $input{"cod2"} =~ /\-/
ABresult
1X1
011
000
1503 0 $gap_cnt += 3; #just increments once if there is a pair of gaps
1504 0 next;
1505 }
1506  
1507 17499 my ($diff_cnt, $same) = count_diffs(\%input);
1508  
1509 #ignore if codons are identical
1510 17499 ▶ next if $diff_cnt == 0 ;
Branch: 1 branch
BranchTrueFalseTotal
if $diff_cnt == 0 12588 4911 17499
1511 4911 ▶ if ($diff_cnt == 1) {
Branch: 3 branches
BranchTrueFalseTotal
if ($diff_cnt == 1) { } 3899 1012 4911
elsif ($diff_cnt == 2) { } 1012 0 1012
elsif ($diff_cnt == 3) { } 0 0 0
1512 3899 $TOTAL += $synchanges{$input{'cod1'}}{$input{'cod2'}};
1513 3899 $TOTAL_n += 1 - $synchanges{$input{'cod1'}}{$input{'cod2'}};
1514 #print " \nfordiff is 1 , total now $TOTAL, total n now $TOTAL_n\n\n"
1515 }
1516 elsif ($diff_cnt ==2) {
1517 1012 my $s_cnt = 0;
1518 1012 my $n_cnt = 0;
1519 1012 my $tot_muts = 4;
1520 #will stay 4 unless there are stop codons at intervening point
1521 1012 OUTER:for my $perm (@{$mutator{'2'}{$same}}) {
1522 2024 my $altered = $input{'cod1'};
1523 2024 my $prev= $altered;
1524 # print "$prev -> (", $t[$CODONS->{$altered}], ")";
1525 2024 for my $mut_i (@$perm) { #index of codon mutated
1526 4048 substr($altered, $mut_i,1) = substr($input{'cod2'}, $mut_i, 1);
1527 4048 ▶ if ($t[$CODONS->{$altered}] eq '*') {
Branch: 1 branch
BranchTrueFalseTotal
if ($t[$Bio::Align::DNAStatistics::CODONS->{$altered}] eq '*') { } 0 4048 4048
1528 0 $tot_muts -=2;
1529 #print "changes to stop codon!!\n";
1530 0 next OUTER;
1531 }
1532 else {
1533 4048 $s_cnt += $synchanges{$prev}{$altered};
1534 # print "$altered ->(", $t[$CODONS->{$altered}], ") ";
1535 }
1536 4048 $prev = $altered;
1537 }
1538 # print "\n";
1539 }
1540 1012 ▶ if ($tot_muts != 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($tot_muts != 0) 1012 0 1012
1541 1012 $TOTAL += ($s_cnt/($tot_muts/2));
1542 1012 $TOTAL_n += ($tot_muts - $s_cnt)/ ($tot_muts / 2);
1543 }
1544  
1545 }
1546 elsif ($diff_cnt ==3 ) {
1547 0 my $s_cnt = 0;
1548 0 my $n_cnt = 0;
1549 0 my $tot_muts = 18; #potential number of mutations
1550 0 OUTER: for my $perm (@{$mutator{'3'}}) {
1551 0 my $altered = $input{'cod1'};
1552 0 my $prev= $altered;
1553 # print "$prev -> (", $t[$CODONS->{$altered}], ")";
1554 0 for my $mut_i (@$perm) { #index of codon mutated
1555 0 substr($altered, $mut_i,1) = substr($input{'cod2'}, $mut_i, 1);
1556 0 ▶ if ($t[$CODONS->{$altered}] eq '*') {
Branch: 1 branch
BranchTrueFalseTotal
if ($t[$Bio::Align::DNAStatistics::CODONS->{$altered}] eq '*') { } 0 0 0
1557 0 $tot_muts -=3;
1558 # print "changes to stop codon!!\n";
1559 0 next OUTER;
1560  
1561 }
1562 else {
1563 0 $s_cnt += $synchanges{$prev}{$altered};
1564 # print "$altered ->(", $t[$CODONS->{$altered}], ") ";
1565 }
1566 0 $prev = $altered;
1567 }
1568 # print "\n";
1569  
1570 }#end OUTER loop
1571 #calculate number of synonymous/non synonymous mutations for that codon
1572 # and add to total
1573 0 ▶ if ($tot_muts != 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($tot_muts != 0) 0 0 0
1574 0 $TOTAL += ($s_cnt / ($tot_muts /3));
1575 0 $TOTAL_n += 3 - ($s_cnt / ($tot_muts /3));
1576 }
1577 } #endif $diffcnt = 3
1578 } #end of sequencetraversal
1579 307 return ($TOTAL, $TOTAL_n, $gap_cnt);
1580 }
1581  
1582  
1583 17499 ▶sub count_diffs {
Subroutine count_diffs: called CC=3 SCAR=11.0
Pod undocumented
1584 #counts the number of nucleotide differences between 2 codons
1585 # returns this value plus the codon index of which nucleotide is the same when 2
1586 #nucleotides are different. This is so analyse_mutations() knows which nucleotides
1587 # to change.
1588 17499 my $ref = shift;
1589 17499 my $cnt = 0;
1590 17499 my $same= undef;
1591 #just for 2 differences
1592 17499 for (0..2) {
1593 52497 ▶ if (substr($ref->{'cod1'}, $_,1) ne substr($ref->{'cod2'}, $_, 1)){
Branch: 1 branch
BranchTrueFalseTotal
if (substr($ref->{'cod1'}, $_, 1) ne substr($ref->{'cod2'}, $_, 1)) { } 5923 46574 52497
1594 5923 $cnt++;
1595 } else {
1596 46574 $same = $_;
1597 }
1598 }
1599 17499 return ($cnt, $same);
1600 }
1601  
1602 =head2 get_syn_changes
1603  
1604 Title : get_syn_changes
1605 Usage : Bio::Align::DNAStatitics->get_syn_changes
1606 Function: Generate a hashref of all pairwise combinations of codns
1607 differing by 1
1608 Returns : Symetic matrix using hashes
1609 First key is codon
1610 and each codon points to a hashref of codons
1611 the values of which describe type of change.
1612 my $type = $hash{$codon1}->{$codon2};
1613 values are :
1614 1 synonymous
1615 0 non-syn
1616 -1 either codon is a stop codon
1617 Args : none
1618  
1619 =cut
1620  
1621 3 ▶sub get_syn_changes {
Subroutine get_syn_changes: called CC=9 SCAR=22.0
Pod documented
1622 #hash of all pairwise combinations of codons differing by 1
1623 # 1 = syn, 0 = non-syn, -1 = stop
1624 3 my %results;
1625 3 my @codons = _make_codons ();
1626 3 my $arr_len = scalar @codons;
1627 3 ▶ for (my $i = 0; $i < $arr_len -1; $i++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < $arr_len - 1) 189 3 192
1628 189 my $cod1 = $codons[$i];
1629 189 ▶ for (my $j = $i +1; $j < $arr_len; $j++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($j < $arr_len) 6048 189 6237
1630 6048 my $diff_cnt = 0;
1631 6048 for my $pos(0..2) {
1632 18144 ▶ $diff_cnt++ if substr($cod1, $pos, 1) ne substr($codons[$j], $pos, 1);
Branch: 1 branch
BranchTrueFalseTotal
if substr($cod1, $pos, 1) ne substr($codons[$j], $pos, 1) 13824 4320 18144
1633 }
1634 6048 ▶ next if $diff_cnt !=1;
Branch: 1 branch
BranchTrueFalseTotal
if $diff_cnt != 1 5184 864 6048
1635  
1636 #synon change
1637 864 ▶ if($t[$CODONS->{$cod1}] eq $t[$CODONS->{$codons[$j]}]) {
Branch: 2 branches
BranchTrueFalseTotal
if ($t[$Bio::Align::DNAStatistics::CODONS->{$cod1}] eq $t[$$Bio::Align::DNAStatistics::CODONS{$codons[$j]}]) { } 207 657 864
elsif ($t[$Bio::Align::DNAStatistics::CODONS->{$cod1}] eq '*' or $t[$$Bio::Align::DNAStatistics::CODONS{$codons[$j]}] eq '*') { } 69 588 657
1638 207 $results{$cod1}{$codons[$j]} =1;
1639 207 $results{$codons[$j]}{$cod1} = 1;
1640 }
1641 #stop codon
1642 ▶ elsif ($t[$CODONS->{$cod1}] eq '*' or $t[$CODONS->{$codons[$j]}] eq '*') {
Condition100%3/3
$t[$Bio::Align::DNAStatistics::CODONS->{$cod1}] eq "*" or $t[$$Bio::Align::DNAStatistics::CODONS{$codons[$j]}] eq "*"
l!l&&r!l&&!r
3336588
MC/DC100%2/2
$t[$Bio::Align::DNAStatistics::CODONS->{$cod1}] eq "*" or $t[$$Bio::Align::DNAStatistics::CODONS{$codons[$j]}] eq "*"
$t[$Bio::Align::DNAStatistics::CODONS->{$cod1}] eq "*" $t[$$Bio::Align::DNAStatistics::CODONS{$codons[$j]}] eq "*"
Truth table100%3/3
A or B
A= $t[$Bio::Align::DNAStatistics::CODONS->{$cod1}] eq "*"B= $t[$$Bio::Align::DNAStatistics::CODONS{$codons[$j]}] eq "*"
ABresult
1X1
011
000
1643 69 $results{$cod1}{$codons[$j]} = -1;
1644 69 $results{$codons[$j]}{$cod1} = -1;
1645 }
1646 # nc change
1647 else {
1648 588 $results{$cod1}{$codons[$j]} = 0;
1649 588 $results{$codons[$j]}{$cod1} = 0;
1650 }
1651 }
1652 }
1653 3 return %results;
1654 }
1655  
1656 =head2 dnds_pattern_number
1657  
1658 Title : dnds_pattern_number
1659 Usage : my $patterns = $stats->dnds_pattern_number($alnobj);
1660 Function: Counts the number of codons with no gaps in the MSA
1661 Returns : Number of codons with no gaps ('patterns' in PAML notation)
1662 Args : A Bio::Align::AlignI compliant object such as a
1663 Bio::SimpleAlign object.
1664  
1665 =cut
1666  
1667 0 ▶sub dnds_pattern_number{
Subroutine dnds_pattern_number: not called CC=1 SCAR=6.9
Pod documented
1668 0 my ($self, $aln) = @_;
1669 0 return ($aln->remove_gaps->length)/3;
1670 }
1671  
1672 615 ▶sub count_syn_sites {
Subroutine count_syn_sites: called CC=4 SCAR=13.9
Pod undocumented
1673 #counts the number of possible synonymous changes for sequence
1674 615 my ($seq, $synsite) = @_;
1675 615 ▶ __PACKAGE__->throw("not integral number of codons") if length($seq) % 3 != 0;
Branch: 1 branch
BranchTrueFalseTotal
if length($seq) % 3 != 0 1 614 615
1676 614 my $S = 0;
1677 614 ▶ for (my $i = 0; $i< length($seq); $i+=3) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < length $seq) 34998 614 35612
1678 34998 my $cod = substr($seq, $i, 3);
1679 34998 ▶ next if $cod =~ /\-/; #deal with alignment gaps
Branch: 1 branch
BranchTrueFalseTotal
if $cod =~ /\-/ 0 34998 34998
1680 34998 $S += $synsite->{$cod}{'s'};
1681 }
1682 #print "S is $S\n";
1683 614 return $S;
1684 }
1685  
1686
1687  
1688 3 ▶sub get_syn_sites {
Subroutine get_syn_sites: called CC=10 SCAR=23.0
Pod undocumented
1689 #sub to generate lookup hash for the number of synonymous changes per codon
1690 3 my @nucs = qw(T C A G);
1691 3 my %raw_results;
1692 3 for my $i (@nucs) {
1693 12 for my $j (@nucs) {
1694 48 for my $k (@nucs) {
1695 # for each possible codon
1696 192 my $cod = "$i$j$k";
1697 192 my $aa = $t[$CODONS->{$cod}];
1698 #calculate number of synonymous mutations vs non syn mutations
1699 192 for my $i (qw(0 1 2)){
1700 576 my $s = 0;
1701 576 my $n = 3;
1702 576 for my $nuc (qw(A T C G)) {
1703 2304 ▶ next if substr ($cod, $i,1) eq $nuc;
Branch: 1 branch
BranchTrueFalseTotal
if substr($cod, $i, 1) eq $nuc 576 1728 2304
1704 1728 my $test = $cod;
1705 1728 substr($test, $i, 1) = $nuc ;
1706 1728 ▶ if ($t[$CODONS->{$test}] eq $aa) {
Branch: 1 branch
BranchTrueFalseTotal
if ($t[$Bio::Align::DNAStatistics::CODONS->{$test}] eq $aa) 414 1314 1728
1707 414 $s++;
1708 }
1709 1728 ▶ if ($t[$CODONS->{$test}] eq '*') {
Branch: 1 branch
BranchTrueFalseTotal
if ($t[$Bio::Align::DNAStatistics::CODONS->{$test}] eq "*") 81 1647 1728
1710 81 $n--;
1711 }
1712 }
1713 576 $raw_results{$cod}[$i] = {'s' => $s ,
1714 'n' => $n };
1715 }
1716
1717 } #end analysis of single codon
1718 }
1719 } #end analysis of all codons
1720 3 my %final_results;
1721
1722 3 for my $cod (sort keys %raw_results) {
1723 192 my $t = 0;
1724 192 map{$t += ($_->{'s'} /$_->{'n'})} @{$raw_results{$cod}};
1725 192 $final_results{$cod} = { 's'=>$t, 'n' => 3 -$t};
1726 }
1727 3 return \%final_results;
1728 }
1729  
1730 6 ▶sub _make_codons {
Subroutine _make_codons: called CC=4 SCAR=13.9
1731 #makes all codon combinations, returns array of them
1732 6 my @nucs = qw(T C A G);
1733 6 my @codons;
1734 6 for my $i (@nucs) {
1735 24 for my $j (@nucs) {
1736 96 for my $k (@nucs) {
1737 384 push @codons, "$i$j$k";
1738 }
1739 }
1740 }
1741 6 return @codons;
1742 }
1743  
1744 3 ▶sub get_codons {
Subroutine get_codons: called CC=2 SCAR=6.9
Pod undocumented
1745 #generates codon translation look up table#
1746 3 my $x = 0;
1747 3 my $CODONS = {};
1748 3 for my $codon (_make_codons) {
1749 192 $CODONS->{$codon} = $x;
1750 192 $x++;
1751 }
1752 3 return $CODONS;
1753 }
1754  
1755 #########stats subs, can go in another module? Here for speed. ###
1756 204 ▶sub mean {
Subroutine mean: called CC=1 SCAR=0.0
Pod undocumented
1757 204 my $ref = shift;
1758 204 my $el_num = scalar @$ref;
1759 204 my $tot = 0;
1760 204 map{$tot += $_}@$ref;
1761 204 return ($tot/$el_num);
1762 }
1763  
1764 2 ▶sub variance {
Subroutine variance: called CC=1 SCAR=0.0
Pod undocumented
1765 2 my $ref = shift;
1766 2 my $mean = mean($ref);
1767 2 my $sum_of_squares = 0;
1768 2 map{$sum_of_squares += ($_ - $mean) **2}@$ref;
1769 2 return $sum_of_squares;
1770 }
1771  
1772 2 ▶sub sampling_variance {
Subroutine sampling_variance: called CC=1 SCAR=0.0
Pod undocumented
1773 2 my $ref = shift;
1774 2 return variance($ref) / (scalar @$ref -1);
1775 }
1776  
1777 3 1;
« Bio/SeqIO.pm ↑ Summary Bio/PrimarySeq.pm »