FAST/Bio/AlignIO/phylip.pm untested

filter: Statementstmt 0.0% 0 / 222 Branchbran 0.0% 0 / 110 Conditioncond 0.0% 0 / 48 MC/DCmcdc 0.0% 0 / 31 Subroutinesub 0.0% 0 / 17 Podpod 0.0% 0 / 12 totaltotal 0.0% 0 / 440 CC 56 SCAR 54.8
CC
56
Cov
0%
next_aln
506.0
write_aln
306.0
_initialize
90.0
CRAP 240.6
1 #
2 # BioPerl module for FAST::Bio::AlignIO::phylip
3 #
4 # Copyright Heikki Lehvaslaiho
5 #
6  
7 =head1 NAME
8  
9 FAST::Bio::AlignIO::phylip - PHYLIP format sequence input/output stream
10  
11 =head1 SYNOPSIS
12  
13 # Do not use this module directly. Use it via the FAST::Bio::AlignIO class.
14  
15 use FAST::Bio::AlignIO;
16 use FAST::Bio::SimpleAlign;
17 #you can set the name length to something other than the default 10
18 #if you use a version of phylip (hacked) that accepts ids > 10
19 my $phylipstream = FAST::Bio::AlignIO->new(-format => 'phylip',
20 -fh => \*STDOUT,
21 -idlength=>30);
22 # convert data from one format to another
23 my $gcgstream = FAST::Bio::AlignIO->new(-format => 'msf',
24 -file => 't/data/cysprot1a.msf');
25  
26 while( my $aln = $gcgstream->next_aln ) {
27 $phylipstream->write_aln($aln);
28 }
29  
30 # do it again with phylip sequential format format
31 $phylipstream->interleaved(0);
32 # can also initialize the object like this
33 $phylipstream = FAST::Bio::AlignIO->new(-interleaved => 0,
34 -format => 'phylip',
35 -fh => \*STDOUT,
36 -idlength=>10);
37 $gcgstream = FAST::Bio::AlignIO->new(-format => 'msf',
38 -file => 't/data/cysprot1a.msf');
39  
40 while( my $aln = $gcgstream->next_aln ) {
41 $phylipstream->write_aln($aln);
42 }
43  
44 =head1 DESCRIPTION
45  
46 This object can transform FAST::Bio::SimpleAlign objects to and from PHYLIP
47 format. By default it works with the interleaved format. By specifying
48 the flag -interleaved =E<gt> 0 in the initialization the module can
49 read or write data in sequential format.
50  
51 Long IDs up to 50 characters are supported by flag -longid =E<gt>
52 1. ID strings can be surrounded by single quoted. They are mandatory
53 only if the IDs contain spaces.
54  
55 =head1 FEEDBACK
56  
57 =head2 Support
58  
59 Please direct usage questions or support issues to the mailing list:
60  
61 I<bioperl-l@bioperl.org>
62  
63 rather than to the module maintainer directly. Many experienced and
64 reponsive experts will be able look at the problem and quickly
65 address it. Please include a thorough description of the problem
66 with code and data examples if at all possible.
67  
68 =head2 Reporting Bugs
69  
70 Report bugs to the Bioperl bug tracking system to help us keep track
71 the bugs and their resolution. Bug reports can be submitted via the
72 web:
73  
74 https://redmine.open-bio.org/projects/bioperl/
75  
76 =head1 AUTHORS - Heikki Lehvaslaiho and Jason Stajich
77  
78 Email: heikki at ebi.ac.uk
79 Email: jason at bioperl.org
80  
81 =head1 APPENDIX
82  
83 The rest of the documentation details each of the object
84 methods. Internal methods are usually preceded with a _
85  
86 =cut
87  
88 # Let the code begin...
89  
90 package FAST::Bio::AlignIO::phylip;
91 use vars qw($DEFAULTIDLENGTH $DEFAULTLINELEN $DEFAULTTAGLEN);
92 use strict;
93  
94 use FAST::Bio::SimpleAlign;
95 use POSIX; # for the rounding call
96  
97 use base qw(FAST::Bio::AlignIO);
98  
99 BEGIN {
100 $DEFAULTIDLENGTH = 10;
101 $DEFAULTLINELEN = 60;
102 $DEFAULTTAGLEN = 10;
103 }
104  
105 =head2 new
106  
107 Title : new
108 Usage : my $alignio = FAST::Bio::AlignIO->new(-format => 'phylip'
109 -file => '>file',
110 -idlength => 10,
111 -idlinebreak => 1);
112 Function: Initialize a new L<FAST::Bio::AlignIO::phylip> reader or writer
113 Returns : L<FAST::Bio::AlignIO> object
114 Args : [specific for writing of phylip format files]
115 -idlength => integer - length of the id (will pad w/
116 spaces if needed)
117 -interleaved => boolean - whether interleaved
118 or sequential format required
119 -line_length => integer of how long a sequence lines should be
120 -idlinebreak => insert a line break after the sequence id
121 so that sequence starts on the next line
122 -flag_SI => whether or not write a "S" or "I" just after
123 the num.seq. and line len., in the first line
124 -tag_length => integer of how long the tags have to be in
125 each line between the space separator. set it
126 to 0 to have 1 tag only.
127 -wrap_sequential => boolean for whether or not sequential
128 format should be broken up or a single line
129 default is false (single line)
130 -longid => boolean for allowing arbitrary long IDs (default is false)
131  
132 =cut
133  
134 sub _initialize {
135 my($self,@args) = @_;
136 $self->SUPER::_initialize(@args);
137  
138 my ($interleave,$linelen,$idlinebreak,
139 $idlength, $flag_SI, $tag_length,$ws, $longid) =
140 $self->_rearrange([qw(INTERLEAVED
141 LINE_LENGTH
142 IDLINEBREAK
143 IDLENGTH
144 FLAG_SI
145 TAG_LENGTH
146 WRAP_SEQUENTIAL
147 LONGID)],@args);
148 $self->interleaved($interleave ? 1 : 0) if defined $interleave;
149 $self->idlength($idlength || $DEFAULTIDLENGTH);
150 $self->id_linebreak(1) if( $idlinebreak );
151 $self->line_length($linelen) if defined $linelen && $linelen > 0;
152 $self->flag_SI(1) if ( $flag_SI );
153 $self->tag_length($tag_length) if ( $tag_length || $DEFAULTTAGLEN );
154 $self->wrap_sequential($ws ? 1 : 0);
155 $self->longid($longid ? 1 : 0);
156 1;
157 }
158  
159 =head2 next_aln
160  
161 Title : next_aln
162 Usage : $aln = $stream->next_aln()
163 Function: returns the next alignment in the stream.
164 Throws an exception if trying to read in PHYLIP
165 sequential format.
166 Returns : L<FAST::Bio::SimpleAlign> object
167 Args :
168  
169 =cut
170  
171 sub next_aln {
172 my $self = shift;
173 my $entry;
174 my ($seqcount, $residuecount, %hash, $name,$str,
175 @names,$seqname,$start,$end,$count,$seq);
176  
177 my $aln = FAST::Bio::SimpleAlign->new(-source => 'phylip');
178  
179 # skip blank lines until we see header line
180 # if we see a non-blank line that isn't the seqcount and residuecount line
181 # then bail out of next_aln (return)
182 HEADER: while ($entry = $self->_readline) {
183 next if $entry =~ /^\s?$/;
184 if ($entry =~ /\s*(\d+)\s+(\d+)/) {
185 ($seqcount, $residuecount) = ($1, $2);
186  
187 }
188 last HEADER;
189 }
190 return unless $seqcount and $residuecount;
191  
192 # first alignment section
193 my $idlen = $self->idlength;
194 $count = 0;
195 my $iter = 1;
196 my $interleaved = $self->interleaved;
197 while( $entry = $self->_readline) {
198 last if( $entry =~ /^\s?$/ && $interleaved );
199  
200 # we've hit the next entry.
201 if( $entry =~ /^\s+(\d+)\s+(\d+)\s*$/) {
202 $self->_pushback($entry);
203 last;
204 }
205 if( $self->longid && $entry =~ /\w/ ) {
206 if ($entry =~ /'/) {
207 $entry =~ /^\s*'([^']+)'\s+(.+)$/;
208 $name = $1;
209 $str = $2;
210 } else {
211 $entry =~ /^\s*([^\s]+)\s+(.+)$/;
212 $name = $1;
213 $str = $2;
214 }
215 # $name =~ s/[\s\/]/_/g; # not sure how wise is it to do this
216 $name =~ s/_+$//; # remove any trailing _'s
217
218 push @names, $name;
219 $str =~ s/\s//g;
220 $count = scalar @names;
221 $hash{$count} = $str;
222  
223 } elsif( $entry =~ /^\s+(.+)$/ ) {
224 $interleaved = 0;
225 $str = $1;
226 $str =~ s/\s//g;
227 $count = scalar @names;
228 $hash{$count} .= $str;
229 } elsif( $entry =~ /^(.{$idlen})\s*(.*)\s$/ ||
230 $entry =~ /^(.{$idlen})(\S{$idlen}\s+.+)\s$/ # Handle weirdness when id is too long
231 ) {
232 $name = $1;
233 $str = $2;
234 $name =~ s/[\s\/]/_/g;
235 $name =~ s/_+$//; # remove any trailing _'s
236  
237 push @names, $name;
238 $str =~ s/\s//g;
239 $count = scalar @names;
240 $hash{$count} = $str;
241 } elsif( $interleaved ) {
242 if( $entry =~ /^(\S+)\s+(.+)/ ||
243 $entry =~ /^(.{$idlen})(.*)\s$/ ) {
244 $name = $1;
245 $str = $2;
246 $name =~ s/[\s\/]/_/g;
247 $name =~ s/_+$//; # remove any trailing _'s
248 push @names, $name;
249 $str =~ s/\s//g;
250 $count = scalar @names;
251 $hash{$count} = $str;
252 } else {
253 $self->debug("unmatched line: $entry");
254 }
255 }
256 $self->throw("Not a valid interleaved PHYLIP file!") if $count > $seqcount;
257 }
258  
259 if( $interleaved ) {
260 # interleaved sections
261 $count = 0;
262 while( $entry = $self->_readline) {
263 # finish current entry
264 if($entry =~/\s*\d+\s+\d+/){
265 $self->_pushback($entry);
266 last;
267 }
268 $count = 0, next if $entry =~ /^\s$/;
269 $entry =~ /\s*(.*)$/ && do {
270 $str = $1;
271 $str =~ s/\s//g;
272 $count++;
273 $hash{$count} .= $str;
274 };
275 $self->throw("Not a valid interleaved PHYLIP file! [$count,$seqcount] ($entry)") if $count > $seqcount;
276 }
277 }
278 return if scalar @names < 1;
279  
280 # sequence creation
281 $count = 0;
282 foreach $name ( @names ) {
283 $count++;
284 if( $name =~ /(\S+)\/(\d+)-(\d+)/ ) {
285 $seqname = $1;
286 $start = $2;
287 $end = $3;
288 } else {
289 $seqname=$name;
290 $start = 1;
291 $str = $hash{$count};
292 # $str =~ s/[^A-Za-z]//g;
293 #$end = length($str);
294 }
295 # consistency test
296 $self->throw("Length of sequence [$seqname] is not [$residuecount] it is ".CORE::length($hash{$count})."! ")
297 unless CORE::length($hash{$count}) == $residuecount;
298  
299 $seq = FAST::Bio::LocatableSeq->new('-seq' => $hash{$count},
300 '-display_id' => $seqname,
301 '-start' => $start,
302 (defined $end) ? ('-end' => $end) : (),
303 '-alphabet' => $self->alphabet,
304 );
305 $aln->add_seq($seq);
306  
307 }
308 return $aln if $aln->num_sequences;
309 return;
310 }
311  
312  
313 =head2 write_aln
314  
315 Title : write_aln
316 Usage : $stream->write_aln(@aln)
317 Function: writes the $aln object into the stream in phylip format
318 Returns : 1 for success and 0 for error
319 Args : L<FAST::Bio::Align::AlignI> object
320  
321 =cut
322  
323 sub write_aln {
324 my ($self,@aln) = @_;
325 my $count = 0;
326 my $wrapped = 0;
327 my $maxname;
328 my $width = $self->line_length();
329 my ($length,$date,$name,$seq,$miss,$pad,
330 %hash,@arr,$tempcount,$index,$idlength,$flag_SI,$line_length, $tag_length);
331  
332 foreach my $aln (@aln) {
333 if( ! $aln || ! $aln->isa('FAST::Bio::Align::AlignI') ) {
334 $self->warn("Must provide a FAST::Bio::Align::AlignI object when calling write_aln");
335 next;
336 }
337 $self->throw("All sequences in the alignment must be the same length")
338 unless $aln->is_flush(1) ;
339  
340 $flag_SI = $self->flag_SI();
341 $aln->set_displayname_flat(); # plain
342 $length = $aln->length();
343 if ($flag_SI) {
344 if ($self->interleaved() ) {
345 $self->_print (sprintf(" %s %s I\n", $aln->num_sequences, $aln->length));
346 } else {
347 $self->_print (sprintf(" %s %s S\n", $aln->num_sequences, $aln->length));
348 }
349 } else {
350 $self->_print (sprintf(" %s %s\n", $aln->num_sequences, $aln->length));
351 }
352  
353 $idlength = $self->idlength();
354 $line_length = $self->line_length();
355 $tag_length = $self->tag_length();
356 foreach $seq ( $aln->each_seq() ) {
357 $name = $aln->displayname($seq->get_nse);
358 if ($self->longid) {
359 $self->warn("The lenght of the name is over 50 chars long [$name]")
360 if length($name) > 50;
361 $name = "'$name' "
362 } else {
363 $name = substr($name, 0, $idlength) if length($name) > $idlength;
364 $name = sprintf("%-".$idlength."s",$name);
365 if( $self->interleaved() ) {
366 $name .= ' ' ;
367 } elsif( $self->id_linebreak) {
368 $name .= "\n";
369 }
370 }
371 #phylip needs dashes not dots
372 my $seq = $seq->seq();
373 $seq =~ s/\./-/g;
374 $hash{$name} = $seq;
375 push(@arr,$name);
376 }
377  
378 if( $self->interleaved() ) {
379 my $numtags;
380 if ($tag_length <= $line_length) {
381 $numtags = floor($line_length/$tag_length);
382 $line_length = $tag_length*$numtags;
383 } else {
384 $numtags = 1;
385 }
386 while( $count < $length ) {
387  
388 # there is another block to go!
389 foreach $name ( @arr ) {
390 my $dispname = $name;
391 $dispname = '' if $wrapped;
392 $self->_print (sprintf("%".($idlength+3)."s",$dispname));
393 $tempcount = $count;
394 $index = 0;
395 $self->debug("residue count: $count\n") if ($count%100000 == 0);
396 while( ($tempcount + $tag_length < $length) &&
397 ($index < $numtags) ) {
398 $self->_print (sprintf("%s ",substr($hash{$name},
399 $tempcount,
400 $tag_length)));
401 $tempcount += $tag_length;
402 $index++;
403 }
404 # last
405 if( $index < $numtags) {
406 # space to print!
407 $self->_print (sprintf("%s ",substr($hash{$name},
408 $tempcount)));
409 $tempcount += $tag_length;
410 }
411 $self->_print ("\n");
412 }
413 $self->_print ("\n");
414 $count = $tempcount;
415 $wrapped = 1;
416 }
417 } else {
418 foreach $name ( @arr ) {
419 my $dispname = $name;
420 my $line = sprintf("%s%s\n",$dispname,$hash{$name});
421 if( $self->wrap_sequential ) {
422 $line =~ s/(.{1,$width})/$1\n/g;
423 }
424 $self->_print ($line);
425 }
426 }
427 }
428 $self->flush if $self->_flush_on_write && defined $self->_fh;
429 return 1;
430 }
431  
432 =head2 interleaved
433  
434 Title : interleaved
435 Usage : my $interleaved = $obj->interleaved
436 Function: Get/Set Interleaved status
437 Returns : boolean
438 Args : boolean
439  
440  
441 =cut
442  
443 sub interleaved {
444 my ($self,$value) = @_;
445 if( defined $value ) {
446 if ($value) {$self->{'_interleaved'} = 1 }
447 else {$self->{'_interleaved'} = 0 }
448 }
449 return 1 unless defined $self->{'_interleaved'};
450 return $self->{'_interleaved'};
451 }
452  
453 =head2 flag_SI
454  
455 Title : flag_SI
456 Usage : my $flag = $obj->flag_SI
457 Function: Get/Set if the Sequential/Interleaved flag has to be shown
458 after the number of sequences and sequence length
459 Example :
460 Returns : boolean
461 Args : boolean
462  
463  
464 =cut
465  
466 sub flag_SI{
467 my ($self,$value) = @_;
468 my $previous = $self->{'_flag_SI'};
469 if( defined $value ) {
470 $self->{'_flag_SI'} = $value;
471 }
472 return $previous;
473 }
474  
475 =head2 idlength
476  
477 Title : idlength
478 Usage : my $idlength = $obj->idlength
479 Function: Get/Set value of id length
480 Returns : string
481 Args : string
482  
483  
484 =cut
485  
486 sub idlength {
487 my($self,$value) = @_;
488 if (defined $value){
489 $self->{'_idlength'} = $value;
490 }
491 return $self->{'_idlength'};
492 }
493  
494 =head2 line_length
495  
496 Title : line_length
497 Usage : $obj->line_length($newval)
498 Function:
499 Returns : value of line_length
500 Args : newvalue (optional)
501  
502  
503 =cut
504  
505 sub line_length{
506 my ($self,$value) = @_;
507 if( defined $value) {
508 $self->{'_line_length'} = $value;
509 }
510 return $self->{'_line_length'} || $DEFAULTLINELEN;
511  
512 }
513  
514 =head2 tag_length
515  
516 Title : tag_length
517 Usage : $obj->tag_length($newval)
518 Function:
519 Example : my $tag_length = $obj->tag_length
520 Returns : value of the length for each space-separated tag in a line
521 Args : newvalue (optional) - set to zero to have one tag per line
522  
523  
524 =cut
525  
526 sub tag_length{
527 my ($self,$value) = @_;
528 if( defined $value) {
529 $self->{'_tag_length'} = $value;
530 }
531 return $self->{'_tag_length'} || $DEFAULTTAGLEN;
532 }
533  
534  
535 =head2 id_linebreak
536  
537 Title : id_linebreak
538 Usage : $obj->id_linebreak($newval)
539 Function:
540 Returns : value of id_linebreak
541 Args : newvalue (optional)
542  
543  
544 =cut
545  
546 sub id_linebreak{
547 my ($self,$value) = @_;
548 if( defined $value) {
549 $self->{'_id_linebreak'} = $value;
550 }
551 return $self->{'_id_linebreak'} || 0;
552 }
553  
554  
555 =head2 wrap_sequential
556  
557 Title : wrap_sequential
558 Usage : $obj->wrap_sequential($newval)
559 Function:
560 Returns : value of wrap_sequential
561 Args : newvalue (optional)
562  
563  
564 =cut
565  
566 sub wrap_sequential{
567 my ($self,$value) = @_;
568 if( defined $value) {
569 $self->{'_wrap_sequential'} = $value;
570 }
571 return $self->{'_wrap_sequential'} || 0;
572 }
573  
574 =head2 longid
575  
576 Title : longid
577 Usage : $obj->longid($newval)
578 Function:
579 Returns : value of longid
580 Args : newvalue (optional)
581  
582  
583 =cut
584  
585 sub longid{
586 my ($self,$value) = @_;
587 if( defined $value) {
588 $self->{'_longid'} = $value;
589 }
590 return $self->{'_longid'} || 0;
591 }
592  
593 1;