[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.19, Sat Aug 21 17:29:14 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    #  Remove all alignment gaps from sequences:
92    #
93    #   @packed_seqs = pack_sequences(  @seqs )
94    #   @packed_seqs = pack_sequences( \@seqs )
95    #  \@packed_seqs = pack_sequences(  @seqs )
96    #  \@packed_seqs = pack_sequences( \@seqs )
97    #
98    # Basic sequence manipulation functions:
99    #
100  #  @entry  = subseq_DNA_entry( @seq_entry, $from, $to [, $fix_id] );  #  @entry  = subseq_DNA_entry( @seq_entry, $from, $to [, $fix_id] );
101  #  @entry  = subseq_RNA_entry( @seq_entry, $from, $to [, $fix_id] );  #  @entry  = subseq_RNA_entry( @seq_entry, $from, $to [, $fix_id] );
102    #  $DNAseq = DNA_subseq(  $seq, $from, $to );
103    #  $DNAseq = DNA_subseq( \$seq, $from, $to );
104    #  $RNAseq = RNA_subseq(  $seq, $from, $to );
105    #  $RNAseq = RNA_subseq( \$seq, $from, $to );
106  #  @entry  = complement_DNA_entry( @seq_entry [, $fix_id] );  #  @entry  = complement_DNA_entry( @seq_entry [, $fix_id] );
107  #  @entry  = complement_RNA_entry( @seq_entry [, $fix_id] );  #  @entry  = complement_RNA_entry( @seq_entry [, $fix_id] );
108  #  $DNAseq = complement_DNA_seq( $NA_seq );  #  $DNAseq = complement_DNA_seq( $NA_seq );
# Line 60  Line 112 
112  #  $seq    = pack_seq( $sequence )  #  $seq    = pack_seq( $sequence )
113  #  $seq    = clean_ae_sequence( $seq )  #  $seq    = clean_ae_sequence( $seq )
114  #  #
115  #  $seq = translate_seq( $seq [, $met_start] )  #  $aa = translate_seq( $nt, $met_start )
116    #  $aa = translate_seq( $nt )
117  #  $aa  = translate_codon( $triplet );  #  $aa  = translate_codon( $triplet );
 #  $aa  = translate_uc_DNA_codon( $upcase_DNA_triplet );  
118  #  #
119  #  User-supplied genetic code must be upper case index and match the  #  User-supplied genetic code.  The supplied code needs to be complete in
120  #  DNA versus RNA type of sequence  #  RNA and/or DNA, and upper and/or lower case.  The program guesses based
121    #  on lysine and phenylalanine codons.
122    #
123    #  $aa = translate_seq_with_user_code( $nt, $gen_code_hash, $met_start )
124    #  $aa = translate_seq_with_user_code( $nt, $gen_code_hash )
125  #  #
126  #  Locations (= oriented intervals) are ( id, start, end )  #  Locations (= oriented intervals) are ( id, start, end )
127  #  Intervals are ( id, left, right )  #  Intervals are ( id, left, right )
# Line 81  Line 137 
137  #  Convert GenBank locations to SEED locations  #  Convert GenBank locations to SEED locations
138  #  #
139  #  @seed_locs = gb_location_2_seed( $contig, @gb_locs )  #  @seed_locs = gb_location_2_seed( $contig, @gb_locs )
140    #
141    #  Read quality scores from a fasta-like file:
142    #
143    #  @seq_entries = read_qual( )               #  STDIN
144    # \@seq_entries = read_qual( )               #  STDIN
145    #  @seq_entries = read_qual( \*FILEHANDLE )
146    # \@seq_entries = read_qual( \*FILEHANDLE )
147    #  @seq_entries = read_qual(  $filename )
148    # \@seq_entries = read_qual(  $filename )
149    #
150    #  Evaluate alignments:
151    #
152    #  $fraction_diff = fraction_nt_diff( $seq1, $seq2, \%options )
153    #  $fraction_diff = fraction_nt_diff( $seq1, $seq2 )
154    #  $fraction_diff = fraction_nt_diff( $seq1, $seq2, $gap_weight )
155    #  $fraction_diff = fraction_nt_diff( $seq1, $seq2, $gap_open, $gap_extend )
156    #
157    #  ( $npos, $nid, $ndif, $ngap, $nopen, $tgap, $topen ) = interpret_nt_align( $seq1, $seq2 )
158    #  ( $npos, $nid, $ndif, $ngap, $nopen, $tgap, $topen ) = interpret_aa_align( $seq1, $seq2 )
159    #
160    
161  use strict;  use strict;
162    use Carp;
163  use gjolib qw( wrap_text );  use Data::Dumper;
164    
165  #  Exported global variables:  #  Exported global variables:
166    
# Line 128  Line 203 
203          seq_data_by_id          seq_data_by_id
204    
205          pack_alignment          pack_alignment
206            pack_sequences
207    
208          subseq_DNA_entry          subseq_DNA_entry
209          subseq_RNA_entry          subseq_RNA_entry
210            DNA_subseq
211            RNA_subseq
212          complement_DNA_entry          complement_DNA_entry
213          complement_RNA_entry          complement_RNA_entry
214          complement_DNA_seq          complement_DNA_seq
# Line 152  Line 230 
230          reverse_intervals          reverse_intervals
231    
232          gb_location_2_seed          gb_location_2_seed
233    
234            read_qual
235    
236            fraction_nt_diff
237            interpret_nt_align
238            interpret_aa_align
239          );          );
240    
241  our @EXPORT_OK = qw(  our @EXPORT_OK = qw(
# Line 198  Line 282 
282      if ( ! ref( $file ) )      if ( ! ref( $file ) )
283      {      {
284          my $fh;          my $fh;
285          -f $file or die "Could not find input file \"$file\"\n";          if    ( -f $file                       ) { }
286          open( $fh, "<$file" ) || die "Could not open \"$file\" for input\n";          elsif (    $file =~ /^>(.+)$/ && -f $1 ) { $file = $1 }
287            else { die "Could not find input file '$file'\n" }
288            open( $fh, "<$file" ) || die "Could not open '$file' for input\n";
289          return ( $fh, $file, 1 );          return ( $fh, $file, 1 );
290      }      }
291    
# Line 219  Line 305 
305    
306    
307  #-----------------------------------------------------------------------------  #-----------------------------------------------------------------------------
308  #  Read fasta sequences.  #  Read fasta sequences.  Save the contents in a list of refs to arrays:
309  #  Save the contents in a list of refs to arrays:  (id, description, seq)  #
310    #     $seq_entry = [ id, description, seq ]
311  #  #
312  #     @seq_entries = read_fasta( )               #  STDIN  #     @seq_entries = read_fasta( )               #  STDIN
313  #    \@seq_entries = read_fasta( )               #  STDIN  #    \@seq_entries = read_fasta( )               #  STDIN
# Line 228  Line 315 
315  #    \@seq_entries = read_fasta( \*FILEHANDLE )  #    \@seq_entries = read_fasta( \*FILEHANDLE )
316  #     @seq_entries = read_fasta(  $filename )  #     @seq_entries = read_fasta(  $filename )
317  #    \@seq_entries = read_fasta(  $filename )  #    \@seq_entries = read_fasta(  $filename )
318    #  #  @seq_entries = read_fasta( "command |" )   #  open and read from pipe
319    #  # \@seq_entries = read_fasta( "command |" )   #  open and read from pipe
320    #     @seq_entries = read_fasta( \$string )      #  reference to file as string
321    #    \@seq_entries = read_fasta( \$string )      #  reference to file as string
322    #
323  #-----------------------------------------------------------------------------  #-----------------------------------------------------------------------------
324  sub read_fasta {  sub read_fasta
325    {
326        my @seqs;
327        if ( $_[0] && ref $_[0] eq 'SCALAR' )
328        {
329            @seqs = map { $_->[2] =~ tr/ \n\r\t//d; $_ }
330                    map { /^(\S+)([ \t]+([^\n]*\S)?\s*)?\n(.+)$/s ? [ $1, $3 || '', $4 ] : () }
331                    split /^>\s*/m, ${$_[0]};
332        }
333        else
334        {
335            @seqs = map { $_->[2] =~ tr/ \n\r\t//d; $_ }
336                    map { /^(\S+)([ \t]+([^\n]*\S)?\s*)?\n(.+)$/s ? [ $1, $3 || '', $4 ] : () }
337                    split /^>\s*/m, slurp( @_ );
338        }
339    
340        wantarray() ? @seqs : \@seqs;
341    }
342    
343    #-----------------------------------------------------------------------------
344    #  A fast file reader:
345    #
346    #     $data = slurp( )               #  \*STDIN
347    #     $data = slurp( \*FILEHANDLE )  #  an open file handle
348    #     $data = slurp(  $filename )    #  a file name
349    #     $data = slurp( "<$filename" )  #  file with explicit direction
350    #   # $data = slurp( "$command |" )  #  open and read from pipe
351    #
352    #  Note:  It is faster to read lines by reading the file and splitting
353    #         than by reading the lines sequentially.  If space is not an
354    #         issue, this is the way to go.  If space is an issue, then lines
355    #         or records should be processed one-by-one (rather than loading
356    #         the whole input into a string or array).
357    #-----------------------------------------------------------------------------
358    sub slurp
359    {
360        my ( $fh, $close );
361        if ( ref $_[0] eq 'GLOB' )
362        {
363            $fh = shift;
364        }
365        elsif ( $_[0] && ! ref $_[0] )
366        {
367            my $file = shift;
368            if    ( -f $file                       ) { $file = "<$file" }
369            elsif (    $file =~ /^<(.*)$/ && -f $1 ) { }  # Explicit read
370          # elsif (    $file =~ /\S\s*\|$/         ) { }  # Read from a pipe
371            else                                     { return undef }
372            open $fh, $file or return undef;
373            $close = 1;
374        }
375        else
376        {
377            $fh = \*STDIN;
378            $close = 0;
379        }
380    
381        my $out = '';
382        my $inc = 1048576;
383        my $end =       0;
384        my $read;
385        while ( $read = read( $fh, $out, $inc, $end ) ) { $end += $read }
386        close( $fh ) if $close;
387    
388        $out;
389    }
390    
391    
392    #-----------------------------------------------------------------------------
393    #  Previous, 50% slower fasta reader:
394    #-----------------------------------------------------------------------------
395    sub read_fasta_0
396    {
397      my ( $fh, $name, $close, $unused ) = input_filehandle( $_[0] );      my ( $fh, $name, $close, $unused ) = input_filehandle( $_[0] );
398      $unused && die "Bad reference type (" . ref( $unused ) . ") passed to read_fasta\n";      $unused && die "Bad reference type (" . ref( $unused ) . ") passed to read_fasta\n";
399    
# Line 255  Line 419 
419    
420    
421  #-----------------------------------------------------------------------------  #-----------------------------------------------------------------------------
422  #  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
423  #  Return the contents as an array:  (id, description, seq)  #  read_fasta(), but can handle an arbitrarily large file.  State information
424    #  is retained in hashes, so any number of streams can be interlaced.
425    #
426    #      @entry = read_next_fasta_seq( \*FILEHANDLE )
427    #     \@entry = read_next_fasta_seq( \*FILEHANDLE )
428    #      @entry = read_next_fasta_seq(  $filename )
429    #     \@entry = read_next_fasta_seq(  $filename )
430    #      @entry = read_next_fasta_seq()                # \*STDIN
431    #     \@entry = read_next_fasta_seq()                # \*STDIN
432  #  #
433  #     @seq_entry = read_next_fasta_seq( \*FILEHANDLE )  #      @entry = ( $id, $description, $seq )
434    #
435    #  When reading at the end of file, () is returned.
436    #  With a filename, reading past this will reopen the file at the beginning.
437  #-----------------------------------------------------------------------------  #-----------------------------------------------------------------------------
438  #  Reading always overshoots, so save next id and description  #  Reading always overshoots, so save next id and description
439    
440  {   #  Use bare block to scope the header hash  {   #  Use bare block to scope the header hash
441    
442      my %next_header;      my %next_header;
443        my %file_handle;
444        my %close_file;
445    
446      sub read_next_fasta_seq {      sub read_next_fasta_seq
447          my $fh = shift;      {
448          my ( $id, $desc );          $_[0] ||= \*STDIN;               #  Undefined $_[0] fails with use warn
449            my $fh = $file_handle{ $_[0] };
450            if ( ! $fh )
451            {
452                if ( ref $_[0] )
453                {
454                    return () if ref $_[0] ne 'GLOB';
455                    $fh = $_[0];
456                }
457                else
458                {
459                    my $file = $_[0];
460                    if    ( -f $file                       ) { $file = "<$file" }
461                    elsif (    $file =~ /^<(.*)$/ && -f $1 ) { }  # Explicit read
462                  # elsif (    $file =~ /\S\s*\|$/         ) { }  # Read from a pipe
463                    else                                     { return () }
464                    open $fh, $file or return ();
465                    $close_file{ $fh } = 1;
466                }
467                $file_handle{ $_[0] } = $fh;
468            }
469    
470          if ( defined( $next_header{$fh} ) ) {          my ( $id, $desc, $seq ) = ( undef, '', '' );
471            if ( defined( $next_header{$fh} ) )
472            {
473              ( $id, $desc ) = parse_fasta_title( $next_header{$fh} );              ( $id, $desc ) = parse_fasta_title( $next_header{$fh} );
474          }          }
475          else {          else
476              $next_header{$fh} = "";          {
477              ( $id, $desc ) = ( undef, "" );              $next_header{$fh} = '';
478          }          }
         my $seq = "";  
479    
480          while ( <$fh> ) {          while ( <$fh> )
481            {
482              chomp;              chomp;
483              if ( /^>/ ) {        #  new id              if ( /^>/ )        #  new id
484                {
485                  $next_header{$fh} = $_;                  $next_header{$fh} = $_;
486                  if ( defined($id) && $seq )                  if ( defined($id) && $seq )
487                  {                  {
488                      return wantarray ? ($id, $desc, $seq) : [$id, $desc, $seq]                      return wantarray ? ($id, $desc, $seq) : [$id, $desc, $seq]
489                  }                  }
490                  ( $id, $desc ) = parse_fasta_title( $next_header{$fh} );                  ( $id, $desc ) = parse_fasta_title( $next_header{$fh} );
491                  $seq = "";                  $seq = '';
492              }              }
493              else {              else
494                  tr/     0-9//d;              {
495                    tr/ \t\r//d;
496                  $seq .= $_ ;                  $seq .= $_ ;
497              }              }
498          }          }
499    
500          #  Done with file, delete "next header"          #  Done with file; there is no next header:
501    
502          delete $next_header{$fh};          delete $next_header{$fh};
503          return ( defined($id) && $seq ) ? ( wantarray ? ($id, $desc, $seq)  
504                                                        : [$id, $desc, $seq]          #  Return last set of data:
505                                            )  
506                                          : () ;          if ( defined($id) && $seq )
507            {
508                return wantarray ? ($id,$desc,$seq) : [$id,$desc,$seq]
509            }
510    
511            #  Or close everything out (returning the empty list tells caller
512            #  that we are done)
513    
514            if ( $close_file{ $fh } ) { close $fh; delete $close_file{ $fh } }
515            delete $file_handle{ $_[0] };
516    
517            return ();
518      }      }
519  }  }
520    
# Line 352  Line 564 
564  #     ($id, $def) = parse_fasta_title( $title )  #     ($id, $def) = parse_fasta_title( $title )
565  #     ($id, $def) = split_fasta_title( $title )  #     ($id, $def) = split_fasta_title( $title )
566  #-----------------------------------------------------------------------------  #-----------------------------------------------------------------------------
567  sub parse_fasta_title {  sub parse_fasta_title
568    {
569      my $title = shift;      my $title = shift;
570      chomp;      chomp $title;
     if ($title =~ /^>?\s*(\S+)(:?\s+(.*\S)\s*)?$/) {  
         return ($1, $3 ? $3 : "");  
     }  
     elsif ($title =~ /^>/) {  
         return ("", "");  
     }  
     else {  
         return (undef, "");  
     }  
 }  
571    
572  sub split_fasta_title {      return $title =~ /^>?\s*(\S+)(\s+(.*\S)?\s*)?$/ ? ( $1, $3 || '' )
573      parse_fasta_title ( shift );           : $title =~ /^>/                           ? ( '', '' )
574             :                                            ( undef, undef )
575  }  }
576    
577    sub split_fasta_title { parse_fasta_title( @_ ) }
578    
579    
580  #-----------------------------------------------------------------------------  #-----------------------------------------------------------------------------
581  #  Helper function for defining an output filehandle:  #  Helper function for defining an output filehandle:
# Line 377  Line 583 
583  #     string is taken as file name to be openend  #     string is taken as file name to be openend
584  #     undef or "" defaults to STDOUT  #     undef or "" defaults to STDOUT
585  #  #
586  #    ( \*FH, $name, $close [, $file] ) = output_filehandle( $file );  #    ( \*FH, $close [, $file] ) = output_filehandle( $file );
587  #  #
588  #-----------------------------------------------------------------------------  #-----------------------------------------------------------------------------
589  sub output_filehandle  sub output_filehandle
590  {  {
591      my $file = shift;      my $file = shift;
592    
593        #  Null string or undef
594    
595        return ( \*STDOUT, 0 ) if ( ! defined( $file ) || ( $file eq "" ) );
596    
597      #  FILEHANDLE      #  FILEHANDLE
598    
599      return ( $file, $file, 0 ) if ( ref( $file ) eq "GLOB" );      return ( $file, 0 ) if ( ref( $file ) eq "GLOB" );
600    
601      #  Null string or undef      #  Some other kind of reference; return the unused value
602    
603      return ( \*STDOUT, "", 0 ) if ( ! defined( $file ) || ( $file eq "" ) );      return ( \*STDOUT, 0, $file ) if ref( $file );
604    
605      #  File name      #  File name
606    
     if ( ! ref( $file ) )  
     {  
607          my $fh;          my $fh;
608          open( $fh, ">$file" ) || die "Could not open output $file\n";          open( $fh, ">$file" ) || die "Could not open output $file\n";
609          return ( $fh, $file, 1 );      return ( $fh, 1 );
     }  
   
     #  Some other kind of reference; return the unused value  
   
     return ( \*STDOUT, undef, 0, $file );  
610  }  }
611    
612    
# Line 427  Line 630 
630  #     print_alignment_as_fasta(  $filename,   \@seq_entry_list );  #     print_alignment_as_fasta(  $filename,   \@seq_entry_list );
631  #-----------------------------------------------------------------------------  #-----------------------------------------------------------------------------
632  sub print_alignment_as_fasta {  sub print_alignment_as_fasta {
633      my ( $fh, undef, $close, $unused ) = output_filehandle( shift );      my ( $fh, $close, $unused ) = output_filehandle( shift );
634      ( unshift @_, $unused ) if $unused;      ( unshift @_, $unused ) if $unused;
635    
636      ( 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";
637    
638      #  Expand the sequence entry list if necessary:      #  Expand the sequence entry list if necessary:
639    
# Line 454  Line 657 
657  #     print_alignment_as_phylip(  $filename,   \@seq_entry_list );  #     print_alignment_as_phylip(  $filename,   \@seq_entry_list );
658  #-----------------------------------------------------------------------------  #-----------------------------------------------------------------------------
659  sub print_alignment_as_phylip {  sub print_alignment_as_phylip {
660      my ( $fh, undef, $close, $unused ) = output_filehandle( shift );      my ( $fh, $close, $unused ) = output_filehandle( shift );
661      ( unshift @_, $unused ) if $unused;      ( unshift @_, $unused ) if $unused;
662    
663      ( 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 716 
716  #     print_alignment_as_nexus(  $filename,   [ \%label_hash, ] \@seq_entry_list );  #     print_alignment_as_nexus(  $filename,   [ \%label_hash, ] \@seq_entry_list );
717  #-----------------------------------------------------------------------------  #-----------------------------------------------------------------------------
718  sub print_alignment_as_nexus {  sub print_alignment_as_nexus {
719      my ( $fh, undef, $close, $unused ) = output_filehandle( shift );      my ( $fh, $close, $unused ) = output_filehandle( shift );
720      ( unshift @_, $unused ) if $unused;      ( unshift @_, $unused ) if $unused;
721    
722      my $lbls = ( ref( $_[0] ) eq "HASH" ) ? shift : undef;      my $lbls = ( ref( $_[0] ) eq "HASH" ) ? shift : undef;
# Line 587  Line 790 
790    
791    
792  #-----------------------------------------------------------------------------  #-----------------------------------------------------------------------------
793  #  Print one sequence in fasta format to an open file  #  Print one sequence in fasta format to an open file.
794  #  #
795  #     print_seq_as_fasta( \*FILEHANDLE, $id, $desc, $seq );  #     print_seq_as_fasta( \*FILEHANDLE, $id, $desc, $seq );
796  #     print_seq_as_fasta( \*FILEHANDLE, @seq_entry );  #     print_seq_as_fasta(               $id, $desc, $seq );
797  #-----------------------------------------------------------------------------  #     print_seq_as_fasta( \*FILEHANDLE, $id,        $seq );
798  sub print_seq_as_fasta {  #     print_seq_as_fasta(               $id,        $seq );
799      my $fh = shift;  #
800      my ($id, $desc, $seq) = @_;  #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
801    #  print_seq_as_fasta() is meant more as a internal support routine than an
802      printf $fh ($desc) ? ">$id $desc\n" : ">$id\n";  #  external interface.  To print a single sequence to a named file use:
803      my $len = length($seq);  #
804      for (my $i = 0; $i < $len; $i += 60) {  #     print_alignment_as_fasta( $filename, [ $id, $desc, $seq ] );
805          print $fh substr($seq, $i, 60) . "\n";  #     print_alignment_as_fasta( $filename, [ $id,        $seq ] );
806      }  #-----------------------------------------------------------------------------
807    sub print_seq_as_fasta
808    {
809        my $fh = ( ref $_[0] eq 'GLOB' ) ? shift : \*STDOUT;
810        return if ( @_ < 2 ) || ( @_ > 3 ) || ! ( defined $_[0] && defined $_[-1] );
811        #  Print header line
812        print $fh  ( @_ == 3 && defined $_[1] && $_[1] =~ /\S/ ) ? ">$_[0] $_[1]\n" : ">$_[0]\n";
813        #  Print sequence, 60 chars per line
814        print $fh  join( "\n", $_[-1] =~ m/.{1,60}/g ), "\n";
815  }  }
816    
817    
# Line 633  Line 844 
844    
845    
846  #-----------------------------------------------------------------------------  #-----------------------------------------------------------------------------
847    #  Return a string with text wrapped to defined line lengths:
848    #
849    #     $wrapped_text = wrap_text( $str )                  # default len   =  80
850    #     $wrapped_text = wrap_text( $str, $len )            # default ind   =   0
851    #     $wrapped_text = wrap_text( $str, $len, $indent )   # default ind_n = ind
852    #     $wrapped_text = wrap_text( $str, $len, $indent_1, $indent_n )
853    #-----------------------------------------------------------------------------
854    sub wrap_text {
855        my ($str, $len, $ind, $indn) = @_;
856    
857        defined($str)  || die "wrap_text called without a string\n";
858        defined($len)  || ($len  =   80);
859        defined($ind)  || ($ind  =    0);
860        ($ind  < $len) || die "wrap error: indent greater than line length\n";
861        defined($indn) || ($indn = $ind);
862        ($indn < $len) || die "wrap error: indent_n greater than line length\n";
863    
864        $str =~ s/\s+$//;
865        $str =~ s/^\s+//;
866        my ($maxchr, $maxchr1);
867        my (@lines) = ();
868    
869        while ($str) {
870            $maxchr1 = ($maxchr = $len - $ind) - 1;
871            if ($maxchr >= length($str)) {
872                push @lines, (" " x $ind) . $str;
873                last;
874            }
875            elsif ($str =~ /^(.{0,$maxchr1}\S)\s+(\S.*)$/) { # no expr in {}
876                push @lines, (" " x $ind) . $1;
877                $str = $2;
878            }
879            elsif ($str =~ /^(.{0,$maxchr1}-)(.*)$/) {
880                push @lines, (" " x $ind) . $1;
881                $str = $2;
882            }
883            else {
884                push @lines, (" " x $ind) . substr($str, 0, $maxchr);
885                $str = substr($str, $maxchr);
886            }
887            $ind = $indn;
888        }
889    
890        return join("\n", @lines);
891    }
892    
893    
894    #-----------------------------------------------------------------------------
895  #  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)
896  #  #
897  #     my \%seq_ind  = index_seq_list(  @seq_list );  #     my \%seq_ind  = index_seq_list(  @seq_list );
# Line 721  Line 980 
980  }  }
981    
982  #-----------------------------------------------------------------------------  #-----------------------------------------------------------------------------
983    #  Remove all alignment gaps from sequences:
984    #
985    #   @packed_seqs = pack_sequences(  @seqs )
986    #   @packed_seqs = pack_sequences( \@seqs )
987    #  \@packed_seqs = pack_sequences(  @seqs )
988    #  \@packed_seqs = pack_sequences( \@seqs )
989    #
990    #-----------------------------------------------------------------------------
991    
992    sub pack_sequences
993    {
994        my @seqs = ( ref( $_[0] ) eq 'ARRAY' and ref( $_[0]->[0] ) eq 'ARRAY' ) ? @{$_[0]} : @_;
995        @seqs or return wantarray ? () : [];
996    
997        my @seqs2 = map { [ $_->[0], $_->[1], pack_seq( $_->[2] ) ] } @seqs;
998    
999        return wantarray ? @seqs2 : \@seqs2;
1000    }
1001    
1002    #-----------------------------------------------------------------------------
1003  #  Some simple sequence manipulations:  #  Some simple sequence manipulations:
1004  #  #
1005  #     @entry  = subseq_DNA_entry( @seq_entry, $from, $to [, $fix_id] );  #     @entry  = subseq_DNA_entry( @seq_entry, $from, $to [, $fix_id] );
# Line 794  Line 1073 
1073  }  }
1074    
1075    
1076    sub DNA_subseq
1077    {
1078        my ( $seq, $from, $to ) = @_;
1079    
1080        my $len = ref( $seq ) eq 'SCALAR' ? length( $$seq )
1081                                          : length(  $seq );
1082        if ( ( $from eq '$' ) || ( $from eq "" ) ) { $from = $len }
1083        if ( ( $to   eq '$' ) || ( ! $to       ) ) { $to   = $len }
1084    
1085        my $left  = ( $from < $to ) ? $from : $to;
1086        my $right = ( $from < $to ) ? $to   : $from;
1087        if ( ( $right < 1 ) || ( $left > $len ) ) { return "" }
1088        if ( $right > $len ) { $right = $len }
1089        if ( $left  < 1    ) { $left  =    1 }
1090    
1091        my $subseq = ref( $seq ) eq 'SCALAR' ? substr( $$seq, $left-1, $right-$left+1 )
1092                                             : substr(  $seq, $left-1, $right-$left+1 );
1093    
1094        if ( $from > $to )
1095        {
1096            $subseq = reverse $subseq;
1097            $subseq =~ tr[ACGTUKMRSWYBDHVNacgtukmrswybdhvn]
1098                         [TGCAAMKYSWRVHDBNtgcaamkyswrvhdbn];
1099        }
1100    
1101        $subseq
1102    }
1103    
1104    
1105    sub RNA_subseq
1106    {
1107        my ( $seq, $from, $to ) = @_;
1108    
1109        my $len = ref( $seq ) eq 'SCALAR' ? length( $$seq )
1110                                          : length(  $seq );
1111        if ( ( $from eq '$' ) || ( $from eq "" ) ) { $from = $len }
1112        if ( ( $to   eq '$' ) || ( ! $to       ) ) { $to   = $len }
1113    
1114        my $left  = ( $from < $to ) ? $from : $to;
1115        my $right = ( $from < $to ) ? $to   : $from;
1116        if ( ( $right < 1 ) || ( $left > $len ) ) { return "" }
1117        if ( $right > $len ) { $right = $len }
1118        if ( $left  < 1    ) { $left  =    1 }
1119    
1120        my $subseq = ref( $seq ) eq 'SCALAR' ? substr( $$seq, $left-1, $right-$left+1 )
1121                                             : substr(  $seq, $left-1, $right-$left+1 );
1122    
1123        if ( $from > $to )
1124        {
1125            $subseq = reverse $subseq;
1126            $subseq =~ tr[ACGTUKMRSWYBDHVNacgtukmrswybdhvn]
1127                         [UGCAAMKYSWRVHDBNugcaamkyswrvhdbn];
1128        }
1129    
1130        $subseq
1131    }
1132    
1133    
1134  sub complement_DNA_entry {  sub complement_DNA_entry {
1135      my ($id, $desc, $seq, $fix_id) = @_;      my ($id, $desc, $seq, $fix_id) = @_;
1136      $fix_id ||= 0;     #  fix undef values      $fix_id ||= 0;     #  fix undef values
# Line 868  Line 1205 
1205    
1206  sub pack_seq {  sub pack_seq {
1207      my $seq = shift;      my $seq = shift;
1208      $seq =~ tr/A-Za-z//cd;      $seq =~ tr/A-Za-z*//cd;
1209      return $seq;      $seq;
1210  }  }
1211    
1212    
# Line 911  Line 1248 
1248  #  Translate nucleotides to one letter protein:  #  Translate nucleotides to one letter protein:
1249  #  #
1250  #  $seq = translate_seq( $seq [, $met_start] )  #  $seq = translate_seq( $seq [, $met_start] )
1251  #  $aa  = translate_codon( $triplet );  #     $aa  = translate_codon( $triplet )
1252  #  $aa  = translate_uc_DNA_codon( $upcase_DNA_triplet );  #     $aa  = translate_DNA_codon( $triplet )     # Does not rely on DNA
1253    #     $aa  = translate_uc_DNA_codon( $triplet )  # Does not rely on uc or DNA
1254  #  #
1255  #  User-supplied genetic code must be upper case index and match the  #  User-supplied genetic code must be upper case index and match the
1256  #  DNA versus RNA type of sequence  #  DNA versus RNA type of sequence
# Line 929  Line 1267 
1267    
1268      # DNA version      # DNA version
1269    
1270      TTT => "F",  TCT => "S",  TAT => "Y",  TGT => "C",      TTT => 'F',  TCT => 'S',  TAT => 'Y',  TGT => 'C',
1271      TTC => "F",  TCC => "S",  TAC => "Y",  TGC => "C",      TTC => 'F',  TCC => 'S',  TAC => 'Y',  TGC => 'C',
1272      TTA => "L",  TCA => "S",  TAA => "*",  TGA => "*",      TTA => 'L',  TCA => 'S',  TAA => '*',  TGA => '*',
1273      TTG => "L",  TCG => "S",  TAG => "*",  TGG => "W",      TTG => 'L',  TCG => 'S',  TAG => '*',  TGG => 'W',
1274      CTT => "L",  CCT => "P",  CAT => "H",  CGT => "R",      CTT => 'L',  CCT => 'P',  CAT => 'H',  CGT => 'R',
1275      CTC => "L",  CCC => "P",  CAC => "H",  CGC => "R",      CTC => 'L',  CCC => 'P',  CAC => 'H',  CGC => 'R',
1276      CTA => "L",  CCA => "P",  CAA => "Q",  CGA => "R",      CTA => 'L',  CCA => 'P',  CAA => 'Q',  CGA => 'R',
1277      CTG => "L",  CCG => "P",  CAG => "Q",  CGG => "R",      CTG => 'L',  CCG => 'P',  CAG => 'Q',  CGG => 'R',
1278      ATT => "I",  ACT => "T",  AAT => "N",  AGT => "S",      ATT => 'I',  ACT => 'T',  AAT => 'N',  AGT => 'S',
1279      ATC => "I",  ACC => "T",  AAC => "N",  AGC => "S",      ATC => 'I',  ACC => 'T',  AAC => 'N',  AGC => 'S',
1280      ATA => "I",  ACA => "T",  AAA => "K",  AGA => "R",      ATA => 'I',  ACA => 'T',  AAA => 'K',  AGA => 'R',
1281      ATG => "M",  ACG => "T",  AAG => "K",  AGG => "R",      ATG => 'M',  ACG => 'T',  AAG => 'K',  AGG => 'R',
1282      GTT => "V",  GCT => "A",  GAT => "D",  GGT => "G",      GTT => 'V',  GCT => 'A',  GAT => 'D',  GGT => 'G',
1283      GTC => "V",  GCC => "A",  GAC => "D",  GGC => "G",      GTC => 'V',  GCC => 'A',  GAC => 'D',  GGC => 'G',
1284      GTA => "V",  GCA => "A",  GAA => "E",  GGA => "G",      GTA => 'V',  GCA => 'A',  GAA => 'E',  GGA => 'G',
1285      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",  
1286    
1287      #  The following ambiguous encodings are not necessary,  but      #  The following ambiguous encodings are not necessary,  but
1288      #  speed up the processing of some ambiguous triplets:      #  speed up the processing of some ambiguous triplets:
1289    
1290      TTY => "F",  TCY => "S",  TAY => "Y",  TGY => "C",      TTY => 'F',  TCY => 'S',  TAY => 'Y',  TGY => 'C',
1291      TTR => "L",  TCR => "S",  TAR => "*",      TTR => 'L',  TCR => 'S',  TAR => '*',
1292                   TCN => "S",                   TCN => 'S',
1293      CTY => "L",  CCY => "P",  CAY => "H",  CGY => "R",      CTY => 'L',  CCY => 'P',  CAY => 'H',  CGY => 'R',
1294      CTR => "L",  CCR => "P",  CAR => "Q",  CGR => "R",      CTR => 'L',  CCR => 'P',  CAR => 'Q',  CGR => 'R',
1295      CTN => "L",  CCN => "P",               CGN => "R",      CTN => 'L',  CCN => 'P',               CGN => 'R',
1296      ATY => "I",  ACY => "T",  AAY => "N",  AGY => "S",      ATY => 'I',  ACY => 'T',  AAY => 'N',  AGY => 'S',
1297                   ACR => "T",  AAR => "K",  AGR => "R",                   ACR => 'T',  AAR => 'K',  AGR => 'R',
1298                   ACN => "T",                   ACN => 'T',
1299      GTY => "V",  GCY => "A",  GAY => "D",  GGY => "G",      GTY => 'V',  GCY => 'A',  GAY => 'D',  GGY => 'G',
1300      GTR => "V",  GCR => "A",  GAR => "E",  GGR => "G",      GTR => 'V',  GCR => 'A',  GAR => 'E',  GGR => 'G',
1301      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"  
1302  );  );
1303    
1304    #  Add RNA by construction:
1305    
1306    foreach ( grep { /T/ } keys %genetic_code )
1307    {
1308        my $codon = $_;
1309        $codon =~ s/T/U/g;
1310        $genetic_code{ $codon } = lc $genetic_code{ $_ }
1311    }
1312    
1313  #  Add lower case by construction:  #  Add lower case by construction:
1314    
1315  foreach ( keys %genetic_code ) {  foreach ( keys %genetic_code )
1316    {
1317      $genetic_code{ lc $_ } = lc $genetic_code{ $_ }      $genetic_code{ lc $_ } = lc $genetic_code{ $_ }
1318  }  }
1319    
1320    
1321  #  Construct the genetic code with selanocysteine by difference:  #  Construct the genetic code with selenocysteine by difference:
1322    
1323  %genetic_code_with_U = map { $_ => $genetic_code{ $_ } } keys %genetic_code;  %genetic_code_with_U = %genetic_code;
1324  $genetic_code_with_U{ TGA } = "U";  $genetic_code_with_U{ TGA } = 'U';
1325  $genetic_code_with_U{ tga } = "u";  $genetic_code_with_U{ tga } = 'u';
1326  $genetic_code_with_U{ UGA } = "U";  $genetic_code_with_U{ UGA } = 'U';
1327  $genetic_code_with_U{ uga } = "u";  $genetic_code_with_U{ uga } = 'u';
1328    
1329    
1330  %amino_acid_codons_DNA = (  %amino_acid_codons_DNA = (
# Line 1271  Line 1588 
1588    
1589    
1590  #-----------------------------------------------------------------------------  #-----------------------------------------------------------------------------
1591  #  Translate nucleotides to one letter protein:  #  Translate nucleotides to one letter protein.  Respects case of the
1592    #  nucleotide sequence.
1593  #  #
1594  #      $seq = translate_seq( $seq [, $met_start] )  #      $aa = translate_seq( $nt, $met_start )
1595    #      $aa = translate_seq( $nt )
1596  #  #
1597  #-----------------------------------------------------------------------------  #-----------------------------------------------------------------------------
1598    
1599  sub translate_seq {  sub translate_seq
1600      my $seq = uc shift;  {
1601      $seq =~ tr/UX/TN/;      #  make it DNA, and allow X      my $seq = shift;
1602      $seq =~ tr/-//d;        #  remove gaps      $seq =~ tr/-//d;        #  remove gaps
1603    
1604      my $met = shift || 0;   #  a second argument that is true      my @codons = $seq =~ m/(...?)/g;  #  Will try to translate last 2 nt
1605                              #  forces first amino acid to be Met  
1606                              #  (note: undef is false)      #  A second argument that is true forces first amino acid to be Met
1607    
1608      my $imax = length($seq) - 2;  # will try to translate 2 nucleotides!      my @met;
1609      my $pep = ( ($met && ($imax >= 0)) ? "M" : "" );      if ( ( shift @_ ) && ( my $codon1 = shift @codons ) )
1610      for (my $i = $met ? 3 : 0; $i <= $imax; $i += 3) {      {
1611          $pep .= translate_uc_DNA_codon( substr($seq,$i,3) );          push @met, ( $codon1 =~ /[a-z]/ ? 'm' : 'M' );
1612      }      }
1613    
1614      return $pep;      join( '', @met, map { translate_codon( $_ ) } @codons )
1615  }  }
1616    
1617    
1618  #-----------------------------------------------------------------------------  #-----------------------------------------------------------------------------
1619  #  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.  
1620  #  #
1621  #      $aa = translate_codon( $triplet )  #      $aa = translate_codon( $triplet )
1622    #      $aa = translate_DNA_codon( $triplet )
1623    #      $aa = translate_uc_DNA_codon( $triplet )
1624  #  #
1625  #-----------------------------------------------------------------------------  #-----------------------------------------------------------------------------
1626    
1627  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);  
 }  
1628    
1629    sub translate_uc_DNA_codon { translate_codon( uc $_[0] ) }
1630    
1631  #-----------------------------------------------------------------------------  sub translate_codon
1632  #  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 )  
 #  
 #-----------------------------------------------------------------------------  
   
 sub translate_uc_DNA_codon {  
1633      my $codon = shift;      my $codon = shift;
1634      my $aa;      $codon =~ tr/Uu/Tt/;     #  Make it DNA
1635    
1636      #  Try a simple lookup:      #  Try a simple lookup:
1637    
1638        my $aa;
1639      if ( $aa = $genetic_code{ $codon } ) { return $aa }      if ( $aa = $genetic_code{ $codon } ) { return $aa }
1640    
1641      #  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  
1642    
1643      #  Expand all ambiguous nucleotides to see if they all yield same aa.      $codon = ( $codon =~ /[a-z]/ ) ? lc $codon : uc $codon;
1644      #  Loop order tries to fail quickly with first position change.      if ( $aa = $genetic_code{ $codon } ) { return $aa }
1645    
1646      $aa = "";      #  The code defined above catches simple N, R and Y ambiguities in the
1647      for my $n2 ( @{ $DNA_letter_can_be{ substr($codon,1,1) } } ) {      #  third position.  Other codons (e.g., GG[KMSWBDHV], or even GG) might
1648          for my $n3 ( @{ $DNA_letter_can_be{ substr($codon,2,1) } } ) {      #  be unambiguously translated by converting the last position to N and
1649              for my $n1 ( @{ $DNA_letter_can_be{ substr($codon,0,1) } } ) {      #  seeing if this is in the code table:
1650                  #  set the first value of $aa  
1651                  if ($aa eq "") { $aa = $genetic_code{ $n1 . $n2 . $n3 } }      my $N = ( $codon =~ /[a-z]/ ) ? 'n' : 'N';
1652                  #  or break out if any other amino acid is detected      if ( $aa = $genetic_code{ substr($codon,0,2) . $N } ) { return $aa }
1653                  elsif ($aa ne $genetic_code{ $n1 . $n2 . $n3 } ) { return "X" }  
1654              }      #  Test that codon is valid for an unambiguous aa:
1655          }  
1656        my $X = ( $codon =~ /[a-z]/ ) ? 'x' : 'X';
1657        if ( $codon !~ m/^[ACGTMY][ACGT][ACGTKMRSWYBDHVN]$/i
1658          && $codon !~ m/^YT[AGR]$/i     #  Leu YTR
1659          && $codon !~ m/^MG[AGR]$/i     #  Arg MGR
1660           )
1661        {
1662            return $X;
1663      }      }
1664    
1665      return $aa || "X";      #  Expand all ambiguous nucleotides to see if they all yield same aa.
1666    
1667        my @n1 = @{ $DNA_letter_can_be{ substr( $codon, 0, 1 ) } };
1668        my $n2 =                        substr( $codon, 1, 1 );
1669        my @n3 = @{ $DNA_letter_can_be{ substr( $codon, 2, 1 ) } };
1670        my @triples = map { my $n12 = $_ . $n2; map { $n12 . $_ } @n3 } @n1;
1671    
1672        my $triple = shift @triples;
1673        $aa = $genetic_code{ $triple };
1674        $aa or return $X;
1675    
1676        foreach $triple ( @triples ) { return $X if $aa ne $genetic_code{$triple} }
1677    
1678        return $aa;
1679  }  }
1680    
1681    
# Line 1368  Line 1684 
1684  #  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
1685  #  code, and transform the supplied nucleotide sequence to match.  #  code, and transform the supplied nucleotide sequence to match.
1686  #  #
1687  #  translate_seq_with_user_code($seq, \%gen_code [, $start_with_met] )  #     $aa = translate_seq_with_user_code( $nt, \%gen_code )
1688    #     $aa = translate_seq_with_user_code( $nt, \%gen_code, $start_with_met )
1689  #  #
1690    #  Modified 2007-11-22 to be less intrusive in these diagnoses by sensing
1691    #  the presence of both versions in the user code.
1692  #-----------------------------------------------------------------------------  #-----------------------------------------------------------------------------
1693    
1694  sub translate_seq_with_user_code {  sub translate_seq_with_user_code
1695    {
1696      my $seq = shift;      my $seq = shift;
1697      $seq =~ tr/-//d;     #  remove gaps  ***  Why?      $seq =~ tr/-//d;     #  remove gaps  ***  Why?
     $seq =~ tr/Xx/Nn/;   #  allow X  
1698    
1699      my $gc = shift;      #  Reference to hash of DNA alphabet code      my $gc = shift;      #  Reference to hash of code
1700      if (! $gc || ref($gc) ne "HASH") {      if (! $gc || ref($gc) ne "HASH")
1701          die "translate_seq_with_user_code needs genetic code hash as secondargument.";      {
1702            print STDERR "translate_seq_with_user_code needs genetic code hash as second argument.";
1703            return undef;
1704      }      }
1705    
1706      #  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);  
1707    
1708      if ($gc->{ "AAA" }) {     #  Looks like uppercase code table      my ( $TTT, $UUU );
1709        if    ( $gc->{AAA} && ! $gc->{aaa} )   #  Uppercase only code table
1710        {
1711          $seq   = uc $seq;     #  Uppercase sequence          $seq   = uc $seq;     #  Uppercase sequence
1712          $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  
1713      }      }
1714      elsif ($gc->{ "aaa" }) {  #  Looks like lowercase code table      elsif ( $gc->{aaa} && ! $gc->{AAA} )   #  Lowercase only code table
1715        {
1716          $seq   = lc $seq;     #  Lowercase sequence          $seq   = lc $seq;     #  Lowercase sequence
1717          $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  
1718      }      }
1719      else {      elsif ( $gc->{aaa} )
1720          die "User-supplied genetic code does not have aaa or AAA\n";      {
1721            ( $TTT, $UUU ) = ( 'ttt', 'uuu' );
1722        }
1723        else
1724        {
1725            print STDERR "User-supplied genetic code does not have aaa or AAA\n";
1726            return undef;
1727      }      }
1728    
1729      #  Test the type of code supplied:  UUU versus TTT      #  Test code support for U vs T:
   
     my ($ambigs);  
1730    
1731      if ($gc->{ $RNA_F }) {     #  Looks like RNA code table      my $ambigs;
1732          $seq =~ tr/Tt/Uu/;      if    ( $gc->{$UUU} && ! $gc->{$TTT} )  # RNA only code table
1733        {
1734            $seq = tr/Tt/Uu/;
1735          $ambigs = \%RNA_letter_can_be;          $ambigs = \%RNA_letter_can_be;
1736      }      }
1737      elsif ($gc->{ $DNA_F }) {  #  Looks like DNA code table      elsif ( $gc->{$TTT} && ! $gc->{$UUU} )  # DNA only code table
1738          $seq =~ tr/Uu/Tt/;      {
1739            $seq = tr/Uu/Tt/;
1740          $ambigs = \%DNA_letter_can_be;          $ambigs = \%DNA_letter_can_be;
1741      }      }
1742      else {      else
1743          die "User-supplied genetic code does not have $RNA_F or $DNA_F\n";      {
1744            my $t = $seq =~ tr/Tt//;
1745            my $u = $seq =~ tr/Uu//;
1746            $ambigs = ( $t > $u ) ? \%DNA_letter_can_be : \%RNA_letter_can_be;
1747      }      }
1748    
1749      my $imax = length($seq) - 2;  # will try to translate 2 nucleotides!      #  We can now do the codon-by-codon translation:
1750    
1751      my $met = shift;     #  a third argument that is true      my @codons = $seq =~ m/(...?)/g;  #  will try to translate last 2 nt
1752                           #  forces first amino acid to be Met  
1753                           #  (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;  
1754    
1755      for (my $i = $met ? 3 : 0; $i <= $imax; $i += 3) {      my @met;
1756          $pep .= translate_codon_with_user_code( substr($seq,$i,3), $gc, $N, $X, $ambigs );      if ( ( shift @_ ) && ( my $codon1 = shift @codons ) )
1757        {
1758            push @met, ( $codon1 =~ /[a-z]/ ? 'm' : 'M' );
1759      }      }
1760    
1761      return $pep;      join( '', @met, map { translate_codon_with_user_code( $_, $gc, $ambigs ) } @codons )
1762  }  }
1763    
1764    
1765  #-----------------------------------------------------------------------------  #-----------------------------------------------------------------------------
1766  #  Translate with user-supplied genetic code hash.  For speed, no error  #  Translate with user-supplied genetic code hash.  No error check on the code.
1767  #  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  
1768  #  #
1769  #   translate_codon_with_user_code( $triplet, \%code, $N, $X, $ambig_table )  #     $aa = translate_codon_with_user_code( $triplet, \%code, \%ambig_table )
1770  #  #
1771  #  $triplet      speaks for itself  #  $triplet      speaks for itself
1772  #  $code         ref to the hash with the codon translations  #  \%code         ref to the hash with the codon translations
1773  #  $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  
1774  #-----------------------------------------------------------------------------  #-----------------------------------------------------------------------------
1775    
1776    sub translate_codon_with_user_code
1777  sub translate_codon_with_user_code {  {
1778      my $codon = shift;      my ( $codon, $gc, $ambigs ) = @_;
     my $gc    = shift;  
     my $aa;  
1779    
1780      #  Try a simple lookup:      #  Try a simple lookup:
1781    
1782        my $aa;
1783      if ( $aa = $gc->{ $codon } ) { return $aa }      if ( $aa = $gc->{ $codon } ) { return $aa }
1784    
1785      #  Test that codon is valid and might have unambiguous aa:      #  Attempt to recover from mixed-case codons:
1786    
1787      my ($N, $X, $ambigs) = @_;      $codon = ( $codon =~ /[a-z]/ ) ? lc $codon : uc $codon;
1788      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  
1789    
1790      #  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.  
1791    
1792      $aa = "";      my $X = ( $codon =~ /[a-z]/ ) ? 'x' : 'X';
1793      for my $n2 ( @{ $ambigs->{ substr($codon,1,1) } } ) {  
1794          for my $n3 ( @{ $ambigs->{ substr($codon,2,1) } } ) {      if ( $codon =~ m/^[ACGTU][ACGTU]$/i )  # Add N?
1795              for my $n1 ( @{ $ambigs->{ substr($codon,0,1) } } ) {      {
1796                  #  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" }  
1797              }              }
1798        #  This makes assumptions about the user code, but tranlating ambiguous
1799        #  codons is really a bit off the wall to start with:
1800        elsif ( $codon !~ m/^[ACGTUMY][ACGTU][ACGTUKMRSWYBDHVN]$/i ) # Valid?
1801        {
1802            return $X;
1803          }          }
1804    
1805        #  Expand all ambiguous nucleotides to see if they all yield same aa.
1806    
1807        my @n1 = @{ $ambigs->{ substr( $codon, 0, 1 ) } };
1808        my $n2 =               substr( $codon, 1, 1 );
1809        my @n3 = @{ $ambigs->{ substr( $codon, 2, 1 ) } };
1810        my @triples = map { my $n12 = $_ . $n2; map { $n12 . $_ } @n3 } @n1;
1811    
1812        my $triple = shift @triples;
1813        $aa = $gc->{ $triple } || $gc->{ lc $triple } || $gc->{ uc $triple };
1814        $aa or return $X;
1815    
1816        foreach $triple ( @triples )
1817        {
1818            return $X if $aa ne ( $gc->{$triple} || $gc->{lc $triple} || $gc->{uc $triple} );
1819      }      }
1820    
1821      return $aa || $X;      return $aa;
1822  }  }
1823    
1824    
# Line 1676  Line 2006 
2006  }  }
2007    
2008    
2009    #-----------------------------------------------------------------------------
2010    #  Read qual.
2011    #
2012    #  Save the contents in a list of refs to arrays: [ $id, $descript, \@qual ]
2013    #
2014    #     @seq_entries = read_qual( )               #  STDIN
2015    #    \@seq_entries = read_qual( )               #  STDIN
2016    #     @seq_entries = read_qual( \*FILEHANDLE )
2017    #    \@seq_entries = read_qual( \*FILEHANDLE )
2018    #     @seq_entries = read_qual(  $filename )
2019    #    \@seq_entries = read_qual(  $filename )
2020    #-----------------------------------------------------------------------------
2021    sub read_qual {
2022        my ( $fh, $name, $close, $unused ) = input_filehandle( $_[0] );
2023        $unused && die "Bad reference type (" . ref( $unused ) . ") passed to read_qual\n";
2024    
2025        my @quals = ();
2026        my ($id, $desc, $qual) = ("", "", []);
2027    
2028        while ( <$fh> ) {
2029            chomp;
2030            if (/^>\s*(\S+)(\s+(.*))?$/) {        #  new id
2031                if ($id && @$qual) { push @quals, [ $id, $desc, $qual ] }
2032                ($id, $desc, $qual) = ($1, $3 ? $3 : "", []);
2033            }
2034            else {
2035                push @$qual, split;
2036            }
2037        }
2038        close( $fh ) if $close;
2039    
2040        if ($id && @$qual) { push @quals, [ $id, $desc, $qual ] }
2041        return wantarray ? @quals : \@quals;
2042    }
2043    
2044    
2045    #-------------------------------------------------------------------------------
2046    #  Fraction difference for an alignment of two nucleotide sequences in terms of
2047    #  number of differing residues, number of gaps, and number of gap opennings.
2048    #
2049    #     $fraction_diff = fraction_nt_diff( $seq1, $seq2, \%options )
2050    #
2051    #  or
2052    #
2053    #     $fraction_diff = fraction_nt_diff( $seq1, $seq2 )
2054    #     $fraction_diff = fraction_nt_diff( $seq1, $seq2, $gap_wgt )
2055    #     $fraction_diff = fraction_nt_diff( $seq1, $seq2, $open_wgt, $extend_wgt )
2056    #
2057    #  Options:
2058    #
2059    #      gap      => $gap_wgt          # Gap open and extend weight (D = 0.5)
2060    #      open     => $open_wgt         # Gap openning weight (D = gap_wgt)
2061    #      extend   => $extend_wgt       # Gap extension weight (D = open_wgt)
2062    #      t_gap    => $term_gap_wgt     # Terminal open and extend weight
2063    #      t_open   => $term_open_wgt    # Terminal gap open weight (D = open_wgt)
2064    #      t_extend => $term_extend_wgt  # Terminal gap extend weight (D = extend_wgt)
2065    #
2066    #  Default gap open and gap extend weights are 1/2.  Beware that
2067    #
2068    #     $fraction_diff = fraction_nt_diff( $seq1, $seq2, 1 )
2069    #
2070    #  and
2071    #
2072    #     $fraction_diff = fraction_nt_diff( $seq1, $seq2, 1, 0 )
2073    #
2074    #  are different.  The first has equal openning and extension weights, whereas
2075    #  the second has an openning weight of 1, and and extension weight of 0 (it
2076    #  only penalizes the number of runs of gaps).
2077    #-------------------------------------------------------------------------------
2078    sub fraction_nt_diff
2079    {
2080        my ( $npos, $nid, $ndif, $ngap, $nopen, $tgap, $topen ) = interpret_nt_align( @_[0,1] );
2081    
2082        my $diff_scr;
2083        if ( ref( $_[2] ) eq 'HASH' )
2084        {
2085            my $opts = $_[2];
2086            my $gap_open    = defined $opts->{ open }     ? $opts->{ open }
2087                            : defined $opts->{ gap }      ? $opts->{ gap }
2088                            : 0.5;
2089            my $gap_extend  = defined $opts->{ extend }   ? $opts->{ extend }
2090                            : $gap_open;
2091            my $term_open   = defined $opts->{ t_open }   ? $opts->{ t_open }
2092                            : defined $opts->{ t_gap }    ? $opts->{ t_gap }
2093                            : $gap_open;
2094            my $term_extend = defined $opts->{ t_extend } ? $opts->{ t_extend }
2095                            : defined $opts->{ t_gap }    ? $opts->{ t_gap }
2096                            : $gap_extend;
2097    
2098            $nopen -= $topen;
2099            $ngap  -= $tgap;
2100            $diff_scr = $ndif + $gap_open  * $nopen + $gap_extend  * ($ngap-$nopen)
2101                              + $term_open * $topen + $term_extend * ($tgap-$topen);
2102        }
2103        else
2104        {
2105            my $gap_open   = defined( $_[2] ) ? $_[2] : 0.5;
2106            my $gap_extend = defined( $_[3] ) ? $_[3] : $gap_open;
2107            $diff_scr = $ndif + $gap_open * $nopen + $gap_extend * ($ngap-$nopen);
2108        }
2109        my $ttl_scr = $nid + $diff_scr;
2110    
2111        $ttl_scr ? $diff_scr / $ttl_scr : undef
2112    }
2113    
2114    
2115    #-------------------------------------------------------------------------------
2116    #  Interpret an alignment of two nucleotide sequences in terms of: useful
2117    #  aligned positions (unambiguous, and not a common gap), number of identical
2118    #  residues, number of differing residues, number of gaps, and number of gap
2119    #  opennings.
2120    #
2121    #     ( $npos, $nid, $ndif, $ngap, $nopen, $tgap, $topen ) = interpret_nt_align( $seq1, $seq2 )
2122    #
2123    #  $npos  = total aligned positons (= $nid + $ndif + $ngap)
2124    #  $nid   = number of positions with identical nucleotides (ignoring case)
2125    #  $ndif  = number of positions with differing nucleotides
2126    #  $ngap  = number of positions with gap in one sequence but not the other
2127    #  $nopen = number of runs of gaps
2128    #  $tgap  = number of gaps in runs adjacent to a terminus
2129    #  $topen = number of alignment ends with gaps
2130    #
2131    #  Some of the methods might seem overly complex, but are necessary for cases
2132    #  in which the gaps switch strands in the alignment:
2133    #
2134    #     seq1  ---ACGTGAC--TTGCAGAG
2135    #     seq2  TTT---TGACGG--GCAGGG
2136    #     mask  00000011110000111111
2137    #
2138    #     npos  = 20
2139    #     nid   =  9
2140    #     ndif  =  1
2141    #     ngap  = 10
2142    #     nopen =  4
2143    #     tgap  =  3
2144    #     topen =  1
2145    #
2146    #  Although there are 4 gap opennings, there are only 2 runs in the mask,
2147    #  and the terminal run is length 6, not 3.  (Why handle these?  Because
2148    #  pairs of sequences from a multiple sequence alignment can look like this.)
2149    #-------------------------------------------------------------------------------
2150    sub interpret_nt_align
2151    {
2152        #  Remove alignment columns that are not informative:
2153        my ( $s1, $s2 ) = useful_nt_align( @_[0,1] );
2154        my $nmat = length( $s1 );          # Useful alignment length
2155    
2156        my $m1 = $s1;
2157        $m1 =~ tr/ACGT/\377/;              # Nucleotides to all 1 bits
2158        $m1 =~ tr/\377/\000/c;             # Others (gaps) to null byte
2159        my $m2 = $s2;
2160        $m2 =~ tr/ACGT/\377/;              # Nucleotides to all 1 bits
2161        $m2 =~ tr/\377/\000/c;             # Others (gaps) to null byte
2162        $m1 &= $m2;                        # Gap in either sequence becomes null
2163        $s1 &= $m1;                        # Apply mask to sequence 1
2164        $s2 &= $m1;                        # Apply mask to sequence 2
2165        my $nopen = @{[ $s1 =~ /\000+/g ]}   # Gap opens in sequence 1
2166                  + @{[ $s2 =~ /\000+/g ]};  # Gap opens in sequence 2
2167        my ( $tgap, $topen ) = ( 0, 0 );
2168        if ( $s1 =~ /^(\000+)/ || $s2 =~ /^(\000+)/ ) { $tgap += length( $1 ); $topen++ }
2169        if ( $s1 =~ /(\000+)$/ || $s2 =~ /(\000+)$/ ) { $tgap += length( $1 ); $topen++ }
2170        $s1 =~ tr/\000//d;                 # Remove nulls (former gaps)
2171        $s2 =~ tr/\000//d;                 # Remove nulls (former gaps)
2172        my $ngap = $nmat - length( $s1 );  # Total gaps
2173    
2174        my $xor = $s1 ^ $s2;               # xor of identical residues is null byte
2175        my $nid = ( $xor =~ tr/\000//d );  # Count the nulls (identical residues)
2176        my $ndif = $nmat - $nid - $ngap;
2177    
2178        ( $nmat, $nid, $ndif, $ngap, $nopen, $tgap, $topen )
2179    }
2180    
2181    
2182    sub useful_nt_align
2183    {
2184        my ( $s1, $s2 ) = map { uc $_ } @_;
2185        $s1 =~ tr/U/T/;         # Convert U to T
2186        my $m1 = $s1;
2187        $m1 =~ tr/ACGT-/\377/;  # Allowed symbols to hex FF byte
2188        $m1 =~ tr/\377/\000/c;  # All else to null byte
2189        $s2 =~ tr/U/T/;         # Convert U to T
2190        my $m2 = $s2;
2191        $m2 =~ tr/ACGT-/\377/;  # Allowed symbols to hex FF byte
2192        $m2 =~ tr/\377/\000/c;  # All else to null byte
2193        $m1 &= $m2;             # Invalid in either sequence becomes null
2194        $s1 &= $m1;             # Apply mask to sequence 1
2195        $s1 =~ tr/\000//d;      # Delete nulls in sequence 1
2196        $s2 &= $m1;             # Apply mask to sequence 2
2197        $s2 =~ tr/\000//d;      # Delete nulls in sequence 2
2198        ( $s1, $s2 )
2199    }
2200    
2201    
2202    #-------------------------------------------------------------------------------
2203    #  Interpret an alignment of two protein sequences in terms of: useful
2204    #  aligned positions (unambiguous, and not a common gap), number of identical
2205    #  residues, number of differing residues, number of gaps, and number of gap
2206    #  opennings.
2207    #
2208    #     ( $npos, $nid, $ndif, $ngap, $nopen, $tgap, $topen ) = interpret_aa_align( $seq1, $seq2 )
2209    #
2210    #  $npos  = total aligned positons (= $nid + $ndif + $ngap)
2211    #  $nid   = number of positions with identical amino acids (ignoring case)
2212    #  $ndif  = number of positions with differing amino acids
2213    #  $ngap  = number of positions with gap in one sequence but not the other
2214    #  $nopen = number of runs of gaps
2215    #  $tgap  = number of gaps in runs adjacent to a terminus
2216    #  $topen = number of alignment ends with gaps
2217    #
2218    #-------------------------------------------------------------------------------
2219    sub interpret_aa_align
2220    {
2221        #  Remove alignment columns that are not informative:
2222        my ( $s1, $s2 ) = useful_aa_align( @_[0,1] );
2223        my $nmat = length( $s1 );            # Useful alignment length
2224    
2225        my $m1 = $s1;
2226        $m1 =~ tr/ACDEFGHIKLMNPQRSTUVWY/\377/;  # Amino acids to all 1 bits
2227        $m1 =~ tr/\377/\000/c;               # Others (gaps) to null byte
2228        my $m2 = $s2;
2229        $m2 =~ tr/ACDEFGHIKLMNPQRSTUVWY/\377/;  # Amino acids to all 1 bits
2230        $m2 =~ tr/\377/\000/c;               # Others (gaps) to null byte
2231        $m1 &= $m2;                          # Gap in either sequence becomes null
2232        $s1 &= $m1;                          # Apply mask to sequence 1
2233        $s2 &= $m1;                          # Apply mask to sequence 2
2234        my $nopen = @{[ $s1 =~ /\000+/g ]}   # Gap opens in sequence 1
2235                  + @{[ $s2 =~ /\000+/g ]};  # Gap opens in sequence 2
2236        my ( $tgap, $topen ) = ( 0, 0 );
2237        if ( $s1 =~ /^(\000+)/ || $s2 =~ /^(\000+)/ ) { $tgap += length( $1 ); $topen++ }
2238        if ( $s1 =~ /(\000+)$/ || $s2 =~ /(\000+)$/ ) { $tgap += length( $1 ); $topen++ }
2239        $s1 =~ tr/\000//d;                 # Remove nulls (former gaps)
2240        $s2 =~ tr/\000//d;                 # Remove nulls (former gaps)
2241        my $ngap = $nmat - length( $s1 );  # Total gaps
2242    
2243        my $xor = $s1 ^ $s2;               # xor of identical residues is null byte
2244        my $nid = ( $xor =~ tr/\000//d );  # Count the nulls (identical residues)
2245        my $ndif = $nmat - $nid - $ngap;
2246    
2247        ( $nmat, $nid, $ndif, $ngap, $nopen, $tgap, $topen )
2248    }
2249    
2250    
2251    sub useful_aa_align
2252    {
2253        my ( $s1, $s2 ) = map { uc $_ } @_;
2254        my $m1 = $s1;
2255        $m1 =~ tr/ACDEFGHIKLMNPQRSTUVWY-/\377/;  # Allowed symbols to hex FF byte
2256        $m1 =~ tr/\377/\000/c;  # All else to null byte
2257        my $m2 = $s2;
2258        $m2 =~ tr/ACDEFGHIKLMNPQRSTUVWY-/\377/;  # Allowed symbols to hex FF byte
2259        $m2 =~ tr/\377/\000/c;  # All else to null byte
2260        $m1 &= $m2;             # Invalid in either sequence becomes null
2261        $s1 &= $m1;             # Apply mask to sequence 1
2262        $s1 =~ tr/\000//d;      # Delete nulls in sequence 1
2263        $s2 &= $m1;             # Apply mask to sequence 2
2264        $s2 =~ tr/\000//d;      # Delete nulls in sequence 2
2265        ( $s1, $s2 )
2266    }
2267    
2268    
2269  1;  1;

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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3