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

Annotation of /FigKernelPackages/gjoseqlib.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3