[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.17, Mon Jan 18 20:01: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    # Basic sequence manipulation functions:
92    #
93  #  @entry  = subseq_DNA_entry( @seq_entry, $from, $to [, $fix_id] );  #  @entry  = subseq_DNA_entry( @seq_entry, $from, $to [, $fix_id] );
94  #  @entry  = subseq_RNA_entry( @seq_entry, $from, $to [, $fix_id] );  #  @entry  = subseq_RNA_entry( @seq_entry, $from, $to [, $fix_id] );
95    #  $DNAseq = DNA_subseq(  $seq, $from, $to );
96    #  $DNAseq = DNA_subseq( \$seq, $from, $to );
97    #  $RNAseq = RNA_subseq(  $seq, $from, $to );
98    #  $RNAseq = RNA_subseq( \$seq, $from, $to );
99  #  @entry  = complement_DNA_entry( @seq_entry [, $fix_id] );  #  @entry  = complement_DNA_entry( @seq_entry [, $fix_id] );
100  #  @entry  = complement_RNA_entry( @seq_entry [, $fix_id] );  #  @entry  = complement_RNA_entry( @seq_entry [, $fix_id] );
101  #  $DNAseq = complement_DNA_seq( $NA_seq );  #  $DNAseq = complement_DNA_seq( $NA_seq );
# Line 60  Line 105 
105  #  $seq    = pack_seq( $sequence )  #  $seq    = pack_seq( $sequence )
106  #  $seq    = clean_ae_sequence( $seq )  #  $seq    = clean_ae_sequence( $seq )
107  #  #
108  #  $seq = translate_seq( $seq [, $met_start] )  #  $aa = translate_seq( $nt, $met_start )
109    #  $aa = translate_seq( $nt )
110  #  $aa  = translate_codon( $triplet );  #  $aa  = translate_codon( $triplet );
 #  $aa  = translate_uc_DNA_codon( $upcase_DNA_triplet );  
111  #  #
112  #  User-supplied genetic code must be upper case index and match the  #  User-supplied genetic code.  The supplied code needs to be complete in
113  #  DNA versus RNA type of sequence  #  RNA and/or DNA, and upper and/or lower case.  The program guesses based
114    #  on lysine and phenylalanine codons.
115    #
116    #  $aa = translate_seq_with_user_code( $nt, $gen_code_hash, $met_start )
117    #  $aa = translate_seq_with_user_code( $nt, $gen_code_hash )
118  #  #
119  #  Locations (= oriented intervals) are ( id, start, end )  #  Locations (= oriented intervals) are ( id, start, end )
120  #  Intervals are ( id, left, right )  #  Intervals are ( id, left, right )
# Line 81  Line 130 
130  #  Convert GenBank locations to SEED locations  #  Convert GenBank locations to SEED locations
131  #  #
132  #  @seed_locs = gb_location_2_seed( $contig, @gb_locs )  #  @seed_locs = gb_location_2_seed( $contig, @gb_locs )
133    #
134    #  Read quality scores from a fasta-like file:
135    #
136    #  @seq_entries = read_qual( )               #  STDIN
137    # \@seq_entries = read_qual( )               #  STDIN
138    #  @seq_entries = read_qual( \*FILEHANDLE )
139    # \@seq_entries = read_qual( \*FILEHANDLE )
140    #  @seq_entries = read_qual(  $filename )
141    # \@seq_entries = read_qual(  $filename )
142    #
143    #  Evaluate alignments:
144    #
145    #  $fraction_diff = fraction_nt_diff( $seq1, $seq2, \%options )
146    #  $fraction_diff = fraction_nt_diff( $seq1, $seq2 )
147    #  $fraction_diff = fraction_nt_diff( $seq1, $seq2, $gap_weight )
148    #  $fraction_diff = fraction_nt_diff( $seq1, $seq2, $gap_open, $gap_extend )
149    #
150    #  ( $npos, $nid, $ndif, $ngap, $nopen, $tgap, $topen ) = interpret_nt_align( $seq1, $seq2 )
151    #  ( $npos, $nid, $ndif, $ngap, $nopen, $tgap, $topen ) = interpret_aa_align( $seq1, $seq2 )
152    #
153    
154  use strict;  use strict;
155    use Carp;
 use gjolib qw( wrap_text );  
156    
157  #  Exported global variables:  #  Exported global variables:
158    
# Line 131  Line 198 
198    
199          subseq_DNA_entry          subseq_DNA_entry
200          subseq_RNA_entry          subseq_RNA_entry
201            DNA_subseq
202            RNA_subseq
203          complement_DNA_entry          complement_DNA_entry
204          complement_RNA_entry          complement_RNA_entry
205          complement_DNA_seq          complement_DNA_seq
# Line 152  Line 221 
221          reverse_intervals          reverse_intervals
222    
223          gb_location_2_seed          gb_location_2_seed
224    
225            read_qual
226    
227            fraction_nt_diff
228            interpret_nt_align
229            interpret_aa_align
230          );          );
231    
232  our @EXPORT_OK = qw(  our @EXPORT_OK = qw(
# Line 198  Line 273 
273      if ( ! ref( $file ) )      if ( ! ref( $file ) )
274      {      {
275          my $fh;          my $fh;
276          -f $file or die "Could not find input file \"$file\"\n";          if    ( -f $file                       ) { }
277          open( $fh, "<$file" ) || die "Could not open \"$file\" for input\n";          elsif (    $file =~ /^>(.+)$/ && -f $1 ) { $file = $1 }
278            else { die "Could not find input file '$file'\n" }
279            open( $fh, "<$file" ) || die "Could not open '$file' for input\n";
280          return ( $fh, $file, 1 );          return ( $fh, $file, 1 );
281      }      }
282    
# Line 219  Line 296 
296    
297    
298  #-----------------------------------------------------------------------------  #-----------------------------------------------------------------------------
299  #  Read fasta sequences.  #  Read fasta sequences.  Save the contents in a list of refs to arrays:
300  #  Save the contents in a list of refs to arrays:  (id, description, seq)  #
301    #     $seq_entry = [ id, description, seq ]
302  #  #
303  #     @seq_entries = read_fasta( )               #  STDIN  #     @seq_entries = read_fasta( )               #  STDIN
304  #    \@seq_entries = read_fasta( )               #  STDIN  #    \@seq_entries = read_fasta( )               #  STDIN
# Line 228  Line 306 
306  #    \@seq_entries = read_fasta( \*FILEHANDLE )  #    \@seq_entries = read_fasta( \*FILEHANDLE )
307  #     @seq_entries = read_fasta(  $filename )  #     @seq_entries = read_fasta(  $filename )
308  #    \@seq_entries = read_fasta(  $filename )  #    \@seq_entries = read_fasta(  $filename )
309    #  #  @seq_entries = read_fasta( "command |" )   #  open and read from pipe
310    #  # \@seq_entries = read_fasta( "command |" )   #  open and read from pipe
311    #
312  #-----------------------------------------------------------------------------  #-----------------------------------------------------------------------------
313  sub read_fasta {  sub read_fasta
314    {
315        my @seqs = map { $_->[2] =~ tr/ \n\r\t//d; $_ }
316                   map { /^(\S+)([ \t]+([^\n]*\S)?\s*)?\n(.+)$/s ? [ $1, $3 || '', $4 ] : () }
317                   split /^>\s*/m, slurp( @_ );
318        wantarray() ? @seqs : \@seqs;
319    }
320    
321    #-----------------------------------------------------------------------------
322    #  A fast file reader:
323    #
324    #     $data = slurp( )               #  \*STDIN
325    #     $data = slurp( \*FILEHANDLE )  #  an open file handle
326    #     $data = slurp(  $filename )    #  a file name
327    #     $data = slurp( "<$filename" )  #  file with explicit direction
328    #   # $data = slurp( "$command |" )  #  open and read from pipe
329    #
330    #  Note:  It is faster to read lines by reading the file and splitting
331    #         than by reading the lines sequentially.  If space is not an
332    #         issue, this is the way to go.  If space is an issue, then lines
333    #         or records should be processed one-by-one (rather than loading
334    #         the whole input into a string or array).
335    #-----------------------------------------------------------------------------
336    sub slurp
337    {
338        my ( $fh, $close );
339        if ( ref $_[0] eq 'GLOB' )
340        {
341            $fh = shift;
342        }
343        elsif ( $_[0] && ! ref $_[0] )
344        {
345            my $file = shift;
346            if    ( -f $file                       ) { $file = "<$file" }
347            elsif (    $file =~ /^<(.*)$/ && -f $1 ) { }  # Explicit read
348          # elsif (    $file =~ /\S\s*\|$/         ) { }  # Read from a pipe
349            else                                     { return undef }
350            open $fh, $file or return undef;
351            $close = 1;
352        }
353        else
354        {
355            $fh = \*STDIN;
356        }
357    
358        my $out = '';
359        my $inc = 1048576;
360        my $end =       0;
361        my $read;
362        while ( $read = read( $fh, $out, $inc, $end ) ) { $end += $read }
363        close( $fh ) if $close;
364    
365        $out;
366    }
367    
368    
369    #-----------------------------------------------------------------------------
370    #  Previous, 50% slower fasta reader:
371    #-----------------------------------------------------------------------------
372    sub read_fasta_0
373    {
374      my ( $fh, $name, $close, $unused ) = input_filehandle( $_[0] );      my ( $fh, $name, $close, $unused ) = input_filehandle( $_[0] );
375      $unused && die "Bad reference type (" . ref( $unused ) . ") passed to read_fasta\n";      $unused && die "Bad reference type (" . ref( $unused ) . ") passed to read_fasta\n";
376    
# Line 255  Line 396 
396    
397    
398  #-----------------------------------------------------------------------------  #-----------------------------------------------------------------------------
399  #  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
400  #  Return the contents as an array:  (id, description, seq)  #  read_fasta(), but can handle an arbitrarily large file.  State information
401    #  is retained in hashes, so any number of streams can be interlaced.
402    #
403    #      @entry = read_next_fasta_seq( \*FILEHANDLE )
404    #     \@entry = read_next_fasta_seq( \*FILEHANDLE )
405    #      @entry = read_next_fasta_seq(  $filename )
406    #     \@entry = read_next_fasta_seq(  $filename )
407    #      @entry = read_next_fasta_seq()                # \*STDIN
408    #     \@entry = read_next_fasta_seq()                # \*STDIN
409    #
410    #      @entry = ( $id, $description, $seq )
411  #  #
412  #     @seq_entry = read_next_fasta_seq( \*FILEHANDLE )  #  When reading at the end of file, () is returned.
413    #  With a filename, reading past this will reopen the file at the beginning.
414  #-----------------------------------------------------------------------------  #-----------------------------------------------------------------------------
415  #  Reading always overshoots, so save next id and description  #  Reading always overshoots, so save next id and description
416    
417  {   #  Use bare block to scope the header hash  {   #  Use bare block to scope the header hash
418    
419      my %next_header;      my %next_header;
420        my %file_handle;
421        my %close_file;
422    
423      sub read_next_fasta_seq {      sub read_next_fasta_seq
424          my $fh = shift;      {
425          my ( $id, $desc );          $_[0] ||= \*STDIN;               #  Undefined $_[0] fails with use warn
426            my $fh = $file_handle{ $_[0] };
427            if ( ! $fh )
428            {
429                if ( ref $_[0] )
430                {
431                    return () if ref $_[0] ne 'GLOB';
432                    $fh = $_[0];
433                }
434                else
435                {
436                    my $file = $_[0];
437                    if    ( -f $file                       ) { $file = "<$file" }
438                    elsif (    $file =~ /^<(.*)$/ && -f $1 ) { }  # Explicit read
439                  # elsif (    $file =~ /\S\s*\|$/         ) { }  # Read from a pipe
440                    else                                     { return () }
441                    open $fh, $file or return ();
442                    $close_file{ $fh } = 1;
443                }
444                $file_handle{ $_[0] } = $fh;
445            }
446    
447          if ( defined( $next_header{$fh} ) ) {          my ( $id, $desc, $seq ) = ( undef, '', '' );
448            if ( defined( $next_header{$fh} ) )
449            {
450              ( $id, $desc ) = parse_fasta_title( $next_header{$fh} );              ( $id, $desc ) = parse_fasta_title( $next_header{$fh} );
451          }          }
452          else {          else
453              $next_header{$fh} = "";          {
454              ( $id, $desc ) = ( undef, "" );              $next_header{$fh} = '';
455          }          }
         my $seq = "";  
456    
457          while ( <$fh> ) {          while ( <$fh> )
458            {
459              chomp;              chomp;
460              if ( /^>/ ) {        #  new id              if ( /^>/ )        #  new id
461                {
462                  $next_header{$fh} = $_;                  $next_header{$fh} = $_;
463                  if ( defined($id) && $seq )                  if ( defined($id) && $seq )
464                  {                  {
465                      return wantarray ? ($id, $desc, $seq) : [$id, $desc, $seq]                      return wantarray ? ($id, $desc, $seq) : [$id, $desc, $seq]
466                  }                  }
467                  ( $id, $desc ) = parse_fasta_title( $next_header{$fh} );                  ( $id, $desc ) = parse_fasta_title( $next_header{$fh} );
468                  $seq = "";                  $seq = '';
469              }              }
470              else {              else
471                  tr/     0-9//d;              {
472                    tr/ \t\r//d;
473                  $seq .= $_ ;                  $seq .= $_ ;
474              }              }
475          }          }
476    
477          #  Done with file, delete "next header"          #  Done with file; there is no next header:
478    
479          delete $next_header{$fh};          delete $next_header{$fh};
480          return ( defined($id) && $seq ) ? ( wantarray ? ($id, $desc, $seq)  
481                                                        : [$id, $desc, $seq]          #  Return last set of data:
482                                            )  
483                                          : () ;          if ( defined($id) && $seq )
484            {
485                return wantarray ? ($id,$desc,$seq) : [$id,$desc,$seq]
486            }
487    
488            #  Or close everything out (returning the empty list tells caller
489            #  that we are done)
490    
491            if ( $close_file{ $fh } ) { close $fh; delete $close_file{ $fh } }
492            delete $file_handle{ $_[0] };
493    
494            return ();
495      }      }
496  }  }
497    
# Line 352  Line 541 
541  #     ($id, $def) = parse_fasta_title( $title )  #     ($id, $def) = parse_fasta_title( $title )
542  #     ($id, $def) = split_fasta_title( $title )  #     ($id, $def) = split_fasta_title( $title )
543  #-----------------------------------------------------------------------------  #-----------------------------------------------------------------------------
544  sub parse_fasta_title {  sub parse_fasta_title
545    {
546      my $title = shift;      my $title = shift;
547      chomp;      chomp $title;
     if ($title =~ /^>?\s*(\S+)(:?\s+(.*\S)\s*)?$/) {  
         return ($1, $3 ? $3 : "");  
     }  
     elsif ($title =~ /^>/) {  
         return ("", "");  
     }  
     else {  
         return (undef, "");  
     }  
 }  
548    
549  sub split_fasta_title {      return $title =~ /^>?\s*(\S+)(\s+(.*\S)?\s*)?$/ ? ( $1, $3 || '' )
550      parse_fasta_title ( shift );           : $title =~ /^>/                           ? ( '', '' )
551             :                                            ( undef, undef )
552  }  }
553    
554    sub split_fasta_title { parse_fasta_title( @_ ) }
555    
556    
557  #-----------------------------------------------------------------------------  #-----------------------------------------------------------------------------
558  #  Helper function for defining an output filehandle:  #  Helper function for defining an output filehandle:
# Line 430  Line 613 
613      my ( $fh, undef, $close, $unused ) = output_filehandle( shift );      my ( $fh, undef, $close, $unused ) = output_filehandle( shift );
614      ( unshift @_, $unused ) if $unused;      ( unshift @_, $unused ) if $unused;
615    
616      ( 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";
617    
618      #  Expand the sequence entry list if necessary:      #  Expand the sequence entry list if necessary:
619    
# Line 587  Line 770 
770    
771    
772  #-----------------------------------------------------------------------------  #-----------------------------------------------------------------------------
773  #  Print one sequence in fasta format to an open file  #  Print one sequence in fasta format to an open file.
774  #  #
775  #     print_seq_as_fasta( \*FILEHANDLE, $id, $desc, $seq );  #     print_seq_as_fasta( \*FILEHANDLE, $id, $desc, $seq );
776  #     print_seq_as_fasta( \*FILEHANDLE, @seq_entry );  #     print_seq_as_fasta(               $id, $desc, $seq );
777  #-----------------------------------------------------------------------------  #     print_seq_as_fasta( \*FILEHANDLE, $id,        $seq );
778  sub print_seq_as_fasta {  #     print_seq_as_fasta(               $id,        $seq );
779      my $fh = shift;  #
780      my ($id, $desc, $seq) = @_;  #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
781    #  print_seq_as_fasta() is meant more as a internal support routine than an
782      printf $fh ($desc) ? ">$id $desc\n" : ">$id\n";  #  external interface.  To print a single sequence to a named file use:
783      my $len = length($seq);  #
784      for (my $i = 0; $i < $len; $i += 60) {  #     print_alignment_as_fasta( $filename, [ $id, $desc, $seq ] );
785          print $fh substr($seq, $i, 60) . "\n";  #     print_alignment_as_fasta( $filename, [ $id,        $seq ] );
786      }  #-----------------------------------------------------------------------------
787    sub print_seq_as_fasta
788    {
789        my $fh = ( ref $_[0] eq 'GLOB' ) ? shift : \*STDOUT;
790        return if ( @_ < 2 ) || ( @_ > 3 ) || ! ( defined $_[0] && defined $_[-1] );
791        #  Print header line
792        print $fh  ( @_ == 3 && defined $_[1] && $_[1] =~ /\S/ ) ? ">$_[0] $_[1]\n" : ">$_[0]\n";
793        #  Print sequence, 60 chars per line
794        print $fh  join( "\n", $_[-1] =~ m/.{1,60}/g ), "\n";
795  }  }
796    
797    
# Line 633  Line 824 
824    
825    
826  #-----------------------------------------------------------------------------  #-----------------------------------------------------------------------------
827    #  Return a string with text wrapped to defined line lengths:
828    #
829    #     $wrapped_text = wrap_text( $str )                  # default len   =  80
830    #     $wrapped_text = wrap_text( $str, $len )            # default ind   =   0
831    #     $wrapped_text = wrap_text( $str, $len, $indent )   # default ind_n = ind
832    #     $wrapped_text = wrap_text( $str, $len, $indent_1, $indent_n )
833    #-----------------------------------------------------------------------------
834    sub wrap_text {
835        my ($str, $len, $ind, $indn) = @_;
836    
837        defined($str)  || die "wrap_text called without a string\n";
838        defined($len)  || ($len  =   80);
839        defined($ind)  || ($ind  =    0);
840        ($ind  < $len) || die "wrap error: indent greater than line length\n";
841        defined($indn) || ($indn = $ind);
842        ($indn < $len) || die "wrap error: indent_n greater than line length\n";
843    
844        $str =~ s/\s+$//;
845        $str =~ s/^\s+//;
846        my ($maxchr, $maxchr1);
847        my (@lines) = ();
848    
849        while ($str) {
850            $maxchr1 = ($maxchr = $len - $ind) - 1;
851            if ($maxchr >= length($str)) {
852                push @lines, (" " x $ind) . $str;
853                last;
854            }
855            elsif ($str =~ /^(.{0,$maxchr1}\S)\s+(\S.*)$/) { # no expr in {}
856                push @lines, (" " x $ind) . $1;
857                $str = $2;
858            }
859            elsif ($str =~ /^(.{0,$maxchr1}-)(.*)$/) {
860                push @lines, (" " x $ind) . $1;
861                $str = $2;
862            }
863            else {
864                push @lines, (" " x $ind) . substr($str, 0, $maxchr);
865                $str = substr($str, $maxchr);
866            }
867            $ind = $indn;
868        }
869    
870        return join("\n", @lines);
871    }
872    
873    
874    #-----------------------------------------------------------------------------
875  #  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)
876  #  #
877  #     my \%seq_ind  = index_seq_list(  @seq_list );  #     my \%seq_ind  = index_seq_list(  @seq_list );
# Line 794  Line 1033 
1033  }  }
1034    
1035    
1036    sub DNA_subseq
1037    {
1038        my ( $seq, $from, $to ) = @_;
1039    
1040        my $len = ref( $seq ) eq 'SCALAR' ? length( $$seq )
1041                                          : length(  $seq );
1042        if ( ( $from eq '$' ) || ( $from eq "" ) ) { $from = $len }
1043        if ( ( $to   eq '$' ) || ( ! $to       ) ) { $to   = $len }
1044    
1045        my $left  = ( $from < $to ) ? $from : $to;
1046        my $right = ( $from < $to ) ? $to   : $from;
1047        if ( ( $right < 1 ) || ( $left > $len ) ) { return "" }
1048        if ( $right > $len ) { $right = $len }
1049        if ( $left  < 1    ) { $left  =    1 }
1050    
1051        my $subseq = ref( $seq ) eq 'SCALAR' ? substr( $$seq, $left-1, $right-$left+1 )
1052                                             : substr(  $seq, $left-1, $right-$left+1 );
1053    
1054        if ( $from > $to )
1055        {
1056            $subseq = reverse $subseq;
1057            $subseq =~ tr[ACGTUKMRSWYBDHVNacgtukmrswybdhvn]
1058                         [TGCAAMKYSWRVHDBNtgcaamkyswrvhdbn];
1059        }
1060    
1061        $subseq
1062    }
1063    
1064    
1065    sub RNA_subseq
1066    {
1067        my ( $seq, $from, $to ) = @_;
1068    
1069        my $len = ref( $seq ) eq 'SCALAR' ? length( $$seq )
1070                                          : length(  $seq );
1071        if ( ( $from eq '$' ) || ( $from eq "" ) ) { $from = $len }
1072        if ( ( $to   eq '$' ) || ( ! $to       ) ) { $to   = $len }
1073    
1074        my $left  = ( $from < $to ) ? $from : $to;
1075        my $right = ( $from < $to ) ? $to   : $from;
1076        if ( ( $right < 1 ) || ( $left > $len ) ) { return "" }
1077        if ( $right > $len ) { $right = $len }
1078        if ( $left  < 1    ) { $left  =    1 }
1079    
1080        my $subseq = ref( $seq ) eq 'SCALAR' ? substr( $$seq, $left-1, $right-$left+1 )
1081                                             : substr(  $seq, $left-1, $right-$left+1 );
1082    
1083        if ( $from > $to )
1084        {
1085            $subseq = reverse $subseq;
1086            $subseq =~ tr[ACGTUKMRSWYBDHVNacgtukmrswybdhvn]
1087                         [UGCAAMKYSWRVHDBNugcaamkyswrvhdbn];
1088        }
1089    
1090        $subseq
1091    }
1092    
1093    
1094  sub complement_DNA_entry {  sub complement_DNA_entry {
1095      my ($id, $desc, $seq, $fix_id) = @_;      my ($id, $desc, $seq, $fix_id) = @_;
1096      $fix_id ||= 0;     #  fix undef values      $fix_id ||= 0;     #  fix undef values
# Line 911  Line 1208 
1208  #  Translate nucleotides to one letter protein:  #  Translate nucleotides to one letter protein:
1209  #  #
1210  #  $seq = translate_seq( $seq [, $met_start] )  #  $seq = translate_seq( $seq [, $met_start] )
1211  #  $aa  = translate_codon( $triplet );  #     $aa  = translate_codon( $triplet )
1212  #  $aa  = translate_uc_DNA_codon( $upcase_DNA_triplet );  #     $aa  = translate_DNA_codon( $triplet )     # Does not rely on DNA
1213    #     $aa  = translate_uc_DNA_codon( $triplet )  # Does not rely on uc or DNA
1214  #  #
1215  #  User-supplied genetic code must be upper case index and match the  #  User-supplied genetic code must be upper case index and match the
1216  #  DNA versus RNA type of sequence  #  DNA versus RNA type of sequence
# Line 929  Line 1227 
1227    
1228      # DNA version      # DNA version
1229    
1230      TTT => "F",  TCT => "S",  TAT => "Y",  TGT => "C",      TTT => 'F',  TCT => 'S',  TAT => 'Y',  TGT => 'C',
1231      TTC => "F",  TCC => "S",  TAC => "Y",  TGC => "C",      TTC => 'F',  TCC => 'S',  TAC => 'Y',  TGC => 'C',
1232      TTA => "L",  TCA => "S",  TAA => "*",  TGA => "*",      TTA => 'L',  TCA => 'S',  TAA => '*',  TGA => '*',
1233      TTG => "L",  TCG => "S",  TAG => "*",  TGG => "W",      TTG => 'L',  TCG => 'S',  TAG => '*',  TGG => 'W',
1234      CTT => "L",  CCT => "P",  CAT => "H",  CGT => "R",      CTT => 'L',  CCT => 'P',  CAT => 'H',  CGT => 'R',
1235      CTC => "L",  CCC => "P",  CAC => "H",  CGC => "R",      CTC => 'L',  CCC => 'P',  CAC => 'H',  CGC => 'R',
1236      CTA => "L",  CCA => "P",  CAA => "Q",  CGA => "R",      CTA => 'L',  CCA => 'P',  CAA => 'Q',  CGA => 'R',
1237      CTG => "L",  CCG => "P",  CAG => "Q",  CGG => "R",      CTG => 'L',  CCG => 'P',  CAG => 'Q',  CGG => 'R',
1238      ATT => "I",  ACT => "T",  AAT => "N",  AGT => "S",      ATT => 'I',  ACT => 'T',  AAT => 'N',  AGT => 'S',
1239      ATC => "I",  ACC => "T",  AAC => "N",  AGC => "S",      ATC => 'I',  ACC => 'T',  AAC => 'N',  AGC => 'S',
1240      ATA => "I",  ACA => "T",  AAA => "K",  AGA => "R",      ATA => 'I',  ACA => 'T',  AAA => 'K',  AGA => 'R',
1241      ATG => "M",  ACG => "T",  AAG => "K",  AGG => "R",      ATG => 'M',  ACG => 'T',  AAG => 'K',  AGG => 'R',
1242      GTT => "V",  GCT => "A",  GAT => "D",  GGT => "G",      GTT => 'V',  GCT => 'A',  GAT => 'D',  GGT => 'G',
1243      GTC => "V",  GCC => "A",  GAC => "D",  GGC => "G",      GTC => 'V',  GCC => 'A',  GAC => 'D',  GGC => 'G',
1244      GTA => "V",  GCA => "A",  GAA => "E",  GGA => "G",      GTA => 'V',  GCA => 'A',  GAA => 'E',  GGA => 'G',
1245      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",  
1246    
1247      #  The following ambiguous encodings are not necessary,  but      #  The following ambiguous encodings are not necessary,  but
1248      #  speed up the processing of some ambiguous triplets:      #  speed up the processing of some ambiguous triplets:
1249    
1250      TTY => "F",  TCY => "S",  TAY => "Y",  TGY => "C",      TTY => 'F',  TCY => 'S',  TAY => 'Y',  TGY => 'C',
1251      TTR => "L",  TCR => "S",  TAR => "*",      TTR => 'L',  TCR => 'S',  TAR => '*',
1252                   TCN => "S",                   TCN => 'S',
1253      CTY => "L",  CCY => "P",  CAY => "H",  CGY => "R",      CTY => 'L',  CCY => 'P',  CAY => 'H',  CGY => 'R',
1254      CTR => "L",  CCR => "P",  CAR => "Q",  CGR => "R",      CTR => 'L',  CCR => 'P',  CAR => 'Q',  CGR => 'R',
1255      CTN => "L",  CCN => "P",               CGN => "R",      CTN => 'L',  CCN => 'P',               CGN => 'R',
1256      ATY => "I",  ACY => "T",  AAY => "N",  AGY => "S",      ATY => 'I',  ACY => 'T',  AAY => 'N',  AGY => 'S',
1257                   ACR => "T",  AAR => "K",  AGR => "R",                   ACR => 'T',  AAR => 'K',  AGR => 'R',
1258                   ACN => "T",                   ACN => 'T',
1259      GTY => "V",  GCY => "A",  GAY => "D",  GGY => "G",      GTY => 'V',  GCY => 'A',  GAY => 'D',  GGY => 'G',
1260      GTR => "V",  GCR => "A",  GAR => "E",  GGR => "G",      GTR => 'V',  GCR => 'A',  GAR => 'E',  GGR => 'G',
1261      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"  
1262  );  );
1263    
1264    #  Add RNA by construction:
1265    
1266    foreach ( grep { /T/ } keys %genetic_code )
1267    {
1268        my $codon = $_;
1269        $codon =~ s/T/U/g;
1270        $genetic_code{ $codon } = lc $genetic_code{ $_ }
1271    }
1272    
1273  #  Add lower case by construction:  #  Add lower case by construction:
1274    
1275  foreach ( keys %genetic_code ) {  foreach ( keys %genetic_code )
1276    {
1277      $genetic_code{ lc $_ } = lc $genetic_code{ $_ }      $genetic_code{ lc $_ } = lc $genetic_code{ $_ }
1278  }  }
1279    
1280    
1281  #  Construct the genetic code with selanocysteine by difference:  #  Construct the genetic code with selenocysteine by difference:
1282    
1283  %genetic_code_with_U = map { $_ => $genetic_code{ $_ } } keys %genetic_code;  %genetic_code_with_U = %genetic_code;
1284  $genetic_code_with_U{ TGA } = "U";  $genetic_code_with_U{ TGA } = 'U';
1285  $genetic_code_with_U{ tga } = "u";  $genetic_code_with_U{ tga } = 'u';
1286  $genetic_code_with_U{ UGA } = "U";  $genetic_code_with_U{ UGA } = 'U';
1287  $genetic_code_with_U{ uga } = "u";  $genetic_code_with_U{ uga } = 'u';
1288    
1289    
1290  %amino_acid_codons_DNA = (  %amino_acid_codons_DNA = (
# Line 1271  Line 1548 
1548    
1549    
1550  #-----------------------------------------------------------------------------  #-----------------------------------------------------------------------------
1551  #  Translate nucleotides to one letter protein:  #  Translate nucleotides to one letter protein.  Respects case of the
1552    #  nucleotide sequence.
1553  #  #
1554  #      $seq = translate_seq( $seq [, $met_start] )  #      $aa = translate_seq( $nt, $met_start )
1555    #      $aa = translate_seq( $nt )
1556  #  #
1557  #-----------------------------------------------------------------------------  #-----------------------------------------------------------------------------
1558    
1559  sub translate_seq {  sub translate_seq
1560      my $seq = uc shift;  {
1561      $seq =~ tr/UX/TN/;      #  make it DNA, and allow X      my $seq = shift;
1562      $seq =~ tr/-//d;        #  remove gaps      $seq =~ tr/-//d;        #  remove gaps
1563    
1564      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)  
1565    
1566      my $imax = length($seq) - 2;  # will try to translate 2 nucleotides!      #  A second argument that is true forces first amino acid to be Met
1567      my $pep = ( ($met && ($imax >= 0)) ? "M" : "" );  
1568      for (my $i = $met ? 3 : 0; $i <= $imax; $i += 3) {      my @met;
1569          $pep .= translate_uc_DNA_codon( substr($seq,$i,3) );      if ( ( shift @_ ) && ( my $codon1 = shift @codons ) )
1570        {
1571            push @met, ( $codon1 =~ /[a-z]/ ? 'm' : 'M' );
1572      }      }
1573    
1574      return $pep;      join( '', @met, map { translate_codon( $_ ) } @codons )
1575  }  }
1576    
1577    
1578  #-----------------------------------------------------------------------------  #-----------------------------------------------------------------------------
1579  #  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.  
1580  #  #
1581  #      $aa = translate_codon( $triplet )  #      $aa = translate_codon( $triplet )
1582    #      $aa = translate_DNA_codon( $triplet )
1583    #      $aa = translate_uc_DNA_codon( $triplet )
1584  #  #
1585  #-----------------------------------------------------------------------------  #-----------------------------------------------------------------------------
1586    
1587  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);  
 }  
1588    
1589    sub translate_uc_DNA_codon { translate_codon( uc $_[0] ) }
1590    
1591  #-----------------------------------------------------------------------------  sub translate_codon
1592  #  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 {  
1593      my $codon = shift;      my $codon = shift;
1594      my $aa;      $codon =~ tr/Uu/Tt/;     #  Make it DNA
1595    
1596      #  Try a simple lookup:      #  Try a simple lookup:
1597    
1598        my $aa;
1599      if ( $aa = $genetic_code{ $codon } ) { return $aa }      if ( $aa = $genetic_code{ $codon } ) { return $aa }
1600    
1601      #  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  
1602    
1603      #  Expand all ambiguous nucleotides to see if they all yield same aa.      $codon = ( $codon =~ /[a-z]/ ) ? lc $codon : uc $codon;
1604      #  Loop order tries to fail quickly with first position change.      if ( $aa = $genetic_code{ $codon } ) { return $aa }
1605    
1606      $aa = "";      #  The code defined above catches simple N, R and Y ambiguities in the
1607      for my $n2 ( @{ $DNA_letter_can_be{ substr($codon,1,1) } } ) {      #  third position.  Other codons (e.g., GG[KMSWBDHV], or even GG) might
1608          for my $n3 ( @{ $DNA_letter_can_be{ substr($codon,2,1) } } ) {      #  be unambiguously translated by converting the last position to N and
1609              for my $n1 ( @{ $DNA_letter_can_be{ substr($codon,0,1) } } ) {      #  seeing if this is in the code table:
1610                  #  set the first value of $aa  
1611                  if ($aa eq "") { $aa = $genetic_code{ $n1 . $n2 . $n3 } }      my $N = ( $codon =~ /[a-z]/ ) ? 'n' : 'N';
1612                  #  or break out if any other amino acid is detected      if ( $aa = $genetic_code{ substr($codon,0,2) . $N } ) { return $aa }
1613                  elsif ($aa ne $genetic_code{ $n1 . $n2 . $n3 } ) { return "X" }  
1614              }      #  Test that codon is valid for an unambiguous aa:
1615          }  
1616        my $X = ( $codon =~ /[a-z]/ ) ? 'x' : 'X';
1617        if ( $codon !~ m/^[ACGTMY][ACGT][ACGTKMRSWYBDHVN]$/i
1618          && $codon !~ m/^YT[AGR]$/i     #  Leu YTR
1619          && $codon !~ m/^MG[AGR]$/i     #  Arg MGR
1620           )
1621        {
1622            return $X;
1623      }      }
1624    
1625      return $aa || "X";      #  Expand all ambiguous nucleotides to see if they all yield same aa.
1626    
1627        my @n1 = @{ $DNA_letter_can_be{ substr( $codon, 0, 1 ) } };
1628        my $n2 =                        substr( $codon, 1, 1 );
1629        my @n3 = @{ $DNA_letter_can_be{ substr( $codon, 2, 1 ) } };
1630        my @triples = map { my $n12 = $_ . $n2; map { $n12 . $_ } @n3 } @n1;
1631    
1632        my $triple = shift @triples;
1633        $aa = $genetic_code{ $triple };
1634        $aa or return $X;
1635    
1636        foreach $triple ( @triples ) { return $X if $aa ne $genetic_code{$triple} }
1637    
1638        return $aa;
1639  }  }
1640    
1641    
# Line 1368  Line 1644 
1644  #  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
1645  #  code, and transform the supplied nucleotide sequence to match.  #  code, and transform the supplied nucleotide sequence to match.
1646  #  #
1647  #  translate_seq_with_user_code($seq, \%gen_code [, $start_with_met] )  #     $aa = translate_seq_with_user_code( $nt, \%gen_code )
1648    #     $aa = translate_seq_with_user_code( $nt, \%gen_code, $start_with_met )
1649  #  #
1650    #  Modified 2007-11-22 to be less intrusive in these diagnoses by sensing
1651    #  the presence of both versions in the user code.
1652  #-----------------------------------------------------------------------------  #-----------------------------------------------------------------------------
1653    
1654  sub translate_seq_with_user_code {  sub translate_seq_with_user_code
1655    {
1656      my $seq = shift;      my $seq = shift;
1657      $seq =~ tr/-//d;     #  remove gaps  ***  Why?      $seq =~ tr/-//d;     #  remove gaps  ***  Why?
     $seq =~ tr/Xx/Nn/;   #  allow X  
1658    
1659      my $gc = shift;      #  Reference to hash of DNA alphabet code      my $gc = shift;      #  Reference to hash of code
1660      if (! $gc || ref($gc) ne "HASH") {      if (! $gc || ref($gc) ne "HASH")
1661          die "translate_seq_with_user_code needs genetic code hash as secondargument.";      {
1662            print STDERR "translate_seq_with_user_code needs genetic code hash as second argument.";
1663            return undef;
1664      }      }
1665    
1666      #  Test the type of code supplied: uppercase versus lowercase      #  Test code support for upper vs lower case:
1667    
1668      my ($RNA_F, $DNA_F, $M, $N, $X);      my ( $TTT, $UUU );
1669        if    ( $gc->{AAA} && ! $gc->{aaa} )   #  Uppercase only code table
1670      if ($gc->{ "AAA" }) {     #  Looks like uppercase code table      {
1671          $seq   = uc $seq;     #  Uppercase sequence          $seq   = uc $seq;     #  Uppercase sequence
1672          $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  
1673      }      }
1674      elsif ($gc->{ "aaa" }) {  #  Looks like lowercase code table      elsif ( $gc->{aaa} && ! $gc->{AAA} )   #  Lowercase only code table
1675        {
1676          $seq   = lc $seq;     #  Lowercase sequence          $seq   = lc $seq;     #  Lowercase sequence
1677          $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  
1678      }      }
1679      else {      elsif ( $gc->{aaa} )
1680          die "User-supplied genetic code does not have aaa or AAA\n";      {
1681            ( $TTT, $UUU ) = ( 'ttt', 'uuu' );
1682        }
1683        else
1684        {
1685            print STDERR "User-supplied genetic code does not have aaa or AAA\n";
1686            return undef;
1687      }      }
1688    
1689      #  Test the type of code supplied:  UUU versus TTT      #  Test code support for U vs T:
   
     my ($ambigs);  
1690    
1691      if ($gc->{ $RNA_F }) {     #  Looks like RNA code table      my $ambigs;
1692          $seq =~ tr/Tt/Uu/;      if    ( $gc->{$UUU} && ! $gc->{$TTT} )  # RNA only code table
1693        {
1694            $seq = tr/Tt/Uu/;
1695          $ambigs = \%RNA_letter_can_be;          $ambigs = \%RNA_letter_can_be;
1696      }      }
1697      elsif ($gc->{ $DNA_F }) {  #  Looks like DNA code table      elsif ( $gc->{$TTT} && ! $gc->{$UUU} )  # DNA only code table
1698          $seq =~ tr/Uu/Tt/;      {
1699            $seq = tr/Uu/Tt/;
1700          $ambigs = \%DNA_letter_can_be;          $ambigs = \%DNA_letter_can_be;
1701      }      }
1702      else {      else
1703          die "User-supplied genetic code does not have $RNA_F or $DNA_F\n";      {
1704            my $t = $seq =~ tr/Tt//;
1705            my $u = $seq =~ tr/Uu//;
1706            $ambigs = ( $t > $u ) ? \%DNA_letter_can_be : \%RNA_letter_can_be;
1707      }      }
1708    
1709      my $imax = length($seq) - 2;  # will try to translate 2 nucleotides!      #  We can now do the codon-by-codon translation:
1710    
1711      my $met = shift;     #  a third 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)  
     my $pep  = ($met && ($imax >= 0)) ? $M : "";  
     my $aa;  
1712    
1713      for (my $i = $met ? 3 : 0; $i <= $imax; $i += 3) {      #  A third argument that is true forces first amino acid to be Met
1714          $pep .= translate_codon_with_user_code( substr($seq,$i,3), $gc, $N, $X, $ambigs );  
1715        my @met;
1716        if ( ( shift @_ ) && ( my $codon1 = shift @codons ) )
1717        {
1718            push @met, ( $codon1 =~ /[a-z]/ ? 'm' : 'M' );
1719      }      }
1720    
1721      return $pep;      join( '', @met, map { translate_codon_with_user_code( $_, $gc, $ambigs ) } @codons )
1722  }  }
1723    
1724    
1725  #-----------------------------------------------------------------------------  #-----------------------------------------------------------------------------
1726  #  Translate with user-supplied genetic code hash.  For speed, no error  #  Translate with user-supplied genetic code hash.  No error check on the code.
1727  #  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.  
1728  #  #
1729  #  Should only be called through translate_seq_with_user_code  #     $aa = translate_codon_with_user_code( $triplet, \%code, \%ambig_table )
 #  
 #   translate_codon_with_user_code( $triplet, \%code, $N, $X, $ambig_table )  
