[Bio] / FigKernelPackages / gjoseqlib.pm Repository:
ViewVC logotype

Diff of /FigKernelPackages/gjoseqlib.pm

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 1.3, Mon Dec 5 19:06:30 2005 UTC revision 1.8, Tue Jun 26 15:20:16 2007 UTC
# Line 1  Line 1 
 #  
 # Copyright (c) 2003-2006 University of Chicago and Fellowship  
 # for Interpretations of Genomes. All Rights Reserved.  
 #  
 # This file is part of the SEED Toolkit.  
 #  
 # The SEED Toolkit is free software. You can redistribute  
 # it and/or modify it under the terms of the SEED Toolkit  
 # Public License.  
 #  
 # You should have received a copy of the SEED Toolkit Public License  
 # along with this program; if not write to the University of Chicago  
 # at info@ci.uchicago.edu or the Fellowship for Interpretation of  
 # Genomes at veronika@thefig.info or download a copy from  
 # http://www.theseed.org/LICENSE.TXT.  
 #  
   
1  package gjoseqlib;  package gjoseqlib;
2    use Carp;
3    
4  #  A sequence entry is ( $id, $def, $seq )  #  A sequence entry is ( $id, $def, $seq )
5  #  A list of entries is a list of references  #  A list of entries is a list of references
6  #  #
7  #  @seq_entry = read_next_fasta_seq( *FILEHANDLE )  #  @seq_entry   = read_next_fasta_seq( \*FILEHANDLE )
8  #  @seq_entries = read_fasta_seqs( *FILEHANDLE )  #  @seq_entries = read_fasta_seqs( \*FILEHANDLE )   # Original form
9  #  $seq_ind = index_seq_list( @seq_entries ); # hash from ids to entry refs  #  @seq_entries = read_fasta( )                     # STDIN
10    #  @seq_entries = read_fasta( \*FILEHANDLE )
11    #  @seq_entries = read_fasta(  $filename )
12    #  @seq_entries = read_clustal( )                   # STDIN
13    #  @seq_entries = read_clustal( \*FILEHANDLE )
14    #  @seq_entries = read_clustal(  $filename )
15    #  @seq_entries = read_clustal_file(  $filename )
16  #  #
17    #  $seq_ind   = index_seq_list( @seq_entries );   # hash from ids to entries
18  #  @seq_entry = seq_entry_by_id( \%seq_index, $seq_id );  #  @seq_entry = seq_entry_by_id( \%seq_index, $seq_id );
19  #  $seq_desc  = seq_desc_by_id(  \%seq_index, $seq_id );  #  $seq_desc  = seq_desc_by_id(  \%seq_index, $seq_id );
20  #  $seq       = seq_data_by_id(  \%seq_index, $seq_id );  #  $seq       = seq_data_by_id(  \%seq_index, $seq_id );
# Line 31  Line 22 
22  #  ( $id, $def ) = parse_fasta_title( $title )  #  ( $id, $def ) = parse_fasta_title( $title )
23  #  ( $id, $def ) = split_fasta_title( $title )  #  ( $id, $def ) = split_fasta_title( $title )
24  #  #
25  #  print_seq_list_as_fasta( *FILEHANDLE, @seq_entry_list );  #  print_seq_list_as_fasta( \*FILEHANDLE, @seq_entry_list );  # Original form
26  #  print_seq_as_fasta( *FILEHANDLE, $id, $desc, $seq) ;  #  print_alignment_as_fasta(                @seq_entry_list ); # STDOUT
27  #  print_seq_as_fasta( *FILEHANDLE, @seq_entry );  #  print_alignment_as_fasta(               \@seq_entry_list ); # STDOUT
28  #  print_gb_locus( *FILEHANDLE, $locus, $def, $accession, $seq )  #  print_alignment_as_fasta( \*FILEHANDLE,  @seq_entry_list );
29    #  print_alignment_as_fasta( \*FILEHANDLE, \@seq_entry_list );
30    #  print_alignment_as_fasta(  $filename,    @seq_entry_list );
31    #  print_alignment_as_fasta(  $filename,   \@seq_entry_list );
32    #  print_alignment_as_phylip(                @seq_entry_list ); # STDOUT
33    #  print_alignment_as_phylip(               \@seq_entry_list ); # STDOUT
34    #  print_alignment_as_phylip( \*FILEHANDLE,  @seq_entry_list );
35    #  print_alignment_as_phylip( \*FILEHANDLE, \@seq_entry_list );
36    #  print_alignment_as_phylip(  $filename,    @seq_entry_list );
37    #  print_alignment_as_phylip(  $filename,   \@seq_entry_list );
38    #  print_alignment_as_nexus(               [ \%label_hash, ]  @seq_entry_list );
39    #  print_alignment_as_nexus(               [ \%label_hash, ] \@seq_entry_list );
40    #  print_alignment_as_nexus( \*FILEHANDLE, [ \%label_hash, ]  @seq_entry_list );
41    #  print_alignment_as_nexus( \*FILEHANDLE, [ \%label_hash, ] \@seq_entry_list );
42    #  print_alignment_as_nexus(  $filename,   [ \%label_hash, ]  @seq_entry_list );
43    #  print_alignment_as_nexus(  $filename,   [ \%label_hash, ] \@seq_entry_list );
44    #  print_seq_as_fasta( \*FILEHANDLE, $id, $desc, $seq) ;
45    #  print_seq_as_fasta( \*FILEHANDLE, @seq_entry );
46    #  print_gb_locus( \*FILEHANDLE, $locus, $def, $accession, $seq );
47    #
48    #   @packed_seqs = pack_alignment(  @seqs )
49    #   @packed_seqs = pack_alignment( \@seqs )
50    #  \@packed_seqs = pack_alignment(  @seqs )
51    #  \@packed_seqs = pack_alignment( \@seqs )
52  #  #
53  #  @entry  = subseq_DNA_entry( @seq_entry, $from, $to [, $fix_id] );  #  @entry  = subseq_DNA_entry( @seq_entry, $from, $to [, $fix_id] );
54  #  @entry  = subseq_RNA_entry( @seq_entry, $from, $to [, $fix_id] );  #  @entry  = subseq_RNA_entry( @seq_entry, $from, $to [, $fix_id] );
# Line 57  Line 71 
71  #  Locations (= oriented intervals) are ( id, start, end )  #  Locations (= oriented intervals) are ( id, start, end )
72  #  Intervals are ( id, left, right )  #  Intervals are ( id, left, right )
73  #  #
74  #  @intervals = read_intervals( *FILEHANDLE )  #  @intervals = read_intervals( \*FILEHANDLE )
75  #  @intervals = read_oriented_intervals( *FILEHANDLE )  #  @intervals = read_oriented_intervals( \*FILEHANDLE )
76  #  @intervals = standardize_intervals( @interval_refs ) # (id, left, right)  #  @intervals = standardize_intervals( @interval_refs ) # (id, left, right)
77  #  @joined    = join_intervals( @interval_refs )  #  @joined    = join_intervals( @interval_refs )
78  #  @intervals = locations_2_intervals( @locations )  #  @intervals = locations_2_intervals( @locations )
79  #  $interval  = locations_2_intervals( $location  )  #  $interval  = locations_2_intervals( $location  )
80  #  @reversed  = reverse_intervals( @interval_refs )      # (id, end, start)  #  @reversed  = reverse_intervals( @interval_refs )      # (id, end, start)
81    #
82    #  Convert GenBank locations to SEED locations
83    #
84    #  @seed_locs = gb_location_2_seed( $contig, @gb_locs )
85    #
86    #  Read quality scores from a fasta-like file:
87    #
88    #  @seq_entries = read_qual( )               #  STDIN
89    # \@seq_entries = read_qual( )               #  STDIN
90    #  @seq_entries = read_qual( \*FILEHANDLE )
91    # \@seq_entries = read_qual( \*FILEHANDLE )
92    #  @seq_entries = read_qual(  $filename )
93    # \@seq_entries = read_qual(  $filename )
94    #
95    
96  use strict;  use strict;
97    
 use gjolib qw( wrap_text );  
   
