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

Annotation of /FigKernelPackages/representative_sequences.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3