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

Annotation of /FigKernelPackages/representative_sequences.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3