98  #  Exported global variables:  #  Exported global variables:
99    
100  our @aa_1_letter_order;  # Alpha by 1 letter  our @aa_1_letter_order;  # Alpha by 1 letter
# Line 92  Line 117 
117  our @ISA = qw(Exporter);  our @ISA = qw(Exporter);
118  our @EXPORT = qw(  our @EXPORT = qw(
119          read_fasta_seqs          read_fasta_seqs
120            read_fasta
121          read_next_fasta_seq          read_next_fasta_seq
122            read_clustal_file
123            read_clustal
124          parse_fasta_title          parse_fasta_title
125          split_fasta_title          split_fasta_title
126          print_seq_list_as_fasta          print_seq_list_as_fasta
127            print_alignment_as_fasta
128            print_alignment_as_phylip
129            print_alignment_as_nexus
130          print_seq_as_fasta          print_seq_as_fasta
131          print_gb_locus          print_gb_locus
132    
# Line 104  Line 135 
135          seq_desc_by_id          seq_desc_by_id
136          seq_data_by_id          seq_data_by_id
137    
138            pack_alignment
139    
140          subseq_DNA_entry          subseq_DNA_entry
141          subseq_RNA_entry          subseq_RNA_entry
142          complement_DNA_entry          complement_DNA_entry
# Line 125  Line 158 
158          locations_2_intervals          locations_2_intervals
159          read_oriented_intervals          read_oriented_intervals
160          reverse_intervals          reverse_intervals
161    
162            gb_location_2_seed
163    
164            read_qual
165          );          );
166    
167  our @EXPORT_OK = qw(  our @EXPORT_OK = qw(
# Line 146  Line 183 
183    
184    
185  #-----------------------------------------------------------------------------  #-----------------------------------------------------------------------------
186  #  Read fasta sequences from a file.  #  Helper function for defining an input filehandle:
187    #     filehandle is passed through
188    #     string is taken as file name to be openend
189    #     undef or "" defaults to STDOUT
190    #
191    #    ( \*FH, $name, $close [, $file] ) = input_filehandle( $file );
192    #
193    #-----------------------------------------------------------------------------
194    sub input_filehandle
195    {
196        my $file = shift;
197    
198        #  FILEHANDLE
199    
200        return ( $file, $file, 0 ) if ( ref( $file ) eq "GLOB" );
201    
202        #  Null string or undef
203    
204        return ( \*STDIN, "", 0 ) if ( ! defined( $file ) || ( $file eq "" ) );
205    
206        #  File name
207    
208        if ( ! ref( $file ) )
209        {
210            my $fh;
211            -f $file or die "Could not find input file \"$file\"\n";
212            open( $fh, "<$file" ) || die "Could not open \"$file\" for input\n";
213            return ( $fh, $file, 1 );
214        }
215    
216        #  Some other kind of reference; return the unused value
217    
218        return ( \*STDIN, undef, 0, $file );
219    }
220    
221    
222    #-----------------------------------------------------------------------------
223    #  Read fasta sequences from a filehandle (legacy interface; use read_fasta)
224  #  Save the contents in a list of refs to arrays:  (id, description, seq)  #  Save the contents in a list of refs to arrays:  (id, description, seq)
225  #  #
226  #     @seqs = read_fasta_seqs(*FILEHANDLE)  #     @seq_entries = read_fasta_seqs( \*FILEHANDLE )
227  #-----------------------------------------------------------------------------  #-----------------------------------------------------------------------------
228  sub read_fasta_seqs {  sub read_fasta_seqs { read_fasta( @_ ) }
229      my $fh = shift;  
230      wantarray || die "read_fasta_seqs requires list context\n";  
231    #-----------------------------------------------------------------------------
232    #  Read fasta sequences.
233    #  Save the contents in a list of refs to arrays:  (id, description, seq)
234    #
235    #     @seq_entries = read_fasta( )               #  STDIN
236    #    \@seq_entries = read_fasta( )               #  STDIN
237    #     @seq_entries = read_fasta( \*FILEHANDLE )
238    #    \@seq_entries = read_fasta( \*FILEHANDLE )
239    #     @seq_entries = read_fasta(  $filename )
240    #    \@seq_entries = read_fasta(  $filename )
241    #-----------------------------------------------------------------------------
242    sub read_fasta {
243        my ( $fh, $name, $close, $unused ) = input_filehandle( $_[0] );
244        $unused && die "Bad reference type (" . ref( $unused ) . ") passed to read_fasta\n";
245    
246      my @seqs = ();      my @seqs = ();
247      my ($id, $desc, $seq) = ("", "", "");      my ($id, $desc, $seq) = ("", "", "");
# Line 169  Line 257 
257              $seq .= $_ ;              $seq .= $_ ;
258          }          }
259      }      }
260        close( $fh ) if $close;
261    
262      if ($id && $seq) { push @seqs, [ $id, $desc, $seq ] }      if ($id && $seq) { push @seqs, [ $id, $desc, $seq ] }
263      return @seqs;      return wantarray ? @seqs : \@seqs;
264  }  }
265    
266    
# Line 179  Line 268 
268  #  Read one fasta sequence at a time from a file.  #  Read one fasta sequence at a time from a file.
269  #  Return the contents as an array:  (id, description, seq)  #  Return the contents as an array:  (id, description, seq)
270  #  #
271  #     @seq_entry = read_next_fasta_seq(*FILEHANDLE)  #     @seq_entry = read_next_fasta_seq( \*FILEHANDLE )
272  #-----------------------------------------------------------------------------  #-----------------------------------------------------------------------------
273  #  Reading always overshoots, so save next id and description  #  Reading always overshoots, so save next id and description
274    
# Line 188  Line 277 
277      my %next_header;      my %next_header;
278    
279      sub read_next_fasta_seq {      sub read_next_fasta_seq {
         wantarray || die "read_next_fasta_seq requires list context\n";  
   
280          my $fh = shift;          my $fh = shift;
281          my ( $id, $desc );          my ( $id, $desc );
282    
# Line 206  Line 293 
293              chomp;              chomp;
294              if ( /^>/ ) {        #  new id              if ( /^>/ ) {        #  new id
295                  $next_header{$fh} = $_;                  $next_header{$fh} = $_;
296                  if ( defined($id) && $seq ) { return ($id, $desc, $seq) }                  if ( defined($id) && $seq )
297                    {
298                        return wantarray ? ($id, $desc, $seq) : [$id, $desc, $seq]
299                    }
300                  ( $id, $desc ) = parse_fasta_title( $next_header{$fh} );                  ( $id, $desc ) = parse_fasta_title( $next_header{$fh} );
301                  $seq = "";                  $seq = "";
302              }              }
# Line 219  Line 309 
309          #  Done with file, delete "next header"          #  Done with file, delete "next header"
310    
311          delete $next_header{$fh};          delete $next_header{$fh};
312          return (defined($id) && $seq) ? ($id, $desc, $seq) : () ;          return ( defined($id) && $seq ) ? ( wantarray ? ($id, $desc, $seq)
313                                                          : [$id, $desc, $seq]
314                                              )
315                                            : () ;
316      }      }
317  }  }
318    
319    
320  #-----------------------------------------------------------------------------  #-----------------------------------------------------------------------------
321    #  Read a clustal alignment from a file.
322    #  Save the contents in a list of refs to arrays:  (id, description, seq)
323    #
324    #     @seq_entries = read_clustal_file( $filename )
325    #-----------------------------------------------------------------------------
326    sub read_clustal_file { read_clustal( @_ ) }
327    
328    
329    #-----------------------------------------------------------------------------
330    #  Read a clustal alignment.
331    #  Save the contents in a list of refs to arrays:  (id, description, seq)
332    #
333    #     @seq_entries = read_clustal( )              # STDIN
334    #     @seq_entries = read_clustal( \*FILEHANDLE )
335    #     @seq_entries = read_clustal(  $filename )
336    #-----------------------------------------------------------------------------
337    sub read_clustal {
338        my ( $fh, undef, $close, $unused ) = input_filehandle( shift );
339        $unused && die "Bad reference type (" . ref( $unused ) . ") passed to read_clustal_file\n";
340    
341        my ( %seq, @ids, $line );
342        while ( defined( $line = <$fh> ) )
343        {
344            ( $line =~ /^[A-Za-z0-9]/ ) or next;
345            chomp $line;
346            my @flds = split /\s+/, $line;
347            if ( @flds == 2 )
348            {
349                $seq{ $flds[0] } or push @ids, $flds[0];
350                push @{ $seq{ $flds[0] } }, $flds[1];
351            }
352        }
353        close( $fh ) if $close;
354    
355        map { [ $_, "", join( "", @{$seq{$_}} ) ] } @ids;
356    }
357    
358    
359    #-----------------------------------------------------------------------------
360  #  Parse a fasta file header to id and definition parts  #  Parse a fasta file header to id and definition parts
361  #  #
362  #     ($id, $def) = parse_fasta_title( $title )  #     ($id, $def) = parse_fasta_title( $title )
# Line 250  Line 382 
382    
383    
384  #-----------------------------------------------------------------------------  #-----------------------------------------------------------------------------
385  #  Print list of sequence entries in fasta format  #  Helper function for defining an output filehandle:
386    #     filehandle is passed through
387    #     string is taken as file name to be openend
388    #     undef or "" defaults to STDOUT
389    #
390    #    ( \*FH, $name, $close [, $file] ) = output_filehandle( $file );
391  #  #
 #     print_seq_list_as_fasta(*FILEHANDLE, @seq_entry_list);  
