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

Annotation of /FigKernelPackages/gjoseqlib.pm

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1.11 - (view) (download) (as text)

1 : efrank 1.1 package gjoseqlib;
2 :    
3 : golsen 1.2 # A sequence entry is ( $id, $def, $seq )
4 :     # A list of entries is a list of references
5 :     #
6 : overbeek 1.4 # @seq_entry = read_next_fasta_seq( \*FILEHANDLE )
7 :     # @seq_entries = read_fasta_seqs( \*FILEHANDLE ) # Original form
8 :     # @seq_entries = read_fasta( ) # STDIN
9 :     # @seq_entries = read_fasta( \*FILEHANDLE )
10 :     # @seq_entries = read_fasta( $filename )
11 :     # @seq_entries = read_clustal( ) # STDIN
12 :     # @seq_entries = read_clustal( \*FILEHANDLE )
13 :     # @seq_entries = read_clustal( $filename )
14 :     # @seq_entries = read_clustal_file( $filename )
15 : golsen 1.2 #
16 : overbeek 1.4 # $seq_ind = index_seq_list( @seq_entries ); # hash from ids to entries
17 : golsen 1.2 # @seq_entry = seq_entry_by_id( \%seq_index, $seq_id );
18 :     # $seq_desc = seq_desc_by_id( \%seq_index, $seq_id );
19 :     # $seq = seq_data_by_id( \%seq_index, $seq_id );
20 :     #
21 :     # ( $id, $def ) = parse_fasta_title( $title )
22 :     # ( $id, $def ) = split_fasta_title( $title )
23 :     #
24 : overbeek 1.4 # print_seq_list_as_fasta( \*FILEHANDLE, @seq_entry_list ); # Original form
25 :     # print_alignment_as_fasta( @seq_entry_list ); # STDOUT
26 :     # print_alignment_as_fasta( \@seq_entry_list ); # STDOUT
27 :     # print_alignment_as_fasta( \*FILEHANDLE, @seq_entry_list );
28 :     # print_alignment_as_fasta( \*FILEHANDLE, \@seq_entry_list );
29 :     # print_alignment_as_fasta( $filename, @seq_entry_list );
30 :     # print_alignment_as_fasta( $filename, \@seq_entry_list );
31 :     # print_alignment_as_phylip( @seq_entry_list ); # STDOUT
32 :     # print_alignment_as_phylip( \@seq_entry_list ); # STDOUT
33 :     # print_alignment_as_phylip( \*FILEHANDLE, @seq_entry_list );
34 :     # print_alignment_as_phylip( \*FILEHANDLE, \@seq_entry_list );
35 :     # print_alignment_as_phylip( $filename, @seq_entry_list );
36 :     # print_alignment_as_phylip( $filename, \@seq_entry_list );
37 :     # print_alignment_as_nexus( [ \%label_hash, ] @seq_entry_list );
38 :     # print_alignment_as_nexus( [ \%label_hash, ] \@seq_entry_list );
39 :     # print_alignment_as_nexus( \*FILEHANDLE, [ \%label_hash, ] @seq_entry_list );
40 :     # print_alignment_as_nexus( \*FILEHANDLE, [ \%label_hash, ] \@seq_entry_list );
41 :     # print_alignment_as_nexus( $filename, [ \%label_hash, ] @seq_entry_list );
42 :     # print_alignment_as_nexus( $filename, [ \%label_hash, ] \@seq_entry_list );
43 :     # print_seq_as_fasta( \*FILEHANDLE, $id, $desc, $seq) ;
44 :     # print_seq_as_fasta( \*FILEHANDLE, @seq_entry );
45 :     # print_gb_locus( \*FILEHANDLE, $locus, $def, $accession, $seq );
46 : golsen 1.2 #
47 : golsen 1.6 # @packed_seqs = pack_alignment( @seqs )
48 :     # @packed_seqs = pack_alignment( \@seqs )
49 :     # \@packed_seqs = pack_alignment( @seqs )
50 :     # \@packed_seqs = pack_alignment( \@seqs )
51 : golsen 1.5 #
52 : golsen 1.2 # @entry = subseq_DNA_entry( @seq_entry, $from, $to [, $fix_id] );
53 :     # @entry = subseq_RNA_entry( @seq_entry, $from, $to [, $fix_id] );
54 : golsen 1.9 # $DNAseq = DNA_subseq( $seq, $from, $to );
55 :     # $DNAseq = DNA_subseq( \$seq, $from, $to );
56 :     # $RNAseq = RNA_subseq( $seq, $from, $to );
57 :     # $RNAseq = RNA_subseq( \$seq, $from, $to );
58 : golsen 1.2 # @entry = complement_DNA_entry( @seq_entry [, $fix_id] );
59 :     # @entry = complement_RNA_entry( @seq_entry [, $fix_id] );
60 :     # $DNAseq = complement_DNA_seq( $NA_seq );
61 :     # $RNAseq = complement_RNA_seq( $NA_seq );
62 :     # $DNAseq = to_DNA_seq( $NA_seq );
63 :     # $RNAseq = to_RNA_seq( $NA_seq );
64 :     # $seq = pack_seq( $sequence )
65 :     # $seq = clean_ae_sequence( $seq )
66 :     #
67 : golsen 1.10 # $aa = translate_seq( $nt, $met_start )
68 :     # $aa = translate_seq( $nt )
69 :     # $aa = translate_codon( $triplet );
70 :     #
71 :     # User-supplied genetic code. The supplied code needs to be complete in
72 :     # RNA and/or DNA, and upper and/or lower case. The program guesses based
73 :     # on lysine and phenylalanine codons.
74 : golsen 1.2 #
75 : golsen 1.10 # $aa = translate_seq_with_user_code( $nt, $gen_code_hash, $met_start )
76 :     # $aa = translate_seq_with_user_code( $nt, $gen_code_hash )
77 : golsen 1.9 #
78 : golsen 1.10 # Locations (= oriented intervals) are ( id, start, end )
79 :     # Intervals are ( id, left, right )
80 : golsen 1.2 #
81 : overbeek 1.4 # @intervals = read_intervals( \*FILEHANDLE )
82 :     # @intervals = read_oriented_intervals( \*FILEHANDLE )
83 : golsen 1.2 # @intervals = standardize_intervals( @interval_refs ) # (id, left, right)
84 :     # @joined = join_intervals( @interval_refs )
85 :     # @intervals = locations_2_intervals( @locations )
86 :     # $interval = locations_2_intervals( $location )
87 :     # @reversed = reverse_intervals( @interval_refs ) # (id, end, start)
88 : overbeek 1.4 #
89 :     # Convert GenBank locations to SEED locations
90 :     #
91 :     # @seed_locs = gb_location_2_seed( $contig, @gb_locs )
92 : golsen 1.7 #
93 :     # Read quality scores from a fasta-like file:
94 :     #
95 :     # @seq_entries = read_qual( ) # STDIN
96 :     # \@seq_entries = read_qual( ) # STDIN
97 :     # @seq_entries = read_qual( \*FILEHANDLE )
98 :     # \@seq_entries = read_qual( \*FILEHANDLE )
99 :     # @seq_entries = read_qual( $filename )
100 :     # \@seq_entries = read_qual( $filename )
101 :     #
102 : golsen 1.11 # Evaluate nucleotide alignments:
103 :     #
104 :     # $fraction_diff = fraction_nt_diff( $seq1, $seq2, \%options )
105 :     # $fraction_diff = fraction_nt_diff( $seq1, $seq2 )
106 :     # $fraction_diff = fraction_nt_diff( $seq1, $seq2, $gap_weight )
107 :     # $fraction_diff = fraction_nt_diff( $seq1, $seq2, $gap_open, $gap_extend )
108 :     #
109 :     # ( $npos, $nid, $ndif, $ngap, $nopen, $tgap, $topen ) = interpret_nt_align( $seq1, $seq2 )
110 :     #
111 : golsen 1.2
112 :     use strict;
113 : golsen 1.9 use Carp;
114 : efrank 1.1
115 : golsen 1.2 # Exported global variables:
116 : efrank 1.1
117 : golsen 1.2 our @aa_1_letter_order; # Alpha by 1 letter
118 :     our @aa_3_letter_order; # PAM matrix order
119 :     our @aa_n_codon_order;
120 :     our %genetic_code;
121 :     our %genetic_code_with_U;
122 :     our %amino_acid_codons_DNA;
123 :     our %amino_acid_codons_RNA;
124 :     our %n_codon_for_aa;
125 :     our %reverse_genetic_code_DNA;
126 :     our %reverse_genetic_code_RNA;
127 :     our %DNA_letter_can_be;
128 :     our %RNA_letter_can_be;
129 :     our %one_letter_to_three_letter_aa;
130 :     our %three_letter_to_one_letter_aa;
131 : efrank 1.1
132 :     require Exporter;
133 :    
134 :     our @ISA = qw(Exporter);
135 :     our @EXPORT = qw(
136 :     read_fasta_seqs
137 : overbeek 1.4 read_fasta
138 : efrank 1.1 read_next_fasta_seq
139 : overbeek 1.4 read_clustal_file
140 :     read_clustal
141 : efrank 1.1 parse_fasta_title
142 :     split_fasta_title
143 :     print_seq_list_as_fasta
144 : overbeek 1.4 print_alignment_as_fasta
145 :     print_alignment_as_phylip
146 :     print_alignment_as_nexus
147 : efrank 1.1 print_seq_as_fasta
148 :     print_gb_locus
149 :    
150 :     index_seq_list
151 :     seq_entry_by_id
152 :     seq_desc_by_id
153 :     seq_data_by_id
154 :    
155 : golsen 1.5 pack_alignment
156 :    
157 : efrank 1.1 subseq_DNA_entry
158 :     subseq_RNA_entry
159 : golsen 1.9 DNA_subseq
160 :     RNA_subseq
161 : efrank 1.1 complement_DNA_entry
162 :     complement_RNA_entry
163 :     complement_DNA_seq
164 :     complement_RNA_seq
165 :     to_DNA_seq
166 :     to_RNA_seq
167 : golsen 1.2 pack_seq
168 : efrank 1.1 clean_ae_sequence
169 :    
170 :     translate_seq
171 :     translate_codon
172 :     translate_seq_with_user_code
173 :    
174 :     read_intervals
175 : golsen 1.2 standardize_intervals
176 : efrank 1.1 join_intervals
177 : golsen 1.2 locations_2_intervals
178 :     read_oriented_intervals
179 :     reverse_intervals
180 : overbeek 1.4
181 :     gb_location_2_seed
182 : golsen 1.7
183 :     read_qual
184 : golsen 1.11
185 :     fraction_nt_diff
186 :     interpret_nt_align
187 : efrank 1.1 );
188 :    
189 : golsen 1.2 our @EXPORT_OK = qw(
190 :     @aa_1_letter_order
191 :     @aa_3_letter_order
192 :     @aa_n_codon_order
193 :     %genetic_code
194 :     %genetic_code_with_U
195 :     %amino_acid_codons_DNA
196 :     %amino_acid_codons_RNA
197 :     %n_codon_for_aa
198 :     %reverse_genetic_code_DNA
199 :     %reverse_genetic_code_RNA
200 :     %DNA_letter_can_be
201 :     %RNA_letter_can_be
202 :     %one_letter_to_three_letter_aa
203 :     %three_letter_to_one_letter_aa
204 :     );
205 : efrank 1.1
206 :    
207 :     #-----------------------------------------------------------------------------
208 : overbeek 1.4 # Helper function for defining an input filehandle:
209 :     # filehandle is passed through
210 :     # string is taken as file name to be openend
211 :     # undef or "" defaults to STDOUT
212 :     #
213 :     # ( \*FH, $name, $close [, $file] ) = input_filehandle( $file );
214 :     #
215 :     #-----------------------------------------------------------------------------
216 :     sub input_filehandle
217 :     {
218 :     my $file = shift;
219 :    
220 :     # FILEHANDLE
221 :    
222 :     return ( $file, $file, 0 ) if ( ref( $file ) eq "GLOB" );
223 :    
224 :     # Null string or undef
225 :    
226 :     return ( \*STDIN, "", 0 ) if ( ! defined( $file ) || ( $file eq "" ) );
227 :    
228 :     # File name
229 :    
230 :     if ( ! ref( $file ) )
231 :     {
232 :     my $fh;
233 :     -f $file or die "Could not find input file \"$file\"\n";
234 :     open( $fh, "<$file" ) || die "Could not open \"$file\" for input\n";
235 :     return ( $fh, $file, 1 );
236 :     }
237 :    
238 :     # Some other kind of reference; return the unused value
239 :    
240 :     return ( \*STDIN, undef, 0, $file );
241 :     }
242 :    
243 :    
244 :     #-----------------------------------------------------------------------------
245 :     # Read fasta sequences from a filehandle (legacy interface; use read_fasta)
246 : efrank 1.1 # Save the contents in a list of refs to arrays: (id, description, seq)
247 :     #
248 : overbeek 1.4 # @seq_entries = read_fasta_seqs( \*FILEHANDLE )
249 :     #-----------------------------------------------------------------------------
250 :     sub read_fasta_seqs { read_fasta( @_ ) }
251 :    
252 :    
253 : efrank 1.1 #-----------------------------------------------------------------------------
254 : overbeek 1.4 # Read fasta sequences.
255 :     # Save the contents in a list of refs to arrays: (id, description, seq)
256 :     #
257 :     # @seq_entries = read_fasta( ) # STDIN
258 :     # \@seq_entries = read_fasta( ) # STDIN
259 :     # @seq_entries = read_fasta( \*FILEHANDLE )
260 :     # \@seq_entries = read_fasta( \*FILEHANDLE )
261 :     # @seq_entries = read_fasta( $filename )
262 :     # \@seq_entries = read_fasta( $filename )
263 :     #-----------------------------------------------------------------------------
264 :     sub read_fasta {
265 :     my ( $fh, $name, $close, $unused ) = input_filehandle( $_[0] );
266 :     $unused && die "Bad reference type (" . ref( $unused ) . ") passed to read_fasta\n";
267 : efrank 1.1
268 :     my @seqs = ();
269 :     my ($id, $desc, $seq) = ("", "", "");
270 :    
271 : overbeek 1.4 while ( <$fh> ) {
272 : efrank 1.1 chomp;
273 :     if (/^>\s*(\S+)(\s+(.*))?$/) { # new id
274 :     if ($id && $seq) { push @seqs, [ $id, $desc, $seq ] }
275 :     ($id, $desc, $seq) = ($1, $3 ? $3 : "", "");
276 :     }
277 :     else {
278 : golsen 1.2 tr/ 0-9//d;
279 : efrank 1.1 $seq .= $_ ;
280 :     }
281 :     }
282 : overbeek 1.4 close( $fh ) if $close;
283 : efrank 1.1
284 : overbeek 1.4 if ( $id && $seq ) { push @seqs, [ $id, $desc, $seq ] }
285 :     return wantarray ? @seqs : \@seqs;
286 : efrank 1.1 }
287 :    
288 :    
289 :     #-----------------------------------------------------------------------------
290 :     # Read one fasta sequence at a time from a file.
291 :     # Return the contents as an array: (id, description, seq)
292 :     #
293 : overbeek 1.4 # @seq_entry = read_next_fasta_seq( \*FILEHANDLE )
294 : efrank 1.1 #-----------------------------------------------------------------------------
295 :     # Reading always overshoots, so save next id and description
296 :    
297 : golsen 1.2 { # Use bare block to scope the header hash
298 :    
299 :     my %next_header;
300 :    
301 :     sub read_next_fasta_seq {
302 :     my $fh = shift;
303 :     my ( $id, $desc );
304 : efrank 1.1
305 : golsen 1.2 if ( defined( $next_header{$fh} ) ) {
306 :     ( $id, $desc ) = parse_fasta_title( $next_header{$fh} );
307 : efrank 1.1 }
308 :     else {
309 : golsen 1.2 $next_header{$fh} = "";
310 :     ( $id, $desc ) = ( undef, "" );
311 :     }
312 :     my $seq = "";
313 :    
314 :     while ( <$fh> ) {
315 :     chomp;
316 :     if ( /^>/ ) { # new id
317 :     $next_header{$fh} = $_;
318 : overbeek 1.4 if ( defined($id) && $seq )
319 :     {
320 :     return wantarray ? ($id, $desc, $seq) : [$id, $desc, $seq]
321 :     }
322 : golsen 1.2 ( $id, $desc ) = parse_fasta_title( $next_header{$fh} );
323 :     $seq = "";
324 :     }
325 :     else {
326 :     tr/ 0-9//d;
327 :     $seq .= $_ ;
328 :     }
329 : efrank 1.1 }
330 :    
331 : golsen 1.2 # Done with file, delete "next header"
332 : efrank 1.1
333 : golsen 1.2 delete $next_header{$fh};
334 : overbeek 1.4 return ( defined($id) && $seq ) ? ( wantarray ? ($id, $desc, $seq)
335 :     : [$id, $desc, $seq]
336 :     )
337 :     : () ;
338 : golsen 1.2 }
339 : efrank 1.1 }
340 :    
341 :    
342 :     #-----------------------------------------------------------------------------
343 : overbeek 1.4 # Read a clustal alignment from a file.
344 :     # Save the contents in a list of refs to arrays: (id, description, seq)
345 :     #
346 :     # @seq_entries = read_clustal_file( $filename )
347 :     #-----------------------------------------------------------------------------
348 :     sub read_clustal_file { read_clustal( @_ ) }
349 :    
350 :    
351 :     #-----------------------------------------------------------------------------
352 :     # Read a clustal alignment.
353 :     # Save the contents in a list of refs to arrays: (id, description, seq)
354 :     #
355 :     # @seq_entries = read_clustal( ) # STDIN
356 :     # @seq_entries = read_clustal( \*FILEHANDLE )
357 :     # @seq_entries = read_clustal( $filename )
358 :     #-----------------------------------------------------------------------------
359 :     sub read_clustal {
360 :     my ( $fh, undef, $close, $unused ) = input_filehandle( shift );
361 :     $unused && die "Bad reference type (" . ref( $unused ) . ") passed to read_clustal_file\n";
362 :    
363 :     my ( %seq, @ids, $line );
364 :     while ( defined( $line = <$fh> ) )
365 :     {
366 :     ( $line =~ /^[A-Za-z0-9]/ ) or next;
367 :     chomp $line;
368 :     my @flds = split /\s+/, $line;
369 :     if ( @flds == 2 )
370 :     {
371 :     $seq{ $flds[0] } or push @ids, $flds[0];
372 :     push @{ $seq{ $flds[0] } }, $flds[1];
373 :     }
374 :     }
375 :     close( $fh ) if $close;
376 :    
377 :     map { [ $_, "", join( "", @{$seq{$_}} ) ] } @ids;
378 :     }
379 :    
380 :    
381 :     #-----------------------------------------------------------------------------
382 : efrank 1.1 # Parse a fasta file header to id and definition parts
383 :     #
384 :     # ($id, $def) = parse_fasta_title( $title )
385 :     # ($id, $def) = split_fasta_title( $title )
386 :     #-----------------------------------------------------------------------------
387 :     sub parse_fasta_title {
388 :     my $title = shift;
389 :     chomp;
390 :     if ($title =~ /^>?\s*(\S+)(:?\s+(.*\S)\s*)?$/) {
391 :     return ($1, $3 ? $3 : "");
392 :     }
393 : golsen 1.2 elsif ($title =~ /^>/) {
394 :     return ("", "");
395 :     }
396 : efrank 1.1 else {
397 : golsen 1.2 return (undef, "");
398 : efrank 1.1 }
399 :     }
400 :    
401 :     sub split_fasta_title {
402 :     parse_fasta_title ( shift );
403 :     }
404 :    
405 :    
406 :     #-----------------------------------------------------------------------------
407 : overbeek 1.4 # Helper function for defining an output filehandle:
408 :     # filehandle is passed through
409 :     # string is taken as file name to be openend
410 :     # undef or "" defaults to STDOUT
411 :     #
412 :     # ( \*FH, $name, $close [, $file] ) = output_filehandle( $file );
413 : efrank 1.1 #
414 :     #-----------------------------------------------------------------------------
415 : overbeek 1.4 sub output_filehandle
416 :     {
417 :     my $file = shift;
418 :    
419 :     # FILEHANDLE
420 :    
421 :     return ( $file, $file, 0 ) if ( ref( $file ) eq "GLOB" );
422 :    
423 :     # Null string or undef
424 :    
425 :     return ( \*STDOUT, "", 0 ) if ( ! defined( $file ) || ( $file eq "" ) );
426 :    
427 :     # File name
428 :    
429 :     if ( ! ref( $file ) )
430 :     {
431 :     my $fh;
432 :     open( $fh, ">$file" ) || die "Could not open output $file\n";
433 :     return ( $fh, $file, 1 );
434 :     }
435 :    
436 :     # Some other kind of reference; return the unused value
437 :    
438 :     return ( \*STDOUT, undef, 0, $file );
439 :     }
440 :    
441 :    
442 :     #-----------------------------------------------------------------------------
443 :     # Legacy function for printing fasta sequence set:
444 :     #
445 :     # print_seq_list_as_fasta( \*FILEHANDLE, @seq_entry_list );
446 :     #-----------------------------------------------------------------------------
447 :     sub print_seq_list_as_fasta { print_alignment_as_fasta( @_ ) }
448 :    
449 :    
450 :     #-----------------------------------------------------------------------------
451 :     # Print list of sequence entries in fasta format.
452 :     # Missing, undef or "" filename defaults to STDOUT.
453 :     #
454 :     # print_alignment_as_fasta( @seq_entry_list ); # STDOUT
455 :     # print_alignment_as_fasta( \@seq_entry_list ); # STDOUT
456 :     # print_alignment_as_fasta( \*FILEHANDLE, @seq_entry_list );
457 :     # print_alignment_as_fasta( \*FILEHANDLE, \@seq_entry_list );
458 :     # print_alignment_as_fasta( $filename, @seq_entry_list );
459 :     # print_alignment_as_fasta( $filename, \@seq_entry_list );
460 :     #-----------------------------------------------------------------------------
461 :     sub print_alignment_as_fasta {
462 :     my ( $fh, undef, $close, $unused ) = output_filehandle( shift );
463 :     ( unshift @_, $unused ) if $unused;
464 :    
465 : overbeek 1.8 ( ref( $_[0] ) eq "ARRAY" ) or confess "Bad sequence entry passed to print_alignment_as_fasta\n";
466 : overbeek 1.4
467 :     # Expand the sequence entry list if necessary:
468 :    
469 :     if ( ref( $_[0]->[0] ) eq "ARRAY" ) { @_ = @{ $_[0] } }
470 :    
471 :     foreach my $seq_ptr ( @_ ) { print_seq_as_fasta( $fh, @$seq_ptr ) }
472 :    
473 :     close( $fh ) if $close;
474 :     }
475 :    
476 :    
477 :     #-----------------------------------------------------------------------------
478 :     # Print list of sequence entries in phylip format.
479 :     # Missing, undef or "" filename defaults to STDOUT.
480 :     #
481 :     # print_alignment_as_phylip( @seq_entry_list ); # STDOUT
482 :     # print_alignment_as_phylip( \@seq_entry_list ); # STDOUT
483 :     # print_alignment_as_phylip( \*FILEHANDLE, @seq_entry_list );
484 :     # print_alignment_as_phylip( \*FILEHANDLE, \@seq_entry_list );
485 :     # print_alignment_as_phylip( $filename, @seq_entry_list );
486 :     # print_alignment_as_phylip( $filename, \@seq_entry_list );
487 :     #-----------------------------------------------------------------------------
488 :     sub print_alignment_as_phylip {
489 :     my ( $fh, undef, $close, $unused ) = output_filehandle( shift );
490 :     ( unshift @_, $unused ) if $unused;
491 :    
492 :     ( ref( $_[0] ) eq "ARRAY" ) or die die "Bad sequence entry passed to print_alignment_as_phylip\n";
493 :    
494 :     my @seq_list = ( ref( $_[0]->[0] ) eq "ARRAY" ) ? @{ $_[0] } : @_;
495 :    
496 :     my ( %id2, %used );
497 :     my $maxlen = 0;
498 :     foreach ( @seq_list )
499 :     {
500 :     my ( $id, undef, $seq ) = @$_;
501 :    
502 :     # Need a name that is unique within 10 characters
503 :    
504 :     my $id2 = substr( $id, 0, 10 );
505 :     $id2 =~ s/_/ /g; # PHYLIP sequence files accept spaces
506 :     my $n = "0";
507 :     while ( $used{ $id2 } )
508 :     {
509 :     $n++;
510 :     $id2 = substr( $id, 0, 10 - length( $n ) ) . $n;
511 :     }
512 :     $used{ $id2 } = 1;
513 :     $id2{ $id } = $id2;
514 :    
515 :     # Prepare to pad sequences (should not be necessary, but ...)
516 :    
517 :     my $len = length( $seq );
518 :     $maxlen = $len if ( $len > $maxlen );
519 :     }
520 : efrank 1.1
521 : overbeek 1.4 my $nseq = @seq_list;
522 :     print $fh "$nseq $maxlen\n";
523 :     foreach ( @seq_list )
524 :     {
525 :     my ( $id, undef, $seq ) = @$_;
526 :     my $len = length( $seq );
527 :     printf $fh "%-10s %s%s\n", $id2{ $id },
528 :     $seq,
529 :     $len<$maxlen ? ("?" x ($maxlen-$len)) : "";
530 : efrank 1.1 }
531 : overbeek 1.4
532 :     close( $fh ) if $close;
533 :     }
534 :    
535 :    
536 :     #-----------------------------------------------------------------------------
537 :     # Print list of sequence entries in nexus format.
538 :     # Missing, undef or "" filename defaults to STDOUT.
539 :     #
540 :     # print_alignment_as_nexus( [ \%label_hash, ] @seq_entry_list );
541 :     # print_alignment_as_nexus( [ \%label_hash, ] \@seq_entry_list );
542 :     # print_alignment_as_nexus( \*FILEHANDLE, [ \%label_hash, ] @seq_entry_list );
543 :     # print_alignment_as_nexus( \*FILEHANDLE, [ \%label_hash, ] \@seq_entry_list );
544 :     # print_alignment_as_nexus( $filename, [ \%label_hash, ] @seq_entry_list );
545 :     # print_alignment_as_nexus( $filename, [ \%label_hash, ] \@seq_entry_list );
546 :     #-----------------------------------------------------------------------------
547 :     sub print_alignment_as_nexus {
548 :     my ( $fh, undef, $close, $unused ) = output_filehandle( shift );
549 :     ( unshift @_, $unused ) if $unused;
550 :    
551 :     my $lbls = ( ref( $_[0] ) eq "HASH" ) ? shift : undef;
552 :    
553 :     ( ref( $_[0] ) eq "ARRAY" ) or die "Bad sequence entry passed to print_alignment_as_nexus\n";
554 :    
555 :     my @seq_list = ( ref( $_[0]->[0] ) eq "ARRAY" ) ? @{ $_[0] } : @_;
556 :    
557 :     my %id2;
558 :     my ( $maxidlen, $maxseqlen ) = ( 0, 0 );
559 :     my ( $n1, $n2, $nt, $nu ) = ( 0, 0, 0, 0 );
560 :     foreach ( @seq_list )
561 :     {
562 :     my ( $id, undef, $seq ) = @$_;
563 :     my $id2 = $lbls ? ( $lbls->{ $id } || $id ) : $id;
564 :     if ( $id2 !~ /^[-+.0-9A-Za-z~_|]+$/ )
565 :     {
566 :     $id2 =~ s/'/''/g;
567 :     $id2 = qq('$id2');
568 :     }
569 :     $id2{ $id } = $id2;
570 :     my $idlen = length( $id2 );
571 :     $maxidlen = $idlen if ( $idlen > $maxidlen );
572 :    
573 :     my $seqlen = length( $seq );
574 :     $maxseqlen = $seqlen if ( $seqlen > $maxseqlen );
575 :    
576 :     $nt += $seq =~ tr/Tt//d;
577 :     $nu += $seq =~ tr/Uu//d;
578 :     $n1 += $seq =~ tr/ACGNacgn//d;
579 :     $n2 += $seq =~ tr/A-Za-z//d;
580 :     }
581 :    
582 :     my $nseq = @seq_list;
583 :     my $type = ( $n1 < 2 * $n2 ) ? 'protein' : ($nt>$nu) ? 'DNA' : 'RNA';
584 :    
585 :     print $fh <<"END_HEAD";
586 :     #NEXUS
587 :    
588 :     BEGIN Data;
589 :     Dimensions
590 :     NTax=$nseq
591 :     NChar=$maxseqlen
592 :     ;
593 :     Format
594 :     DataType=$type
595 :     Gap=-
596 :     Missing=?
597 :     ;
598 :     Matrix
599 :    
600 :     END_HEAD
601 :    
602 :     foreach ( @seq_list )
603 :     {
604 :     my ( $id, undef, $seq ) = @$_;
605 :     my $len = length( $seq );
606 :     printf $fh "%-${maxidlen}s %s%s\n",
607 :     $id2{ $id },
608 :     $seq,
609 :     $len<$maxseqlen ? ("?" x ($maxseqlen-$len)) : "";
610 :     }
611 :    
612 :     print $fh <<"END_TAIL";
613 :     ;
614 :     END;
615 :     END_TAIL
616 :    
617 :     close( $fh ) if $close;
618 : efrank 1.1 }
619 :    
620 :    
621 :     #-----------------------------------------------------------------------------
622 :     # Print one sequence in fasta format to an open file
623 :     #
624 : overbeek 1.4 # print_seq_as_fasta( \*FILEHANDLE, $id, $desc, $seq );
625 :     # print_seq_as_fasta( \*FILEHANDLE, @seq_entry );
626 : efrank 1.1 #-----------------------------------------------------------------------------
627 :     sub print_seq_as_fasta {
628 :     my $fh = shift;
629 :     my ($id, $desc, $seq) = @_;
630 :    
631 :     printf $fh ($desc) ? ">$id $desc\n" : ">$id\n";
632 :     my $len = length($seq);
633 :     for (my $i = 0; $i < $len; $i += 60) {
634 :     print $fh substr($seq, $i, 60) . "\n";
635 :     }
636 :     }
637 :    
638 :    
639 :     #-----------------------------------------------------------------------------
640 :     # Print one sequence in GenBank flat file format:
641 :     #
642 : overbeek 1.4 # print_gb_locus( \*FILEHANDLE, $locus, $def, $accession, $seq )
643 : efrank 1.1 #-----------------------------------------------------------------------------
644 :     sub print_gb_locus {
645 :     my ($fh, $loc, $def, $acc, $seq) = @_;
646 :     my ($len, $i, $imax);
647 :     my $istep = 10;
648 :    
649 :     $len = length($seq);
650 :     printf $fh "LOCUS %-10s%7d bp\n", substr($loc,0,10), $len;
651 :     print $fh "DEFINITION " . substr(wrap_text($def,80,12), 12) . "\n";
652 :     if ($acc) { print $fh "ACCESSION $acc\n" }
653 :     print $fh "ORIGIN\n";
654 :    
655 :     for ($i = 1; $i <= $len; ) {
656 :     printf $fh "%9d", $i;
657 :     $imax = $i + 59; if ($imax > $len) { $imax = $len }
658 :     for ( ; $i <= $imax; $i += $istep) {
659 :     print $fh " " . substr($seq, $i-1, $istep);
660 :     }
661 :     print $fh "\n";
662 :     }
663 :     print $fh "//\n";
664 :     }
665 :    
666 :    
667 :     #-----------------------------------------------------------------------------
668 : golsen 1.7 # Return a string with text wrapped to defined line lengths:
669 :     #
670 :     # $wrapped_text = wrap_text( $str ) # default len = 80
671 :     # $wrapped_text = wrap_text( $str, $len ) # default ind = 0
672 :     # $wrapped_text = wrap_text( $str, $len, $indent ) # default ind_n = ind
673 :     # $wrapped_text = wrap_text( $str, $len, $indent_1, $indent_n )
674 :     #-----------------------------------------------------------------------------
675 :     sub wrap_text {
676 :     my ($str, $len, $ind, $indn) = @_;
677 :    
678 :     defined($str) || die "wrap_text called without a string\n";
679 :     defined($len) || ($len = 80);
680 :     defined($ind) || ($ind = 0);
681 :     ($ind < $len) || die "wrap error: indent greater than line length\n";
682 :     defined($indn) || ($indn = $ind);
683 :     ($indn < $len) || die "wrap error: indent_n greater than line length\n";
684 :    
685 :     $str =~ s/\s+$//;
686 :     $str =~ s/^\s+//;
687 :     my ($maxchr, $maxchr1);
688 :     my (@lines) = ();
689 :    
690 :     while ($str) {
691 :     $maxchr1 = ($maxchr = $len - $ind) - 1;
692 :     if ($maxchr >= length($str)) {
693 :     push @lines, (" " x $ind) . $str;
694 :     last;
695 :     }
696 :     elsif ($str =~ /^(.{0,$maxchr1}\S)\s+(\S.*)$/) { # no expr in {}
697 :     push @lines, (" " x $ind) . $1;
698 :     $str = $2;
699 :     }
700 :     elsif ($str =~ /^(.{0,$maxchr1}-)(.*)$/) {
701 :     push @lines, (" " x $ind) . $1;
702 :     $str = $2;
703 :     }
704 :     else {
705 :     push @lines, (" " x $ind) . substr($str, 0, $maxchr);
706 :     $str = substr($str, $maxchr);
707 :     }
708 :     $ind = $indn;
709 :     }
710 :    
711 :     return join("\n", @lines);
712 :     }
713 :    
714 :    
715 :     #-----------------------------------------------------------------------------
716 : efrank 1.1 # Build an index from seq_id to pointer to sequence entry: (id, desc, seq)
717 :     #
718 : overbeek 1.4 # my \%seq_ind = index_seq_list( @seq_list );
719 :     # my \%seq_ind = index_seq_list( \@seq_list );
720 : efrank 1.1 #
721 :     # Usage example:
722 :     #
723 : overbeek 1.4 # my @seq_list = read_fasta_seqs(\*STDIN); # list of pointers to entries
724 :     # my \%seq_ind = index_seq_list(@seq_list); # hash from names to pointers
725 :     # my @chosen_seq = @{%seq_ind{"contig1"}}; # extract one entry
726 : efrank 1.1 #
727 :     #-----------------------------------------------------------------------------
728 :     sub index_seq_list {
729 : overbeek 1.4 ( ref( $_[0] ) ne 'ARRAY' ) ? {}
730 :     : ( ref( $_[0]->[0] ) ne 'ARRAY' ) ? { map { $_->[0] => $_ } @_ }
731 :     : { map { $_->[0] => $_ } @{ $_[0] } }
732 : efrank 1.1 }
733 :    
734 :    
735 :     #-----------------------------------------------------------------------------
736 :     # Three routines to access all or part of sequence entry by id:
737 :     #
738 : overbeek 1.4 # @seq_entry = seq_entry_by_id( \%seq_index, $seq_id );
739 :     # \@seq_entry = seq_entry_by_id( \%seq_index, $seq_id );
740 :     # $seq_desc = seq_desc_by_id( \%seq_index, $seq_id );
741 :     # $seq = seq_data_by_id( \%seq_index, $seq_id );
742 : efrank 1.1 #
743 :     #-----------------------------------------------------------------------------
744 :     sub seq_entry_by_id {
745 :     (my $ind_ref = shift) || die "No index supplied to seq_entry_by_id\n";
746 :     (my $id = shift) || die "No id supplied to seq_entry_by_id\n";
747 : overbeek 1.4 return wantarray ? @{ $ind_ref->{$id} } : $ind_ref->{$id};
748 : efrank 1.1 }
749 :    
750 :    
751 :     sub seq_desc_by_id {
752 :     (my $ind_ref = shift) || die "No index supplied to seq_desc_by_id\n";
753 :     (my $id = shift) || die "No id supplied to seq_desc_by_id\n";
754 :     return ${ $ind_ref->{$id} }[1];
755 :     }
756 :    
757 :    
758 :     sub seq_data_by_id {
759 :     (my $ind_ref = shift) || die "No index supplied to seq_data_by_id\n";
760 :     (my $id = shift) || die "No id supplied to seq_data_by_id\n";
761 :     return ${ $ind_ref->{$id} }[2];
762 :     }
763 :    
764 : golsen 1.5 #-----------------------------------------------------------------------------
765 :     # Remove columns of alignment gaps from sequences:
766 :     #
767 : golsen 1.6 # @packed_seqs = pack_alignment( @seqs )
768 :     # @packed_seqs = pack_alignment( \@seqs )
769 :     # \@packed_seqs = pack_alignment( @seqs )
770 :     # \@packed_seqs = pack_alignment( \@seqs )
771 : golsen 1.5 #
772 :     #-----------------------------------------------------------------------------
773 :    
774 :     sub pack_alignment
775 :     {
776 :     my @seqs = ( ref( $_[0] ) eq 'ARRAY' and ref( $_[0]->[0] ) eq 'ARRAY' ) ? @{$_[0] } : @_;
777 :     @seqs or return wantarray ? () : [];
778 :    
779 :     my $mask = pack_mask( $seqs[0]->[2] );
780 :     foreach ( @seqs[ 1 .. (@seqs-1) ] )
781 :     {
782 :     $mask |= pack_mask( $_->[2] );
783 :     }
784 :    
785 :     my $seq;
786 :     my @seqs2 = map { $seq = $_->[2] & $mask;
787 :     $seq =~ tr/\000//d;
788 :     [ $_->[0], $_->[1], $seq ]
789 :     }
790 :     @seqs;
791 :    
792 :     return wantarray ? @seqs2 : \@seqs2;
793 :     }
794 :    
795 :     sub pack_mask
796 :     {
797 :     my $mask = shift;
798 :     $mask =~ tr/-/\000/;
799 :     $mask =~ tr/\000/\377/c;
800 :     return $mask;
801 :     }
802 : efrank 1.1
803 :     #-----------------------------------------------------------------------------
804 :     # Some simple sequence manipulations:
805 :     #
806 :     # @entry = subseq_DNA_entry( @seq_entry, $from, $to [, $fix_id] );
807 :     # @entry = subseq_RNA_entry( @seq_entry, $from, $to [, $fix_id] );
808 :     # @entry = complement_DNA_entry( @seq_entry [, $fix_id] );
809 :     # @entry = complement_RNA_entry( @seq_entry [, $fix_id] );
810 :     # $DNAseq = complement_DNA_seq( $NA_seq );
811 :     # $RNAseq = complement_RNA_seq( $NA_seq );
812 :     # $DNAseq = to_DNA_seq( $NA_seq );
813 :     # $RNAseq = to_RNA_seq( $NA_seq );
814 :     #
815 :     #-----------------------------------------------------------------------------
816 :    
817 :     sub subseq_DNA_entry {
818 :     my ($id, $desc, @rest) = @_;
819 :     wantarray || die "subseq_DNA_entry requires array context\n";
820 :    
821 :     my $seq;
822 :     ($id, $seq) = subseq_nt(1, $id, @rest); # 1 is for DNA, not RNA
823 :     return ($id, $desc, $seq);
824 :     }
825 :    
826 :    
827 :     sub subseq_RNA_entry {
828 :     my ($id, $desc, @rest) = @_;
829 :     wantarray || die "subseq_RNA_entry requires array context\n";
830 :    
831 :     my $seq;
832 :     ($id, $seq) = subseq_nt(0, $id, @rest); # 0 is for not DNA, i.e., RNA
833 :     return ($id, $desc, $seq);
834 :     }
835 :    
836 :    
837 :     sub subseq_nt {
838 :     my ($DNA, $id, $seq, $from, $to, $fix_id) = @_;
839 :     $fix_id ||= 0; # fix undef value
840 :    
841 :     my $len = length($seq);
842 :     if ( ( $from eq '$' ) || ( $from eq "" ) ) { $from = $len }
843 :     if (! $to || ( $to eq '$' ) || ( $to eq "" ) ) { $to = $len }
844 :    
845 :     my $left = ( $from < $to ) ? $from : $to;
846 :     my $right = ( $from < $to ) ? $to : $from;
847 :     if ( ( $right < 1 ) || ( $left > $len ) ) { return ($id, "") }
848 :     if ( $right > $len ) { $right = $len }
849 :     if ( $left < 1 ) { $left = 1 }
850 :    
851 :     $seq = substr($seq, $left-1, $right-$left+1);
852 :     if ( $from > $to ) {
853 :     $seq = reverse $seq;
854 :     if ( $DNA ) {
855 :     $seq =~ tr[ACGTUKMRSWYBDHVNacgtukmrswybdhvn]
856 :     [TGCAAMKYSWRVHDBNtgcaamkyswrvhdbn];
857 :     }
858 :     else {
859 :     $seq =~ tr[ACGTUKMRSWYBDHVNacgtukmrswybdhvn]
860 :     [UGCAAMKYSWRVHDBNugcaamkyswrvhdbn];
861 :     }
862 :     }
863 :    
864 :     if ( $fix_id ) {
865 : golsen 1.2 if ( ( $id =~ s/_(\d+)_(\d+)$// )
866 : efrank 1.1 && ( abs($2-$1)+1 == $len ) ) {
867 :     if ( $1 <= $2 ) { $from += $1 - 1; $to += $1 - 1 }
868 :     else { $from = $1 + 1 - $from; $to = $1 + 1 - $to }
869 :     }
870 :     $id .= "_" . $from . "_" . $to;
871 :     }
872 :    
873 :     return ($id, $seq);
874 :     }
875 :    
876 :    
877 : golsen 1.9 sub DNA_subseq
878 :     {
879 :     my ( $seq, $from, $to ) = @_;
880 :    
881 :     my $len = ref( $seq ) eq 'SCALAR' ? length( $$seq )
882 :     : length( $seq );
883 :     if ( ( $from eq '$' ) || ( $from eq "" ) ) { $from = $len }
884 :     if ( ( $to eq '$' ) || ( ! $to ) ) { $to = $len }
885 :    
886 :     my $left = ( $from < $to ) ? $from : $to;
887 :     my $right = ( $from < $to ) ? $to : $from;
888 :     if ( ( $right < 1 ) || ( $left > $len ) ) { return "" }
889 :     if ( $right > $len ) { $right = $len }
890 :     if ( $left < 1 ) { $left = 1 }
891 :    
892 :     my $subseq = ref( $seq ) eq 'SCALAR' ? substr( $$seq, $left-1, $right-$left+1 )
893 :     : substr( $seq, $left-1, $right-$left+1 );
894 :    
895 :     if ( $from > $to )
896 :     {
897 :     $subseq = reverse $subseq;
898 :     $subseq =~ tr[ACGTUKMRSWYBDHVNacgtukmrswybdhvn]
899 :     [TGCAAMKYSWRVHDBNtgcaamkyswrvhdbn];
900 :     }
901 :    
902 :     $subseq
903 :     }
904 :    
905 :    
906 :     sub RNA_subseq
907 :     {
908 :     my ( $seq, $from, $to ) = @_;
909 :    
910 :     my $len = ref( $seq ) eq 'SCALAR' ? length( $$seq )
911 :     : length( $seq );
912 :     if ( ( $from eq '$' ) || ( $from eq "" ) ) { $from = $len }
913 :     if ( ( $to eq '$' ) || ( ! $to ) ) { $to = $len }
914 :    
915 :     my $left = ( $from < $to ) ? $from : $to;
916 :     my $right = ( $from < $to ) ? $to : $from;
917 :     if ( ( $right < 1 ) || ( $left > $len ) ) { return "" }
918 :     if ( $right > $len ) { $right = $len }
919 :     if ( $left < 1 ) { $left = 1 }
920 :    
921 :     my $subseq = ref( $seq ) eq 'SCALAR' ? substr( $$seq, $left-1, $right-$left+1 )
922 :     : substr( $seq, $left-1, $right-$left+1 );
923 :    
924 :     if ( $from > $to )
925 :     {
926 :     $subseq = reverse $subseq;
927 :     $subseq =~ tr[ACGTUKMRSWYBDHVNacgtukmrswybdhvn]
928 :     [UGCAAMKYSWRVHDBNugcaamkyswrvhdbn];
929 :     }
930 :    
931 :     $subseq
932 :     }
933 :    
934 :    
935 : efrank 1.1 sub complement_DNA_entry {
936 :     my ($id, $desc, $seq, $fix_id) = @_;
937 :     $fix_id ||= 0; # fix undef values
938 :    
939 :     wantarray || die "complement_DNA_entry requires array context\n";
940 :     $seq = reverse $seq;
941 :     $seq =~ tr[ACGTUKMRSWYBDHVNacgtukmrswybdhvn]
942 :     [TGCAAMKYSWRVHDBNtgcaamkyswrvhdbn];
943 :     if ($fix_id) {
944 : golsen 1.2 if ($id =~ s/_(\d+)_(\d+)$//) {
945 : efrank 1.1 $id .= "_" . $2 . "_" . $1;
946 :     }
947 :     else {
948 :     $id .= "_" . length($seq) . "_1";
949 :     }
950 :     }
951 :    
952 :     return ($id, $desc, $seq);
953 :     }
954 :    
955 :    
956 :     sub complement_RNA_entry {
957 :     my ($id, $desc, $seq, $fix_id) = @_;
958 :     $fix_id ||= 0; # fix undef values
959 :    
960 :     wantarray || die "complement_DNA_entry requires array context\n";
961 :     $seq = reverse $seq;
962 :     $seq =~ tr[ACGTUKMRSWYBDHVNacgtukmrswybdhvn]
963 :     [UGCAAMKYSWRVHDBNugcaamkyswrvhdbn];
964 :     if ($fix_id) {
965 : golsen 1.2 if ($id =~ s/_(\d+)_(\d+)$//) {
966 : efrank 1.1 $id .= "_" . $2 . "_" . $1;
967 :     }
968 :     else {
969 :     $id .= "_" . length($seq) . "_1";
970 :     }
971 :     }
972 :    
973 :     return ($id, $desc, $seq);
974 :     }
975 :    
976 :    
977 :     sub complement_DNA_seq {
978 :     my $seq = reverse shift;
979 :     $seq =~ tr[ACGTUKMRSWYBDHVNacgtukmrswybdhvn]
980 :     [TGCAAMKYSWRVHDBNtgcaamkyswrvhdbn];
981 :     return $seq;
982 :     }
983 :    
984 :    
985 :     sub complement_RNA_seq {
986 :     my $seq = reverse shift;
987 :     $seq =~ tr[ACGTUKMRSWYBDHVNacgtukmrswybdhvn]
988 :     [UGCAAMKYSWRVHDBNugcaamkyswrvhdbn];
989 :     return $seq;
990 :     }
991 :    
992 :    
993 :     sub to_DNA_seq {
994 :     my $seq = shift;
995 :     $seq =~ tr/Uu/Tt/;
996 :     return $seq;
997 :     }
998 :    
999 :    
1000 :     sub to_RNA_seq {
1001 :     my $seq = shift;
1002 :     $seq =~ tr/Tt/Uu/;
1003 :     return $seq;
1004 :     }
1005 :    
1006 :    
1007 : golsen 1.2 sub pack_seq {
1008 :     my $seq = shift;
1009 :     $seq =~ tr/A-Za-z//cd;
1010 :     return $seq;
1011 :     }
1012 :    
1013 :    
1014 : efrank 1.1 sub clean_ae_sequence {
1015 :     $_ = shift;
1016 :     $_ = to7bit($_);
1017 :     s/[+]/1/g;
1018 :     s/[^0-9A-IK-NP-Za-ik-np-z~.-]/-/g;
1019 :     return $_;
1020 :     }
1021 :    
1022 :    
1023 :     sub to7bit {
1024 :     $_ = shift;
1025 :     my ($o, $c);
1026 :     while (/\\([0-3][0-7][0-7])/) {
1027 :     $o = oct($1) % 128;
1028 :     $c = sprintf("%c", $o);
1029 :     s/\\$1/$c/g;
1030 :     }
1031 :     return $_;
1032 :     }
1033 :    
1034 :    
1035 :     sub to8bit {
1036 :     $_ = shift;
1037 :     my ($o, $c);
1038 :     while (/\\([0-3][0-7][0-7])/) {
1039 :     $o = oct($1);
1040 :     $c = sprintf("%c", $o);
1041 :     s/\\$1/$c/g;
1042 :     }
1043 :     return $_;
1044 :     }
1045 :    
1046 :    
1047 :    
1048 :     #-----------------------------------------------------------------------------
1049 :     # Translate nucleotides to one letter protein:
1050 :     #
1051 : golsen 1.10 # $seq = translate_seq( $seq [, $met_start] )
1052 :     # $aa = translate_codon( $triplet )
1053 :     # $aa = translate_DNA_codon( $triplet ) # Does not rely on DNA
1054 :     # $aa = translate_uc_DNA_codon( $triplet ) # Does not rely on uc or DNA
1055 : efrank 1.1 #
1056 :     # User-supplied genetic code must be upper case index and match the
1057 :     # DNA versus RNA type of sequence
1058 :     #
1059 : golsen 1.10 # $seq = translate_seq_with_user_code( $seq, $gen_code_hash [, $met_start] )
1060 : efrank 1.1 #
1061 :     #-----------------------------------------------------------------------------
1062 :    
1063 : golsen 1.2 @aa_1_letter_order = qw( A C D E F G H I K L M N P Q R S T V W Y ); # Alpha by 1 letter
1064 :     @aa_3_letter_order = qw( A R N D C Q E G H I L K M F P S T W Y V ); # PAM matrix order
1065 :     @aa_n_codon_order = qw( L R S A G P T V I C D E F H K N Q Y M W );
1066 :    
1067 :     %genetic_code = (
1068 :    
1069 :     # DNA version
1070 :    
1071 : golsen 1.10 TTT => 'F', TCT => 'S', TAT => 'Y', TGT => 'C',
1072 :     TTC => 'F', TCC => 'S', TAC => 'Y', TGC => 'C',
1073 :     TTA => 'L', TCA => 'S', TAA => '*', TGA => '*',
1074 :     TTG => 'L', TCG => 'S', TAG => '*', TGG => 'W',
1075 :     CTT => 'L', CCT => 'P', CAT => 'H', CGT => 'R',
1076 :     CTC => 'L', CCC => 'P', CAC => 'H', CGC => 'R',
1077 :     CTA => 'L', CCA => 'P', CAA => 'Q', CGA => 'R',
1078 :     CTG => 'L', CCG => 'P', CAG => 'Q', CGG => 'R',
1079 :     ATT => 'I', ACT => 'T', AAT => 'N', AGT => 'S',
1080 :     ATC => 'I', ACC => 'T', AAC => 'N', AGC => 'S',
1081 :     ATA => 'I', ACA => 'T', AAA => 'K', AGA => 'R',
1082 :     ATG => 'M', ACG => 'T', AAG => 'K', AGG => 'R',
1083 :     GTT => 'V', GCT => 'A', GAT => 'D', GGT => 'G',
1084 :     GTC => 'V', GCC => 'A', GAC => 'D', GGC => 'G',
1085 :     GTA => 'V', GCA => 'A', GAA => 'E', GGA => 'G',
1086 :     GTG => 'V', GCG => 'A', GAG => 'E', GGG => 'G',
1087 : golsen 1.2
1088 : efrank 1.1 # The following ambiguous encodings are not necessary, but
1089 : golsen 1.2 # speed up the processing of some ambiguous triplets:
1090 : efrank 1.1
1091 : golsen 1.10 TTY => 'F', TCY => 'S', TAY => 'Y', TGY => 'C',
1092 :     TTR => 'L', TCR => 'S', TAR => '*',
1093 :     TCN => 'S',
1094 :     CTY => 'L', CCY => 'P', CAY => 'H', CGY => 'R',
1095 :     CTR => 'L', CCR => 'P', CAR => 'Q', CGR => 'R',
1096 :     CTN => 'L', CCN => 'P', CGN => 'R',
1097 :     ATY => 'I', ACY => 'T', AAY => 'N', AGY => 'S',
1098 :     ACR => 'T', AAR => 'K', AGR => 'R',
1099 :     ACN => 'T',
1100 :     GTY => 'V', GCY => 'A', GAY => 'D', GGY => 'G',
1101 :     GTR => 'V', GCR => 'A', GAR => 'E', GGR => 'G',
1102 :     GTN => 'V', GCN => 'A', GGN => 'G'
1103 : golsen 1.2 );
1104 :    
1105 : golsen 1.10 # Add RNA by construction:
1106 :    
1107 :     foreach ( grep { /T/ } keys %genetic_code )
1108 :     {
1109 :     my $codon = $_;
1110 :     $codon =~ s/T/U/g;
1111 :     $genetic_code{ $codon } = lc $genetic_code{ $_ }
1112 :     }
1113 : golsen 1.2
1114 :     # Add lower case by construction:
1115 :    
1116 : golsen 1.10 foreach ( keys %genetic_code )
1117 :     {
1118 : golsen 1.2 $genetic_code{ lc $_ } = lc $genetic_code{ $_ }
1119 :     }
1120 :    
1121 :    
1122 : golsen 1.9 # Construct the genetic code with selenocysteine by difference:
1123 : golsen 1.2
1124 : golsen 1.10 %genetic_code_with_U = %genetic_code;
1125 :     $genetic_code_with_U{ TGA } = 'U';
1126 :     $genetic_code_with_U{ tga } = 'u';
1127 :     $genetic_code_with_U{ UGA } = 'U';
1128 :     $genetic_code_with_U{ uga } = 'u';
1129 : golsen 1.2
1130 :    
1131 :     %amino_acid_codons_DNA = (
1132 : overbeek 1.4 L => [ qw( TTA TTG CTA CTG CTT CTC ) ],
1133 :     R => [ qw( AGA AGG CGA CGG CGT CGC ) ],
1134 :     S => [ qw( AGT AGC TCA TCG TCT TCC ) ],
1135 :     A => [ qw( GCA GCG GCT GCC ) ],
1136 :     G => [ qw( GGA GGG GGT GGC ) ],
1137 :     P => [ qw( CCA CCG CCT CCC ) ],
1138 :     T => [ qw( ACA ACG ACT ACC ) ],
1139 :     V => [ qw( GTA GTG GTT GTC ) ],
1140 :     I => [ qw( ATA ATT ATC ) ],
1141 :     C => [ qw( TGT TGC ) ],
1142 :     D => [ qw( GAT GAC ) ],
1143 :     E => [ qw( GAA GAG ) ],
1144 :     F => [ qw( TTT TTC ) ],
1145 :     H => [ qw( CAT CAC ) ],
1146 :     K => [ qw( AAA AAG ) ],
1147 :     N => [ qw( AAT AAC ) ],
1148 :     Q => [ qw( CAA CAG ) ],
1149 :     Y => [ qw( TAT TAC ) ],
1150 :     M => [ qw( ATG ) ],
1151 :     U => [ qw( TGA ) ],
1152 :     W => [ qw( TGG ) ],
1153 :    
1154 :     l => [ qw( tta ttg cta ctg ctt ctc ) ],
1155 :     r => [ qw( aga agg cga cgg cgt cgc ) ],
1156 :     s => [ qw( agt agc tca tcg tct tcc ) ],
1157 :     a => [ qw( gca gcg gct gcc ) ],
1158 :     g => [ qw( gga ggg ggt ggc ) ],
1159 :     p => [ qw( cca ccg cct ccc ) ],
1160 :     t => [ qw( aca acg act acc ) ],
1161 :     v => [ qw( gta gtg gtt gtc ) ],
1162 :     i => [ qw( ata att atc ) ],
1163 :     c => [ qw( tgt tgc ) ],
1164 :     d => [ qw( gat gac ) ],
1165 :     e => [ qw( gaa gag ) ],
1166 :     f => [ qw( ttt ttc ) ],
1167 :     h => [ qw( cat cac ) ],
1168 :     k => [ qw( aaa aag ) ],
1169 :     n => [ qw( aat aac ) ],
1170 :     q => [ qw( caa cag ) ],
1171 :     y => [ qw( tat tac ) ],
1172 :     m => [ qw( atg ) ],
1173 :     u => [ qw( tga ) ],
1174 :     w => [ qw( tgg ) ],
1175 : golsen 1.2
1176 : overbeek 1.4 '*' => [ qw( TAA TAG TGA ) ]
1177 : efrank 1.1 );
1178 :    
1179 :    
1180 : golsen 1.2
1181 :     %amino_acid_codons_RNA = (
1182 : overbeek 1.4 L => [ qw( UUA UUG CUA CUG CUU CUC ) ],
1183 :     R => [ qw( AGA AGG CGA CGG CGU CGC ) ],
1184 :     S => [ qw( AGU AGC UCA UCG UCU UCC ) ],
1185 :     A => [ qw( GCA GCG GCU GCC ) ],
1186 :     G => [ qw( GGA GGG GGU GGC ) ],
1187 :     P => [ qw( CCA CCG CCU CCC ) ],
1188 :     T => [ qw( ACA ACG ACU ACC ) ],
1189 :     V => [ qw( GUA GUG GUU GUC ) ],
1190 :     B => [ qw( GAU GAC AAU AAC ) ],
1191 :     Z => [ qw( GAA GAG CAA CAG ) ],
1192 :     I => [ qw( AUA AUU AUC ) ],
1193 :     C => [ qw( UGU UGC ) ],
1194 :     D => [ qw( GAU GAC ) ],
1195 :     E => [ qw( GAA GAG ) ],
1196 :     F => [ qw( UUU UUC ) ],
1197 :     H => [ qw( CAU CAC ) ],
1198 :     K => [ qw( AAA AAG ) ],
1199 :     N => [ qw( AAU AAC ) ],
1200 :     Q => [ qw( CAA CAG ) ],
1201 :     Y => [ qw( UAU UAC ) ],
1202 :     M => [ qw( AUG ) ],
1203 :     U => [ qw( UGA ) ],
1204 :     W => [ qw( UGG ) ],
1205 :    
1206 :     l => [ qw( uua uug cua cug cuu cuc ) ],
1207 :     r => [ qw( aga agg cga cgg cgu cgc ) ],
1208 :     s => [ qw( agu agc uca ucg ucu ucc ) ],
1209 :     a => [ qw( gca gcg gcu gcc ) ],
1210 :     g => [ qw( gga ggg ggu ggc ) ],
1211 :     p => [ qw( cca ccg ccu ccc ) ],
1212 :     t => [ qw( aca acg acu acc ) ],
1213 :     v => [ qw( gua gug guu guc ) ],
1214 :     b => [ qw( gau gac aau aac ) ],
1215 :     z => [ qw( gaa gag caa cag ) ],
1216 :     i => [ qw( aua auu auc ) ],
1217 :     c => [ qw( ugu ugc ) ],
1218 :     d => [ qw( gau gac ) ],
1219 :     e => [ qw( gaa gag ) ],
1220 :     f => [ qw( uuu uuc ) ],
1221 :     h => [ qw( cau cac ) ],
1222 :     k => [ qw( aaa aag ) ],
1223 :     n => [ qw( aau aac ) ],
1224 :     q => [ qw( caa cag ) ],
1225 :     y => [ qw( uau uac ) ],
1226 :     m => [ qw( aug ) ],
1227 :     u => [ qw( uga ) ],
1228 :     w => [ qw( ugg ) ],
1229 : golsen 1.2
1230 : overbeek 1.4 '*' => [ qw( UAA UAG UGA ) ]
1231 : golsen 1.2 );
1232 :    
1233 :    
1234 :     %n_codon_for_aa = map {
1235 :     $_ => scalar @{ $amino_acid_codons_DNA{ $_ } }
1236 :     } keys %amino_acid_codons_DNA;
1237 :    
1238 :    
1239 :     %reverse_genetic_code_DNA = (
1240 : overbeek 1.4 A => "GCN", a => "gcn",
1241 :     C => "TGY", c => "tgy",
1242 :     D => "GAY", d => "gay",
1243 :     E => "GAR", e => "gar",
1244 :     F => "TTY", f => "tty",
1245 :     G => "GGN", g => "ggn",
1246 :     H => "CAY", h => "cay",
1247 :     I => "ATH", i => "ath",
1248 :     K => "AAR", k => "aar",
1249 :     L => "YTN", l => "ytn",
1250 :     M => "ATG", m => "atg",
1251 :     N => "AAY", n => "aay",
1252 :     P => "CCN", p => "ccn",
1253 :     Q => "CAR", q => "car",
1254 :     R => "MGN", r => "mgn",
1255 :     S => "WSN", s => "wsn",
1256 :     T => "ACN", t => "acn",
1257 :     U => "TGA", u => "tga",
1258 :     V => "GTN", v => "gtn",
1259 :     W => "TGG", w => "tgg",
1260 :     X => "NNN", x => "nnn",
1261 :     Y => "TAY", y => "tay",
1262 :     '*' => "TRR"
1263 : golsen 1.2 );
1264 :    
1265 :     %reverse_genetic_code_RNA = (
1266 : overbeek 1.4 A => "GCN", a => "gcn",
1267 :     C => "UGY", c => "ugy",
1268 :     D => "GAY", d => "gay",
1269 :     E => "GAR", e => "gar",
1270 :     F => "UUY", f => "uuy",
1271 :     G => "GGN", g => "ggn",
1272 :     H => "CAY", h => "cay",
1273 :     I => "AUH", i => "auh",
1274 :     K => "AAR", k => "aar",
1275 :     L => "YUN", l => "yun",
1276 :     M => "AUG", m => "aug",
1277 :     N => "AAY", n => "aay",
1278 :     P => "CCN", p => "ccn",
1279 :     Q => "CAR", q => "car",
1280 :     R => "MGN", r => "mgn",
1281 :     S => "WSN", s => "wsn",
1282 :     T => "ACN", t => "acn",
1283 :     U => "UGA", u => "uga",
1284 :     V => "GUN", v => "gun",
1285 :     W => "UGG", w => "ugg",
1286 :     X => "NNN", x => "nnn",
1287 :     Y => "UAY", y => "uay",
1288 :     '*' => "URR"
1289 : golsen 1.2 );
1290 :    
1291 :    
1292 :     %DNA_letter_can_be = (
1293 : efrank 1.1 A => ["A"], a => ["a"],
1294 :     B => ["C", "G", "T"], b => ["c", "g", "t"],
1295 :     C => ["C"], c => ["c"],
1296 :     D => ["A", "G", "T"], d => ["a", "g", "t"],
1297 :     G => ["G"], g => ["g"],
1298 :     H => ["A", "C", "T"], h => ["a", "c", "t"],
1299 :     K => ["G", "T"], k => ["g", "t"],
1300 :     M => ["A", "C"], m => ["a", "c"],
1301 :     N => ["A", "C", "G", "T"], n => ["a", "c", "g", "t"],
1302 :     R => ["A", "G"], r => ["a", "g"],
1303 :     S => ["C", "G"], s => ["c", "g"],
1304 :     T => ["T"], t => ["t"],
1305 :     U => ["T"], u => ["t"],
1306 :     V => ["A", "C", "G"], v => ["a", "c", "g"],
1307 :     W => ["A", "T"], w => ["a", "t"],
1308 :     Y => ["C", "T"], y => ["c", "t"]
1309 :     );
1310 :    
1311 :    
1312 : golsen 1.2 %RNA_letter_can_be = (
1313 : efrank 1.1 A => ["A"], a => ["a"],
1314 :     B => ["C", "G", "U"], b => ["c", "g", "u"],
1315 :     C => ["C"], c => ["c"],
1316 :     D => ["A", "G", "U"], d => ["a", "g", "u"],
1317 :     G => ["G"], g => ["g"],
1318 :     H => ["A", "C", "U"], h => ["a", "c", "u"],
1319 :     K => ["G", "U"], k => ["g", "u"],
1320 :     M => ["A", "C"], m => ["a", "c"],
1321 :     N => ["A", "C", "G", "U"], n => ["a", "c", "g", "u"],
1322 :     R => ["A", "G"], r => ["a", "g"],
1323 :     S => ["C", "G"], s => ["c", "g"],
1324 :     T => ["U"], t => ["u"],
1325 :     U => ["U"], u => ["u"],
1326 :     V => ["A", "C", "G"], v => ["a", "c", "g"],
1327 :     W => ["A", "U"], w => ["a", "u"],
1328 :     Y => ["C", "U"], y => ["c", "u"]
1329 :     );
1330 :    
1331 :    
1332 : overbeek 1.4 %one_letter_to_three_letter_aa = (
1333 :     A => "Ala", a => "Ala",
1334 :     B => "Asx", b => "Asx",
1335 :     C => "Cys", c => "Cys",
1336 :     D => "Asp", d => "Asp",
1337 :     E => "Glu", e => "Glu",
1338 :     F => "Phe", f => "Phe",
1339 :     G => "Gly", g => "Gly",
1340 :     H => "His", h => "His",
1341 :     I => "Ile", i => "Ile",
1342 :     K => "Lys", k => "Lys",
1343 :     L => "Leu", l => "Leu",
1344 :     M => "Met", m => "Met",
1345 :     N => "Asn", n => "Asn",
1346 :     P => "Pro", p => "Pro",
1347 :     Q => "Gln", q => "Gln",
1348 :     R => "Arg", r => "Arg",
1349 :     S => "Ser", s => "Ser",
1350 :     T => "Thr", t => "Thr",
1351 :     U => "Sec", u => "Sec",
1352 :     V => "Val", v => "Val",
1353 :     W => "Trp", w => "Trp",
1354 :     X => "Xxx", x => "Xxx",
1355 :     Y => "Tyr", y => "Tyr",
1356 :     Z => "Glx", z => "Glx",
1357 :     '*' => "***"
1358 :     );
1359 : golsen 1.2
1360 :    
1361 :     %three_letter_to_one_letter_aa = (
1362 :     ALA => "A", Ala => "A", ala => "a",
1363 :     ARG => "R", Arg => "R", arg => "r",
1364 :     ASN => "N", Asn => "N", asn => "n",
1365 :     ASP => "D", Asp => "D", asp => "d",
1366 :     ASX => "B", Asx => "B", asx => "b",
1367 :     CYS => "C", Cys => "C", cys => "c",
1368 :     GLN => "Q", Gln => "Q", gln => "q",
1369 :     GLU => "E", Glu => "E", glu => "e",
1370 :     GLX => "Z", Glx => "Z", glx => "z",
1371 :     GLY => "G", Gly => "G", gly => "g",
1372 :     HIS => "H", His => "H", his => "h",
1373 :     ILE => "I", Ile => "I", ile => "i",
1374 :     LEU => "L", Leu => "L", leu => "l",
1375 :     LYS => "K", Lys => "K", lys => "k",
1376 :     MET => "M", Met => "M", met => "m",
1377 :     PHE => "F", Phe => "F", phe => "f",
1378 :     PRO => "P", Pro => "P", pro => "p",
1379 :     SEC => "U", Sec => "U", sec => "u",
1380 :     SER => "S", Ser => "S", ser => "s",
1381 :     THR => "T", Thr => "T", thr => "t",
1382 :     TRP => "W", Trp => "W", trp => "w",
1383 :     TYR => "Y", Tyr => "Y", tyr => "y",
1384 :     VAL => "V", Val => "V", val => "v",
1385 :     XAA => "X", Xaa => "X", xaa => "x",
1386 :     XXX => "X", Xxx => "X", xxx => "x",
1387 :     '***' => "*"
1388 : efrank 1.1 );
1389 :    
1390 :    
1391 :     #-----------------------------------------------------------------------------
1392 : golsen 1.10 # Translate nucleotides to one letter protein. Respects case of the
1393 :     # nucleotide sequence.
1394 : efrank 1.1 #
1395 : golsen 1.10 # $aa = translate_seq( $nt, $met_start )
1396 :     # $aa = translate_seq( $nt )
1397 : efrank 1.1 #
1398 :     #-----------------------------------------------------------------------------
1399 :    
1400 : golsen 1.10 sub translate_seq
1401 :     {
1402 :     my $seq = shift;
1403 : efrank 1.1 $seq =~ tr/-//d; # remove gaps
1404 :    
1405 : golsen 1.10 my @codons = $seq =~ m/(...?)/g; # Will try to translate last 2 nt
1406 :    
1407 :     # A second argument that is true forces first amino acid to be Met
1408 : efrank 1.1
1409 : golsen 1.10 my @met;
1410 :     if ( ( shift @_ ) && ( my $codon1 = shift @codons ) )
1411 :     {
1412 :     push @met, ( $codon1 =~ /[a-z]/ ? 'm' : 'M' );
1413 : efrank 1.1 }
1414 :    
1415 : golsen 1.10 join( '', @met, map { translate_codon( $_ ) } @codons )
1416 : efrank 1.1 }
1417 :    
1418 :    
1419 :     #-----------------------------------------------------------------------------
1420 : golsen 1.10 # Translate a single triplet with "universal" genetic code.
1421 : efrank 1.1 #
1422 :     # $aa = translate_codon( $triplet )
1423 : golsen 1.10 # $aa = translate_DNA_codon( $triplet )
1424 :     # $aa = translate_uc_DNA_codon( $triplet )
1425 : efrank 1.1 #
1426 :     #-----------------------------------------------------------------------------
1427 :    
1428 : golsen 1.10 sub translate_DNA_codon { translate_codon( @_ ) }
1429 : efrank 1.1
1430 : golsen 1.10 sub translate_uc_DNA_codon { translate_codon( uc $_[0] ) }
1431 : efrank 1.1
1432 : golsen 1.10 sub translate_codon
1433 :     {
1434 :     my $codon = shift;
1435 :     $codon =~ tr/Uu/Tt/; # Make it DNA
1436 :    
1437 :     # Try a simple lookup:
1438 : efrank 1.1
1439 :     my $aa;
1440 : golsen 1.10 if ( $aa = $genetic_code{ $codon } ) { return $aa }
1441 : efrank 1.1
1442 : golsen 1.10 # Attempt to recover from mixed-case codons:
1443 : efrank 1.1
1444 : golsen 1.10 $codon = ( $codon =~ /[a-z]/ ) ? lc $codon : uc $codon;
1445 : efrank 1.1 if ( $aa = $genetic_code{ $codon } ) { return $aa }
1446 :    
1447 : golsen 1.10 # The code defined above catches simple N, R and Y ambiguities in the
1448 :     # third position. Other codons (e.g., GG[KMSWBDHV], or even GG) might
1449 :     # be unambiguously translated by converting the last position to N and
1450 :     # seeing if this is in the code table:
1451 :    
1452 :     my $N = ( $codon =~ /[a-z]/ ) ? 'n' : 'N';
1453 :     if ( $aa = $genetic_code{ substr($codon,0,2) . $N } ) { return $aa }
1454 :    
1455 :     # Test that codon is valid for an unambiguous aa:
1456 :    
1457 :     my $X = ( $codon =~ /[a-z]/ ) ? 'x' : 'X';
1458 :     if ( $codon !~ m/^[ACGTMY][ACGT][ACGTKMRSWYBDHVN]$/i
1459 :     && $codon !~ m/^YT[AGR]$/i # Leu YTR
1460 :     && $codon !~ m/^MG[AGR]$/i # Arg MGR
1461 :     )
1462 :     {
1463 :     return $X;
1464 :     }
1465 : efrank 1.1
1466 :     # Expand all ambiguous nucleotides to see if they all yield same aa.
1467 :    
1468 : golsen 1.10 my @n1 = @{ $DNA_letter_can_be{ substr( $codon, 0, 1 ) } };
1469 :     my $n2 = substr( $codon, 1, 1 );
1470 :     my @n3 = @{ $DNA_letter_can_be{ substr( $codon, 2, 1 ) } };
1471 :     my @triples = map { my $n12 = $_ . $n2; map { $n12 . $_ } @n3 } @n1;
1472 :    
1473 :     my $triple = shift @triples;
1474 :     $aa = $genetic_code{ $triple };
1475 :     $aa or return $X;
1476 :    
1477 :     foreach $triple ( @triples ) { return $X if $aa ne $genetic_code{$triple} }
1478 : efrank 1.1
1479 : golsen 1.10 return $aa;
1480 : efrank 1.1 }
1481 :    
1482 :    
1483 :     #-----------------------------------------------------------------------------
1484 :     # Translate with a user-supplied genetic code to translate a sequence.
1485 :     # Diagnose the use of upper versus lower, and T versus U in the supplied
1486 :     # code, and transform the supplied nucleotide sequence to match.
1487 :     #
1488 : golsen 1.10 # $aa = translate_seq_with_user_code( $nt, \%gen_code )
1489 :     # $aa = translate_seq_with_user_code( $nt, \%gen_code, $start_with_met )
1490 : efrank 1.1 #
1491 : golsen 1.10 # Modified 2007-11-22 to be less intrusive in these diagnoses by sensing
1492 :     # the presence of both versions in the user code.
1493 : efrank 1.1 #-----------------------------------------------------------------------------
1494 :    
1495 : golsen 1.10 sub translate_seq_with_user_code
1496 :     {
1497 : efrank 1.1 my $seq = shift;
1498 :     $seq =~ tr/-//d; # remove gaps *** Why?
1499 :    
1500 : golsen 1.10 my $gc = shift; # Reference to hash of code
1501 :     if (! $gc || ref($gc) ne "HASH")
1502 :     {
1503 :     print STDERR "translate_seq_with_user_code needs genetic code hash as second argument.";
1504 :     return undef;
1505 :     }
1506 :    
1507 :     # Test code support for upper vs lower case:
1508 :    
1509 :     my ( $TTT, $UUU );
1510 :     if ( $gc->{AAA} && ! $gc->{aaa} ) # Uppercase only code table
1511 :     {
1512 :     $seq = uc $seq; # Uppercase sequence
1513 :     ( $TTT, $UUU ) = ( 'TTT', 'UUU' );
1514 :     }
1515 :     elsif ( $gc->{aaa} && ! $gc->{AAA} ) # Lowercase only code table
1516 :     {
1517 :     $seq = lc $seq; # Lowercase sequence
1518 :     ( $TTT, $UUU ) = ( 'ttt', 'uuu' );
1519 :     }
1520 :     elsif ( $gc->{aaa} )
1521 :     {
1522 :     ( $TTT, $UUU ) = ( 'ttt', 'uuu' );
1523 : efrank 1.1 }
1524 : golsen 1.10 else
1525 :     {
1526 :     print STDERR "User-supplied genetic code does not have aaa or AAA\n";
1527 :     return undef;
1528 : efrank 1.1 }
1529 :    
1530 : golsen 1.10 # Test code support for U vs T:
1531 : efrank 1.1
1532 : golsen 1.10 my $ambigs;
1533 :     if ( $gc->{$UUU} && ! $gc->{$TTT} ) # RNA only code table
1534 :     {
1535 :     $seq = tr/Tt/Uu/;
1536 : efrank 1.1 $ambigs = \%RNA_letter_can_be;
1537 :     }
1538 : golsen 1.10 elsif ( $gc->{$TTT} && ! $gc->{$UUU} ) # DNA only code table
1539 :     {
1540 :     $seq = tr/Uu/Tt/;
1541 : efrank 1.1 $ambigs = \%DNA_letter_can_be;
1542 :     }
1543 : golsen 1.10 else
1544 :     {
1545 :     my $t = $seq =~ tr/Tt//;
1546 :     my $u = $seq =~ tr/Uu//;
1547 :     $ambigs = ( $t > $u ) ? \%DNA_letter_can_be : \%RNA_letter_can_be;
1548 : efrank 1.1 }
1549 :    
1550 : golsen 1.10 # We can now do the codon-by-codon translation:
1551 : efrank 1.1
1552 : golsen 1.10 my @codons = $seq =~ m/(...?)/g; # will try to translate last 2 nt
1553 :    
1554 :     # A third argument that is true forces first amino acid to be Met
1555 : efrank 1.1
1556 : golsen 1.10 my @met;
1557 :     if ( ( shift @_ ) && ( my $codon1 = shift @codons ) )
1558 :     {
1559 :     push @met, ( $codon1 =~ /[a-z]/ ? 'm' : 'M' );
1560 : efrank 1.1 }
1561 :    
1562 : golsen 1.10 join( '', @met, map { translate_codon_with_user_code( $_, $gc, $ambigs ) } @codons )
1563 : efrank 1.1 }
1564 :    
1565 :    
1566 :     #-----------------------------------------------------------------------------
1567 : golsen 1.10 # Translate with user-supplied genetic code hash. No error check on the code.
1568 :     # Should only be called through translate_seq_with_user_code.
1569 : efrank 1.1 #
1570 : golsen 1.10 # $aa = translate_codon_with_user_code( $triplet, \%code, $ambig_table )
1571 : efrank 1.1 #
1572 :     # $triplet speaks for itself
1573 :     # $code ref to the hash with the codon translations
1574 :     # $ambig_table ref to hash with lists of nucleotides for each ambig code
1575 :     #-----------------------------------------------------------------------------
1576 :    
1577 : golsen 1.10 sub translate_codon_with_user_code
1578 :     {
1579 :     my ( $codon, $gc, $N, $X, $ambigs ) = @_;
1580 :    
1581 :     # Try a simple lookup:
1582 : efrank 1.1
1583 :     my $aa;
1584 : golsen 1.10 if ( $aa = $gc->{ $codon } ) { return $aa }
1585 : efrank 1.1
1586 : golsen 1.10 # Attempt to recover from mixed-case codons:
1587 : efrank 1.1
1588 : golsen 1.10 $codon = ( $codon =~ /[a-z]/ ) ? lc $codon : uc $codon;
1589 :     if ( $aa = $genetic_code{ $codon } ) { return $aa }
1590 : efrank 1.1
1591 : golsen 1.10 # Test that codon is valid for an unambiguous aa:
1592 : efrank 1.1
1593 : golsen 1.10 my $X = ( $codon =~ /[a-z]/ ) ? 'x' : 'X';
1594 :    
1595 :     if ( $codon =~ m/^[ACGTU][ACGTU]$/i ) # Add N?
1596 :     {
1597 :     $codon .= ( $codon =~ /[a-z]/ ) ? 'n' : 'N';
1598 :     }
1599 :     elsif ( $codon !~ m/^[ACGTUMY][ACGTU][ACGTUKMRSWYBDHVN]$/i ) # Valid?
1600 :     {
1601 :     return $X;
1602 :     }
1603 : efrank 1.1
1604 :     # Expand all ambiguous nucleotides to see if they all yield same aa.
1605 :    
1606 : golsen 1.10 my @n1 = @{ $ambigs->{ substr( $codon, 0, 1 ) } };
1607 :     my $n2 = substr( $codon, 1, 1 );
1608 :     my @n3 = @{ $ambigs->{ substr( $codon, 2, 1 ) } };
1609 :     my @triples = map { my $n12 = $_ . $n2; map { $n12 . $_ } @n3 } @n1;
1610 :    
1611 :     my $triple = shift @triples;
1612 :     $aa = $gc->{ $triple } || $gc->{ lc $triple } || $gc->{ uc $triple };
1613 :     $aa or return $X;
1614 :    
1615 :     foreach $triple ( @triples )
1616 :     {
1617 :     return $X if $aa ne ( $gc->{$triple} || $gc->{lc $triple} || $gc->{uc $triple} );
1618 : efrank 1.1 }
1619 :    
1620 : golsen 1.10 return $aa;
1621 : efrank 1.1 }
1622 :    
1623 :    
1624 :     #-----------------------------------------------------------------------------
1625 :     # Read a list of intervals from a file.
1626 :     # Allow id_start_end, or id \s start \s end formats
1627 :     #
1628 : overbeek 1.4 # @intervals = read_intervals( \*FILEHANDLE )
1629 : efrank 1.1 #-----------------------------------------------------------------------------
1630 :     sub read_intervals {
1631 :     my $fh = shift;
1632 :     my @intervals = ();
1633 :    
1634 :     while (<$fh>) {
1635 :     chomp;
1636 :     /^(\S+)_(\d+)_(\d+)(\s.*)?$/ # id_start_end WIT2
1637 :     || /^(\S+)_(\d+)-(\d+)(\s.*)?$/ # id_start-end ???
1638 :     || /^(\S+)=(\d+)=(\d+)(\s.*)?$/ # id=start=end Badger
1639 :     || /^(\S+)\s+(\d+)\s+(\d+)(\s.*)?$/ # id \s start \s end
1640 :     || next;
1641 :    
1642 :     # Matched a pattern. Store reference to (id, left, right):
1643 :     push @intervals, ($2 < $3) ? [ $1, $2+0, $3+0 ]
1644 :     : [ $1, $3+0, $2+0 ];
1645 :     }
1646 :     return @intervals;
1647 :     }
1648 :    
1649 :    
1650 :     #-----------------------------------------------------------------------------
1651 : golsen 1.2 # Convert a list of intervals to read [ id, left_end, right_end ].
1652 :     #
1653 :     # @intervals = standardize_intervals( @interval_refs )
1654 :     #-----------------------------------------------------------------------------
1655 :     sub standardize_intervals {
1656 :     map { ( $_->[1] < $_->[2] ) ? $_ : [ $_->[0], $_->[2], $_->[1] ] } @_;
1657 :     }
1658 :    
1659 :    
1660 :     #-----------------------------------------------------------------------------
1661 : efrank 1.1 # Take the union of a list of intervals
1662 :     #
1663 :     # @joined = join_intervals( @interval_refs )
1664 :     #-----------------------------------------------------------------------------
1665 :     sub join_intervals {
1666 :     my @ordered = sort { $a->[0] cmp $b->[0] # first by id
1667 :     || $a->[1] <=> $b->[1] # next by left end
1668 :     || $b->[2] <=> $a->[2] # finally longest first
1669 :     } @_;
1670 :    
1671 :     my @joined = ();
1672 :     my $n_int = @ordered;
1673 :    
1674 :     my ($cur_id) = "";
1675 :     my ($cur_left) = -1;
1676 :     my ($cur_right) = -1;
1677 :     my ($new_id, $new_left, $new_right);
1678 :    
1679 :     for (my $i = 0; $i < $n_int; $i++) {
1680 :     ($new_id, $new_left, $new_right) = @{$ordered[$i]}; # get the new data
1681 :    
1682 :     if ( ( $new_id ne $cur_id) # if new contig
1683 :     || ( $new_left > $cur_right + 1) # or not touching previous
1684 :     ) { # push the previous interval
1685 :     if ($cur_id) { push (@joined, [ $cur_id, $cur_left, $cur_right ]) }
1686 :     $cur_id = $new_id; # update the current interval
1687 :     $cur_left = $new_left;
1688 :     $cur_right = $new_right;
1689 :     }
1690 :    
1691 :     elsif ($new_right > $cur_right) { # extend the right end if necessary
1692 :     $cur_right = $new_right;
1693 :     }
1694 :     }
1695 :    
1696 :     if ($cur_id) { push (@joined, [$cur_id, $cur_left, $cur_right]) }
1697 :     return @joined;
1698 :     }
1699 :    
1700 : golsen 1.2
1701 :     #-----------------------------------------------------------------------------
1702 :     # Split location strings to oriented intervals.
1703 :     #
1704 :     # @intervals = locations_2_intervals( @locations )
1705 :     # $interval = locations_2_intervals( $location )
1706 :     #-----------------------------------------------------------------------------
1707 :     sub locations_2_intervals {
1708 :     my @intervals = map { /^(\S+)_(\d+)_(\d+)(\s.*)?$/
1709 :     || /^(\S+)_(\d+)-(\d+)(\s.*)?$/
1710 :     || /^(\S+)=(\d+)=(\d+)(\s.*)?$/
1711 :     || /^(\S+)\s+(\d+)\s+(\d+)(\s.*)?$/
1712 :     ? [ $1, $2+0, $3+0 ]
1713 :     : ()
1714 :     } @_;
1715 :    
1716 :     return wantarray ? @intervals : $intervals[0];
1717 :     }
1718 :    
1719 :    
1720 :     #-----------------------------------------------------------------------------
1721 :     # Read a list of oriented intervals from a file.
1722 :     # Allow id_start_end, or id \s start \s end formats
1723 :     #
1724 : overbeek 1.4 # @intervals = read_oriented_intervals( \*FILEHANDLE )
1725 : golsen 1.2 #-----------------------------------------------------------------------------
1726 :     sub read_oriented_intervals {
1727 :     my $fh = shift;
1728 :     my @intervals = ();
1729 :    
1730 :     while (<$fh>) {
1731 :     chomp;
1732 :     /^(\S+)_(\d+)_(\d+)(\s.*)?$/ # id_start_end WIT2
1733 :     || /^(\S+)_(\d+)-(\d+)(\s.*)?$/ # id_start-end ???
1734 :     || /^(\S+)=(\d+)=(\d+)(\s.*)?$/ # id=start=end Badger
1735 :     || /^(\S+)\s+(\d+)\s+(\d+)(\s.*)?$/ # id \s start \s end
1736 :     || next;
1737 :    
1738 :     # Matched a pattern. Store reference to (id, start, end):
1739 :     push @intervals, [ $1, $2+0, $3+0 ];
1740 :     }
1741 :     return @intervals;
1742 :     }
1743 :    
1744 :    
1745 :     #-----------------------------------------------------------------------------
1746 :     # Reverse the orientation of a list of intervals
1747 :     #
1748 :     # @reversed = reverse_intervals( @interval_refs )
1749 :     #-----------------------------------------------------------------------------
1750 :     sub reverse_intervals {
1751 :     map { [ $_->[0], $_->[2], $_->[1] ] } @_;
1752 :     }
1753 :    
1754 :    
1755 : overbeek 1.4 #-----------------------------------------------------------------------------
1756 :     # Convert GenBank locations to SEED locations
1757 :     #
1758 :     # @seed_locs = gb_location_2_seed( $contig, @gb_locs )
1759 :     #-----------------------------------------------------------------------------
1760 :     sub gb_location_2_seed
1761 :     {
1762 :     my $contig = shift @_;
1763 :     $contig or die "First arg of gb_location_2_seed must be contig_id\n";
1764 :    
1765 :     map { join( ',', gb_loc_2_seed_2( $contig, $_ ) ) || undef } @_
1766 :     }
1767 :    
1768 :     sub gb_loc_2_seed_2
1769 :     {
1770 :     my ( $contig, $loc ) = @_;
1771 :    
1772 :     if ( $loc =~ /^(\d+)\.\.(\d+)$/ )
1773 :     {
1774 :     join( '_', $contig, $1, $2 )
1775 :     }
1776 :    
1777 :     elsif ( $loc =~ /^join\((.*)\)$/ )
1778 :     {
1779 :     $loc = $1;
1780 :     my $lvl = 0;
1781 :     for ( my $i = length( $loc )-1; $i >= 0; $i-- )
1782 :     {
1783 :     for ( substr( $loc, $i, 1 ) )
1784 :     {
1785 :     /,/ && ! $lvl and substr( $loc, $i, 1 ) = "\t";
1786 :     /\(/ and $lvl--;
1787 :     /\)/ and $lvl++;
1788 :     }
1789 :     }
1790 :     $lvl == 0 or print STDERR "Paren matching error: $loc\n" and die;
1791 :     map { gb_loc_2_seed_2( $contig, $_ ) } split /\t/, $loc
1792 :     }
1793 :    
1794 :     elsif ( $loc =~ /^complement\((.*)\)$/ )
1795 :     {
1796 :     map { s/_(\d+)_(\d+)$/_$2_$1/; $_ }
1797 :     reverse
1798 :     gb_loc_2_seed_2( $contig, $1 )
1799 :     }
1800 :    
1801 :     else
1802 :     {
1803 :     ()
1804 :     }
1805 :     }
1806 :    
1807 :    
1808 : golsen 1.7 #-----------------------------------------------------------------------------
1809 :     # Read qual.
1810 :     #
1811 :     # Save the contents in a list of refs to arrays: [ $id, $descript, \@qual ]
1812 :     #
1813 :     # @seq_entries = read_qual( ) # STDIN
1814 :     # \@seq_entries = read_qual( ) # STDIN
1815 :     # @seq_entries = read_qual( \*FILEHANDLE )
1816 :     # \@seq_entries = read_qual( \*FILEHANDLE )
1817 :     # @seq_entries = read_qual( $filename )
1818 :     # \@seq_entries = read_qual( $filename )
1819 :     #-----------------------------------------------------------------------------
1820 :     sub read_qual {
1821 :     my ( $fh, $name, $close, $unused ) = input_filehandle( $_[0] );
1822 :     $unused && die "Bad reference type (" . ref( $unused ) . ") passed to read_qual\n";
1823 :    
1824 :     my @quals = ();
1825 :     my ($id, $desc, $qual) = ("", "", []);
1826 :    
1827 :     while ( <$fh> ) {
1828 :     chomp;
1829 :     if (/^>\s*(\S+)(\s+(.*))?$/) { # new id
1830 :     if ($id && @$qual) { push @quals, [ $id, $desc, $qual ] }
1831 :     ($id, $desc, $qual) = ($1, $3 ? $3 : "", []);
1832 :     }
1833 :     else {
1834 :     push @$qual, split;
1835 :     }
1836 :     }
1837 :     close( $fh ) if $close;
1838 :    
1839 :     if ($id && @$qual) { push @quals, [ $id, $desc, $qual ] }
1840 :     return wantarray ? @quals : \@quals;
1841 :     }
1842 :    
1843 :    
1844 : golsen 1.11 #-------------------------------------------------------------------------------
1845 :     # Fraction difference for an alignment of two nucleotide sequences in terms of
1846 :     # number of differing residues, number of gaps, and number of gap opennings.
1847 :     #
1848 :     # $fraction_diff = fraction_nt_diff( $seq1, $seq2, \%options )
1849 :     #
1850 :     # or
1851 :     #
1852 :     # $fraction_diff = fraction_nt_diff( $seq1, $seq2 )
1853 :     # $fraction_diff = fraction_nt_diff( $seq1, $seq2, $gap_wgt )
1854 :     # $fraction_diff = fraction_nt_diff( $seq1, $seq2, $open_wgt, $extend_wgt )
1855 :     #
1856 :     # Options:
1857 :     #
1858 :     # gap => $gap_wgt # Gap open and extend weight (D = 0.5)
1859 :     # open => $open_wgt # Gap openning weight (D = gap_wgt)
1860 :     # extend => $extend_wgt # Gap extension weight (D = open_wgt)
1861 :     # t_gap => $term_gap_wgt # Terminal open and extend weight
1862 :     # t_open => $term_open_wgt # Terminal gap open weight (D = open_wgt)
1863 :     # t_extend => $term_extend_wgt # Terminal gap extend weight (D = extend_wgt)
1864 :     #
1865 :     # Default gap open and gap extend weights are 1/2. Beware that
1866 :     #
1867 :     # $fraction_diff = fraction_nt_diff( $seq1, $seq2, 1 )
1868 :     #
1869 :     # and
1870 :     #
1871 :     # $fraction_diff = fraction_nt_diff( $seq1, $seq2, 1, 0 )
1872 :     #
1873 :     # are different. The first has equal openning and extension weights, whereas
1874 :     # the second has an openning weight of 1, and and extension weight of 0 (it
1875 :     # only penalizes the number of runs of gaps).
1876 :     #-------------------------------------------------------------------------------
1877 :     sub fraction_nt_diff
1878 :     {
1879 :     my ( $npos, $nid, $ndif, $ngap, $nopen, $tgap, $topen ) = interpret_nt_align( @_[0,1] );
1880 :    
1881 :     my $diff_scr;
1882 :     if ( ref( $_[2] ) eq 'HASH' )
1883 :     {
1884 :     my $opts = $_[2];
1885 :     my $gap_open = defined $opts->{ open } ? $opts->{ open }
1886 :     : defined $opts->{ gap } ? $opts->{ gap }
1887 :     : 0.5;
1888 :     my $gap_extend = defined $opts->{ extend } ? $opts->{ extend }
1889 :     : $gap_open;
1890 :     my $term_open = defined $opts->{ t_open } ? $opts->{ t_open }
1891 :     : defined $opts->{ t_gap } ? $opts->{ t_gap }
1892 :     : $gap_open;
1893 :     my $term_extend = defined $opts->{ t_extend } ? $opts->{ t_extend }
1894 :     : defined $opts->{ t_gap } ? $opts->{ t_gap }
1895 :     : $gap_extend;
1896 :    
1897 :     $nopen -= $topen;
1898 :     $ngap -= $tgap;
1899 :     $diff_scr = $ndif + $gap_open * $nopen + $gap_extend * ($ngap-$nopen)
1900 :     + $term_open * $topen + $term_extend * ($tgap-$topen);
1901 :     }
1902 :     else
1903 :     {
1904 :     my $gap_open = defined( $_[2] ) ? $_[2] : 0.5;
1905 :     my $gap_extend = defined( $_[3] ) ? $_[3] : $gap_open;
1906 :     $diff_scr = $ndif + $gap_open * $nopen + $gap_extend * ($ngap-$nopen);
1907 :     }
1908 :     my $ttl_scr = $nid + $diff_scr;
1909 :    
1910 :     $ttl_scr ? $diff_scr / $ttl_scr : undef
1911 :     }
1912 :    
1913 :    
1914 :     #-------------------------------------------------------------------------------
1915 :     # Interpret an alignment of two nucleotide sequences in terms of: useful
1916 :     # aligned positions (unambiguous, and not a common gap), number of identical
1917 :     # residues, number of differing residues, number of gaps, and number of gap
1918 :     # opennings.
1919 :     #
1920 :     # ( $npos, $nid, $ndif, $ngap, $nopen, $tgap, $topen ) = interpret_nt_align( $seq1, $seq2 )
1921 :     #
1922 :     # $npos = total aligned positons (= $nid + $ndif + $ngap)
1923 :     # $nid = number of positions with identical nucleotides (ignoring case)
1924 :     # $ndif = number of positions with differing nucleotides
1925 :     # $ngap = number of positions with gap in one sequence but not the other
1926 :     # $nopen = number of runs of gaps
1927 :     # $tgap = number of gaps in runs adjacent to a terminus
1928 :     # $topen = number of alignment ends with gaps
1929 :     #
1930 :     # Some of the methods might seem overly complex, but are necessary for cases
1931 :     # in which the gaps switch strands in the alignment:
1932 :     #
1933 :     # seq1 ---ACGTGAC--TTGCAGAG
1934 :     # seq2 TTT---TGACGG--GCAGGG
1935 :     # mask 00000011110000111111
1936 :     #
1937 :     # npos = 20
1938 :     # nid = 9
1939 :     # ndif = 1
1940 :     # ngap = 10
1941 :     # nopen = 4
1942 :     # tgap = 3
1943 :     # topen = 1
1944 :     #
1945 :     # Although there are 4 gap opennings, there are only 2 runs in the mask,
1946 :     # and the terminal run is length 6, not 3. (Why handle these? Because
1947 :     # pairs of sequences from a multiple sequence alignment can look like this.)
1948 :     #-------------------------------------------------------------------------------
1949 :     sub interpret_nt_align
1950 :     {
1951 :     # Remove alignment columns that are not informative:
1952 :     my ( $s1, $s2 ) = useful_nt_align( @_[0,1] );
1953 :     my $nmat = length( $s1 ); # Useful alignment length
1954 :    
1955 :     my $m1 = $s1;
1956 :     $m1 =~ tr/ACGT/\377/; # Nucleotides to all 1 bits
1957 :     $m1 =~ tr/\377/\000/c; # Others (gaps) to null byte
1958 :     my $m2 = $s2;
1959 :     $m2 =~ tr/ACGT/\377/; # Nucleotides to all 1 bits
1960 :     $m2 =~ tr/\377/\000/c; # Others (gaps) to null byte
1961 :     $m1 &= $m2; # Gap in either sequence becomes null
1962 :     $s1 &= $m1; # Apply mask to sequence 1
1963 :     $s2 &= $m1; # Apply mask to sequence 2
1964 :     my $nopen = @{[ $s1 =~ /\000+/g ]} # Gap opens in sequence 1
1965 :     + @{[ $s2 =~ /\000+/g ]}; # Gap opens in sequence 2
1966 :     my ( $tgap, $topen ) = ( 0, 0 );
1967 :     if ( $s1 =~ /^(\000+)/ || $s2 =~ /^(\000+)/ ) { $tgap += length( $1 ); $topen++ }
1968 :     if ( $s1 =~ /(\000+)$/ || $s2 =~ /(\000+)$/ ) { $tgap += length( $1 ); $topen++ }
1969 :     $s1 =~ tr/\000//d; # Remove nulls (former gaps)
1970 :     $s2 =~ tr/\000//d; # Remove nulls (former gaps)
1971 :     my $ngap = $nmat - length( $s1 ); # Total gaps
1972 :    
1973 :     my $xor = $s1 ^ $s2; # xor of identical residues is null byte
1974 :     my $nid = ( $xor =~ tr/\000//d ); # Count the nulls (identical residues)
1975 :     my $ndif = $nmat - $nid - $ngap;
1976 :    
1977 :     ( $nmat, $nid, $ndif, $ngap, $nopen, $tgap, $topen )
1978 :     }
1979 :    
1980 :    
1981 :     sub useful_nt_align
1982 :     {
1983 :     my ( $s1, $s2 ) = map { uc $_ } @_;
1984 :     $s1 =~ tr/U/T/; # Convert U to T
1985 :     my $m1 = $s1;
1986 :     $m1 =~ tr/ACGT-/\377/; # Allowed symbols to hex FF byte
1987 :     $m1 =~ tr/\377/\000/c; # All else to null byte
1988 :     $s2 =~ tr/U/T/; # Convert U to T
1989 :     my $m2 = $s2;
1990 :     $m2 =~ tr/ACGT-/\377/; # Allowed symbols to hex FF byte
1991 :     $m2 =~ tr/\377/\000/c; # All else to null byte
1992 :     $m1 &= $m2; # Invalid in either sequence becomes null
1993 :     $s1 &= $m1; # Apply mask to sequence 1
1994 :     $s1 =~ tr/\000//d; # Delete nulls in sequence 1
1995 :     $s2 &= $m1; # Apply mask to sequence 2
1996 :     $s2 =~ tr/\000//d; # Delete nulls in sequence 2
1997 :     ( $s1, $s2 )
1998 :     }
1999 :    
2000 :    
2001 : efrank 1.1 1;

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3