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

Annotation of /FigKernelPackages/gjoseqlib.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3