Debian Codegraph @

TFBS/Matrix.pm

raw symbols SCIP
1 # TFBS module for TFBS::Matrix
2 #
3 # Copyright Boris Lenhard
4 #
5 # You may distribute this module under the same terms as perl itself
6 #
7
8 # POD
9
10 =head1 NAME
11
12 TFBS::Matrix - base class for matrix patterns, containing methods common
13 to all
14
15 =head1 DESCRIPTION
16
17 TFBS::Matrix is a base class consisting of universal constructor called by
18 its subclasses (TFBS::Matrix::*), and matrix manipulation methods that are
19 independent of the matrix type. It is not meant to be instantiated itself.
20
21 =head1 FEEDBACK
22
23 Please send bug reports and other comments to the author.
24
25 =head1 AUTHOR - Boris Lenhard
26
27 Boris Lenhard E<lt>[email protected]<gt>
28 Modified by Eivind Valen [email protected]
29
30 =head1 APPENDIX
31
32 The rest of the documentation details each of the object
33 methods. Internal methods are preceded with an underscore.
34
35 =cut
36
37
38
39 # The code begins HERE:
40
41 package TFBS::Matrix;
42 use vars '@ISA';
43
44 use PDL; # this dependency has to be eliminated in the future versions
45 use TFBS::PatternI;
46
47 use strict;
48
49 @ISA = qw(TFBS::PatternI);
50
51 # IUPAC codes
52 my %dna = ("A" => [12,0,0,0],
53 "C" => [0,12,0,0],
54 "G" => [0,0,12,0],
55 "T" => [0,0,0,12],
56 "U" => [0,0,0,12],
57 "R" => [6,0,6,0],
58 "Y" => [0,6,0,6],
59 "M" => [6,6,0,0],
60 "K" => [0,0,6,6],
61 "W" => [6,0,0,6],
62 "S" => [0,6,6,0],
63 "B" => [0,4,4,4],
64 "D" => [4,0,4,4],
65 "H" => [4,4,0,4],
66 "V" => [4,4,4,0],
67 "N" => [3,3,3,3]);
68
69 sub new {
70 my $class = shift;
71 my %args = @_;
72 my $self = bless {}, ref($class) || $class;
73
74 # first figure out how it was called
75 # we need (-dbh and (-ID or -name) for fetching it from a database
76 # or -matrix for direct matrix input
77
78 if (defined $args{'-matrix'}) {
79 $self->set_matrix($args{'-matrix'});
80 }
81 elsif (defined $args{'-matrixstring'}) {
82 $self->set_matrix($args{'-matrixstring'});
83 }
84 elsif (defined $args{-matrixfile}) {
85 my $matrixstring;
86 open (FILE, $args{-matrixfile})
87 or $self->throw("Could not open $args{-matrixfile}");
88 {
89 local $/ = undef;
90 $matrixstring = <FILE>;
91 }
92 $self->set_matrix($matrixstring);
93 }
94 else {
95 $self->throw("No matrix or db object provided.");
96 }
97
98 # Set the object data.
99 # Parameters specified in constructor call override those
100 # fetched from the database.
101
102 $self->{'ID'} = ($args{-ID} or
103 $self->{ID} or
104 "Unknown");
105 $self->{'name'} = ($args{-name} or
106 $self->{name} or
107 "Unknown");
108 $self->{'class'} = ($args{-class} or
109 $self->{class} or
110 "Unknown");
111 $self->{'strand'} = ($args{-strand} or
112 $self->{strand} or
113 "+");
114 $self->{'bg_probabilities'} =
115 ($args{'-bg_probabilities'} || {A => 0.25,
116 C => 0.25,
117 G => 0.25,
118 T => 0.25});
119
120 $self->{'tags'} = $args{-tags} ? ((ref($args{-tags}) eq "HASH") ? $args{-tags} : {} ) :{};
121
122 return $self;
123 }
124
125
126
127 =head2 matrix
128
129 Title : matrix
130 Usage : my $matrix = $pwm->matrix();
131 $pwm->matrix( [ [12, 3, 0, 0, 4, 0],
132 [ 0, 0, 0,11, 7, 0],
133 [ 0, 9,12, 0, 0, 0],
134 [ 0, 0, 0, 1, 1,12]
135 ]);
136
137 Function: get/set for the matrix data
138 Returns : a reference to 2D array of integers(PFM) or floats (ICM, PWM)
139 Args : none for get;
140 a four line string, reference to 2D array, or a 2D piddle for set
141
142 =cut
143
144
145 sub matrix {
146 my ($self, $matrixdata) = @_;
147 $self->set_matrix($matrixdata) if $matrixdata;
148 return $self->{'matrix'};
149 }
150
151 =head2 pdl_matrix
152
153 Title : pdl_matrix
154 Usage : my $pdl = $pwm->pdl_matrix();
155 Function: access the PDL matrix used to store the actual
156 matrix data directly
157 Returns : a PDL object, aka a piddle
158 Args : none
159
160 =cut
161
162 sub pdl_matrix {
163 pdl $_[0]->{'matrix'};
164 }
165
166 sub set_matrix {
167 my ($self, $matrixdata) = @_;
168
169 # The input matrix (specified as -array=> in the constructir call
170 # can either be
171 # * a 2D regular perl array with 4 rows,
172 # * a piddle (FIXME - check for 4 rows), or
173 # * a four-line string of numbers
174
175 # print STDERR "MATRIX>>>".$matrixdata;
176 if (ref($matrixdata) eq "ARRAY"
177 and ref($matrixdata->[0]) eq "ARRAY"
178 and scalar(@{$matrixdata}) == 4)
179 {
180 # it is a perl array
181 $self->{'matrix'} = $matrixdata;
182 }
183 elsif (ref($matrixdata) eq "PDL")
184 {
185 # it's a piddle
186 $self->{matrix} = _pdl_to_matrixref($matrixdata);
187 }
188 elsif (!ref($matrixdata))
189 #and (scalar split "\n",$matrixdata) == 4)
190 {
191 # it's a string then, but what string?
192 if ($matrixdata =~ /^DE/) {
193 # STAMP string
194 $self->{matrix} = $self->_matrix_from_STAMP_string($matrixdata);
195 } elsif ($matrixdata =~ /[ACGTURYMKWSBDHVNacgturymkwsbdhvn]{3,}/) {
196 $self->{matrix} = $self->_matrix_from_IUPAC_string($matrixdata);
197 } else {
198 # Regular string
199 $self->{matrix} = $self->_matrix_from_string($matrixdata);
200 }
201 }
202 else {
203 $self->throw("Wrong data type/format for -matrix.\n".
204 "Acceptable formats are Array of Arrays (4 rows),\n".
205 "PDL Array, (4 rows),\n".
206 "or plain string (4 lines).");
207 }
208 # $self->_set_min_max_score();
209
210 # print STDERR $self->prettyprint();
211
212 return 1;
213
214 }
215
216 sub _matrix_from_IUPAC_string {
217 my ($self, $matrixstring) = @_;
218 $matrixstring =~ s/^\s+//;
219 $matrixstring =~ s/\s+$//;
220 my @str = split(//, $matrixstring);
221 my @matrix;
222
223 for my $ltr (0..3) {
224 my @l = map {$dna{uc($_)}->[$ltr]} @str;
225 push @matrix, \@l;
226 }
227
228 return \@matrix;
229 }
230
231
232
233 sub _matrix_from_string {
234 my ($self, $matrixstring) = @_;
235 my @array = ();
236 foreach ((split "\n", $matrixstring)[0..3]) {
237 s/^\s+//;
238 s/\s+$//;
239 push @array, [split];
240 }
241 return \@array;
242 }
243
244
245 sub _matrix_from_STAMP_string {
246 my ($self, $matrixstring) = @_;
247 my @lines = split("\n", $matrixstring);
248 my (@a, @c, @g, @t);
249
250 # Remove garbage
251 shift(@lines);
252 pop(@lines);
253
254 for (@lines) {
255 my @l = split;
256 push @a, $l[1];
257 push @c, $l[2];
258 push @g, $l[3];
259 push @t, $l[4];
260 }
261
262 return [\@a, \@c, \@g, \@t];
263 }
264
265 sub _set_min_max_score {
266 my ($self) = @_;
267 my $transpose = $self->pdl_matrix->xchg(0,1);
268 $self->{min_score} = sum(minimum $transpose);
269 $self->{max_score} = sum(maximum $transpose);
270 }
271
272 sub _load {
273 my ($self, $field, $value) = @_;
274 if (substr(ref($self->{db}),0,5) eq "DBI::") {
275 # database retrieval
276 }
277 elsif (-d $self->{dbh}) {
278 # retrieval from .pwm files in a directory
279 $self->_lookup_in_matrixlist($field, $value)
280 or do {
281 warn ("Matrix with $field=>$value not found.");
282 return undef;
283 };
284 my $ID = $self->{ID};
285 my $DIR = $self->{dbh};
286 $self->set_matrix(scalar `cat $DIR/$ID.pwm`); # FIXME - temporary
287
288 }
289 else {
290 $self->throw("-dbh is not a valid database handle or a directory.");
291 }
292 }
293
294
295 =head2 revcom
296
297 Title : revcom
298 Usage : my $revcom_pfm = $pfm->revcom();
299 Function: create a matrix pattern object which is reverse complement
300 of the current one
301 Returns : a TFBS::Matrix::* object of the same type as the one
302 the method acted upon
303 Args : none
304
305 =cut
306
307 sub revcom {
308 my ($self) = @_;
309 my $revcom_matrix =
310 $self->new(-matrix => $self->pdl_matrix->slice('-1:0,-1:0'),
311 # the above line rotates the original matrix 180 deg,
312 -ID => ($self->{ID} or ""),
313 -name => ($self->{name} or ""),
314 -class => ($self->{class} or ""),
315 -strand => ($self->{strand} and $self->{strand} eq "-") ? "+" : "-",
316 -tags => ($self->{tags} or {}) );
317 return $revcom_matrix;
318 }
319
320
321 =head2 rawprint
322
323 Title : rawprint
324 Usage : my $rawstring = $pfm->rawprint);
325 Function: convert matrix data to a simple tab-separated format
326 Returns : a four-line string of tab-separated integers or floats
327 Args : none
328
329 =cut
330
331 sub rawprint {
332 my $self = shift;
333 my $pwmstring = sprintf ( $self->pdl_matrix );
334 $pwmstring =~ s/\[|\]//g; # lose []
335 $pwmstring =~ s/\n /\n/g; # lose leading spaces
336 my @pwmlines = split("\n", $pwmstring); # f
337 $pwmstring = join ("\n", @pwmlines[2..5])."\n";
338 return $pwmstring;
339 }
340
341
342 =head2 prettyprint
343
344 Title : prettyprint
345 Usage : my $prettystring = $pfm->prettyprint();
346 Function: convert matrix data to a human-readable string format
347 Returns : a four-line string with nucleotides and aligned numbers
348 Args : none
349
350 =cut
351
352 sub prettyprint {
353 my $self = shift;
354 my $pwmstring = sprintf ( $self->pdl_matrix );
355 $pwmstring =~ s/\[|\]//g; # lose []
356 $pwmstring =~ s/\n /\n/g; # lose leading spaces
357 my @pwmlines = split("\n", $pwmstring); #
358 @pwmlines = ("A [$pwmlines[2] ]",
359 "C [$pwmlines[3] ]",
360 "G [$pwmlines[4] ]",
361 "T [$pwmlines[5] ]");
362 $pwmstring = join ("\n", @pwmlines)."\n";
363 return $pwmstring;
364 }
365
366
367 =head2 STAMPprint
368
369 Title : STAMPprint
370 Usage : my $STAMPstring = $pfm->STAMPprint();
371 Function: Convert the matrix to STAMP readable format
372 Returns : A string of the matrix in a TRANSFAC like format for STAMP
373 Args : none
374
375 =cut
376
377 sub STAMPprint {
378 my $self = shift;
379 my $pwmstring = sprintf ( $self->pdl_matrix );
380 $pwmstring =~ s/\[|\]//g; # lose []
381 $pwmstring =~ s/\n\s+/\n/g; # lose leading spaces
382 my @pwmlines = split(/\n+/, $pwmstring);
383 @pwmlines = map { [ split(/\s+/, $_) ] } @pwmlines;
384
385 $pwmstring = "DE ".$self->{'ID'}."\t".$self->{'name'}."\t".$self->{'class'}."\n";
386
387 for my $row (0..$#{ $pwmlines[1] }) {
388 $pwmstring .= sprintf "%02d\t", $row;
389 $pwmstring .= $pwmlines[$_]->[$row]."\t" for (1..$#pwmlines);
390 $pwmstring .= "\n";
391 }
392 $pwmstring .= "XX\n";
393
394 return $pwmstring;
395 }
396
397 =head2 length
398
399 Title : length
400 Usage : my $pattern_length = $pfm->length;
401 Function: gets the pattern length in nucleotides
402 (i.e. number of columns in the matrix)
403 Returns : an integer
404 Args : none
405
406 =cut
407
408 sub length {
409 my $self = shift;
410 return $self->pdl_matrix->getdim(0);
411 }
412
413 sub _pdl_to_matrixref {
414 my ($matrixdata) = @_;
415 unless ($matrixdata->isa("PDL")) {
416 die "A non-PDL object passed to _pdl_to_matrixref";
417 }
418 my @list = list $matrixdata;
419 my @array;
420 my $matrix_width = scalar(@list) / 4;
421 for (0..3) {
422 push @array, [splice(@list, 0, $matrix_width)];
423 }
424 return \@array;
425 }
426
427
428 =head2 randomize_columns
429
430 Title : randomize_columns
431 Usage : $pfm->randomize_columns();
432 Function: Randomizes the columns of a matrix (in place).
433 Returns : Nothing
434 Args : none
435
436 =cut
437
438 sub randomize_columns {
439 my $self = shift;
440 my $matrix = $self->{'matrix'};
441 my $i = 0;
442
443 # Schwartzian Transform to get random permutation
444 map { ( undef, $$matrix[0][$i], $$matrix[1][$i], $$matrix[2][$i], $$matrix[3][$i] ) = @$_; $i++; }
445 sort { $a->[0] <=> $b->[0] }
446 map { [ rand(), $$matrix[0][$_], $$matrix[1][$_], $$matrix[2][$_], $$matrix[3][$_] ] } ( 0 .. ($self->length()-1) );
447 }
448
449
450 sub DESTROY {
451 # nothing
452 }
453
454
455
456 1;
457
458
459
460