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

Annotation of /FigKernelPackages/gjoseqlib.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3