Debian Codegraph @

hmmer/src/hmmpgmd_client_example.pl

raw
1 #!/usr/bin/env perl
2
3 =head1 SYNOPSIS
4
5 This script is a very basic version of what is performed by the HMMER website
6 searches. The script will connet to a hmmpgmd client and take the input fasta file
7 (containing one or more sequences) and push each sequence down the socket
8 to be searched by the master. When the results come back, the status is
9 read. If successful, the whole message is read from the socket and written
10 to file in /tmp, as well as being stored in a scalar. The scalar is then
11 unpacked, just to the level of the stats. The sequence is searched against
12 the first database in the hmmpgmd list of databases (whether sequence of HMM).
13
14 NOTE: The socket call is wrapped up in a sig alarm that will die terminate when
15 it does not response. Under normal website operation, this is set to 30 secs.
16
17
18 =cut
19
20 use strict;
21 use warnings;
22 use Carp;
23 use IO::Socket::INET;
24 use Getopt::Long;
25
26 #------------------------------------------------------------------------------
27 #Process the options;
28 #------------------------------------------------------------------------------
29
30 my ( $map, $file, $nocleanup, $peerAddr, $peerPort, $proto, $verbose, $help, $timeout );
31
32 $timeout = 30;
33 GetOptions(
34 "map=s" => \$map,
35 "file=s" => \$file,
36 "PeerAddr=s" => \$peerAddr,
37 "PeerPort=s" => \$peerPort,
38 "Proto=s" => \$proto,
39 "timeout=i" => \$timeout,
40 "verbose" => \$verbose,
41 "nocleanup" => \$nocleanup,
42 "h|help" => \$help
43 ) or die "Failed to parse options, run -h :[$@]\n";
44
45 if ( !defined($map) ) {
46 warn("No accessions will be reported, just hmmpgmd index.\n");
47 }
48 elsif ( !-s $map ) {
49 warn
50 "A map file [$map] was specified, but it either has no size or does not exist.\n";
51 $help = 1;
52 }
53
54 if ( defined($file) ) {
55 unless ( -s $file ) {
56 warn "\n$file either does not exist, or has no size\n\n";
57 $help = 1;
58 }
59 }
60 else {
61 warn "\nPlease specify a query fasta filename!\n\n";
62 $help = 1;
63 }
64
65 help() if ($help);
66
67 #------------------------------------------------------------------------------
68 #Now get the socket connection.
69 #------------------------------------------------------------------------------
70
71 my $connection;
72 $connection = {
73 PeerAddr => defined($peerAddr) ? $peerAddr : '127.0.0.1',
74 PeerPort => defined($peerPort) ? $peerPort : '51371',
75 Proto => defined($proto) ? $proto : 'tcp'
76 };
77
78 $verbose && print STDERR "Getting socket connection";
79 my $sock = IO::Socket::INET->new(%$connection)
80 or die "Could not connect to socket: [$!] \n";
81 $sock->autoflush(1);
82
83 #------------------------------------------------------------------------------
84 # Read in the mapping file
85 #------------------------------------------------------------------------------
86 # In this example, the mappings are read into memory. If you have a large
87 #database, you may want to consider a NoSQL alternative such as Redis or
88 #MongoDB
89
90 my $mappings;
91 if ($map) {
92 $mappings = readMapFile($map);
93 }
94
95 #------------------------------------------------------------------------------
96 main();
97
98 sub main {
99
100 #Build up the connection string
101 my ($optStr);
102
103 #If you are using a hmm database, you would change this to be --hmmdb
104 $optStr = '@--seqdb 1';
105
106 #open the input fasta file.
107 my $c = 1;
108 local $/ = "\n>";
109 open( my $fh, '<', $file ) or die "Could not open $file:[$!]\n";
110 my @fasta = <$fh>;
111 close($fh);
112
113 foreach (@fasta) {
114 $verbose && print STDERR "Working on sequence #: $c\n";
115
116 my $seq = $_;
117 $seq =~ s/>$//mx;
118 $seq =~ s/^([^>])/>$1/x;
119 my ($query_name) = $seq =~ /^>([^\s]*)/mx;
120 $seq .= "\n//"; #add on the file delimiter required by hmmer; That's all there is ...
121
122 $verbose && print STDERR "sending |$optStr\n$seq| to the socket\n";
123
124 #Print the query to the socket
125 print $sock "$optStr\n$seq";
126 my ( $stats, $hits );
127
128 #Wrap this whole call in a sig alarm.
129 local $SIG{ALRM} = sub { croak "Failed to get response from hmmpgmd" };
130 alarm $timeout;
131 eval {
132 #open the file where we store the binary data.
133 open( my $outFH, '>', "/tmp/hmmer.$$.$c.out" )
134 or die "Could not open /tmp/hmmer.$$.c.out:[$!]\n";
135 ( $stats, $hits ) = &unpackResults( $sock, $outFH, $verbose );
136 close($outFH) or croak "Could not close tmp file";
137 };
138 if ($@) {
139 die "Timeout on the socket:$@\n";
140 }
141 alarm 0;
142
143 $verbose && print STDERR "Got " . $stats->{nincluded} . " hits\n";
144 printHits($hits);
145 $c++;
146 }
147
148 #------------------------------------------------------------------------------
149 # Normally we will want to clean up /tmp, but occasionally it will be useful.
150 #------------------------------------------------------------------------------
151
152 unless ($nocleanup) {
153 $verbose && print STDERR "Cleaning up /tmp\n";
154 my @files = glob("/tmp/hmmer.$$.*");
155 foreach my $f (@files) {
156 unlink($f) if ( -e $f );
157 }
158 }
159 exit;
160 }
161
162 #------------------------------------------------------------------------------
163 #Subroutines
164 #------------------------------------------------------------------------------
165 #------------------------------------------------------------------------------
166
167 =head1 SUBROUTINES
168
169
170 =cut
171
172
173 =head2 printHits
174
175 Title : printHits
176 Incept : finnr, Apr 22, 2013 5:16:13 PM
177 Usage : printHits( $hitArrayRef );
178 Function : Prints out elements form the unpacked data sturcture so that
179 : alignments can be viewed.
180 Args : The array reference containing the unpacked data
181 Returns : 1
182
183 =cut
184
185 sub printHits {
186 my ($hits) = @_;
187
188 my $ruler = '-' x 80;
189
190 #Use a flush buffer, so results are written in the entirity.
191 local $/ = 1;
192 foreach my $seq (@$hits) {
193 next if ( !$seq->{nincluded} );
194 my $str = join( "\t",
195 "Seq hit", $seq->{name}, $seq->{desc}, $seq->{score}, $seq->{evalue} );
196 print "$str\n\n";
197 foreach my $dom ( @{ $seq->{domains} } ) {
198 if ( $dom->{is_included} ) {
199 print "Domain hit "
200 . $seq->{name} . "/"
201 . $dom->{ienv} . "-"
202 . $dom->{jenv}
203 . ": score "
204 . sprintf( '%.2f', $dom->{bitscore} )
205 . ", E-value (individual) "
206 . $dom->{ievalue}
207 . " E-value (conditional) "
208 . $dom->{cevalue} . "\n\n";
209 print sprintf( "\t%-30s %6d %s %-6d\n",
210 $seq->{name}, $dom->{alisqfrom}, $dom->{aliaseq}, $dom->{alisqto} );
211 print sprintf( "\t%37s %s\n", '', $dom->{alimline} );
212 print sprintf(
213 "\t%-30s %6d %s %-6d\n",
214 $dom->{alihmmname}, $dom->{alihmmfrom},
215 $dom->{alimodel}, $dom->{alihmmto}
216 );
217 print sprintf( "\t%37s %s\n\n", '', $dom->{alippline} );
218 }
219 }
220 print "$ruler\n";
221 }
222 return 1;
223 }
224
225 #------------------------------------------------------------------------------
226 =head2 unpackResults
227
228 Title : unpackResu;ts
229 Incept : finnr, Apr 22, 2013 5:18:15 PM
230 Usage : unpackResults( $socket, $fh)
231 Function : Takes the sockect connection to hmmpgmd and reads the response. If
232 : successful it will unpack the binary data structure and build a
233 : Perl data structure.
234 Args : An IO::Socket::INET to hmmpgmd, filehandle to temp file.
235 Returns : Perl data sturcture of results.
236 Note : Include a data export module such as Data::Priner to reveal
237 : the entirity of the HMMER result data structure. Everything that
238 : is available in the commandline version is present.
239
240 =cut
241
242 sub unpackResults {
243 my ( $socket, $fh ) = @_;
244
245 #Ths is the unpacking template and length.
246 my $statusTemplate = "I x4 Q";
247 my $STATUS = 16;
248 my $rl = read( $sock, my $statusB, $STATUS );
249
250 #Read the status from the socket.
251 unless ( $rl == $STATUS ) {
252 die "Error reading STATUS from socket. Requested " . $STATUS
253 . "bytes, but only read $rl bytes\n";
254 }
255
256 #Unpack the status.
257 my ( $status, $messLen ) = unpack( $statusTemplate, $statusB );
258 if ( $status == 0 ) #Everything was successful
259 {
260 #read the entire results from the socket. We will store this
261 #in a temporary file. This is not entirely necessary.
262 my $binaryData = readAndStore( $socket, $messLen, $fh );
263
264 #We now process the binary data structure returned by
265 #hmmpgmd. To make the code more readable, we will
266 #unpack section by section, cutting off the front
267 #of the binary and processing just that bit.
268
269 my $bit = substr( $binaryData, 0, 120, '' );
270
271 #Get a hash reference back containing all the search
272 #stats, such as time, number of hits
273 my $stats = unpackStats($bit);
274
275 my $hits = [];
276
277 if ( $stats->{nreported} ) {
278
279 #We have at least some hits to unpack....
280 #The first hit section contains all of the sequence matches
281 #but not domain mataches.
282 for ( my $n = 1 ; $n <= $stats->{nreported} ; $n++ ) {
283 $bit = substr( $binaryData, 0, 152, '' );
284 unpackHit( $bit, $hits, $stats->{Z} );
285 }
286
287 #Now, unpack the domain hits for the sequences
288 for ( my $h = 0 ; $h < $stats->{nreported} ; $h++ ) {
289 if ( $hits->[$h]->{ndom} ) {
290 my $dombit = substr( $binaryData, 0, 72 * $hits->[$h]->{ndom}, '' );
291
292 #This gets the fixed size fields
293 unpackDomain( $dombit, $hits, $h, $stats );
294 for ( my $a = 1 ; $a <= $hits->[$h]->{ndom} ; $a++ ) {
295
296 #Now unpack the variable sized fields.
297 unpackAli( \$binaryData, $hits, $h, $a );
298 }
299 }
300 }
301 }
302 return ( $stats, $hits );
303 }
304 else #There was an error, read the message
305 {
306 $rl = read( $sock, my $errorLine, $messLen );
307 my $errorMessage = unpack( "a$messLen", $errorLine );
308 die "There was an error reported by HMMER: $errorMessage\n";
309 }
310 }
311
312 #------------------------------------------------------------------------------
313 =head2 unpackAli
314
315 Title : unpackAli
316 Incept : finnr, Apr 22, 2013 7:53:39 PM
317 Usage : unpackAli( $binaryData, $hits, $hitCount, $domCount);
318 Function : Takes the binary data, gets the alignment data, which in this case
319 : are dynamic fields. This uses the data found within the hit/domain
320 : information to locate and read the appropriate amount of bytes.
321 Args : The binary data stream, the hit data structure and the hit and domain
322 : positions.
323 Returns : 1
324
325 =cut
326
327 sub unpackAli {
328 my ( $binary, $hits, $h, $a ) = @_;
329
330 my $bit = substr( $$binary, 0, 168, '' );
331 my @aliKeys =
332 qw(rfline mmline csline model mline aseq ppline N hmmname hmmacc hmmdesc
333 hmmfrom hmmto M sqname sqacc sqdesc sqfrom sqto L memsize mem);
334 my @ali = unpack( "Q7 I x4 Q3 I3 x4 Q6 I x4 Q", $bit );
335 my %ali = map { $aliKeys[$_] => $ali[$_] } 0 .. $#aliKeys;
336
337 $bit = substr( $$binary, 0, $ali{memsize}, '' );
338 my @unpackElements = qw(0 1 2 3 4 5 6 8 9 10 14 15 16 20);
339
340 my $offset = 0;
341 for ( my $i = 0 ; $i < $#unpackElements ; $i++ ) {
342 my $e = $unpackElements[$i];
343 next if ( $ali[$e] == 0 ); #Then this element is not defined in the binary
344 my $ne; #Store the next defined element.
345 for ( my $j = $i + 1 ; $j <= $#unpackElements ; $j++ ) {
346 if ( $ali[ $unpackElements[$j] ] > 0 ) {
347 $ne = $unpackElements[$j];
348 $j = $#unpackElements + 1; #break the loop
349 }
350 }
351
352 #The number of bytes that we need to unpack is:
353 my $l = ( $ali[$ne] - $ali[$e] );
354
355 #Define the unpack template:
356 my $template = $offset > 0 ? "x$offset a$l" : "a$l";
357 my $s = $ali[$e] == 0 ? '' : unpack( $template, $bit );
358 chop($s); #This removes the \0 - C string terminator
359 $ali{ $aliKeys[$e] } = $s;
360
361 #keep a note of what has aready been unpacked.
362 $offset += $l;
363 }
364
365 foreach my $k (@aliKeys) {
366 next if $k =~ /memsize/;
367 $hits->[$h]->{domains}->[ $a - 1 ]->{ 'ali' . $k } = $ali{$k};
368 }
369 return 1;
370 }
371
372 #------------------------------------------------------------------------------
373 =head2 unpackDomain
374
375 Title : unpackDomain
376 Incept : finnr, Apr 22, 2013 7:59:59 PM
377 Usage : unpackDomain( $binary, $hits, $h, $stats );
378 Function : unpack the domain hit from the binary string.
379 Args : binary string, the hit array reference, the sequence position,
380 : stats hash ref.
381 Returns : 1
382
383 =cut
384
385 sub unpackDomain {
386 my ( $binary, $hits, $h, $stats ) = @_;
387
388 my @dom = unpack( "i4 f5 x4 d i2 Q x8" x $hits->[$h]->{ndom}, $binary );
389 my $noDomKeys = 13;
390
391 #*** If the P7_DOMAIN struc changes, modify these numbers
392 for ( my $d = 0 ; $d < $hits->[$h]->{ndom} ; $d++ ) {
393 my $off = ( $d * $noDomKeys );
394 my $ievalue = sprintf( "%.1e", exp( $dom[ $off + 9 ] ) * $stats->{Z} );
395 $ievalue = $ievalue < 0.0001 ? $ievalue : sprintf( "%.6g", $ievalue );
396 my $cevalue = sprintf( "%.1e", exp( $dom[ $off + 9 ] ) * $stats->{domZ} );
397 $cevalue = $cevalue < 0.0001 ? $cevalue : sprintf( "%.6g", $cevalue );
398 $hits->[$h]->{domains}->[$d] = {
399 ienv => $dom[$off],
400 jenv => $dom[ $off + 1 ],
401 iali => $dom[ $off + 2 ],
402 jali => $dom[ $off + 3 ],
403 bitscore => $dom[ $off + 8 ],
404 ievalue => $ievalue,
405 cevalue => $cevalue,
406 oasc => sprintf( "%4.2f",
407 ( $dom[ $off + 9 ] / ( 1.0 + abs( $dom[ $off + 1 ] - $dom[$off] ) ) ) ),
408 bias => sprintf( "%.2f", abs( $dom[ $off + 9 ] * 1.442695041 ) ),
409 is_reported => $dom[ $off + 10 ],
410 is_included => $dom[ $off + 11 ],
411 };
412
413 }
414 return 1;
415 }
416
417 #------------------------------------------------------------------------------
418 =head2 unpackHit
419
420 Title : unpackHit
421 Incept : finnr, Apr 22, 2013 8:22:55 PM
422 Usage : unpackHit($binary, $hitArray, $dbsize);
423 Function : unpack a single sequence match, pushing the data into the hitArray
424 : reference. The database size is also passed in to correctly set
425 : the e-value.
426 Args : Binary data, hit array, int of the database size
427 Returns : 1
428
429 =cut
430
431 sub unpackHit {
432 my ( $binary, $hits, $z ) = @_;
433
434 my @hitKeys =
435 qw(name acc desc window_length sort_key score pre_score sum_score
436 pvalue pre_pvalue sum_pvalue nexpected nregions nclustered noverlaps
437 nenvelopes ndom flags nreported nincluded best_domain seqidx subseq_start dcl offset);
438 my $noHitsKeys = scalar(@hitKeys);
439 my $raw_hits = [];
440 @{$raw_hits} = unpack( "Q3 I x4 d f3 x4 d3 f I9 Q4", $binary );
441
442 my $evalue = sprintf( "%.1e", exp( $raw_hits->[8] ) * $z );
443 $evalue = $evalue < 0.0001 ? $evalue : sprintf( "%.6g", $evalue );
444
445 my $acc = $raw_hits->[0];
446 my $desc = $raw_hits->[2];
447
448 if ($mappings) {
449 ( $acc, $desc ) = split( /\s+/xm, $mappings->[ $raw_hits->[0] ], 2 );
450 }
451
452 push @$hits,
453 {
454 name => $acc,
455 acc => $raw_hits->[1],
456 desc => $desc,
457 score => sprintf( "%.1f", $raw_hits->[5] ),
458 bias => sprintf( "%.1f", abs( $raw_hits->[6] - $raw_hits->[5] ) ),
459 pvalue => $raw_hits->[8],
460 nregions => $raw_hits->[12],
461 ndom => $raw_hits->[16],
462 flags => $raw_hits->[17],
463 nreported => $raw_hits->[18],
464 nincluded => $raw_hits->[19],
465 evalue => $evalue,
466 dcl => $raw_hits->[23]
467 };
468 return 1;
469 }
470
471 #------------------------------------------------------------------------------
472 =head2 readAndStore
473
474 Title : readAndStore
475 Incept : finnr, Apr 22, 2013 8:13:49 PM
476 Usage : readAndStore($socket, $messageLength, $filehandle)
477 Function : Reads the message (length in bytes) from the socket and
478 : writes the binary response to the temporary file, returning the
479 : binary data in scalar context.
480 Args : IO::Socket::INET, message length, filehandle.
481 Returns : binary data in scalar
482
483 =cut
484
485 sub readAndStore {
486 my ( $socket, $messLen, $fh ) = @_;
487
488 #Read the number of bytes in the messlen, from the socket, into the results
489 #scalar (binary format)
490 my $rl = read( $socket, my $resultsB, $messLen );
491
492 #Check that the read length is correct.
493 unless ( $rl == $messLen ) {
494 die "Error reading STATS from socket. Requested " . $messLen
495 . " bytes, but only read $rl bytes\n";
496 }
497
498 #Print the results to the file
499 print $fh $resultsB;
500
501 #return the binary string
502 return $resultsB;
503 }
504
505 #------------------------------------------------------------------------------
506 =head2 unpackStats
507
508 Title : unpackStats
509 Incept : finnr, Apr 22, 2013 8:09:15 PM
510 Usage : unpackStats($binaryData)
511 Function : Unpacks the search stats binary data.
512 Args : The binary data
513 Returns : hashRef containing the search statistics.
514
515 =cut
516
517 sub unpackStats {
518 my ($bit) = @_;
519
520 #The binary template
521 my $statsTemplate = "d5 I2 q9";
522
523 #Store how far we have read through the file
524 my @stats = unpack( $statsTemplate, $bit );
525
526 #This is the literal mean of each values. Store in a more informative
527 #hash.
528 my @statsKeys = qw(elapsed user sys Z domZ Z_setby domZ_setby nmodels nseqs
529 n_past_msv n_past_bias n_past_vit n_past_fwd nhits nreported nincluded );
530
531 unless ( $#stats == $#statsKeys ) {
532 die "Missmatch between the number of stats data elements recieved ["
533 . $#stats
534 . "] and expected [$#statsKeys]\n";
535 }
536
537 my %stats = map { $statsKeys[$_] => $stats[$_] } 0 .. $#statsKeys;
538
539 #Return the hashref containing the stats.
540 return \%stats;
541 }
542
543 #------------------------------------------------------------------------------
544 =head2 readMapFile
545
546 Title : readMapFile
547 Incept : finnr, Apr 22, 2013 8:00:16 PM
548 Usage : readMapFile('/path/to/file');
549 Function : Reads the map file produced by esl-reformat into an array so that
550 : sequence 'meta' data can be reapplied.
551 Args : Path to file.
552 Returns : ArrayRef containing sequence meta data. The sequence index is
553 : used as the index into the array.
554
555 =cut
556
557 sub readMapFile {
558 my ($mapfile) = @_;
559
560 #Read the file produced by hmmpgmd, using the sequence index/name as the array
561 #index. This will produce an array where the first zeroth element is uninitalized.
562
563 my @mappings;
564
565 $verbose && print STDERR "Reading map file, $mapfile\n";
566
567 my $M;
568 open( $M, '<', $mapfile ) or die "Could not open map file:[$!]\n";
569 while (<$M>) {
570 chomp;
571 my ( $idx, $header ) = split( /\s+/xm, $_, 2 );
572 next if ( !defined($header) );
573 $mappings[$idx] = $header;
574 }
575 close($M);
576
577 #Return the array reference to the
578 return ( \@mappings );
579 }
580
581 #------------------------------------------------------------------------------
582 =head2 help
583
584 Title : help
585 Incept : finnr, Apr 22, 2013 8:03:50 PM
586 Usage : help
587 Function : prints some help
588 Args : none
589 Returns : nothing
590
591 =cut
592
593 sub help {
594
595 print <<'EOF';
596
597 Summary: Sample hmmpgmd client
598
599 Usage: hmmpgmd_client_example.pl [options] -file seq.fa
600
601 file : The name of the fasta file. The file is not being validated; give it
602 : rubbish and bad things will happen.
603 map : The map file produced by esl-reformat when using hmmpgmd format option.
604 : If this is not provided, then it will just report the index numbers.
605 h|help : Prints this help statement
606 verbose : Prints debug statements/progress reports.
607 nocleanup : When this flag is set, leaves the hmmpgmd binary output files in
608 : /tmp. The files has the format hmmer.#PID.#sequence.out.
609 timeout : Change the default timeout, 30 secs. Time in seconds.
610
611 #The following options control which hmmpgmd master is linked by the client. They are used
612 #by IO::Socket::INET, see CPAN for more information.
613
614 PeerAddr : The IP address of the machine where the master is running, default 127.0.0.1
615 PeerPort : The port number that the master is listening on, default 51371
616 Proto : The socket protocol - should not change this unless the master
617 : changes its communications protocol, which is tcp
618
619 Also, you can run:
620
621 perldoc hmmpgmd_client_example.pl
622
623 for more information.
624
625 Details: This example script shows how to search sequences in a FASTA file against an
626 hmmpgmd format database file, using HMMER's hmmpgmd. Steps include:
627
628 (1) Generate an hmmpgmd format file, including map file, from a FASTA format
629 file, for example using the HMMER/Easel tool esl-reformat:
630
631 prompt% esl-reformat --id_map my.hmmpgmd.map hmmpgmd my.fasta > my.hmmpgmd
632
633 (2) Start the hmmpgmd master/worker, run the following commands:
634
635 prompt% hmmpgmd --master --seqdb my.hmmpgmd
636 prompt% hmmpgmd --worker 127.0.0.1 --cpu 4
637
638 (3) Run this client to connect to the master
639
640 (4) Submit one query to hmmpgmd for each sequence in the query file, retrieve results
641 from the master, then unpack the custom (and undocumented) binary. Examples of
642 unpacking the binary are seen in the unpackXXX() functions.
643
644 EOF
645
646 exit 0;
647
648 }