lib/Microarray/DataMatrix/SmallDataMatrix.pm untested

filter: Statementstmt 0.0% 0 / 280 Branchbran 0.0% 0 / 78 Conditioncond 0.0% 0 / 66 MC/DCmcdc 0.0% 0 / 43 Subroutinesub 0.0% 0 / 27 Podpod 0.0% 0 / 23 totaltotal 0.0% 0 / 517 CC 40 SCAR 27.7
CC
40
Cov
0%
__columnAverage
30.0
_filterRowsOnColumnPercentile
30.0
_scaleColumnData
30.0
CRAP 15.9
1 package Microarray::DataMatrix::SmallDataMatrix;
2  
3 # License information (the MIT license)
4  
5 # Copyright (c) 2003 Christian Rees, Janos Demeter, John Matese, Gavin
6 # Sherlock; Stanford University
7  
8 # Permission is hereby granted, free of charge, to any person
9 # obtaining a copy of this software and associated documentation files
10 # (the "Software"), to deal in the Software without restriction,
11 # including without limitation the rights to use, copy, modify, merge,
12 # publish, distribute, sublicense, and/or sell copies of the Software,
13 # and to permit persons to whom the Software is furnished to do so,
14 # subject to the following conditions:
15  
16 # The above copyright notice and this permission notice shall be
17 # included in all copies or substantial portions of the Software.
18  
19 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
20 # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
21 # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
22 # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
23 # BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
24 # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
25 # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
26 # SOFTWARE.
27  
28  
29 # Author : Gavin Sherlock
30 # Date : 10th June 2002
31  
32 # This package is intended to provide an abstraction layer to a
33 # dataMatrix whose size is such that all its contents, plus any
34 # additional data that will be generated during its processing, is
35 # small enough to fit into memory. It is intended that
36 # smallDataMatrix will be subclassed by an anySizeDataMatrix object,
37 # which is what clients of smallDataMatrix will actually see. It is
38 # up to the anySizeDataMatrix class itself to determine at runtime
39 # whether the matrix used for construction is small enough to be a
40 # smallDataMatrix. Thus anySizeDataMatrix should have the details
41 # about how much memory is available, and a means of determing the
42 # size of the matrix being used for construction. anySizeDataMatrix
43 # can then, at runtime, dynamically choose to inherit from
44 # smallDataMatrix, or the accompanying bigDataMatrix instead.
45  
46 use strict;
47 use Carp;
48 use vars qw ($AUTOLOAD @ISA);
49  
50 $| = 1; # set autoflush, so that reporting will flush immediately
51  
52 # inherit from a base class of dataMatrix
53  
54 use Microarray::DataMatrix;
55 @ISA = qw (Microarray::DataMatrix);
56  
57 ####################################################################
58 #
59 # CLASS GLOBALS
60 #
61 ####################################################################
62  
63 # The following globals are used so we only ever access hash entries
64 # (ie object attributes) using variables, to prevent typos, or
65 # accidental clobberring.
66  
67 # These values are assigned here and then are READ-ONLY.
68  
69 my $PACKAGE = 'Microarray::DataMatrix::SmallDataMatrix'; # will use to prefix all hash entries
70 # which will prevent collision with
71 # any attributes in super or sub
72 # classes.
73  
74 my $kMatrix = $PACKAGE.'::__matrix'; # a pointer the in memory matrix
75 my $kPercentiles = $PACKAGE.'::__percentiles'; # a hash of the percentiles for the data, if they were requested
76  
77  
78 #####################################################################
79 sub _init{
80 #####################################################################
81 # This protected method will read in all the data for the matrix, and
82 # store it in memory. It MUST be called during initialization of a
83 # subclass's object, before any other methods can be called.
84  
85 my ($self) = shift;
86  
87 $self->__readInAndStoreAllData;
88  
89 }
90  
91 #####################################################################
92 sub __readInAndStoreAllData{
93 #####################################################################
94 # This private method uses a concrete subclass's _dataLine method to
95 # request all data from the matrix, and read it into memory.
96 #
97 # Usage : $self->__readInAndStoreAllData;
98  
99 my $self = shift;
100
101 my (@matrix, %validRows, %validColumns);
102
103 my $rowNum = 0;
104
105 # first we'll get all the data
106
107 while (my $lineRef = $self->_dataLine($rowNum)){
108  
109 push (@matrix, $lineRef);
110  
111 $validRows{$rowNum} = undef; # record that this row is valid
112  
113 $rowNum++;
114  
115 }
116  
117 # now record the valid columns
118  
119 for (my $i = 0; $i < @{$matrix[0]}; $i++){
120  
121 $validColumns{$i} = undef; # record the valid columns
122  
123 }
124  
125 # now store the data in the object
126  
127 $self->_setValidColumns(\%validColumns);
128 $self->_setValidRows(\%validRows);
129  
130 $self->__setMatrix(\@matrix);
131  
132 }
133  
134 #####################################################################
135 #
136 # PRIVATE SETTER METHODS - should only be used by this class
137 #
138 #####################################################################
139  
140 #####################################################################
141 sub __setMatrix{
142 #####################################################################
143 # This private setter method receives a reference to an array of array
144 # references, (which contains the matrix itself), and stores it as a
145 # private attribute of the object.
146 #
147 # Usage: $self->__setMatrix(\@matrix);
148 #
149  
150 my ($self, $matrixArrayRef) = @_;
151
152 $self->{$kMatrix} = $matrixArrayRef;
153
154 }
155  
156 #####################################################################
157 sub __setPercentiles{
158 #####################################################################
159 # This private setter method receives a pointer to a hash of hashes
160 # that stores the percentiles of the data. The first key in the hash
161 # is the row from which an element of data came, and the second is the
162 # column. The value is the percentile for that piece of data in the
163 # column in which it is found.
164 #
165 # Usage : $self->__setPercentiles(\%percentiles);
166  
167 my ($self, $percentilesHashRef) = @_;
168
169 $self->{$kPercentiles} = $percentilesHashRef;
170  
171 }
172  
173 ######################################################################
174 sub __pareDownPercentiles{
175 ######################################################################
176 # This private method deletes entries in the percentiles hash that are
177 # not needed - it's really just to save memory....
178 #
179 # Usage : $self->__pareDownPercentiles;
180  
181 my ($self) = @_;
182  
183 my $percentilesRef = $self->{$kPercentiles};
184  
185 my @invalidRows;
186  
187 foreach my $row (keys %{$percentilesRef}){
188  
189 push (@invalidRows, $row) if !$self->_matrixRowIsValid($row);
190  
191 }
192  
193 foreach my $row (@invalidRows){
194  
195 delete $percentilesRef->{$row};
196  
197 }
198  
199 }
200  
201 ######################################################################
202 sub __invalidateMatrixRow{
203 ######################################################################
204 # This private mutator method makes a row invalid. We actually do the
205 # invalidation in the super class, but here, to save memory, we delete
206 # the data from the in memory matrix itself. This method is not
207 # undoable, because the invalidation also deletes the data for the
208 # row.
209 #
210 # Usage : $self->__invalidateMatrixRow($row);
211  
212 my ($self, $row) = @_;
213  
214 $self->SUPER::_invalidateMatrixRow($row);
215  
216 undef $self->{$kMatrix}->[$row] if defined ($self->{$kMatrix}->[$row]); # eliminate data
217  
218 }
219  
220 #####################################################################
221 #
222 # PRIVATE GETTER METHODS - should only be used by this class
223 #
224 #####################################################################
225  
226 ######################################################################
227 sub __matrixArrayRef{
228 ######################################################################
229 # This private method returns a reference to the 2-D array of data owned
230 # by the self object.
231 #
232 # usage : my $matrixArrayRef = $self->__matrixArrayRef;
233  
234 return $_[0]->{$kMatrix};
235  
236 }
237  
238 #
239 # ** DATA TRANSFORMATION METHODS
240 #
241  
242 ######################################################################
243 sub _centerColumns{
244 ######################################################################
245 # This protected method centers each column of data, and returns the
246 # largest absolute value that was used in the centering. The caller
247 # of the method must specify whether to center by means or medians.
248 #
249 # Usage :
250 #
251 # $self->_centerColumns($centerColumnsMethod, $lineEnding, $numColumnsToReport);
252  
253 my ($self, $method, $lineEnding, $numColumnsToReport) = @_;
254  
255 my $largestVal = 0;
256
257 defined $lineEnding && print ("Centering columns by $method", $lineEnding);
258
259 my $num = 0;
260
261 foreach my $column (@{$self->_validColumnsArrayRef}){
262
263 if (defined $lineEnding && !($num++%$numColumnsToReport)){
264  
265 print "Centering column $num", $lineEnding;
266
267 }
268
269 my $average = $self->__columnAverage($column, $method) || next;
270
271 $self->__centerColumn($column, $average);
272  
273 if (abs($average) > $largestVal){
274  
275 $largestVal = abs($average);
276  
277 }
278  
279 }
280  
281 return $largestVal;
282
283 }
284  
285 ######################################################################
286 sub __columnAverage{
287 ######################################################################
288 # This private method calculates and returns the average value for a
289 # column, depending on whether the mean or median was requested.
290 #
291 # Usage:
292 #
293 # my $average = $self->__columnAverage($column, $method)
294  
295 my ($self, $column, $method) = @_;
296
297 my $total = 0;
298 my @data;
299 my $numDatapoints = 0;
300 my $matrixArrayRef = $self->__matrixArrayRef;
301  
302 # simply examine the data for every row in the columm
303  
304 foreach my $row (@{$self->_validRowsArrayRef}){
305  
306 next if ($matrixArrayRef->[$row][$column] eq "");
307
308 $total += $matrixArrayRef->[$row][$column] if ($method eq "mean");
309 push (@data, $matrixArrayRef->[$row][$column]) if ($method eq "median");
310 $numDatapoints++;
311
312 }
313
314 return 0 if ($numDatapoints == 0); # may simply be a blank 'filler' column
315
316 my $average = $self->_average($method, \@data, $total, $numDatapoints);
317
318 return $average;
319  
320 }
321  
322 ######################################################################
323 sub __centerColumn{
324 ######################################################################
325 # This private method centers the data for a single column, by
326 # subtracting the average from every value.
327 #
328 # Usage :
329 #
330 # $self->__centerColumn($column, $average);
331 #
332  
333 my ($self, $column, $average) = @_;
334
335 my $matrixArrayRef = $self->__matrixArrayRef;
336
337 foreach my $row (@{$self->_validRowsArrayRef}){
338
339 next if ($matrixArrayRef->[$row][$column] eq "");
340
341 $matrixArrayRef->[$row][$column] -= $average;
342
343 }
344
345 }
346  
347 ######################################################################
348 sub _centerRows{
349 ######################################################################
350 # This protected method actually centers the row data, by calculating
351 # the average (mean or median, depending on what was requested) for
352 # each row, and then subtracting that value from each datapoint in the row.
353 #
354 # Usage :
355 #
356 # $self->_centerRows($centerRowsMethod, $lineEnding, $numRowsToReport);
357 #
358  
359 my ($self, $method, $lineEnding, $numRowsToReport) = @_;
360
361 my $matrixArrayRef = $self->__matrixArrayRef;
362
363 defined $lineEnding && print ("Centering rows by $method", $lineEnding);
364
365 my $num = 0;
366
367 foreach my $row (@{$self->_validRowsArrayRef}){
368
369 if (defined $lineEnding && !($num++%$numRowsToReport)){
370
371 print "Centering row $num", $lineEnding;
372
373 }
374  
375 # next two methods are from superclass
376
377 my $average = $self->_rowAverage($matrixArrayRef->[$row], $method) || next;
378  
379 $self->_centerRow($matrixArrayRef->[$row], $average);
380  
381 }
382  
383 }
384  
385 ######################################################################
386 sub _filterRowsByPercentPresentData{
387 ######################################################################
388 # This protected method invalidates rows that do not have greater than
389 # the requested percentage of present data
390 #
391 # Usage :
392 #
393 # $self->_filterRowsByPercentPresentData($percent, $lineEnding, $numRowsToReport);
394 #
395  
396 my ($self, $percent, $lineEnding, $numRowsToReport) = @_;
397  
398 my $requiredNumDatapoints = $self->numColumns * ($percent / 100);
399
400 my $matrixArrayRef = $self->__matrixArrayRef;
401
402 my $num = 0;
403
404 foreach my $row (@{$self->_validRowsArrayRef}){
405
406 if (defined $lineEnding && !($num++%$numRowsToReport)){
407
408 print "Filtering row $num", $lineEnding;
409
410 }
411
412 my $numDatapoints = 0;
413
414 foreach my $column (@{$self->_validColumnsArrayRef}){
415
416 next if ($matrixArrayRef->[$row][$column] eq "");
417
418 $numDatapoints++;
419
420 }
421
422 $self->__invalidateMatrixRow($row) unless ($numDatapoints > $requiredNumDatapoints);
423
424 }
425
426 }
427  
428  
429 ######################################################################
430 sub _filterColumnsByPercentPresentData{
431 ######################################################################
432 # This protected method invalidates columns that do not have greater
433 # than the requested percentage of present data
434 #
435 # Usage : $self->_filterColumnsByPercentPresentData($percent, $lineEnding, $numColumnsToReport);
436
437 my ($self, $percent, $lineEnding, $numColumnsToReport) = @_;
438
439 my $requiredNumDatapoints = $self->numRows * ($percent / 100);
440
441 my $matrixArrayRef = $self->__matrixArrayRef;
442
443 my $num = 0;
444
445 foreach my $column (@{$self->_validColumnsArrayRef}){
446
447 if (defined $lineEnding && !($num++%$numColumnsToReport)){
448
449 print "Filtering column $num", $lineEnding;
450
451 }
452
453 my $numDatapoints = 0;
454
455 foreach my $row (@{$self->_validRowsArrayRef}){
456  
457 next if ($matrixArrayRef->[$row][$column] eq "");
458  
459 $numDatapoints++;
460  
461 }
462  
463 $self->_invalidateMatrixColumn($column) unless ($numDatapoints > $requiredNumDatapoints);
464  
465 }
466  
467 }
468  
469 #####################################################################
470 sub _filterRowsOnColumnPercentile{
471 #####################################################################
472 # This protected method filters out rows based on their column
473 # percentile, when all data are known to be in memory, and optionally
474 # allows for the percentiles of each datapoint to be displayed in the
475 # output file.
476 #
477 # Usage:
478 #
479 # $self->_filterRowsOnColumnPercentile($lineEnding, $numColumnsToReport, $percentile, $numColumns, $showPercentile);
480 #
481  
482 my ($self, $lineEnding, $numColumnsToReport, $percentile, $numColumns, $showPercentile) = @_;
483  
484 my $matrixArrayRef = $self->__matrixArrayRef;
485  
486 my (%count, %percentiles, %rowToValue);
487  
488 my $num = 0;
489  
490 # go through every column
491  
492 foreach my $column (@{$self->_validColumnsArrayRef}){
493  
494 if (defined $lineEnding && !($num++%$numColumnsToReport)){
495  
496 print "Examining percentiles of column $num", $lineEnding;
497  
498 }
499  
500 %rowToValue = ();
501  
502 foreach my $row (@{$self->_validRowsArrayRef}){
503  
504 next if ($matrixArrayRef->[$row][$column] eq "");
505  
506 $rowToValue{$row} = $matrixArrayRef->[$row][$column]; # build hash
507  
508 }
509  
510 # sort the row_no's in order of values
511  
512 my @rowsInValueOrder = sort {$rowToValue{$a} <=> $rowToValue{$b}} keys %rowToValue;
513  
514 my $minIndex = int(@rowsInValueOrder * ($percentile/100));
515
516 for (my $index = $minIndex; $index < @rowsInValueOrder; $index++){
517  
518 $count{$rowsInValueOrder[$index]}++; # count only those in the correct percentile
519  
520 }
521  
522 if ($showPercentile){ # they want the percentile in the output
523  
524 # we need to store the percentiles of every row for every column
525  
526 foreach (my $index = 0; $index < @rowsInValueOrder; $index++){
527  
528 $percentiles{$rowsInValueOrder[$index]}{$column} = sprintf "%.4f", $index/@rowsInValueOrder;
529  
530 }
531  
532 }
533  
534 }
535  
536 # now invalidate all rows, which don't have a high enough count
537 # across columns
538  
539 $self->__filterRowsByCount(\%count, $numColumns);
540
541 # now weed out the percentiles hash to only store those we need
542  
543 if ($showPercentile) { # now store the requested percentiles
544  
545 $self->__setPercentiles(\%percentiles);
546 $self->__pareDownPercentiles;
547  
548 }
549  
550 }
551  
552 ######################################################################
553 sub __filterRowsByCount{
554 ######################################################################
555 # This private method filters out rows that don't have a count for
556 # some particular property above or equal to a threshold. It accepts
557 # a hash reference, that hashes the row number to a count, and a
558 # threshold value. Note that not all rows are necessarily entered
559 # into the hash, so this method iterates over all rows, and checks
560 # each valid one for its count in the hash, then invalidates those
561 # with too low a count.
562 #
563 # Usage:
564 #
565 # $self->__filterRowsByCount(\%count, $numColumns);
566  
567 my ($self, $rowToCountHashRef, $threshold) = @_;
568  
569 foreach my $row (@{$self->_validRowsArrayRef}){
570  
571 if (!exists($rowToCountHashRef->{$row}) || $rowToCountHashRef->{$row} < $threshold){
572  
573 $self->__invalidateMatrixRow($row);
574  
575 }
576  
577 }
578  
579 }
580  
581 ########################################################################
582 sub _filterRowsOnColumnDeviation{
583 ########################################################################
584 # This protected method will filter out rows whose values do not
585 # deviate from the column mean by a specified number of standard
586 # deviations, in at least numColumns columns.
587 #
588 # Usage:
589 #
590 # $self->_filterRowsOnColumnDeviation($lineEnding, $numRowsToReport, $deviations, $numColumns);
591  
592 my ($self, $lineEnding, $numRowsToReport, $deviations, $numColumns) = @_;
593
594 # first need to get the standard deviations of all valid columns
595
596 my ($stddevHashRef, $meansHashRef) = $self->__validColumnsStdDevAndMeanHashRefs($lineEnding);
597
598 # now calculate the upper and lower bounds for each column
599  
600 my ($upperHashRef, $lowerHashRef) = $self->_calculateBounds($stddevHashRef, $meansHashRef, $deviations, $lineEnding);
601  
602 # now count up how many values in each row lie outside of the
603 # specified number of deviations from the mean, for each row
604  
605 defined $lineEnding && print("Running filters over each row", $lineEnding);
606
607 my $num = 0;
608  
609 my (%count, $val);
610  
611 my $matrixArrayRef = $self->__matrixArrayRef;
612
613 # go through every row
614
615 foreach my $row (@{$self->_validRowsArrayRef}){
616
617 if (defined $lineEnding && !($num++%$numRowsToReport)){
618
619 print "Filtering row $num", $lineEnding;
620
621 }
622
623 foreach my $column (@{$self->_validColumnsArrayRef}){
624  
625 $val = $matrixArrayRef->[$row][$column];
626
627 next if ($val eq "");
628
629 next unless ($val > $upperHashRef->{$column} || $val < $lowerHashRef->{$column});
630  
631 $count{$row}++; # this value passes the criteria
632  
633 }
634  
635 }
636  
637 $self->__filterRowsByCount(\%count, $numColumns);
638  
639 }
640  
641 ######################################################################
642 sub __validColumnsStdDevAndMeanHashRefs{
643 ######################################################################
644 # This private method calculates the standard deviations for each
645 # valid column, and returns references to two hashes. Both have the
646 # column index as the key, and one has the standard deviation as the
647 # values, the other has the column means as the values.
648 #
649 # mean = Sum of values/n
650 # std dev = square root (((n * sum of (x^2)) - (sum of x)^2)/n(n-1))
651  
652 my ($self, $lineEnding) = @_;
653  
654 my $matrixArrayRef = $self->__matrixArrayRef;
655  
656 my (%sumOfX, %sumX2, %numDataPoints, $val);
657  
658 defined $lineEnding && print ("Calculating mean and standard deviations for each column", $lineEnding);
659  
660 foreach my $row (@{$self->_validRowsArrayRef}){
661  
662 foreach my $column (@{$self->_validColumnsArrayRef}){
663  
664 $val = $matrixArrayRef->[$row][$column];
665  
666 next if ($val eq "");
667  
668 $sumOfX{$column} += $val;
669 $sumX2{$column} += $val*$val;
670 $numDataPoints{$column}++;
671  
672 }
673  
674 }
675  
676 my ($stddevHashRef, $meansHashRef) = $self->_calculateMeansAndStdDeviations(\%sumOfX, \%sumX2, \%numDataPoints);
677  
678 return ($stddevHashRef, $meansHashRef);
679  
680 }
681  
682 ######################################################################
683 sub _filterRowsOnValues{
684 ######################################################################
685 # This protected method filters out rows whose values do not pass a
686 # specified criterion, in at least numColumns columns.
687 #
688 # Usage : $self->_filterRowsOnValues($value, $method, $lineEnding, $numRowsToReport, $numColumns);
689 #
690  
691 my ($self, $value, $method, $lineEnding, $numRowsToReport, $numColumns) = @_;
692
693 my $matrixArrayRef = $self->__matrixArrayRef;
694
695 my (%count, $datum);
696
697 my $num = 0;
698
699 foreach my $row (@{$self->_validRowsArrayRef}){
700
701 if (defined $lineEnding && !($num++%$numRowsToReport)){
702
703 print "Filtering row $num", $lineEnding;
704
705 }
706
707 foreach my $column (@{$self->_validColumnsArrayRef}){
708
709 $datum = $matrixArrayRef->[$row][$column];
710  
711 next if $datum eq "";
712  
713 # following method call returns true if value passes criteria
714  
715 $count{$row}++ if ($self->$method($datum, $value));
716  
717 }
718
719 }
720  
721 $self->__filterRowsByCount(\%count, $numColumns);
722  
723 }
724  
725 ######################################################################
726 sub _filterRowsOnVectorLength{
727 ######################################################################
728 # This protected method filters out rows based on whether the vector
729 # that their values define has a length of greater than the specified
730 # length.
731 #
732 # Usage :
733 #
734 # $self->_filterRowsOnVectorLength($requiredLength, $lineEnding, $numRowsToReport);
735  
736 my ($self, $requiredLength, $lineEnding, $numRowsToReport) = @_;
737  
738 my $matrixArrayRef = $self->__matrixArrayRef;
739  
740 my $val;
741  
742 my $num = 0;
743  
744 foreach my $row (@{$self->_validRowsArrayRef}){
745  
746 if (defined $lineEnding && !($num++%$numRowsToReport)){
747  
748 print "Filtering row $num", $lineEnding;
749  
750 }
751  
752 my $sumSquares;
753  
754 foreach my $column (@{$self->_validColumnsArrayRef}){
755
756 $val = $matrixArrayRef->[$row][$column];
757  
758 next if $val eq "";
759  
760 $sumSquares += $val**2;
761  
762 }
763  
764 # invalidate those who don't pass the length requirement
765  
766 $self->__invalidateMatrixRow($row) unless sqrt($sumSquares) > $requiredLength;
767
768 }
769
770 }
771  
772 ######################################################################
773 sub _logTransformData{
774 ######################################################################
775 # This method log transforms the contents of the data matrix, using
776 # the specified base for the log transformation.
777 #
778 # Usage:
779 #
780 # $self->_logTransformData($logBase, $lineEnding, $numRowsToReport);
781  
782 my ($self, $logBase, $lineEnding, $numRowsToReport) = @_;
783  
784 $self->__dieIfNegativeDataExistInMatrix;
785  
786 my ($val, $column, $row);
787  
788 my $matrixArrayRef = $self->__matrixArrayRef;
789  
790 my $num = 0;
791  
792 foreach $row (@{$self->_validRowsArrayRef}){
793  
794 if (defined $lineEnding && !($num++%$numRowsToReport)){
795  
796 print "Log transforming row $num", $lineEnding;
797  
798 }
799  
800 foreach $column (@{$self->_validColumnsArrayRef}){
801  
802 $val = $matrixArrayRef->[$row][$column];
803  
804 next if (!defined $val || $val eq ""); # skip blanks
805  
806 $matrixArrayRef->[$row][$column] = sprintf "%.4f", log($val)/$logBase;
807  
808 }
809  
810 }
811  
812 }
813  
814 ######################################################################
815 sub __dieIfNegativeDataExistInMatrix{
816 ######################################################################
817 # This private function dies, with an appropriate error message, if any
818 # negative data value is found within the matrix.
819 #
820 # Usage : $self->__dieIfNegativeDataExistInMatrix;
821  
822 my ($self) = @_;
823  
824 my $matrixArrayRef = $self->__matrixArrayRef;
825  
826 my ($val, $row, $column);
827  
828 foreach $column (@{$self->_validColumnsArrayRef}){
829  
830 foreach $row (@{$self->_validRowsArrayRef}){
831  
832 $val = $matrixArrayRef->[$row][$column];
833
834 next if (!defined $val || $val eq ""); # skip blanks
835
836 if ($val <= 0){
837
838 die "The data could not be transformed : the negative value $val exists in row $row, column $column";
839
840 }
841
842 }
843
844 }
845
846 }
847  
848 ######################################################################
849 sub _scaleColumnData{
850 ######################################################################
851 # This protected method scales the data for particular columns as
852 # specified by the client, when all data are in memory.
853 #
854 # Usage :
855 #
856 # $self->_scaleColumnData($columnsToFactorsHashRef, $lineEnding, $numColumnsToReport);
857 #
858 my ($self, $columnsToFactorsHashRef, $lineEnding, $numColumnsToReport) = @_;
859  
860 my $matrixArrayRef = $self->__matrixArrayRef;
861  
862 my $num = 0;
863  
864 my ($val, $scalingFactor);
865  
866 foreach my $column (keys %{$columnsToFactorsHashRef}){
867  
868 if (!$self->_matrixColumnIsValid($column)){
869  
870 print STDERR "The column index, $column, is not valid for this dataMatrix.\n";
871 next;
872  
873 }
874  
875 $scalingFactor = $columnsToFactorsHashRef->{$column};
876  
877 if (!defined $scalingFactor || $scalingFactor == 0){
878  
879 print STDERR "The scaling factor supplied for $column was \"$scalingFactor\".\n";
880 print STDERR "It will not be used.\n";
881  
882 next;
883  
884 }
885  
886 if (defined $lineEnding && !($num++%$numColumnsToReport)){
887  
888 print "Scaling data for column $num with scaling factor $scalingFactor", $lineEnding;
889  
890 }
891
892 foreach my $row (@{$self->_validRowsArrayRef}){
893
894 $val = $matrixArrayRef->[$row][$column];
895  
896 next if $val eq ""; # skip blanks
897  
898 $matrixArrayRef->[$row][$column] = sprintf "%.4f", $val/$scalingFactor;
899  
900 }
901  
902 }
903  
904 }
905  
906 ###################################################################################
907 sub dumpData{
908 ###################################################################################
909 # This method dumps the current contents of the dataMatrix object to a
910 # file, either whose name was provided as a single argument, or to a
911 # file whose name was used to construct the object.
912 #
913 # To do this, it delegates printing to a subclass.
914 # Subclasses have to implement the following methods:
915 #
916 # _printLeadingMeta
917 # _printRow
918 # _printTrailingMeta
919 #
920 # printLeadingMeta is given a reference to an array of the valid columns
921 # printRow is given a row number, and the VALID data for that row
922 # printTrailingMeta is given a reference to an array of the valid columns array of the valid columns
923 #
924 # is there is no leading or trailing meta information to print,
925 # the subclass can leave the subroutines empty.......
926  
927 my ($self, $file) = @_;
928  
929 $file ||= $self->file;
930
931 # have to think about this bit....
932  
933 my $hasPercentiles = exists $self->{$kPercentiles};
934  
935 my $percentilesRef = $self->{$kPercentiles};
936
937 open (DATAOUT, ">$file") || die "Cannot open $file for writing : $!.\n";
938  
939 # print first line
940  
941 $self->_printLeadingMeta(\*DATAOUT, $self->_validColumnsArrayRef, $hasPercentiles, "percentile");
942  
943 my $matrixArrayRef = $self->__matrixArrayRef;
944
945 # now go through each valid row
946
947 foreach my $row (sort {$a <=> $b } @{$self->_validRowsArrayRef}){
948
949 $self->_printRow(\*DATAOUT, $row, $matrixArrayRef->[$row], $self->_validColumnsArrayRef, $hasPercentiles, $percentilesRef);
950
951 }
952
953 $self->_printTrailingMeta(\*DATAOUT, $self->_validColumnsArrayRef, $hasPercentiles);
954
955 close DATAOUT;
956  
957  
958 }
959  
960 1; # to keep Perl happy
961  
962 =pod
963  
964 =head1 NAME
965  
966 Microarray::DataMatrix::SmallDataMatrix - abstraction to matrices that fit in memory
967  
968 =head1 Abstract
969  
970 smallDataMatrix is an abstract class, which provides as abstraction to
971 an in memory matrix of data. It should not be subclassed by concrete
972 subclasses. Instead, the subclass anySizeDataMatrix, can be
973 subclassed with concrete subclasses, which will provide abstractions
974 to dataMatrices stored in particular file formats, such as pcl files.
975  
976 =head1 Overall Logic
977  
978 Internally, all data are read into memory, and the actual data matrix
979 is stored as a 2 dimensional array. The indexes of the array which
980 are still valid are stored in internal hashes, such that subsequent
981 manipulations of the data only consider the data that have not been
982 filtered out. As rows or columns are filtered out by some of the
983 methods, the entries for these rows or columns are deleted from the
984 hashes that track valid data. Thus when data are redumped to a file,
985 only those data that have not been filtered are printed out.
986  
987 =head1 Construction
988  
989 As smallDataMatrix is an abstract class, it has no constructor.
990 However, the subclass, anySizeDataMatrix, once it has determined that
991 a matrix will indeed fit into memory, MUST call the _init method,
992 which will result in all data being read into memory.
993  
994 =head2 _init
995  
996 This protected method will read in all the data for the matrix, and
997 store it in memory. It MUST be called during initialization of a
998 subclass object, before any other methods can be called by the client.
999  
1000 Usage:
1001  
1002 $self->_init;
1003  
1004 or:
1005  
1006 $self->SUPER::_init;
1007  
1008 =head1 private utility methods
1009  
1010 =head2 __readInAndStoreAllData
1011  
1012 This private method uses the _dataLine method from a concrete subclass
1013 to request all data from the matrix, and read it into memory, then
1014 store it internally.
1015  
1016 Usage :
1017  
1018 $self->__readInAndStoreAllData;
1019  
1020 =head2 __columnAverage
1021  
1022 This private method calculates and returns the average value for a
1023 column, depending on whether the mean or median was requested.
1024  
1025 Usage:
1026  
1027 my $average = $self->__columnAverage($column, 'mean');
1028  
1029 =head2 __centerColumn
1030  
1031 This private method centers the data for a single column, by
1032 subtracting the average from every valid value.
1033  
1034 Usage :
1035  
1036 $self->__centerColumn($column, $average);
1037  
1038 =head2 __filterRowsByCount
1039  
1040 This private method filters out rows that do not have a count for some
1041 particular property above or equal to a threshold. It accepts a hash
1042 reference, that hashes the row number to a count, and a threshold
1043 value. Note that not all rows are necessarily entered into the hash,
1044 so this method iterates over all rows, and checks each valid one for
1045 its count in the hash, then invalidates those with too low a count.
1046  
1047 Usage:
1048  
1049 $self->__filterRowsByCount(\%count, $numColumns);
1050  
1051 =head2 __validColumnsStdDevAndMeanHashRefs
1052  
1053 This private method calculates the standard deviations for each valid
1054 column, and returns references to two hashes. Both have the column
1055 index as the key, and one has the standard deviation as the values,
1056 the other has the column means as the values.
1057  
1058 mean = Sum of values/n
1059 std dev = square root (((n * sum of (x^2)) - (sum of x)^2)/n(n-1))
1060  
1061 Usage:
1062  
1063 my ($stddevHashRef, $meansHashRef) = $self->__validColumnsStdDevAndMeanHashRefs($lineEnding);
1064  
1065 =head2 __dieIfNegativeDataExistInMatrix
1066  
1067 This private function dies, with an appropriate error message, if any
1068 negative data value is found within the matrix.
1069  
1070 Usage:
1071  
1072 $self->__dieIfNegativeDataExistInMatrix;
1073  
1074 =head1 private setter methods
1075  
1076 =head2 __setMatrix
1077  
1078 This private setter method receives a reference to an array of array
1079 references (which contains the matrix itself), and stores it as a
1080 private attribute of the object.
1081  
1082 Usage :
1083  
1084 $self->__setMatrix(\@matrix);
1085  
1086 =head2 __setPercentiles
1087  
1088 This private setter method receives a pointer to a hash of hashes that
1089 stores the percentiles of the data. The first key in the hash is the
1090 row from which an element of data came, and the second is the column.
1091 The value is the percentile for that piece of data in the column in
1092 which it is found.
1093  
1094 Usage :
1095  
1096 $self->__setPercentiles(\%percentiles);
1097  
1098 =head2 __pareDownPercentiles
1099  
1100 This private method deletes entries in the percentiles hash that are
1101 not needed - it is really just to save memory....
1102  
1103 Usage :
1104  
1105 $self->__pareDownPercentiles;
1106  
1107 =head2 __invalidateMatrixRow
1108  
1109 This private mutator method makes a row invalid. The invalidation is
1110 actually done by the the super class, but here, to save memory, we
1111 delete the data from the in memory matrix itself. This method is not
1112 undoable, because the invalidation also deletes the data for the row.
1113  
1114 Usage :
1115  
1116 $self->__invalidateMatrixRow($row);
1117  
1118 =head1 private getter methods
1119  
1120 =head2 __matrixArrayRef
1121  
1122 This private method returns a reference to the 2-D array of data owned
1123 by the self object.
1124  
1125 Usage :
1126  
1127 my $matrixArrayRef = $self->__matrixArrayRef;
1128  
1129 =head1 Protected data transformation/filtering methods
1130  
1131 Note: These methods provide the backend nuts and bolts for a
1132 transformation or filtering. They should only be called by the
1133 immediate subclass, anySizeDataMatrix, and not directly by the
1134 concrete subclasses of anySizeDataMatrix. In addition, note that the
1135 companion bigDataMatrix must (and does) provide identical interfaces
1136 to these methods (obviously with different underlying
1137 implementations), such that anySizeDataMatrix can call the methods
1138 without regard to the size of the underlying matrix.
1139  
1140 =head2 _centerColumns
1141  
1142 This protected method centers each column of data, and returns the
1143 largest absolute value that was used in the centering. The caller of
1144 the method must specify whether to center by means or medians.
1145  
1146 Usage :
1147  
1148 $self->_centerColumns('mean', $lineEnding, $numColumnsToReport);
1149  
1150 =head2 _centerRows
1151  
1152 This protected method actually centers the row data, by calculating
1153 the average (mean or median, depending on what was requested) for each
1154 row, and then subtracting that value from each valid datapoint in the
1155 row.
1156  
1157 Usage :
1158  
1159 $self->_centerRows('median', $lineEnding, $numRowsToReport);
1160  
1161 =head2 _filterRowsByPercentPresentData
1162  
1163 This protected method invalidates rows that do not have greater than
1164 the requested percentage of present data.
1165  
1166 Usage :
1167  
1168 $self->_filterRowsByPercentPresentData($percent, $lineEnding, $numRowsToReport);
1169  
1170 =head2 _filterColumnsByPercentPresentData
1171  
1172 This protected method invalidates columns that do not have greater
1173 than the requested percentage of present data.
1174  
1175 Usage :
1176  
1177 $self->_filterColumnsByPercentPresentData($percent, $lineEnding, $numColumnsToReport);
1178  
1179 =head2 _filterRowsOnColumnPercentile
1180  
1181 This protected method filters out rows based on their column
1182 percentile, when all data are known to be in memory, and optionally
1183 allows for the percentiles of each datapoint to be displayed in the
1184 output file.
1185  
1186 Usage:
1187  
1188 $self->_filterRowsOnColumnPercentile($lineEnding, $numColumnsToReport, $percentile, $numColumns, $showPercentile);
1189  
1190 =head2 _filterRowsOnColumnDeviation
1191  
1192 This protected method will filter out rows whose values do not deviate
1193 from the column mean by a specified number of standard deviations, in
1194 at least numColumns columns.
1195  
1196 Usage:
1197  
1198 $self->_filterRowsOnColumnDeviation($lineEnding, $numRowsToReport, $deviations, $numColumns);
1199  
1200 =head2 _filterRowsOnValues
1201  
1202 This protected method filters out rows whose values do not pass a
1203 specified criterion, in at least numColumns columns.
1204  
1205 Usage :
1206  
1207 $self->_filterRowsOnValues($value, $method, $lineEnding, $numRowsToReport, $numColumns);
1208  
1209 =head2 _filterRowsOnVectorLength
1210  
1211 This protected method filters out rows based on whether the vector
1212 that their values define has a length of greater than the specified
1213 length.
1214  
1215 Usage :
1216  
1217 $self->_filterRowsOnVectorLength($requiredLength, $lineEnding, $numRowsToReport);
1218  
1219 =head2 _logTransformData
1220  
1221 This method log transforms the contents of the data matrix, using the
1222 specified base for the log transformation.
1223  
1224 Usage:
1225  
1226 $self->_logTransformData($logBase, $lineEnding, $numRowsToReport);
1227  
1228 =head2 _scaleColumnData
1229  
1230 This protected method scales the data for particular columns as
1231 specified by the client, when all data are in memory.
1232  
1233 Usage :
1234  
1235 $self->_scaleColumnData($columnsToFactorsHashRef, $lineEnding, $numColumnsToReport);
1236  
1237 =head1 public methods
1238  
1239 =head2 dumpData
1240  
1241 This method dumps the current contents of the dataMatrix object to a
1242 file, either whose name was provided as a single argument, or to a
1243 file whose name was used to construct the object.
1244  
1245 Usage:
1246  
1247 $self->dumpData($file);
1248  
1249 =head1 AUTHOR
1250  
1251 Gavin Sherlock
1252  
1253 sherlock@genome.stanford.edu
1254  
1255 =cut