lib/Microarray/DataMatrix/BigDataMatrix.pm untested

filter: Statementstmt 0.0% 0 / 474 Branchbran 0.0% 0 / 138 Conditioncond 0.0% 0 / 97 MC/DCmcdc 0.0% 0 / 64 Subroutinesub 0.0% 0 / 41 Podpod 0.0% 0 / 37 totaltotal 0.0% 0 / 851 CC 70 SCAR 34.9
CC
70
Cov
0%
__centerColumns_median
90.0
_scaleColumnData
72.0
__centerColumns_mean
42.0
CRAP 32.8
1 package Microarray::DataMatrix::BigDataMatrix;
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 July 2002
31  
32 # This package is intended to provide an abstraction layer to a
33 # dataMatrix whose size is such that all its contents cannot fit
34 # simultaneously in memory. It is intended that bigDataMatrix will be
35 # subclassed by an anySizeDataMatrix object, which is what clients of
36 # bigDataMatrix will actually see. It is up to the anySizeDataMatrix
37 # class itself to determine at runtime whether the matrix used for
38 # construction is too large to fit in memory. Thus anySizeDataMatrix
39 # should have the details about how much memory is available, and a
40 # means of determing the size of the matrix being used for
41 # construction. anySizeDataMatrix can then, at runtime, dynamically
42 # choose to inherit from bigDataMatrix, or the accompanying
43 # smallDataMatrix instead. bigDataMatrix uses temp files to carry out
44 # tranformations and filterings on a matrix, rather than doing things
45 # in memory.
46  
47 use strict;
48 use Carp;
49 use vars qw ($AUTOLOAD @ISA);
50  
51 $| = 1; # set autoflush, so that reporting will flush immediately
52  
53 # inherit from a base class of dataMatrix
54  
55 use Microarray::DataMatrix;
56 @ISA = qw (Microarray::DataMatrix);
57  
58  
59 ####################################################################
60 #
61 # CLASS GLOBALS
62 #
63 ####################################################################
64  
65 # The following globals are used so we only ever access hash entries
66 # (ie object attributes) using variables, to prevent typos, or
67 # accidental clobberring.
68  
69 # These values are assigned here and then are READ-ONLY.
70  
71 my $PACKAGE = 'bigDataMatrix'; # will use to prefix all hash entries
72 # which will prevent collision with any
73 # attributes in super or sub classes.
74  
75 # The following attributes are used to store hashes that track the
76 # positions of columns and rows in the original file, compared to
77 # where they may be in a current temporary file.
78  
79 my $kColumnCurrentToOrig = $PACKAGE.'::__columnCurrentToOrig';
80 my $kColumnOrigToCurrent = $PACKAGE.'::__columnOrigToCurrent';
81 my $kRowCurrentToOrig = $PACKAGE.'::__rowCurrentToOrig';
82  
83 # other attributes
84  
85 my $kMaxRowNumber = $PACKAGE.'::__maxRowNumber';# the max row number in the current file
86 my $kTmpNum = $PACKAGE.'::__tmpNum'; # to keep track of the number of tmp files created
87 my $kPercentiles = $PACKAGE.'::__percentiles'; # a hash of the percentiles for the data, if they were requested
88  
89 # Methods used during initialization
90  
91 #####################################################################
92 sub _init{
93 #####################################################################
94 # This method will determine the number of rows and columns in the
95 # matrix, and records their indices as valid. It MUST be called
96 # during initialization of a subclass's object, before any other
97 # methods can be called.
98  
99 my ($self) = @_;
100  
101 my $numColumns = $self->_numDataColumns;
102 my $numRows = $self->_numDataRows;
103  
104 $self->__validateRows($numRows);
105 $self->__validateColumns($numColumns);
106  
107 $self->__setTmpNum(0); # initialize our series of temp numbers.
108 $self->__setMaxRowNumber($numRows);
109  
110 }
111  
112 ######################################################################
113 sub __validateRows{
114 ######################################################################
115 # This method receives the number of rows that the matrix has, and simply
116 # records each one of them as valid. In addition it sets up a map of
117 # the row's current position in a temp file, to it's original position
118 # in a file.
119 #
120 # Usage : $self->__validateRows($numRows);
121  
122 my ($self, $numRows) = @_;
123  
124 my %validRows;
125
126 for (my $i = 0; $i < $numRows; $i++){
127
128 $validRows{$i} = undef;
129 $self->{$kRowCurrentToOrig}->{$i} = $i;
130  
131 }
132
133 $self->_setValidRows(\%validRows);
134  
135 }
136  
137 ######################################################################
138 sub __validateColumns{
139 ######################################################################
140 # This method receives the number of columns that the matrix has, and
141 # simply records each one of them as valid. In addition it sets up a
142 # map of the column's position in the original file to its current
143 # position, and a reverse map of the column's current position, to its
144 # position in the original file.
145 #
146 # Usage : $self->__validateColumns($numColumns);
147  
148 my ($self, $numColumns) = @_;
149  
150 my %validColumns;
151
152 for (my $i = 0; $i < $numColumns; $i++){
153
154 $validColumns{$i} = undef;
155 $self->{$kColumnCurrentToOrig}->{$i} = $i;
156 $self->{$kColumnOrigToCurrent}->{$i} = $i;
157
158 }
159
160 $self->_setValidColumns(\%validColumns);
161  
162 }
163  
164 ######################################################################
165 sub __invalidateMatrixRow{
166 ######################################################################
167 # This private mutator method makes a row invalid. We actually do
168 # the invalidation in the super class, but have to override it here,
169 # so that we mark the row index from the original file as invalid,
170 # rather than marking as invalid the row index based on the row's
171 # current index. We do this by translating the current row number to
172 # its original row index.
173 #
174 # Usage : $self->__invalidateMatrixRow($num)
175  
176 my ($self, $row) = @_;
177  
178 $self->SUPER::_invalidateMatrixRow($self->__origRow($row));
179  
180 }
181  
182 ######################################################################
183 sub __origRow{
184 ######################################################################
185 # This private method returns the original row number to which a row in the
186 # current file now corresponds.
187 #
188 # Usage : $self->__origRow($row);
189  
190 return $_[0]->{$kRowCurrentToOrig}->{$_[1]};
191  
192 }
193  
194 ######################################################################
195 sub __invalidateMatrixColumn{
196 ######################################################################
197 # This private mutator method makes a column invalid. We actually do
198 # the invalidation in the super class, but have to override it here,
199 # so that we mark the columns index from the original file as invalid,
200 # rather than marking as invalid the column index based on the column's
201 # current index. We do this by translating the current column number
202 # to its original.
203 #
204 # Usage : $self->__invalidateMatrixColumn($column);
205  
206 my ($self, $column) = @_;
207
208 $self->SUPER::_invalidateMatrixColumn($self->__origColumn($column));
209  
210 #delete $self->{$kColumnOrigToCurrent}->{$column};
211  
212 }
213  
214 ######################################################################
215 sub __origColumn{
216 ######################################################################
217 # This method returns the original column number to which a column in the
218 # current file now corresponds
219 #
220 # Usage : my $column = $self->__origColumn($column);
221  
222 return $_[0]->{$kColumnCurrentToOrig}->{$_[1]};
223  
224 }
225  
226 ######################################################################
227 sub __remapRow{
228 ######################################################################
229 # This private method remaps a line in a tmp file to the line it corresponds
230 # to in the original file. It receives the current tmp file line, and
231 # the number of lines that have been removed before it. It then
232 # remaps the current row to point to the original row that the current
233 # row, $numFilteredLines ahead of it, is pointing to.
234 #
235 # Usage : $self->__remapRow($numRowsPrinted, $numFilteredLines)
236  
237 my ($self, $row, $numFilteredLines) = @_;
238  
239 $self->{$kRowCurrentToOrig}->{$row} = $self->{$kRowCurrentToOrig}->{$row + $numFilteredLines};
240  
241 }
242  
243 ######################################################################
244 sub __remapColumn{
245 ######################################################################
246 # This method remaps a column in a tmp file to the column it
247 # corresponds to in the original file. It receives the current file
248 # column index. It then remaps the current column to point to the
249 # original column that the current column, $numFilteredColumns ahead
250 # of it, is pointing to.
251 #
252 # Usage : $self->__remapColumn($numColumnsPrinted, $numFilteredColumns)
253  
254 my ($self, $column, $numFilteredColumns) = @_;
255  
256 $self->{$kColumnCurrentToOrig}->{$column} = $self->{$kColumnCurrentToOrig}->{$column + $numFilteredColumns};
257
258 $self->{$kColumnOrigToCurrent}->{$self->{$kColumnCurrentToOrig}->{$column + $numFilteredColumns}} = $column;
259  
260 }
261  
262 ######################################################################
263 sub __remapColumns{
264 ######################################################################
265 # This method remaps all of the columns in the current tmp file with
266 # respect to their column index in the original file. This method
267 # must be called after carrying out any operation that may reduce the
268 # number of columns in the matrix.
269 #
270 # Usage : $self->__remapColumns;
271  
272 my ($self) = @_;
273  
274 my $numColumns = $self->numColumns;
275 my $numColumnsPrinted = 0;
276  
277 my $numFilteredColumns = 0;
278  
279 foreach my $column (sort {$a<=>$b} keys %{$self->{$kColumnCurrentToOrig}}){
280  
281 if (!$self->__currentColumnIsValid($column)){
282  
283 $numFilteredColumns++;
284 next;
285  
286 }
287  
288 $self->__remapColumn($numColumnsPrinted, $numFilteredColumns) if $numFilteredColumns;
289  
290 $numColumnsPrinted++;
291  
292 last if ($numColumnsPrinted == $numColumns);
293  
294 }
295  
296 }
297  
298 ######################################################################
299 sub __setMaxRowNumber{
300 ######################################################################
301 # This method allows recording of the maximum row number that can exist
302 # in the current file that is being read.
303  
304 my ($self, $number) = @_;
305  
306 $self->{$kMaxRowNumber} = $number;
307  
308 }
309  
310 ######################################################################
311 sub __maxRowNumber{
312 ######################################################################
313 # This method returns the maximum row number that can exist
314 # in the current file that is being read.
315  
316 return $_[0]->{$kMaxRowNumber};
317  
318 }
319  
320 ######################################################################
321 sub __currentRowIsValid{
322 ######################################################################
323 # This private accessor returns a boolean to indicate whether a given
324 # row in the tmp file is still valid (ie has not been filtered out).
325 # It does this by mapping the row to what it's original index was in
326 # the file used to instantiate the matrix, and then determining
327 # whether that index is still valid.
328 #
329 # Usage : if ($self->__currentRowIsValid($row)){ # blah }
330  
331 my ($self, $row) = @_;
332  
333 return $self->_matrixRowIsValid($self->{$kRowCurrentToOrig}->{$row});
334  
335 }
336  
337 ######################################################################
338 sub __currentColumnIsValid{
339 ######################################################################
340 # This private accessor returns a boolean to indicate whether a given
341 # column in the tmpfile is still valid (ie has not been filtered out).
342 # It does this by mapping the column to what it's original index was
343 # in the file used to instantiate the matrix, and then determining
344 # whether that index is still valid.
345 #
346 # Usage : if ($self->__currentColumnIsValid($column)){ # blah }
347  
348 my ($self, $column) = @_;
349  
350 return $self->_matrixColumnIsValid($self->{$kColumnCurrentToOrig}->{$column});
351  
352 }
353  
354 #######################################################################
355 sub __currentValidColumnsArrayRef{
356 #######################################################################
357 # This private method returns an reference to an array that contains
358 # the indices of the columns that are currently valid in the present
359 # file.
360 #
361 # Usage : my $validColumnsArrayRef = $self->__currentValidColumnsArrayRef;
362  
363 my ($self) = @_;
364  
365 my @columns;
366  
367 foreach my $column (sort {$a<=>$b} keys %{$self->{$kColumnOrigToCurrent}}){
368  
369 push (@columns, $self->{$kColumnOrigToCurrent}->{$column}) if $self->_matrixColumnIsValid($column);
370  
371 }
372  
373 return \@columns;
374  
375 }
376  
377 ######################################################################
378 sub __currentValidRowsArrayRef{
379 ######################################################################
380 # This private method returns an reference to an array that contains
381 # the indices of the rows that are currently valid in the present file
382 #
383 # Usage : foreach (@{$self->__currentValidRowsArrayRef}){ # blah }
384  
385 my ($self) = @_;
386  
387 my @rows;
388  
389 my $maxRowNum = $self->__maxRowNumber;
390  
391 foreach my $row (sort {$a<=>$b} keys %{$self->{$kRowCurrentToOrig}}){
392  
393 # a row number should not be valid if it is higher than the
394 # maximum allowable row index. Because invalidation does not
395 # deal with this 100%, this extra check here does.
396  
397 push (@rows, $row) if ($row < $maxRowNum && $self->__currentRowIsValid($row));
398  
399 }
400  
401 return \@rows;
402  
403 }
404  
405 ######################################################################
406 sub __currentColumnForOrig{
407 ######################################################################
408 # This method returns the index where a column in the original file,
409 # now maps in the current temp file.
410 #
411 # Usage : my $col = $self->__currentColumnForOrig($column);
412  
413 return $_[0]->{$kColumnOrigToCurrent}->{$_[1]};
414  
415 }
416  
417 ######################################################################
418 sub __tmpFileHandle{
419 ######################################################################
420 # This private method returns a handle to a tmpfile. If given a 'new'
421 # argument, which will be passed to the tmpFile method, the file will
422 # have it's number increased by one - ie a new file will be used.
423 # Otherwise, a previously created file will be opened.
424 #
425 # Usage : my $fh = $self->__tmpFileHandle(new=>1);
426  
427 my ($self, %args) = @_;
428  
429 my $tmpFile = $self->__tmpFile(%args);
430  
431 local *FH;
432
433 open(FH, ">$tmpFile") || die "Couldn't open $tmpFile : $!\n"; # need an error handling strategy here
434
435 my $fh = *FH;
436  
437 return $fh;
438  
439 }
440  
441 ######################################################################
442 sub __tmpFile{
443 ######################################################################
444 # This method returns the name of a tmpfile. If given the 'new'
445 # argument then the name will be of a new file. Otherwise it will be
446 # of the last generated tmpfile.
447 #
448 # Usage : my $tmpFile = $self->__tmpFile(new=>1);
449  
450 my ($self, %args) = @_;
451  
452 my $num = $self->__tmpNum;
453  
454 if ($args{'new'}){
455  
456 $num++;
457  
458 $self->__setTmpNum($num);
459  
460 }
461  
462 return ($self->_tmpDir.'matrix.'.$$.'.'.$num);
463  
464 }
465  
466 ######################################################################
467 sub __tmpNum{
468 ######################################################################
469 # This method returns the number of the temp file. Generally this
470 # number should be incremented by 1 each time a new tmp file is
471 # created.
472 #
473 # Usage : my $num = $self->__tmpNum;
474  
475  
476 return $_[0]->{$kTmpNum};
477  
478 }
479  
480 ######################################################################
481 sub __setTmpNum{
482 ######################################################################
483 # This method allows the tmp num to be set.
484 #
485 # Usage : $self->__setTmpNum($num);
486  
487 my ($self, $num) = @_;
488  
489 $self->{$kTmpNum} = $num;
490  
491 }
492  
493 #
494 # ** DATA TRANSFORMATION METHODS
495 #
496  
497 ######################################################################
498 sub _centerColumns{
499 ######################################################################
500 # This private method centers each column of data, and returns the
501 # largest absolute value that was used in centering.
502 #
503 # This version of the method assumes that all data for the matrix are
504 # too large to fit in memory
505 #
506 # if we are calculating medians, we have to deal with it differently
507 # than if we are centering columns by means. This is because to
508 # calculate medians we need to store data in memory and sort it to
509 # find the median, whereas for means we can simply keep running totals
510 # in memory. Thus to do it by medians, we will have to read the file
511 # several times. Thus I will seperate out these methods into two functions.
512  
513 my ($self, $method, $lineEnding, $numColumnsToReport) = @_;
514
515 defined $lineEnding && print ("Centering columns by $method", $lineEnding);
516
517 my $methodCall = "__centerColumns_".$method;
518
519 my $largestVal = $self->$methodCall($lineEnding, $numColumnsToReport, $self->_numRowsToReport);
520  
521 return $largestVal;
522
523 }
524  
525 ######################################################################
526 sub __centerColumns_mean{
527 ######################################################################
528 # This method is used for centering the columns of a dataset by the
529 # mean value, when the contents of the dataset are too large to all fit
530 # in memory.
531 #
532 # Usage : my $largestVal = $self->__centerColumns_mean($lineEnding, $numColumnsToReport, $numRowsToReport);
533  
534 my ($self, $lineEnding, $numColumnsToReport, $numRowsToReport) = @_;
535  
536 my $largestVal = 0;
537  
538 my $num = -1;
539  
540 my (@totals, @numDataPoints, @means);
541  
542 # first read through all data, and calculate totals for each column
543  
544 while (my $lineRef = $self->_dataLine($num+1)){
545  
546 $num++;
547
548 next if !$self->__currentRowIsValid($num);
549
550 if (defined $lineEnding && !($num%$numRowsToReport)){
551
552 print "Reading data for row $num", $lineEnding;
553
554 }
555
556 my $numDatapoints = 0;
557
558 for (my $i = 0; $i< @{$lineRef}; $i++){ # go through each data value
559  
560 next if (!$self->__currentColumnIsValid($i)|| $lineRef->[$i] eq ""); # skip blanks and invalid columns
561  
562 $totals[$i] += $lineRef->[$i]; # keep running sum
563 $numDataPoints[$i]++;
564  
565 }
566  
567 }
568  
569 # now calculate the means
570  
571 for (my $i = 0; $i < @totals; $i++){
572  
573 next if (!defined $numDataPoints[$i]); # they may simply have filler columns, with no data
574
575 $means[$i] = $totals[$i]/$numDataPoints[$i];
576
577 if (abs($means[$i]) > $largestVal){
578
579 $largestVal = abs($means[$i]);
580
581 }
582
583 }
584
585 # now we have to actually center the data, by going through the
586 # data again and creating a new file with the means subtracted.
587 # This can be put in another function, that can be used by the
588 # centerColumnMedians as well
589  
590 $self->__subtractColumnAverages(\@means, $lineEnding, $numColumnsToReport, $numRowsToReport);
591  
592 return $largestVal;
593
594 }
595  
596  
597 ######################################################################
598 sub __centerColumns_median{
599 ######################################################################
600 # This method is used for centering the columns of a dataset by the
601 # median value, when the contents of the dataset are too large to all fit
602 # in memory.
603 #
604 # Because we need to have a sorted list of values to calculate the
605 # median, we are going to have to read through all the data multiple
606 # times (potentially).
607 #
608 # Usage : my $largestVal = $self->__centerColumns_median($lineEnding, $numColumnsToReport, $numRowsToReport);
609  
610 my ($self, $lineEnding, $numColumnsToReport, $numRowsToReport) = @_;
611  
612 my $largestVal = 0;
613  
614 my $numColumns = $self->_numDataColumns; # get info from subclass
615 my $numRows = $self->_numDataRows; # to decide on the fly how many columns we can read
616  
617 # now get data for a certain number of columns at a time
618  
619 my $numColumnsToProcess = int(500000/$numRows); # assume if 50,000 rows, can process 10 columns at a time
620  
621 if ($numColumnsToProcess > $numColumns){
622  
623 $numColumnsToProcess = $numColumns;
624  
625 }
626  
627 my @medians;
628  
629 for (my $i = 0; $i < $numColumns; $i+= $numColumnsToProcess){
630  
631 if (defined $lineEnding){
632  
633 print "Processing columns $i through ", $i + $numColumnsToProcess, $lineEnding;
634  
635 }
636  
637 my $num = -1;
638  
639 my @values;
640  
641 my $lastIndex; # the index of the last data column to process in this round
642  
643 if ($i + $numColumnsToProcess > $numColumns){
644  
645 $lastIndex = $numColumns;
646  
647 }else{
648  
649 $lastIndex = $i + $numColumnsToProcess;
650  
651 }
652  
653 while (my $lineRef = $self->_dataLine($num+1)){
654
655 $num++;
656  
657 next if !$self->__currentRowIsValid($num);
658  
659 if (defined $lineEnding && !($num%$numRowsToReport)){
660
661 print "Reading data for row $num", $lineEnding;
662
663 }
664
665 my $col = -1;
666
667 for (my $j = $i; $j < $lastIndex; $j++){ # go through each data value
668  
669 $col++;
670
671 next if (!$self->__currentColumnIsValid($j) || $lineRef->[$j] eq ""); # skip invalid columns and blanks
672  
673 push (@{$values[$col]}, $lineRef->[$j]);
674
675 }
676
677 }
678  
679 # now get the median value for each of those columns
680  
681 my $col = -1;
682  
683 for (my $j = $i; $j < $lastIndex; $j++){ # go through each column of data
684  
685 $col++;
686  
687 next if (!$self->__currentColumnIsValid($j) || !defined $values[$col]); # skip invalid columns, or columns with no data
688
689 my $median = $self->_average("median", $values[$col]);
690  
691 if (abs($median) > $largestVal){
692  
693 $largestVal = abs($median);
694  
695 }
696  
697 $medians[$j] = $median;
698  
699 }
700  
701 }
702  
703 # once we get here, we should have calculate the median for every column
704 # so now need to subtract them from every column
705  
706 $self->__subtractColumnAverages(\@medians, $lineEnding, $numColumnsToReport, $numRowsToReport);
707  
708 return $largestVal;
709  
710 }
711  
712 ######################################################################
713 sub __subtractColumnAverages{
714 ######################################################################
715 # This method retrieves data from the dataMatrix through the subclass,
716 # subtracts the column average from each value, then, through the subclass
717 # writes out a new file.
718 #
719 # Usage : $self->__subtractColumnAverages(\@medians, $lineEnding, $numColumnsToReport);
720 #
721 # Note we're not worrying here about percentiles being dumped out
722  
723 my ($self, $averagesArrayRef, $lineEnding, $numColumnsToReport, $numRowsToReport) = @_;
724
725 my $num = -1;
726 my $numFilteredLines = 0; # keep a record of how many lines are filtered out
727 my $numRowsPrinted = 0;
728  
729 my $validColumnsArrayRef = $self->__currentValidColumnsArrayRef;
730  
731 my $hasPercentiles;
732 my $percentilesHashRef; # have to worry about
733
734 # first open a new file, and dump out the meta data
735
736 my $fh = $self->__tmpFileHandle(new=>1);
737
738 $self->_printLeadingMeta($fh, $self->_validColumnsArrayRef);
739
740 # go through all data, and subtract average
741
742 while (my $lineRef = $self->_dataLine($num+1)){
743
744 $num++;
745
746 if (!$self->__currentRowIsValid($num)){
747
748 $numFilteredLines++;
749 next; # don't print this line out
750  
751 }
752
753 if (defined $lineEnding && !($num%$numRowsToReport)){
754
755 print "Subtracting column averages from row $num", $lineEnding;
756
757 }
758
759 for (my $i = 0; $i< @{$lineRef}; $i++){ # go through each data value
760  
761 next if $lineRef->[$i] eq ""; # skip blanks
762  
763 $lineRef->[$i] -= $averagesArrayRef->[$i];
764  
765 }
766  
767 # now we want to dump the data line to disk
768  
769 $self->_printRow($fh, $self->__origRow($num), $lineRef, $validColumnsArrayRef);
770  
771 # if any lines have been filtered, we need to remap the current row
772  
773 $self->__remapRow($numRowsPrinted, $numFilteredLines) if $numFilteredLines;
774  
775 $numRowsPrinted++;
776  
777 }
778  
779 # now dump out any trailing meta data, then close the handle
780
781 $self->_printTrailingMeta($fh, $self->_validColumnsArrayRef);
782  
783 close $fh;
784  
785 $self->_setFileForReading($self->__tmpFile);
786  
787 $self->__remapColumns;
788  
789 $self->__setMaxRowNumber($self->numRows);
790  
791 }
792  
793
794 ######################################################################
795 sub _centerRows{
796 ######################################################################
797 # This private method actually centers the row data. This version assumes
798 # that all data are too big to fit in memory.
799  
800 my ($self, $method, $lineEnding, $numRowsToReport) = @_;
801  
802 defined $lineEnding && print ("Centering rows by $method", $lineEnding);
803  
804 my $fh = $self->__tmpFileHandle(new=>1);
805  
806 my $validColumnsArrayRef = $self->__currentValidColumnsArrayRef;
807  
808 $self->_printLeadingMeta($fh, $self->_validColumnsArrayRef);
809  
810 my $num = -1;
811  
812 while (my $lineRef = $self->_dataLine($num+1)){
813  
814 $num++;
815  
816 next if !$self->__currentRowIsValid($num);
817
818 if (defined $lineEnding && !($num%$numRowsToReport)){
819
820 print "Centering row $num", $lineEnding;
821
822 }
823
824 my $average = $self->_rowAverage($lineRef, $method);
825  
826 # now subtract average from each value
827  
828 $self->_centerRow($lineRef, $average);
829
830 # now we want to dump the data line to disk
831  
832 $self->_printRow($fh, $self->__origRow($num), $lineRef, $validColumnsArrayRef);
833  
834 }
835  
836 # now dump out any trailing meta data, then close the handle
837
838 $self->_printTrailingMeta($fh, $self->_validColumnsArrayRef);
839  
840 close $fh;
841  
842 $self->_setFileForReading($self->__tmpFile);
843  
844 $self->__remapColumns;
845  
846 $self->__setMaxRowNumber($self->numRows);
847  
848 }
849  
850 ######################################################################
851 sub _filterRowsByPercentPresentData{
852 ######################################################################
853 # This method invalidates rows that do not have greater than the
854 # requested percentage of present data.
855  
856 my ($self, $percent, $lineEnding, $numRowsToReport) = @_;
857
858 my $requiredNumDatapoints = $self->numColumns * ($percent / 100);
859
860 my $num = -1;
861  
862 while (my $lineRef = $self->_dataLine($num+1)){
863
864 $num++;
865  
866 next if !$self->__currentRowIsValid($num);
867  
868 if (defined $lineEnding && !($num%$numRowsToReport)){
869
870 print "Filtering row $num", $lineEnding;
871
872 }
873  
874 my $numDatapoints = 0;
875
876 foreach (my $i = 0; $i < @{$lineRef}; $i++){ # go through each data value
877
878 next if (!$self->__currentColumnIsValid($i) || $lineRef->[$i] eq "");
879
880 $numDatapoints++;
881
882 }
883  
884 $self->__invalidateMatrixRow($num) unless ($numDatapoints > $requiredNumDatapoints);
885  
886 }
887
888 }
889  
890 ######################################################################
891 sub _filterColumnsByPercentPresentData{
892 ######################################################################
893 # This method invalidates columns that do not have greater than the
894 # requested percentage of present data
895 #
896 # This version of the method is for when all data are too large fit in memory.
897  
898 my ($self, $percent, $lineEnding, $numColumnsToReport) = @_;
899  
900 my $numRowsToReport = $self->_numRowsToReport;
901  
902 my $requiredNumDatapoints = $self->numRows * ($percent / 100);
903  
904 my $num = -1;
905  
906 my @totals;
907  
908 while (my $lineRef = $self->_dataLine($num+1)){
909
910 $num++;
911  
912 next if !$self->__currentRowIsValid($num);
913  
914 if (defined $lineEnding && !($num%$numRowsToReport)){
915
916 print "Reading data for row $num", $lineEnding;
917
918 }
919  
920 # now keep a tally of the number of datapoints per column
921
922 my $numDatapoints = 0;
923
924 for (my $i = 0; $i < @{$lineRef} ; $i++){
925  
926 next if (!$self->__currentColumnIsValid($i) || $lineRef->[$i] eq "");
927  
928 $totals[$i]++;
929  
930 }
931  
932 }
933
934 for (my $i = 0; $i < @totals; $i++){
935  
936 next if !$self->__currentColumnIsValid($i);
937  
938 $self->__invalidateMatrixColumn($i) unless (defined ($totals[$i]) && $totals[$i] > $requiredNumDatapoints);
939  
940 }
941  
942 }
943 ##############################################################################################
944 sub _filterRowsOnColumnPercentile{
945 ##############################################################################################
946 # This method filters out rows based on their column percentile, when all data are too BIG
947 # to fit in memory simultaneously
948  
949 die "_filterRowsOnColumnPercentile is not implemented for big datamatrices.";
950  
951 }
952  
953 ######################################################################
954 sub __filterRowsByCount{
955 ######################################################################
956 # This private method filters out rows that don't have a count for
957 # some particular property above or equal to a threshold. It accepts
958 # a hash reference, that hashes the row number to a count, and a
959 # threshold value. Note that not all rows are necessarily entered
960 # into the hash, so this method iterates over all rows, and checks
961 # each valid one for its count in the hash, then invalidates those
962 # with too low a count.
963 #
964 # Usage : $self->__filterRowsByCount(\%count, $numColumns);
965  
966 my ($self, $rowToCountHashRef, $threshold) = @_;
967  
968 foreach my $row (sort {$a<=>$b} @{$self->__currentValidRowsArrayRef}){
969  
970 if (!exists($rowToCountHashRef->{$row}) || $rowToCountHashRef->{$row} < $threshold){
971  
972 $self->__invalidateMatrixRow($row);
973  
974 }
975  
976 }
977  
978 }
979  
980 ########################################################################
981 sub _filterRowsOnColumnDeviation{
982 ########################################################################
983 # This method will filter out rows whose values do not deviate from
984 # the column mean by a specified number of standard deviations, in at
985 # least numColumns columns. This version of the method is written
986 # for the case when all data are too large to fit in memory
987 #
988  
989 my ($self, $lineEnding, $numRowsToReport, $deviations, $numColumns) = @_;
990  
991 # first need to get the standard deviations of all valid columns
992  
993 my ($stddevHashRef, $meansHashRef) = $self->__validColumnsStdDevAndMeanHashRefs($lineEnding, $numRowsToReport);
994
995 # now calculate the upper and lower bounds for each column
996  
997 my ($upperHashRef, $lowerHashRef) = $self->_calculateBounds($stddevHashRef, $meansHashRef, $deviations, $lineEnding);
998  
999 # now count up how many values in each row lie outside of the
1000 # specified number of deviations from the mean, for each row
1001  
1002 my (%count, $val);
1003  
1004 # go through every row
1005  
1006 defined $lineEnding && print("Running filters over each row", $lineEnding);
1007  
1008 my $num = -1;
1009  
1010 while (my $lineRef = $self->_dataLine($num+1)){
1011
1012 $num++;
1013  
1014 next if !$self->__currentRowIsValid($num);
1015  
1016 if (defined $lineEnding && !($num%$numRowsToReport)){
1017  
1018 print "Filtering row $num", $lineEnding;
1019
1020 }
1021  
1022 foreach (my $column = 0; $column < @{$lineRef}; $column++){
1023  
1024 next if !$self->__currentColumnIsValid($column);
1025  
1026 $val = $lineRef->[$column];
1027  
1028 next if ($val eq "");
1029  
1030 next unless ($val > $upperHashRef->{$column} || $val < $lowerHashRef->{$column});
1031  
1032 $count{$num}++; # this value passes the criteria
1033  
1034 }
1035  
1036 }
1037  
1038 $self->__filterRowsByCount(\%count, $numColumns);
1039  
1040 }
1041  
1042 ######################################################################
1043 sub __validColumnsStdDevAndMeanHashRefs{
1044 ######################################################################
1045 # This method calculates the standard deviations for each valid
1046 # column, and returns references to two hashes. Both have the column
1047 # index as the key, and one has the standard deviation as the values,
1048 # the other has the column means as the values.
1049 #
1050 # mean = Sum of values/n
1051 # std dev = square root (((n * sum of (x^2)) - (sum of x)^2)/n(n-1))
1052 #
1053 # Usage : my ($stddevHashRef, $meansHashRef) = $self->__validColumnsStdDevAndMeanHashRefs($lineEnding);
1054  
1055 my ($self, $lineEnding, $numRowsToReport) = @_;
1056  
1057 my (%sumOfX, %sumX2, %numDataPoints, $val);
1058  
1059 defined $lineEnding && print ("Calculating mean and standard deviations for each column", $lineEnding);
1060  
1061 my $num = -1;
1062  
1063 while (my $lineRef = $self->_dataLine($num+1)){
1064
1065 $num++;
1066  
1067 if (defined $lineEnding && !($num%$numRowsToReport)){
1068  
1069 print "Processing row $num", $lineEnding;
1070  
1071 }
1072  
1073 next if !$self->__currentRowIsValid($num);
1074  
1075 for (my $column = 0; $column < @{$lineRef}; $column++){
1076  
1077 next if !$self->__currentColumnIsValid($column);
1078  
1079 $val = $lineRef->[$column];
1080  
1081 next if ($val eq "");
1082  
1083 $sumOfX{$column} += $val;
1084 $sumX2{$column} += $val*$val;
1085 $numDataPoints{$column}++;
1086  
1087 }
1088  
1089 }
1090  
1091 my ($stddevHashRef, $meansHashRef) = $self->_calculateMeansAndStdDeviations(\%sumOfX, \%sumX2, \%numDataPoints);
1092  
1093 return ($stddevHashRef, $meansHashRef);
1094  
1095 }
1096  
1097 ######################################################################
1098 sub _filterRowsOnValues{
1099 ######################################################################
1100 # This method filters out rows whose values do not pass a specified
1101 # criterion, in at least numColumns columns. This is the version for
1102 # when all data cannot fit in memory
1103 #
1104  
1105 my ($self, $value, $method, $lineEnding, $numRowsToReport, $numColumns) = @_;
1106  
1107 my (%count, $datum);
1108  
1109 my $num = -1;
1110  
1111 while (my $lineRef = $self->_dataLine($num+1)){
1112  
1113 $num++;
1114  
1115 if (defined $lineEnding && !($num%$numRowsToReport)){
1116  
1117 print "Filtering row $num", $lineEnding;
1118  
1119 }
1120
1121 next if !$self->__currentRowIsValid($num);
1122
1123 for (my $column = 0; $column < @{$lineRef}; $column++){
1124  
1125 next if !$self->__currentColumnIsValid($column);
1126  
1127 $datum = $lineRef->[$column];
1128  
1129 next if $datum eq "";
1130  
1131 # following method call returns true if value passes criteria
1132  
1133 $count{$num}++ if ($self->$method($datum, $value));
1134  
1135 }
1136
1137 }
1138  
1139 $self->__filterRowsByCount(\%count, $numColumns);
1140
1141 }
1142  
1143 ######################################################################
1144 sub _filterRowsOnVectorLength{
1145 ######################################################################
1146 # This method filters out rows based on whether the vector that their
1147 # values define has a length of greater than the specified length.
1148 #
1149  
1150 my ($self, $requiredLength, $lineEnding, $numRowsToReport) = @_;
1151  
1152 my $val;
1153  
1154 my $num = -1;
1155  
1156 while (my $lineRef = $self->_dataLine($num+1)){
1157  
1158 $num++;
1159  
1160 next if (!$self->__currentRowIsValid($num));
1161  
1162 if (defined $lineEnding && !($num%$numRowsToReport)){
1163  
1164 print "Filtering row $num", $lineEnding;
1165  
1166 }
1167  
1168 my $sumSquares;
1169  
1170 foreach (my $column = 0; $column <@{$lineRef}; $column++){
1171  
1172 next if !$self->__currentColumnIsValid($column);
1173
1174 $val = $lineRef->[$column];
1175  
1176 next if $val eq "";
1177
1178 $sumSquares += $val**2;
1179
1180 }
1181
1182 # invalidate those who don't pass the length requirement
1183
1184 $self->__invalidateMatrixRow($num) unless sqrt($sumSquares) > $requiredLength;
1185
1186 }
1187  
1188 }
1189  
1190  
1191 ######################################################################
1192 sub _logTransformData{
1193 ######################################################################
1194 # This method log transforms the contents of the data matrix, using
1195 # the specified base.
1196 #
1197 # This version is for when all data cannot fit in memory
1198  
1199 my ($self, $logBase, $lineEnding, $numRowsToReport) = @_;
1200  
1201 my ($val);
1202  
1203 my $fh = $self->__tmpFileHandle(new=>1);
1204  
1205 my $validColumnsArrayRef = $self->__currentValidColumnsArrayRef;
1206  
1207 $self->_printLeadingMeta($fh, $self->_validColumnsArrayRef);
1208  
1209 my $num = -1;
1210  
1211 while (my $lineRef = $self->_dataLine($num+1)){
1212  
1213 $num++;
1214  
1215 next if !$self->__currentRowIsValid($num);
1216  
1217 if (defined $lineEnding && !($num%$numRowsToReport)){
1218  
1219 print "Log transforming row $num", $lineEnding;
1220  
1221 }
1222  
1223 foreach (my $column = 0; $column < @{$lineRef}; $column++){
1224  
1225 next if !$self->__currentColumnIsValid($column);
1226  
1227 $val = $lineRef->[$column];
1228
1229 next if (!defined $val || $val eq ""); # skip blanks
1230  
1231 $lineRef->[$column] = sprintf "%.4f", log($val)/$logBase;
1232  
1233 }
1234  
1235 $self->_printRow($fh, $self->__origRow($num), $lineRef, $validColumnsArrayRef);
1236  
1237 }
1238  
1239 # now dump out any trailing meta data, then close the handle
1240
1241 $self->_printTrailingMeta($fh, $self->_validColumnsArrayRef);
1242  
1243 close $fh;
1244  
1245 $self->_setFileForReading($self->__tmpFile);
1246  
1247 $self->__remapColumns; # do we need to do this?
1248  
1249 $self->__setMaxRowNumber($self->numRows);
1250  
1251 }
1252  
1253 ######################################################################
1254 sub _scaleColumnData{
1255 ######################################################################
1256 # This method scales the data for particular columns as specified by
1257 # the client, when all data are too big to fit in memory.
1258 #
1259  
1260 my ($self, $columnsToFactorsHashRef, $lineEnding, $numRowsToReport) = @_;
1261  
1262 my $num = -1;
1263  
1264 my ($val, $scalingFactor, $printed1, $printed2);
1265  
1266 my $fh = $self->__tmpFileHandle(new=>1);
1267  
1268 my $validColumnsArrayRef = $self->__currentValidColumnsArrayRef;
1269  
1270 $self->_printLeadingMeta($fh, $self->_validColumnsArrayRef);
1271  
1272 while (my $lineRef = $self->_dataLine($num+1)){
1273  
1274 $num++;
1275  
1276 next if !$self->__currentRowIsValid($num);
1277  
1278 if (defined $lineEnding && !($num%$numRowsToReport)){
1279  
1280 print "Scaling column data on row $num", $lineEnding;
1281  
1282 }
1283  
1284 foreach my $column (keys %{$columnsToFactorsHashRef}){
1285  
1286 if (!$self->_matrixColumnIsValid($column)){
1287  
1288 if (!defined ($printed1)){
1289  
1290 print STDERR "The column index, $column, is not valid for this dataMatrix.\n";
1291  
1292 }
1293  
1294 $printed1 = 1; # so we only print message once
1295 next;
1296
1297 }
1298  
1299 $scalingFactor = $columnsToFactorsHashRef->{$column};
1300  
1301 if (!defined $scalingFactor || $scalingFactor == 0){
1302  
1303 if (!defined $printed2){
1304  
1305 print STDERR "The scaling factor supplied for $column was \"$scalingFactor\".\n";
1306 print STDERR "It will not be used.\n";
1307
1308 }
1309  
1310 $printed2 = 1; # so we only print message once
1311 next;
1312  
1313 }
1314
1315 $val = $lineRef->[$self->__currentColumnForOrig($column)];
1316  
1317 next if $val eq ""; # skip blanks
1318  
1319 $lineRef->[$self->__currentColumnForOrig($column)] = sprintf "%.4f", $val/$scalingFactor;
1320  
1321 }
1322  
1323 $self->_printRow($fh, $self->__origRow($num), $lineRef, $validColumnsArrayRef);
1324  
1325 }
1326  
1327 # now dump out any trailing meta data, then close the handle
1328
1329 $self->_printTrailingMeta($fh, $self->_validColumnsArrayRef);
1330  
1331 close $fh;
1332  
1333 $self->_setFileForReading($self->__tmpFile);
1334  
1335 $self->__remapColumns; # do we need to do this?
1336  
1337 $self->__setMaxRowNumber($self->numRows);
1338  
1339 }
1340  
1341  
1342 ######################################################################
1343 sub dumpData{
1344 ######################################################################
1345 # This method dumps the current contents of the dataMatrix object to a
1346 # file, either whose name was provided as a single argument, or to a
1347 # file whose name was used to construct the object.
1348 #
1349 # To do this, it delegates printing to a subclass.
1350 # Subclasses have to implement the following methods:
1351 #
1352 # _printLeadingMeta
1353 # _printRow
1354 # _printTrailingMeta
1355 #
1356 # printLeadingMeta is given a reference to an array of the valid columns
1357 # printRow is given a row number, and the VALID data for that row
1358 # printTrailingMeta is given a reference to an array of the valid columns array of the valid columns
1359 #
1360 # is there is no leading or trailing meta information to print,
1361 # the subclass can leave the subroutines empty.......
1362  
1363 my ($self, $file) = @_;
1364  
1365 # As the matrix did not fit in memory, we may need to use the
1366 # original file to read in the data, if we do not have our own tmp
1367 # file, and if no filename was provided, as it is the only source
1368 # of the data
1369  
1370 if (!$self->__tmpNum && !$file){
1371  
1372 my $tmpFile = $self->__tmpFile(new=>1);
1373  
1374 # we can simply rename the file, as the user wants it overwritten anyway
1375  
1376 rename ($self->file, $tmpFile);
1377  
1378 # need to tell the subclass that the file for reading has had its name changed
1379  
1380 $self->_setFileForReading($tmpFile);
1381  
1382 }
1383  
1384 my $remove = $file; # if a file name was passed in, we'll be allowed to remove the last temp file.
1385  
1386 $file ||= $self->file;
1387  
1388 if (defined $self->_fileForReading && $file eq $self->_fileForReading){ # don't want to clobber ourselves
1389  
1390 my $tmpFile = $self->__tmpFile(new=>1);
1391  
1392 # we can simply rename the file, as the user wants it overwritten anyway
1393  
1394 rename ($self->_fileForReading, $tmpFile);
1395  
1396 # need to tell the subclass that the file for reading has had its name changed
1397  
1398 $self->_setFileForReading($tmpFile);
1399  
1400 }
1401  
1402 my $hasPercentiles = exists $self->{$kPercentiles};
1403  
1404 my $percentilesRef = $self->{$kPercentiles};
1405  
1406 open (DATAOUT, ">$file") || die "Cannot open $file for writing : $!.\n";
1407  
1408 # print first line
1409  
1410 $self->_printLeadingMeta(\*DATAOUT, $self->_validColumnsArrayRef, $hasPercentiles, "percentiles");
1411
1412 my $row = -1;
1413 my $numFilteredLines = 0; # keep a record of how many lines are filtered out
1414 my $numRowsPrinted = 0;
1415  
1416 my $currentValidColumnsArrayRef = $self->__currentValidColumnsArrayRef;
1417  
1418 while (my $lineRef = $self->_dataLine($row+1)){
1419
1420 $row++;
1421
1422 if (!$self->__currentRowIsValid($row)){
1423
1424 $numFilteredLines++;
1425 next; # don't print this line out
1426
1427 }
1428
1429 $self->_printRow(\*DATAOUT, $self->__origRow($row), $lineRef, $currentValidColumnsArrayRef, $hasPercentiles, $percentilesRef);
1430  
1431 # if any lines have been filtered, we need to remap the current row
1432  
1433 $self->__remapRow($numRowsPrinted, $numFilteredLines) if $numFilteredLines;
1434  
1435 $numRowsPrinted++; # do this last, as we call the first line zero
1436
1437 }
1438  
1439 $self->__remapColumns;
1440
1441 $self->_printTrailingMeta(\*DATAOUT, $self->_validColumnsArrayRef, $hasPercentiles);
1442  
1443 close DATAOUT;
1444  
1445 $self->_setFileForReading($file);
1446  
1447 $remove && unlink($self->__tmpFile);
1448  
1449 $self->__setMaxRowNumber($self->numRows);
1450  
1451 }
1452  
1453  
1454 1; # to keep Perl happy
1455  
1456 =pod
1457  
1458 =head1 NAME
1459  
1460 Microarray::DataMatrix::BigDataMatrix - abstraction to matrix that won't fit in memory
1461  
1462 =head1 Abstract
1463  
1464 bigDataMatrix is an abstract class, which provides as abstraction to a
1465 matrix of data that is too large to fit into memory. It should not be
1466 subclassed by concrete subclasses. Instead, the subclass
1467 anySizeDataMatrix, can be subclassed with concrete subclasses, which
1468 will provide abstractions to dataMatrices stored in particular file
1469 formats, such as pcl files.
1470  
1471 =head1 Overall Logic
1472  
1473 Internally, bigDataMatrix simply keeps track of which rows and columns
1474 are still valid. As it runs filters, or transformations on data, it
1475 creates temp files, which contain the result of such an operation. It
1476 keeps track of which rows and columns in the latest temp file are
1477 valid, and also to which rows and columns in the original file, used
1478 for object construction, that they map. Then, when it comes time to
1479 dump data to disk, it is able to instruct a concrete subclass what the
1480 original index of a row or column was, so that the concrete subclass
1481 can print out the appropriate meta data.
1482  
1483 =head1 Construction
1484  
1485 As bigDataMatrix is an abstract class, it has no constructor.
1486 However, the subclass, anySizeDataMatrix, once it has determined that
1487 a matrix will not fit into memory, MUST call the _init method, which
1488 is described below.
1489  
1490 =head2 _init
1491  
1492 This protected method will read determine how many rows and columns
1493 there are in the initial matrix. It MUST be called during
1494 initialization of a subclass object, before any other methods can be
1495 called by the client (in practice it is called from anyDataMatrix).
1496  
1497 Usage:
1498  
1499 $self->_init;
1500  
1501 or:
1502  
1503 $self->SUPER::_init;
1504  
1505 =head1 private utility methods
1506  
1507 =head2 __validateRows
1508  
1509 This private method receives the number of rows that the matrix has,
1510 and simply records each one of them as valid. In addition it sets up
1511 a map of the current row positions in a temp file, to their original
1512 positions in the file used for construction.
1513  
1514 Usage:
1515  
1516 $self->__validateRows($numRows);
1517  
1518 =head2 __validateColumns
1519  
1520 This method receives the number of columns that the matrix has, and
1521 simply records each one of them as valid. In addition it sets up a
1522 map of the column positions in the original file to their current
1523 positions, and a reverse map of the columns current positions, to
1524 their positions in the original matrix file used for object
1525 construction.
1526  
1527 Usage :
1528  
1529 $self->__validateColumns($numColumns);
1530  
1531 =head2 __invalidateMatrixRow
1532  
1533 This private mutator method makes a row invalid. We actually do the
1534 invalidation in the super class, but have to use this method to call
1535 the superclass method, so that we mark the row index from the original
1536 file as invalid, rather than marking as invalid the row index based on
1537 the rows current index. We do this by translating the current row
1538 number to its original row index.
1539  
1540 Usage :
1541  
1542 $self->__invalidateMatrixRow($num);
1543  
1544 =head2 __origRow
1545  
1546 This private method returns the original row number to which a row in
1547 the current file now corresponds.
1548  
1549 Usage :
1550  
1551 my $origRow = $self->__origRow($row);
1552  
1553 =head2 __invalidateMatrixColumn
1554  
1555 This private mutator method makes a column invalid. We actually do
1556 the invalidation in the super class, but have to use this method to
1557 call the superclass method, so that we mark the columns index from the
1558 original file as invalid, rather than marking as invalid the column
1559 index based on the current index of a column. We do this by translating
1560 the current column number to its original.
1561  
1562 Usage :
1563
1564 $self->__invalidateMatrixColumn($column);
1565  
1566 =head2 __origColumn
1567  
1568 This method returns the original column number to which a column in
1569 the current file now corresponds.
1570  
1571 Usage :
1572  
1573 my $column = $self->__origColumn($column);
1574  
1575 =head2 __remapRow
1576  
1577 This private method remaps a line in a tmp file to the line it corresponds
1578 to in the original file. It receives the current tmp file line, and
1579 the number of lines that have been removed before it. It then
1580 remaps the current row to point to the original row that the current
1581 row, $numFilteredLines ahead of it, is pointing to.
1582  
1583 Usage :
1584  
1585 $self->__remapRow($numRowsPrinted, $numFilteredLines);
1586  
1587 =head2 __remapColumn
1588  
1589 This private method remaps a column in a tmp file to the column it
1590 corresponds to in the original file. It receives the current file
1591 column index. It then remaps the current column to point to the
1592 original column that the current column, $numFilteredColumns ahead of
1593 it, is pointing to.
1594  
1595 Usage :
1596  
1597 $self->__remapColumn($numColumnsPrinted, $numFilteredColumns);
1598  
1599 =head2 __remapColumns
1600  
1601 This method remaps all of the columns in the current tmp file with
1602 respect to their column index in the original file. This method must
1603 be called after carrying out any operation that may reduce the number
1604 of columns in the matrix.
1605  
1606 Usage :
1607  
1608 $self->__remapColumns;
1609  
1610 =head2 __currentRowIsValid
1611  
1612 This private accessor returns a boolean to indicate whether a given
1613 row in the tmp file is still valid (ie has not been filtered out). It
1614 does this by mapping the row to what its original index was in the
1615 file used to instantiate the matrix, and then determining whether that
1616 index is still valid.
1617  
1618 Usage :
1619  
1620 if ($self->__currentRowIsValid($row)){ # blah }
1621  
1622 =head2 __currentColumnIsValid
1623  
1624 This private accessor returns a boolean to indicate whether a given
1625 column in the tmpfile is still valid (ie has not been filtered out).
1626 It does this by mapping the column to what its original index was
1627 in the file used to instantiate the matrix, and then determining
1628 whether that index is still valid.
1629  
1630 Usage :
1631  
1632 if ($self->__currentColumnIsValid($column)){ # blah }
1633  
1634 =head2 __currentValidColumnsArrayRef
1635  
1636 This private method returns an reference to an array that contains the
1637 indices of the columns that are currently valid in the present file.
1638  
1639 Usage :
1640  
1641 my $validColumnsArrayRef = $self->__currentValidColumnsArrayRef;
1642  
1643 =head2 __currentValidRowsArrayRef
1644  
1645 This private method returns an reference to an array that contains the
1646 indices of the rows that are currently valid in the present file
1647  
1648 Usage :
1649  
1650 foreach (@{$self->__currentValidRowsArrayRef}){ # blah }
1651  
1652 =head2 __currentColumnForOrig
1653  
1654 This method returns the index where a column in the original file,
1655 now maps in the current temp file.
1656  
1657 Usage :
1658  
1659 my $col = $self->__currentColumnForOrig($column);
1660  
1661 =head2 __tmpFileHandle
1662  
1663 This private method returns a handle to a tmpfile. If given a 'new'
1664 argument, which will be passed to the tmpFile method, the file will
1665 have its associated number increased by one - ie a new file will be
1666 used. Otherwise, a previously created file will be opened.
1667  
1668 Usage :
1669  
1670 my $fh = $self->__tmpFileHandle(new=>1);
1671  
1672 =head2 __tmpFile
1673  
1674 This private method returns the name of a tmpfile. If given the 'new'
1675 argument then the name will be of a new file. Otherwise it will be of
1676 the last generated tmpfile.
1677  
1678 Usage :
1679  
1680 my $tmpFile = $self->__tmpFile(new=>1);
1681  
1682 =head2 __tmpNum
1683  
1684 This method returns the number of the temp file. Generally this
1685 number should be incremented by 1 each time a new tmp file is created.
1686  
1687 Usage :
1688  
1689 my $num = $self->__tmpNum;
1690  
1691 =head2 __setTmpNum
1692  
1693 This method allows the tmp num to be set.
1694  
1695 Usage :
1696  
1697 $self->__setTmpNum($num);
1698  
1699 =head2 __centerColumns_mean
1700  
1701 This private method is used for centering the columns of a dataset by
1702 the mean value.
1703  
1704 Usage :
1705  
1706 my $largestVal = $self->__centerColumns_mean($lineEnding, $numColumnsToReport);
1707  
1708 =head2 __centerColumns_median
1709  
1710 This method is used for centering the columns of a dataset by the
1711 median value.
1712  
1713 Because we need to have a sorted list of values to calculate the
1714 median, we are going to have to read through all the data multiple
1715 times (potentially), to avoid having to have too much data in memory.
1716  
1717 Usage :
1718  
1719 my $largestVal = $self->__centerColumns_median($lineEnding, $numColumnsToReport);
1720  
1721 =head2 __subtractColumnAverages
1722  
1723 This method retrieves data from the dataMatrix through the subclass,
1724 subtracts the column average from each value, then, through the
1725 subclass methods writes out a new file.
1726  
1727 Usage :
1728  
1729 $self->__subtractColumnAverages(\@medians, $lineEnding, $numColumnsToReport);
1730  
1731 =head2 __filterRowsByCount
1732  
1733 This private method filters out rows that do not have a count for some
1734 particular property above or equal to a threshold. It accepts a hash
1735 reference, that hashes the row number to a count, and a threshold
1736 value. Note that not all rows are necessarily entered into the hash,
1737 so this method iterates over all rows, and checks each valid one for
1738 its count in the hash, then invalidates those with too low a count.
1739  
1740 Usage :
1741  
1742 $self->__filterRowsByCount(\%count, $numColumns);
1743  
1744 =head2 __validColumnsStdDevAndMeanHashRefs
1745  
1746 This method calculates the standard deviations for each valid column,
1747 and returns references to two hashes. Both have the column index as
1748 the key, and one has the standard deviation as the values, the other
1749 has the column means as the values.
1750  
1751 mean = Sum of values/n
1752 std dev = square root (((n * sum of (x^2)) - (sum of x)^2)/n(n-1))
1753  
1754 Usage :
1755  
1756 my ($stddevHashRef, $meansHashRef) = $self->__validColumnsStdDevAndMeanHashRefs($lineEnding);
1757  
1758 =head1 Protected data transformation/filtering methods
1759  
1760 Note: These methods provide the backend nuts and bolts for a
1761 transformation or filtering. They should only be called by the
1762 immediate subclass, anySizeDataMatrix, and not directly by the
1763 concrete subclasses of anySizeDataMatrix. In addition, note that the
1764 companion smallDataMatrix must (and does) provide identical interfaces
1765 to these methods (obviously with different underlying
1766 implementations), such that anySizeDataMatrix can call the methods
1767 without regard to the size of the underlying matrix.
1768  
1769 =head2 _centerColumns
1770  
1771 This protected method centers each column of data, and returns the
1772 largest absolute value that was used in the centering. The caller of
1773 the method must specify whether to center by means or medians.
1774  
1775 Usage :
1776  
1777 $self->_centerColumns('mean', $lineEnding, $numColumnsToReport);
1778  
1779 =head2 _centerRows
1780  
1781 This protected method actually centers the row data, by calculating
1782 the average (mean or nedian, depending on what was requested) for each
1783 row, and then subtracting that value from each valid datapoint in the
1784 row.
1785  
1786 Usage :
1787  
1788 $self->_centerRows('median', $lineEnding, $numRowsToReport);
1789  
1790 =head2 _filterRowsByPercentPresentData
1791  
1792 This protected method invalidates rows that do not have greater than
1793 the requested percentage of present data.
1794  
1795 Usage :
1796  
1797 $self->_filterRowsByPercentPresentData($percent, $lineEnding, $numRowsToReport);
1798  
1799 =head2 _filterColumnsByPercentPresentData
1800  
1801 This protected method invalidates columns that do not have greater
1802 than the requested percentage of present data.
1803  
1804 Usage :
1805  
1806 $self->_filterColumnsByPercentPresentData($percent, $lineEnding, $numColumnsToReport);
1807  
1808 =head2 _filterRowsOnColumnPercentile
1809  
1810 NB: THIS METHOD HAS NOT YET BEEN IMPLEMENTED FOR BIG DATAMATRICES
1811  
1812 This protected method filters out rows based on their column
1813 percentile, when all data are known to be in memory, and optionally
1814 allows for the percentiles of each datapoint to be displayed in the
1815 output file.
1816  
1817 Usage:
1818  
1819 $self->_filterRowsOnColumnPercentile($lineEnding, $numColumnsToReport, $percentile, $numColumns, $showPercentile);
1820  
1821 =head2 _filterRowsOnColumnDeviation
1822  
1823 This protected method will filter out rows whose values do not deviate
1824 from the column mean by a specified number of standard deviations, in
1825 at least numColumns columns.
1826  
1827 Usage:
1828  
1829 $self->_filterRowsOnColumnDeviation($lineEnding, $numRowsToReport, $deviations, $numColumns);
1830  
1831 =head2 _filterRowsOnValues
1832  
1833 This protected method filters out rows whose values do not pass a
1834 specified criterion, in at least numColumns columns.
1835  
1836 Usage :
1837  
1838 $self->_filterRowsOnValues($value, $method, $lineEnding, $numRowsToReport, $numColumns);
1839  
1840 =head2 _filterRowsOnVectorLength
1841  
1842 This protected method filters out rows based on whether the vector
1843 that their values define has a length of greater than the specified
1844 length.
1845  
1846 Usage :
1847  
1848 $self->_filterRowsOnVectorLength($requiredLength, $lineEnding, $numRowsToReport);
1849  
1850 =head2 _logTransformData
1851  
1852 This method log transforms the contents of the data matrix, using the
1853 specified base for the log transformation.
1854  
1855 Usage:
1856  
1857 $self->_logTransformData($logBase, $lineEnding, $numRowsToReport);
1858  
1859 =head2 _scaleColumnData
1860  
1861 This protected method scales the data for particular columns as
1862 specified by the client, when all data are in memory.
1863  
1864 Usage :
1865  
1866 $self->_scaleColumnData($columnsToFactorsHashRef, $lineEnding, $numColumnsToReport);
1867  
1868 =head1 public methods
1869  
1870 =head2 dumpData
1871  
1872 This method dumps the current contents of the dataMatrix object to a
1873 file, either whose name was provided as a single argument, or to a
1874 file whose name was used to construct the object.
1875  
1876 Usage:
1877  
1878 $self->dumpData($file);
1879  
1880 =head1 AUTHOR
1881  
1882 Gavin Sherlock
1883  
1884 sherlock@genome.stanford.edu
1885  
1886 =cut