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

Annotation of /FigKernelPackages/gjoseqlib.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3