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

Annotation of /FigKernelPackages/representative_sequences.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

1 : golsen 1.1 package representative_sequences;
2 :    
3 : overbeek 1.10 # This is a SAS component
4 :     #
5 : golsen 1.1 use strict;
6 :     use gjoparseblast;
7 :    
8 : golsen 1.5 eval { use Data::Dumper }; # Not in all installations
9 :    
10 :     # These variables are used as globals below. They have been made SEED-aware,
11 :     # but not SEED-dependent. formatdb is run as a system command, and might
12 : golsen 1.1 # be encapsulated in a run() construct for the SEED. blastall is in an
13 :     # input pipe.
14 :    
15 : golsen 1.5 my $formatdb = $FIG_Config::ext_bin ? "$FIG_Config::ext_bin/formatdb"
16 :     : "formatdb";
17 :     my $blastall = $FIG_Config::ext_bin ? "$FIG_Config::ext_bin/blastall"
18 :     : "blastall";
19 : golsen 1.1
20 :     require Exporter;
21 :    
22 :     our @ISA = qw(Exporter);
23 :     our @EXPORT = qw( representative_sequences
24 :     rep_seq_2
25 : golsen 1.5 rep_seq
26 : golsen 1.1 );
27 :    
28 :     #===============================================================================
29 : golsen 1.8 # Build or add to a set of representative sequences (if you do not want an
30 : golsen 1.5 # enrichment of sequences around a focus sequence (called the reference), this
31 :     # is probably the subroutine that you want).
32 : golsen 1.1 #
33 : golsen 1.5 # \@reps = rep_seq( \@reps, \@new, \%options );
34 :     # \@reps = rep_seq( \@new, \%options );
35 : golsen 1.1 #
36 :     # or
37 :     #
38 : golsen 1.5 # ( \@reps, \%representing ) = rep_seq( \@reps, \@new, \%options );
39 :     # ( \@reps, \%representing ) = rep_seq( \@new, \%options );
40 : golsen 1.1 #
41 : golsen 1.5 # or
42 : golsen 1.2 #
43 :     # \@reps = rep_seq_2( \@reps, \@new, \%options );
44 :     # \@reps = rep_seq_2( \@new, \%options );
45 :     #
46 :     # or
47 :     #
48 :     # ( \@reps, \%representing ) = rep_seq_2( \@reps, \@new, \%options );
49 :     # ( \@reps, \%representing ) = rep_seq_2( \@new, \%options );
50 : golsen 1.1 #
51 : golsen 1.5 # Construct a representative set of related sequences:
52 :     #
53 :     # \@repseqs = representative_sequences( $ref, \@seqs, $max_sim, \%options );
54 :     #
55 :     # or
56 :     #
57 :     # ( \@repseqs, \%representing, \@low_sim ) = representative_sequences( $ref,
58 :     # \@seqs, $max_sim, \%options );
59 :     #
60 : golsen 1.1 # Output:
61 :     #
62 :     # \@repseqs Reference to the list of retained (representative subset)
63 :     # of sequence entries. Sequence entries have the form
64 :     # [ $id, $def, $seq ]
65 :     #
66 :     # \%representing
67 :     # Reference to a hash in which the keys are the ids of the
68 :     # representative sequences, for which the corresponding value
69 :     # is a list of ids of other sequences that are represented by
70 :     # that representive.
71 :     #
72 :     #
73 :     # Arguments (only \@seqs is required):
74 :     #
75 :     # $ref A reference sequence as [ $id, $def, $seq ]. If present, the
76 :     # reference sequence defines a focal point for the analysis. A
77 :     # representative sequence from each lineage in its vicinity will
78 :     # be retained, even though they are more similar than max_sim to
79 :     # the reference, or to each other. The reference will always be
80 :     # included in the representative set. A limit is put on the
81 :     # similarity of lineages retained by the reference sequence with
82 :     # the max_ref_sim option (default = 0.99). The reference sequence
83 : golsen 1.2 # should not be repeated in the set of other sequences. (Only
84 :     # applies to representative_sequences; there is no equivalent for
85 :     # rep_seq_2.)
86 :     #
87 :     # \@reps In rep_seq_2, these sequences will each be placed in their own
88 :     # cluster, regardless of their similarity to one another. Each
89 :     # remaining sequence is added to the cluster to which it is
90 :     # most similar, unless it is less simililar than max_sim, in
91 :     # which case it represents a new cluster.
92 : golsen 1.1 #
93 :     # \@seqs Set of sequences to be pruned. If there is no reference
94 :     # sequence, the fist sequence in this list will be the starting
95 :     # point for the analysis and will be retained, but all sequences
96 :     # more similar than max_sim to it will be removed (in contrast to
97 :     # a reference sequence, which retains a representative of each
98 :     # lineage in its vicinity). Sequences that fail the E-value test
99 :     # relative to the reference (or the fist sequence if there is no
100 :     # reference) are dropped.
101 :     #
102 : golsen 1.2 # $max_sim (representative_sequences only; an option for rep_seq_2)
103 :     # Sequences with a higher similarity than max_sim to an existing
104 :     # representative sequence will not be included in the @reps
105 :     # output. Their ids are associated with the identifier of the
106 :     # sequence representing them in \%representing. The details of
107 :     # the behaviour are modified by other options. (default = 0.80)
108 : golsen 1.1 #
109 : golsen 1.8 # \%options Key => Value pairs that modify the behaviour:
110 :     #
111 :     # by_size (rep_seq and rep_seq_2 only)
112 :     # By default, sequences are analyzed in input order. This
113 :     # option set to true will sort from longest to shortest.
114 : golsen 1.1 #
115 :     # logfile Filehandle for a logfile of the progress. As each
116 : golsen 1.2 # sequence is analyzed, its disposition in recorded.
117 :     # In representative_sequences(), the id of each new
118 :     # representative is followed by a tab separated list of the
119 :     # ids that it represents. In rep_seq_2(), as each sequence
120 :     # is analyzed, it is recorded, followed by the id of the
121 :     # sequence representing it, if it is not the first member
122 :     # of a new cluster. Autoflush is set for the logfile.
123 : golsen 1.1 # If the value supplied is not a reference to a GLOB, then
124 :     # the log is sent to STDOUT (which is probably not what you
125 :     # want in most cases). The behavior is intended to aid in
126 :     # following prgress, and in recovery of interupted runs.
127 :     #
128 : golsen 1.2 # max_ref_sim (representative_sequences only)
129 : golsen 1.1 # Maximum similarity of any sequence to the reference. If
130 :     # max_ref_sim is less than max_sim, it is silently reset to
131 :     # max_sim. (default = 0.99, because 1.0 can be annoying)
132 :     #
133 : golsen 1.2 # max_e_val Maximum E-value for blastall. Probably moot, but will help
134 :     # with performance. (default = 0.01)
135 :     #
136 :     # max_sim Sequences with a higher similarity than max_sim to a
137 :     # retained sequence will be deleted. The details of the
138 :     # behaviour is modified by other options. (default = 0.80)
139 :     # (a parameter for representative_sequences, but an option
140 :     # for rep_seq_2).
141 : golsen 1.1 #
142 : golsen 1.5 # save_tmp Do not delete temporary files upon completion (for debug)
143 :     #
144 : golsen 1.1 # sim_meas Measure similarity for inclusion or exclusion by
145 :     # 'identity_fraction' (default), 'positive_fraction', or
146 :     # 'score_per_position'
147 :     #
148 : golsen 1.2 # save_exp (representative_sequences only)
149 :     # When there is a reference sequence, lineages more similar
150 : golsen 1.1 # than max_sim will be retained near the reference. The
151 :     # default goal is to save one member of each lineage. If
152 :     # the initial representative of the lineage is seq1, we
153 :     # pose the question, "Are there sufficiently deep divisions
154 :     # within the lineage to seq1 that it they might be viewed
155 :     # as independent? That is, might there be another sequence,
156 :     # seq2 that so different from seq1 that we might want to see
157 :     # it also?
158 :     #
159 :     # +---------------------- ref
160 :     # |
161 :     # ---+ +-------------------- seq1
162 :     # +-+
163 :     # +-------------------- seq2
164 :     #
165 :     # Without any special treatment, if the similarity of seq1
166 :     # to ref ( S(seq1,ref) ) is greater than max_sim, seq1 would
167 :     # be the sole representative of thelineage containing both
168 :     # seq1 and seq2, because the similarity of seq1 to seq2
169 :     # ( S(seq1,seq2) ) is greater than S(seq1,ref). This can
170 :     # be altered by the value of save_exp. In terms of
171 :     # similarity, seq2 will be discarded if:
172 :     #
173 :     # S(seq1,seq2) > S(seq1,ref) ** save_exp, and
174 :     # S(seq1,seq2) > S(seq2,ref) ** save_exp
175 :     #
176 :     # The default behavior described above occurs when save_exp
177 :     # is 1. If save_exp < 1, then greater similarities between
178 :     # seq1 and seq2 are allowed. Reasonable values of save_exp
179 :     # are roughly 0.7 to 1.0. (At save_exp = 0, any similarity
180 :     # would be allowed; yuck.)
181 :     #
182 : golsen 1.2 # stable (representative_sequences only; always true for rep_seq_2)
183 :     # If true (not undef, '', or 0), then the representatives
184 : golsen 1.1 # will be chosen from as early in the list as possible (this
185 : golsen 1.2 # facilitates augmentation of an existing list).
186 : golsen 1.1 #
187 :     #-------------------------------------------------------------------------------
188 :     #
189 : golsen 1.2 # Diagram of the pruning behavior of representative_sequences():
190 : golsen 1.1 #
191 :     # 0.5 0.6 0.7 0.8 0.9 1.0 Similarity
192 :     # |---------|---------|---------|---------|---------|
193 :     # .
194 :     # . + A
195 :     # . +---+
196 :     # . | + B
197 :     # . +---+
198 :     # . | +---- C
199 :     # . +----------+
200 :     # . | +-------- D
201 :     # . |
202 :     # +-----------+ +----------------- E
203 :     # | . +-+
204 :     # | . +----------------- F
205 :     # +----------------+ .
206 :     # | | . +--------------------------- G
207 :     # | +---+
208 :     # | . | +--------------------- H
209 :     # --+ . +-----+
210 :     # | . +--------------------- I
211 :     # | .
212 :     # | +------------------------------- J
213 :     # +----------------+ .
214 :     # | . +--------------------------- K
215 :     # +---+
216 :     # . +--------------------------- L
217 :     # .
218 :     # |---------|---------|---------|---------|---------|
219 :     # 0.5 0.6 0.7 0.8 0.9 1.0 Similarity
220 :     #
221 :     # In the above tree and max_sim = 0.70 and max_ref_sim = 0.99:
222 :     #
223 :     # With no reference sequence, and A first in the list, the representative
224 :     # sequences will be A, G, J and K.
225 :     #
226 :     # With A as the reference sequence and save_exp left at its default, the
227 :     # representative sequences will be A, C, D, E, G, J and K. B is excluded
228 :     # because it is more similar than max_ref_sim to A.
229 :     #
230 :     # With A as the reference sequence and save_exp = 0.8, the representative
231 :     # sequences will be A, C, D, E, F (comparably similar to A and E), G,
232 :     # H (comparably similar to A and G), J and K. The sequence L will be
233 :     # represented by K because L is much closer to K than to A.
234 :     #
235 :     # This oversimplifies the choice of representative of a cluster of related
236 :     # sequences. For example, whether G, H or I would represent the group of
237 :     # three actually depends on relative clock speed (slower is better) and
238 :     # sequence coverage (more complete is better). The actual order is by BLAST
239 :     # bit score (possibly combining independent segments).
240 :     #
241 :     # In addition, this discussion is in terms of a tree, but the calculations
242 :     # are based on a (partial) set of pairwise sequence similarities. Thus, the
243 :     # precise behavior is hard to predict, but should be similar to that described
244 :     # above.
245 :     #
246 :     #-------------------------------------------------------------------------------
247 :     #
248 :     # To construct a representative set of sequences relative to a reference
249 :     # sequence:
250 :     #
251 :     # 1. Prioritize sequences for keeping, from highest to lowest scoring
252 :     # relative to reference, as measured by blast score (bits).
253 :     # When stable is set, priority is from first to last in input file
254 :     # (a reference sequence should not be supplied).
255 :     #
256 :     # 2. Based on the similarity of each sequence to the reference and save_exp,
257 :     # compute sequence-specific values of max_sim:
258 :     #
259 :     # max_sim( seq_i ) = exp( save_exp * ln( seq_i_ref_sim ) )
260 :     #
261 :     # 3. Examine the next prioritized sequence (seq1).
262 :     #
263 :     # 4. If seq1 has been vetoed, go to 7.
264 :     #
265 :     # 5. Mark seq1 to keep.
266 :     #
267 :     # 6. Use blast to find similarities of seq1 to other sequences.
268 :     #
269 :     # 7. For each similar sequence (seq2):
270 :     #
271 :     # 7a. Skip if seq2 is marked to keep, or marked for veto
272 :     #
273 :     # 7b. Compute the maximum simiarity of seq1 and seq2 for retaining seq2:
274 :     #
275 :     # max_sim_1_2 = max( max_sim, max_sim( seq1 ), max_sim( seq2 ) )
276 :     #
277 :     # 7c. If similarity of seq1 and seq2 > max_sim, veto seq2
278 :     #
279 :     # 7d. Next seq2
280 :     #
281 :     # 8. If there are more sequences to examine, go to 3.
282 :     #
283 :     # 9. Collect the sequences marked for keeping.
284 :     #
285 :     #===============================================================================
286 :    
287 : golsen 1.5 #===============================================================================
288 :     # Build or add to a set of representative sequences. The difference of
289 :     # rep_seq_2 and rep_seq is that rep_seq can have multiple representatives
290 :     # in the blast database for a given group. This helps prevent fragmentation
291 :     # of clusters.
292 :     #
293 :     # \@reps = rep_seq( \@reps, \@new, \%options );
294 :     # \@reps = rep_seq( \@new, \%options );
295 :     #
296 :     # or
297 :     #
298 :     # ( \@reps, \%representing ) = rep_seq( \@reps, \@new, \%options );
299 :     # ( \@reps, \%representing ) = rep_seq( \@new, \%options );
300 :     #
301 :     #===============================================================================
302 :    
303 :     sub rep_seq
304 :     {
305 :     ref $_[0] eq 'ARRAY'
306 :     or print STDERR "First parameter of rep_seq must be an ARRAY reference\n"
307 :     and return undef;
308 :    
309 :     my ( $reps, $seqs, $options ) = ( [], undef, {} );
310 : golsen 1.1
311 : golsen 1.5 if ( @_ == 1 )
312 : golsen 1.1 {
313 : golsen 1.5 $seqs = shift;
314 : golsen 1.1 }
315 : golsen 1.5
316 :     elsif ( @_ == 2 )
317 : golsen 1.1 {
318 : golsen 1.5 if ( ref $_[1] eq 'ARRAY' ) { ( $reps, $seqs ) = @_ }
319 :     elsif ( ref $_[1] eq 'HASH' ) { ( $seqs, $options ) = @_ }
320 :     else
321 :     {
322 :     print STDERR "Second parameter of rep_seq must be an ARRAY or HASH reference\n";
323 :     return undef;
324 :     }
325 : golsen 1.1 }
326 :    
327 : golsen 1.5 elsif ( @_ == 3 )
328 :     {
329 :     if ( ref $_[1] ne 'ARRAY' )
330 :     {
331 :     print STDERR "Second parameter of 3 parameter rep_seq must be an ARRAY reference\n";
332 :     return undef;
333 :     }
334 :     if ( ref $_[2] ne 'HASH' )
335 :     {
336 :     print STDERR "Third parameter of 3 parameter rep_seq must be a HASH reference\n";
337 :     return undef;
338 :     }
339 : golsen 1.1
340 : golsen 1.5 ( $reps, $seqs, $options ) = @_;
341 :     }
342 :     else
343 : golsen 1.1 {
344 : golsen 1.5 print STDERR "rep_seq called with @{[scalar @_]} parameters\n";
345 :     return undef;
346 : golsen 1.1 }
347 :    
348 :     # ---------------------------------------# Default values for options
349 :    
350 : golsen 1.8 my $by_size = undef; # Analyze sequences in order provided
351 : golsen 1.5 my $max_sim = 0.80; # Retain 80% identity of less
352 :     my $logfile = undef; # Log file of sequences processed
353 :     my $max_e_val = 0.01; # Blast E-value to decrease output
354 :     my $sim_meas = 'identity_fraction'; # Use sequence identity as measure
355 : golsen 1.1
356 :     # Two questionable decisions:
357 :     # 1. Be painfully flexible on option names.
358 :     # 2. Silently fix bad parameter values.
359 :    
360 :     foreach ( keys %$options )
361 :     {
362 : golsen 1.5 my $value = $options->{ $_ };
363 :     if ( m/^log/i ) # logfile
364 :     {
365 :     next if ! $value;
366 :     $logfile = ( ref $value eq "GLOB" ? $value : \*STDOUT );
367 :     select( ( select( $logfile ), $| = 1 )[0] ); # autoflush on
368 :     }
369 :     elsif ( m/max/i && m/sim/i ) # max(imum)_sim(ilarity)
370 :     {
371 :     $value += 0;
372 :     $value = 0 if $value < 0;
373 :     $value = 1 if $value > 1;
374 :     $max_sim = $value;
375 :     }
376 :     elsif ( m/max/i || m/[ep]_?val/i ) # Other "max" tests must come first
377 :     {
378 :     $value += 0;
379 :     $value = 0 if $value < 0;
380 :     $max_e_val = $value;
381 :     }
382 :     elsif ( m/sim/i || m/meas/i ) # sim(ilarity)_meas(ure)
383 :     {
384 :     $sim_meas = standardize_similarity_measure( $value );
385 :     }
386 :     elsif ( m/save_?te?mp/i ) # group temporary files
387 :     {
388 :     $options->{ savetmp } = 1;
389 :     }
390 : golsen 1.8 elsif ( m/size/i ) # add longest to shortest
391 :     {
392 :     $by_size = 1;
393 :     }
394 : golsen 1.5 else
395 :     {
396 :     print STDERR "WARNING: rep_seq bad option ignored: '$_' => '$value'\n";
397 :     }
398 : golsen 1.1 }
399 :    
400 : golsen 1.5 # Check sequence ids for duplicates:
401 : golsen 1.1
402 : golsen 1.5 my $reps2 = [];
403 :     my $seen = {};
404 : golsen 1.1
405 : golsen 1.5 my $id;
406 :     foreach ( @$reps )
407 :     {
408 :     $id = $_->[0];
409 :     if ( $seen->{ $id }++ )
410 :     {
411 :     print STDERR "Duplicate sequence id '$id' skipped by rep_seq\n";
412 :     }
413 :     else
414 :     {
415 :     push @$reps2, $_;
416 :     }
417 :     }
418 : golsen 1.1
419 : golsen 1.5 my $seqs2 = [];
420 :     foreach ( @$seqs )
421 :     {
422 :     $id = $_->[0];
423 :     if ( $seen->{ $id }++ )
424 :     {
425 : golsen 1.6 print STDERR "Duplicate sequence id '$id' skipped by rep_seq\n";
426 : golsen 1.5 }
427 :     else
428 :     {
429 :     push @$seqs2, $_;
430 :     }
431 :     }
432 : golsen 1.1
433 : golsen 1.8 if ( $by_size )
434 :     {
435 :     @$reps2 = sort { length( $b->[2] ) <=> length( $a->[2] ) } @$reps2;
436 :     }
437 :    
438 : golsen 1.5 # If no preexisting representatives, then take first sequence:
439 : golsen 1.1
440 : golsen 1.5 @$reps2 or ( @$reps2 = shift @$seqs2 );
441 : golsen 1.1
442 : golsen 1.5 if ( $logfile ) { foreach ( @$reps2 ) { print $logfile "$_->[0]\n" } }
443 : golsen 1.1
444 : golsen 1.5 # Search each rep sequence against itself to get max_bpp
445 : golsen 1.1
446 : golsen 1.5 my ( $tmp_dir, $save_tmp ) = &tmp_dir( $options );
447 :     $tmp_dir or print STDERR "Unable to locate temporary file directory\n"
448 :     and return;
449 :     my $db = "$tmp_dir/tmp_blast_db_$$";
450 :     my $protein = are_protein( $reps2 );
451 :     my %max_bpp;
452 :     my $entry;
453 :     foreach $entry ( @$reps2 )
454 :     {
455 :     $max_bpp{ $entry->[0] } = self_bpp( $db, $entry, $protein );
456 :     }
457 : golsen 1.1
458 : golsen 1.5 my $naln = 10; # Alignments to make
459 :     my $self = 1; # Self match will never occur
460 :     my $prog = $protein ? 'blastp' : 'blastn';
461 :     my $blast_opt = "-e $max_e_val -v $naln -b $naln -F F -a 2";
462 :     $blast_opt .= " -r 1 -q -1" if ! $protein;
463 : golsen 1.1
464 : golsen 1.5 # List of who is represented by a sequence:
465 : golsen 1.1
466 : golsen 1.5 my %group = map { $_->[0] => [] } @$reps2;
467 : golsen 1.1
468 : golsen 1.5 # Groups can have more than one representative in the blast database:
469 : golsen 1.1
470 : golsen 1.5 my $rep4blast = [ @$reps2 ]; # initial reps
471 :     my %group_id = map { $_->[0] => $_->[0] } @$reps2; # represent self
472 : golsen 1.1
473 : golsen 1.5 # Search each sequence against the database.
474 : golsen 1.1
475 : golsen 1.5 my ( $seq, $bpp_max, $sid, $gid );
476 :     my $newdb = 1;
477 : golsen 1.1
478 : golsen 1.5 foreach $entry ( @$seqs2 )
479 :     {
480 :     # Is it time to rebuild a BLAST database?
481 : golsen 1.1
482 : golsen 1.5 if ( $newdb )
483 :     {
484 :     make_blast_db( $db, $rep4blast, $protein );
485 :     $newdb = 0;
486 :     }
487 : golsen 1.1
488 : golsen 1.5 # Do the blast analysis. Returned records are of the form:
489 :     #
490 :     # 0 1 2 3 4 5 6 7 8 9 10 11
491 :     # [ qid, qdef, qlen, sid, sdef, slen, scr, e_val, n_mat, n_id, n_pos, n_gap ]
492 :     #
493 :     # $tophit = [ $score, $blast_record, $surething ]
494 : golsen 1.1
495 : golsen 1.5 $id = $entry->[0];
496 :     $seq = $entry->[2];
497 :     my ( $tophit ) = sort { $b->[0] <=> $a->[0] }
498 :     map { in_group( $_, $max_sim, $sim_meas, $max_bpp{ $_->[3] } ) }
499 :     top_blast_per_subject( $prog, $db, $id, $seq, $self, $blast_opt );
500 : golsen 1.1
501 : golsen 1.5 # It matches an existing representative
502 : golsen 1.1
503 : golsen 1.5 if ( $tophit )
504 :     {
505 :     $sid = $tophit->[1]->[3]; # id of the best matching sequence
506 :     $gid = $group_id{ $sid }; # look up representative for group
507 :     push @{ $group{ $gid } }, $id; # add sequence to list in group
508 :     $group_id{ $id } = $gid; # record group for id
509 :     print $logfile "$id\t$gid\n" if $logfile;
510 :    
511 :     # Add sequence to blast database if it is not a 'surething'
512 :    
513 :     if ( ! $tophit->[2] )
514 :     {
515 :     push @$rep4blast, $entry;
516 :     $max_bpp{ $id } = self_bpp( $db, $entry, $protein ) if $sim_meas =~ /^sc/;
517 :     $newdb = 1;
518 :     }
519 :     }
520 : golsen 1.1
521 : golsen 1.5 # It is a new representative
522 : golsen 1.1
523 : golsen 1.5 else
524 :     {
525 :     push @$reps2, $entry;
526 :     push @$rep4blast, $entry;
527 :     $group{ $id } = [];
528 :     $group_id{ $id } = $id; # represent self
529 :     $max_bpp{ $id } = self_bpp( $db, $entry, $protein ) if $sim_meas =~ /^sc/;
530 :     $newdb = 1;
531 :     print $logfile "$id\n" if $logfile;
532 :     }
533 : golsen 1.1 }
534 :    
535 : golsen 1.5 if ( $save_tmp ) {} # This is not used, might be in future
536 :     elsif ( $protein ) { unlink $db, "$db.psq", "$db.pin", "$db.phr" }
537 :     else { unlink $db, "$db.nsq", "$db.nin", "$db.nhr" }
538 : golsen 1.1
539 : golsen 1.5 # Return the surviving sequence entries, and optionally the hash of
540 :     # ids represented by each survivor:
541 :    
542 :     wantarray ? ( $reps2, \%group ) : $reps2;
543 :     }
544 : golsen 1.1
545 :    
546 : golsen 1.5 #===============================================================================
547 :     # Caluculate sequence similarity according to the requested measure, and return
548 :     # empty list if lower than max_sim. Otherwise, return the hit and and
549 :     # whether the hit is really strong:
550 :     #
551 :     # [ $score, $hit, $surething ] = in_group( $hit, $max_sim, $measure, $bpp_max )
552 :     # () = in_group( $hit, $max_sim, $measure, $bpp_max )
553 :     #
554 :     # $hit is a structure with blast information:
555 :     #
556 :     # [ qid, qdef, qlen, sid, sdef, slen, scr, e_val, n_mat, n_id, n_pos, n_gap ]
557 :     #
558 :     # The surething is the similarity for which $max_sim is 4 standard deviations
559 :     # lower.
560 :     #===============================================================================
561 : golsen 1.1
562 : golsen 1.5 sub in_group
563 :     { my ( $hit, $max_sim, $measure, $bpp_max ) = @_;
564 : golsen 1.1
565 : golsen 1.5 my $n = $hit->[8]; # aligned positions
566 :     return () if ( $n <= 0 );
567 : golsen 1.1
568 : golsen 1.5 my $m; # matched positions
569 : golsen 1.1
570 : golsen 1.5 if ( $measure =~ /^sc/ ) { $m = $hit->[ 6] / ( $bpp_max || 2 ) } # score/pos
571 :     elsif ( $measure =~ /^po/ ) { $m = $hit->[10] } # positives
572 :     else { $m = $hit->[ 9] } # identities
573 : golsen 1.1
574 : golsen 1.5 return () if $m < ( $max_sim * $n );
575 : golsen 1.1
576 : golsen 1.5 my $u = ( $n > $m ) ? ( $n - $m ) : 0; # differing positions
577 :     my $stddev = sqrt( $m * $u / $n );
578 :     my $conf = 4; # standard deviations for "surething"
579 :     $max_sim = 0.01 if $max_sim < 0.01;
580 :     my $surething = ( $u + $conf * $stddev ) <= ( ( 1 - $max_sim ) * $n ) ? 1 : 0;
581 : golsen 1.1
582 : golsen 1.5 [ $m/$n, $hit, $surething ]
583 : golsen 1.1 }
584 :    
585 :    
586 :     #===============================================================================
587 :     # Build or add to a set of representative sequences.
588 :     #
589 :     # \@reps = rep_seq_2( \@reps, \@new, \%options );
590 :     # \@reps = rep_seq_2( \@new, \%options );
591 :     #
592 :     # or
593 :     #
594 :     # ( \@reps, \%representing ) = rep_seq_2( \@reps, \@new, \%options );
595 :     # ( \@reps, \%representing ) = rep_seq_2( \@new, \%options );
596 :     #
597 :     #===============================================================================
598 :    
599 :     sub rep_seq_2
600 :     {
601 :     ref $_[0] eq 'ARRAY'
602 :     or print STDERR "First parameter of rep_seq_2 must be an ARRAY reference\n"
603 :     and return undef;
604 :    
605 :     my ( $reps, $seqs, $options ) = ( [], undef, {} );
606 :    
607 :     if ( @_ == 1 )
608 :     {
609 :     $seqs = shift;
610 :     }
611 :    
612 :     elsif ( @_ == 2 )
613 :     {
614 :     if ( ref $_[1] eq 'ARRAY' ) { ( $reps, $seqs ) = @_ }
615 :     elsif ( ref $_[1] eq 'HASH' ) { ( $seqs, $options ) = @_ }
616 :     else
617 :     {
618 :     print STDERR "Second parameter of rep_seq_2 must be an ARRAY or HASH reference\n";
619 :     return undef;
620 :     }
621 :     }
622 :    
623 :     elsif ( @_ == 3 )
624 :     {
625 :     if ( ref $_[1] ne 'ARRAY' )
626 :     {
627 :     print STDERR "Second parameter of 3 parameter rep_seq_2 must be an ARRAY reference\n";
628 :     return undef;
629 :     }
630 :     if ( ref $_[2] ne 'HASH' )
631 :     {
632 :     print STDERR "Third parameter of 3 parameter rep_seq_2 must be a HASH reference\n";
633 :     return undef;
634 :     }
635 :    
636 :     ( $reps, $seqs, $options ) = @_;
637 :     }
638 :     else
639 :     {
640 :     print STDERR "rep_seq_2 called with @{[scalar @_]} parameters\n";
641 :     return undef;
642 :     }
643 :    
644 :     # ---------------------------------------# Default values for options
645 :    
646 : golsen 1.8 my $by_size = undef; # Analyze sequences in order provided
647 :     my $max_sim = 0.80; # Retain 80% identity of less
648 : golsen 1.1 my $logfile = undef; # Log file of sequences processed
649 :     my $max_e_val = 0.01; # Blast E-value to decrease output
650 :     my $sim_meas = 'identity_fraction'; # Use sequence identity as measure
651 :    
652 :     # Two questionable decisions:
653 :     # 1. Be painfully flexible on option names.
654 :     # 2. Silently fix bad parameter values.
655 :    
656 :     foreach ( keys %$options )
657 :     {
658 : golsen 1.5 my $value = $options->{ $_ };
659 :     if ( m/^log/i ) # logfile
660 :     {
661 :     next if ! $value;
662 :     $logfile = ( ref $value eq "GLOB" ? $value : \*STDOUT );
663 :     select( ( select( $logfile ), $| = 1 )[0] ); # autoflush on
664 :     }
665 :     elsif ( m/max/i && m/sim/i ) # max(imum)_sim(ilarity)
666 :     {
667 :     $value += 0;
668 :     $value = 0 if $value < 0;
669 :     $value = 1 if $value > 1;
670 :     $max_sim = $value;
671 :     }
672 :     elsif ( m/max/i || m/[ep]_?val/i ) # Other "max" tests must come first
673 :     {
674 :     $value += 0;
675 :     $value = 0 if $value < 0;
676 :     $max_e_val = $value;
677 :     }
678 :     elsif ( m/sim/i || m/meas/i ) # sim(ilarity)_meas(ure)
679 :     {
680 :     $sim_meas = standardize_similarity_measure( $value );
681 :     }
682 : golsen 1.8 elsif ( m/by_?size/i || m/size/i ) # add longest to shortest
683 :     {
684 :     $by_size = 1;
685 :     }
686 : golsen 1.5 else
687 :     {
688 :     print STDERR "WARNING: rep_seq_2 bad option ignored: '$_' => '$value'\n";
689 :     }
690 : golsen 1.1 }
691 :    
692 :     # Check sequence ids for duplicates:
693 :    
694 :     my $reps2 = [];
695 :     my $seen = {};
696 :    
697 :     my $id;
698 :     foreach ( @$reps )
699 :     {
700 :     $id = $_->[0];
701 :     if ( $seen->{ $id }++ )
702 :     {
703 :     print STDERR "Duplicate sequence id '$id' skipped by rep_seq_2\n";
704 :     }
705 :     else
706 :     {
707 :     push @$reps2, $_;
708 :     }
709 :     }
710 :    
711 :     my $seqs2 = [];
712 :     foreach ( @$seqs )
713 :     {
714 :     $id = $_->[0];
715 :     if ( $seen->{ $id }++ )
716 :     {
717 : golsen 1.6 print STDERR "Duplicate sequence id '$id' skipped by rep_seq_2\n";
718 : golsen 1.1 }
719 :     else
720 :     {
721 :     push @$seqs2, $_;
722 :     }
723 :     }
724 :    
725 : golsen 1.8 if ( $by_size )
726 :     {
727 :     @$reps2 = sort { length( $b->[2] ) <=> length( $a->[2] ) } @$reps2;
728 :     }
729 :    
730 : golsen 1.1 # If no preexisting representatives, then take first sequence:
731 :    
732 :     @$reps2 or @$reps2 = ( shift @$seqs2 );
733 :    
734 :     if ( $logfile ) { foreach ( @$reps2 ) { print $logfile "$_->[0]\n" } }
735 :    
736 :     # Search each rep sequence against itself for max_bpp
737 :    
738 : golsen 1.5 my ( $tmp_dir, $save_tmp ) = &tmp_dir( $options );
739 :     $tmp_dir or print STDERR "Unable to locate temporary file directory\n"
740 :     and return;
741 :     my $db = "$tmp_dir/tmp_blast_db_$$";
742 : golsen 1.1 my $protein = are_protein( $reps2 );
743 :     my %max_bpp;
744 :     my $entry;
745 :     foreach $entry ( @$reps2 )
746 :     {
747 :     $max_bpp{ $entry->[0] } = self_bpp( $db, $entry, $protein );
748 :     }
749 :    
750 :     my $naln = 10; # Alignments to make
751 :     my $self = 1; # Self match will never occur
752 :     my $prog = $protein ? 'blastp' : 'blastn';
753 :     my $blast_opt = "-e $max_e_val -v $naln -b $naln -F F -a 2";
754 :     $blast_opt .= " -r 1 -q -1" if ! $protein;
755 :    
756 :     # List of who is represented by a sequence:
757 :    
758 : golsen 1.5 my %group = map { $_->[0] => [] } @$reps2;
759 : golsen 1.1
760 :     # Search each sequence against the database.
761 :    
762 :     my ( $seq, $bpp_max );
763 :     my $newdb = 1;
764 :    
765 :     foreach $entry ( @$seqs2 )
766 :     {
767 : golsen 1.5 # Is it time to rebuild a BLAST database?
768 :    
769 :     if ( $newdb )
770 :     {
771 :     make_blast_db( $db, $reps2, $protein );
772 :     $newdb = 0;
773 :     }
774 : golsen 1.1
775 :     # Do the blast analysis. Returned records are of the form:
776 :     #
777 :     # 0 1 2 3 4 5 6 7 8 9 10 11
778 :     # [ qid, qdef, qlen, sid, sdef, slen, scr, e_val, n_mat, n_id, n_pos, n_gap ]
779 :    
780 : golsen 1.5 $id = $entry->[0];
781 :     $seq = $entry->[2];
782 : golsen 1.1 my ( $tophit ) = sort { $b->[0] <=> $a->[0] }
783 :     grep { $_->[0] >= $max_sim }
784 :     map { [ seq_similarity( $_, $sim_meas, $max_bpp{ $_->[3] } ), $_ ] }
785 :     top_blast_per_subject( $prog, $db, $id, $seq, $self, $blast_opt );
786 :    
787 :    
788 :     # It matches an existing representative
789 :    
790 : golsen 1.5 if ( $tophit )
791 :     {
792 :     # print STDERR join(", ", $tophit->[0], @{$tophit->[1]} ), "\n";
793 :     push @{ $group{ $tophit->[1]->[3] } }, $id;
794 :     print $logfile "$id\t$tophit->[1]->[3]\n" if $logfile;
795 :     }
796 :    
797 :     # It is a new representative
798 :    
799 :     else
800 :     {
801 :     push @$reps2, $entry;
802 :     $group{ $id } = [];
803 :     $max_bpp{ $id } = self_bpp( $db, $entry, $protein );
804 :     $newdb = 1;
805 :     print $logfile "$id\n" if $logfile;
806 :     }
807 : golsen 1.1 }
808 :    
809 : golsen 1.5 if ( $save_tmp ) {} # This is not used, might be in future
810 :     elsif ( $protein ) { unlink $db, "$db.psq", "$db.pin", "$db.phr" }
811 :     else { unlink $db, "$db.nsq", "$db.nin", "$db.nhr" }
812 : golsen 1.1
813 :     # Return the surviving sequence entries, and optionally the hash of
814 :     # ids represented by each survivor:
815 :    
816 : golsen 1.5 wantarray ? ( $reps2, \%group ) : $reps2;
817 :     }
818 :    
819 :    
820 :     #===============================================================================
821 :     # Construct a representative set of related sequences:
822 :     #
823 :     # \@repseqs = representative_sequences( $ref, \@seqs, $max_sim, \%options );
824 :     #
825 :     # or
826 :     #
827 :     # ( \@repseqs, \%representing, \@low_sim ) = representative_sequences( $ref,
828 :     # \@seqs, $max_sim, \%options );
829 :     #
830 :     #===============================================================================
831 :     sub representative_sequences {
832 :     my $seqs = ( shift @_ || shift @_ ); # If $ref is undef, shift again
833 :     ref( $seqs ) eq "ARRAY"
834 :     or die "representative_sequences called with bad first argument\n";
835 :    
836 :     my ( $ref, $use_ref );
837 :     if ( ! ref( $seqs->[0] ) ) # First item was sequence entry, not list of entries
838 :     {
839 :     $ref = $seqs;
840 :     $seqs = shift @_;
841 :     ref( $seqs ) eq "ARRAY"
842 :     and ref( $seqs->[0] ) eq "ARRAY"
843 :     or die "representative_sequences called with bad sequences list\n";
844 :     $use_ref = 1;
845 :     }
846 :     else # First item was list of entries, split off first
847 :     {
848 :     ref( $seqs->[0] ) eq "ARRAY"
849 :     or die "representative_sequences called with bad sequences list\n";
850 :     $ref = shift @$seqs;
851 :     $use_ref = 0;
852 :     }
853 :    
854 :     my $max_sim = shift @_;
855 :     my $options;
856 :    
857 :     # Undocumented feature: skip max_sim (D = 0.8)
858 :    
859 :     if ( ref( $max_sim ) eq "HASH" )
860 :     {
861 :     $options = $max_sim;
862 :     $max_sim = undef;
863 :     }
864 :    
865 :     # If the above did not give us options, get them now:
866 :    
867 :     $options ||= ( shift @_ ) || {};
868 :    
869 :     # ---------------------------------------# Default values for options
870 :    
871 :     $max_sim ||= 0.80; # Retain 80% identity of less
872 :     my $logfile = undef; # Log file of sequences processed
873 :     my $max_ref_sim = 0.99; # Get rid of identical sequences
874 :     my $max_e_val = 0.01; # Blast E-value to decrease output
875 :     my $sim_meas = 'identity_fraction'; # Use sequence identity as measure
876 :     my $save_exp = 1.0; # Don't retain near equivalents
877 :     my $stable = 0; # Pick reps input order
878 :    
879 :     # Two questionable decisions:
880 :     # 1. Be painfully flexible on option names.
881 :     # 2. Silently fix bad parameter values.
882 :    
883 :     foreach ( keys %$options )
884 :     {
885 :     my $value = $options->{ $_ };
886 :     if ( m/^log/i ) # logfile
887 :     {
888 :     next if ! $value;
889 :     $logfile = ( ref $value eq "GLOB" ? $value : \*STDOUT );
890 :     select( ( select( $logfile ), $| = 1 )[0] ); # autoflush on
891 :     }
892 :     elsif ( m/ref/i ) # max_ref_sim
893 :     {
894 :     $value += 0;
895 :     $value = 0 if $value < 0;
896 :     $value = 1 if $value > 1;
897 :     $max_ref_sim = $value;
898 :     }
899 :     elsif ( m/max/i && m/sim/i ) # max(imum)_sim(ilarity)
900 :     {
901 :     $value += 0;
902 :     $value = 0 if $value < 0;
903 :     $value = 1 if $value > 1;
904 :     $max_sim = $value;
905 :     }
906 :     elsif ( m/max/i || m/[ep]_?val/i ) # Other "max" tests must come first
907 :     {
908 :     $value += 0;
909 :     $value = 0 if $value < 0;
910 :     $max_e_val = $value;
911 :     }
912 :     elsif ( m/sim/i || m/meas/i ) # sim(ilarity)_meas(ure)
913 :     {
914 :     $sim_meas = standardize_similarity_measure( $value );
915 :     }
916 :     elsif ( m/sav/i || m/exp/i ) # save_exp(onent)
917 :     {
918 :     $value += 0;
919 :     $value = 0 if $value < 0;
920 :     $value = 1 if $value > 1;
921 :     $save_exp = $value;
922 :     }
923 :     elsif ( m/stab/i ) # stable order
924 :     {
925 :     $stable = $value ? 1 : 0;
926 :     }
927 :     else
928 :     {
929 :     print STDERR "WARNING: representative_sequences bad option ignored: '$_' => '$value'\n";
930 :     }
931 :     }
932 :    
933 :     # Silent sanity check. This should not happen, as it is almost equivalent
934 :     # to making no reference sequence.
935 :    
936 :     $max_ref_sim = $max_sim if ( $max_ref_sim < $max_sim );
937 :    
938 :     # Do the analysis
939 :    
940 :     my $ref_id = $ref->[0];
941 :     my $ref_seq = $ref->[2];
942 :    
943 :     # Build a list of the ids (without ref) and an index for the sequence entries:
944 :    
945 :     my @seq_id = map { $_->[0] } @$seqs;
946 :     my $seq_ind = { map { @{$_}[0] => $_ } ( $ref, @$seqs ) };
947 :    
948 :     # Make a lookup table of the sequence number, for use in reording
949 :     # sequences later:
950 :    
951 :     my $n = 0;
952 :     my %ord = ( map { @$_[0] => ++$n } @$seqs );
953 :    
954 :     # Build blast database (it includes the reference):
955 :    
956 :     my $protein = are_protein( $seqs );
957 :     my ( $tmp_dir, $save_tmp ) = &tmp_dir( $options );
958 :     $tmp_dir or print STDERR "Unable to locate temporary file directory\n"
959 :     and return;
960 :     my $db = "$tmp_dir/tmp_blast_db_$$";
961 :     make_blast_db( $db, [ $ref, @$seqs ], $protein );
962 :    
963 :     # Search query against new database
964 :    
965 :     my $max = 3 * @$seqs; # Alignments to keep
966 :     my $self = 1; # Keep self match (for its bit score)
967 :    
968 :     my $blast_opt = "-e $max_e_val -v $max -b $max -F F -a 2";
969 :    
970 :     # Do the blast analysis. Returned records are of the form:
971 :     #
972 :     # 0 1 2 3 4 5 6 7 8 9 10 11
973 :     # [ qid, qdef, qlen, sid, sdef, slen, scr, e_val, n_mat, n_id, n_pos, n_gap ]
974 :    
975 :     my $prog = $protein ? 'blastp' : 'blastn';
976 :     $blast_opt .= " -r 1 -q -1" if ! $protein;
977 :     my @ref_hits = top_blast_per_subject( $prog, $db, $ref_id, $ref_seq, $self, $blast_opt );
978 :    
979 :     # First hit is always a perfect match, so we get bits per position:
980 :     # This is only used if the measure is bits per position
981 :    
982 :     my $ref_bpp = $ref_hits[0]->[6] / $ref_hits[0]->[8];
983 :    
984 :     # Remove self match (might not be first if there are identical sequences):
985 :    
986 :     my %hit = ();
987 :     @ref_hits = grep { my $sid = $_->[3]; $hit{ $sid } = 1; ( $sid ne $ref_id ) } @ref_hits;
988 :    
989 :     my %group = ();
990 :     $group{ $ref_id } = [];
991 :     my %veto = ();
992 :     my $n_to_do = @ref_hits;
993 :     my $rebuild_d_n = 40;
994 :     my $last_rebuild = 1.5 * $rebuild_d_n;
995 :     my $rebuild = ( $n_to_do > $last_rebuild ) ? $n_to_do - $rebuild_d_n : 0;
996 :    
997 :     # Sequence-specific maximum similarities:
998 :    
999 :     my %max_sim = map { ( $_ => $max_sim ) } @seq_id;
1000 :    
1001 :     foreach ( @ref_hits )
1002 :     {
1003 :     my $id = $_->[3];
1004 :     my $sim = seq_similarity( $_, $sim_meas, $ref_bpp );
1005 :    
1006 :     if ( $sim > ( $use_ref ? $max_ref_sim : $max_sim ) )
1007 :     {
1008 :     $veto{ $id } = 1;
1009 :     push @{ $group{ $ref_id } }, $id; # Log the sequences represented
1010 :     $n_to_do--;
1011 :     }
1012 :     else
1013 :     {
1014 :     my $max_sim_i = exp( $save_exp * log( $sim ) );
1015 :     $max_sim{ $id } = $max_sim_i if ( $max_sim_i > $max_sim );
1016 :     }
1017 :     }
1018 :    
1019 :    
1020 :     if ( $logfile )
1021 :     {
1022 :     print $logfile join( "\t", $ref_id, @{ $group{ $ref_id } } ), "\n";
1023 :     }
1024 :    
1025 :     # Search each sequence against the database.
1026 :     # If the order is to be stable, reorder hits to match input order.
1027 :    
1028 :     my ( $id1, $seq1, $max_sim_1, $id2, $max_sim_2, $bpp_max );
1029 :     my @ids_to_do = map { $_->[3] } @ref_hits;
1030 :     @ids_to_do = sort { $ord{ $a } <=> $ord{ $b } } @ids_to_do if $stable;
1031 :    
1032 :     while ( $id1 = shift @ids_to_do )
1033 :     {
1034 :     next if $veto{ $id1 };
1035 :    
1036 :     # Is it time to rebuild a smaller BLAST database? This helps
1037 :     # significantly in the overall performance.
1038 :    
1039 :     if ( $n_to_do <= $rebuild )
1040 :     {
1041 :     if ( $protein ) { unlink $db, "$db.psq", "$db.pin", "$db.phr" }
1042 :     else { unlink $db, "$db.nsq", "$db.nin", "$db.nhr" }
1043 :     make_blast_db( $db, [ map { $seq_ind->{ $_ } } # id to sequence entry
1044 :     grep { ! $veto{ $_ } } # id not vetoed
1045 :     ( $id1, @ids_to_do ) # remaining ids
1046 :     ],
1047 :     $protein
1048 :     );
1049 :     $rebuild = ( $n_to_do > $last_rebuild ) ? $n_to_do - $rebuild_d_n : 0;
1050 :     }
1051 :    
1052 :     $n_to_do--;
1053 :     $group{ $id1 } = [];
1054 :    
1055 :     $max_sim_1 = $max_sim{ $id1 };
1056 :     $bpp_max = undef;
1057 :     $seq1 = $seq_ind->{$id1}->[2];
1058 :     foreach ( top_blast_per_subject( $prog, $db, $id1, $seq1, $self, $blast_opt ) )
1059 :     {
1060 :     $bpp_max ||= $_->[6] / $_->[8];
1061 :     $id2 = $_->[3];
1062 :     next if ( $veto{ $id2 } || $group{ $id2 } );
1063 :     $max_sim_2 = $max_sim{ $id2 };
1064 :     $max_sim_2 = $max_sim_1 if ( $max_sim_1 > $max_sim_2 );
1065 :     if ( seq_similarity( $_, $sim_meas, $bpp_max ) > $max_sim_2 )
1066 :     {
1067 :     $veto{ $id2 } = 1;
1068 :     push @{ $group{ $id1 } }, $id2; # Log the sequences represented
1069 :     $n_to_do--;
1070 :     }
1071 :     }
1072 :    
1073 :     if ( $logfile )
1074 :     {
1075 :     print $logfile join( "\t", $id1, @{ $group{ $id1 } } ), "\n";
1076 :     }
1077 :     }
1078 :    
1079 :     if ( $save_tmp ) {} # This is not used, might be in future
1080 :     elsif ( $protein ) { unlink $db, "$db.psq", "$db.pin", "$db.phr" }
1081 :     else { unlink $db, "$db.nsq", "$db.nin", "$db.nhr" }
1082 :    
1083 :     # Return the surviving sequence entries, and optionally the hash of
1084 :     # ids represented by each survivor:
1085 :    
1086 :     my $kept = [ $ref, grep { $group{ $_->[0] } } @$seqs ];
1087 :    
1088 :     wantarray ? ( $kept, \%group, [ grep { ! $hit{ $_->[0] } } @$seqs ] ) : $kept;
1089 : golsen 1.1 }
1090 :    
1091 :    
1092 :     #===============================================================================
1093 :     # Try to figure out the sequence similarity measure that is being requested:
1094 :     #
1095 :     # $type = standardize_similarity_measure( $requested_type )
1096 :     #
1097 :     #===============================================================================
1098 :    
1099 :     sub standardize_similarity_measure
1100 :     { my ( $req_meas ) = @_;
1101 :     return ( ! $req_meas ) ? 'identity_fraction'
1102 :     : ( $req_meas =~ /id/i ) ? 'identity_fraction'
1103 :     : ( $req_meas =~ /sc/i ) ? 'score_per_position'
1104 :     : ( $req_meas =~ /spp/i ) ? 'score_per_position'
1105 :     : ( $req_meas =~ /bit/i ) ? 'score_per_position'
1106 :     : ( $req_meas =~ /bpp/i ) ? 'score_per_position'
1107 :     : ( $req_meas =~ /tiv/i ) ? 'positive_fraction'
1108 :     : ( $req_meas =~ /pos_/i ) ? 'positive_fraction'
1109 :     : ( $req_meas =~ /ppp/i ) ? 'positive_fraction'
1110 :     : 'identity_fraction';
1111 :     }
1112 :    
1113 :    
1114 :     #===============================================================================
1115 :     # Caluculate sequence similarity according to the requested measure:
1116 :     #
1117 :     # $similarity = seq_similarity( $hit, $measure, $bpp_max )
1118 :     #
1119 :     # $hit is a structure with blast information:
1120 :     #
1121 :     # [ qid, qdef, qlen, sid, sdef, slen, scr, e_val, n_mat, n_id, n_pos, n_gap ]
1122 :     #===============================================================================
1123 :    
1124 :     sub seq_similarity
1125 :     { my ( $hit, $measure, $bpp_max ) = @_;
1126 :     return ( @$hit < 11 ) ? undef
1127 :     : ( $measure =~ /^sc/ ) ? $hit->[ 6] / ( $hit->[8] * ( $bpp_max || 2 ) )
1128 :     : ( $measure =~ /^po/ ) ? $hit->[10] / $hit->[8]
1129 :     : $hit->[ 9] / $hit->[8]
1130 :     }
1131 :    
1132 :    
1133 :     #===============================================================================
1134 :     # Caluculate self similarity of a sequence in bits per position:
1135 :     #
1136 :     # $max_bpp = self_bpp( $db_name, $entry, $protein )
1137 :     #
1138 :     #===============================================================================
1139 :    
1140 :     sub self_bpp
1141 :     {
1142 :     my ( $db, $entry, $protein ) = @_;
1143 :    
1144 :     # Build blast database:
1145 :    
1146 :     make_blast_db( $db, [ $entry ], $protein );
1147 :    
1148 :     # Search sequence against the database
1149 :    
1150 :     my $id = $entry->[0];
1151 :     my $seq = $entry->[2];
1152 :     my $self = 1; # Self match will never occur
1153 :    
1154 :     my $prog = $protein ? 'blastp' : 'blastn';
1155 :     my $blast_opt = "-v 1 -b 1 -F F -a 2";
1156 :     $blast_opt .= " -r 1 -q -1" if ! $protein;
1157 :    
1158 :     # Do the blast analysis. Returned records are of the form:
1159 :     #
1160 :     # 0 1 2 3 4 5 6 7 8 9 10 11
1161 :     # [ qid, qdef, qlen, sid, sdef, slen, scr, e_val, n_mat, n_id, n_pos, n_gap ]
1162 :    
1163 :     my ( $hit ) = top_blast_per_subject( $prog, $db, $id, $seq, $self, $blast_opt );
1164 :     # print STDERR join( ", ", @$hit ), "\n";
1165 :    
1166 :     # First hit is always a perfect match, so we get bits per position:
1167 :     # This is only used if the measure is bits per position
1168 : golsen 1.5
1169 : golsen 1.1 $hit->[6] / $hit->[8];
1170 :     }
1171 :    
1172 :    
1173 :     #===============================================================================
1174 :     # Make a blast databse from a set of sequence entries. The type of database
1175 :     # (protein or nucleic acid) is quessed from the sequence data.
1176 :     #
1177 :     # make_blast_db( $db_filename, \@seq_entries, $protein )
1178 :     #
1179 :     # Sequence entries have the form: [ $id, $def, $seq ]
1180 :     #===============================================================================
1181 :    
1182 :     sub make_blast_db
1183 :     { my ( $db, $seqs, $protein ) = @_;
1184 :    
1185 :     open FH, ">$db" or die "Could not create blast database file \"$db\"";
1186 :     foreach ( @$seqs )
1187 :     {
1188 : golsen 1.5 print FH ">$_->[0]", ( $_->[1] ? " $_->[1]" : () ), "\n$_->[2]\n";
1189 : golsen 1.1 }
1190 :     close FH;
1191 :    
1192 :     my $is_prot = $protein ? 'T' : 'F';
1193 :     system "$formatdb -p $is_prot -i '$db'";
1194 :     }
1195 :    
1196 :    
1197 :     #===============================================================================
1198 :     # The type of data (protein or nucleic acid) is quessed from the sequences.
1199 :     #
1200 :     # are_protein( \@seq_entries )
1201 :     #
1202 :     # Sequence entries have the form: [ $id, $def, $seq ]
1203 :     #===============================================================================
1204 :    
1205 :     sub are_protein
1206 :     { my ( $seqs ) = @_;
1207 :     my ( $nt, $aa ) = ( 0, 0 );
1208 :     foreach ( @$seqs )
1209 :     {
1210 : golsen 1.5 my $s = $_->[2];
1211 :     $nt += $s =~ tr/ACGTacgt//d;
1212 :     $aa += $s =~ tr/A-Za-z//d;
1213 : golsen 1.1 }
1214 :     ( $nt < 3 * $aa ) ? 1 : 0;
1215 :     }
1216 :    
1217 :    
1218 :     #===============================================================================
1219 :     # Blast a subject against a datbase, saving only top hit per subject
1220 :     #
1221 :     # Return:
1222 :     #
1223 :     # [ qid, qdef, qlen, sid, sdef, slen, scr, e_val, n_mat, n_id, n_pos, n_gap ]
1224 :     #
1225 :     #===============================================================================
1226 :    
1227 :     # Use a bare block to compartmentalize a counter:
1228 :    
1229 :     { my $cnt = 0;
1230 :    
1231 :     sub top_blast_per_subject
1232 :     { my ( $prog, $db, $qid, $qseq, $self, $blast_opt, $sort, $no_merge ) = @_;
1233 :    
1234 :     $cnt++;
1235 : golsen 1.5 my ( $tmp_dir, $save_tmp ) = &tmp_dir( );
1236 :     $tmp_dir or print STDERR "Unable to locate temporary file directory\n"
1237 :     and return;
1238 :     my $query_file = "$tmp_dir/tmp_blast_seq_${$}_$cnt";
1239 : golsen 1.1 my $QFILE;
1240 :     open $QFILE, ">$query_file" or die "Could not create sequence file \"$query_file\"";
1241 :     print $QFILE ">$qid\n$qseq\n";
1242 :     close $QFILE;
1243 :    
1244 :     my $blast_cmd = "$blastall -p $prog -d '$db' -i '$query_file' $blast_opt";
1245 : golsen 1.5
1246 : golsen 1.1 my $BPIPE;
1247 :     open $BPIPE, "$blast_cmd |" or die "Could open blast pipe\n";
1248 :     my $sims = integrate_blast_segments( $BPIPE, $sort, $no_merge, $self );
1249 :     close $BPIPE;
1250 : golsen 1.5 unlink $query_file if ! $save_tmp;
1251 : golsen 1.1
1252 :     my $pq = ""; # Previous query id
1253 :     my $ps = ""; # Previous subject id
1254 :     my $keep;
1255 :    
1256 :     grep { $keep = ( $pq ne $_->[0] ) || ( $ps ne $_->[3] );
1257 :     $pq = $_->[0];
1258 :     $ps = $_->[3];
1259 :     $keep && ( $self || ( $pq ne $ps ) );
1260 :     } @$sims;
1261 :     }
1262 :     }
1263 :    
1264 :    
1265 :     #===============================================================================
1266 :     # Read output of rationalize blast and assemble minimally overlapping segments
1267 :     # into a total score for each subject sequence. For each query, sort matches
1268 :     # into user-chosen order (D = total score):
1269 :     #
1270 :     # @sims = integrate_blast_segments( \*FILEHANDLE, $sort_order, $no_merge )
1271 :     # \@sims = integrate_blast_segments( \*FILEHANDLE, $sort_order, $no_merge )
1272 :     #
1273 :     # Allowed sort orders are 'score', 'score_per_position', 'identity_fraction',
1274 :     # and 'positive_fraction' (matched very flexibly).
1275 :     #
1276 :     # Returned sims (e_val is only for best HSP, not any composite):
1277 :     #
1278 :     # [ qid, qdef, qlen, sid, sdef, slen, scr, e_val, n_mat, n_id, n_pos, n_gap ]
1279 :     #
1280 :     # There is a strategic decision to not read the blast output from memory;
1281 :     # it could be enormous. This cuts the flexibility some.
1282 :     #===============================================================================
1283 :     #
1284 :     # coverage fields:
1285 :     #
1286 :     # [ scr, e_val, n_mat, n_id, n_pos, n_gap, dir, [ intervals_covered ] ]
1287 :     #
1288 :     #===============================================================================
1289 :    
1290 :     sub integrate_blast_segments
1291 :     { my ( $fh, $order, $no_merge, $self ) = @_;
1292 :     $fh ||= \*STDIN;
1293 :     ( ref( $fh ) eq "GLOB" ) || die "integrate_blast_segments called without a filehandle\n";
1294 :    
1295 :     $order = ( ! $order ) ? 'score'
1296 :     : ( $order =~ /sc/i ) ? ( $order =~ /p/i ? 'score_per_position' : 'score' )
1297 :     : ( $order =~ /bit/i ) ? ( $order =~ /p/i ? 'score_per_position' : 'score' )
1298 :     : ( $order =~ /spp/i ) ? 'score_per_position'
1299 :     : ( $order =~ /id/i ) ? 'identity_fraction'
1300 :     : ( $order =~ /tiv/i ) ? 'positive_fraction'
1301 :     : 'score';
1302 :    
1303 :     my $max_frac_overlap = 0.2;
1304 :    
1305 :     my ( $qid, $qdef, $qlen, $sid, $sdef, $slen );
1306 :     my ( $scr, $e_val, $n_mat, $n_id, $n_pos, $n_gap );
1307 :     my ( $ttl_scr, $ttl_mat, $ttl_id, $ttl_pos, $ttl_gap );
1308 :     my @sims = ();
1309 :     my @qsims = ();
1310 :     my $coverage = undef;
1311 :     my $record;
1312 :    
1313 :     while ( $_ = next_blast_record( $fh, $self ) )
1314 :     {
1315 : golsen 1.5 chomp;
1316 :     if ( $_->[0] eq 'Query=' )
1317 :     {
1318 :     if ( $coverage )
1319 :     {
1320 :     push @qsims, [ $sid, $sdef, $slen, @$coverage[ 0 .. 5 ] ];
1321 :     $coverage = undef;
1322 :     }
1323 :     if ( @qsims ) { push @sims, order_query_sims( $qid, $qdef, $qlen, \@qsims, $order ) }
1324 :     ( undef, $qid, $qdef, $qlen ) = @$_;
1325 :     $sid = undef;
1326 :     @qsims = ();
1327 :     }
1328 :     elsif ( $_->[0] eq '>' )
1329 :     {
1330 :     if ( $coverage )
1331 :     {
1332 :     push @qsims, [ $sid, $sdef, $slen, @$coverage[ 0 .. 5 ] ];
1333 :     $coverage = undef;
1334 :     }
1335 :     next if ! $qid;
1336 :     ( undef, $sid, $sdef, $slen ) = @$_;
1337 :     }
1338 :     elsif ( $_->[0] eq 'HSP' && $sid )
1339 :     {
1340 :     $coverage = integrate_HSP( $coverage, $_, $max_frac_overlap, $no_merge );
1341 :     }
1342 : golsen 1.1 }
1343 :    
1344 :     if ( $coverage ) { push @qsims, [ $sid, $sdef, $slen, @$coverage[ 0 .. 5 ] ] }
1345 :    
1346 :     if ( @qsims ) { push @sims, order_query_sims( $qid, $qdef, $qlen, \@qsims, $order ) }
1347 :    
1348 :     wantarray ? @sims : \@sims;
1349 :     }
1350 :    
1351 :    
1352 :     #===============================================================================
1353 :     #
1354 :     # Try to integrate non-conflicting HSPs for the same subject sequence. The
1355 :     # conflicts are only assessed from the standpoint of the query, at least for
1356 :     # now. We could track the subject sequence coverage as well (to avoid a direct
1357 :     # repeat in the query from matching the same subject twice).
1358 :     #
1359 :     # $new_coverage = integrate_HSP( $coverage, $hsp, $max_frac_overlap, $no_merge )
1360 :     #
1361 :     # 0 1 2 3 4 5 6 7
1362 :     # $coverage = [ scr, e_val, n_mat, n_id, n_pos, n_gap, dir, [ intervals_covered ] ]
1363 :     #
1364 :     # $coverage should be undefined at the first call; the function intiallizes
1365 :     # all of the fields from the first HSP. scr, n_mat, n_id, n_pos, and n_gap
1366 :     # are sums over the combined HSPs. e_val is based only of the first HSP.
1367 :     #
1368 :     # 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
1369 :     # $hsp = [ 'HSP', scr, e_val, n_seg, e_val2, n_mat, n_id, n_pos, n_gap, dir, s1, e1, sq1, s2, e2, sq2 ]
1370 :     #
1371 :     # $max_frac_overlap Amount of the new HSP that is allowed to overlap already
1372 :     # incorporated HSPs
1373 :     #
1374 :     # $no_merge Disable the merging of multiple HSPs. The structure will
1375 :     # be filled in from the first HSP and left unchanged though
1376 :     # subsequence calls. This simplifies the program structure.
1377 :     #
1378 :     # Fitting a new HSP into covered intervals:
1379 :     #
1380 :     # 1 qlen
1381 :     # |---------------------------------------------------------------| query
1382 :     # ------------ --------------- covered
1383 :     # ------------- new match
1384 :     # l r
1385 :     #
1386 :     #===============================================================================
1387 :    
1388 :     sub integrate_HSP
1389 :     { my ( $coverage, $hsp, $max_frac_overlap, $no_merge ) = @_;
1390 :     my ( undef, $scr, $e_val, undef, undef, $n_mat, $n_id, $n_pos, $n_gap, $dir, $s1, $e1 ) = @$hsp;
1391 :    
1392 :     # Ignore frame; just use direction of match:
1393 :    
1394 :     $dir = substr( $dir, 0, 1 );
1395 :    
1396 :     # Orient by left and right ends:
1397 :    
1398 :     my ( $l, $r ) = ( $e1 > $s1 ) ? ( $s1, $e1 ) : ( $e1, $s1 );
1399 :    
1400 :     # First HSP for the subject sequence:
1401 :    
1402 :     if ( ! $coverage )
1403 :     {
1404 : golsen 1.5 return [ $scr, $e_val, $n_mat, $n_id, $n_pos, $n_gap, $dir, [ [ $s1, $e1 ] ] ];
1405 : golsen 1.1 }
1406 :    
1407 :     # Not first; must be same direction to combine (also test no_merge here):
1408 :    
1409 :     return $coverage if ( $no_merge || ( $dir ne $coverage->[6] ) );
1410 :    
1411 :     # Not first; must fall in a gap of query sequence coverage:
1412 :    
1413 :     my @intervals = @{ $coverage->[7] };
1414 :     my $max_overlap = $max_frac_overlap * ( $r - $l + 1 );
1415 :     my $prev_end = 0;
1416 :     my $next_beg = $intervals[0]->[0];
1417 :     my @used = ();
1418 :     while ( $next_beg <= $l ) # *** Sequential search could be made binary
1419 :     {
1420 : golsen 1.5 $prev_end = $intervals[0]->[1];
1421 :     push @used, scalar shift @intervals;
1422 :     $next_beg = @intervals ? $intervals[0]->[0] : 1e10;
1423 : golsen 1.1 }
1424 :    
1425 :     my $overlap = ( ( $l <= $prev_end ) ? ( $prev_end - $l + 1 ) : 0 )
1426 :     + ( ( $r >= $next_beg ) ? ( $r - $next_beg + 1 ) : 0 );
1427 :     return $coverage if ( $overlap > $max_overlap );
1428 :    
1429 :     # Okay, we have passed the overlap test. We need to integrate the
1430 :     # match into the coverage description. Yes, I know that this counts
1431 :     # the overlap region. We could pro rate it, but that is messy too:
1432 :    
1433 :     $coverage->[0] += $scr;
1434 :     $coverage->[2] += $n_mat;
1435 :     $coverage->[3] += $n_id;
1436 :     $coverage->[4] += $n_pos;
1437 :     $coverage->[5] += $n_gap;
1438 :    
1439 :     # Refigure the covered intervals, fusing intervals separated by a
1440 :     # gap of less than 10:
1441 :    
1442 :     my $min_gap = 10;
1443 :     if ( $l <= $prev_end + $min_gap )
1444 :     {
1445 : golsen 1.5 if ( @used ) { $l = $used[-1]->[0]; pop @used }
1446 :     else { $l = 1 }
1447 : golsen 1.1 }
1448 :     if ( $r >= $next_beg - $min_gap )
1449 :     {
1450 : golsen 1.5 if ( @intervals ) { $r = $intervals[0]->[1]; shift @intervals }
1451 :     else { $r = 1e10 }
1452 : golsen 1.1 }
1453 :    
1454 :     $coverage->[7] = [ @used, [ $l, $r ], @intervals ];
1455 :    
1456 :     return $coverage;
1457 :     }
1458 :    
1459 :    
1460 :     #===============================================================================
1461 :     # Sort the blast matches by the desired criterion:
1462 :     #
1463 :     # @sims = order_query_sims( $qid, $qdef, $qlen, \@qsims, $order )
1464 :     #
1465 :     # Allowed sort orders are 'score', 'score_per_position', 'identity_fraction',
1466 :     # and 'positive_fraction'
1467 :     #
1468 :     # @qsims fields:
1469 :     #
1470 :     # 0 1 2 3 4 5 6 7 8
1471 :     # [ sid, sdef, slen, scr, e_val, n_mat, n_id, n_pos, n_gap ]
1472 :     #
1473 :     #===============================================================================
1474 :    
1475 :     sub order_query_sims
1476 :     { my ( $qid, $qdef, $qlen, $qsims, $order ) = @_;
1477 :    
1478 :     my @sims;
1479 :     if ( $order eq 'score_per_position' )
1480 :     {
1481 : golsen 1.5 @sims = map { [ $_->[5] ? $_->[3]/$_->[5] : 0, $_ ] } @$qsims;
1482 : golsen 1.1 }
1483 :     elsif ( $order eq 'identity_fraction' )
1484 :     {
1485 : golsen 1.5 @sims = map { [ $_->[5] ? $_->[6]/$_->[5] : 0, $_ ] } @$qsims;
1486 : golsen 1.1 }
1487 :     elsif ( $order eq 'positive_fraction' )
1488 :     {
1489 : golsen 1.5 @sims = map { [ $_->[5] ? $_->[7]/$_->[5] : 0, $_ ] } @$qsims;
1490 : golsen 1.1 }
1491 :     else # Default is by 'score'
1492 :     {
1493 : golsen 1.5 @sims = map { [ $_->[3], $_ ] } @$qsims;
1494 : golsen 1.1 }
1495 :    
1496 :     map { [ $qid, $qdef, $qlen, @{$_->[1]} ] } sort { $b->[0] <=> $a->[0] } @sims;
1497 :     }
1498 :    
1499 :    
1500 : golsen 1.5 #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1501 :     # Locate the directory for temporary files in a SEED-aware, but not SEED-
1502 :     # dependent manner:
1503 :     #
1504 :     # ( $tmp_dir, $save_tmp ) = tmp_dir( \%options )
1505 :     #
1506 :     # $save_tmp is true if the option 'savetmp' is true.
1507 :     #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1508 :     sub tmp_dir
1509 :     {
1510 :     my $options = ref( $_[0] ) eq 'HASH' ? shift : {};
1511 :    
1512 :     my $tmp = $options->{ tmp } && -d $options->{ tmp } ? $options->{ tmp }
1513 :     : $FIG_Config::temp && -d $FIG_Config::temp ? $FIG_Config::temp
1514 :     : -d '/tmp' ? '/tmp'
1515 :     : '.';
1516 :    
1517 :     my $save_tmp = $options->{ savetmp } || 0;
1518 :    
1519 :     return ( $tmp, $save_tmp );
1520 :     }
1521 :    
1522 : overbeek 1.7 ###############################################################################
1523 : golsen 1.5
1524 : overbeek 1.7 sub n_rep_seqs {
1525 :     my(%args) = (ref($_[0]) eq 'HASH') ? %{$_[0]} : @_;
1526 :    
1527 :     my($seqs) = $args{seqs} || return undef;
1528 :     my($reps) = $args{reps} || undef;
1529 :     my($max_iden) = $args{max_iden} || 0.9; # we don't keep seqs more than 90% identical
1530 :     my($max_rep) = $args{max_rep} || 50; # maximum number of seqs in returned set
1531 :    
1532 : overbeek 1.9 if ($args{by_size}) { $seqs = [sort { length($b->[2]) <=> length($a->[2]) } @$seqs] };
1533 :    
1534 : overbeek 1.7 my($lost) = {};
1535 :     my($repseqs,$representing) = &rep_seq_2($reps ? $reps : (), $seqs, { max_sim => $max_iden });
1536 :     if ($max_rep >= @$repseqs)
1537 :     {
1538 :     return ($repseqs,$representing);
1539 :     }
1540 :     my $n_rep = $reps ? @$reps : 0;
1541 :     my $incr = $max_iden / 2;
1542 :     # print STDERR "max_iden=$max_iden, ", scalar @$repseqs,"\n";
1543 :     my $iterations_left = 7;
1544 :    
1545 :     my @seqs2;
1546 :     while ($iterations_left && ($max_rep != @$repseqs))
1547 :     {
1548 :     if ($max_rep > @$repseqs)
1549 :     {
1550 :     $max_iden += $incr;
1551 :     }
1552 :     else
1553 :     {
1554 :     @seqs2 = @$repseqs[$n_rep..(@$repseqs - 1)];
1555 :     &add_to_lost($lost,$representing);
1556 :     $max_iden -= $incr;
1557 :     }
1558 :     ($repseqs,$representing) = &rep_seq_2($reps ? $reps : (), \@seqs2, { max_sim => $max_iden });
1559 :     # print STDERR "max_iden=$max_iden, ", scalar @$repseqs,"\n";
1560 :     $iterations_left--;
1561 :     $incr = $incr / 2;
1562 :     }
1563 :    
1564 :     foreach my $id (keys(%$lost))
1565 :     {
1566 :     my $rep_by = $lost->{$id};
1567 :     while ($lost->{$rep_by})
1568 :     {
1569 :     $rep_by = $lost->{$rep_by};
1570 :     }
1571 :     push(@{$representing->{$rep_by}},$id);
1572 :     }
1573 :     return ($repseqs,$representing);
1574 :     }
1575 :    
1576 :     sub add_to_lost {
1577 :     my($lost,$representing) = @_;
1578 :    
1579 :     foreach my $id (keys(%$representing))
1580 :     {
1581 :     my $x = $representing->{$id};
1582 :     foreach my $lost_id (@$x)
1583 :     {
1584 :     $lost->{$lost_id} = $id;
1585 :     }
1586 :     }
1587 :     }
1588 :    
1589 :     ###############################################################################
1590 : golsen 1.5
1591 : golsen 1.1 1;

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3