clean
[sgn.git] / lib / Bio / SecreTary / Table.pm
blob15e9617830bd49c230d2c55f640d93005e06f6f8
1 package Bio::SecreTary::Table;
2 use strict;
3 use warnings;
4 use Carp;
5 use Moose;
6 use namespace::autoclean;
8 =head2 function new
10 Synopsis : my $table_obj = Bio::SecreTary::Table->new(
11 label => 'io_center',
12 marked_position => 10, # zero-based here
13 table => [ [ 56.22, 63.83 ],[ 56.55, 56.78 ] ] );
15 =cut
18 has label => (isa => 'Str', is => 'rw', required => 1 );
19 has marked_position => (isa => 'Int', is => 'rw', required => 1 );
20 has table => (isa => 'ArrayRef[ArrayRef[Num]]', is => 'rw', required => 1 );
22 # scale using aa frequency vector
23 # the matrix should have 20 rows.
24 # i.e. it is a ref to an array of 20 array refs.
25 # each column is first normalized to sum to 1, then
27 sub scale {
28 my $self = shift;
29 my $v = shift;
30 my $m = $self->table();
31 ( scalar @$m == scalar @$v )
32 || croak( "in Table::scale, sizes of m, v dont match:", scalar @$m, " ", scalar @$v, "\n" );
34 my $ncols = scalar @{$m->[0]};
35 my @sums = ( (0) x $ncols );
37 foreach my $row (@$m) { # get the sums of each col; $row is an array ref
38 for ( my $jcol = 0 ; $jcol < scalar @$row ; $jcol++ ) {
39 $sums[$jcol] += $row->[$jcol];
42 foreach my $row (@$m) { # do something about elements which are zero
43 for ( my $jcol = 0 ; $jcol < scalar @$row ; $jcol++ ) {
44 my $element = $row->[$jcol];
45 if ( $element == 0 ) {
46 $row->[$jcol] = 1 / $sums[$jcol]
47 ; # slavish imitation of pascal code - probably should be changed.
48 # $sums[$jcol] += $row->[$jcol]; # so sum reflects changed val of element
52 my $irow = 0;
53 foreach my $row (@$m) { #
54 for ( my $jcol = 0 ; $jcol < scalar @$row ; $jcol++ ) {
55 my $element = $row->[$jcol]/$sums[$jcol]; # normalize col sum to 1.
56 $row->[$jcol] = log( $element / $v->[$irow] );
58 $irow++;
60 return $m;
63 sub add_row{
64 my $self = shift;
65 my $new_row = shift; # array ref
66 my $rows = $self->table(); # ref to array of array refs
67 push @$rows, $new_row;
68 return $self->table($rows);
70 sub table_as_string {
71 my $self = shift;
72 my $string = $self->label() . "\n";
73 $string .= $self->marked_position . "\n";
74 my $m = $self->table();
75 foreach (@$m) {
76 $string .= join( ', ', @$_ ) . "\n";
78 return $string;
81 __PACKAGE__->meta->make_immutable;