Genetics/API/Analysis.pm untested

filter: Statementstmt 0.0% 0 / 185 Branchbran 0.0% 0 / 24 Conditioncond 0.0% 0 / 45 MC/DCmcdc 0.0% 0 / 27 Subroutinesub 0.0% 0 / 11 Podpod 0.0% 0 / 7 totaltotal 0.0% 0 / 299 CC 13 SCAR 30.8
CC
13
Cov
0%
calculateSnpHW
56.0
graphAlleleFreqs
12.0
_formatFloat
12.0
CRAP 21.7
1 # GenPerl module
2 #
3  
4 # POD documentation - main docs before the code
5  
6 =head1 NAME
7  
8 Genetics::API::Analysis
9  
10 =head1 SYNOPSIS
11  
12 # The following code will produce a graph of allele frequencies in two
13 # different Subject Clusters
14  
15 $affCluster = $api->getObject({TYPE => "Cluster", NAME => "HT Affecteds"}) ;
16 $unaffCluster = $api->getObject({TYPE => "Cluster", NAME => "Normals"}) ;
17  
18 $marker = $api->getObject({TYPE => "Marker", NAME => "agtT174M"}) ;
19  
20 $api->graphAlleleFreqs(
21 MARKER => $marker,
22 FREQSOURCES => [ $affCluster, $unaffCluster ],
23 ALLELETYPE => "Nucleotide"
24 ) ;
25  
26 # The following code will perform a chi-square test on this same data
27  
28 $api->chiSquareAssocTest(
29 MARKER => $marker,
30 SC1 => $affCluster,
31 SC2 => $unaffCluster,
32 ALLELETYPE => "Nucleotide",
33 ) ;
34  
35 =head1 DESCRIPTION
36  
37 This package contains methods for the analysis of data contained in GenPerl
38 objects. Also see Genetics::API::Analysis::Linkage for methods relating to
39 genetic linkage analyses.
40  
41 =head1 LICENSE
42  
43 This program is free software; you can redistribute it and/or modify
44 it under the terms of the GNU General Public License as published by
45 the Free Software Foundation; either version 2 of the License, or
46 (at your option) any later version.
47  
48 This program is distributed in the hope that it will be useful,
49 but WITHOUT ANY WARRANTY; without even the implied warranty of
50 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
51 GNU General Public License for more details.
52  
53 You should have received a copy of the GNU General Public License
54 along with this program; if not, write to the Free Software
55 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
56  
57 =head1 FEEDBACK
58  
59 Currently, all feedback should be sent directly to the author.
60  
61 =head1 AUTHOR - Steve Mathias
62  
63 Email: mathias@genomica.com
64  
65 Phone: (720) 565-4029
66  
67 Address: Genomica Corporation
68 1745 38th Street
69 Boulder, CO 80301
70  
71 =head1 DETAILS
72  
73 The rest of the documentation describes each of the object variables and
74 methods. The names of internal variables and methods are preceded with an
75 underscore (_).
76  
77 =cut
78  
79 ##################
80 # #
81 # Begin the code #
82 # #
83 ##################
84  
85 package Genetics::API::Analysis ;
86  
87 BEGIN {
88 $ID = "Genetics::API::Analysis" ;
89 #$DEBUG = $main::DEBUG ;
90 $DEBUG = 0 ;
91 $DEBUG and warn "Debugging in $ID is on" ;
92 }
93  
94 =head1 Imported Packages
95  
96 strict Just to be anal
97 vars Global variables
98 Carp Error reporting
99 GD::Graph::bars Graphing allele frequencies
100 GD::Graph::colour Graphing allele frequencies
101 GD::Graph::Data Graphing allele frequencies
102  
103 =cut
104  
105 use strict ;
106 use vars qw(@ISA @EXPORT @EXPORT_OK $ID $DEBUG) ;
107 use Carp ;
108 use Exporter ;
109 #use GD::Graph::bars ; # Comment this out for distribution.
110 #use GD::Graph::colour ; # Comment this out for distribution.
111 #use GD::Graph::Data ; # Comment this out for distribution.
112  
113 =head1 Inheritance
114  
115 Exporter Make methods available to importing packages
116  
117 =cut
118  
119 @ISA = qw(Exporter) ;
120  
121 @EXPORT = qw(test calculateHet calculateSnpHW
122 chiSquareAssocTest graphAlleleFreqs
123 ) ;
124 @EXPORT_OK = qw();
125  
126  
127 =head1 Public Methods
128  
129 sub test {
130 my($self) = @_ ;
131 my($sth, $aoaRef) ;
132 my $dbh = $self->{dbh} ;
133  
134 $sth = $dbh->prepare( "select alleleCallID from AlleleCall
135 where gtID = 4009
136 and alleleID = 26" ) ;
137 $sth->execute() ;
138 $aoaRef = $sth->fetchall_arrayref() ;
139 print scalar(@$aoaRef), "\n" ;
140  
141 return(1) ;
142 }
143  
144 =head2 chiSquareAssocTest
145  
146 Function : Perform a simple chi-square association test.
147 Arguments : A Marker object, a string containing an allele type and two
148 Subject Cluster objects.
149 Returns : N/A
150 Scope : Public
151 Called by :
152 Comments :
153  
154 =cut
155  
156 sub chiSquareAssocTest {
157 my($self, %param) = @_ ;
158 my($marker, $alleleType, $sc1, $sc2, $clusterName, $alleleName, %counts,
159 %alleleNames, %totals, $total, $chiSquare, $obs, $exp, $part, $dof,
160 $i, $level, $names, $countsStr, @counts, $markerName) ;
161 my %ChiSquareDist = (
162 level => [0.95, 0.9, 0.8, 0.7, 0.5, 0.3, 0.2, 0.1, 0.05, 0.01, 0.001],
163 1 => [0.004, 0.02, 0.06, 0.15 , 0.46, 1.07, 1.64 , 2.71, 3.84, 6.64 , 10.83],
164 2 => [0.10, 0.21, 0.45, 0.71 , 1.39, 2.41, 3.22 , 4.60, 5.99, 9.21 , 13.82],
165 3 => [0.35, 0.58, 1.01, 1.42 , 2.37, 3.66, 4.64 , 6.25, 7.82, 11.34 , 16.27],
166 4 => [0.71, 1.06, 1.65, 2.20 , 3.36, 4.88, 5.99 , 7.78, 9.49, 13.28 , 18.47],
167 5 => [1.14, 1.61, 2.34, 3.00 , 4.35, 6.06, 7.29 , 9.24, 11.07, 15.09 , 20.52],
168 6 => [1.63, 2.20, 3.07, 3.83 , 5.35, 7.23, 8.56 , 10.64, 12.59, 16.81 , 22.46],
169 7 => [2.17, 2.83, 3.82, 4.67 , 6.35, 8.38, 9.80 , 12.02, 14.07, 18.48 , 24.32],
170 8 => [2.73, 3.49, 4.59, 5.53 , 7.34, 9.52, 11.03 , 13.36, 15.51, 20.09 , 26.12],
171 9 => [3.32, 4.17, 5.38, 6.39 , 8.34, 10.66, 12.24 , 14.68, 16.92, 21.67 , 27.88],
172 10 => [3.94, 4.86, 6.18, 7.27 , 9.34, 11.78, 13.44 , 15.99, 18.31, 23.21 , 29.59]
173 ) ;
174  
175 defined($marker = $param{MARKER}) or
176 croak "ERROR [chiSquareAssocTest]: No Marker!" ;
177 $markerName = $marker->name ;
178
179 defined($sc1 = $param{SC1}) or
180 croak "ERROR [chiSquareAssocTest]: No source(s) for allele frequencies!" ;
181 defined($sc2 = $param{SC2}) or
182 croak "ERROR [chiSquareAssocTest]: No source(s) for allele frequencies!" ;
183 defined($alleleType = $param{ALLELETYPE}) or $alleleType = "Code" ;
184
185 $clusterName = $sc1->name ;
186 $clusterName =~ s/\s+/_/g ;
187 $counts{$clusterName} = $self->getAlleleCounts($marker, $alleleType, $sc1) ;
188 $clusterName = $sc2->name ;
189 $clusterName =~ s/\s+/_/g ;
190 $counts{$clusterName} = $self->getAlleleCounts($marker, $alleleType, $sc2) ;
191  
192 # generate the totals
193 foreach $clusterName (keys %counts) {
194 foreach $alleleName (keys %{$counts{$clusterName}}) {
195 $alleleNames{$alleleName}++ ; # keep track of all allele names seen
196 $totals{$clusterName} += $counts{$clusterName}->{$alleleName} ;
197 $totals{$alleleName} += $counts{$clusterName}->{$alleleName} ;
198 }
199 $total += $totals{$clusterName} ;
200 }
201
202 # # see the counts
203 # foreach $clusterName (keys %counts) {
204 # print "Cluster: $clusterName\n" ;
205 # foreach $alleleName (sort keys %{$counts{$clusterName}}) {
206 # print "\t$alleleName -> $counts{$clusterName}->{$alleleName}\n" ;
207 # }
208 # }
209 # # see the totals
210 # foreach my $x (keys %totals) {
211 # print "Total for $x -> $totals{$x}\n" ;
212 # }
213 # print "Total: $total\n" ;
214  
215 # Calculate chisquare
216 print "Allele counts: \n\n" ;
217 print "\t\t", join( "\t", sort(keys(%alleleNames)) ), "\n" ;
218 foreach $clusterName (keys %counts) {
219 $countsStr = "" ;
220 @counts = () ;
221 foreach $alleleName ( sort(keys(%alleleNames)) ) {
222 push(@counts, $counts{$clusterName}->{$alleleName}) ;
223 $obs = $counts{$clusterName}->{$alleleName} ;
224 $exp = $totals{$clusterName} * $totals{$alleleName} / $total ;
225 $part = (($obs - $exp)**2)/$exp ;
226 $chiSquare += (($obs - $exp)**2)/$exp ;
227 #print "$clusterName $alleleName\n" ;
228 #print "(($obs - $exp)**2)/$exp = $part\n" ;
229 }
230 $countsStr = join("\t", @counts) ;
231 write ;
232 }
233 # Determine significance level
234 $dof = scalar(keys(%alleleNames)) - 1 ;
235 for ($i=0 ; $i<=10 ; $i++) {
236 #print "$i $chiSquare ? ", $ChiSquareDist{$dof}->[$i], "\n" ;
237 last if ($chiSquare <= $ChiSquareDist{$dof}->[$i]) ;
238 }
239 $level = $ChiSquareDist{level}->[$i-1] ;
240  
241 print "\nThe Chi-Square value is $chiSquare, with $dof degrees of freedom\n" ;
242 $names = join(" and ", keys(%counts)) ;
243 $markerName = $marker->field("name") ;
244 print "\nThe probability that the differences in allele distributions between Subject Clusters $names at marker $markerName is due to chance is less than $level.\n\n" ;
245  
246 format STDOUT =
247 @<<<<<<<<<<<<<< @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
248 $clusterName, $countsStr
249 .
250  
251 return(1) ;
252 }
253  
254 =head2 graphAlleleFreqs
255  
256 Function : Graph the allele frequencies for a Marker in a group of Subjects.
257 Arguments : A hash of parameters as follows
258 MARKER => The Marker object whose allele frequencies are to be graphed.
259 Required, for obvious reasons.
260 FREQSOURCES => Array pointer to a list of Cluster (Kindred or Subject)
261 and/or FrequencySource objects.
262 The source(s) for allele frequencies.
263 Required, for obvious reasons.
264 ALLELETYPE => The type of alleles whose frequencies are to be graphed.
265 Optional, the default value is "Code".
266 Returns : N/A
267 Scope : Public
268 Comments : Calls xv to display the graphic.
269  
270 =cut
271  
272 sub graphAlleleFreqs {
273 my($self, %param) = @_ ;
274 my($marker, $sourceListPtr, $alleleType, $markerName, @alleleNames, @data,
275 @sourceNames, $source, $alleleName, $freqsPtr, @freqs, $graph, $fileName) ;
276
277 # Get the input parameters and check a few things
278 defined($marker = $param{MARKER}) or
279 croak "ERROR [graphAlleleFreqs]: No Marker!" ;
280 $markerName = $marker->field("name") ;
281 defined($sourceListPtr = $param{FREQSOURCES}) or
282 croak "ERROR [graphAlleleFreqs]: No source(s) for allele frequencies!" ;
283 defined($alleleType = $param{ALLELETYPE}) or $alleleType = "Code" ;
284  
285 # Get the frequencies
286 @alleleNames = $self->getAllelesByType($marker, $alleleType) ;
287 push @data, [ @alleleNames ] ;
288 foreach $source (@$sourceListPtr) {
289 if ( ref($source) eq "Genetics::FrequencySource" ) {
290 $freqsPtr = $source->getAlleleFreqsByMarkerName($markerName, $alleleType) ;
291 } elsif ( ref($source) eq "Genetics::Cluster" ) {
292 $freqsPtr = $self->getAlleleFreqs($marker, $alleleType, $source) ;
293 } else {
294 carp "WARNING [graphAlleleFreqs]: $source is an invalid source for allele frequencies!" ;
295 next ;
296 }
297 @freqs = () ;
298 push @sourceNames, $source->field("name") ;
299 foreach $alleleName (@alleleNames) {
300 push @freqs, $$freqsPtr{$alleleName} ;
301 }
302 push @data, [ @freqs ] ;
303 }
304 defined($data[1]) or croak "ERROR [graphAlleleFreqs]: No valid allele frequency data!" ;
305  
306 # Create and display the graph
307 $graph = GD::Graph::bars->new() ;
308 $graph->set(
309 x_label => 'Allele',
310 y_label => 'Frequency',
311 title => "$markerName Allele Frequencies",
312 long_ticks => 1,
313 y_max_value => 1.0,
314 y_tick_number => 20,
315 y_label_skip => 2,
316 bar_spacing => 3,
317 # shadow_depth => 2,
318 # shadowclr => 'black',
319 transparent => 0,
320 ) or carp "WARNING [graphAlleleFreqs]: " . $graph->error ;
321 $graph->set_legend( @sourceNames );
322 $graph->plot( \@data ) or croak "ERROR [graphAlleleFreqs]: " . $graph->error ;
323 $fileName = "/tmp/$$.png" ;
324 &_saveGraphToFile($graph, $fileName) ;
325 system("xv $fileName &") == 0 or
326 croak "ERROR [graphAlleleFreqs]: system xv $fileName & failed: $?" ;
327  
328 return(1) ;
329 }
330  
331 =head2 calculateHet
332  
333 Function : Calculate the heterozygosity for a Marker or SNP.
334 Arguments : A Marker object, a string containing an allele type, and one of
335 the following defining the Subject group:
336 - a Subject Cluster object
337 - an array reference to a list of Subject objects
338 - a Kindred Cluster object
339 - an array reference to a list of Kindred objects
340 Returns : A scalar float
341 Scope : Public
342 Comments : Arguments are passed directly to API::DB::Query::getAlleleFreqs()
343  
344 =cut
345  
346 sub calculateHet {
347 my($self, $marker, $alleleType, $subjGroup) = @_ ;
348 my($freqsPtr, $allele, $sumFreqsSquared, $het) ;
349  
350 # Parameter checking, to the extent that it happens at all, is taken
351 # care of by API::DB::Query::getAlleleFreqs()
352 # Get the allele frequencies
353 $freqsPtr = $self->getAlleleFreqs($marker, $alleleType, $subjGroup) ;
354 # Calculate heterozygosity
355 foreach $allele (sort keys %$freqsPtr) {
356 next if ($alleleType eq "Nucleotide" and $allele eq "N") ;
357 $sumFreqsSquared += ($$freqsPtr{$allele})**2 ;
358 }
359 $het = 1 - $sumFreqsSquared ;
360  
361 return( _formatFloat($het) ) ;
362 }
363  
364 =head2 calculateSnpHW
365  
366 Function :
367 Arguments :
368 Returns :
369 Example : calculateHW()
370 Scope :
371 Comments :
372  
373 =cut
374  
375 sub calculateSnpHW {
376 my($self, $po, $sc) = @_ ;
377 my($gtCountsPtr, $alleleCountsPtr, @alleles, $i, @allelePairs,
378 $n11, $n12, $n22, $n, $obs, $exp, $chiSquare) ;
379  
380 if ( ref($po) !~ /^Genetics::(Marker|SNP)$/ ) {
381 croak "ERROR [calculateHW]: Invalid input Marker/SNP $po." ;
382 }
383 if ( ref($sc) ne "Genetics::Cluster" ) {
384 croak "ERROR [calculateHW]: Invalid input Cluster $sc." ;
385 if ( $sc->clusterType() ne "Subject" ) {
386 croak "ERROR [calculateHW]: Invalid input Cluster type." ;
387 }
388 }
389  
390 # Genotype counts
391 $gtCountsPtr = $self->getSNPGtCounts($po, $sc) ;
392 # Allele counts
393 $alleleCountsPtr = $self->getAlleleCounts($po, "Nucleotide", $sc) ;
394  
395 @alleles = $self->getAllelesByType($po, "Nucleotide") ;
396 for ($i=0 ; $i<=$#alleles ; $i++) {
397 splice(@alleles, $i, 1) if $alleles[$i] eq "N" ;
398 }
399 push @allelePairs, "$alleles[0]$alleles[0]" ;
400 push @allelePairs, "$alleles[0]$alleles[1]" ;
401 push @allelePairs, "$alleles[1]$alleles[1]" ;
402  
403 # observed genotype counts
404 $n11 = $$gtCountsPtr{$allelePairs[0]} ;
405 $n12 = $$gtCountsPtr{$allelePairs[1]} ;
406 $n22 = $$gtCountsPtr{$allelePairs[2]} ;
407 $n = $n11 + $n12 + $n22 ;
408 return("0.0000") if ( ($n11 == 0 or $n22 == 0) and ($n12 == 0) ) ;
409 $chiSquare = 0 ;
410 # allele pair 1
411 $obs = $n11 ;
412 $exp = ( (((2*$n11) + $n12)**2) / (4*$n) ) ;
413 #print "AllelePair: $allelePairs[0] obs: $obs, exp: $exp X2: $chiSquare\n" ;
414 $chiSquare = ((($obs - $exp)**2) / $exp) ;
415 # allele pair 2
416 $obs = $n12 ;
417 $exp = ( (((2*$n11) + $n12) * ((2*$n22) + $n12)) / (2*$n) ) ;
418 #print "AllelePair: $allelePairs[1] obs: $obs, exp: $exp X2: $chiSquare\n" ;
419 $chiSquare += ((($obs - $exp)**2) / $exp) ;
420 # allele pair 3
421 $obs = $n22 ;
422 $exp = ( (((2*$n22) + $n12)**2) / (4*$n) ) ;
423 #print "AllelePair: $allelePairs[2] obs: $obs, exp: $exp X2: $chiSquare\n" ;
424 $chiSquare += ((($obs - $exp)**2) / $exp) ;
425  
426 $chiSquare < 0.0001 ? return("0.0000")
427 : return( &_formatFloat($chiSquare) ) ;
428 }
429  
430  
431 sub _formatFloat {
432 my($f) = @_;
433 my($g) ;
434  
435 if ( $f =~ /(\d.\d{3})(\d)(\d)/ ) {
436 if ($3 >= 5) {
437 $g = "$1" . ($2 + 1) ;
438 } else {
439 $g = $1 . $2 ;
440 }
441 } else {
442 $g = $f ;
443 }
444  
445 return($g) ;
446 }
447  
448 sub _saveGraphToFile {
449 my $graph = shift or carp "ERROR [_saveGraphToFile]: Need a chart!" ;
450 my $fileName = shift or carp "ERROR [_saveGraphToFile]: Need a file name!" ;
451
452 local(*OUT) ;
453 my $extn = $graph->export_format() ;
454
455 open(OUT, "> $fileName") or
456 carp "ERROR [_saveGraphToFile]: Can't write file $fileName.$extn: $!" ;
457 binmode OUT ;
458 print OUT $graph->gd->$extn() ;
459 close OUT ;
460 print STDERR "MESSAGE [_saveGraphToFile]: Wrote file $fileName\n" ;
461 return(1) ;
462 }
463  
464  
465 1;