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

Annotation of /FigKernelPackages/representative_sequences.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3