[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.12, Mon Feb 11 20:37:27 2008 UTC
# Line 3  Line 3 
3  #  A sequence entry is ( $id, $def, $seq )  #  A sequence entry is ( $id, $def, $seq )
4  #  A list of entries is a list of references  #  A list of entries is a list of references
5  #  #
 #  @seq_entry   = read_next_fasta_seq( \*FILEHANDLE )  
 #  @seq_entries = read_fasta_seqs( \*FILEHANDLE )   # Original form  
6  #  @seq_entries = read_fasta( )                     # STDIN  #  @seq_entries = read_fasta( )                     # STDIN
7  #  @seq_entries = read_fasta( \*FILEHANDLE )  #  @seq_entries = read_fasta( \*FILEHANDLE )
8  #  @seq_entries = read_fasta(  $filename )  #  @seq_entries = read_fasta(  $filename )
9    #  @entry = read_next_fasta_seq( \*FILEHANDLE )
10    # \@entry = read_next_fasta_seq( \*FILEHANDLE )
11    #  @entry = read_next_fasta_seq(  $filename )
12    # \@entry = read_next_fasta_seq(  $filename )
13    #  @entry = read_next_fasta_seq()                   # STDIN
14    # \@entry = read_next_fasta_seq()                   # STDIN
15    #  @seq_entries = read_fasta_seqs( \*FILEHANDLE )   # Original form
16  #  @seq_entries = read_clustal( )                   # STDIN  #  @seq_entries = read_clustal( )                   # STDIN
17  #  @seq_entries = read_clustal( \*FILEHANDLE )  #  @seq_entries = read_clustal( \*FILEHANDLE )
18  #  @seq_entries = read_clustal(  $filename )  #  @seq_entries = read_clustal(  $filename )
# Line 51  Line 56 
56  #  #
57  #  @entry  = subseq_DNA_entry( @seq_entry, $from, $to [, $fix_id] );  #  @entry  = subseq_DNA_entry( @seq_entry, $from, $to [, $fix_id] );
58  #  @entry  = subseq_RNA_entry( @seq_entry, $from, $to [, $fix_id] );  #  @entry  = subseq_RNA_entry( @seq_entry, $from, $to [, $fix_id] );
59    #  $DNAseq = DNA_subseq(  $seq, $from, $to );
60    #  $DNAseq = DNA_subseq( \$seq, $from, $to );
61    #  $RNAseq = RNA_subseq(  $seq, $from, $to );
62    #  $RNAseq = RNA_subseq( \$seq, $from, $to );
63  #  @entry  = complement_DNA_entry( @seq_entry [, $fix_id] );  #  @entry  = complement_DNA_entry( @seq_entry [, $fix_id] );
64  #  @entry  = complement_RNA_entry( @seq_entry [, $fix_id] );  #  @entry  = complement_RNA_entry( @seq_entry [, $fix_id] );
65  #  $DNAseq = complement_DNA_seq( $NA_seq );  #  $DNAseq = complement_DNA_seq( $NA_seq );
# Line 60  Line 69 
69  #  $seq    = pack_seq( $sequence )  #  $seq    = pack_seq( $sequence )
70  #  $seq    = clean_ae_sequence( $seq )  #  $seq    = clean_ae_sequence( $seq )
71  #  #
72  #  $seq = translate_seq( $seq [, $met_start] )  #  $aa = translate_seq( $nt, $met_start )
73    #  $aa = translate_seq( $nt )
74  #  $aa  = translate_codon( $triplet );  #  $aa  = translate_codon( $triplet );
 #  $aa  = translate_uc_DNA_codon( $upcase_DNA_triplet );  
75  #  #
76  #  User-supplied genetic code must be upper case index and match the  #  User-supplied genetic code.  The supplied code needs to be complete in
77  #  DNA versus RNA type of sequence  #  RNA and/or DNA, and upper and/or lower case.  The program guesses based
78    #  on lysine and phenylalanine codons.
79    #
80    #  $aa = translate_seq_with_user_code( $nt, $gen_code_hash, $met_start )
81    #  $aa = translate_seq_with_user_code( $nt, $gen_code_hash )
82  #  #
83  #  Locations (= oriented intervals) are ( id, start, end )  #  Locations (= oriented intervals) are ( id, start, end )
84  #  Intervals are ( id, left, right )  #  Intervals are ( id, left, right )
# Line 81  Line 94 
94  #  Convert GenBank locations to SEED locations  #  Convert GenBank locations to SEED locations
95  #  #
96  #  @seed_locs = gb_location_2_seed( $contig, @gb_locs )  #  @seed_locs = gb_location_2_seed( $contig, @gb_locs )
97    #
98    #  Read quality scores from a fasta-like file:
99    #
100    #  @seq_entries = read_qual( )               #  STDIN
101    # \@seq_entries = read_qual( )               #  STDIN
102    #  @seq_entries = read_qual( \*FILEHANDLE )
103    # \@seq_entries = read_qual( \*FILEHANDLE )
104    #  @seq_entries = read_qual(  $filename )
105    # \@seq_entries = read_qual(  $filename )
106    #
107    #  Evaluate nucleotide alignments:
108    #
109    #  $fraction_diff = fraction_nt_diff( $seq1, $seq2, \%options )
110    #  $fraction_diff = fraction_nt_diff( $seq1, $seq2 )
111    #  $fraction_diff = fraction_nt_diff( $seq1, $seq2, $gap_weight )
112    #  $fraction_diff = fraction_nt_diff( $seq1, $seq2, $gap_open, $gap_extend )
113    #
114    #  ( $npos, $nid, $ndif, $ngap, $nopen, $tgap, $topen ) = interpret_nt_align( $seq1, $seq2 )
115    #
116    
117  use strict;  use strict;
118    use Carp;
 use gjolib qw( wrap_text );  
119    
120  #  Exported global variables:  #  Exported global variables:
121    
# Line 131  Line 161 
161    
162          subseq_DNA_entry          subseq_DNA_entry
163          subseq_RNA_entry          subseq_RNA_entry
164            DNA_subseq
165            RNA_subseq
166          complement_DNA_entry          complement_DNA_entry
167          complement_RNA_entry          complement_RNA_entry
168          complement_DNA_seq          complement_DNA_seq
# Line 152  Line 184 
184          reverse_intervals          reverse_intervals
185    
186          gb_location_2_seed          gb_location_2_seed
187    
188            read_qual
189    
190            fraction_nt_diff
191            interpret_nt_align
192          );          );
193    
194  our @EXPORT_OK = qw(  our @EXPORT_OK = qw(
# Line 198  Line 235 
235      if ( ! ref( $file ) )      if ( ! ref( $file ) )
236      {      {
237          my $fh;          my $fh;
238          -f $file or die "Could not find input file \"$file\"\n";          if    ( -f $file                       ) { }
239          open( $fh, "<$file" ) || die "Could not open \"$file\" for input\n";          elsif (    $file =~ /^>(.+)$/ && -f $1 ) { $file = $1 }
240            else { die "Could not find input file '$file'\n" }
241            open( $fh, "<$file" ) || die "Could not open '$file' for input\n";
242          return ( $fh, $file, 1 );          return ( $fh, $file, 1 );
243      }      }
244    
# Line 219  Line 258 
258    
259    
260  #-----------------------------------------------------------------------------  #-----------------------------------------------------------------------------
261  #  Read fasta sequences.  #  Read fasta sequences.  Save the contents in a list of refs to arrays:
262  #  Save the contents in a list of refs to arrays:  (id, description, seq)  #
263    #     $seq_entry = [ id, description, seq ]
264  #  #
265  #     @seq_entries = read_fasta( )               #  STDIN  #     @seq_entries = read_fasta( )               #  STDIN
266  #    \@seq_entries = read_fasta( )               #  STDIN  #    \@seq_entries = read_fasta( )               #  STDIN
# Line 228  Line 268 
268  #    \@seq_entries = read_fasta( \*FILEHANDLE )  #    \@seq_entries = read_fasta( \*FILEHANDLE )
269  #     @seq_entries = read_fasta(  $filename )  #     @seq_entries = read_fasta(  $filename )
270  #    \@seq_entries = read_fasta(  $filename )  #    \@seq_entries = read_fasta(  $filename )
271    #  #  @seq_entries = read_fasta( "command |" )   #  open and read from pipe
272    #  # \@seq_entries = read_fasta( "command |" )   #  open and read from pipe
273    #
274    #-----------------------------------------------------------------------------
275    sub read_fasta
276    {
277        my @seqs = map { $_->[2] =~ tr/ \n\r\t//d; $_ }
278                   map { /^(\S+)(\s+([^\n]*\S)?\s*)?\n(.+)$/s ? [ $1, $3 || '', $4 ] : () }
279                   split /^>\s*/m, slurp( @_ );
280        wantarray() ? @seqs : \@seqs;
281    }
282    
283    #-----------------------------------------------------------------------------
284    #  A fast file reader:
285    #
286    #     $data = slurp( )               #  \*STDIN
287    #     $data = slurp( \*FILEHANDLE )  #  an open file handle
288    #     $data = slurp(  $filename )    #  a file name
289    #     $data = slurp( "<$filename" )  #  file with explicit direction
290    #   # $data = slurp( "$command |" )  #  open and read from pipe
291    #
292    #  Note:  It is faster to read lines by reading the file and splitting
293    #         than by reading the lines sequentially.  If space is not an
294    #         issue, this is the way to go.  If space is an issue, then lines
295    #         or records should be processed one-by-one (rather than loading
296    #         the whole input into a string or array).
297    #-----------------------------------------------------------------------------
298    sub slurp
299    {
300        my ( $fh, $close );
301        if ( ref $_[0] eq 'GLOB' )
302        {
303            $fh = shift;
304        }
305        elsif ( $_[0] && ! ref $_[0] )
306        {
307            my $file = shift;
308            if    ( -f $file                       ) { $file = "<$file" }
309            elsif (    $file =~ /^<(.*)$/ && -f $1 ) { }  # Explicit read
310          # elsif (    $file =~ /\S\s*\|$/         ) { }  # Read from a pipe
311            else                                     { return undef }
312            open $fh, $file or return undef;
313            $close = 1;
314        }
315        else
316        {
317            $fh = \*STDIN;
318        }
319    
320        my $out = '';
321        my $inc = 1048576;
322        my $end =       0;
323        my $read;
324        while ( $read = read( $fh, $out, $inc, $end ) ) { $end += $read }
325        close( $fh ) if $close;
326    
327        $out;
328    }
329    
330    
331  #-----------------------------------------------------------------------------  #-----------------------------------------------------------------------------
332  sub read_fasta {  #  Previous, 50% slower fasta reader:
333    #-----------------------------------------------------------------------------
334    sub read_fasta_0
335    {
336      my ( $fh, $name, $close, $unused ) = input_filehandle( $_[0] );      my ( $fh, $name, $close, $unused ) = input_filehandle( $_[0] );
337      $unused && die "Bad reference type (" . ref( $unused ) . ") passed to read_fasta\n";      $unused && die "Bad reference type (" . ref( $unused ) . ") passed to read_fasta\n";
338    
# Line 255  Line 358 
358    
359    
360  #-----------------------------------------------------------------------------  #-----------------------------------------------------------------------------
361  #  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
362  #  Return the contents as an array:  (id, description, seq)  #  read_fasta(), but can handle an arbitrarily large file.  State information
363    #  is retained in hashes, so any number of streams can be interlaced.
364    #
365    #      @entry = read_next_fasta_seq( \*FILEHANDLE )
366    #     \@entry = read_next_fasta_seq( \*FILEHANDLE )
367    #      @entry = read_next_fasta_seq(  $filename )
368    #     \@entry = read_next_fasta_seq(  $filename )
369    #      @entry = read_next_fasta_seq()                # \*STDIN
370    #     \@entry = read_next_fasta_seq()                # \*STDIN
371  #  #
372  #     @seq_entry = read_next_fasta_seq( \*FILEHANDLE )  #      @entry = ( $id, $description, $seq )
373    #
374    #  When reading at the end of file, () is returned.
375    #  With a filename, reading past this will reopen the file at the beginning.
376  #-----------------------------------------------------------------------------  #-----------------------------------------------------------------------------
377  #  Reading always overshoots, so save next id and description  #  Reading always overshoots, so save next id and description
378    
379  {   #  Use bare block to scope the header hash  {   #  Use bare block to scope the header hash
380    
381      my %next_header;      my %next_header;
382        my %file_handle;
383        my %close_file;
384    
385      sub read_next_fasta_seq {      sub read_next_fasta_seq
386          my $fh = shift;      {
387          my ( $id, $desc );          my $fh = $file_handle{ $_[0] };
388            if ( ! $fh )
389            {
390                if ( ref $_[0] )
391                {
392                    return () if ref $_[0] ne 'GLOB';
393                    $fh = $_[0];
394                }
395                elsif ( $_[0] )
396                {
397                    my $file = $_[0];
398                    if    ( -f $file                       ) { $file = "<$file" }
399                    elsif (    $file =~ /^<(.*)$/ && -f $1 ) { }  # Explicit read
400                  # elsif (    $file =~ /\S\s*\|$/         ) { }  # Read from a pipe
401                    else                                     { return () }
402                    open $fh, $file or return ();
403                    $close_file{ $fh } = 1;
404                }
405                else
406                {
407                    $fh = \*STDIN;
408                }
409                $file_handle{ $_[0] } = $fh;
410            }
411    
412          if ( defined( $next_header{$fh} ) ) {          my ( $id, $desc, $seq ) = ( undef, '', '' );
413            if ( defined( $next_header{$fh} ) )
414            {
415              ( $id, $desc ) = parse_fasta_title( $next_header{$fh} );              ( $id, $desc ) = parse_fasta_title( $next_header{$fh} );
416          }          }
417          else {          else
418              $next_header{$fh} = "";          {
419              ( $id, $desc ) = ( undef, "" );              $next_header{$fh} = '';
420          }          }
         my $seq = "";  
421    
422          while ( <$fh> ) {          while ( <$fh> )
423            {
424              chomp;              chomp;
425              if ( /^>/ ) {        #  new id              if ( /^>/ )        #  new id
426                {
427                  $next_header{$fh} = $_;                  $next_header{$fh} = $_;
428                  if ( defined($id) && $seq )                  if ( defined($id) && $seq )
429                  {                  {
430                      return wantarray ? ($id, $desc, $seq) : [$id, $desc, $seq]                      return wantarray ? ($id, $desc, $seq) : [$id, $desc, $seq]
431                  }                  }
432                  ( $id, $desc ) = parse_fasta_title( $next_header{$fh} );                  ( $id, $desc ) = parse_fasta_title( $next_header{$fh} );
433                  $seq = "";                  $seq = '';
434              }              }
435              else {              else
436                  tr/     0-9//d;              {
437                    tr/ \t\r//d;
438                  $seq .= $_ ;                  $seq .= $_ ;
439              }              }
440          }          }
441    
442          #  Done with file, delete "next header"          #  Done with file; there is no next header:
443    
444          delete $next_header{$fh};          delete $next_header{$fh};
445          return ( defined($id) && $seq ) ? ( wantarray ? ($id, $desc, $seq)  
446                                                        : [$id, $desc, $seq]          #  Return last set of data:
447                                            )  
448                                          : () ;          if ( defined($id) && $seq )
449            {
450                return wantarray ? ($id,$desc,$seq) : [$id,$desc,$seq]
451            }
452    
453            #  Or close everything out (returning the empty list tells caller
454            #  that we are done)
455    
456            if ( $close_file{ $fh } ) { close $fh; delete $close_file{ $fh } }
457            delete $file_handle{ $_[0] };
458    
459            return ();
460      }      }
461  }  }
462    
# Line 352  Line 506 
506  #     ($id, $def) = parse_fasta_title( $title )  #     ($id, $def) = parse_fasta_title( $title )
507  #     ($id, $def) = split_fasta_title( $title )  #     ($id, $def) = split_fasta_title( $title )
508  #-----------------------------------------------------------------------------  #-----------------------------------------------------------------------------
509  sub parse_fasta_title {  sub parse_fasta_title
510    {
511      my $title = shift;      my $title = shift;
512      chomp;      chomp $title;
     if ($title =~ /^>?\s*(\S+)(:?\s+(.*\S)\s*)?$/) {  
         return ($1, $3 ? $3 : "");  
     }  
     elsif ($title =~ /^>/) {  
         return ("", "");  
     }  
     else {  
         return (undef, "");  
     }  
 }  
513    
514  sub split_fasta_title {      return $title =~ /^>?\s*(\S+)(\s+(.*\S)?\s*)?$/ ? ( $1, $3 || '' )
515      parse_fasta_title ( shift );           : $title =~ /^>/                           ? ( '', '' )
516             :                                            ( undef, undef )
517  }  }
518    
519    sub split_fasta_title { parse_fasta_title( @_ ) }
520    
521    
522  #-----------------------------------------------------------------------------  #-----------------------------------------------------------------------------
523  #  Helper function for defining an output filehandle:  #  Helper function for defining an output filehandle:
# Line 430  Line 578 
578      my ( $fh, undef, $close, $unused ) = output_filehandle( shift );      my ( $fh, undef, $close, $unused ) = output_filehandle( shift );
579      ( unshift @_, $unused ) if $unused;      ( unshift @_, $unused ) if $unused;
580    
581      ( 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";
582    
583      #  Expand the sequence entry list if necessary:      #  Expand the sequence entry list if necessary:
584    
# Line 633  Line 781 
781    
782    
783  #-----------------------------------------------------------------------------  #-----------------------------------------------------------------------------
784    #  Return a string with text wrapped to defined line lengths:
785    #
786    #     $wrapped_text = wrap_text( $str )                  # default len   =  80
787    #     $wrapped_text = wrap_text( $str, $len )            # default ind   =   0
788    #     $wrapped_text = wrap_text( $str, $len, $indent )   # default ind_n = ind
789    #     $wrapped_text = wrap_text( $str, $len, $indent_1, $indent_n )
790    #-----------------------------------------------------------------------------
791    sub wrap_text {
792        my ($str, $len, $ind, $indn) = @_;
793    
794        defined($str)  || die "wrap_text called without a string\n";
795        defined($len)  || ($len  =   80);
796        defined($ind)  || ($ind  =    0);
797        ($ind  < $len) || die "wrap error: indent greater than line length\n";
798        defined($indn) || ($indn = $ind);
799        ($indn < $len) || die "wrap error: indent_n greater than line length\n";
800    
801        $str =~ s/\s+$//;
802        $str =~ s/^\s+//;
803        my ($maxchr, $maxchr1);
804        my (@lines) = ();
805    
806        while ($str) {
807            $maxchr1 = ($maxchr = $len - $ind) - 1;
808            if ($maxchr >= length($str)) {
809                push @lines, (" " x $ind) . $str;
810                last;
811            }
812            elsif ($str =~ /^(.{0,$maxchr1}\S)\s+(\S.*)$/) { # no expr in {}
813                push @lines, (" " x $ind) . $1;
814                $str = $2;
815            }
816            elsif ($str =~ /^(.{0,$maxchr1}-)(.*)$/) {
817                push @lines, (" " x $ind) . $1;
818                $str = $2;
819            }
820            else {
821                push @lines, (" " x $ind) . substr($str, 0, $maxchr);
822                $str = substr($str, $maxchr);
823            }
824            $ind = $indn;
825        }
826    
827        return join("\n", @lines);
828    }
829    
830    
831    #-----------------------------------------------------------------------------
832  #  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)
833  #  #
834  #     my \%seq_ind  = index_seq_list(  @seq_list );  #     my \%seq_ind  = index_seq_list(  @seq_list );
# Line 794  Line 990 
990  }  }
991    
992    
993    sub DNA_subseq
994    {
995        my ( $seq, $from, $to ) = @_;
996    
997        my $len = ref( $seq ) eq 'SCALAR' ? length( $$seq )
998                                          : length(  $seq );
999        if ( ( $from eq '$' ) || ( $from eq "" ) ) { $from = $len }
1000        if ( ( $to   eq '$' ) || ( ! $to       ) ) { $to   = $len }
1001    
1002        my $left  = ( $from < $to ) ? $from : $to;
1003        my $right = ( $from < $to ) ? $to   : $from;
1004        if ( ( $right < 1 ) || ( $left > $len ) ) { return "" }
1005        if ( $right > $len ) { $right = $len }
1006        if ( $left  < 1    ) { $left  =    1 }
1007    
1008        my $subseq = ref( $seq ) eq 'SCALAR' ? substr( $$seq, $left-1, $right-$left+1 )
1009                                             : substr(  $seq, $left-1, $right-$left+1 );
1010    
1011        if ( $from > $to )
1012        {
1013            $subseq = reverse $subseq;
1014            $subseq =~ tr[ACGTUKMRSWYBDHVNacgtukmrswybdhvn]
1015                         [TGCAAMKYSWRVHDBNtgcaamkyswrvhdbn];
1016        }
1017    
1018        $subseq
1019    }
1020    
1021    
1022    sub RNA_subseq
1023    {
1024        my ( $seq, $from, $to ) = @_;
1025    
1026        my $len = ref( $seq ) eq 'SCALAR' ? length( $$seq )
1027                                          : length(  $seq );
1028        if ( ( $from eq '$' ) || ( $from eq "" ) ) { $from = $len }
1029        if ( ( $to   eq '$' ) || ( ! $to       ) ) { $to   = $len }
1030    
1031        my $left  = ( $from < $to ) ? $from : $to;
1032        my $right = ( $from < $to ) ? $to   : $from;
1033        if ( ( $right < 1 ) || ( $left > $len ) ) { return "" }
1034        if ( $right > $len ) { $right = $len }
1035        if ( $left  < 1    ) { $left  =    1 }
1036    
1037        my $subseq = ref( $seq ) eq 'SCALAR' ? substr( $$seq, $left-1, $right-$left+1 )
1038                                             : substr(  $seq, $left-1, $right-$left+1 );
1039    
1040        if ( $from > $to )
1041        {
1042            $subseq = reverse $subseq;
1043            $subseq =~ tr[ACGTUKMRSWYBDHVNacgtukmrswybdhvn]
1044                         [UGCAAMKYSWRVHDBNugcaamkyswrvhdbn];
1045        }
1046    
1047        $subseq
1048    }
1049    
1050    
1051  sub complement_DNA_entry {  sub complement_DNA_entry {
1052      my ($id, $desc, $seq, $fix_id) = @_;      my ($id, $desc, $seq, $fix_id) = @_;
1053      $fix_id ||= 0;     #  fix undef values      $fix_id ||= 0;     #  fix undef values
# Line 911  Line 1165 
1165  #  Translate nucleotides to one letter protein:  #  Translate nucleotides to one letter protein:
1166  #  #
1167  #  $seq = translate_seq( $seq [, $met_start] )  #  $seq = translate_seq( $seq [, $met_start] )
1168  #  $aa  = translate_codon( $triplet );  #     $aa  = translate_codon( $triplet )
1169  #  $aa  = translate_uc_DNA_codon( $upcase_DNA_triplet );  #     $aa  = translate_DNA_codon( $triplet )     # Does not rely on DNA
1170    #     $aa  = translate_uc_DNA_codon( $triplet )  # Does not rely on uc or DNA
1171  #  #
1172  #  User-supplied genetic code must be upper case index and match the  #  User-supplied genetic code must be upper case index and match the
1173  #  DNA versus RNA type of sequence  #  DNA versus RNA type of sequence
# Line 929  Line 1184 
1184    
1185      # DNA version      # DNA version
1186    
1187      TTT => "F",  TCT => "S",  TAT => "Y",  TGT => "C",      TTT => 'F',  TCT => 'S',  TAT => 'Y',  TGT => 'C',
1188      TTC => "F",  TCC => "S",  TAC => "Y",  TGC => "C",      TTC => 'F',  TCC => 'S',  TAC => 'Y',  TGC => 'C',
1189      TTA => "L",  TCA => "S",  TAA => "*",  TGA => "*",      TTA => 'L',  TCA => 'S',  TAA => '*',  TGA => '*',
1190      TTG => "L",  TCG => "S",  TAG => "*",  TGG => "W",      TTG => 'L',  TCG => 'S',  TAG => '*',  TGG => 'W',
1191      CTT => "L",  CCT => "P",  CAT => "H",  CGT => "R",      CTT => 'L',  CCT => 'P',  CAT => 'H',  CGT => 'R',
1192      CTC => "L",  CCC => "P",  CAC => "H",  CGC => "R",      CTC => 'L',  CCC => 'P',  CAC => 'H',  CGC => 'R',
1193      CTA => "L",  CCA => "P",  CAA => "Q",  CGA => "R",      CTA => 'L',  CCA => 'P',  CAA => 'Q',  CGA => 'R',
1194      CTG => "L",  CCG => "P",  CAG => "Q",  CGG => "R",      CTG => 'L',  CCG => 'P',  CAG => 'Q',  CGG => 'R',
1195      ATT => "I",  ACT => "T",  AAT => "N",  AGT => "S",      ATT => 'I',  ACT => 'T',  AAT => 'N',  AGT => 'S',
1196      ATC => "I",  ACC => "T",  AAC => "N",  AGC => "S",      ATC => 'I',  ACC => 'T',  AAC => 'N',  AGC => 'S',
1197      ATA => "I",  ACA => "T",  AAA => "K",  AGA => "R",      ATA => 'I',  ACA => 'T',  AAA => 'K',  AGA => 'R',
1198      ATG => "M",  ACG => "T",  AAG => "K",  AGG => "R",      ATG => 'M',  ACG => 'T',  AAG => 'K',  AGG => 'R',
1199      GTT => "V",  GCT => "A",  GAT => "D",  GGT => "G",      GTT => 'V',  GCT => 'A',  GAT => 'D',  GGT => 'G',
1200      GTC => "V",  GCC => "A",  GAC => "D",  GGC => "G",      GTC => 'V',  GCC => 'A',  GAC => 'D',  GGC => 'G',
1201      GTA => "V",  GCA => "A",  GAA => "E",  GGA => "G",      GTA => 'V',  GCA => 'A',  GAA => 'E',  GGA => 'G',
1202      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",  
1203    
1204      #  The following ambiguous encodings are not necessary,  but      #  The following ambiguous encodings are not necessary,  but
1205      #  speed up the processing of some ambiguous triplets:      #  speed up the processing of some ambiguous triplets:
1206    
1207      TTY => "F",  TCY => "S",  TAY => "Y",  TGY => "C",      TTY => 'F',  TCY => 'S',  TAY => 'Y',  TGY => 'C',
1208      TTR => "L",  TCR => "S",  TAR => "*",      TTR => 'L',  TCR => 'S',  TAR => '*',
1209                   TCN => "S",                   TCN => 'S',
1210      CTY => "L",  CCY => "P",  CAY => "H",  CGY => "R",      CTY => 'L',  CCY => 'P',  CAY => 'H',  CGY => 'R',
1211      CTR => "L",  CCR => "P",  CAR => "Q",  CGR => "R",      CTR => 'L',  CCR => 'P',  CAR => 'Q',  CGR => 'R',
1212      CTN => "L",  CCN => "P",               CGN => "R",      CTN => 'L',  CCN => 'P',               CGN => 'R',
1213      ATY => "I",  ACY => "T",  AAY => "N",  AGY => "S",      ATY => 'I',  ACY => 'T',  AAY => 'N',  AGY => 'S',
1214                   ACR => "T",  AAR => "K",  AGR => "R",                   ACR => 'T',  AAR => 'K',  AGR => 'R',
1215                   ACN => "T",                   ACN => 'T',
1216      GTY => "V",  GCY => "A",  GAY => "D",  GGY => "G",      GTY => 'V',  GCY => 'A',  GAY => 'D',  GGY => 'G',
1217      GTR => "V",  GCR => "A",  GAR => "E",  GGR => "G",      GTR => 'V',  GCR => 'A',  GAR => 'E',  GGR => 'G',
1218      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"  
1219  );  );
1220    
1221    #  Add RNA by construction:
1222    
1223    foreach ( grep { /T/ } keys %genetic_code )
1224    {
1225        my $codon = $_;
1226        $codon =~ s/T/U/g;
1227        $genetic_code{ $codon } = lc $genetic_code{ $_ }
1228    }
1229    
1230  #  Add lower case by construction:  #  Add lower case by construction:
1231    
1232  foreach ( keys %genetic_code ) {  foreach ( keys %genetic_code )
1233    {
1234      $genetic_code{ lc $_ } = lc $genetic_code{ $_ }      $genetic_code{ lc $_ } = lc $genetic_code{ $_ }
1235  }  }
1236    
1237    
1238  #  Construct the genetic code with selanocysteine by difference:  #  Construct the genetic code with selenocysteine by difference:
1239    
1240  %genetic_code_with_U = map { $_ => $genetic_code{ $_ } } keys %genetic_code;  %genetic_code_with_U = %genetic_code;
1241  $genetic_code_with_U{ TGA } = "U";  $genetic_code_with_U{ TGA } = 'U';
1242  $genetic_code_with_U{ tga } = "u";  $genetic_code_with_U{ tga } = 'u';
1243  $genetic_code_with_U{ UGA } = "U";  $genetic_code_with_U{ UGA } = 'U';
1244  $genetic_code_with_U{ uga } = "u";  $genetic_code_with_U{ uga } = 'u';
1245    
1246    
1247  %amino_acid_codons_DNA = (  %amino_acid_codons_DNA = (
# Line 1271  Line 1505 
1505    
1506    
1507  #-----------------------------------------------------------------------------  #-----------------------------------------------------------------------------
1508  #  Translate nucleotides to one letter protein:  #  Translate nucleotides to one letter protein.  Respects case of the
1509    #  nucleotide sequence.
1510  #  #
1511  #      $seq = translate_seq( $seq [, $met_start] )  #      $aa = translate_seq( $nt, $met_start )
1512    #      $aa = translate_seq( $nt )
1513  #  #
1514  #-----------------------------------------------------------------------------  #-----------------------------------------------------------------------------
1515    
1516  sub translate_seq {  sub translate_seq
1517      my $seq = uc shift;  {
1518      $seq =~ tr/UX/TN/;      #  make it DNA, and allow X      my $seq = shift;
1519      $seq =~ tr/-//d;        #  remove gaps      $seq =~ tr/-//d;        #  remove gaps
1520    
1521      my $met = shift || 0;   #  a second argument that is true      my @codons = $seq =~ m/(...?)/g;  #  Will try to translate last 2 nt
1522                              #  forces first amino acid to be Met  
1523                              #  (note: undef is false)      #  A second argument that is true forces first amino acid to be Met
1524    
1525      my $imax = length($seq) - 2;  # will try to translate 2 nucleotides!      my @met;
1526      my $pep = ( ($met && ($imax >= 0)) ? "M" : "" );      if ( ( shift @_ ) && ( my $codon1 = shift @codons ) )
1527      for (my $i = $met ? 3 : 0; $i <= $imax; $i += 3) {      {
1528          $pep .= translate_uc_DNA_codon( substr($seq,$i,3) );          push @met, ( $codon1 =~ /[a-z]/ ? 'm' : 'M' );
1529      }      }
1530    
1531      return $pep;      join( '', @met, map { translate_codon( $_ ) } @codons )
1532  }  }
1533    
1534    
1535  #-----------------------------------------------------------------------------  #-----------------------------------------------------------------------------
1536  #  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.  
1537  #  #
1538  #      $aa = translate_codon( $triplet )  #      $aa = translate_codon( $triplet )
1539    #      $aa = translate_DNA_codon( $triplet )
1540    #      $aa = translate_uc_DNA_codon( $triplet )
1541  #  #
1542  #-----------------------------------------------------------------------------  #-----------------------------------------------------------------------------
1543    
1544  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);  
 }  
1545    
1546    sub translate_uc_DNA_codon { translate_codon( uc $_[0] ) }
1547    
1548  #-----------------------------------------------------------------------------  sub translate_codon
1549  #  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 {  
1550      my $codon = shift;      my $codon = shift;
1551      my $aa;      $codon =~ tr/Uu/Tt/;     #  Make it DNA
1552    
1553      #  Try a simple lookup:      #  Try a simple lookup:
1554    
1555        my $aa;
1556      if ( $aa = $genetic_code{ $codon } ) { return $aa }      if ( $aa = $genetic_code{ $codon } ) { return $aa }
1557    
1558      #  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  
1559    
1560      #  Expand all ambiguous nucleotides to see if they all yield same aa.      $codon = ( $codon =~ /[a-z]/ ) ? lc $codon : uc $codon;
1561      #  Loop order tries to fail quickly with first position change.      if ( $aa = $genetic_code{ $codon } ) { return $aa }
1562    
1563      $aa = "";      #  The code defined above catches simple N, R and Y ambiguities in the
1564      for my $n2 ( @{ $DNA_letter_can_be{ substr($codon,1,1) } } ) {      #  third position.  Other codons (e.g., GG[KMSWBDHV], or even GG) might
1565          for my $n3 ( @{ $DNA_letter_can_be{ substr($codon,2,1) } } ) {      #  be unambiguously translated by converting the last position to N and
1566              for my $n1 ( @{ $DNA_letter_can_be{ substr($codon,0,1) } } ) {      #  seeing if this is in the code table:
1567                  #  set the first value of $aa  
1568                  if ($aa eq "") { $aa = $genetic_code{ $n1 . $n2 . $n3 } }      my $N = ( $codon =~ /[a-z]/ ) ? 'n' : 'N';
1569                  #  or break out if any other amino acid is detected      if ( $aa = $genetic_code{ substr($codon,0,2) . $N } ) { return $aa }
1570                  elsif ($aa ne $genetic_code{ $n1 . $n2 . $n3 } ) { return "X" }  
1571              }      #  Test that codon is valid for an unambiguous aa:
1572          }  
1573        my $X = ( $codon =~ /[a-z]/ ) ? 'x' : 'X';
1574        if ( $codon !~ m/^[ACGTMY][ACGT][ACGTKMRSWYBDHVN]$/i
1575          && $codon !~ m/^YT[AGR]$/i     #  Leu YTR
1576          && $codon !~ m/^MG[AGR]$/i     #  Arg MGR
1577           )
1578        {
1579            return $X;
1580      }      }
1581    
1582      return $aa || "X";      #  Expand all ambiguous nucleotides to see if they all yield same aa.
1583    
1584        my @n1 = @{ $DNA_letter_can_be{ substr( $codon, 0, 1 ) } };
1585        my $n2 =                        substr( $codon, 1, 1 );
1586        my @n3 = @{ $DNA_letter_can_be{ substr( $codon, 2, 1 ) } };
1587        my @triples = map { my $n12 = $_ . $n2; map { $n12 . $_ } @n3 } @n1;
1588    
1589        my $triple = shift @triples;
1590        $aa = $genetic_code{ $triple };
1591        $aa or return $X;
1592    
1593        foreach $triple ( @triples ) { return $X if $aa ne $genetic_code{$triple} }
1594    
1595        return $aa;
1596  }  }
1597    
1598    
# Line 1368  Line 1601 
1601  #  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
1602  #  code, and transform the supplied nucleotide sequence to match.  #  code, and transform the supplied nucleotide sequence to match.
1603  #  #
1604  #  translate_seq_with_user_code($seq, \%gen_code [, $start_with_met] )  #     $aa = translate_seq_with_user_code( $nt, \%gen_code )
1605    #     $aa = translate_seq_with_user_code( $nt, \%gen_code, $start_with_met )
1606  #  #
1607    #  Modified 2007-11-22 to be less intrusive in these diagnoses by sensing
1608    #  the presence of both versions in the user code.
1609  #-----------------------------------------------------------------------------  #-----------------------------------------------------------------------------
1610    
1611  sub translate_seq_with_user_code {  sub translate_seq_with_user_code
1612    {
1613      my $seq = shift;      my $seq = shift;
1614      $seq =~ tr/-//d;     #  remove gaps  ***  Why?      $seq =~ tr/-//d;     #  remove gaps  ***  Why?
     $seq =~ tr/Xx/Nn/;   #  allow X  
1615    
1616      my $gc = shift;      #  Reference to hash of DNA alphabet code      my $gc = shift;      #  Reference to hash of code
1617      if (! $gc || ref($gc) ne "HASH") {      if (! $gc || ref($gc) ne "HASH")
1618          die "translate_seq_with_user_code needs genetic code hash as secondargument.";      {
1619            print STDERR "translate_seq_with_user_code needs genetic code hash as second argument.";
1620            return undef;
1621      }      }
1622    
1623      #  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);  
1624    
1625      if ($gc->{ "AAA" }) {     #  Looks like uppercase code table      my ( $TTT, $UUU );
1626        if    ( $gc->{AAA} && ! $gc->{aaa} )   #  Uppercase only code table
1627        {
1628          $seq   = uc $seq;     #  Uppercase sequence          $seq   = uc $seq;     #  Uppercase sequence
1629          $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  
1630      }      }
1631      elsif ($gc->{ "aaa" }) {  #  Looks like lowercase code table      elsif ( $gc->{aaa} && ! $gc->{AAA} )   #  Lowercase only code table
1632        {
1633          $seq   = lc $seq;     #  Lowercase sequence          $seq   = lc $seq;     #  Lowercase sequence
1634          $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  
1635      }      }
1636      else {      elsif ( $gc->{aaa} )
1637          die "User-supplied genetic code does not have aaa or AAA\n";      {
1638            ( $TTT, $UUU ) = ( 'ttt', 'uuu' );
1639        }
1640        else
1641        {
1642            print STDERR "User-supplied genetic code does not have aaa or AAA\n";
1643            return undef;
1644      }      }
1645    
1646      #  Test the type of code supplied:  UUU versus TTT      #  Test code support for U vs T:
   
     my ($ambigs);  
1647    
1648      if ($gc->{ $RNA_F }) {     #  Looks like RNA code table      my $ambigs;
1649          $seq =~ tr/Tt/Uu/;      if    ( $gc->{$UUU} && ! $gc->{$TTT} )  # RNA only code table
1650        {
1651            $seq = tr/Tt/Uu/;
1652          $ambigs = \%RNA_letter_can_be;          $ambigs = \%RNA_letter_can_be;
1653      }      }
1654      elsif ($gc->{ $DNA_F }) {  #  Looks like DNA code table      elsif ( $gc->{$TTT} && ! $gc->{$UUU} )  # DNA only code table
1655          $seq =~ tr/Uu/Tt/;      {
1656            $seq = tr/Uu/Tt/;
1657          $ambigs = \%DNA_letter_can_be;          $ambigs = \%DNA_letter_can_be;
1658      }      }
1659      else {      else
1660          die "User-supplied genetic code does not have $RNA_F or $DNA_F\n";      {
1661            my $t = $seq =~ tr/Tt//;
1662            my $u = $seq =~ tr/Uu//;
1663            $ambigs = ( $t > $u ) ? \%DNA_letter_can_be : \%RNA_letter_can_be;
1664      }      }
1665    
1666      my $imax = length($seq) - 2;  # will try to translate 2 nucleotides!      #  We can now do the codon-by-codon translation:
1667    
1668      my $met = shift;     #  a third argument that is true      my @codons = $seq =~ m/(...?)/g;  #  will try to translate last 2 nt
1669                           #  forces first amino acid to be Met  
1670                           #  (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;  
1671    
1672      for (my $i = $met ? 3 : 0; $i <= $imax; $i += 3) {      my @met;
1673          $pep .= translate_codon_with_user_code( substr($seq,$i,3), $gc, $N, $X, $ambigs );      if ( ( shift @_ ) && ( my $codon1 = shift @codons ) )
1674        {
1675            push @met, ( $codon1 =~ /[a-z]/ ? 'm' : 'M' );
1676      }      }
1677    
1678      return $pep;      join( '', @met, map { translate_codon_with_user_code( $_, $gc, $ambigs ) } @codons )
1679  }  }
1680    
1681    
1682  #-----------------------------------------------------------------------------  #-----------------------------------------------------------------------------
1683  #  Translate with user-supplied genetic code hash.  For speed, no error  #  Translate with user-supplied genetic code hash.  No error check on the code.
1684  #  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  
1685  #  #
1686  #   translate_codon_with_user_code( $triplet, \%code, $N, $X, $ambig_table )  #     $aa = translate_codon_with_user_code( $triplet, \%code, \%ambig_table )
1687  #  #
1688  #  $triplet      speaks for itself  #  $triplet      speaks for itself
1689  #  $code         ref to the hash with the codon translations  #  \%code         ref to the hash with the codon translations
1690  #  $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  
1691  #-----------------------------------------------------------------------------  #-----------------------------------------------------------------------------
1692    
1693    sub translate_codon_with_user_code
1694  sub translate_codon_with_user_code {  {
1695      my $codon = shift;      my ( $codon, $gc, $ambigs ) = @_;
     my $gc    = shift;  
     my $aa;  
1696    
1697      #  Try a simple lookup:      #  Try a simple lookup:
1698    
1699        my $aa;
1700      if ( $aa = $gc->{ $codon } ) { return $aa }      if ( $aa = $gc->{ $codon } ) { return $aa }
1701    
1702      #  Test that codon is valid and might have unambiguous aa:      #  Attempt to recover from mixed-case codons:
1703    
1704        $codon = ( $codon =~ /[a-z]/ ) ? lc $codon : uc $codon;
1705        if ( $aa = $genetic_code{ $codon } ) { return $aa }
1706    
1707      my ($N, $X, $ambigs) = @_;      #  Test that codon is valid for an unambiguous aa:
     if ( $codon =~ m/^[ACGTUMY][ACGTU]$/i ) { $codon .= $N }  
     if ( $codon !~ m/^[ACGTUMY][ACGTU][ACGTUKMRSWYBDHVN]$/i ) { return $X }  
     #                          ^^  
     #                          |+- for leucine YTR  
     #                          +-- for arginine MGR  
1708    
1709      #  Expand all ambiguous nucleotides to see if they all yield same aa.      my $X = ( $codon =~ /[a-z]/ ) ? 'x' : 'X';
     #  Loop order tries to fail quickly with first position change.  
1710    
1711      $aa = "";      if ( $codon =~ m/^[ACGTU][ACGTU]$/i )  # Add N?
1712      for my $n2 ( @{ $ambigs->{ substr($codon,1,1) } } ) {      {
1713          for my $n3 ( @{ $ambigs->{ substr($codon,2,1) } } ) {          $codon .= ( $codon =~ /[a-z]/ ) ? 'n' : 'N';
             for my $n1 ( @{ $ambigs->{ substr($codon,0,1) } } ) {  
                 #  set the first value of $aa  
                 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" }  
1714              }              }
1715        #  This makes assumptions about the user code, but tranlating ambiguous
1716        #  codons is really a bit off the wall to start with:
1717        elsif ( $codon !~ m/^[ACGTUMY][ACGTU][ACGTUKMRSWYBDHVN]$/i ) # Valid?
1718        {
1719            return $X;
1720          }          }
1721    
1722        #  Expand all ambiguous nucleotides to see if they all yield same aa.
1723    
1724        my @n1 = @{ $ambigs->{ substr( $codon, 0, 1 ) } };
1725        my $n2 =               substr( $codon, 1, 1 );
1726        my @n3 = @{ $ambigs->{ substr( $codon, 2, 1 ) } };
1727        my @triples = map { my $n12 = $_ . $n2; map { $n12 . $_ } @n3 } @n1;
1728    
1729        my $triple = shift @triples;
1730        $aa = $gc->{ $triple } || $gc->{ lc $triple } || $gc->{ uc $triple };
1731        $aa or return $X;
1732    
1733        foreach $triple ( @triples )
1734        {
1735            return $X if $aa ne ( $gc->{$triple} || $gc->{lc $triple} || $gc->{uc $triple} );
1736      }      }
1737    
1738      return $aa || $X;      return $aa;
1739  }  }
1740    
1741    
# Line 1676  Line 1923 
1923  }  }
1924    
1925    
1926    #-----------------------------------------------------------------------------
1927    #  Read qual.
1928    #
1929    #  Save the contents in a list of refs to arrays: [ $id, $descript, \@qual ]
1930    #
1931    #     @seq_entries = read_qual( )               #  STDIN
1932    #    \@seq_entries = read_qual( )               #  STDIN
1933    #     @seq_entries = read_qual( \*FILEHANDLE )
1934    #    \@seq_entries = read_qual( \*FILEHANDLE )
1935    #     @seq_entries = read_qual(  $filename )
1936    #    \@seq_entries = read_qual(  $filename )
1937    #-----------------------------------------------------------------------------
1938    sub read_qual {
1939        my ( $fh, $name, $close, $unused ) = input_filehandle( $_[0] );
1940        $unused && die "Bad reference type (" . ref( $unused ) . ") passed to read_qual\n";
1941    
1942        my @quals = ();
1943        my ($id, $desc, $qual) = ("", "", []);
1944    
1945        while ( <$fh> ) {
1946            chomp;
1947            if (/^>\s*(\S+)(\s+(.*))?$/) {        #  new id
1948                if ($id && @$qual) { push @quals, [ $id, $desc, $qual ] }
1949                ($id, $desc, $qual) = ($1, $3 ? $3 : "", []);
1950            }
1951            else {
1952                push @$qual, split;
1953            }
1954        }
1955        close( $fh ) if $close;
1956    
1957        if ($id && @$qual) { push @quals, [ $id, $desc, $qual ] }
1958        return wantarray ? @quals : \@quals;
1959    }
1960    
1961    
1962    #-------------------------------------------------------------------------------
1963    #  Fraction difference for an alignment of two nucleotide sequences in terms of
1964    #  number of differing residues, number of gaps, and number of gap opennings.
1965    #
1966    #     $fraction_diff = fraction_nt_diff( $seq1, $seq2, \%options )
1967    #
1968    #  or
1969    #
1970    #     $fraction_diff = fraction_nt_diff( $seq1, $seq2 )
1971    #     $fraction_diff = fraction_nt_diff( $seq1, $seq2, $gap_wgt )
1972    #     $fraction_diff = fraction_nt_diff( $seq1, $seq2, $open_wgt, $extend_wgt )
1973    #
1974    #  Options:
1975    #
1976    #      gap      => $gap_wgt          # Gap open and extend weight (D = 0.5)
1977    #      open     => $open_wgt         # Gap openning weight (D = gap_wgt)
1978    #      extend   => $extend_wgt       # Gap extension weight (D = open_wgt)
1979    #      t_gap    => $term_gap_wgt     # Terminal open and extend weight
1980    #      t_open   => $term_open_wgt    # Terminal gap open weight (D = open_wgt)
1981    #      t_extend => $term_extend_wgt  # Terminal gap extend weight (D = extend_wgt)
1982    #
1983    #  Default gap open and gap extend weights are 1/2.  Beware that
1984    #
1985    #     $fraction_diff = fraction_nt_diff( $seq1, $seq2, 1 )
1986    #
1987    #  and
1988    #
1989    #     $fraction_diff = fraction_nt_diff( $seq1, $seq2, 1, 0 )
1990    #
1991    #  are different.  The first has equal openning and extension weights, whereas
1992    #  the second has an openning weight of 1, and and extension weight of 0 (it
1993    #  only penalizes the number of runs of gaps).
1994    #-------------------------------------------------------------------------------
1995    sub fraction_nt_diff
1996    {
1997        my ( $npos, $nid, $ndif, $ngap, $nopen, $tgap, $topen ) = interpret_nt_align( @_[0,1] );
1998    
1999        my $diff_scr;
2000        if ( ref( $_[2] ) eq 'HASH' )
2001        {
2002            my $opts = $_[2];
2003            my $gap_open    = defined $opts->{ open }     ? $opts->{ open }
2004                            : defined $opts->{ gap }      ? $opts->{ gap }
2005                            : 0.5;
2006            my $gap_extend  = defined $opts->{ extend }   ? $opts->{ extend }
2007                            : $gap_open;
2008            my $term_open   = defined $opts->{ t_open }   ? $opts->{ t_open }
2009                            : defined $opts->{ t_gap }    ? $opts->{ t_gap }
2010                            : $gap_open;
2011            my $term_extend = defined $opts->{ t_extend } ? $opts->{ t_extend }
2012                            : defined $opts->{ t_gap }    ? $opts->{ t_gap }
2013                            : $gap_extend;
2014    
2015            $nopen -= $topen;
2016            $ngap  -= $tgap;
2017            $diff_scr = $ndif + $gap_open  * $nopen + $gap_extend  * ($ngap-$nopen)
2018                              + $term_open * $topen + $term_extend * ($tgap-$topen);
2019        }
2020        else
2021        {
2022            my $gap_open   = defined( $_[2] ) ? $_[2] : 0.5;
2023            my $gap_extend = defined( $_[3] ) ? $_[3] : $gap_open;
2024            $diff_scr = $ndif + $gap_open * $nopen + $gap_extend * ($ngap-$nopen);
2025        }
2026        my $ttl_scr = $nid + $diff_scr;
2027    
2028        $ttl_scr ? $diff_scr / $ttl_scr : undef
2029    }
2030    
2031    
2032    #-------------------------------------------------------------------------------
2033    #  Interpret an alignment of two nucleotide sequences in terms of: useful
2034    #  aligned positions (unambiguous, and not a common gap), number of identical
2035    #  residues, number of differing residues, number of gaps, and number of gap
2036    #  opennings.
2037    #
2038    #     ( $npos, $nid, $ndif, $ngap, $nopen, $tgap, $topen ) = interpret_nt_align( $seq1, $seq2 )
2039    #
2040    #  $npos  = total aligned positons (= $nid + $ndif + $ngap)
2041    #  $nid   = number of positions with identical nucleotides (ignoring case)
2042    #  $ndif  = number of positions with differing nucleotides
2043    #  $ngap  = number of positions with gap in one sequence but not the other
2044    #  $nopen = number of runs of gaps
2045    #  $tgap  = number of gaps in runs adjacent to a terminus
2046    #  $topen = number of alignment ends with gaps
2047    #
2048    #  Some of the methods might seem overly complex, but are necessary for cases
2049    #  in which the gaps switch strands in the alignment:
2050    #
2051    #     seq1  ---ACGTGAC--TTGCAGAG
2052    #     seq2  TTT---TGACGG--GCAGGG
2053    #     mask  00000011110000111111
2054    #
2055    #     npos  = 20
2056    #     nid   =  9
2057    #     ndif  =  1
2058    #     ngap  = 10
2059    #     nopen =  4
2060    #     tgap  =  3
2061    #     topen =  1
2062    #
2063    #  Although there are 4 gap opennings, there are only 2 runs in the mask,
2064    #  and the terminal run is length 6, not 3.  (Why handle these?  Because
2065    #  pairs of sequences from a multiple sequence alignment can look like this.)
2066    #-------------------------------------------------------------------------------
2067    sub interpret_nt_align
2068    {
2069        #  Remove alignment columns that are not informative:
2070        my ( $s1, $s2 ) = useful_nt_align( @_[0,1] );
2071        my $nmat = length( $s1 );          # Useful alignment length
2072    
2073        my $m1 = $s1;
2074        $m1 =~ tr/ACGT/\377/;              # Nucleotides to all 1 bits
2075        $m1 =~ tr/\377/\000/c;             # Others (gaps) to null byte
2076        my $m2 = $s2;
2077        $m2 =~ tr/ACGT/\377/;              # Nucleotides to all 1 bits
2078        $m2 =~ tr/\377/\000/c;             # Others (gaps) to null byte
2079        $m1 &= $m2;                        # Gap in either sequence becomes null
2080        $s1 &= $m1;                        # Apply mask to sequence 1
2081        $s2 &= $m1;                        # Apply mask to sequence 2
2082        my $nopen = @{[ $s1 =~ /\000+/g ]}   # Gap opens in sequence 1
2083                  + @{[ $s2 =~ /\000+/g ]};  # Gap opens in sequence 2
2084        my ( $tgap, $topen ) = ( 0, 0 );
2085        if ( $s1 =~ /^(\000+)/ || $s2 =~ /^(\000+)/ ) { $tgap += length( $1 ); $topen++ }
2086        if ( $s1 =~ /(\000+)$/ || $s2 =~ /(\000+)$/ ) { $tgap += length( $1 ); $topen++ }
2087        $s1 =~ tr/\000//d;                 # Remove nulls (former gaps)
2088        $s2 =~ tr/\000//d;                 # Remove nulls (former gaps)
2089        my $ngap = $nmat - length( $s1 );  # Total gaps
2090    
2091        my $xor = $s1 ^ $s2;               # xor of identical residues is null byte
2092        my $nid = ( $xor =~ tr/\000//d );  # Count the nulls (identical residues)
2093        my $ndif = $nmat - $nid - $ngap;
2094    
2095        ( $nmat, $nid, $ndif, $ngap, $nopen, $tgap, $topen )
2096    }
2097    
2098    
2099    sub useful_nt_align
2100    {
2101        my ( $s1, $s2 ) = map { uc $_ } @_;
2102        $s1 =~ tr/U/T/;         # Convert U to T
2103        my $m1 = $s1;
2104        $m1 =~ tr/ACGT-/\377/;  # Allowed symbols to hex FF byte
2105        $m1 =~ tr/\377/\000/c;  # All else to null byte
2106        $s2 =~ tr/U/T/;         # Convert U to T
2107        my $m2 = $s2;
2108        $m2 =~ tr/ACGT-/\377/;  # Allowed symbols to hex FF byte
2109        $m2 =~ tr/\377/\000/c;  # All else to null byte
2110        $m1 &= $m2;             # Invalid in either sequence becomes null
2111        $s1 &= $m1;             # Apply mask to sequence 1
2112        $s1 =~ tr/\000//d;      # Delete nulls in sequence 1
2113        $s2 &= $m1;             # Apply mask to sequence 2
2114        $s2 =~ tr/\000//d;      # Delete nulls in sequence 2
2115        ( $s1, $s2 )
2116    }
2117    
2118    
2119  1;  1;

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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3