1730  #  #
1731  #  $triplet      speaks for itself  #  $triplet      speaks for itself
1732  #  $code         ref to the hash with the codon translations  #  \%code         ref to the hash with the codon translations
1733  #  $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  
1734  #-----------------------------------------------------------------------------  #-----------------------------------------------------------------------------
1735    
1736    sub translate_codon_with_user_code
1737  sub translate_codon_with_user_code {  {
1738      my $codon = shift;      my ( $codon, $gc, $ambigs ) = @_;
     my $gc    = shift;  
     my $aa;  
1739    
1740      #  Try a simple lookup:      #  Try a simple lookup:
1741    
1742        my $aa;
1743      if ( $aa = $gc->{ $codon } ) { return $aa }      if ( $aa = $gc->{ $codon } ) { return $aa }
1744    
1745      #  Test that codon is valid and might have unambiguous aa:      #  Attempt to recover from mixed-case codons:
1746    
1747      my ($N, $X, $ambigs) = @_;      $codon = ( $codon =~ /[a-z]/ ) ? lc $codon : uc $codon;
1748      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  
1749    
1750      #  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.  
1751    
1752      $aa = "";      my $X = ( $codon =~ /[a-z]/ ) ? 'x' : 'X';
1753      for my $n2 ( @{ $ambigs->{ substr($codon,1,1) } } ) {  
1754          for my $n3 ( @{ $ambigs->{ substr($codon,2,1) } } ) {      if ( $codon =~ m/^[ACGTU][ACGTU]$/i )  # Add N?
1755              for my $n1 ( @{ $ambigs->{ substr($codon,0,1) } } ) {      {
1756                  #  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" }  
1757              }              }
1758        #  This makes assumptions about the user code, but tranlating ambiguous
1759        #  codons is really a bit off the wall to start with:
1760        elsif ( $codon !~ m/^[ACGTUMY][ACGTU][ACGTUKMRSWYBDHVN]$/i ) # Valid?
1761        {
1762            return $X;
1763          }          }
1764    
1765        #  Expand all ambiguous nucleotides to see if they all yield same aa.
1766    
1767        my @n1 = @{ $ambigs->{ substr( $codon, 0, 1 ) } };
1768        my $n2 =               substr( $codon, 1, 1 );
1769        my @n3 = @{ $ambigs->{ substr( $codon, 2, 1 ) } };
1770        my @triples = map { my $n12 = $_ . $n2; map { $n12 . $_ } @n3 } @n1;
1771    
1772        my $triple = shift @triples;
1773        $aa = $gc->{ $triple } || $gc->{ lc $triple } || $gc->{ uc $triple };
1774        $aa or return $X;
1775    
1776        foreach $triple ( @triples )
1777        {
1778            return $X if $aa ne ( $gc->{$triple} || $gc->{lc $triple} || $gc->{uc $triple} );
1779      }      }
1780    
1781      return $aa || $X;      return $aa;
1782  }  }
1783    
1784    
# Line 1676  Line 1966 
1966  }  }
1967    
1968    
1969    #-----------------------------------------------------------------------------
1970    #  Read qual.
1971    #
1972    #  Save the contents in a list of refs to arrays: [ $id, $descript, \@qual ]
1973    #
1974    #     @seq_entries = read_qual( )               #  STDIN
1975    #    \@seq_entries = read_qual( )               #  STDIN
1976    #     @seq_entries = read_qual( \*FILEHANDLE )
1977    #    \@seq_entries = read_qual( \*FILEHANDLE )
1978    #     @seq_entries = read_qual(  $filename )
1979    #    \@seq_entries = read_qual(  $filename )
1980    #-----------------------------------------------------------------------------
1981    sub read_qual {
1982        my ( $fh, $name, $close, $unused ) = input_filehandle( $_[0] );
1983        $unused && die "Bad reference type (" . ref( $unused ) . ") passed to read_qual\n";
1984    
1985        my @quals = ();
1986        my ($id, $desc, $qual) = ("", "", []);
1987    
1988        while ( <$fh> ) {
1989            chomp;
1990            if (/^>\s*(\S+)(\s+(.*))?$/) {        #  new id
1991                if ($id && @$qual) { push @quals, [ $id, $desc, $qual ] }
1992                ($id, $desc, $qual) = ($1, $3 ? $3 : "", []);
1993            }
1994            else {
1995                push @$qual, split;
1996            }
1997        }
1998        close( $fh ) if $close;
1999    
2000        if ($id && @$qual) { push @quals, [ $id, $desc, $qual ] }
2001        return wantarray ? @quals : \@quals;
2002    }
2003    
2004    
2005    #-------------------------------------------------------------------------------
2006    #  Fraction difference for an alignment of two nucleotide sequences in terms of
2007    #  number of differing residues, number of gaps, and number of gap opennings.
2008    #
2009    #     $fraction_diff = fraction_nt_diff( $seq1, $seq2, \%options )
2010    #
2011    #  or
2012    #
2013    #     $fraction_diff = fraction_nt_diff( $seq1, $seq2 )
2014    #     $fraction_diff = fraction_nt_diff( $seq1, $seq2, $gap_wgt )
2015    #     $fraction_diff = fraction_nt_diff( $seq1, $seq2, $open_wgt, $extend_wgt )
2016    #
2017    #  Options:
2018    #
2019    #      gap      => $gap_wgt          # Gap open and extend weight (D = 0.5)
2020    #      open     => $open_wgt         # Gap openning weight (D = gap_wgt)
2021    #      extend   => $extend_wgt       # Gap extension weight (D = open_wgt)
2022    #      t_gap    => $term_gap_wgt     # Terminal open and extend weight
2023    #      t_open   => $term_open_wgt    # Terminal gap open weight (D = open_wgt)
2024    #      t_extend => $term_extend_wgt  # Terminal gap extend weight (D = extend_wgt)
2025    #
2026    #  Default gap open and gap extend weights are 1/2.  Beware that
2027    #
2028    #     $fraction_diff = fraction_nt_diff( $seq1, $seq2, 1 )
2029    #
2030    #  and
2031    #
2032    #     $fraction_diff = fraction_nt_diff( $seq1, $seq2, 1, 0 )
2033    #
2034    #  are different.  The first has equal openning and extension weights, whereas
2035    #  the second has an openning weight of 1, and and extension weight of 0 (it
2036    #  only penalizes the number of runs of gaps).
2037    #-------------------------------------------------------------------------------
2038    sub fraction_nt_diff
2039    {
2040        my ( $npos, $nid, $ndif, $ngap, $nopen, $tgap, $topen ) = interpret_nt_align( @_[0,1] );
2041    
2042        my $diff_scr;
2043        if ( ref( $_[2] ) eq 'HASH' )
2044        {
2045            my $opts = $_[2];
2046            my $gap_open    = defined $opts->{ open }     ? $opts->{ open }
2047                            : defined $opts->{ gap }      ? $opts->{ gap }
2048                            : 0.5;
2049            my $gap_extend  = defined $opts->{ extend }   ? $opts->{ extend }
2050                            : $gap_open;
2051            my $term_open   = defined $opts->{ t_open }   ? $opts->{ t_open }
2052                            : defined $opts->{ t_gap }    ? $opts->{ t_gap }
2053                            : $gap_open;
2054            my $term_extend = defined $opts->{ t_extend } ? $opts->{ t_extend }
2055                            : defined $opts->{ t_gap }    ? $opts->{ t_gap }
2056                            : $gap_extend;
2057    
2058            $nopen -= $topen;
2059            $ngap  -= $tgap;
2060            $diff_scr = $ndif + $gap_open  * $nopen + $gap_extend  * ($ngap-$nopen)
2061                              + $term_open * $topen + $term_extend * ($tgap-$topen);
2062        }
2063        else
2064        {
2065            my $gap_open   = defined( $_[2] ) ? $_[2] : 0.5;
2066            my $gap_extend = defined( $_[3] ) ? $_[3] : $gap_open;
2067            $diff_scr = $ndif + $gap_open * $nopen + $gap_extend * ($ngap-$nopen);
2068        }
2069        my $ttl_scr = $nid + $diff_scr;
2070    
2071        $ttl_scr ? $diff_scr / $ttl_scr : undef
2072    }
2073    
2074    
2075    #-------------------------------------------------------------------------------
2076    #  Interpret an alignment of two nucleotide sequences in terms of: useful
2077    #  aligned positions (unambiguous, and not a common gap), number of identical
2078    #  residues, number of differing residues, number of gaps, and number of gap
2079    #  opennings.
2080    #
2081    #     ( $npos, $nid, $ndif, $ngap, $nopen, $tgap, $topen ) = interpret_nt_align( $seq1, $seq2 )
2082    #
2083    #  $npos  = total aligned positons (= $nid + $ndif + $ngap)
2084    #  $nid   = number of positions with identical nucleotides (ignoring case)
2085    #  $ndif  = number of positions with differing nucleotides
2086    #  $ngap  = number of positions with gap in one sequence but not the other
2087    #  $nopen = number of runs of gaps
2088    #  $tgap  = number of gaps in runs adjacent to a terminus
2089    #  $topen = number of alignment ends with gaps
2090    #
2091    #  Some of the methods might seem overly complex, but are necessary for cases
2092    #  in which the gaps switch strands in the alignment:
2093    #
2094    #     seq1  ---ACGTGAC--TTGCAGAG
2095    #     seq2  TTT---TGACGG--GCAGGG
2096    #     mask  00000011110000111111
2097    #
2098    #     npos  = 20
2099    #     nid   =  9
2100    #     ndif  =  1
2101    #     ngap  = 10
2102    #     nopen =  4
2103    #     tgap  =  3
2104    #     topen =  1
2105    #
2106    #  Although there are 4 gap opennings, there are only 2 runs in the mask,
2107    #  and the terminal run is length 6, not 3.  (Why handle these?  Because
2108    #  pairs of sequences from a multiple sequence alignment can look like this.)
2109    #-------------------------------------------------------------------------------
2110    sub interpret_nt_align
2111    {
2112        #  Remove alignment columns that are not informative:
2113        my ( $s1, $s2 ) = useful_nt_align( @_[0,1] );
2114        my $nmat = length( $s1 );          # Useful alignment length
2115    
2116        my $m1 = $s1;
2117        $m1 =~ tr/ACGT/\377/;              # Nucleotides to all 1 bits
2118        $m1 =~ tr/\377/\000/c;             # Others (gaps) to null byte
2119        my $m2 = $s2;
2120        $m2 =~ tr/ACGT/\377/;              # Nucleotides to all 1 bits
2121        $m2 =~ tr/\377/\000/c;             # Others (gaps) to null byte
2122        $m1 &= $m2;                        # Gap in either sequence becomes null
2123        $s1 &= $m1;                        # Apply mask to sequence 1
2124        $s2 &= $m1;                        # Apply mask to sequence 2
2125        my $nopen = @{[ $s1 =~ /\000+/g ]}   # Gap opens in sequence 1
2126                  + @{[ $s2 =~ /\000+/g ]};  # Gap opens in sequence 2
2127        my ( $tgap, $topen ) = ( 0, 0 );
2128        if ( $s1 =~ /^(\000+)/ || $s2 =~ /^(\000+)/ ) { $tgap += length( $1 ); $topen++ }
2129        if ( $s1 =~ /(\000+)$/ || $s2 =~ /(\000+)$/ ) { $tgap += length( $1 ); $topen++ }
2130        $s1 =~ tr/\000//d;                 # Remove nulls (former gaps)
2131        $s2 =~ tr/\000//d;                 # Remove nulls (former gaps)
2132        my $ngap = $nmat - length( $s1 );  # Total gaps
2133    
2134        my $xor = $s1 ^ $s2;               # xor of identical residues is null byte
2135        my $nid = ( $xor =~ tr/\000//d );  # Count the nulls (identical residues)
2136        my $ndif = $nmat - $nid - $ngap;
2137    
2138        ( $nmat, $nid, $ndif, $ngap, $nopen, $tgap, $topen )
2139    }
2140    
2141    
2142    sub useful_nt_align
2143    {
2144        my ( $s1, $s2 ) = map { uc $_ } @_;
2145        $s1 =~ tr/U/T/;         # Convert U to T
2146        my $m1 = $s1;
2147        $m1 =~ tr/ACGT-/\377/;  # Allowed symbols to hex FF byte
2148        $m1 =~ tr/\377/\000/c;  # All else to null byte
2149        $s2 =~ tr/U/T/;         # Convert U to T
2150        my $m2 = $s2;
2151        $m2 =~ tr/ACGT-/\377/;  # Allowed symbols to hex FF byte
2152        $m2 =~ tr/\377/\000/c;  # All else to null byte
2153        $m1 &= $m2;             # Invalid in either sequence becomes null
2154        $s1 &= $m1;             # Apply mask to sequence 1
2155        $s1 =~ tr/\000//d;      # Delete nulls in sequence 1
2156        $s2 &= $m1;             # Apply mask to sequence 2
2157        $s2 =~ tr/\000//d;      # Delete nulls in sequence 2
2158        ( $s1, $s2 )
2159    }
2160    
2161    
2162    #-------------------------------------------------------------------------------
2163    #  Interpret an alignment of two protein sequences in terms of: useful
2164    #  aligned positions (unambiguous, and not a common gap), number of identical
2165    #  residues, number of differing residues, number of gaps, and number of gap
2166    #  opennings.
2167    #
2168    #     ( $npos, $nid, $ndif, $ngap, $nopen, $tgap, $topen ) = interpret_aa_align( $seq1, $seq2 )
2169    #
2170    #  $npos  = total aligned positons (= $nid + $ndif + $ngap)
2171    #  $nid   = number of positions with identical amino acids (ignoring case)
2172    #  $ndif  = number of positions with differing amino acids
2173    #  $ngap  = number of positions with gap in one sequence but not the other
2174    #  $nopen = number of runs of gaps
2175    #  $tgap  = number of gaps in runs adjacent to a terminus
2176    #  $topen = number of alignment ends with gaps
2177    #
2178    #-------------------------------------------------------------------------------
2179    sub interpret_aa_align
2180    {
2181        #  Remove alignment columns that are not informative:
2182        my ( $s1, $s2 ) = useful_aa_align( @_[0,1] );
2183        my $nmat = length( $s1 );            # Useful alignment length
2184    
2185        my $m1 = $s1;
2186        $m1 =~ tr/ACDEFGHIKLMNPQRSTUVWY/\377/;  # Amino acids to all 1 bits
2187        $m1 =~ tr/\377/\000/c;               # Others (gaps) to null byte
2188        my $m2 = $s2;
2189        $m2 =~ tr/ACDEFGHIKLMNPQRSTUVWY/\377/;  # Amino acids to all 1 bits
2190        $m2 =~ tr/\377/\000/c;               # Others (gaps) to null byte
2191        $m1 &= $m2;                          # Gap in either sequence becomes null
2192        $s1 &= $m1;                          # Apply mask to sequence 1
2193        $s2 &= $m1;                          # Apply mask to sequence 2
2194        my $nopen = @{[ $s1 =~ /\000+/g ]}   # Gap opens in sequence 1
2195                  + @{[ $s2 =~ /\000+/g ]};  # Gap opens in sequence 2
2196        my ( $tgap, $topen ) = ( 0, 0 );
2197        if ( $s1 =~ /^(\000+)/ || $s2 =~ /^(\000+)/ ) { $tgap += length( $1 ); $topen++ }
2198        if ( $s1 =~ /(\000+)$/ || $s2 =~ /(\000+)$/ ) { $tgap += length( $1 ); $topen++ }
2199        $s1 =~ tr/\000//d;                 # Remove nulls (former gaps)
2200        $s2 =~ tr/\000//d;                 # Remove nulls (former gaps)
2201        my $ngap = $nmat - length( $s1 );  # Total gaps
2202    
2203        my $xor = $s1 ^ $s2;               # xor of identical residues is null byte
2204        my $nid = ( $xor =~ tr/\000//d );  # Count the nulls (identical residues)
2205        my $ndif = $nmat - $nid - $ngap;
2206    
2207        ( $nmat, $nid, $ndif, $ngap, $nopen, $tgap, $topen )
2208    }
2209    
2210    
2211    sub useful_aa_align
2212    {
2213        my ( $s1, $s2 ) = map { uc $_ } @_;
2214        my $m1 = $s1;
2215        $m1 =~ tr/ACDEFGHIKLMNPQRSTUVWY-/\377/;  # Allowed symbols to hex FF byte
2216        $m1 =~ tr/\377/\000/c;  # All else to null byte
2217        my $m2 = $s2;
2218        $m2 =~ tr/ACDEFGHIKLMNPQRSTUVWY-/\377/;  # Allowed symbols to hex FF byte
2219        $m2 =~ tr/\377/\000/c;  # All else to null byte
2220        $m1 &= $m2;             # Invalid in either sequence becomes null
2221        $s1 &= $m1;             # Apply mask to sequence 1
2222        $s1 =~ tr/\000//d;      # Delete nulls in sequence 1
2223        $s2 &= $m1;             # Apply mask to sequence 2
2224        $s2 =~ tr/\000//d;      # Delete nulls in sequence 2
2225        ( $s1, $s2 )
2226    }
2227    
2228    
2229  1;  1;

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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3