lib/Microarray/DataMatrix/AnySizeDataMatrix.pm untested

filter: Statementstmt 0.0% 0 / 189 Branchbran 0.0% 0 / 88 Conditioncond 0.0% 0 / 78 MC/DCmcdc 0.0% 0 / 50 Subroutinesub 0.0% 0 / 30 Podpod 0.0% 0 / 25 totaltotal 0.0% 0 / 460 CC 45 SCAR 34.8
CC
45
Cov
0%
_center
110.0
_filterByPercentPresentData
56.0
_filterRowsOnColumnPercentile
42.0
CRAP 32.5
1 package Microarray::DataMatrix::AnySizeDataMatrix;
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 : 11th June 2002
31  
32 # This package is intended to provide an abstraction layer to a
33 # dataMatrix of anysize, whether or not all of its associated data
34 # will fit into memory. It is an abstract class, and requires that a
35 # concrete subclass be created to take advantage. Such concrete subclasses
36 # may include pclFile, or cdtFile.
37  
38 # The constructor of an inheriting subclass MUST call this class's
39 # _init method immediately after blessing the object's hash, before
40 # any other methods are called on the object.
41  
42 # Upon calling of the _init method, it will be determined whether the
43 # contents of the matrix used for construction will fit into memory or
44 # not, and then as appropriate, inherit from either smallDataMatrix,
45 # or from bigDataMatrix at runtime.
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 # use both big and small DataMatrix - decide at runtime which to
54 # inherit from
55  
56 use Microarray::DataMatrix::SmallDataMatrix;
57 use Microarray::DataMatrix::BigDataMatrix;
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 = 'Microarray::DataMatrix::AnySizeDataMatrix'; # will use to prefix all hash
72 # entries which will prevent
73 # collision with any attributes in
74 # super or sub classes.
75  
76 my $kTmpDir = $PACKAGE.'::__tmpDir'; # hold tmp directory
77  
78 my $kFile = $PACKAGE.'::__file'; # name of the file
79 my $kFh = $PACKAGE.'::__fh'; # file handle
80 my $kFileForReading = $PACKAGE.'::_fileForReading'; # allow superclass to specify a different file
81  
82 # This variable maps the size to the superclass that should be used
83  
84 my %kSizesToClasses = ('BIG' => 'Microarray::DataMatrix::BigDataMatrix',
85 'SMALL' => 'Microarray::DataMatrix::SmallDataMatrix');
86  
87 ########################################################################
88 sub _init{
89 ########################################################################
90 # This method initializes the dataMatrix, such that it will inherit
91 # from the correct superclass, based on its size. The constructor of
92 # any concrete subclasses of anySizeDataMatrix MUST call this method
93 # in their constructors, immediately after blessing the object reference.
94 #
95 # A single argument, a directory that can be used to write tmp files if
96 # necessary, must be provided.
97 #
98 # usage : $self->_init($tmpDir), or $self->SUPER::_init($tmpDir);
99  
100 my ($self, $tmpDir) = @_;
101  
102 $self->__setTmpDir($tmpDir);
103  
104 # decide who we inherit from, based on size of matrix
105
106 @ISA = ($kSizesToClasses{$self->__size});
107  
108 # print "ISA :".$self->__size."::".$kSizesToClasses{$self->__size}."\n";
109  
110 # then call superclass's _init method, which will 'do the right thing'
111
112 $self->SUPER::_init();
113  
114 }
115  
116 ######################################################################
117 sub __size{
118 ######################################################################
119 # This private method is used to either find out if the size of the
120 # dataMatrix, e.g. "SMALL" or "BIG". It is only used within this
121 # class (ie private), and is only called once, from the _init method.
122 #
123 # Usage : if ($self->__size eq "SMALL"){
124 #
125 # # blah
126 #
127 # }
128 #
129  
130 my ($self) = @_;
131
132 # here we work out how many entries will be in the matrix. First
133 # find out how much memory this user is allowed per process, then
134 # combine this with an estimate of space required per matrix
135 # entry. Then decide whether it will all fit in memory.
136
137 my $numColumns = $self->_numDataColumns;
138 my $numRows = $self->_numDataRows;
139  
140 print "column: $numColumns rows: $numRows\n";
141
142 my $numMatrixEntries = $numColumns * $numRows;
143
144 my $limit = `/usr/bin/ulimit -d`; # find out how much memory is allowed
145
146 chomp $limit;
147
148 if ($limit eq "unlimited"){ # it's unlimited, but let's impose a max
149
150 $limit = 200000;
151
152 }
153  
154 # limit is in kilobytes, so convert to bytes, as our estimates are in bytes
155  
156 $limit *= 1000;
157
158 my $memEstPerDatum = 10; # probably an overestimate of 25 bytes per matrix entry
159 my $memMetaEstPerRow = 200; # estimate of memory for meta information per row
160 my $fudgeFactor = 7.5; # assume it takes seven times as much memory....
161  
162 my $requiredMem = ($numMatrixEntries * $memEstPerDatum) + ($numRows * $memMetaEstPerRow);
163
164 if ($requiredMem * $fudgeFactor > $limit){ # won't fit in memory
165  
166 return ("BIG");
167
168 }else{
169  
170 return ("SMALL");
171
172 }
173
174 }
175  
176 ####################################################################
177 sub __setTmpDir{
178 ####################################################################
179 # This private method is used to set the tmp directory where any tmp
180 # files may be written.
181 #
182 # Usage:
183 #
184 # $self->__setTmpDir($tmpDir);
185
186 my ($self, $tmpDir) = @_;
187  
188 if (!-e $tmpDir){
189  
190 die "The tmp directory that was supplied, $tmpDir, does not exist.\n";
191  
192 }elsif (!-d $tmpDir){
193  
194 die "The tmp directory that was supplied, $tmpDir, is not a directory.\n";
195  
196 }elsif (!-w $tmpDir){
197  
198 die "The tmp directory that was supplied, $tmpDir, is not writable.\n";
199  
200 }
201  
202 $self->{$kTmpDir} = $tmpDir;
203  
204 }
205  
206 ####################################################################
207 sub _tmpDir{
208 ####################################################################
209 # This protected method returns the tmp directory that was set during
210 # initialization.
211 #
212  
213 return $_[0]->{$kTmpDir};
214  
215 }
216  
217 #
218 # ** Methods for dealing with the file that is being used
219 # ** to hold the dataMatrix.
220 #
221  
222 ############################################################
223 sub _setFile{
224 ############################################################
225 # This protected method simply takes a fully qualified filename
226 # as an argument, checks if it exists, and if so enters it
227 # into the object's hash. If not, it will die with a usage
228 # message.
229 #
230 # Usage : $self->_setFile($file);
231  
232 my ($self, $file) = @_;
233  
234 if (-e $file){
235  
236 $self->{$kFile} = $file;
237  
238 }else{
239  
240 $self->_usage("$file does not exist");
241  
242 }
243  
244 }
245  
246 ######################################################################
247 sub file{
248 ######################################################################
249 # This method returns the fully qualified name of the file that was used
250 # to instantiate the object
251 #
252 # Usage : my $file = $matrix->file;
253 #
254  
255 return $_[0]->{$kFile};
256  
257 }
258  
259 ######################################################################
260 sub _setFileForReading{
261 ######################################################################
262 # This method allows setting of the file that should be read, eg as a
263 # superclass may use temporary files on disk, that it needs this class
264 # to read from instead
265  
266 my ($self, $fileName) = @_;
267  
268 $self->{$kFileForReading} = $fileName; # record the new file
269 $self->_fileHandle(reset=>1); # reset the file handle
270  
271 return $_[0]->{$kFileForReading};
272  
273 }
274  
275 ######################################################################
276 sub _fileForReading{
277 ######################################################################
278 # This method returns the name of the file that is currently meant to
279 # be read.
280  
281 return $_[0]->{$kFileForReading};
282  
283 }
284  
285 ######################################################################
286 sub _fileHandle{
287 ######################################################################
288 # This method returns a file handle on the dataMatrix file that was
289 # used to instantiate the object, or on a file that it has been told
290 # is for reading. This second reason is so that the base class can
291 # communicate with the subclass, to indicate that a new tmp file
292 # exists that should be used as the data source. If it receives a
293 # true value for the 'reset' argument, it will close any open file
294 # handle, then reopen a handle on the file. In doing so, it shall
295 # reset the current file data row to a value of -1.
296  
297 my ($self, %args) = @_;
298  
299 if ($args{'reset'} && exists $self->{$kFh}){ # want to start from beginning
300  
301 close $self->{$kFh}; # close an existent file handle
302  
303 delete $self->{$kFh}; # get rid of the defunct handle
304  
305 }
306  
307 if (!exists $self->{$kFh}){ # open a handle if we need to
308  
309 local *FH;
310
311 my $file = $self->_fileForReading || $self->file;
312  
313 open(FH, $file) || die "Couldn't open $file : $!\n"; # need an error handling strategy here
314
315 $self->{$kFh} = *FH;
316  
317 $self->_setFileHandleToStart; # tell subclass that file handle is at beginning
318  
319 }
320  
321 return $self->{$kFh};
322  
323 }
324  
325  
326 #
327 # ** METHODS THAT MUST BE OVERIDDEN BY CONCRETE SUBCLASSES
328 #
329  
330 ####################################################################
331 sub _numDataRows{
332 ####################################################################
333  
334 $_[0]->_giveOverrideMessage();
335  
336 }
337  
338 ####################################################################
339 sub _numDataColumns{
340 ####################################################################
341  
342 $_[0]->_giveOverrideMessage();
343  
344 }
345  
346 ####################################################################
347 sub _dataLine{
348 ####################################################################
349  
350 $_[0]->_giveOverrideMessage();
351  
352 }
353  
354 ####################################################################
355 sub _printLeadingMeta{
356 ####################################################################
357  
358 $_[0]->_giveOverrideMessage();
359  
360 }
361
362 ####################################################################
363 sub _printRow{
364 ####################################################################
365  
366 $_[0]->_giveOverrideMessage();
367  
368 }
369  
370 ####################################################################
371 sub _printTrailingMeta{
372 ####################################################################
373  
374 $_[0]->_giveOverrideMessage();
375  
376 }
377  
378  
379 #
380 # ** DATA TRANSFORMATION METHODS
381 #
382  
383 ####################################################################
384 sub AUTOLOAD{
385 ####################################################################
386 # The AUTOLOAD method is called by perl if a method canot be resolved.
387 # It will be used for all public data transformation methods, so that
388 # they can all be easily be wrapped in an eval, and report errors
389 # appropriately. The public interface will define the method as being
390 # called one thing, but it will be implemented in the object with a
391 # leading underscore on the name. It will thus be caught by AUTOLOAD,
392 # before being dispatched inside an eval clause.
393  
394 # All the actual data transformation methods are implemented in the
395 # superclass that is specific to a particular size of dataMatrix. The
396 # internal dispatching is dealt with by methods within this class
397 # (which have common elements, irrespective of the size of matrix),
398 # but the actual specifics are dealt with in the superclass. If the
399 # superclass method is named the same as the generic method in this
400 # class, it is called using the $self->SUPER::method() syntax.
401  
402 my ($self, %args) = @_;
403  
404 # my $caller = (caller(1))[3];
405 #
406 # print "Called by : $caller (calling $AUTOLOAD)\n";
407 #
408 # foreach my $key (keys %args){
409 #
410 # print $key, "=> '", $args{$key}, "'\n";
411 #
412 # }
413  
414 if ($AUTOLOAD =~ /.*::(\w+)/){ # get method name
415  
416 my $method = "_".$1;
417  
418 # check to see if method is allowed
419  
420 if ($self->can($method)){
421  
422 # check to see if any errors occurred during method running
423  
424 eval {
425  
426 $self->$method(%args);
427  
428 };
429  
430 if ($@){
431  
432 $self->_setErrstr($@); # store the error message
433
434 print STDERR "$@\n";
435  
436 return 0; # 0 means failure
437
438 }else{
439  
440 if ($self->_autoDump){
441  
442 print "Dumping data.\n";
443  
444 $self->dumpData($args{'file'});
445  
446 }
447  
448 return 1; # 1 means success
449
450 }
451  
452 }
453  
454 }
455  
456 # if we get here, they called a method that wasn't allowed
457  
458 die "No such method: $AUTOLOAD";
459  
460 }
461  
462 # The following methods are public, but called via the autoloading
463 # mechanism, without the leading underscore :
464 #
465 # _center, _filterByPercentPresentData, _filterRowsOnColumnPercentile,
466 # _filterRowsOnColumnDeviation, _filterRowsOnValues, _filterRowsOnVectorLength
467 # _logTransformData, _scaleColumnData
468  
469  
470 ######################################################################
471 sub _center{
472 ######################################################################
473  
474 # This method allows either rows or columns of the dataMatrix to be
475 # centered using either means or medians. If centering both rows and
476 # columns, centering will be done iteratively, until no datapoint
477 # changes by more than 0.01. Alternatively, the maxNumIterations can
478 # be specified, or the maxAllowableChange can be specified. If used
479 # in combination, the first one that is met will terminate centering.
480 # The defaults are:
481  
482 # maxAllowableChange 0.01
483 # maxNumIterations 10
484 #
485 # Usage: eg:
486 #
487 # $dataMatrix->center(rows=>'mean',
488 # columns=>'median');
489 #
490  
491
492 my ($self, %args) = @_;
493  
494 my $maxAllowableChange = $args{'maxAllowableChange'} || 0.01;
495 my $maxNumIterations = $args{'maxNumIterations'} || 10;
496  
497 my $centerRowsMethod = $args{'rows'};
498 my $centerColumnsMethod = $args{'columns'};
499  
500 my $message = ""; # to hold any error message
501  
502 if (defined($centerRowsMethod) && !($self->_centeringMethodIsAllowed($centerRowsMethod))){
503  
504 $message .= "\"$centerRowsMethod\" is not a recognized method for centering rows.\n";
505  
506 }elsif (defined $centerColumnsMethod && !$self->_centeringMethodIsAllowed($centerColumnsMethod)){
507  
508 $message .= "\"$centerColumnsMethod\" is not a recognized method for centering columns.\n";
509  
510 }
511  
512 $message && die $message;
513  
514 my $lineEnding = $self->_lineEnding($args{'verbose'}) if (exists $args{'verbose'});
515 my $numColumnsToReport = $self->_numColumnsToReport;
516 my $numRowsToReport = $self->_numRowsToReport;
517
518 if ($centerRowsMethod && $centerColumnsMethod){
519
520 my $iteration = 1;
521
522 while (1){
523
524 if (defined $lineEnding && $maxNumIterations > 1){
525
526 print "Iteration ", $iteration, $lineEnding;
527
528 }
529
530 my $maxChange = $self->_centerColumns($centerColumnsMethod, $lineEnding, $numColumnsToReport);
531 $self->_centerRows($centerRowsMethod, $lineEnding, $numRowsToReport);
532
533 $iteration++;
534
535 last if $iteration >= $maxNumIterations;
536 last if $maxChange < $maxAllowableChange;
537  
538 }
539  
540 }elsif ($centerRowsMethod){
541  
542 $self->_centerRows($centerRowsMethod, $lineEnding, $numRowsToReport);
543  
544 }elsif ($centerColumnsMethod){
545  
546 $self->_centerColumns($centerColumnsMethod, $lineEnding, $numColumnsToReport);
547  
548 }
549  
550 }
551  
552
553 ######################################################################
554 sub _filterByPercentPresentData{
555 ######################################################################
556 # This method allows for filtering out of rows or columns which do not
557 # have greater than the specified percentage of data available. Note,
558 # if filtering by both rows and columns, filtering will be done
559 # sequentially, firstly by rows. To overide this, make two seperate
560 # calls to the method, in the opposite order. There is no fancy
561 # algorithm to maximize the amount of retained data (eg consider
562 # filter by rows, then by columns, that removal of a column means that
563 # some rows thrown out in the first step may have greater than 80%
564 # good data for the remaining columns - this method does not consider
565 # this).
566 #
567 # $dataMatrix->filterByPercentPresentData(rows=>80,
568 # columns=>80);
569 #
570 # $dataMatrix->filterByPercentPresentData(rows=>90,
571 # filename=>$filename);
572  
573 my ($self, %args) = @_;
574
575 my $lineEnding = $self->_lineEnding($args{'verbose'}) if (exists $args{'verbose'});
576
577 if (!exists($args{'rows'}) && !exists($args{'columns'})){
578
579 die "filterByPercentPresentData requires you to specify either rows or columns to be filtered.\n";
580
581 }
582
583 if (exists($args{'rows'})){
584
585 if ($args{'rows'} >= 100 || $args{'rows'} < 0){
586
587 die "You must specify percent present data greater than or equal to 0 and less than 100.\n";
588
589 }
590
591 defined $lineEnding && print ("Filtering out rows with less than $args{'rows'}\% present data", $lineEnding);
592
593 $self->_filterRowsByPercentPresentData($args{'rows'}, $lineEnding, $self->_numRowsToReport);
594
595 }
596
597 if (exists($args{'columns'})){
598
599 if ($args{'columns'} >= 100 || $args{'columns'} < 0){
600
601 die "You must specify percent present data greater than or equal to 0 and less than 100.\n";
602
603 }
604
605 defined $lineEnding && print ("Filtering out columns with less than $args{'columns'}\% present data", $lineEnding);
606  
607 $self->_filterColumnsByPercentPresentData($args{'columns'}, $lineEnding, $self->_numColumnsToReport);
608  
609 }
610
611 }
612  
613 ######################################################################
614 sub _filterRowsOnColumnPercentile{
615 ######################################################################
616 # This method will filter out rows whose values do not have a
617 # percentile rank for their particular column above a specified
618 # percentile rank, in at least numColumns columns. Note it only
619 # considers rows and columns that have not been filtered out by ant
620 # previous method calls.
621 #
622 # Usage:
623 #
624 # $dataMatrix->filterRowsOnColumnPercentile(percentile=>95,
625 # numColumns=>1);
626  
627 # To actually do this, we need to look at each column of data, sort
628 # it, while tracking the row to value mapping, and see which of the
629 # rows are above the requested percentile, and keep a count of them.
630 # The method use here simply for each column in turn creates a hash of
631 # row number to value (for those that have values - it does not
632 # consider the empty ones). It then sorts those keys by their values,
633 # and puts the keys in that order into an array. It then looks at
634 # those array elements that correspond to the required percentile, and
635 # keeps a count of the rows in that percentile. After doing this for
636 # all columns, it filters out rows that don't have a high enough
637 # count.
638  
639 my ($self, %args) = @_;
640  
641 if (!exists($args{'percentile'})){
642  
643 die "You must specify a percentile argument for filterRowsOnColumnPercentile.\n";
644  
645 }
646  
647 if (!exists($args{'numColumns'})){
648  
649 die "You must specify a numColumns argument for filterRowsOnColumnPercentile.\n";
650  
651 }
652  
653 if ($args{'percentile'} <= 0 || $args{'percentile'} >= 100){
654  
655 die "You must specify the percentile argument as greater than 0 and less than 100.\n";
656  
657 }
658  
659 if ($args{'numColumns'} <= 0){
660  
661 die "You cannot specify the numColumns argument as less than or equal to zero.\n";
662  
663 }
664  
665 my $lineEnding = $self->_lineEnding($args{'verbose'}) if (exists $args{'verbose'});
666 my $numColumnsToReport = $self->_numColumnsToReport;
667 my $showPercentile = $args{'showPercentile'} || 0;
668  
669 defined $lineEnding && print ("Filtering rows by column percentile rank", $lineEnding);
670  
671 $self->SUPER::_filterRowsOnColumnPercentile($lineEnding, $numColumnsToReport, $args{'percentile'}, $args{'numColumns'}, $showPercentile);
672  
673 }
674  
675 ######################################################################
676 sub _filterRowsOnColumnDeviation{
677 ######################################################################
678 # This method will filter out rows whose values do not deviate from
679 # the column mean by a specified number of standard deviations, in at
680 # least numColumns columns.
681 #
682 # Usage:
683 #
684 # $dataMatrix->filterRowsOnColumnDeviation(deviations=>2,
685 # numColumns=>1);
686  
687 my ($self, %args) = @_;
688  
689 if (!exists($args{'deviations'}) || $args{'deviations'} <= 0){
690  
691 die "You must supply a deviations argument with a value greater than zero.\n";
692  
693 }
694  
695 if (!exists($args{'numColumns'}) || $args{'numColumns'} < 1){
696  
697 die "You must supply a numColumns argument with a value greater than or equal to 1.\n";
698  
699 }
700  
701 my $lineEnding = $self->_lineEnding($args{'verbose'}) if (exists $args{'verbose'});
702 my $numRowsToReport = $self->_numRowsToReport;
703 my $deviations = $args{'deviations'};
704 my $numColumns = $args{'numColumns'};
705  
706 $self->SUPER::_filterRowsOnColumnDeviation($lineEnding, $numRowsToReport, $deviations, $numColumns);
707  
708 }
709  
710 ######################################################################
711 sub _filterRowsOnValues{
712 ######################################################################
713 # This method filters out rows whose values do not pass a specified
714 # criterion, in at least numColumns columns. To specify the criterion, a
715 # value, and an operator must be specified. The valid operators are:
716 #
717 # "absolute value >" also aliased by "absgt" and "|>|"
718 # "absolute value >=" also aliased by "absgteq" and "|>=|"
719 # "absolute value =" also aliased by "abseq" and "|=|"
720 # "absolute value <" also aliased by "abslt" and "|<|"
721 # "absolute value <=" also aliased by "abslteq" and "|<=|"
722 # ">" also aliased by "gt"
723 # ">=" also aliased by "gteq"
724 # "=" also aliased by "eq" and "=="
725 # "<=" also aliased by "lteq"
726 # "<" also aliased by "lt"
727 # "not equal" also aliased by "ne" and "!="
728 #
729 # Usage:
730 #
731 # $dataMatrix->filterRowsOnValues(operator=>"absolute value >",
732 # value=>2,
733 # numColumns=>1);
734  
735 my ($self, %args) = @_;
736  
737 if (!exists ($args{'operator'}) || !defined ($args{'operator'})){
738  
739 die "You must supply an operator argument for the filterRowsOnValues method.".
740
741 "Available operators are: ".join("\n", $self->allowedOperators)."\n";
742  
743 }elsif (!$self->_operatorIsAllowed($args{'operator'})){
744  
745 die "The operator argument you supplied for the filterRowsOnValues method is not allowed.".
746  
747 "Available methods are: ".join("\n", $self->allowedOperators)."\n";
748  
749 }
750  
751 if (!exists($args{'value'}) || !defined($args{'value'})){
752  
753 die "You must supply a value to the filterRowsOnValues method.\n";
754  
755 }
756  
757 my $value = $args{'value'};
758  
759 my $method = $self->_methodForOperator($args{'operator'});
760  
761 my $lineEnding = $self->_lineEnding($args{'verbose'}) if (exists $args{'verbose'});
762  
763 my $numColumns = $args{'numColumns'};
764  
765 defined $lineEnding && print ("Filtering rows based on $args{'operator'} $value in $args{'numColumns'} columns", $lineEnding);
766
767 $self->SUPER::_filterRowsOnValues($value, $method, $lineEnding, $self->_numRowsToReport, $numColumns);
768  
769 }
770  
771 ######################################################################
772 sub _filterRowsOnVectorLength{
773 ######################################################################
774 # This method filters out rows based on whether the vector that their
775 # values define has a length of greater than the specified length.
776 #
777 # Usage:
778 #
779 # $dataMatrix->filterRowsOnVectorLength(length=>2);
780  
781 my ($self, %args) = @_;
782
783 if (!exists($args{'length'}) || $args{'length'} <= 0){
784
785 die "You must provide a length argument with a positive value to filterRowsOnVectorLength\n";
786
787 }
788
789 my $requiredLength = $args{'length'};
790  
791 my $lineEnding = $self->_lineEnding($args{'verbose'}) if (exists $args{'verbose'});
792 my $numRowsToReport = $self->_numRowsToReport;
793  
794 defined $lineEnding && print ("Filtering out rows whose vector length is not greater than $args{'length'}", $lineEnding);
795
796 $self->SUPER::_filterRowsOnVectorLength($requiredLength, $lineEnding, $numRowsToReport);
797  
798 }
799  
800 ######################################################################
801 sub _logTransformData{
802 ######################################################################
803 # This method log transforms the contents of the data matrix, using
804 # the specified base. If any values less than or equal to zero are
805 # encountered, then the transformation will fail. The matrix will be
806 # returned to its state prior to log transformation
807  
808 # Usage :
809 #
810 # $dataMatrix->logTransformData(base=>2);
811  
812 my ($self, %args) = @_;
813  
814 my $base = $args{'base'};
815  
816 die "You must provide a 'base' argument whose value is greater than zero.\n" if ($base <= 0);
817  
818 my $logBase = log($base);
819  
820 my $lineEnding = $self->_lineEnding($args{'verbose'}) if (exists $args{'verbose'});
821 my $numRowsToReport = $self->_numRowsToReport;
822  
823 defined $lineEnding && print ("Log transforming data in base $base.", $lineEnding);
824  
825 $self->SUPER::_logTransformData($logBase, $lineEnding, $numRowsToReport);
826  
827 }
828  
829 ######################################################################
830 sub _scaleColumnData{
831 ######################################################################
832 # This method scales the data for particular columns as specified by
833 # the client, by dividing the values by specified factors. It could,
834 # for instance, be used to renormalize the data (only if the data are
835 # in ratio form).
836 #
837 # The client passes in a hash, by reference, of the column number
838 # (starting from zero) as the key, and the scaling factor as the
839 # value.
840 #
841 # Usage:
842 #
843 # $datamatrix->scaleColumnData(columns=>{0=>1.2,
844 # 2=>0.8});
845 #
846 #
847 # If a column number which is invalid is specified, then a warning to
848 # STDERR will be printed. Also, if a scaling factor of zero (or
849 # undef) is supplied for a column, a warning will be printed, and the
850 # zero will not be used.
851  
852 my ($self, %args) = @_;
853  
854 my $columnsToFactorsHashRef = $args{'columns'} || die "You must supply a columns argument to scaleColumnData.\n";
855  
856 my $lineEnding = $self->_lineEnding($args{'verbose'}) if (exists $args{'verbose'});
857 my $numColumnsToReport = $self->_numColumnsToReport;
858  
859 defined $lineEnding && print ("Scaling column data.", $lineEnding);
860  
861 $self->SUPER::_scaleColumnData($columnsToFactorsHashRef, $lineEnding, $numColumnsToReport);
862  
863 }
864  
865 sub DESTROY{
866  
867 }
868  
869 1; # to keep Perl happy
870  
871  
872 =pod
873  
874 =head1 NAME
875  
876 Microarray::DataMatrix::AnySizeDataMatrix - abstraction to DataMatrix
877  
878 =head1 Abstract
879  
880 anySizeDataMatrix.pm provides an abstraction layer to a dataMatrix, in
881 that it provides methods for manipulating or querying the contents of
882 a dataMatrix. anySizeDataMatrix is an abstract class - thus
883 anySizeDataMatrix objects themselves cannot be instantiated - only
884 objects of concrete subclasses can be instantiated.
885  
886 =head1 Overall Logic
887  
888 This is for programmers only - do not rely on any of these details
889 when programming clients of the concrete subclasses of
890 anySizeDataMatrix, or programming the subclasses themselves, as the
891 underlying implementation is subject to change at any time without
892 notice. Just stick to using the API! (described below).
893  
894 Implementation of an anySizeDataMatrix depends on its size. Upon
895 construction of concrete subclass, anySizeDatamatrix will determine if
896 the matrix is too big to fit into memory. It then dynamically
897 inherits from either smallDataMatrix, or bigDataMatrix. In the case
898 that anySizeDataMatrix decides to inherit from smallDataMatrix, then
899 all data are read into memory, and the actual data matrix from the
900 file (used to instantiate the concrete subclass) is stored as a 2
901 dimensional array. The indexes of the array which are still valid
902 (following some filtering step) are stored in internal hashes, such
903 that subsequent manipulations of the data only consider the data that
904 have not been filtered out. As rows or columns are filtered out by
905 some of the methods, the entries for these rows or columns are deleted
906 from the hashes that track valid data. Thus when data are redumped to
907 a file, only those data that have not been filtered are printed out.
908  
909 When anySizeDatamatrix instead inherits from bigDataMatrix, because a
910 matrix is too large to be read into memory, then all operations are
911 carried out on disk versions of the matrix. This is obviously less
912 efficient, as it often requires the file to be read multiple times,
913 and intermediate results to be stored in tmp files.
914  
915 Whether the matrix fits into memory or not, all reading and writing of
916 files is carried out by methods that have to be implemented in the
917 concrete subclass, though the matrix class itself (small or big)
918 actually deals with calling them appropriately in its own methods.
919  
920 For all the data transformation / filtering methods, the methods are
921 actually autoloaded in anySizeDatamatrix, then redispatched to
922 protected versions of the method, and then again dispatched to
923 protected methods within small and bigDataMatrix. This is done so
924 that thay can all be wrapped by a generic eval clause, which only
925 needs to appear once in the AUTOLOAD method.
926  
927 Construction of objects is up to the client subclasses to implement,
928 as anySizeDatamatrix has no new() method. Upon object construction, a
929 concrete subclass must call the _init method of anySizeDatamatrix,
930 giving it the name of the tmp directory that can be used for storage
931 of any temp files. _init is defined thus:
932  
933 =head2 _init
934  
935 This method initializes the dataMatrix, such that it will inherit from
936 the correct superclass, based on its size. The constructor of any
937 concrete subclasses of anySizeDataMatrix MUST call this method in
938 their constructors, after blessing the object reference, but before
939 returning it to the client. The _init method will call the
940 _numDataRows and _numDataColumns methods that the subclass must
941 implement (see below) during initialization. Thus the concrete
942 subclass must take care of any of its own initialization that will be
943 required for these to work correctly, prior to calling the
944 anySizeDataMatrixs _init() method.
945  
946 A single argument, a directory that can be used to write tmp files if
947 necessary, must be provided to _init.
948  
949 Usage :
950  
951 $self->_init($tmpDir)
952  
953 or
954  
955 $self->SUPER::_init($tmpDir);
956  
957  
958 =head1 Methods that must be implemented by concrete subclasses.
959  
960 =head2 _numDataRows
961  
962 This method should return the number of rows that can be expected to
963 be read from the file with which the object was instantiated.
964  
965 Usage:
966  
967 my $numRows = $self->_numDataRows;
968  
969 =head2 _numDataColumns
970  
971 This method should return the number of data columns that can be
972 expected from the file with which the object was instantiated.
973  
974 Usage:
975  
976 my $numColumns = $self->_numDataColumns;
977  
978 =head2 _dataLine
979  
980 This method should return the requested row of data from the file
981 whose name is available from the _fileForReading() method. It should
982 return a reference to an array of the data. Null values in the line
983 of data should be dealt with as blanks in the array. A requested row
984 number of zero means the first line of data in the file. If no line
985 of data corresponds to the requested row number, then undef should be
986 returned.
987  
988 Usage:
989  
990 my $dataArrayRef = $self->_dataLine($lineNo);
991  
992 =head2 _printLeadingMeta
993  
994 This method should print the leading meta data from that corresponds
995 to the file from which the object was instantiated.
996  
997 Usage:
998  
999 $self->_printLeadingMeta($fh, $validColumnsArrayRef,
1000 $hasExtraInfo, $extraInfoName);
1001  
1002 where:
1003  
1004 $fh is a file handle to which the information should be printed.
1005  
1006 $validColumnsArrayRef is a reference to an array of column numbers of
1007 the columns that are still valid in the dataMatrix. The column
1008 numbers are with respect to the columns in the original file with
1009 which the object was instantiated.
1010  
1011 $hasExtraInfo is a boolean to indicate whether extra information
1012 should be interleaved with the data.
1013  
1014 $extraInfoName is the name of the extra information.
1015  
1016 Note these last two are to support the interleaving of percentile data
1017 into a datafile. This will probably be removed, such that a separate
1018 percentiles file, or any other type of extra information file is
1019 created instead. This is currently in here as legacy support.
1020  
1021 =head2 _printRow
1022  
1023 This method prints to the passed in file handle. It will only print
1024 information for those valid columns. If the $extraInfo variable is
1025 true (ie a non-zero value) it will print the extra info interleaved
1026 between each column of data. The extra info comes from the 2D hash
1027 whose reference is passed in. The relevant piece of extra information
1028 is accessed by the row as the key of the first hash dimension, and the
1029 columns as the key of the second hash dimension.
1030  
1031 Usage :
1032  
1033 $self->_printRow($fh, $row, $dataRef, $validColumnsArrayRef,
1034 $hasExtraInfo, $extraInfoHashRef);
1035  
1036 =head2 _printTrailingMeta
1037  
1038 This method prints out any trailing meta data to the passed in file
1039 handle.
1040  
1041 Usage:
1042  
1043 $self->_printTrailingMeta($fh, $validColumnsArrayRef,
1044 $hasExtraInfo, $extraInfoName);
1045  
1046 =head1 Protected methods that are used by both the superclass and subclasses
1047  
1048 =head2 _setFile
1049  
1050 This protected method simply takes a fully qualified filename as an
1051 argument, checks if it exists, and if so stores it in the object. If
1052 not, it will die with a usage message.
1053  
1054 =head2 _fileForReading
1055  
1056 This method should return the fully qualified name of the file that is
1057 currently holding the data. This may change from the original file
1058 that was used to instantiate the object, as the abstract superclass of
1059 anySizeDatamatrix may use temp files to hold the contents of the
1060 matrix. If the file that the subclass is supposed to be reading data
1061 from is changed, then it is up to the subclass to deal with that
1062 appropriately, ie it should read from the correct file when it needs to.
1063  
1064 Usage:
1065  
1066 my $file = $self->_fileForReading;
1067  
1068 =head2 _setFileForReading
1069  
1070 This method should allow the super class to set the file which
1071 the concrete subclass should be using to get data.
1072  
1073 Usage:
1074  
1075 $self->_setFileForReading($newFile);
1076  
1077 =head2 _fileHandle
1078  
1079 This method returns a file handle on the matrix file that was used to
1080 instantiate the object, or on a file that it has been told is for
1081 reading. This second reason is so that the superclass can communicate
1082 with the subclass, to indicate that a new tmp file exists that should
1083 be used as the data source. If it receives a true value for the
1084 'reset' argument, it will close any open file handle, then reopen a
1085 handle on the file. In doing so, it shall reset the current file data
1086 row to a value of -1.
1087  
1088 Usage:
1089  
1090 my $fh = $self->_fileHandle(reset=>$reset);
1091  
1092 =head1 Public methods implemented in the size independent anySizeDataMatrix
1093  
1094 =head2 file
1095  
1096 This methods returns the name of the file that was used to construct
1097 the object.
1098  
1099 Usage:
1100  
1101 my $file = $matrix->file;
1102  
1103 returns: a scalar
1104  
1105  
1106 =head1 Public methods, implemented in the size dependent super classes of anySizeDataMatrix.
1107  
1108 =head2 dumpData
1109  
1110 This method dumps the current contents of the dataMatrix object to a
1111 file, either whose name was provided as a single argument, or to a
1112 file whose name was used to construct the object. If the data have
1113 been filtered based on columnPercentiles, and these were elected to be
1114 shown, then these will be dumped out too (see below).
1115  
1116 Usage:
1117  
1118 $dataMatrix->dumpData($file);
1119  
1120 or:
1121  
1122 $dataMatrix->dumpData;
1123  
1124 =head2 Tranformation and Filtering Methods
1125  
1126 Developer note : The initial 'front-end' common parts to these methods
1127 are implemented in anySizeDataMatrix, but the full, 'back-end' nuts
1128 and bolts of each method is implemented in the relevant size dependent
1129 super-classes, small- and bigDataMatrix, as the way in which each
1130 deals with filtering is fundamentally different, depending on whether
1131 they are memory constrained or not. This does mean that any new
1132 filtering/transformation methods that are implemented MUST be added to
1133 both small and bigDataMatrix, potentially with some shared common code
1134 being implemented in anySizeDataMatrix.
1135  
1136 General note on methods that transform the data : If autodumping is
1137 on, then by default, they will overwrite the file that was used to
1138 create the object of the concrete subclass, unless a new filename is
1139 passed in. If a new filename is passed in (as an argument named
1140 'file'), and autodumping is on, then further operations on the
1141 dataMatrix of filtered data will operate on the already filtered data.
1142 Note, the program MUST have permissions to overwrite the original
1143 file, if no new filename is provided.
1144  
1145 All of the transformation and filtering methods return 1 upon success.
1146 If an error was encountered, then the method will return 0, and the
1147 error message associated with the problem can be retrieved using the
1148 errstr() method, eg:
1149  
1150 $dataMatrix->methodX(%args) || die "An error occured ".$dataMatrix->errstr."\n";
1151  
1152 All of the transformation and filtering methods allow a verbose
1153 argument to be passed in, with valid values for the verbose argument
1154 being either 'text' or 'html'. For text, \n will be used as an end of
1155 line character after every line of reporting is printed. For html,
1156 \n<br> will be used, eg:
1157  
1158 $dataMatrix->center(rows=>'mean',
1159 verbose=>'html') || die $dataMatrix->errstr;
1160  
1161 =head2 center
1162  
1163 This method allows either rows or columns of the dataMatrix to be
1164 centered using either means or medians (centering is when the average
1165 - mean or median - is set to zero, by subtracting the average from
1166 every value for that row/column). If centering both rows and columns,
1167 centering will be done iteratively, until no datapoint changes by more
1168 than 0.01. Alternatively, the maxNumIterations can be specified, or
1169 the maxAllowableChange can be specified. If used in combination, the
1170 first one that is met will terminate centering. The defaults are:
1171  
1172 maxAllowableChange 0.01
1173 maxNumIterations 10
1174  
1175 Usage: eg:
1176  
1177 $dataMatrix->center(rows=>'mean',
1178 columns=>'median') || die $dataMatrix->errstr;
1179  
1180  
1181 returns : 1 upon success, or 0 otherwise
1182  
1183 =head2 filterByPercentPresentData
1184  
1185 This method allows for filtering out of rows or columns which do not
1186 have greater than the specified percentage of data available. Note,
1187 if filtering by both rows and columns, filtering will be done
1188 sequentially, firstly by rows. To overide this, make two seperate
1189 calls to the method, in the opposite order. There is no fancy
1190 algorithm to maximize the amount of retained data (eg consider filter
1191 by rows, then by columns, that removal of a column means that some
1192 rows thrown out in the first step may have greater than 80% good data
1193 for the remaining columns - this method does not consider this).
1194  
1195 $dataMatrix->filterByPercentPresentData(rows=>80,
1196 columns=>80);
1197  
1198 $dataMatrix->filterByPercentPresentData(rows=>90,
1199 file=>$filename);
1200  
1201 returns: 1 upon success, or 0 otherwise
1202  
1203 =head2 filterRowsOnColumnPercentile
1204  
1205 This method will filter out rows whose values do not have a percentile
1206 rank for their particular column above a specified percentile rank, in
1207 at least numColumns columns. In addition, this method will accept a
1208 'showPercentile' argument, which if set to a non-zero value, will
1209 result in the percentiles of the datapoints being dumped out with the
1210 data, when the data are aubsequently dumped to a file. Columns of
1211 percentiles are interleaved with the data columns, so the resulting
1212 file can not be clustered.
1213  
1214 Note: This method has not yet been implemented for matrices that do
1215 not fit into memory, so calling it on such a matrix will produce an
1216 error (which of course, you are always checking for).
1217  
1218 Usage:
1219  
1220 $dataMatrix->filterRowsOnColumnPercentile(percentile=>95,
1221 numColumns=>1,
1222 showPercentiles=>1);
1223  
1224  
1225 returns : 1 upon success, or 0 otherwise
1226  
1227 =head2 filterRowsOnColumnDeviation
1228  
1229 This method will filter out rows whose values do not deviate from the
1230 column mean by a specified number of standard deviations, in at least
1231 numColumns columns.
1232  
1233 Usage:
1234  
1235 $dataMatrix->filterRowsOnColumnDeviation(deviations=>2,
1236 numColumns=>1);
1237  
1238 returns : 1 upon success, or 0 otherwise
1239  
1240 =head2 filterRowsOnValues
1241  
1242 This method filters out rows whose values do not pass a specified
1243 criterion, in at least numColumns columns. To specify the criterion,
1244 a value, and an operator must be specified. The valid operators are:
1245  
1246 "absolute value >" also aliased by "absgt" and "|>|"
1247 "absolute value >=" also aliased by "absgteq" and "|>=|"
1248 "absolute value =" also aliased by "abseq" and "|=|"
1249 "absolute value <" also aliased by "abslt" and "|<|"
1250 "absolute value <=" also aliased by "abslteq" and "|<=|"
1251 ">" also aliased by "gt"
1252 ">=" also aliased by "gteq"
1253 "=" also aliased by "eq" and "=="
1254 "<=" also aliased by "lteq"
1255 "<" also aliased by "lt"
1256 "not equal" also aliased by "ne" and "!="
1257  
1258  
1259 Usage:
1260  
1261 $dataMatrix->filterRowsOnValues(operator=>"absolute value >",
1262 value=>2,
1263 numColumns=>1);
1264  
1265  
1266 returns : 1 upon success, or 0 otherwise
1267  
1268 =head2 filterRowsOnVectorLength
1269  
1270 This method filters out rows based on whether the vector that their
1271 values define has a length of greater than the specified length.
1272  
1273 Usage:
1274  
1275 $dataMatrix->filterRowsOnVectorLength(length=>2);
1276  
1277 returns : 1 upon success, or 0 otherwise
1278  
1279 =head2 logTransformData
1280  
1281 This method log transforms the contents of the data matrix, using the
1282 specified base. If any values less than or equal to zero are
1283 encountered, then the transformation will fail. The matrix may be
1284 left in an indeterminate state if the operation fails, so the object
1285 should not be used further if the transformation is unsuccessful.
1286  
1287 Usage :
1288  
1289 $dataMatrix->logTransformData(base=>2);
1290  
1291 returns : 1 upon success, or 0 otherwise
1292  
1293 =head2 scaleColumnData
1294  
1295 This method scales the data for particular columns as specified by the
1296 client, by dividing the values by specified factors. It could, for
1297 instance, be used to renormalize the data. Note it is only
1298 appropriate to normalize ratio data, not log transformed data.
1299  
1300 The client passes in a hash, by reference, of the column numbers
1301 (starting from zero) as the keys, and the scaling factors as the
1302 values.
1303  
1304 If a column number which is invalid is specified, then a warning to
1305 STDERR will be printed. Also, if a scaling factor of zero (or undef)
1306 is supplied for a column, a warning will also be printed to STDERR,
1307 and the column data for that column will not be scaled.
1308  
1309 Usage:
1310  
1311 $datamatrix->scaleColumnData(columns=>{0=>1.2,
1312 2=>0.8});
1313  
1314 returns : 1 upon success, or 0 otherwise
1315  
1316 =head1 Accessor Methods
1317  
1318 Developer note : The following methods are actually implemented in the
1319 dataMatrix class, which is a superclass of both small- and
1320 bigDataMatrix.
1321  
1322 =head2 numRows
1323  
1324 This method returns the number of rows that are currently valid in the
1325 data matrix.
1326  
1327 Usage:
1328  
1329 my $numRows = $dataMatrix->numRows;
1330  
1331 returns: a scalar
1332  
1333 =head2 numColumns
1334  
1335 This method returns the number of columns that are currently valid in
1336 the data matrix.
1337  
1338 Usage:
1339  
1340 my $numColumn = $dataMatrix->numColumns;
1341  
1342 returns: a scalar
1343  
1344 =head2 errstr
1345  
1346 This method returns an error string that is associated with the last
1347 failed call to a data transformation/filtering method. Calling this
1348 method will clear the contents of the error string.
1349  
1350 =head1 Setter Methods
1351  
1352 =head2 setNumColumnsToReport
1353  
1354 This method accepts a positive integer, that indicates the number of
1355 columns that have been processed during a filtering/transformation
1356 method that is carried out on a column basis, after which progress
1357 should be indicated. If a client has not set this value, then it
1358 defaults to 50.
1359  
1360 Usage :
1361  
1362 $matrix->setNumColumnsToReport(50);
1363  
1364 =head2 setNumRowsToReport
1365  
1366 This method accepts a positive integer, that indicates the number of
1367 rows that have been processed during a filtering/transformation method
1368 that is carried out on a row basis, after which progress should be
1369 indicated. If a client has not set this value, then it defaults to
1370 5000.
1371  
1372 Usage :
1373  
1374 $matrix->setNumRowsToReport(5000);
1375  
1376 =head2 allowedOperators
1377  
1378 This public method returns an array of all the allowed operators that
1379 may be used by methods (in subclasses) that employ the operators for
1380 whatever reason (their interface should indicate that they employ such
1381 operators).
1382  
1383 Usage :
1384  
1385 my @operators = $matrix->allowedOperators;
1386  
1387 =head1 AUTHOR
1388  
1389 Gavin Sherlock
1390  
1391 sherlock@genome.stanford.edu
1392  
1393 =cut
1394  
1395  
1396