[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.6, Sun Jun 10 17:24:38 2007 UTC revision 1.20, Sun Aug 29 22:13:28 2010 UTC
# Line 1  Line 1 
1  package gjoseqlib;  package gjoseqlib;
2    
3    # This is a SAS component.
4    
5  #  A sequence entry is ( $id, $def, $seq )  #  A sequence entry is ( $id, $def, $seq )
6  #  A list of entries is a list of references  #  A list of entries is a list of references
7  #  #
8  #  @seq_entry   = read_next_fasta_seq( \*FILEHANDLE )  #  Efficient reading of an entire file of sequences:
9  #  @seq_entries = read_fasta_seqs( \*FILEHANDLE )   # Original form  #
10  #  @seq_entries = read_fasta( )                     # STDIN  #  @seq_entries = read_fasta( )                     # STDIN
11  #  @seq_entries = read_fasta( \*FILEHANDLE )  #  @seq_entries = read_fasta( \*FILEHANDLE )
12  #  @seq_entries = read_fasta(  $filename )  #  @seq_entries = read_fasta(  $filename )
13    #
14    #  Reading sequences one at a time to conserve memory.  Calls to different
15    #  files can be intermixed.
16    #
17    #  @entry = read_next_fasta_seq( \*FILEHANDLE )
18    # \@entry = read_next_fasta_seq( \*FILEHANDLE )
19    #  @entry = read_next_fasta_seq(  $filename )
20    # \@entry = read_next_fasta_seq(  $filename )
21    #  @entry = read_next_fasta_seq()                   # STDIN
22    # \@entry = read_next_fasta_seq()                   # STDIN
23    #
24    #  Legacy interface:
25    #  @seq_entries = read_fasta_seqs( \*FILEHANDLE )   # Original form
26    #
27    #  Reading clustal alignment.
28    #
29  #  @seq_entries = read_clustal( )                   # STDIN  #  @seq_entries = read_clustal( )                   # STDIN
30  #  @seq_entries = read_clustal( \*FILEHANDLE )  #  @seq_entries = read_clustal( \*FILEHANDLE )
31  #  @seq_entries = read_clustal(  $filename )  #  @seq_entries = read_clustal(  $filename )
32    #
33    #  Legacy interface:
34  #  @seq_entries = read_clustal_file(  $filename )  #  @seq_entries = read_clustal_file(  $filename )
35  #  #
36  #  $seq_ind   = index_seq_list( @seq_entries );   # hash from ids to entries  #  $seq_ind   = index_seq_list( @seq_entries );   # hash from ids to entries
# Line 21  Line 41 
41  #  ( $id, $def ) = parse_fasta_title( $title )  #  ( $id, $def ) = parse_fasta_title( $title )
42  #  ( $id, $def ) = split_fasta_title( $title )  #  ( $id, $def ) = split_fasta_title( $title )
43  #  #
44  #  print_seq_list_as_fasta( \*FILEHANDLE, @seq_entry_list );  # Original form  #  Write a fasta format file from sequences.
45    #
46  #  print_alignment_as_fasta(                @seq_entry_list ); # STDOUT  #  print_alignment_as_fasta(                @seq_entry_list ); # STDOUT
47  #  print_alignment_as_fasta(               \@seq_entry_list ); # STDOUT  #  print_alignment_as_fasta(               \@seq_entry_list ); # STDOUT
48  #  print_alignment_as_fasta( \*FILEHANDLE,  @seq_entry_list );  #  print_alignment_as_fasta( \*FILEHANDLE,  @seq_entry_list );
49  #  print_alignment_as_fasta( \*FILEHANDLE, \@seq_entry_list );  #  print_alignment_as_fasta( \*FILEHANDLE, \@seq_entry_list );
50  #  print_alignment_as_fasta(  $filename,    @seq_entry_list );  #  print_alignment_as_fasta(  $filename,    @seq_entry_list );
51  #  print_alignment_as_fasta(  $filename,   \@seq_entry_list );  #  print_alignment_as_fasta(  $filename,   \@seq_entry_list );
52    #
53    #  Legacy interface:
54    #  print_seq_list_as_fasta( \*FILEHANDLE, @seq_entry_list );  # Original form
55    #
56    #  Interface that it really meant for internal use to write the next sequence
57    #  to an open file:
58    #
59    #  print_seq_as_fasta( \*FILEHANDLE, $id, $desc, $seq );
60    #  print_seq_as_fasta(               $id, $desc, $seq );
61    #  print_seq_as_fasta( \*FILEHANDLE, $id,        $seq );
62    #  print_seq_as_fasta(               $id,        $seq );
63    #
64    #  Write PHYLIP alignment.  Names might be altered to fit 10 character limit:
65    #
66  #  print_alignment_as_phylip(                @seq_entry_list ); # STDOUT  #  print_alignment_as_phylip(                @seq_entry_list ); # STDOUT
67  #  print_alignment_as_phylip(               \@seq_entry_list ); # STDOUT  #  print_alignment_as_phylip(               \@seq_entry_list ); # STDOUT
68  #  print_alignment_as_phylip( \*FILEHANDLE,  @seq_entry_list );  #  print_alignment_as_phylip( \*FILEHANDLE,  @seq_entry_list );
69  #  print_alignment_as_phylip( \*FILEHANDLE, \@seq_entry_list );  #  print_alignment_as_phylip( \*FILEHANDLE, \@seq_entry_list );
70  #  print_alignment_as_phylip(  $filename,    @seq_entry_list );  #  print_alignment_as_phylip(  $filename,    @seq_entry_list );
71  #  print_alignment_as_phylip(  $filename,   \@seq_entry_list );  #  print_alignment_as_phylip(  $filename,   \@seq_entry_list );
72    #
73    #  Write basic NEXUS alignment for PAUP.
74    #
75  #  print_alignment_as_nexus(               [ \%label_hash, ]  @seq_entry_list );  #  print_alignment_as_nexus(               [ \%label_hash, ]  @seq_entry_list );
76  #  print_alignment_as_nexus(               [ \%label_hash, ] \@seq_entry_list );  #  print_alignment_as_nexus(               [ \%label_hash, ] \@seq_entry_list );
77  #  print_alignment_as_nexus( \*FILEHANDLE, [ \%label_hash, ]  @seq_entry_list );  #  print_alignment_as_nexus( \*FILEHANDLE, [ \%label_hash, ]  @seq_entry_list );
78  #  print_alignment_as_nexus( \*FILEHANDLE, [ \%label_hash, ] \@seq_entry_list );  #  print_alignment_as_nexus( \*FILEHANDLE, [ \%label_hash, ] \@seq_entry_list );
79  #  print_alignment_as_nexus(  $filename,   [ \%label_hash, ]  @seq_entry_list );  #  print_alignment_as_nexus(  $filename,   [ \%label_hash, ]  @seq_entry_list );
80  #  print_alignment_as_nexus(  $filename,   [ \%label_hash, ] \@seq_entry_list );  #  print_alignment_as_nexus(  $filename,   [ \%label_hash, ] \@seq_entry_list );
81  #  print_seq_as_fasta( \*FILEHANDLE, $id, $desc, $seq) ;  #
 #  print_seq_as_fasta( \*FILEHANDLE, @seq_entry );  
82  #  print_gb_locus( \*FILEHANDLE, $locus, $def, $accession, $seq );  #  print_gb_locus( \*FILEHANDLE, $locus, $def, $accession, $seq );
83  #  #
84    #  Remove extra columns of alignment gaps from an alignment:
85    #
86  #   @packed_seqs = pack_alignment(  @seqs )  #   @packed_seqs = pack_alignment(  @seqs )
87  #   @packed_seqs = pack_alignment( \@seqs )  #   @packed_seqs = pack_alignment( \@seqs )
88  #  \@packed_seqs = pack_alignment(  @seqs )  #  \@packed_seqs = pack_alignment(  @seqs )
89  #  \@packed_seqs = pack_alignment( \@seqs )  #  \@packed_seqs = pack_alignment( \@seqs )
90  #  #
91    #  Pack mask for an alignment (gap = 0x00, others are 0xFF)
92    #
93    #   $mask = alignment_gap_mask(  @seqs )
94    #   $mask = alignment_gap_mask( \@seqs )
95    #
96    #  Pack a sequence alignment according to a mask:
97    #
98    #   @packed = pack_alignment_by_mask( $mask,  @align )
99    #   @packed = pack_alignment_by_mask( $mask, \@align )
100    #  \@packed = pack_alignment_by_mask( $mask,  @align )
101    #  \@packed = pack_alignment_by_mask( $mask, \@align )
102    #
103    #  Expand sequence by a mask, adding indel at "\000" or '-' in mask:
104    #
105    #   $expanded = expand_sequence_by_mask( $seq, $mask )
106    #
107    #  Remove all alignment gaps from sequences:
108    #
109    #   @packed_seqs = pack_sequences(  @seqs )  #  Works for one sequence, too
110    #   @packed_seqs = pack_sequences( \@seqs )
111    #  \@packed_seqs = pack_sequences(  @seqs )
112    #  \@packed_seqs = pack_sequences( \@seqs )
113    #
114    # Basic sequence manipulation functions:
115    #
116  #  @entry  = subseq_DNA_entry( @seq_entry, $from, $to [, $fix_id] );  #  @entry  = subseq_DNA_entry( @seq_entry, $from, $to [, $fix_id] );
117  #  @entry  = subseq_RNA_entry( @seq_entry, $from, $to [, $fix_id] );  #  @entry  = subseq_RNA_entry( @seq_entry, $from, $to [, $fix_id] );
118    #  $DNAseq = DNA_subseq(  $seq, $from, $to );
119    #  $DNAseq = DNA_subseq( \$seq, $from, $to );
120    #  $RNAseq = RNA_subseq(  $seq, $from, $to );
121    #  $RNAseq = RNA_subseq( \$seq, $from, $to );
122  #  @entry  = complement_DNA_entry( @seq_entry [, $fix_id] );  #  @entry  = complement_DNA_entry( @seq_entry [, $fix_id] );
123  #  @entry  = complement_RNA_entry( @seq_entry [, $fix_id] );  #  @entry  = complement_RNA_entry( @seq_entry [, $fix_id] );
124  #  $DNAseq = complement_DNA_seq( $NA_seq );  #  $DNAseq = complement_DNA_seq( $NA_seq );
# Line 60  Line 128 
128  #  $seq    = pack_seq( $sequence )  #  $seq    = pack_seq( $sequence )
129  #  $seq    = clean_ae_sequence( $seq )  #  $seq    = clean_ae_sequence( $seq )
130  #  #
131  #  $seq = translate_seq( $seq [, $met_start] )  #  $aa = translate_seq( $nt, $met_start )
132    #  $aa = translate_seq( $nt )
133  #  $aa  = translate_codon( $triplet );  #  $aa  = translate_codon( $triplet );
 #  $aa  = translate_uc_DNA_codon( $upcase_DNA_triplet );  
134  #  #
135  #  User-supplied genetic code must be upper case index and match the  #  User-supplied genetic code.  The supplied code needs to be complete in
136  #  DNA versus RNA type of sequence  #  RNA and/or DNA, and upper and/or lower case.  The program guesses based
137    #  on lysine and phenylalanine codons.
138    #
139    #  $aa = translate_seq_with_user_code( $nt, $gen_code_hash, $met_start )
140    #  $aa = translate_seq_with_user_code( $nt, $gen_code_hash )
141  #  #
142  #  Locations (= oriented intervals) are ( id, start, end )  #  Locations (= oriented intervals) are ( id, start, end )
143  #  Intervals are ( id, left, right )  #  Intervals are ( id, left, right )
# Line 81  Line 153 
153  #  Convert GenBank locations to SEED locations  #  Convert GenBank locations to SEED locations
154  #  #
155  #  @seed_locs = gb_location_2_seed( $contig, @gb_locs )  #  @seed_locs = gb_location_2_seed( $contig, @gb_locs )
156    #
157    #  Read quality scores from a fasta-like file:
158    #
159    #  @seq_entries = read_qual( )               #  STDIN
160    # \@seq_entries = read_qual( )               #  STDIN
161    #  @seq_entries = read_qual( \*FILEHANDLE )
162    # \@seq_entries = read_qual( \*FILEHANDLE )
163    #  @seq_entries = read_qual(  $filename )
164    # \@seq_entries = read_qual(  $filename )
165    #
166    #  Evaluate alignments:
167    #
168    #  $fraction_diff = fraction_nt_diff( $seq1, $seq2, \%options )
169    #  $fraction_diff = fraction_nt_diff( $seq1, $seq2 )
170    #  $fraction_diff = fraction_nt_diff( $seq1, $seq2, $gap_weight )
171    #  $fraction_diff = fraction_nt_diff( $seq1, $seq2, $gap_open, $gap_extend )
172    #
173    #  ( $npos, $nid, $ndif, $ngap, $nopen, $tgap, $topen ) = interpret_nt_align( $seq1, $seq2 )
174    #  ( $npos, $nid, $ndif, $ngap, $nopen, $tgap, $topen ) = interpret_aa_align( $seq1, $seq2 )
175    #
176    
177  use strict;  use strict;
178    use Carp;
179  use gjolib qw( wrap_text );  use Data::Dumper;
180    
181  #  Exported global variables:  #  Exported global variables:
182    
# Line 128  Line 219 
219          seq_data_by_id          seq_data_by_id
220    
221          pack_alignment          pack_alignment
222            alignment_gap_mask
223            pack_alignment_by_mask
224            expand_sequence_by_mask
225            pack_sequences
226    
227          subseq_DNA_entry          subseq_DNA_entry
228          subseq_RNA_entry          subseq_RNA_entry
229            DNA_subseq
230            RNA_subseq
231          complement_DNA_entry          complement_DNA_entry
232          complement_RNA_entry          complement_RNA_entry
233          complement_DNA_seq          complement_DNA_seq
# Line 152  Line 249 
249          reverse_intervals          reverse_intervals
250    
251          gb_location_2_seed          gb_location_2_seed
252    
253            read_qual
254    
255            fraction_nt_diff
256            interpret_nt_align
257            interpret_aa_align
258          );          );
259    
260  our @EXPORT_OK = qw(  our @EXPORT_OK = qw(
# Line 198  Line 301 
301      if ( ! ref( $file ) )      if ( ! ref( $file ) )
302      {      {
303          my $fh;          my $fh;
304          -f $file or die "Could not find input file \"$file\"\n";          if    ( -f $file                       ) { }
305          open( $fh, "<$file" ) || die "Could not open \"$file\" for input\n";          elsif (    $file =~ /^>(.+)$/ && -f $1 ) { $file = $1 }
306            else { die "Could not find input file '$file'\n" }
307            open( $fh, "<$file" ) || die "Could not open '$file' for input\n";
308          return ( $fh, $file, 1 );          return ( $fh, $file, 1 );
309      }      }
310    
# Line 219  Line 324 
324    
325    
326  #-----------------------------------------------------------------------------  #-----------------------------------------------------------------------------
327  #  Read fasta sequences.  #  Read fasta sequences.  Save the contents in a list of refs to arrays:
328  #  Save the contents in a list of refs to arrays:  (id, description, seq)  #
329    #     $seq_entry = [ id, description, seq ]
330  #  #
331  #     @seq_entries = read_fasta( )               #  STDIN  #     @seq_entries = read_fasta( )               #  STDIN
332  #    \@seq_entries = read_fasta( )               #  STDIN  #    \@seq_entries = read_fasta( )               #  STDIN
# Line 228  Line 334 
334  #    \@seq_entries = read_fasta( \*FILEHANDLE )  #    \@seq_entries = read_fasta( \*FILEHANDLE )
335  #     @seq_entries = read_fasta(  $filename )  #     @seq_entries = read_fasta(  $filename )
336  #    \@seq_entries = read_fasta(  $filename )  #    \@seq_entries = read_fasta(  $filename )
337    #  #  @seq_entries = read_fasta( "command |" )   #  open and read from pipe
338    #  # \@seq_entries = read_fasta( "command |" )   #  open and read from pipe
339    #     @seq_entries = read_fasta( \$string )      #  reference to file as string
340    #    \@seq_entries = read_fasta( \$string )      #  reference to file as string
341    #
342    #-----------------------------------------------------------------------------
343    sub read_fasta
344    {
345        my @seqs;
346        if ( $_[0] && ref $_[0] eq 'SCALAR' )
347        {
348            @seqs = map { $_->[2] =~ tr/ \n\r\t//d; $_ }
349                    map { /^(\S+)([ \t]+([^\n]*\S)?\s*)?\n(.+)$/s ? [ $1, $3 || '', $4 ] : () }
350                    split /^>\s*/m, ${$_[0]};
351        }
352        else
353        {
354            @seqs = map { $_->[2] =~ tr/ \n\r\t//d; $_ }
355                    map { /^(\S+)([ \t]+([^\n]*\S)?\s*)?\n(.+)$/s ? [ $1, $3 || '', $4 ] : () }
356                    split /^>\s*/m, slurp( @_ );
357        }
358    
359        wantarray() ? @seqs : \@seqs;
360    }
361    
362    #-----------------------------------------------------------------------------
363    #  A fast file reader:
364    #
365    #     $data = slurp( )               #  \*STDIN
366    #     $data = slurp( \*FILEHANDLE )  #  an open file handle
367    #     $data = slurp(  $filename )    #  a file name
368    #     $data = slurp( "<$filename" )  #  file with explicit direction
369    #   # $data = slurp( "$command |" )  #  open and read from pipe
370    #
371    #  Note:  It is faster to read lines by reading the file and splitting
372    #         than by reading the lines sequentially.  If space is not an
373    #         issue, this is the way to go.  If space is an issue, then lines
374    #         or records should be processed one-by-one (rather than loading
375    #         the whole input into a string or array).
376    #-----------------------------------------------------------------------------
377    sub slurp
378    {
379        my ( $fh, $close );
380        if ( ref $_[0] eq 'GLOB' )
381        {
382            $fh = shift;
383        }
384        elsif ( $_[0] && ! ref $_[0] )
385        {
386            my $file = shift;
387            if    ( -f $file                       ) { $file = "<$file" }
388            elsif (    $file =~ /^<(.*)$/ && -f $1 ) { }  # Explicit read
389          # elsif (    $file =~ /\S\s*\|$/         ) { }  # Read from a pipe
390            else                                     { return undef }
391            open $fh, $file or return undef;
392            $close = 1;
393        }
394        else
395        {
396            $fh = \*STDIN;
397            $close = 0;
398        }
399    
400        my $out = '';
401        my $inc = 1048576;
402        my $end =       0;
403        my $read;
404        while ( $read = read( $fh, $out, $inc, $end ) ) { $end += $read }
405        close( $fh ) if $close;
406    
407        $out;
408    }
409    
410    
411    #-----------------------------------------------------------------------------
412    #  Previous, 50% slower fasta reader:
413  #-----------------------------------------------------------------------------  #-----------------------------------------------------------------------------
414  sub read_fasta {  sub read_fasta_0
415    {
416      my ( $fh, $name, $close, $unused ) = input_filehandle( $_[0] );      my ( $fh, $name, $close, $unused ) = input_filehandle( $_[0] );
417      $unused && die "Bad reference type (" . ref( $unused ) . ") passed to read_fasta\n";      $unused && die "Bad reference type (" . ref( $unused ) . ") passed to read_fasta\n";
418    
# Line 255  Line 438 
438    
439    
440  #-----------------------------------------------------------------------------  #-----------------------------------------------------------------------------
441  #  Read one fasta sequence at a time from a file.  #  Read one fasta sequence at a time from a file.  This is half as fast a
442  #  Return the contents as an array:  (id, description, seq)  #  read_fasta(), but can handle an arbitrarily large file.  State information
443    #  is retained in hashes, so any number of streams can be interlaced.
444    #
445    #      @entry = read_next_fasta_seq( \*FILEHANDLE )
446    #     \@entry = read_next_fasta_seq( \*FILEHANDLE )
447    #      @entry = read_next_fasta_seq(  $filename )
448    #     \@entry = read_next_fasta_seq(  $filename )
449    #      @entry = read_next_fasta_seq()                # \*STDIN
450    #     \@entry = read_next_fasta_seq()                # \*STDIN
451    #
452    #      @entry = ( $id, $description, $seq )
453  #  #
454  #     @seq_entry = read_next_fasta_seq( \*FILEHANDLE )  #  When reading at the end of file, () is returned.
455    #  With a filename, reading past this will reopen the file at the beginning.
456  #-----------------------------------------------------------------------------  #-----------------------------------------------------------------------------
457  #  Reading always overshoots, so save next id and description  #  Reading always overshoots, so save next id and description
458    
459  {   #  Use bare block to scope the header hash  {   #  Use bare block to scope the header hash
460    
461      my %next_header;      my %next_header;
462        my %file_handle;
463        my %close_file;
464    
465      sub read_next_fasta_seq {      sub read_next_fasta_seq
466          my $fh = shift;      {
467          my ( $id, $desc );          $_[0] ||= \*STDIN;               #  Undefined $_[0] fails with use warn
468            my $fh = $file_handle{ $_[0] };
469            if ( ! $fh )
470            {
471                if ( ref $_[0] )
472                {
473                    return () if ref $_[0] ne 'GLOB';
474                    $fh = $_[0];
475                }
476                else
477                {
478                    my $file = $_[0];
479                    if    ( -f $file                       ) { $file = "<$file" }
480                    elsif (    $file =~ /^<(.*)$/ && -f $1 ) { }  # Explicit read
481                  # elsif (    $file =~ /\S\s*\|$/         ) { }  # Read from a pipe
482                    else                                     { return () }
483                    open $fh, $file or return ();
484                    $close_file{ $fh } = 1;
485                }
486                $file_handle{ $_[0] } = $fh;
487            }
488    
489          if ( defined( $next_header{$fh} ) ) {          my ( $id, $desc, $seq ) = ( undef, '', '' );
490            if ( defined( $next_header{$fh} ) )
491            {
492              ( $id, $desc ) = parse_fasta_title( $next_header{$fh} );              ( $id, $desc ) = parse_fasta_title( $next_header{$fh} );
493          }          }
494          else {          else
495              $next_header{$fh} = "";          {
496              ( $id, $desc ) = ( undef, "" );              $next_header{$fh} = '';
497          }          }
         my $seq = "";  
498    
499          while ( <$fh> ) {          while ( <$fh> )
500            {
501              chomp;              chomp;
502              if ( /^>/ ) {        #  new id              if ( /^>/ )        #  new id
503                {
504                  $next_header{$fh} = $_;                  $next_header{$fh} = $_;
505                  if ( defined($id) && $seq )                  if ( defined($id) && $seq )
506                  {                  {
507                      return wantarray ? ($id, $desc, $seq) : [$id, $desc, $seq]                      return wantarray ? ($id, $desc, $seq) : [$id, $desc, $seq]
508                  }                  }
509                  ( $id, $desc ) = parse_fasta_title( $next_header{$fh} );                  ( $id, $desc ) = parse_fasta_title( $next_header{$fh} );
510                  $seq = "";                  $seq = '';
511              }              }
512              else {              else
513                  tr/     0-9//d;              {
514                    tr/ \t\r//d;
515                  $seq .= $_ ;                  $seq .= $_ ;
516              }              }
517          }          }
518    
519          #  Done with file, delete "next header"          #  Done with file; there is no next header:
520    
521          delete $next_header{$fh};          delete $next_header{$fh};
522          return ( defined($id) && $seq ) ? ( wantarray ? ($id, $desc, $seq)  
523                                                        : [$id, $desc, $seq]          #  Return last set of data:
524                                            )  
525                                          : () ;          if ( defined($id) && $seq )
526            {
527                return wantarray ? ($id,$desc,$seq) : [$id,$desc,$seq]
528            }
529    
530            #  Or close everything out (returning the empty list tells caller
531            #  that we are done)
532    
533            if ( $close_file{ $fh } ) { close $fh; delete $close_file{ $fh } }
534            delete $file_handle{ $_[0] };
535    
536            return ();
537      }      }
538  }  }
539    
# Line 352  Line 583 
583  #     ($id, $def) = parse_fasta_title( $title )  #     ($id, $def) = parse_fasta_title( $title )
584  #     ($id, $def) = split_fasta_title( $title )  #     ($id, $def) = split_fasta_title( $title )
585  #-----------------------------------------------------------------------------  #-----------------------------------------------------------------------------
586  sub parse_fasta_title {  sub parse_fasta_title
587    {
588      my $title = shift;      my $title = shift;
589      chomp;      chomp $title;
     if ($title =~ /^>?\s*(\S+)(:?\s+(.*\S)\s*)?$/) {  
         return ($1, $3 ? $3 : "");  
     }  
     elsif ($title =~ /^>/) {  
         return ("", "");  
     }  
     else {  
         return (undef, "");  
     }  
 }  
590    
591  sub split_fasta_title {      return $title =~ /^>?\s*(\S+)(\s+(.*\S)?\s*)?$/ ? ( $1, $3 || '' )
592      parse_fasta_title ( shift );           : $title =~ /^>/                           ? ( '', '' )
593             :                                            ( undef, undef )
594  }  }
595    
596    sub split_fasta_title { parse_fasta_title( @_ ) }
597    
598    
599  #-----------------------------------------------------------------------------  #-----------------------------------------------------------------------------
600  #  Helper function for defining an output filehandle:  #  Helper function for defining an output filehandle:
# Line 377  Line 602 
602  #     string is taken as file name to be openend  #     string is taken as file name to be openend
603  #     undef or "" defaults to STDOUT  #     undef or "" defaults to STDOUT
604  #  #
605  #    ( \*FH, $name, $close [, $file] ) = output_filehandle( $file );  #    ( \*FH, $close [, $file] ) = output_filehandle( $file );
606  #  #
607  #-----------------------------------------------------------------------------  #-----------------------------------------------------------------------------
608  sub output_filehandle  sub output_filehandle
609  {  {
610      my $file = shift;      my $file = shift;
611    
612        #  Null string or undef
613    
614        return ( \*STDOUT, 0 ) if ( ! defined( $file ) || ( $file eq "" ) );
615    
616      #  FILEHANDLE      #  FILEHANDLE
617    
618      return ( $file, $file, 0 ) if ( ref( $file ) eq "GLOB" );      return ( $file, 0 ) if ( ref( $file ) eq "GLOB" );
619    
620      #  Null string or undef      #  Some other kind of reference; return the unused value
621    
622      return ( \*STDOUT, "", 0 ) if ( ! defined( $file ) || ( $file eq "" ) );      return ( \*STDOUT, 0, $file ) if ref( $file );
623    
624      #  File name      #  File name
625    
     if ( ! ref( $file ) )  
     {  
626          my $fh;          my $fh;
627          open( $fh, ">$file" ) || die "Could not open output $file\n";          open( $fh, ">$file" ) || die "Could not open output $file\n";
628          return ( $fh, $file, 1 );      return ( $fh, 1 );
     }  
   
     #  Some other kind of reference; return the unused value  
   
     return ( \*STDOUT, undef, 0, $file );  
629  }  }
630    
631    
# Line 427  Line 649 
649  #     print_alignment_as_fasta(  $filename,   \@seq_entry_list );  #     print_alignment_as_fasta(  $filename,   \@seq_entry_list );
650  #-----------------------------------------------------------------------------  #-----------------------------------------------------------------------------
651  sub print_alignment_as_fasta {  sub print_alignment_as_fasta {
652      my ( $fh, undef, $close, $unused ) = output_filehandle( shift );      my ( $fh, $close, $unused ) = output_filehandle( shift );
653      ( unshift @_, $unused ) if $unused;      ( unshift @_, $unused ) if $unused;
654    
655      ( ref( $_[0] ) eq "ARRAY" ) or die "Bad sequence entry passed to print_alignment_as_fasta\n";      ( ref( $_[0] ) eq "ARRAY" ) or confess "Bad sequence entry passed to print_alignment_as_fasta\n";
656    
657      #  Expand the sequence entry list if necessary:      #  Expand the sequence entry list if necessary:
658    
# Line 454  Line 676 
676  #     print_alignment_as_phylip(  $filename,   \@seq_entry_list );  #     print_alignment_as_phylip(  $filename,   \@seq_entry_list );
677  #-----------------------------------------------------------------------------  #-----------------------------------------------------------------------------
678  sub print_alignment_as_phylip {  sub print_alignment_as_phylip {
679      my ( $fh, undef, $close, $unused ) = output_filehandle( shift );      my ( $fh, $close, $unused ) = output_filehandle( shift );
680      ( unshift @_, $unused ) if $unused;      ( unshift @_, $unused ) if $unused;
681    
682      ( ref( $_[0] ) eq "ARRAY" ) or die die "Bad sequence entry passed to print_alignment_as_phylip\n";      ( ref( $_[0] ) eq "ARRAY" ) or die die "Bad sequence entry passed to print_alignment_as_phylip\n";
# Line 513  Line 735 
735  #     print_alignment_as_nexus(  $filename,   [ \%label_hash, ] \@seq_entry_list );  #     print_alignment_as_nexus(  $filename,   [ \%label_hash, ] \@seq_entry_list );
736  #-----------------------------------------------------------------------------  #-----------------------------------------------------------------------------
737  sub print_alignment_as_nexus {  sub print_alignment_as_nexus {
738      my ( $fh, undef, $close, $unused ) = output_filehandle( shift );      my ( $fh, $close, $unused ) = output_filehandle( shift );
739      ( unshift @_, $unused ) if $unused;      ( unshift @_, $unused ) if $unused;
740    
741      my $lbls = ( ref( $_[0] ) eq "HASH" ) ? shift : undef;      my $lbls = ( ref( $_[0] ) eq "HASH" ) ? shift : undef;
# Line 587  Line 809 
809    
810    
811  #-----------------------------------------------------------------------------  #-----------------------------------------------------------------------------
812  #  Print one sequence in fasta format to an open file  #  Print one sequence in fasta format to an open file.
813  #  #
814  #     print_seq_as_fasta( \*FILEHANDLE, $id, $desc, $seq );  #     print_seq_as_fasta( \*FILEHANDLE, $id, $desc, $seq );
815  #     print_seq_as_fasta( \*FILEHANDLE, @seq_entry );  #     print_seq_as_fasta(               $id, $desc, $seq );
816  #-----------------------------------------------------------------------------  #     print_seq_as_fasta( \*FILEHANDLE, $id,        $seq );
817  sub print_seq_as_fasta {  #     print_seq_as_fasta(               $id,        $seq );
818      my $fh = shift;  #
819      my ($id, $desc, $seq) = @_;  #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
820    #  print_seq_as_fasta() is meant more as a internal support routine than an
821      printf $fh ($desc) ? ">$id $desc\n" : ">$id\n";  #  external interface.  To print a single sequence to a named file use:
822      my $len = length($seq);  #
823      for (my $i = 0; $i < $len; $i += 60) {  #     print_alignment_as_fasta( $filename, [ $id, $desc, $seq ] );
824          print $fh substr($seq, $i, 60) . "\n";  #     print_alignment_as_fasta( $filename, [ $id,        $seq ] );
825      }  #-----------------------------------------------------------------------------
826    sub print_seq_as_fasta
827    {
828        my $fh = ( ref $_[0] eq 'GLOB' ) ? shift : \*STDOUT;
829        return if ( @_ < 2 ) || ( @_ > 3 ) || ! ( defined $_[0] && defined $_[-1] );
830        #  Print header line
831        print $fh  ( @_ == 3 && defined $_[1] && $_[1] =~ /\S/ ) ? ">$_[0] $_[1]\n" : ">$_[0]\n";
832        #  Print sequence, 60 chars per line
833        print $fh  join( "\n", $_[-1] =~ m/.{1,60}/g ), "\n";
834  }  }
835    
836    
# Line 633  Line 863 
863    
864    
865  #-----------------------------------------------------------------------------  #-----------------------------------------------------------------------------
866    #  Return a string with text wrapped to defined line lengths:
867    #
868    #     $wrapped_text = wrap_text( $str )                  # default len   =  80
869    #     $wrapped_text = wrap_text( $str, $len )            # default ind   =   0
870    #     $wrapped_text = wrap_text( $str, $len, $indent )   # default ind_n = ind
871    #     $wrapped_text = wrap_text( $str, $len, $indent_1, $indent_n )
872    #-----------------------------------------------------------------------------
873    sub wrap_text {
874        my ($str, $len, $ind, $indn) = @_;
875    
876        defined($str)  || die "wrap_text called without a string\n";
877        defined($len)  || ($len  =   80);
878        defined($ind)  || ($ind  =    0);
879        ($ind  < $len) || die "wrap error: indent greater than line length\n";
880        defined($indn) || ($indn = $ind);
881        ($indn < $len) || die "wrap error: indent_n greater than line length\n";
882    
883        $str =~ s/\s+$//;
884        $str =~ s/^\s+//;
885        my ($maxchr, $maxchr1);
886        my (@lines) = ();
887    
888        while ($str) {
889            $maxchr1 = ($maxchr = $len - $ind) - 1;
890            if ($maxchr >= length($str)) {
891                push @lines, (" " x $ind) . $str;
892                last;
893            }
894            elsif ($str =~ /^(.{0,$maxchr1}\S)\s+(\S.*)$/) { # no expr in {}
895                push @lines, (" " x $ind) . $1;
896                $str = $2;
897            }
898            elsif ($str =~ /^(.{0,$maxchr1}-)(.*)$/) {
899                push @lines, (" " x $ind) . $1;
900                $str = $2;
901            }
902            else {
903                push @lines, (" " x $ind) . substr($str, 0, $maxchr);
904                $str = substr($str, $maxchr);
905            }
906            $ind = $indn;
907        }
908    
909        return join("\n", @lines);
910    }
911    
912    
913    #-----------------------------------------------------------------------------
914  #  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)
915  #  #
916  #     my \%seq_ind  = index_seq_list(  @seq_list );  #     my \%seq_ind  = index_seq_list(  @seq_list );
# Line 681  Line 959 
959      return ${ $ind_ref->{$id} }[2];      return ${ $ind_ref->{$id} }[2];
960  }  }
961    
962    
963  #-----------------------------------------------------------------------------  #-----------------------------------------------------------------------------
964  #  Remove columns of alignment gaps from sequences:  #  Remove columns of alignment gaps from sequences:
965  #  #
# Line 689  Line 968 
968  #  \@packed_seqs = pack_alignment(  @seqs )  #  \@packed_seqs = pack_alignment(  @seqs )
969  #  \@packed_seqs = pack_alignment( \@seqs )  #  \@packed_seqs = pack_alignment( \@seqs )
970  #  #
971    #  Gap characters are defined below as '-', '~', '.', and ' '.
972  #-----------------------------------------------------------------------------  #-----------------------------------------------------------------------------
   
973  sub pack_alignment  sub pack_alignment
974  {  {
975      my @seqs = ( ref( $_[0] ) eq 'ARRAY' and ref( $_[0]->[0] ) eq 'ARRAY' ) ? @{$_[0] } : @_;      $_[0] && ( ref( $_[0] ) eq 'ARRAY' ) && @{$_[0]} && defined( $_[0]->[0] )
976            or return ();
977    
978        my @seqs = ( ref( $_[0]->[0] ) eq 'ARRAY' ) ? @{$_[0] } : @_;
979      @seqs or return wantarray ? () : [];      @seqs or return wantarray ? () : [];
980    
981      my $mask  = pack_mask( $seqs[0]->[2] );      my $mask  = gap_mask( $seqs[0]->[2] );
982      foreach ( @seqs[ 1 .. (@seqs-1) ] )      foreach ( @seqs[ 1 .. (@seqs-1) ] )
983      {      {
984          $mask |= pack_mask( $_->[2] );          $mask |= gap_mask( $_->[2] );
985      }      }
986    
987      my $seq;      my $seq;
# Line 709  Line 991 
991                      }                      }
992                  @seqs;                  @seqs;
993    
994      return wantarray ? @seqs2 : \@seqs2;      wantarray ? @seqs2 : \@seqs2;
995    }
996    
997    
998    #-------------------------------------------------------------------------------
999    #  Produce a packing mask for columns of alignment gaps in sequences.  Gap
1000    #  columns are 0x00 characters, and all others are 0xFF.
1001    #
1002    #   $mask = alignment_gap_mask(  @seqs )
1003    #   $mask = alignment_gap_mask( \@seqs )
1004    #
1005    #-------------------------------------------------------------------------------
1006    sub alignment_gap_mask
1007    {
1008        $_[0] && ( ref( $_[0] ) eq 'ARRAY' ) && @{$_[0]} && defined( $_[0]->[0] )
1009            or return undef;
1010    
1011        my @seqs = ( ref( $_[0]->[0] ) eq 'ARRAY' ) ? @{$_[0] } : @_;
1012        @seqs or return undef;
1013    
1014        my $mask = gap_mask( $seqs[0]->[2] );
1015        foreach ( @seqs[ 1 .. (@seqs-1) ] ) { $mask |= gap_mask( $_->[2] ) }
1016    
1017        $mask;
1018    }
1019    
1020    
1021    #-------------------------------------------------------------------------------
1022    #  Pack a sequence alignment according to a mask, removing positions where
1023    #  mask has 0x00 (or '-') characters
1024    #
1025    #   @packed = pack_alignment_by_mask( $mask,  @align )
1026    #   @packed = pack_alignment_by_mask( $mask, \@align )
1027    #  \@packed = pack_alignment_by_mask( $mask,  @align )
1028    #  \@packed = pack_alignment_by_mask( $mask, \@align )
1029    #
1030    #-------------------------------------------------------------------------------
1031    sub pack_alignment_by_mask
1032    {
1033        my $mask = shift;
1034        defined $mask && ! ref( $mask ) && length( $mask )
1035            or return ();
1036        $mask =~ tr/-/\000/;      # Allow '-' as a column to be removed
1037        $mask =~ tr/\000/\377/c;  # Make sure that everything not null is 0xFF
1038    
1039        $_[0] && ( ref( $_[0] ) eq 'ARRAY' ) && @{$_[0]} && defined( $_[0]->[0] )
1040            or return ();
1041        my @seqs = ( ref( $_[0]->[0] ) eq 'ARRAY' ) ? @{$_[0] } : @_;
1042    
1043        my $seq;
1044        my @seqs2 = map { $seq = $_->[2] & $mask;     # Apply mask to sequence
1045                          $seq =~ tr/\000//d;         # Delete null characters
1046                          [ $_->[0], $_->[1], $seq ]  # Rebuild sequence entries
1047                        }
1048                    @seqs;
1049    
1050        wantarray ? @seqs2 : \@seqs2;
1051    }
1052    
1053    
1054    #-------------------------------------------------------------------------------
1055    #  Weight a sequence alignment according to a mask of digits, 0-9.
1056    #
1057    #   @packed = weight_alignment_by_mask( $mask,  @align )
1058    #   @packed = weight_alignment_by_mask( $mask, \@align )
1059    #  \@packed = weight_alignment_by_mask( $mask,  @align )
1060    #  \@packed = weight_alignment_by_mask( $mask, \@align )
1061    #
1062    #-------------------------------------------------------------------------------
1063    sub weight_alignment_by_mask
1064    {
1065        my $mask = shift;
1066        defined $mask && ! ref( $mask ) && length( $mask )
1067            or return ();
1068    
1069        $_[0] && ( ref( $_[0] ) eq 'ARRAY' ) && @{$_[0]} && defined( $_[0]->[0] )
1070            or return ();
1071        my @seqs = ( ref( $_[0]->[0] ) eq 'ARRAY' ) ? @{$_[0] } : @_;
1072    
1073        my @seqs2 = map { [ $_->[0], $_->[1], weight_seq_by_mask_0( $mask, $_->[2] ) ] } @seqs;
1074    
1075        wantarray ? @seqs2 : \@seqs2;
1076    }
1077    
1078    
1079    #
1080    #  Assume data are valid
1081    #
1082    sub weight_seq_by_mask_0
1083    {
1084        my ( $mask, $seq ) = @_;
1085    
1086        #  Remove 0 weight columns, which is fast and easy:
1087        my $m0 = $mask;
1088        $m0 =~ tr/123456789/\377/;
1089        $m0 =~ tr/\377/\000/c;
1090        ( $mask &= $m0 ) =~ tr/\000//d;
1091        ( $seq  &= $m0 ) =~ tr/\000//d;
1092    
1093        #  If all remaining cols are weight 1, we are done:
1094        return $seq if $mask =~ /^1*$/;
1095    
1096        my @seq;
1097        for ( my $i = 0; $i < length( $mask ); $i++ )
1098        {
1099            push @seq, substr( $seq, $i, 1 ) x substr( $mask, $i, 1 );
1100        }
1101    
1102        join( '', @seq );
1103  }  }
1104    
1105  sub pack_mask  
1106    #-----------------------------------------------------------------------------
1107    #  Make a mask in which gap characters ('-', '~', '.', and ' ') are converted
1108    #  to 0x00, and all other characters to 0xFF.
1109    #
1110    #      $mask = gap_mask( $seq )
1111    #
1112    #-----------------------------------------------------------------------------
1113    sub gap_mask
1114  {  {
1115      my $mask = shift;      my $mask = shift;
1116      $mask =~ tr/-/\000/;      defined $mask or return '';
1117      $mask =~ tr/\000/\377/c;  
1118      return $mask;      $mask =~ tr/-~. /\000/;    #  Gap characters (might be extended)
1119        $mask =~ tr/\000/\377/c;   #  Non-gap characters
1120        $mask;
1121    }
1122    
1123    
1124    #===============================================================================
1125    #  Expand sequences with the local gap character in a manner that reverses the
1126    #  pack by mask function.
1127    #
1128    #      $expanded = expand_sequence_by_mask( $seq, $mask )
1129    #
1130    #  The columns to be added can be marked by '-' or "\000" in the mask.
1131    #
1132    #  Code note:
1133    #
1134    #  The function attempts to match the local gap character in the sequence.
1135    #  $c0 and $c1 are the previous and next characters in the sequence being
1136    #  expanded.  (($c0,$c1)=($c1,shift @s1))[0] updates the values and evaluates
1137    #  to what was the next character, and becomes the new previous character.
1138    #  The following really does print w, x, y, and z, one per line:
1139    #
1140    #     ( $a, $b, @c ) = ("", split //, "wxyz");
1141    #     while ( defined $b ) { print( (($a,$b)=($b,shift @c))[0], "\n" ) }
1142    #===============================================================================
1143    
1144    sub expand_sequence_by_mask
1145    {
1146        my ( $seq, $mask ) = @_;
1147    
1148        $mask =~ tr/-/\000/;  #  Allow hyphen or null in mask at added positions.
1149        my ( $c0, $c1, @s1 ) = ( '', split( //, $seq ), '' );
1150    
1151        join '', map { $_  ne "\000"            ? (($c0,$c1)=($c1,shift @s1))[0]
1152                     : $c0 eq '~' || $c1 eq '~' ? '~'
1153                     : $c0 eq '.' || $c1 eq '.' ? '.'
1154                     :                            '-'
1155  }  }
1156                 split //, $mask;
1157    }
1158    
1159    
1160    #-----------------------------------------------------------------------------
1161    #  Remove all alignment gaps from sequences:
1162    #
1163    #   @packed_seqs = pack_sequences(  @seqs )  # Also handles single sequence
1164    #   @packed_seqs = pack_sequences( \@seqs )
1165    #  \@packed_seqs = pack_sequences(  @seqs )
1166    #  \@packed_seqs = pack_sequences( \@seqs )
1167    #
1168    #-----------------------------------------------------------------------------
1169    sub pack_sequences
1170    {
1171        $_[0] && ( ref( $_[0] ) eq 'ARRAY' ) && @{$_[0]} && defined( $_[0]->[0] )
1172            or return ();
1173    
1174        my @seqs = ( ref( $_[0]->[0] ) eq 'ARRAY' ) ? @{$_[0] } : @_;
1175    
1176        my @seqs2 = map { [ $_->[0], $_->[1], pack_seq( $_->[2] ) ] } @seqs;
1177    
1178        wantarray ? @seqs2 : \@seqs2;
1179    }
1180    
1181    
1182  #-----------------------------------------------------------------------------  #-----------------------------------------------------------------------------
1183  #  Some simple sequence manipulations:  #  Some simple sequence manipulations:
# Line 794  Line 1253 
1253  }  }
1254    
1255    
1256    sub DNA_subseq
1257    {
1258        my ( $seq, $from, $to ) = @_;
1259    
1260        my $len = ref( $seq ) eq 'SCALAR' ? length( $$seq )
1261                                          : length(  $seq );
1262        if ( ( $from eq '$' ) || ( $from eq "" ) ) { $from = $len }
1263        if ( ( $to   eq '$' ) || ( ! $to       ) ) { $to   = $len }
1264    
1265        my $left  = ( $from < $to ) ? $from : $to;
1266        my $right = ( $from < $to ) ? $to   : $from;
1267        if ( ( $right < 1 ) || ( $left > $len ) ) { return "" }
1268        if ( $right > $len ) { $right = $len }
1269        if ( $left  < 1    ) { $left  =    1 }
1270    
1271        my $subseq = ref( $seq ) eq 'SCALAR' ? substr( $$seq, $left-1, $right-$left+1 )
1272                                             : substr(  $seq, $left-1, $right-$left+1 );
1273    
1274        if ( $from > $to )
1275        {
1276            $subseq = reverse $subseq;
1277            $subseq =~ tr[ACGTUKMRSWYBDHVNacgtukmrswybdhvn]
1278                         [TGCAAMKYSWRVHDBNtgcaamkyswrvhdbn];
1279        }
1280    
1281        $subseq
1282    }
1283    
1284    
1285    sub RNA_subseq
1286    {
1287        my ( $seq, $from, $to ) = @_;
1288    
1289        my $len = ref( $seq ) eq 'SCALAR' ? length( $$seq )
1290                                          : length(  $seq );
1291        if ( ( $from eq '$' ) || ( $from eq "" ) ) { $from = $len }
1292        if ( ( $to   eq '$' ) || ( ! $to       ) ) { $to   = $len }
1293    
1294        my $left  = ( $from < $to ) ? $from : $to;
1295        my $right = ( $from < $to ) ? $to   : $from;
1296        if ( ( $right < 1 ) || ( $left > $len ) ) { return "" }
1297        if ( $right > $len ) { $right = $len }
1298        if ( $left  < 1    ) { $left  =    1 }
1299    
1300        my $subseq = ref( $seq ) eq 'SCALAR' ? substr( $$seq, $left-1, $right-$left+1 )
1301                                             : substr(  $seq, $left-1, $right-$left+1 );
1302    
1303        if ( $from > $to )
1304        {
1305            $subseq = reverse $subseq;
1306            $subseq =~ tr[ACGTUKMRSWYBDHVNacgtukmrswybdhvn]
1307                         [UGCAAMKYSWRVHDBNugcaamkyswrvhdbn];
1308        }
1309    
1310        $subseq
1311    }
1312    
1313    
1314  sub complement_DNA_entry {  sub complement_DNA_entry {
1315      my ($id, $desc, $seq, $fix_id) = @_;      my ($id, $desc, $seq, $fix_id) = @_;
1316      $fix_id ||= 0;     #  fix undef values      $fix_id ||= 0;     #  fix undef values
# Line 868  Line 1385 
1385    
1386  sub pack_seq {  sub pack_seq {
1387      my $seq = shift;      my $seq = shift;
1388      $seq =~ tr/A-Za-z//cd;      $seq =~ tr/A-Za-z*//cd;
1389      return $seq;      $seq;
1390  }  }
1391    
1392    
1393  sub clean_ae_sequence {  sub clean_ae_sequence {
1394      $_ = shift;      local $_ = shift;
1395      $_ = to7bit($_);      $_ = to7bit($_);
1396      s/[+]/1/g;      s/\+/1/g;
1397      s/[^0-9A-IK-NP-Za-ik-np-z~.-]/-/g;      s/[^0-9A-IK-NP-Za-ik-np-z~.-]/-/g;
1398      return $_;      return $_;
1399  }  }
1400    
1401    
1402  sub to7bit {  sub to7bit {
1403      $_ = shift;      local $_ = shift;
1404      my ($o, $c);      my ($o, $c);
1405      while (/\\([0-3][0-7][0-7])/) {      while (/\\([0-3][0-7][0-7])/) {
1406          $o = oct($1) % 128;          $o = oct($1) % 128;
# Line 895  Line 1412 
1412    
1413    
1414  sub to8bit {  sub to8bit {
1415      $_ = shift;      local $_ = shift;
1416      my ($o, $c);      my ($o, $c);
1417      while (/\\([0-3][0-7][0-7])/) {      while (/\\([0-3][0-7][0-7])/) {
1418          $o = oct($1);          $o = oct($1);
# Line 911  Line 1428 
1428  #  Translate nucleotides to one letter protein:  #  Translate nucleotides to one letter protein:
1429  #  #
1430  #  $seq = translate_seq( $seq [, $met_start] )  #  $seq = translate_seq( $seq [, $met_start] )
1431  #  $aa  = translate_codon( $triplet );  #     $aa  = translate_codon( $triplet )
1432  #  $aa  = translate_uc_DNA_codon( $upcase_DNA_triplet );  #     $aa  = translate_DNA_codon( $triplet )     # Does not rely on DNA
1433    #     $aa  = translate_uc_DNA_codon( $triplet )  # Does not rely on uc or DNA
1434  #  #
1435  #  User-supplied genetic code must be upper case index and match the  #  User-supplied genetic code must be upper case index and match the
1436  #  DNA versus RNA type of sequence  #  DNA versus RNA type of sequence
# Line 929  Line 1447 
1447    
1448      # DNA version      # DNA version
1449    
1450      TTT => "F",  TCT => "S",  TAT => "Y",  TGT => "C",      TTT => 'F',  TCT => 'S',  TAT => 'Y',  TGT => 'C',
1451      TTC => "F",  TCC => "S",  TAC => "Y",  TGC => "C",      TTC => 'F',  TCC => 'S',  TAC => 'Y',  TGC => 'C',
1452      TTA => "L",  TCA => "S",  TAA => "*",  TGA => "*",      TTA => 'L',  TCA => 'S',  TAA => '*',  TGA => '*',
1453      TTG => "L",  TCG => "S",  TAG => "*",  TGG => "W",      TTG => 'L',  TCG => 'S',  TAG => '*',  TGG => 'W',
1454      CTT => "L",  CCT => "P",  CAT => "H",  CGT => "R",      CTT => 'L',  CCT => 'P',  CAT => 'H',  CGT => 'R',
1455      CTC => "L",  CCC => "P",  CAC => "H",  CGC => "R",      CTC => 'L',  CCC => 'P',  CAC => 'H',  CGC => 'R',
1456      CTA => "L",  CCA => "P",  CAA => "Q",  CGA => "R",      CTA => 'L',  CCA => 'P',  CAA => 'Q',  CGA => 'R',
1457      CTG => "L",  CCG => "P",  CAG => "Q",  CGG => "R",      CTG => 'L',  CCG => 'P',  CAG => 'Q',  CGG => 'R',
1458      ATT => "I",  ACT => "T",  AAT => "N",  AGT => "S",      ATT => 'I',  ACT => 'T',  AAT => 'N',  AGT => 'S',
1459      ATC => "I",  ACC => "T",  AAC => "N",  AGC => "S",      ATC => 'I',  ACC => 'T',  AAC => 'N',  AGC => 'S',
1460      ATA => "I",  ACA => "T",  AAA => "K",  AGA => "R",      ATA => 'I',  ACA => 'T',  AAA => 'K',  AGA => 'R',
1461      ATG => "M",  ACG => "T",  AAG => "K",  AGG => "R",      ATG => 'M',  ACG => 'T',  AAG => 'K',  AGG => 'R',
1462      GTT => "V",  GCT => "A",  GAT => "D",  GGT => "G",      GTT => 'V',  GCT => 'A',  GAT => 'D',  GGT => 'G',
1463      GTC => "V",  GCC => "A",  GAC => "D",  GGC => "G",      GTC => 'V',  GCC => 'A',  GAC => 'D',  GGC => 'G',
1464      GTA => "V",  GCA => "A",  GAA => "E",  GGA => "G",      GTA => 'V',  GCA => 'A',  GAA => 'E',  GGA => 'G',
1465      GTG => "V",  GCG => "A",  GAG => "E",  GGG => "G",      GTG => 'V',  GCG => 'A',  GAG => 'E',  GGG => 'G',
   
     # RNA suppliment  
   
     UUU => "F",  UCU => "S",  UAU => "Y",  UGU => "C",  
     UUC => "F",  UCC => "S",  UAC => "Y",  UGC => "C",  
     UUA => "L",  UCA => "S",  UAA => "*",  UGA => "*",  
     UUG => "L",  UCG => "S",  UAG => "*",  UGG => "W",  
     CUU => "L",  CCU => "P",  CAU => "H",  CGU => "R",  
     CUC => "L",  
     CUA => "L",  
     CUG => "L",  
     AUU => "I",  ACU => "T",  AAU => "N",  AGU => "S",  
     AUC => "I",  
     AUA => "I",  
     AUG => "M",  
     GUU => "V",  GCU => "A",  GAU => "D",  GGU => "G",  
     GUC => "V",  
     GUA => "V",  
     GUG => "V",  
1466    
1467      #  The following ambiguous encodings are not necessary,  but      #  The following ambiguous encodings are not necessary,  but
1468      #  speed up the processing of some ambiguous triplets:      #  speed up the processing of some ambiguous triplets:
1469    
1470      TTY => "F",  TCY => "S",  TAY => "Y",  TGY => "C",      TTY => 'F',  TCY => 'S',  TAY => 'Y',  TGY => 'C',
1471      TTR => "L",  TCR => "S",  TAR => "*",      TTR => 'L',  TCR => 'S',  TAR => '*',
1472                   TCN => "S",                   TCN => 'S',
1473      CTY => "L",  CCY => "P",  CAY => "H",  CGY => "R",      CTY => 'L',  CCY => 'P',  CAY => 'H',  CGY => 'R',
1474      CTR => "L",  CCR => "P",  CAR => "Q",  CGR => "R",      CTR => 'L',  CCR => 'P',  CAR => 'Q',  CGR => 'R',
1475      CTN => "L",  CCN => "P",               CGN => "R",      CTN => 'L',  CCN => 'P',               CGN => 'R',
1476      ATY => "I",  ACY => "T",  AAY => "N",  AGY => "S",      ATY => 'I',  ACY => 'T',  AAY => 'N',  AGY => 'S',
1477                   ACR => "T",  AAR => "K",  AGR => "R",                   ACR => 'T',  AAR => 'K',  AGR => 'R',
1478                   ACN => "T",                   ACN => 'T',
1479      GTY => "V",  GCY => "A",  GAY => "D",  GGY => "G",      GTY => 'V',  GCY => 'A',  GAY => 'D',  GGY => 'G',
1480      GTR => "V",  GCR => "A",  GAR => "E",  GGR => "G",      GTR => 'V',  GCR => 'A',  GAR => 'E',  GGR => 'G',
1481      GTN => "V",  GCN => "A",               GGN => "G",      GTN => 'V',  GCN => 'A',               GGN => 'G'
   
     UUY => "F",  UCY => "S",  UAY => "Y",  UGY => "C",  
     UUR => "L",  UCR => "S",  UAR => "*",  
                  UCN => "S",  
     CUY => "L",  
     CUR => "L",  
     CUN => "L",  
     AUY => "I",  
     GUY => "V",  
     GUR => "V",  
     GUN => "V"  
1482  );  );
1483    
1484    #  Add RNA by construction:
1485    
1486    foreach ( grep { /T/ } keys %genetic_code )
1487    {
1488        my $codon = $_;
1489        $codon =~ s/T/U/g;
1490        $genetic_code{ $codon } = lc $genetic_code{ $_ }
1491    }
1492    
1493  #  Add lower case by construction:  #  Add lower case by construction:
1494    
1495  foreach ( keys %genetic_code ) {  foreach ( keys %genetic_code )
1496    {
1497      $genetic_code{ lc $_ } = lc $genetic_code{ $_ }      $genetic_code{ lc $_ } = lc $genetic_code{ $_ }
1498  }  }
1499    
1500    
1501  #  Construct the genetic code with selanocysteine by difference:  #  Construct the genetic code with selenocysteine by difference:
1502    
1503  %genetic_code_with_U = map { $_ => $genetic_code{ $_ } } keys %genetic_code;  %genetic_code_with_U = %genetic_code;
1504  $genetic_code_with_U{ TGA } = "U";  $genetic_code_with_U{ TGA } = 'U';
1505  $genetic_code_with_U{ tga } = "u";  $genetic_code_with_U{ tga } = 'u';
1506  $genetic_code_with_U{ UGA } = "U";  $genetic_code_with_U{ UGA } = 'U';
1507  $genetic_code_with_U{ uga } = "u";  $genetic_code_with_U{ uga } = 'u';
1508    
1509    
1510  %amino_acid_codons_DNA = (  %amino_acid_codons_DNA = (
# Line 1271  Line 1768 
1768    
1769    
1770  #-----------------------------------------------------------------------------  #-----------------------------------------------------------------------------
1771  #  Translate nucleotides to one letter protein:  #  Translate nucleotides to one letter protein.  Respects case of the
1772    #  nucleotide sequence.
1773  #  #
1774  #      $seq = translate_seq( $seq [, $met_start] )  #      $aa = translate_seq( $nt, $met_start )
1775    #      $aa = translate_seq( $nt )
1776  #  #
1777  #-----------------------------------------------------------------------------  #-----------------------------------------------------------------------------
1778    
1779  sub translate_seq {  sub translate_seq
1780      my $seq = uc shift;  {
1781      $seq =~ tr/UX/TN/;      #  make it DNA, and allow X      my $seq = shift;
1782      $seq =~ tr/-//d;        #  remove gaps      $seq =~ tr/-//d;        #  remove gaps
1783    
1784      my $met = shift || 0;   #  a second argument that is true      my @codons = $seq =~ m/(...?)/g;  #  Will try to translate last 2 nt
                             #  forces first amino acid to be Met  
                             #  (note: undef is false)  
1785    
1786      my $imax = length($seq) - 2;  # will try to translate 2 nucleotides!      #  A second argument that is true forces first amino acid to be Met
1787      my $pep = ( ($met && ($imax >= 0)) ? "M" : "" );  
1788      for (my $i = $met ? 3 : 0; $i <= $imax; $i += 3) {      my @met;
1789          $pep .= translate_uc_DNA_codon( substr($seq,$i,3) );      if ( ( shift @_ ) && ( my $codon1 = shift @codons ) )
1790        {
1791            push @met, ( $codon1 =~ /[a-z]/ ? 'm' : 'M' );
1792      }      }
1793    
1794      return $pep;      join( '', @met, map { translate_codon( $_ ) } @codons )
1795  }  }
1796    
1797    
1798  #-----------------------------------------------------------------------------  #-----------------------------------------------------------------------------
1799  #  Translate a single triplet with "universal" genetic code  #  Translate a single triplet with "universal" genetic code.
 #  Uppercase and DNA are performed, then translate_uc_DNA_codon  
 #  is called.  
1800  #  #
1801  #      $aa = translate_codon( $triplet )  #      $aa = translate_codon( $triplet )
1802    #      $aa = translate_DNA_codon( $triplet )
1803    #      $aa = translate_uc_DNA_codon( $triplet )
1804  #  #
1805  #-----------------------------------------------------------------------------  #-----------------------------------------------------------------------------
1806    
1807  sub translate_codon {  sub translate_DNA_codon { translate_codon( @_ ) }
     my $codon = uc shift;  #  Make it uppercase  
     $codon =~ tr/UX/TN/;   #  Make it DNA, and allow X  
     return translate_uc_DNA_codon($codon);  
 }  
   
1808    
1809  #-----------------------------------------------------------------------------  sub translate_uc_DNA_codon { translate_codon( uc $_[0] ) }
 #  Translate a single triplet with "universal" genetic code  
 #  Uppercase and DNA assumed  
 #  Intended for private use by translate_codon and translate_seq  
 #  
 #      $aa = translate_uc_DNA_codon( $triplet )  
 #  
 #-----------------------------------------------------------------------------  
1810    
1811  sub translate_uc_DNA_codon {  sub translate_codon
1812    {
1813      my $codon = shift;      my $codon = shift;
1814      my $aa;      $codon =~ tr/Uu/Tt/;     #  Make it DNA
1815    
1816      #  Try a simple lookup:      #  Try a simple lookup:
1817    
1818        my $aa;
1819      if ( $aa = $genetic_code{ $codon } ) { return $aa }      if ( $aa = $genetic_code{ $codon } ) { return $aa }
1820    
1821      #  With the expanded code defined above, this catches simple N, R      #  Attempt to recover from mixed-case codons:
     #  and Y ambiguities in the third position.  Other codes like  
     #  GG[KMSWBDHV], or even GG, might be unambiguously translated by  
     #  converting the last position to N and seeing if this is in the  
     #  (expanded) code table:  
   
     if ( $aa = $genetic_code{ substr($codon,0,2) . "N" } ) { return $aa }  
   
     #  Test that codon is valid and might have unambiguous aa:  
   
     if ( $codon !~ m/^[ACGTMY][ACGT][ACGTKMRSWYBDHVN]$/ ) { return "X" }  
     #                     ^^  
     #                     |+- for leucine YTR  
     #                     +-- for arginine MGR  
1822    
1823      #  Expand all ambiguous nucleotides to see if they all yield same aa.      $codon = ( $codon =~ /[a-z]/ ) ? lc $codon : uc $codon;
1824      #  Loop order tries to fail quickly with first position change.      if ( $aa = $genetic_code{ $codon } ) { return $aa }
1825    
1826      $aa = "";      #  The code defined above catches simple N, R and Y ambiguities in the
1827      for my $n2 ( @{ $DNA_letter_can_be{ substr($codon,1,1) } } ) {      #  third position.  Other codons (e.g., GG[KMSWBDHV], or even GG) might
1828          for my $n3 ( @{ $DNA_letter_can_be{ substr($codon,2,1) } } ) {      #  be unambiguously translated by converting the last position to N and
1829              for my $n1 ( @{ $DNA_letter_can_be{ substr($codon,0,1) } } ) {      #  seeing if this is in the code table:
1830                  #  set the first value of $aa  
1831                  if ($aa eq "") { $aa = $genetic_code{ $n1 . $n2 . $n3 } }      my $N = ( $codon =~ /[a-z]/ ) ? 'n' : 'N';
1832                  #  or break out if any other amino acid is detected      if ( $aa = $genetic_code{ substr($codon,0,2) . $N } ) { return $aa }
1833                  elsif ($aa ne $genetic_code{ $n1 . $n2 . $n3 } ) { return "X" }  
1834              }      #  Test that codon is valid for an unambiguous aa:
1835          }  
1836        my $X = ( $codon =~ /[a-z]/ ) ? 'x' : 'X';
1837        if ( $codon !~ m/^[ACGTMY][ACGT][ACGTKMRSWYBDHVN]$/i
1838          && $codon !~ m/^YT[AGR]$/i     #  Leu YTR
1839          && $codon !~ m/^MG[AGR]$/i     #  Arg MGR
1840           )
1841        {
1842            return $X;
1843      }      }
1844    
1845      return $aa || "X";      #  Expand all ambiguous nucleotides to see if they all yield same aa.
1846    
1847        my @n1 = @{ $DNA_letter_can_be{ substr( $codon, 0, 1 ) } };
1848        my $n2 =                        substr( $codon, 1, 1 );
1849        my @n3 = @{ $DNA_letter_can_be{ substr( $codon, 2, 1 ) } };
1850        my @triples = map { my $n12 = $_ . $n2; map { $n12 . $_ } @n3 } @n1;
1851    
1852        my $triple = shift @triples;
1853        $aa = $genetic_code{ $triple };
1854        $aa or return $X;
1855    
1856        foreach $triple ( @triples ) { return $X if $aa ne $genetic_code{$triple} }
1857    
1858        return $aa;
1859  }  }
1860    
1861    
# Line 1368  Line 1864 
1864  #  Diagnose the use of upper versus lower, and T versus U in the supplied  #  Diagnose the use of upper versus lower, and T versus U in the supplied
1865  #  code, and transform the supplied nucleotide sequence to match.  #  code, and transform the supplied nucleotide sequence to match.
1866  #  #
1867  #  translate_seq_with_user_code($seq, \%gen_code [, $start_with_met] )  #     $aa = translate_seq_with_user_code( $nt, \%gen_code )
1868    #     $aa = translate_seq_with_user_code( $nt, \%gen_code, $start_with_met )
1869  #  #
1870    #  Modified 2007-11-22 to be less intrusive in these diagnoses by sensing
1871    #  the presence of both versions in the user code.
1872  #-----------------------------------------------------------------------------  #-----------------------------------------------------------------------------
1873    
1874  sub translate_seq_with_user_code {  sub translate_seq_with_user_code
1875    {
1876      my $seq = shift;      my $seq = shift;
1877      $seq =~ tr/-//d;     #  remove gaps  ***  Why?      $seq =~ tr/-//d;     #  remove gaps  ***  Why?
     $seq =~ tr/Xx/Nn/;   #  allow X  
1878    
1879      my $gc = shift;      #  Reference to hash of DNA alphabet code      my $gc = shift;      #  Reference to hash of code
1880      if (! $gc || ref($gc) ne "HASH") {      if (! $gc || ref($gc) ne "HASH")
1881          die "translate_seq_with_user_code needs genetic code hash as secondargument.";      {
1882            print STDERR "translate_seq_with_user_code needs genetic code hash as second argument.";
1883            return undef;
1884      }      }
1885    
1886      #  Test the type of code supplied: uppercase versus lowercase      #  Test code support for upper vs lower case:
   
     my ($RNA_F, $DNA_F, $M, $N, $X);  
1887    
1888      if ($gc->{ "AAA" }) {     #  Looks like uppercase code table      my ( $TTT, $UUU );
1889        if    ( $gc->{AAA} && ! $gc->{aaa} )   #  Uppercase only code table
1890        {
1891          $seq   = uc $seq;     #  Uppercase sequence          $seq   = uc $seq;     #  Uppercase sequence
1892          $RNA_F = "UUU";       #  Uppercase RNA Phe codon          ( $TTT, $UUU ) = ( 'TTT', 'UUU' );
         $DNA_F = "TTT";       #  Uppercase DNA Phe codon  
         $M     = "M";         #  Uppercase initiator  
         $N     = "N";         #  Uppercase ambiguous nuc  
         $X     = "X";         #  Uppercase ambiguous aa  
1893      }      }
1894      elsif ($gc->{ "aaa" }) {  #  Looks like lowercase code table      elsif ( $gc->{aaa} && ! $gc->{AAA} )   #  Lowercase only code table
1895        {
1896          $seq   = lc $seq;     #  Lowercase sequence          $seq   = lc $seq;     #  Lowercase sequence
1897          $RNA_F = "uuu";       #  Lowercase RNA Phe codon          ( $TTT, $UUU ) = ( 'ttt', 'uuu' );
         $DNA_F = "ttt";       #  Lowercase DNA Phe codon  
         $M     = "m";         #  Lowercase initiator  
         $N     = "n";         #  Lowercase ambiguous nuc  
         $X     = "x";         #  Lowercase ambiguous aa  
1898      }      }
1899      else {      elsif ( $gc->{aaa} )
1900          die "User-supplied genetic code does not have aaa or AAA\n";      {
1901            ( $TTT, $UUU ) = ( 'ttt', 'uuu' );
1902        }
1903        else
1904        {
1905            print STDERR "User-supplied genetic code does not have aaa or AAA\n";
1906            return undef;
1907      }      }
1908    
1909      #  Test the type of code supplied:  UUU versus TTT      #  Test code support for U vs T:
   
     my ($ambigs);  
1910    
1911      if ($gc->{ $RNA_F }) {     #  Looks like RNA code table      my $ambigs;
1912          $seq =~ tr/Tt/Uu/;      if    ( $gc->{$UUU} && ! $gc->{$TTT} )  # RNA only code table
1913        {
1914            $seq = tr/Tt/Uu/;
1915          $ambigs = \%RNA_letter_can_be;          $ambigs = \%RNA_letter_can_be;
1916      }      }
1917      elsif ($gc->{ $DNA_F }) {  #  Looks like DNA code table      elsif ( $gc->{$TTT} && ! $gc->{$UUU} )  # DNA only code table
1918          $seq =~ tr/Uu/Tt/;      {
1919            $seq = tr/Uu/Tt/;
1920          $ambigs = \%DNA_letter_can_be;          $ambigs = \%DNA_letter_can_be;
1921      }      }
1922      else {      else
1923          die "User-supplied genetic code does not have $RNA_F or $DNA_F\n";      {
1924            my $t = $seq =~ tr/Tt//;
1925            my $u = $seq =~ tr/Uu//;
1926            $ambigs = ( $t > $u ) ? \%DNA_letter_can_be : \%RNA_letter_can_be;
1927      }      }
1928    
1929      my $imax = length($seq) - 2;  # will try to translate 2 nucleotides!      #  We can now do the codon-by-codon translation:
1930    
1931      my $met = shift;     #  a third argument that is true      my @codons = $seq =~ m/(...?)/g;  #  will try to translate last 2 nt
1932                           #  forces first amino acid to be Met  
1933                           #  (note: undef is false)      #  A third argument that is true forces first amino acid to be Met
     my $pep  = ($met && ($imax >= 0)) ? $M : "";  
     my $aa;  
1934    
1935      for (my $i = $met ? 3 : 0; $i <= $imax; $i += 3) {      my @met;
1936          $pep .= translate_codon_with_user_code( substr($seq,$i,3), $gc, $N, $X, $ambigs );      if ( ( shift @_ ) && ( my $codon1 = shift @codons ) )
1937        {
1938            push @met, ( $codon1 =~ /[a-z]/ ? 'm' : 'M' );
1939      }      }
1940    
1941      return $pep;      join( '', @met, map { translate_codon_with_user_code( $_, $gc, $ambigs ) } @codons )
1942  }  }
1943    
1944    
1945  #-----------------------------------------------------------------------------  #-----------------------------------------------------------------------------
1946  #  Translate with user-supplied genetic code hash.  For speed, no error  #  Translate with user-supplied genetic code hash.  No error check on the code.
1947  #  check on the hash.  Calling programs should check for the hash at a  #  Should only be called through translate_seq_with_user_code.
 #  higher level.  
 #  
 #  Should only be called through translate_seq_with_user_code  
1948  #  #
1949  #   translate_codon_with_user_code( $triplet, \%code, $N, $X, $ambig_table )  #     $aa = translate_codon_with_user_code( $triplet, \%code, \%ambig_table )
1950  #  #
1951  #  $triplet      speaks for itself  #  $triplet      speaks for itself
1952  #  $code         ref to the hash with the codon translations  #  \%code         ref to the hash with the codon translations
1953  #  $N            character to use for ambiguous nucleotide  #  \%ambig_table  ref to hash with lists of nucleotides for each ambig code
 #  $X            character to use for ambiguous amino acid  
 #  $ambig_table  ref to hash with lists of nucleotides for each ambig code  
1954  #-----------------------------------------------------------------------------  #-----------------------------------------------------------------------------
1955    
1956    sub translate_codon_with_user_code
1957  sub translate_codon_with_user_code {  {
1958      my $codon = shift;      my ( $codon, $gc, $ambigs ) = @_;
     my $gc    = shift;  
     my $aa;  
1959    
1960      #  Try a simple lookup:      #  Try a simple lookup:
1961    
1962        my $aa;
1963      if ( $aa = $gc->{ $codon } ) { return $aa }      if ( $aa = $gc->{ $codon } ) { return $aa }
1964    
1965      #  Test that codon is valid and might have unambiguous aa:      #  Attempt to recover from mixed-case codons:
1966    
1967      my ($N, $X, $ambigs) = @_;      $codon = ( $codon =~ /[a-z]/ ) ? lc $codon : uc $codon;
1968      if ( $codon =~ m/^[ACGTUMY][ACGTU]$/i ) { $codon .= $N }      if ( $aa = $genetic_code{ $codon } ) { return $aa }
     if ( $codon !~ m/^[ACGTUMY][ACGTU][ACGTUKMRSWYBDHVN]$/i ) { return $X }  
     #                          ^^  
     #                          |+- for leucine YTR  
     #                          +-- for arginine MGR  
1969    
1970      #  Expand all ambiguous nucleotides to see if they all yield same aa.      #  Test that codon is valid for an unambiguous aa:
     #  Loop order tries to fail quickly with first position change.  
1971    
1972      $aa = "";      my $X = ( $codon =~ /[a-z]/ ) ? 'x' : 'X';
1973      for my $n2 ( @{ $ambigs->{ substr($codon,1,1) } } ) {  
1974          for my $n3 ( @{ $ambigs->{ substr($codon,2,1) } } ) {      if ( $codon =~ m/^[ACGTU][ACGTU]$/i )  # Add N?
1975              for my $n1 ( @{ $ambigs->{ substr($codon,0,1) } } ) {      {
1976                  #  set the first value of $aa          $codon .= ( $codon =~ /[a-z]/ ) ? 'n' : 'N';
                 if ($aa eq "") { $aa = $gc->{ $n1 . $n2 . $n3 } }  
                 #  break out if any other amino acid is detected  
                 elsif ($aa ne $gc->{ $n1 . $n2 . $n3 } ) { return "X" }  
1977              }              }
1978        #  This makes assumptions about the user code, but tranlating ambiguous
1979        #  codons is really a bit off the wall to start with:
1980        elsif ( $codon !~ m/^[ACGTUMY][ACGTU][ACGTUKMRSWYBDHVN]$/i ) # Valid?
1981        {
1982            return $X;
1983          }          }
1984    
1985        #  Expand all ambiguous nucleotides to see if they all yield same aa.
1986    
1987        my @n1 = @{ $ambigs->{ substr( $codon, 0, 1 ) } };
1988        my $n2 =               substr( $codon, 1, 1 );
1989        my @n3 = @{ $ambigs->{ substr( $codon, 2, 1 ) } };
1990        my @triples = map { my $n12 = $_ . $n2; map { $n12 . $_ } @n3 } @n1;
1991    
1992        my $triple = shift @triples;
1993        $aa = $gc->{ $triple } || $gc->{ lc $triple } || $gc->{ uc $triple };
1994        $aa or return $X;
1995    
1996        foreach $triple ( @triples )
1997        {
1998            return $X if $aa ne ( $gc->{$triple} || $gc->{lc $triple} || $gc->{uc $triple} );
1999      }      }
2000    
2001      return $aa || $X;      return $aa;
2002  }  }
2003    
2004    
# Line 1676  Line 2186 
2186  }  }
2187    
2188    
2189    #-----------------------------------------------------------------------------
2190    #  Read qual.
2191    #
2192    #  Save the contents in a list of refs to arrays: [ $id, $descript, \@qual ]
2193    #
2194    #     @seq_entries = read_qual( )               #  STDIN
2195    #    \@seq_entries = read_qual( )               #  STDIN
2196    #     @seq_entries = read_qual( \*FILEHANDLE )
2197    #    \@seq_entries = read_qual( \*FILEHANDLE )
2198    #     @seq_entries = read_qual(  $filename )
2199    #    \@seq_entries = read_qual(  $filename )
2200    #-----------------------------------------------------------------------------
2201    sub read_qual {
2202        my ( $fh, $name, $close, $unused ) = input_filehandle( $_[0] );
2203        $unused && die "Bad reference type (" . ref( $unused ) . ") passed to read_qual\n";
2204    
2205        my @quals = ();
2206        my ($id, $desc, $qual) = ("", "", []);
2207    
2208        while ( <$fh> ) {
2209            chomp;
2210            if (/^>\s*(\S+)(\s+(.*))?$/) {        #  new id
2211                if ($id && @$qual) { push @quals, [ $id, $desc, $qual ] }
2212                ($id, $desc, $qual) = ($1, $3 ? $3 : "", []);
2213            }
2214            else {
2215                push @$qual, split;
2216            }
2217        }
2218        close( $fh ) if $close;
2219    
2220        if ($id && @$qual) { push @quals, [ $id, $desc, $qual ] }
2221        return wantarray ? @quals : \@quals;
2222    }
2223    
2224    
2225    #-------------------------------------------------------------------------------
2226    #  Fraction difference for an alignment of two nucleotide sequences in terms of
2227    #  number of differing residues, number of gaps, and number of gap opennings.
2228    #
2229    #     $fraction_diff = fraction_nt_diff( $seq1, $seq2, \%options )
2230    #
2231    #  or
2232    #
2233    #     $fraction_diff = fraction_nt_diff( $seq1, $seq2 )
2234    #     $fraction_diff = fraction_nt_diff( $seq1, $seq2, $gap_wgt )
2235    #     $fraction_diff = fraction_nt_diff( $seq1, $seq2, $open_wgt, $extend_wgt )
2236    #
2237    #  Options:
2238    #
2239    #      gap      => $gap_wgt          # Gap open and extend weight (D = 0.5)
2240    #      open     => $open_wgt         # Gap openning weight (D = gap_wgt)
2241    #      extend   => $extend_wgt       # Gap extension weight (D = open_wgt)
2242    #      t_gap    => $term_gap_wgt     # Terminal open and extend weight
2243    #      t_open   => $term_open_wgt    # Terminal gap open weight (D = open_wgt)
2244    #      t_extend => $term_extend_wgt  # Terminal gap extend weight (D = extend_wgt)
2245    #
2246    #  Default gap open and gap extend weights are 1/2.  Beware that
2247    #
2248    #     $fraction_diff = fraction_nt_diff( $seq1, $seq2, 1 )
2249    #
2250    #  and
2251    #
2252    #     $fraction_diff = fraction_nt_diff( $seq1, $seq2, 1, 0 )
2253    #
2254    #  are different.  The first has equal openning and extension weights, whereas
2255    #  the second has an openning weight of 1, and and extension weight of 0 (it
2256    #  only penalizes the number of runs of gaps).
2257    #-------------------------------------------------------------------------------
2258    sub fraction_nt_diff
2259    {
2260        my ( $npos, $nid, $ndif, $ngap, $nopen, $tgap, $topen ) = interpret_nt_align( @_[0,1] );
2261    
2262        my $diff_scr;
2263        if ( ref( $_[2] ) eq 'HASH' )
2264        {
2265            my $opts = $_[2];
2266            my $gap_open    = defined $opts->{ open }     ? $opts->{ open }
2267                            : defined $opts->{ gap }      ? $opts->{ gap }
2268                            : 0.5;
2269            my $gap_extend  = defined $opts->{ extend }   ? $opts->{ extend }
2270                            : $gap_open;
2271            my $term_open   = defined $opts->{ t_open }   ? $opts->{ t_open }
2272                            : defined $opts->{ t_gap }    ? $opts->{ t_gap }
2273                            : $gap_open;
2274            my $term_extend = defined $opts->{ t_extend } ? $opts->{ t_extend }
2275                            : defined $opts->{ t_gap }    ? $opts->{ t_gap }
2276                            : $gap_extend;
2277    
2278            $nopen -= $topen;
2279            $ngap  -= $tgap;
2280            $diff_scr = $ndif + $gap_open  * $nopen + $gap_extend  * ($ngap-$nopen)
2281                              + $term_open * $topen + $term_extend * ($tgap-$topen);
2282        }
2283        else
2284        {
2285            my $gap_open   = defined( $_[2] ) ? $_[2] : 0.5;
2286            my $gap_extend = defined( $_[3] ) ? $_[3] : $gap_open;
2287            $diff_scr = $ndif + $gap_open * $nopen + $gap_extend * ($ngap-$nopen);
2288        }
2289        my $ttl_scr = $nid + $diff_scr;
2290    
2291        $ttl_scr ? $diff_scr / $ttl_scr : undef
2292    }
2293    
2294    
2295    #-------------------------------------------------------------------------------
2296    #  Interpret an alignment of two nucleotide sequences in terms of: useful
2297    #  aligned positions (unambiguous, and not a common gap), number of identical
2298    #  residues, number of differing residues, number of gaps, and number of gap
2299    #  opennings.
2300    #
2301    #     ( $npos, $nid, $ndif, $ngap, $nopen, $tgap, $topen ) = interpret_nt_align( $seq1, $seq2 )
2302    #
2303    #  $npos  = total aligned positons (= $nid + $ndif + $ngap)
2304    #  $nid   = number of positions with identical nucleotides (ignoring case)
2305    #  $ndif  = number of positions with differing nucleotides
2306    #  $ngap  = number of positions with gap in one sequence but not the other
2307    #  $nopen = number of runs of gaps
2308    #  $tgap  = number of gaps in runs adjacent to a terminus
2309    #  $topen = number of alignment ends with gaps
2310    #
2311    #  Some of the methods might seem overly complex, but are necessary for cases
2312    #  in which the gaps switch strands in the alignment:
2313    #
2314    #     seq1  ---ACGTGAC--TTGCAGAG
2315    #     seq2  TTT---TGACGG--GCAGGG
2316    #     mask  00000011110000111111
2317    #
2318    #     npos  = 20
2319    #     nid   =  9
2320    #     ndif  =  1
2321    #     ngap  = 10
2322    #     nopen =  4
2323    #     tgap  =  3
2324    #     topen =  1
2325    #
2326    #  Although there are 4 gap opennings, there are only 2 runs in the mask,
2327    #  and the terminal run is length 6, not 3.  (Why handle these?  Because
2328    #  pairs of sequences from a multiple sequence alignment can look like this.)
2329    #-------------------------------------------------------------------------------
2330    sub interpret_nt_align
2331    {
2332        #  Remove alignment columns that are not informative:
2333        my ( $s1, $s2 ) = useful_nt_align( @_[0,1] );
2334        my $nmat = length( $s1 );          # Useful alignment length
2335    
2336        my $m1 = $s1;
2337        $m1 =~ tr/ACGT/\377/;              # Nucleotides to all 1 bits
2338        $m1 =~ tr/\377/\000/c;             # Others (gaps) to null byte
2339        my $m2 = $s2;
2340        $m2 =~ tr/ACGT/\377/;              # Nucleotides to all 1 bits
2341        $m2 =~ tr/\377/\000/c;             # Others (gaps) to null byte
2342        $m1 &= $m2;                        # Gap in either sequence becomes null
2343        $s1 &= $m1;                        # Apply mask to sequence 1
2344        $s2 &= $m1;                        # Apply mask to sequence 2
2345        my $nopen = @{[ $s1 =~ /\000+/g ]}   # Gap opens in sequence 1
2346                  + @{[ $s2 =~ /\000+/g ]};  # Gap opens in sequence 2
2347        my ( $tgap, $topen ) = ( 0, 0 );
2348        if ( $s1 =~ /^(\000+)/ || $s2 =~ /^(\000+)/ ) { $tgap += length( $1 ); $topen++ }
2349        if ( $s1 =~ /(\000+)$/ || $s2 =~ /(\000+)$/ ) { $tgap += length( $1 ); $topen++ }
2350        $s1 =~ tr/\000//d;                 # Remove nulls (former gaps)
2351        $s2 =~ tr/\000//d;                 # Remove nulls (former gaps)
2352        my $ngap = $nmat - length( $s1 );  # Total gaps
2353    
2354        my $xor = $s1 ^ $s2;               # xor of identical residues is null byte
2355        my $nid = ( $xor =~ tr/\000//d );  # Count the nulls (identical residues)
2356        my $ndif = $nmat - $nid - $ngap;
2357    
2358        ( $nmat, $nid, $ndif, $ngap, $nopen, $tgap, $topen )
2359    }
2360    
2361    
2362    sub useful_nt_align
2363    {
2364        my ( $s1, $s2 ) = map { uc $_ } @_;
2365        $s1 =~ tr/U/T/;         # Convert U to T
2366        my $m1 = $s1;
2367        $m1 =~ tr/ACGT-/\377/;  # Allowed symbols to hex FF byte
2368        $m1 =~ tr/\377/\000/c;  # All else to null byte
2369        $s2 =~ tr/U/T/;         # Convert U to T
2370        my $m2 = $s2;
2371        $m2 =~ tr/ACGT-/\377/;  # Allowed symbols to hex FF byte
2372        $m2 =~ tr/\377/\000/c;  # All else to null byte
2373        $m1 &= $m2;             # Invalid in either sequence becomes null
2374        $s1 &= $m1;             # Apply mask to sequence 1
2375        $s1 =~ tr/\000//d;      # Delete nulls in sequence 1
2376        $s2 &= $m1;             # Apply mask to sequence 2
2377        $s2 =~ tr/\000//d;      # Delete nulls in sequence 2
2378        ( $s1, $s2 )
2379    }
2380    
2381    
2382    #-------------------------------------------------------------------------------
2383    #  Interpret an alignment of two protein sequences in terms of: useful
2384    #  aligned positions (unambiguous, and not a common gap), number of identical
2385    #  residues, number of differing residues, number of gaps, and number of gap
2386    #  opennings.
2387    #
2388    #     ( $npos, $nid, $ndif, $ngap, $nopen, $tgap, $topen ) = interpret_aa_align( $seq1, $seq2 )
2389    #
2390    #  $npos  = total aligned positons (= $nid + $ndif + $ngap)
2391    #  $nid   = number of positions with identical amino acids (ignoring case)
2392    #  $ndif  = number of positions with differing amino acids
2393    #  $ngap  = number of positions with gap in one sequence but not the other
2394    #  $nopen = number of runs of gaps
2395    #  $tgap  = number of gaps in runs adjacent to a terminus
2396    #  $topen = number of alignment ends with gaps
2397    #
2398    #-------------------------------------------------------------------------------
2399    sub interpret_aa_align
2400    {
2401        #  Remove alignment columns that are not informative:
2402        my ( $s1, $s2 ) = useful_aa_align( @_[0,1] );
2403        my $nmat = length( $s1 );            # Useful alignment length
2404    
2405        my $m1 = $s1;
2406        $m1 =~ tr/ACDEFGHIKLMNPQRSTUVWY/\377/;  # Amino acids to all 1 bits
2407        $m1 =~ tr/\377/\000/c;               # Others (gaps) to null byte
2408        my $m2 = $s2;
2409        $m2 =~ tr/ACDEFGHIKLMNPQRSTUVWY/\377/;  # Amino acids to all 1 bits
2410        $m2 =~ tr/\377/\000/c;               # Others (gaps) to null byte
2411        $m1 &= $m2;                          # Gap in either sequence becomes null
2412        $s1 &= $m1;                          # Apply mask to sequence 1
2413        $s2 &= $m1;                          # Apply mask to sequence 2
2414        my $nopen = @{[ $s1 =~ /\000+/g ]}   # Gap opens in sequence 1
2415                  + @{[ $s2 =~ /\000+/g ]};  # Gap opens in sequence 2
2416        my ( $tgap, $topen ) = ( 0, 0 );
2417        if ( $s1 =~ /^(\000+)/ || $s2 =~ /^(\000+)/ ) { $tgap += length( $1 ); $topen++ }
2418        if ( $s1 =~ /(\000+)$/ || $s2 =~ /(\000+)$/ ) { $tgap += length( $1 ); $topen++ }
2419        $s1 =~ tr/\000//d;                 # Remove nulls (former gaps)
2420        $s2 =~ tr/\000//d;                 # Remove nulls (former gaps)
2421        my $ngap = $nmat - length( $s1 );  # Total gaps
2422    
2423        my $xor = $s1 ^ $s2;               # xor of identical residues is null byte
2424        my $nid = ( $xor =~ tr/\000//d );  # Count the nulls (identical residues)
2425        my $ndif = $nmat - $nid - $ngap;
2426    
2427        ( $nmat, $nid, $ndif, $ngap, $nopen, $tgap, $topen )
2428    }
2429    
2430    
2431    sub useful_aa_align
2432    {
2433        my ( $s1, $s2 ) = map { uc $_ } @_;
2434        my $m1 = $s1;
2435        $m1 =~ tr/ACDEFGHIKLMNPQRSTUVWY-/\377/;  # Allowed symbols to hex FF byte
2436        $m1 =~ tr/\377/\000/c;  # All else to null byte
2437        my $m2 = $s2;
2438        $m2 =~ tr/ACDEFGHIKLMNPQRSTUVWY-/\377/;  # Allowed symbols to hex FF byte
2439        $m2 =~ tr/\377/\000/c;  # All else to null byte
2440        $m1 &= $m2;             # Invalid in either sequence becomes null
2441        $s1 &= $m1;             # Apply mask to sequence 1
2442        $s1 =~ tr/\000//d;      # Delete nulls in sequence 1
2443        $s2 &= $m1;             # Apply mask to sequence 2
2444        $s2 =~ tr/\000//d;      # Delete nulls in sequence 2
2445        ( $s1, $s2 )
2446    }
2447    
2448    
2449  1;  1;

Legend:
Removed from v.1.6  
changed lines
  Added in v.1.20

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3