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

Annotation of /FigKernelPackages/gjoseqlib.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3