Debian Codegraph @

TFBS/Matrix/PWM.pm

raw symbols SCIP
1 # TFBS module for TFBS::Matrix::PWM
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::PWM - class for position weight matrices of nucleotide
13 patterns
14
15 =head1 SYNOPSIS
16
17 =over 4
18
19 =item * creating a TFBS::Matrix::PWM object manually:
20
21 my $matrixref = [ [ 0.61, -3.16, 1.83, -3.16, 1.21, -0.06],
22 [-0.15, -2.57, -3.16, -3.16, -2.57, -1.83],
23 [-1.57, 1.85, -2.57, -1.34, -1.57, 1.14],
24 [ 0.31, -3.16, -2.57, 1.76, 0.24, -0.83]
25 ];
26 my $pwm = TFBS::Matrix::PWM->new(-matrix => $matrixref,
27 -name => "MyProfile",
28 -ID => "M0001"
29 );
30 # or
31
32 my $matrixstring = <<ENDMATRIX
33 0.61 -3.16 1.83 -3.16 1.21 -0.06
34 -0.15 -2.57 -3.16 -3.16 -2.57 -1.83
35 -1.57 1.85 -2.57 -1.34 -1.57 1.14
36 0.31 -3.16 -2.57 1.76 0.24 -0.83
37 ENDMATRIX
38 ;
39 my $pwm = TFBS::Matrix::PWM->new(-matrixstring => $matrixstring,
40 -name => "MyProfile",
41 -ID => "M0001"
42 );
43
44
45 =item * retrieving a TFBS::Matix::PWM object from a database:
46
47 (See documentation of individual TFBS::DB::* modules to learn
48 how to connect to different types of pattern databases and retrieve
49 TFBS::Matrix::* objects from them.)
50
51 my $db_obj = TFBS::DB::JASPAR2->new
52 (-connect => ["dbi:mysql:JASPAR2:myhost",
53 "myusername", "mypassword"]);
54 my $pwm = $db_obj->get_Matrix_by_ID("M0001", "PWM");
55 # or
56 my $pwm = $db_obj->get_Matrix_by_name("MyProfile", "PWM");
57
58
59 =item * retrieving list of individual TFBS::Matrix::PWM objects
60 from a TFBS::MatrixSet object
61
62 (see decumentation of TFBS::MatrixSet to learn how to create
63 objects for storage and manipulation of multiple matrices)
64
65 my @pwm_list = $matrixset->all_patterns(-sort_by=>"name");
66
67 =item * scanning a nucleotide sequence with a matrix
68
69 my $siteset = $pwm->search_seq(-file =>"myseq.fa",
70 -threshold => "80%");
71
72 =item * scanning a pairwise alignment with a matrix
73
74 my $site_pair_set = $pwm->search_aln(-file =>"myalign.aln",
75 -threshold => "80%",
76 -cutoff => "70%",
77 -window => 50);
78
79
80 =back
81
82 =head1 DESCRIPTION
83
84 TFBS::Matrix::PWM is a class whose instances are objects representing
85 position weight matrices (PWMs). A PWM is normally calculated from a
86 raw position frequency matrix (see L<TFBS::Matrix::PFM>
87 for the explanation of position frequency matrices). For example, given
88 the following position frequency matrix:
89
90 A:[ 12 3 0 0 4 0 ]
91 C:[ 0 0 0 11 7 0 ]
92 G:[ 0 9 12 0 0 0 ]
93 T:[ 0 0 0 1 1 12 ]
94
95 The standard computational procedure is applied to convert it into the
96 following position weight matrix:
97
98 A:[ 0.61 -3.16 1.83 -3.16 1.21 -0.06]
99 C:[-0.15 -2.57 -3.16 -3.16 -2.57 -1.83]
100 G:[-1.57 1.85 -2.57 -1.34 -1.57 1.14]
101 T:[ 0.31 -3.16 -2.57 1.76 0.24 -0.83]
102
103 which contains the "weights" associated with the occurrence of each
104 nucleotide at the given position in a pattern.
105
106 A TFBS::Matrix::PWM object is equipped with methods to search nucleotide
107 sequences and pairwise alignments of nucleotide sequences with the
108 pattern they represent, and return a set of sites in nucleotide
109 sequence (a TFBS::SiteSet object for single sequence search, and a
110 TFBS::SitePairSet for the alignment search).
111
112 =head1 FEEDBACK
113
114 Please send bug reports and other comments to the author.
115
116 =head1 AUTHOR - Boris Lenhard
117
118 Boris Lenhard E<lt>[email protected]<gt>
119
120 =head1 APPENDIX
121
122 The rest of the documentation details each of the object
123 methods. Internal methods are preceded with an underscore.
124
125 =cut
126
127
128 # The code begins HERE:
129
130 package TFBS::Matrix::PWM;
131
132 use vars '@ISA';
133 use PDL;
134 use strict;
135 use Bio::Root::Root;
136 use Bio::Seq;
137 use Bio::SeqIO;
138 use TFBS::Matrix;
139 use TFBS::SiteSet;
140 use TFBS::Matrix::_Alignment;
141 use TFBS::Ext::pwmsearch;
142 use File::Temp qw/:POSIX/;
143 @ISA = qw(TFBS::Matrix Bio::Root::Root);
144
145
146 #################################################################
147 # PUBLIC METHODS
148 #################################################################
149
150 =head2 new
151
152 Title : new
153 Usage : my $pwm = TFBS::Matrix::PWM->new(%args)
154 Function: constructor for the TFBS::Matrix::PWM object
155 Returns : a new TFBS::Matrix::PWM object
156 Args : # you must specify either one of the following three:
157
158 -matrix, # reference to an array of arrays of integers
159 #or
160 -matrixstring,# a string containing four lines
161 # of tab- or space-delimited integers
162 #or
163 -matrixfile, # the name of a file containing four lines
164 # of tab- or space-delimited integers
165 #######
166
167 -name, # string, OPTIONAL
168 -ID, # string, OPTIONAL
169 -class, # string, OPTIONAL
170 -tags # an array reference, OPTIONAL
171
172 =cut
173
174 sub new {
175 my ($class, %args) = @_;
176 my $matrix = TFBS::Matrix->new(%args, -matrixtype=>"PWM");
177 my $self = bless $matrix, ref($class) || $class;
178 $self->_set_min_max_score();
179 return $self;
180 }
181
182
183 =head2 search_seq
184
185 Title : search_seq
186 Usage : my $siteset = $pwm->search_seq(%args)
187 Function: scans a nucleotide sequence with the pattern represented
188 by the PWM
189 Returns : a TFBS::SiteSet object
190 Args : # you must specify either one of the following three:
191
192 -file, # the name od a fasta file (single sequence)
193 #or
194 -seqobj # a Bio::Seq object
195 # (more accurately, a Bio::PrimarySeqobject or a
196 # subclass thereof)
197 #or
198 -seqstring # a string containing the sequence
199
200 -threshold, # minimum score for the hit, either absolute
201 # (e.g. 11.2) or relative (e.g. "75%")
202 # OPTIONAL: default "80%"
203
204 -subpart # subpart of the sequence to search, given as
205 # -subpart => { start => 140,
206 # end => 180 }
207 # where start and end are coordinates in the
208 # sequence; the coordinate range is interpreted
209 # in the BioPerl tradition (1-based, inclusive)
210 # OPTIONAL: by default searches entire alignment
211
212 =cut
213
214 sub search_seq {
215 my ($self, %args) = @_;
216 $self->_search(%args);
217 }
218
219
220 =head2 search_aln
221
222 Title : search_aln
223 Usage : my $site_pair_set = $pwm->search_aln(%args)
224 Function: Scans a pairwise alignment of nucleotide sequences
225 with the pattern represented by the PWM: it reports only
226 those hits that are present in equivalent positions of both
227 sequences and exceed a specified threshold score in both, AND
228 are found in regions of the alignment above the specified
229 conservation cutoff value.
230 Returns : a TFBS::SitePairSet object
231 Args : # you must specify either one of the following three:
232
233 -file, # the name of the alignment file in Clustal
234 format
235 #or
236 -alignobj # a Bio::SimpleAlign object
237 # (more accurately, a Bio::PrimarySeqobject or a
238 # subclass thereof)
239 #or
240 -alignstring # a multi-line string containing the alignment
241 # in clustal format
242 #############
243
244 -threshold, # minimum score for the hit, either absolute
245 # (e.g. 11.2) or relative (e.g. "75%")
246 # OPTIONAL: default "80%"
247
248 -window, # size of the sliding window (inn nucleotides)
249 # for calculating local conservation in the
250 # alignment
251 # OPTIONAL: default 50
252
253 -cutoff # conservation cutoff (%) for including the
254 # region in the results of the pattern search
255 # OPTIONAL: default "70%"
256
257 -subpart # subpart of the alignment to search, given as e.g.
258 # -subpart => { relative_to => 1,
259 # start => 140,
260 # end => 180 }
261 # where start and end are coordinates in the
262 # sequence indicated by relative_to (1 for the
263 # 1st sequence in the alignment, 2 for the 2nd)
264 # OPTIONAL: by default searches entire alignment
265
266 -conservation
267 # conservation profile, a TFBS::ConservationProfile
268 # OPTIONAL: by default the conservation profile is
269 # computed internally on the fly (less efficient)
270
271 =cut
272
273
274 sub search_aln {
275 my ($self, %args) = @_;
276 unless ($args{-alignstring} or $args{-alignobj} or $args{-file}) {
277 $self->throw
278 ("No alignment file, string or object passed to search_aln.");
279 }
280 $args{-pattern_set} = $self;
281 my $aln = ($args{-alignment_setup} or TFBS::Matrix::_Alignment->new(%args));
282 $aln->do_sitesearch(%args);
283 return $aln->site_pair_set;
284
285 }
286
287 sub max_score {
288 $_[0]->{max_score};
289 }
290
291 sub min_score {
292 $_[0]->{min_score};
293 }
294
295
296
297 =head2 name
298
299 =head2 ID
300
301 =head2 class
302
303 =head2 matrix
304
305 =head2 length
306
307 =head2 revcom
308
309 =head2 rawprint
310
311 =head2 prettyprint
312
313 The above methods are common to all matrix objects. Please consult
314 L<TFBS::Matrix> to find out how to use them.
315
316 =cut
317
318 #################################################################
319 # PRIVATE METHODS
320 #################################################################
321
322
323 sub _set_min_max_score {
324 my ($self) = @_;
325 my $transpose = $self->pdl_matrix->xchg(0,1);
326 $self->{min_score} = sum(minimum $transpose);
327 $self->{max_score} = sum(maximum $transpose);
328 }
329
330 sub _search {
331 # this method runs the pwmsearch C extension and parses the data
332 # similarly to _csearch, which will eventually be discontinued
333 my ($self, %args) = @_;
334 my $seqobj = $self->_to_seqobj(%args);
335 my ($subseq_start, $subseq_end) = (1,$seqobj->length);
336 if(my $subpart = $args{-subpart}) {
337 $subseq_start = $subpart->{-start};
338 $subseq_end = $subpart->{-end};
339 unless($subseq_start and $subseq_end) {
340 $self->throw("Option -subpart missing suboption -start or -end");
341 }
342 }
343 return TFBS::Ext::pwmsearch::pwmsearch($self, $seqobj,
344 ($args{-threshold} or 0),
345 $subseq_start, $subseq_end);
346 }
347
348
349 sub _csearch {
350
351 # this is a wrapper around Wyeth Wasserman's's pwm_searchPFF program
352 # until we do a proper extension
353
354 my ($self) = shift; #the rest of @_ goes to _to_seqob;
355 my %args = @_;
356 my $PWM_SEARCH = $args{'-binary'}
357 || "pwm_searchPFF";
358
359 # dump the sequence into a tempfile
360
361 my $seqobj = $self->_to_seqobj(@_);
362 my ($fastaFH, $fastafile);
363 if (defined $seqobj->{_fastaFH} and defined $seqobj->{_fastafile}) {
364 ($fastaFH, $fastafile) = ($seqobj->{_fastaFH}, $seqobj->{_fastafile});
365 }
366 else {
367 ($fastaFH, $fastafile) = tmpnam();
368 my $seqFH = Bio::SeqIO->newFh(-fh =>$fastaFH, -format=>"Fasta");
369 print $seqFH $seqobj;
370 }
371 # we need $fastafile below
372
373
374 # calculate threshold
375
376 my $threshold;
377 if ($args{-threshold}) {
378 if ($args{-threshold} =~ /(.+)%/) {
379 # percentage
380 $threshold = $self->{min_score} +
381 ($self->{max_score} - $self->{min_score})* $1/100;
382 }
383 else {
384 # absolute value
385 $threshold = $args{-threshold};
386 }
387 }
388 else {
389 # no threshold given
390 $threshold = $self->{min_score} -1;
391 }
392
393
394 # convert piddle to text (there MUST be a better way)
395
396 my $pwmstring = sprintf ( $self->pdl_matrix );
397 $pwmstring =~ s/\[|\]//g; # lose []
398 $pwmstring =~ s/\n /\n/g; # lose leading spaces
399 my @pwmlines = split("\n", $pwmstring); # f
400 $pwmstring = join ("\n", @pwmlines[2..5])."\n";
401
402 # dump pwm into a tempfile
403
404 my ($pwmFH, $pwmfile) = tmpnam(); # we need $pwmfile below
405 print $pwmFH $pwmstring;
406 close $pwmFH;
407
408 # run pwmsearch
409 my $hitlist = TFBS::SiteSet->new();
410 my ($TFname, $TFclass) = ($self->{name}, $self->{class});
411
412 my @search_result_lines =
413 `$PWM_SEARCH $pwmfile $fastafile $threshold -n $TFname -c $TFclass`;
414 foreach (@search_result_lines) {
415 chomp;
416 my ($seq_id, $factor, $class, $strand, $score, $pos, $siteseq) =
417 (split)[0, 2, 3, 4, 5, 7, 9];
418 my $correct_strand = ($strand eq "+")? "-1" : "1";
419 my $site = TFBS::Site->new ( -seq_id => $seqobj->display_id()."",
420 -seqobj => $seqobj,
421 -strand => $correct_strand."",
422 -pattern => $self,
423 -siteseq => $siteseq."",
424 -score => $score."",
425 -start => $pos,
426 -end => $pos + length($siteseq) -1
427 );
428 $hitlist->add_site($site);
429 }
430
431
432 # cleanup
433 unlink $fastafile unless $seqobj->{_fastafile};
434 unlink $pwmfile;
435 return $hitlist;
436 }
437
438
439
440 sub _bsearch {
441
442 # this is Perl/PDL only search routine. For experimental purposes only
443
444 my ($self,%args) = @_; #the rest of @_ goes to _to_seqob;
445 my @PWMs;
446
447 # prepare the sequence
448
449 my $seqobj = $self->_to_seqobj(%args);
450 my $seqmatrix = (defined $seqobj->{_pdl_matrix})
451 ? $seqobj->{_pdl_matrix}
452 : _seq_to_pdlmatrix($seqobj);
453
454 # calculate threshold
455
456 my $threshold;
457 if ($args{-threshold}) {
458 if ($args{-threshold} =~ /(.+)%/) {
459 # percentage
460 $threshold = $self->{min_score} +
461 ($self->{max_score} - $self->{min_score})* $1/100;
462 }
463 else {
464 # absolute value
465 $threshold = $args{-threshold};
466 }
467 }
468 else {
469 # no threshold given
470 $threshold = $self->{min_score} -1;
471 }
472
473 # do the analysis
474
475 my $hitlist = TFBS::SiteSet->new();
476 foreach my $pwm ($self, $self->revcom()) {
477 my $TFlength = $pwm->pdl_matrix->getdim(0);
478 my $position_score_pdl = zeroes($seqmatrix->getdim(0) - $TFlength + 1);
479 my $position_index_pdl = sequence($seqmatrix->getdim(0) - $TFlength + 1)+1;
480
481 foreach my $i (0..($TFlength-1)) {
482 my $columnproduct = $seqmatrix * $pwm->pdl_matrix->slice("$i,:");
483 $position_score_pdl +=
484 $columnproduct->xchg(0,1)->sumover->slice($i.":".($i-$TFlength));
485 }
486 my @hitpositions =
487 list $position_index_pdl->where($position_score_pdl >= $threshold);
488 my @hitscores =
489 list $position_score_pdl->where($position_score_pdl >= $threshold);
490
491 for my $i(0..$#hitpositions) {
492 my($pos,$score) = ($hitpositions[$i], $hitscores[$i]);
493 my $siteseq = scalar($seqobj->subseq($pos, $pos+$TFlength-1));
494 my $site = TFBS::Site->new ( -seq_id => $seqobj->display_id(),
495 -seqobj => $seqobj,
496 -strand => $pwm->{strand},
497 -Matrix => $pwm,
498 -siteseq => $siteseq,
499 -score => $score,
500 -start => $pos);
501 $hitlist->add_site($site);
502 }
503 }
504 return $hitlist;
505 }
506
507
508 sub _to_seqobj {
509 my ($self, %args) = @_;
510
511 my $seq;
512 if ($args{-file}) { # not a Bio::Seq
513 return Bio::SeqIO->new(-file => $args{-file},
514 -format => 'fasta',
515 -moltype => 'dna')->next_seq();
516 }
517 elsif ($args{-seqstring}
518 or $args{-seq})
519 { # I guess it's a string then
520 return Bio::Seq->new(-seq => ($args{-seqstring} or $args{-seq}),
521 -id => ($args{-seq_id} or "undefined"),
522 -moltype => 'dna');
523 }
524 elsif ($args{'-seqobj'} and ref($args{'-seqobj'}) and $args{'-seqobj'}->can("seq")) {
525 # do nothing (maybe check later)
526 return $args{'-seqobj'};
527 }
528 #elsif (ref($format) =~ /Bio\:\:Seq/ and !defined $seq) {
529 # if only one parameter passed and it's a Bio::Seq
530 #return $format;
531 #}
532 else {
533 $self->throw ("Wrong parameters passed to search method: ".%args);
534 }
535
536 }
537
538 sub _seq_to_pdlmatrix {
539 # called from ?search
540
541 # not OO - help function for search
542
543 my $seqobj = shift;
544 my $seqstring = uc($seqobj->seq());
545
546 my @perlarray;
547 foreach (qw(A C G T)) {
548 my $seqtobits = $seqstring;
549 eval "\$seqtobits =~ tr/$_/1/"; # curr. letter $_ to 1
550 eval "\$seqtobits =~ tr/1/0/c"; # non-1s to 0
551 push @perlarray, [split("", $seqtobits)];
552 }
553 return byte (\@perlarray);
554 }
555
556
557 sub DESTROY {
558 # nothing
559 }
560
561
562 1;