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

Annotation of /FigKernelPackages/gjoseqlib.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3