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

Annotation of /FigKernelPackages/gjoseqlib.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3