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

Annotation of /FigKernelPackages/gjoseqlib.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3