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

Annotation of /FigKernelPackages/gjoseqlib.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3