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

Annotation of /FigKernelPackages/gjoseqlib.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3