392  #-----------------------------------------------------------------------------  #-----------------------------------------------------------------------------
393  sub print_seq_list_as_fasta {  sub output_filehandle
394      my $fh = shift;  {
395      my @seq_list = @_;      my $file = shift;
396    
397        #  FILEHANDLE
398    
399        return ( $file, $file, 0 ) if ( ref( $file ) eq "GLOB" );
400    
401        #  Null string or undef
402    
403        return ( \*STDOUT, "", 0 ) if ( ! defined( $file ) || ( $file eq "" ) );
404    
405        #  File name
406    
407        if ( ! ref( $file ) )
408        {
409            my $fh;
410            open( $fh, ">$file" ) || die "Could not open output $file\n";
411            return ( $fh, $file, 1 );
412        }
413    
414        #  Some other kind of reference; return the unused value
415    
416        return ( \*STDOUT, undef, 0, $file );
417    }
418    
419    
420    #-----------------------------------------------------------------------------
421    #  Legacy function for printing fasta sequence set:
422    #
423    #     print_seq_list_as_fasta( \*FILEHANDLE, @seq_entry_list );
424    #-----------------------------------------------------------------------------
425    sub print_seq_list_as_fasta { print_alignment_as_fasta( @_ ) }
426    
427    
428    #-----------------------------------------------------------------------------
429    #  Print list of sequence entries in fasta format.
430    #  Missing, undef or "" filename defaults to STDOUT.
431    #
432    #     print_alignment_as_fasta(                @seq_entry_list ); # STDOUT
433    #     print_alignment_as_fasta(               \@seq_entry_list ); # STDOUT
434    #     print_alignment_as_fasta( \*FILEHANDLE,  @seq_entry_list );
435    #     print_alignment_as_fasta( \*FILEHANDLE, \@seq_entry_list );
436    #     print_alignment_as_fasta(  $filename,    @seq_entry_list );
437    #     print_alignment_as_fasta(  $filename,   \@seq_entry_list );
438    #-----------------------------------------------------------------------------
439    sub print_alignment_as_fasta {
440        my ( $fh, undef, $close, $unused ) = output_filehandle( shift );
441        ( unshift @_, $unused ) if $unused;
442    
443        ( ref( $_[0] ) eq "ARRAY" ) or confess "Bad sequence entry passed to print_alignment_as_fasta\n";
444    
445        #  Expand the sequence entry list if necessary:
446    
447        if ( ref( $_[0]->[0] ) eq "ARRAY" ) { @_ = @{ $_[0] } }
448    
449        foreach my $seq_ptr ( @_ ) { print_seq_as_fasta( $fh, @$seq_ptr ) }
450    
451        close( $fh ) if $close;
452    }
453    
454    
455    #-----------------------------------------------------------------------------
456    #  Print list of sequence entries in phylip format.
457    #  Missing, undef or "" filename defaults to STDOUT.
458    #
459    #     print_alignment_as_phylip(                @seq_entry_list ); # STDOUT
460    #     print_alignment_as_phylip(               \@seq_entry_list ); # STDOUT
461    #     print_alignment_as_phylip( \*FILEHANDLE,  @seq_entry_list );
462    #     print_alignment_as_phylip( \*FILEHANDLE, \@seq_entry_list );
463    #     print_alignment_as_phylip(  $filename,    @seq_entry_list );
464    #     print_alignment_as_phylip(  $filename,   \@seq_entry_list );
465    #-----------------------------------------------------------------------------
466    sub print_alignment_as_phylip {
467        my ( $fh, undef, $close, $unused ) = output_filehandle( shift );
468        ( unshift @_, $unused ) if $unused;
469    
470        ( ref( $_[0] ) eq "ARRAY" ) or die die "Bad sequence entry passed to print_alignment_as_phylip\n";
471    
472        my @seq_list = ( ref( $_[0]->[0] ) eq "ARRAY" ) ? @{ $_[0] } : @_;
473    
474        my ( %id2, %used );
475        my $maxlen = 0;
476        foreach ( @seq_list )
477        {
478            my ( $id, undef, $seq ) = @$_;
479    
480            #  Need a name that is unique within 10 characters
481    
482            my $id2 = substr( $id, 0, 10 );
483            $id2 =~ s/_/ /g;  # PHYLIP sequence files accept spaces
484            my $n = "0";
485            while ( $used{ $id2 } )
486            {
487                $n++;
488                $id2 = substr( $id, 0, 10 - length( $n ) ) . $n;
489            }
490            $used{ $id2 } = 1;
491            $id2{ $id } = $id2;
492    
493      foreach my $seq_ptr (@seq_list) {                  #  Prepare to pad sequences (should not be necessary, but ...)
494          print_seq_as_fasta($fh, @$seq_ptr);  
495            my $len = length( $seq );
496            $maxlen = $len if ( $len > $maxlen );
497        }
498    
499        my $nseq = @seq_list;
500        print $fh "$nseq  $maxlen\n";
501        foreach ( @seq_list )
502        {
503            my ( $id, undef, $seq ) = @$_;
504            my $len = length( $seq );
505            printf $fh "%-10s  %s%s\n", $id2{ $id },
506                                        $seq,
507                                        $len<$maxlen ? ("?" x ($maxlen-$len)) : "";
508      }      }
509    
510        close( $fh ) if $close;
511    }
512    
513    
514    #-----------------------------------------------------------------------------
515    #  Print list of sequence entries in nexus format.
516    #  Missing, undef or "" filename defaults to STDOUT.
517    #
518    #     print_alignment_as_nexus(               [ \%label_hash, ]  @seq_entry_list );
519    #     print_alignment_as_nexus(               [ \%label_hash, ] \@seq_entry_list );
520    #     print_alignment_as_nexus( \*FILEHANDLE, [ \%label_hash, ]  @seq_entry_list );
521    #     print_alignment_as_nexus( \*FILEHANDLE, [ \%label_hash, ] \@seq_entry_list );
522    #     print_alignment_as_nexus(  $filename,   [ \%label_hash, ]  @seq_entry_list );
523    #     print_alignment_as_nexus(  $filename,   [ \%label_hash, ] \@seq_entry_list );
524    #-----------------------------------------------------------------------------
525    sub print_alignment_as_nexus {
526        my ( $fh, undef, $close, $unused ) = output_filehandle( shift );
527        ( unshift @_, $unused ) if $unused;
528    
529        my $lbls = ( ref( $_[0] ) eq "HASH" ) ? shift : undef;
530    
531        ( ref( $_[0] ) eq "ARRAY" ) or die "Bad sequence entry passed to print_alignment_as_nexus\n";
532    
533        my @seq_list = ( ref( $_[0]->[0] ) eq "ARRAY" ) ? @{ $_[0] } : @_;
534    
535        my %id2;
536        my ( $maxidlen, $maxseqlen ) = ( 0, 0 );
537        my ( $n1, $n2, $nt, $nu ) = ( 0, 0, 0, 0 );
538        foreach ( @seq_list )
539        {
540            my ( $id, undef, $seq ) = @$_;
541            my $id2 = $lbls ? ( $lbls->{ $id } || $id ) : $id;
542            if ( $id2 !~ /^[-+.0-9A-Za-z~_|]+$/ )
543            {
544                    $id2 =~ s/'/''/g;
545                    $id2 = qq('$id2');
546                }
547            $id2{ $id } = $id2;
548            my $idlen = length( $id2 );
549            $maxidlen = $idlen if ( $idlen > $maxidlen );
550    
551            my $seqlen = length( $seq );
552            $maxseqlen = $seqlen if ( $seqlen > $maxseqlen );
553    
554            $nt += $seq =~ tr/Tt//d;
555            $nu += $seq =~ tr/Uu//d;
556            $n1 += $seq =~ tr/ACGNacgn//d;
557            $n2 += $seq =~ tr/A-Za-z//d;
558        }
559    
560        my $nseq = @seq_list;
561        my $type = ( $n1 < 2 * $n2 ) ?  'protein' : ($nt>$nu) ? 'DNA' : 'RNA';
562    
563        print $fh <<"END_HEAD";
564    #NEXUS
565    
566    BEGIN Data;
567        Dimensions
568            NTax=$nseq
569            NChar=$maxseqlen
570            ;
571        Format
572            DataType=$type
573            Gap=-
574            Missing=?
575            ;
576        Matrix
577    
578    END_HEAD
579    
580        foreach ( @seq_list )
581        {
582            my ( $id, undef, $seq ) = @$_;
583            my $len = length( $seq );
584            printf  $fh  "%-${maxidlen}s  %s%s\n",
585                         $id2{ $id },
586                         $seq,
587                         $len<$maxseqlen ? ("?" x ($maxseqlen-$len)) : "";
588        }
589    
590        print $fh <<"END_TAIL";
591    ;
592    END;
593    END_TAIL
594    
595        close( $fh ) if $close;
596  }  }
597    
598    
599  #-----------------------------------------------------------------------------  #-----------------------------------------------------------------------------
600  #  Print one sequence in fasta format to an open file  #  Print one sequence in fasta format to an open file
601  #  #
602  #     print_seq_as_fasta(*FILEHANDLE, $id, $desc, $seq);  #     print_seq_as_fasta( \*FILEHANDLE, $id, $desc, $seq );
603  #     print_seq_as_fasta(*FILEHANDLE, @seq_entry);  #     print_seq_as_fasta( \*FILEHANDLE, @seq_entry );
604  #-----------------------------------------------------------------------------  #-----------------------------------------------------------------------------
605  sub print_seq_as_fasta {  sub print_seq_as_fasta {
606      my $fh = shift;      my $fh = shift;
# Line 285  Line 617 
617  #-----------------------------------------------------------------------------  #-----------------------------------------------------------------------------
618  #  Print one sequence in GenBank flat file format:  #  Print one sequence in GenBank flat file format:
619  #  #
620  #     print_gb_locus( *FILEHANDLE, $locus, $def, $accession, $seq )  #     print_gb_locus( \*FILEHANDLE, $locus, $def, $accession, $seq )
621  #-----------------------------------------------------------------------------  #-----------------------------------------------------------------------------
622  sub print_gb_locus {  sub print_gb_locus {
623      my ($fh, $loc, $def, $acc, $seq) = @_;      my ($fh, $loc, $def, $acc, $seq) = @_;
# Line 311  Line 643 
643    
644    
645  #-----------------------------------------------------------------------------  #-----------------------------------------------------------------------------
646    #  Return a string with text wrapped to defined line lengths:
647    #
648    #     $wrapped_text = wrap_text( $str )                  # default len   =  80
649    #     $wrapped_text = wrap_text( $str, $len )            # default ind   =   0
650    #     $wrapped_text = wrap_text( $str, $len, $indent )   # default ind_n = ind
651    #     $wrapped_text = wrap_text( $str, $len, $indent_1, $indent_n )
652    #-----------------------------------------------------------------------------
653    sub wrap_text {
654        my ($str, $len, $ind, $indn) = @_;
655    
656        defined($str)  || die "wrap_text called without a string\n";
657        defined($len)  || ($len  =   80);
658        defined($ind)  || ($ind  =    0);
659        ($ind  < $len) || die "wrap error: indent greater than line length\n";
660        defined($indn) || ($indn = $ind);
661        ($indn < $len) || die "wrap error: indent_n greater than line length\n";
662    
663        $str =~ s/\s+$//;
664        $str =~ s/^\s+//;
665        my ($maxchr, $maxchr1);
666        my (@lines) = ();
667    
668        while ($str) {
669            $maxchr1 = ($maxchr = $len - $ind) - 1;
670            if ($maxchr >= length($str)) {
671                push @lines, (" " x $ind) . $str;
672                last;
673            }
674            elsif ($str =~ /^(.{0,$maxchr1}\S)\s+(\S.*)$/) { # no expr in {}
675                push @lines, (" " x $ind) . $1;
676                $str = $2;
677            }
678            elsif ($str =~ /^(.{0,$maxchr1}-)(.*)$/) {
679                push @lines, (" " x $ind) . $1;
680                $str = $2;
681            }
682            else {
683                push @lines, (" " x $ind) . substr($str, 0, $maxchr);
684                $str = substr($str, $maxchr);
685            }
686            $ind = $indn;
687        }
688    
689        return join("\n", @lines);
690    }
691    
692    
693    #-----------------------------------------------------------------------------
694  #  Build an index from seq_id to pointer to sequence entry: (id, desc, seq)  #  Build an index from seq_id to pointer to sequence entry: (id, desc, seq)
695  #  #
696  #     my \%seq_ind  = index_seq_list(@seq_list);  #     my \%seq_ind  = index_seq_list(@seq_list);
697    #     my \%seq_ind  = index_seq_list( \@seq_list );
698  #  #
699  #  Usage example:  #  Usage example:
700  #  #
701  #  my @seq_list   = read_fasta_seqs(*STDIN);   # list of pointers to entries  #  my  @seq_list   = read_fasta_seqs(\*STDIN);  # list of pointers to entries
702  #  my \%seq_ind   = index_seq_list(@seq_list); # hash from names to pointers  #  my \%seq_ind   = index_seq_list(@seq_list); # hash from names to pointers
703  #  my @chosen_seq = @{%seq_ind{"contig1"}};    # extract one entry  #  my @chosen_seq = @{%seq_ind{"contig1"}};    # extract one entry
704  #  #
705  #-----------------------------------------------------------------------------  #-----------------------------------------------------------------------------
706  sub index_seq_list {  sub index_seq_list {
707      my %seq_index = map { @{$_}[0] => $_ } @_;      ( ref( $_[0] )      ne 'ARRAY' ) ? {}
708      return \%seq_index;    : ( ref( $_[0]->[0] ) ne 'ARRAY' ) ? { map { $_->[0] => $_ } @_ }
709      :                                    { map { $_->[0] => $_ } @{ $_[0] } }
710  }  }
711    
712    
713  #-----------------------------------------------------------------------------  #-----------------------------------------------------------------------------
714  #  Three routines to access all or part of sequence entry by id:  #  Three routines to access all or part of sequence entry by id:
715  #  #
716  #     my @seq_entry  = seq_entry_by_id( \%seq_index, $seq_id );  #     @seq_entry = seq_entry_by_id( \%seq_index, $seq_id );
717  #     my $seq_desc   = seq_desc_by_id(  \%seq_index, $seq_id );  #    \@seq_entry = seq_entry_by_id( \%seq_index, $seq_id );
718  #     my $seq        = seq_data_by_id(  \%seq_index, $seq_id );  #     $seq_desc  = seq_desc_by_id(  \%seq_index, $seq_id );
719    #     $seq       = seq_data_by_id(  \%seq_index, $seq_id );
720  #  #
721  #-----------------------------------------------------------------------------  #-----------------------------------------------------------------------------
722  sub seq_entry_by_id {  sub seq_entry_by_id {
723      (my $ind_ref = shift)  || die "No index supplied to seq_entry_by_id\n";      (my $ind_ref = shift)  || die "No index supplied to seq_entry_by_id\n";
724      (my $id      = shift)  || die "No id supplied to seq_entry_by_id\n";      (my $id      = shift)  || die "No id supplied to seq_entry_by_id\n";
725      wantarray || die "entry_by_id requires list context\n";      return wantarray ? @{ $ind_ref->{$id} } : $ind_ref->{$id};
     return @{ $ind_ref->{$id} };  
726  }  }
727    
728    
# Line 357  Line 739 
739      return ${ $ind_ref->{$id} }[2];      return ${ $ind_ref->{$id} }[2];
740  }  }
741    
742    #-----------------------------------------------------------------------------
743    #  Remove columns of alignment gaps from sequences:
744    #
745    #   @packed_seqs = pack_alignment(  @seqs )
746    #   @packed_seqs = pack_alignment( \@seqs )
747    #  \@packed_seqs = pack_alignment(  @seqs )
748    #  \@packed_seqs = pack_alignment( \@seqs )
749    #
750    #-----------------------------------------------------------------------------
751    
752    sub pack_alignment
753    {
754        my @seqs = ( ref( $_[0] ) eq 'ARRAY' and ref( $_[0]->[0] ) eq 'ARRAY' ) ? @{$_[0] } : @_;
755        @seqs or return wantarray ? () : [];
756    
757        my $mask  = pack_mask( $seqs[0]->[2] );
758        foreach ( @seqs[ 1 .. (@seqs-1) ] )
759        {
760            $mask |= pack_mask( $_->[2] );
761        }
762    
763        my $seq;
764        my @seqs2 = map { $seq = $_->[2] & $mask;
765                          $seq =~ tr/\000//d;
766                          [ $_->[0], $_->[1], $seq ]
767                        }
768                    @seqs;
769    
770        return wantarray ? @seqs2 : \@seqs2;
771    }
772    
773    sub pack_mask
774    {
775        my $mask = shift;
776        $mask =~ tr/-/\000/;
777        $mask =~ tr/\000/\377/c;
778        return $mask;
779    }
780    
781  #-----------------------------------------------------------------------------  #-----------------------------------------------------------------------------
782  #  Some simple sequence manipulations:  #  Some simple sequence manipulations:
# Line 849  Line 1269 
1269  );  );
1270    
1271    
1272  %one_letter_to_three_letter_aa = {  %one_letter_to_three_letter_aa = (
1273           A  => "Ala", a  => "Ala",           A  => "Ala", a  => "Ala",
1274           B  => "Asx", b  => "Asx",           B  => "Asx", b  => "Asx",
1275           C  => "Cys", c  => "Cys",           C  => "Cys", c  => "Cys",
# Line 875  Line 1295 
1295           Y  => "Tyr", y  => "Tyr",           Y  => "Tyr", y  => "Tyr",
1296           Z  => "Glx", z  => "Glx",           Z  => "Glx", z  => "Glx",
1297          '*' => "***"          '*' => "***"
1298          };          );
1299    
1300    
1301  %three_letter_to_one_letter_aa = (  %three_letter_to_one_letter_aa = (
# Line 1134  Line 1554 
1554  #  Read a list of intervals from a file.  #  Read a list of intervals from a file.
1555  #  Allow id_start_end, or id \s start \s end formats  #  Allow id_start_end, or id \s start \s end formats
1556  #  #
1557  #     @intervals = read_intervals( *FILEHANDLE )  #     @intervals = read_intervals( \*FILEHANDLE )
1558  #-----------------------------------------------------------------------------  #-----------------------------------------------------------------------------
1559  sub read_intervals {  sub read_intervals {
1560      my $fh = shift;      my $fh = shift;
# Line 1230  Line 1650 
1650  #  Read a list of oriented intervals from a file.  #  Read a list of oriented intervals from a file.
1651  #  Allow id_start_end, or id \s start \s end formats  #  Allow id_start_end, or id \s start \s end formats
1652  #  #
1653  #     @intervals = read_oriented_intervals( *FILEHANDLE )  #     @intervals = read_oriented_intervals( \*FILEHANDLE )
1654  #-----------------------------------------------------------------------------  #-----------------------------------------------------------------------------
1655  sub read_oriented_intervals {  sub read_oriented_intervals {
1656      my $fh = shift;      my $fh = shift;
# Line 1261  Line 1681 
1681  }  }
1682    
1683    
1684    #-----------------------------------------------------------------------------
1685    #  Convert GenBank locations to SEED locations
1686    #
1687    #     @seed_locs = gb_location_2_seed( $contig, @gb_locs )
1688    #-----------------------------------------------------------------------------
1689    sub gb_location_2_seed
1690    {
1691        my $contig = shift @_;
1692        $contig or die "First arg of gb_location_2_seed must be contig_id\n";
1693    
1694        map { join( ',', gb_loc_2_seed_2( $contig, $_ ) ) || undef } @_
1695    }
1696    
1697    sub gb_loc_2_seed_2
1698    {
1699        my ( $contig, $loc ) = @_;
1700    
1701        if ( $loc =~ /^(\d+)\.\.(\d+)$/ )
1702        {
1703            join( '_', $contig, $1, $2 )
1704        }
1705    
1706        elsif ( $loc =~ /^join\((.*)\)$/ )
1707        {
1708            $loc = $1;
1709            my $lvl = 0;
1710            for ( my $i = length( $loc )-1; $i >= 0; $i-- )
1711            {
1712                for ( substr( $loc, $i, 1 ) )
1713                {
1714                    /,/ && ! $lvl and substr( $loc, $i, 1 ) = "\t";
1715                    /\(/          and $lvl--;
1716                    /\)/          and $lvl++;
1717                }
1718            }
1719            $lvl == 0 or print STDERR "Paren matching error: $loc\n" and die;
1720            map { gb_loc_2_seed_2( $contig, $_ ) } split /\t/, $loc
1721        }
1722    
1723        elsif ( $loc =~ /^complement\((.*)\)$/ )
1724        {
1725            map { s/_(\d+)_(\d+)$/_$2_$1/; $_ }
1726            reverse
1727            gb_loc_2_seed_2( $contig, $1 )
1728        }
1729    
1730        else
1731        {
1732            ()
1733        }
1734    }
1735    
1736    
1737    #-----------------------------------------------------------------------------
1738    #  Read qual.
1739    #
1740    #  Save the contents in a list of refs to arrays: [ $id, $descript, \@qual ]
1741    #
1742    #     @seq_entries = read_qual( )               #  STDIN
1743    #    \@seq_entries = read_qual( )               #  STDIN
1744    #     @seq_entries = read_qual( \*FILEHANDLE )
1745    #    \@seq_entries = read_qual( \*FILEHANDLE )
1746    #     @seq_entries = read_qual(  $filename )
1747    #    \@seq_entries = read_qual(  $filename )
1748    #-----------------------------------------------------------------------------
1749    sub read_qual {
1750        my ( $fh, $name, $close, $unused ) = input_filehandle( $_[0] );
1751        $unused && die "Bad reference type (" . ref( $unused ) . ") passed to read_qual\n";
1752    
1753        my @quals = ();
1754        my ($id, $desc, $qual) = ("", "", []);
1755    
1756        while ( <$fh> ) {
1757            chomp;
1758            if (/^>\s*(\S+)(\s+(.*))?$/) {        #  new id
1759                if ($id && @$qual) { push @quals, [ $id, $desc, $qual ] }
1760                ($id, $desc, $qual) = ($1, $3 ? $3 : "", []);
1761            }
1762            else {
1763                push @$qual, split;
1764            }
1765        }
1766        close( $fh ) if $close;
1767    
1768        if ($id && @$qual) { push @quals, [ $id, $desc, $qual ] }
1769        return wantarray ? @quals : \@quals;
1770    }
1771    
1772    
1773  1;  1;

Legend:
Removed from v.1.3  
changed lines
  Added in v.1.8

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3