2 # BioPerl module for Bio::Search::Tiling::MapTiling
4 # Please direct questions and support issues to <bioperl-l@bioperl.org>
6 # Cared for by Mark A. Jensen <maj@fortinbras.us>
8 # Copyright Mark A. Jensen
10 # You may distribute this module under the same terms as perl itself
12 # POD documentation - main docs before the code
16 Bio::Search::Tiling::MapTiling - An implementation of an HSP tiling
17 algorithm, with methods to obtain frequently-requested statistics
21 # get a BLAST $hit from somewhere, then
22 $tiling = Bio::Search::Tiling::MapTiling->new($hit);
25 $numID = $tiling->identities();
26 $numCons = $tiling->conserved();
27 $query_length = $tiling->length('query');
28 $subject_length = $tiling->length('subject'); # or...
29 $subject_length = $tiling->length('hit');
31 # get a visual on the coverage map
32 print $tiling->coverage_map_as_text('query',$context,'LEGEND');
35 $context = $tiling->_context( -type => 'subject', -strand=> 1, -frame=>1);
36 @covering_hsps_for_subject = $tiling->next_tiling('subject',$context);
37 $context = $tiling->_context( -type => 'query', -strand=> -1, -frame=>0);
38 @covering_hsps_for_query = $tiling->next_tiling('query', $context);
42 Frequently, users want to use a set of high-scoring pairs (HSPs)
43 obtained from a BLAST or other search to assess the overall level of
44 identity, conservation, or coverage represented by matches between a
45 subject and a query sequence. Because a set of HSPs frequently
46 describes multiple overlapping sequence fragments, a simple summation of
47 statistics over the HSPs will generally overestimate those
48 statistics. To obtain an accurate estimate of global hit statistics, a
49 'tiling' of HSPs onto either the subject or the query sequence must be
50 performed, in order to properly correct for this.
52 This module will execute a tiling algorithm on a given hit based on an
53 interval decomposition I'm calling the "coverage map". Internal object
54 methods compute the various statistics, which are then stored in
55 appropriately-named public object attributes. See
56 L<Bio::Search::Tiling::MapTileUtils> for more info on the algorithm.
58 =head2 STRAND/FRAME CONTEXTS
60 In BLASTX, TBLASTN, and TBLASTX reports, strand and frame information
61 are reported for the query, subject, or query and subject,
62 respectively, for each HSP. Tilings for these sequence types are only
63 meaningful when they include HSPs in the same strand and frame, or
64 "context". So, in these situations, the context must be specified
65 in the method calls or the methods will throw.
67 Contexts are specified as strings: C<[ 'all' | [m|p][_|0|1|2] ]>, where
68 C<all> = all HSPs (will throw if context must be specified), C<m> = minus
69 strand, C<p> = plus strand, and C<_> = no frame info, C<0,1,2> = respective
70 (absolute) frame. The L</_make_context_key> method will convert a (strand,
71 frame) specification to a context string, e.g.:
73 $context = $self->_context(-type=>'query', -strand=>-1, -frame=>-2);
77 The contexts present among the HSPs in a hit are identified and stored
78 for convenience upon object construction. These are accessed off the
79 object with the L</contexts> method. If contexts don't apply for the
80 given report, this returns C<('all')>.
82 =head1 TILED ALIGNMENTS
84 The experimental method L<ALIGNMENTS/get_tiled_alns> will use a tiling
85 to concatenate tiled hsps into a series of L<Bio::SimpleAlign>
88 @alns = $tiling->get_tiled_alns($type, $context);
90 Each alignment contains two sequences with ids 'query' and 'subject',
91 and consists of a concatenation of tiling HSPs which overlap or are
92 directly adjacent. The alignment are returned in C<$type> sequence
93 order. When HSPs overlap, the alignment sequence is taken from the HSP
94 which comes first in the coverage map array.
96 The sequences in each alignment contain features (even though they are
97 L<Bio::LocatableSeq> objects) which map the original query/subject
98 coordinates to the new alignment sequence coordinates. You can
99 determine the original BLAST fragments this way:
101 $aln = ($tiling->get_tiled_alns)[0];
102 $qseq = $aln->get_seq_by_id('query');
103 $hseq = $aln->get_seq_by_id('subject');
104 foreach my $feat ($qseq->get_SeqFeatures) {
105 $org_start = ($feat->get_tag_values('query_start'))[0];
106 $org_end = ($feat->get_tag_values('query_end'))[0];
107 # original fragment as represented in the tiled alignment:
108 $org_fragment = $feat->seq;
110 foreach my $feat ($hseq->get_SeqFeatures) {
111 $org_start = ($feat->get_tag_values('subject_start'))[0];
112 $org_end = ($feat->get_tag_values('subject_end'))[0];
113 # original fragment as represented in the tiled alignment:
114 $org_fragment = $feat->seq;
119 The major calculations are made just-in-time, and then memoized. So,
120 for example, for a given MapTiling object, a coverage map would
121 usually be calculated only once (for the query), and at most twice (if
122 the subject perspective is also desired), and then only when a
123 statistic is first accessed. Afterward, the map and/or any statistic
124 is read from storage. So feel free to call the statistic methods
125 frequently if it suits you.
131 User feedback is an integral part of the evolution of this and other
132 Bioperl modules. Send your comments and suggestions preferably to
133 the Bioperl mailing list. Your participation is much appreciated.
135 bioperl-l@bioperl.org - General discussion
136 http://bioperl.org/wiki/Mailing_lists - About the mailing lists
140 Please direct usage questions or support issues to the mailing list:
142 I<bioperl-l@bioperl.org>
144 rather than to the module maintainer directly. Many experienced and
145 reponsive experts will be able look at the problem and quickly
146 address it. Please include a thorough description of the problem
147 with code and data examples if at all possible.
149 =head2 Reporting Bugs
151 Report bugs to the Bioperl bug tracking system to help us keep track
152 of the bugs and their resolution. Bug reports can be submitted via
155 https://redmine.open-bio.org/projects/bioperl/
157 =head1 AUTHOR - Mark A. Jensen
159 Email maj -at- fortinbras -dot- us
163 The rest of the documentation details each of the object methods.
164 Internal methods are usually preceded with a _
168 # Let the code begin...
170 package Bio
::Search
::Tiling
::MapTiling
;
174 # Object preamble - inherits from Bio::Root::Root
178 use Bio
::Search
::Tiling
::TilingI
;
179 use Bio
::Search
::Tiling
::MapTileUtils
;
180 use Bio
::LocatableSeq
;
182 # use base qw(Bio::Root::Root Bio::Search::Tiling::TilingI);
183 use base
qw(Bio::Root::Root Bio::Search::Tiling::TilingI);
190 Usage : my $obj = new Bio::Search::Tiling::GenericTiling();
191 Function: Builds a new Bio::Search::Tiling::GenericTiling object
192 Returns : an instance of Bio::Search::Tiling::GenericTiling
193 Args : -hit => $a_Bio_Search_Hit_HitI_object
194 general filter function:
195 -hsp_filter => sub { my $this_hsp = shift;
205 my $self = $class->SUPER::new
(@args);
206 my($hit, $filter) = $self->_rearrange( [qw( HIT HSP_FILTER)],@args );
208 $self->throw("HitI object required") unless $hit;
209 $self->throw("Argument must be HitI object") unless ( ref $hit && $hit->isa('Bio::Search::Hit::HitI') );
211 $self->_set_attributes();
212 $self->{"_algorithm"} = $hit->algorithm;
214 my @hsps = $hit->hsps;
215 # apply filter function if requested
216 if ( defined $filter ) {
217 if ( ref($filter) eq 'CODE' ) {
218 @hsps = map { $filter->($_) ?
$_ : () } @hsps;
221 $self->warn("-filter is not a coderef; ignoring");
225 # identify available contexts
226 for my $t (qw( query hit )) {
228 for my $i (0..$#hsps) {
229 my $ctxt = $self->_context(
231 -strand
=> $hsps[$i]->strand($t),
232 -frame
=> $hsps[$i]->frame($t));
233 $contexts{$ctxt} ||= [];
234 push @
{$contexts{$ctxt}}, $i;
236 $self->{"_contexts_${t}"} = \
%contexts;
239 $self->warn("No HSPs present in hit after filtering") unless (@hsps);
244 # a tiling is based on the set of hsps contained in a single hit.
245 # check all the boundaries - zero hsps, one hsp, all disjoint hsps
247 =head1 TILING ITERATORS
252 Usage : @hsps = $self->next_tiling($type);
253 Function: Obtain a tiling: a minimal set of HSPs covering the $type
254 ('hit', 'subject', 'query') sequence
256 Returns : an array of HSPI objects
257 Args : scalar $type: one of 'hit', 'subject', 'query', with
258 'subject' an alias for 'hit'
264 my ($type, $context) = @_;
265 $self->_check_type_arg(\
$type);
266 $self->_check_context_arg($type, \
$context);
267 return $self->_tiling_iterator($type, $context)->();
270 =head2 rewind_tilings
272 Title : rewind_tilings
273 Usage : $self->rewind_tilings($type)
274 Function: Reset the next_tilings($type) iterator
276 Returns : True on success
277 Args : scalar $type: one of 'hit', 'subject', 'query';
284 my ($type,$context) = @_;
285 $self->_check_type_arg(\
$type);
286 $self->_check_context_arg($type, \
$context);
287 return $self->_tiling_iterator($type, $context)->('REWIND');
292 =head2 get_tiled_alns()
294 Title : get_tiled_alns
295 Usage : @alns = $tiling->get_tiled_alns($type, $context)
296 Function: Use a tiling to construct a minimal set of alignment
297 objects covering the region specified by $type/$context
298 by splicing adjacent HSP tiles
299 Returns : an array of Bio::SimpleAlign objects; see Note below
300 Args : scalar $type: one of 'hit', 'subject', 'query'
302 scalar $context: strand/frame context string
303 Following $type and $context, an array of
304 ordered, tiled HSP objects can be specified; this is
305 the tiling that will directly the alignment construction
306 default -- the first tiling provided by a tiling iterator
307 Notes : Each returned alignment is a concatenation of adjacent tiles.
308 The set of alignments will cover all regions described by the
309 $type/$context pair in the hit. The pair of sequences in each
310 alignment have ids 'query' and 'subject', and each sequence
311 possesses SeqFeatures that map the original query or subject
312 coordinates to the sequence coordinates in the tiled alignment.
318 my ($type, $context) = @_;
319 $self->_check_type_arg(\
$type);
320 $self->_check_context_arg($type, \
$context);
321 my $t = shift; # first arg after type/context, arrayref to a tiling
323 if ($t && (ref($t) eq 'ARRAY')) {
326 else { # otherwise, take the first tiling available
328 @tiling = $self->_make_tiling_iterator($type,$context)->();
332 my @map = $self->coverage_map($type, $context);
333 my @intervals = map {$_->[0]} @map; # disjoint decomp
334 # divide into disjoint covering groups
335 my @groups = covering_groups
(@intervals);
337 require Bio
::SimpleAlign
;
338 require Bio
::SeqFeature
::Generic
;
339 # cut hsp aligns along the disjoint decomp
340 # look for gaps...or add gaps?
341 my ($q_start, $h_start, $q_strand, $h_strand);
343 for my $grp (@groups) {
344 my $taln = Bio
::SimpleAlign
->new();
345 my (@qfeats, @hfeats);
346 my $query_string = '';
348 my ($qlen,$hlen) = (0,0);
349 my ($qinc, $hinc, $qstart, $hstart);
350 for my $intvl (@
$grp) {
351 # following just chooses the first available hsp containing the
352 # interval -- this is arbitrary, could be smarter.
353 my $aln = ( containing_hsps
($intvl, @tiling) )[0]->get_aln;
354 my $qseq = $aln->get_seq_by_pos(1);
355 my $hseq = $aln->get_seq_by_pos(2);
356 $qstart ||= $qseq->start;
357 $hstart ||= $hseq->start;
358 # calculate the slice boundaries
362 $beg = $aln->column_from_residue_number($qseq->id, $intvl->[0]);
363 $end = $aln->column_from_residue_number($qseq->id, $intvl->[1]);
366 /subject|hit/ && do {
367 $beg = $aln->column_from_residue_number($hseq->id, $intvl->[0]);
368 $end = $aln->column_from_residue_number($hseq->id, $intvl->[1]);
372 $aln = $aln->slice($beg, $end);
373 $qseq = $aln->get_seq_by_pos(1);
374 $hseq = $aln->get_seq_by_pos(2);
375 $qinc = $qseq->length - $qseq->num_gaps($Bio::LocatableSeq
::GAP_SYMBOLS
);
376 $hinc = $hseq->length - $hseq->num_gaps($Bio::LocatableSeq
::GAP_SYMBOLS
);
378 push @qfeats, Bio
::SeqFeature
::Generic
->new(
381 -strand
=> $qseq->strand,
383 -source_tag
=> 'BLAST',
384 -display_name
=> 'query coordinates',
385 -tag
=> { query_id
=> $qseq->id,
386 query_desc
=> $qseq->desc,
387 query_start
=> $qstart + (($qseq->strand && $qseq->strand < 0) ?
-1 : 1)*$qlen,
388 query_end
=> $qstart + (($qseq->strand && $qseq->strand < 0) ?
-1 : 1)*($qlen+$qinc-1),
391 push @hfeats, Bio
::SeqFeature
::Generic
->new(
394 -strand
=> $hseq->strand,
395 -primary
=> 'subject/hit',
396 -source_tag
=> 'BLAST',
397 -display_name
=> 'subject/hit coordinates',
398 -tag
=> { subject_id
=> $hseq->id,
399 subject_desc
=> $hseq->desc,
400 subject_start
=> $hstart + (($hseq->strand && $hseq->strand < 0) ?
-1 : 1)*$hlen,
401 subject_end
=> $hstart + (($hseq->strand && $hseq->strand < 0) ?
-1 : 1)*($hlen+$hinc-1)
404 $query_string .= $qseq->seq;
405 $hit_string .= $hseq->seq;
409 # create the LocatableSeqs and add the features to each
410 # then add the seqs to the new aln
411 # note in MapTileUtils, Bio::FeatureHolderI methods have been
412 # mixed into Bio::LocatableSeq
413 my $qseq = Bio
::LocatableSeq
->new( -id
=> 'query',
414 -seq
=> $query_string);
415 $qseq->add_SeqFeature(@qfeats);
416 my $hseq = Bio
::LocatableSeq
->new( -id
=> 'subject',
417 -seq
=> $hit_string );
418 $hseq->add_SeqFeature(@hfeats);
419 $taln->add_seq($qseq);
420 $taln->add_seq($hseq);
432 Usage : $tiling->identities($type, $action, $context)
433 Function: Retrieve the calculated number of identities for the invocant
435 Returns : value of identities (a scalar)
436 Args : scalar $type: one of 'hit', 'subject', 'query'
438 option scalar $action: one of 'exact', 'est', 'fast', 'max'
440 option scalar $context: strand/frame context string
447 my ($type, $action, $context) = @_;
448 $self->_check_type_arg(\
$type);
449 $self->_check_action_arg(\
$action);
450 $self->_check_context_arg($type, \
$context);
451 if (!defined $self->{"identities_${type}_${action}_${context}"}) {
452 $self->_calc_stats($type, $action, $context);
454 return $self->{"identities_${type}_${action}_${context}"};
460 Usage : $tiling->conserved($type, $action)
461 Function: Retrieve the calculated number of conserved sites for the invocant
463 Returns : value of conserved (a scalar)
464 Args : scalar $type: one of 'hit', 'subject', 'query'
466 option scalar $action: one of 'exact', 'est', 'fast', 'max'
468 option scalar $context: strand/frame context string
475 my ($type, $action, $context) = @_;
476 $self->_check_type_arg(\
$type);
477 $self->_check_action_arg(\
$action);
478 $self->_check_context_arg($type, \
$context);
479 if (!defined $self->{"conserved_${type}_${action}_${context}"}) {
480 $self->_calc_stats($type, $action, $context);
482 return $self->{"conserved_${type}_${action}_${context}"};
488 Usage : $tiling->length($type, $action, $context)
489 Function: Retrieve the total length of aligned residues for
492 Returns : value of length (a scalar)
493 Args : scalar $type: one of 'hit', 'subject', 'query'
495 option scalar $action: one of 'exact', 'est', 'fast', 'max'
497 option scalar $context: strand/frame context string
504 my ($type,$action,$context) = @_;
505 $self->_check_type_arg(\
$type);
506 $self->_check_action_arg(\
$action);
507 $self->_check_context_arg($type, \
$context);
508 if (!defined $self->{"length_${type}_${action}_${context}"}) {
509 $self->_calc_stats($type, $action, $context);
511 return $self->{"length_${type}_${action}_${context}"};
517 Usage : $tiling->frac($type, $denom, $action, $context, $method)
518 Function: Return the fraction of sequence length consisting
519 of desired kinds of pairs (given by $method),
520 with respect to $denom
521 Returns : scalar float
522 Args : -type => one of 'hit', 'subject', 'query'
523 -denom => one of 'total', 'aligned'
524 -action => one of 'exact', 'est', 'fast', 'max'
525 -context => strand/frame context string
526 -method => one of 'identical', 'conserved'
527 Note : $denom == 'aligned', return desired_stat/num_aligned
528 $denom == 'total', return desired_stat/_reported_length
529 (i.e., length of the original input sequences)
530 Note : In keeping with the spirit of Bio::Search::HSP::HSPI,
531 reported lengths of translated dna are reduced by
532 a factor of 3, to provide fractions relative to
533 amino acid coordinates.
540 my ($type, $denom, $action, $context, $method) = $self->_rearrange([qw(TYPE DENOM ACTION CONTEXT METHOD)],@args);
541 $self->_check_type_arg(\
$type);
542 $self->_check_action_arg(\
$action);
543 $self->_check_context_arg($type, \
$context);
544 unless ($method and grep(/^$method$/, qw( identical conserved ))) {
545 $self->throw("-method must specified; one of ('identical', 'conserved')");
548 unless (grep /^$denom/, qw( total aligned )) {
549 $self->throw("Denominator selection must be one of ('total', 'aligned'), not '$denom'");
551 my $key = "frac_${method}_${type}_${denom}_${action}_${context}";
554 $_ eq 'identical' && do {
555 $stat = $self->identities($type, $action, $context);
558 $_ eq 'conserved' && do {
559 $stat = $self->conserved($type, $action, $context);
563 $self->throw("What are YOU doing here?");
566 if (!defined $self->{$key}) {
570 $stat/$self->_reported_length($type); # need fudge fac??
575 $stat/$self->length($type,$action,$context);
579 $self->throw("What are YOU doing here?");
583 return $self->{$key};
586 =head2 frac_identical
588 Title : frac_identical
589 Usage : $tiling->frac_identical($type, $denom, $action, $context)
590 Function: Return the fraction of sequence length consisting
591 of identical pairs, with respect to $denom
592 Returns : scalar float
593 Args : -type => one of 'hit', 'subject', 'query'
594 -denom => one of 'total', 'aligned'
595 -action => one of 'exact', 'est', 'fast', 'max'
596 -context => strand/frame context string
597 Note : $denom == 'aligned', return conserved/num_aligned
598 $denom == 'total', return conserved/_reported_length
599 (i.e., length of the original input sequences)
600 Note : In keeping with the spirit of Bio::Search::HSP::HSPI,
601 reported lengths of translated dna are reduced by
602 a factor of 3, to provide fractions relative to
603 amino acid coordinates.
604 Note : This an alias that calls frac()
611 my ($type, $denom, $action,$context) = $self->_rearrange( [qw
[ TYPE DENOM ACTION CONTEXT
]],@args );
612 $self->frac( -type
=>$type, -denom
=>$denom, -action
=>$action, -method
=>'identical', -context
=>$context);
615 =head2 frac_conserved
617 Title : frac_conserved
618 Usage : $tiling->frac_conserved($type, $denom, $action, $context)
619 Function: Return the fraction of sequence length consisting
620 of conserved pairs, with respect to $denom
621 Returns : scalar float
622 Args : -type => one of 'hit', 'subject', 'query'
623 -denom => one of 'total', 'aligned'
624 -action => one of 'exact', 'est', 'fast', 'max'
625 -context => strand/frame context string
626 Note : $denom == 'aligned', return conserved/num_aligned
627 $denom == 'total', return conserved/_reported_length
628 (i.e., length of the original input sequences)
629 Note : In keeping with the spirit of Bio::Search::HSP::HSPI,
630 reported lengths of translated dna are reduced by
631 a factor of 3, to provide fractions relative to
632 amino acid coordinates.
633 Note : This an alias that calls frac()
640 my ($type, $denom, $action, $context) = $self->_rearrange( [qw
[ TYPE DENOM ACTION CONTEXT
]],@args );
641 $self->frac( -type
=>$type, -denom
=>$denom, -action
=>$action, -context
=>$context, -method
=>'conserved');
647 Aliases : frac_aligned_query - frac_aligned(-type=>'query',...)
648 frac_aligned_hit - frac_aligned(-type=>'hit',...)
649 Usage : $tiling->frac_aligned(-type=>$type,
652 Function: Return the fraction of input sequence length
653 that was aligned by the algorithm
654 Returns : scalar float
655 Args : -type => one of 'hit', 'subject', 'query'
656 -action => one of 'exact', 'est', 'fast', 'max'
657 -context => strand/frame context string
662 my ($self, @args) = @_;
663 my ($type, $action, $context) = $self->_rearrange([qw(TYPE ACTION CONTEXT)],@args);
664 $self->_check_type_arg(\
$type);
665 $self->_check_action_arg(\
$action);
666 $self->_check_context_arg($type, \
$context);
667 if (!$self->{"frac_aligned_${type}_${action}_${context}"}) {
668 $self->{"frac_aligned_${type}_${action}_${context}"} = $self->num_aligned($type,$action,$context)/$self->_reported_length($type);
670 return $self->{"frac_aligned_${type}_${action}_${context}"};
673 sub frac_aligned_query
{ shift->frac_aligned(-type
=>'query', @_) }
674 sub frac_aligned_hit
{ shift->frac_aligned(-type
=>'hit', @_) }
680 Usage : $tiling->num_aligned(-type=>$type)
681 Function: Return the number of residues of sequence $type
682 that were aligned by the algorithm
684 Args : -type => one of 'hit', 'subject', 'query'
685 -action => one of 'exact', 'est', 'fast', 'max'
686 -context => strand/frame context string
687 Note : Since this is calculated from reported coordinates,
688 not symbol string counts, it is already in terms of
690 Note : Aliases length()
694 sub num_aligned
{ shift->length( @_ ) };
698 Title : num_unaligned
699 Usage : $tiling->num_unaligned(-type=>$type)
700 Function: Return the number of residues of sequence $type
701 that were left unaligned by the algorithm
703 Args : -type => one of 'hit', 'subject', 'query'
704 -action => one of 'exact', 'est', 'fast', 'max'
705 -context => strand/frame context string
706 Note : Since this is calculated from reported coordinates,
707 not symbol string counts, it is already in terms of
714 my ($type,$action,$context) = @_;
716 $self->_check_type_arg(\
$type);
717 $self->_check_action_arg(\
$action);
718 $self->_check_context_arg($type, \
$context);
719 if (!defined $self->{"num_unaligned_${type}_${action}_${context}"}) {
720 $self->{"num_unaligned_${type}_${action}_${context}"} = $self->_reported_length($type)-$self->num_aligned($type,$action,$context);
722 return $self->{"num_unaligned_${type}_${action}_${context}"};
729 Usage : $tiling->range(-type=>$type)
730 Function: Returns the extent of the longest tiling
731 as ($min_coord, $max_coord)
732 Returns : array of two scalar integers
733 Args : -type => one of 'hit', 'subject', 'query'
734 -context => strand/frame context string
739 my ($self, $type, $context) = @_;
740 $self->_check_type_arg(\
$type);
741 $self->_check_context_arg($type, \
$context);
742 my @a = $self->_contig_intersection($type,$context);
743 return ($a[0][0], $a[-1][1]);
753 Usage : $map = $tiling->coverage_map($type)
754 Function: Property to contain the coverage map calculated
755 by _calc_coverage_map() - see that for
758 Returns : value of coverage_map_$type as an array
759 Args : scalar $type: one of 'hit', 'subject', 'query'
767 my ($type, $context) = @_;
768 $self->_check_type_arg(\
$type);
769 $self->_check_context_arg($type, \
$context);
771 if (!defined $self->{"coverage_map_${type}_${context}"}) {
772 # following calculates coverage maps in all strands/frames
774 $self->_calc_coverage_map($type, $context);
776 # if undef is returned, then there were no hsps for given strand/frame
777 if (!defined $self->{"coverage_map_${type}_${context}"}) {
778 $self->warn("No HSPS present for type '$type' in context '$context' for this hit");
781 return @
{$self->{"coverage_map_${type}_${context}"}};
784 =head2 coverage_map_as_text
786 Title : coverage_map_as_text
787 Usage : $tiling->coverage_map_as_text($type, $legend_flag)
788 Function: Format a text-graphic representation of the
790 Returns : an array of scalar strings, suitable for printing
791 Args : $type: one of 'query', 'hit', 'subject'
792 $context: strand/frame context string
793 $legend_flag: boolean; add a legend indicating
794 the actual interval coordinates for each component
795 interval and hsp (in the $type sequence context)
796 Example : print $tiling->coverage_map_as_text('query',1);
800 sub coverage_map_as_text
{
802 my ($type, $context, $legend_q) = @_;
803 $self->_check_type_arg(\
$type);
804 $self->_check_context_arg($type, \
$context);
806 my @map = $self->coverage_map($type, $context);
808 my @hsps = $self->hit->hsps;
810 require Tie
::RefHash
;
811 tie
%hsps_i, 'Tie::RefHash';
812 @hsps_i{@hsps} = (0..$#hsps);
815 my @hspx = ('') x
@hsps;
816 my @these_hsps = @
{$map[$_]->[1]};
817 @hspx[@hsps_i{@these_hsps}] = ('*') x
@these_hsps;
822 push @ret, "\tIntvl\n";
823 push @ret, "HSPS\t", join ("\t", (0..$#map)), "\n";
824 foreach my $h (0..$#hsps) {
825 push @ret, join("\t", $h, map { $mx[$_][$h] } (0..$#map) ),"\n";
828 push @ret, "Interval legend\n";
830 push @ret, sprintf("%d\t[%d, %d]\n", $_, @
{$map[$_][0]});
832 push @ret, "HSP legend\n";
833 my @ints = get_intervals_from_hsps
($type,@hsps);
834 foreach (0..$#hsps) {
835 push @ret, sprintf("%d\t[%d, %d]\n", $_, @
{$ints[$_]});
847 Returns : The HitI object associated with the invocant
855 $self->warn("Getter only") if @_;
856 return $self->{'hit'};
862 Usage : $tiling->hsps()
863 Function: Container for the HSP objects associated with invocant
865 Returns : an array of hsps associated with the hit
866 Args : on set, new value (an arrayref or undef, optional)
872 return $self->{'hsps'} = shift if @_;
873 return @
{$self->{'hsps'}};
879 Usage : @contexts = $tiling->context($type) or
880 @indices = $tiling->context($type, $context)
881 Function: Retrieve the set of available contexts in the hit,
882 or the indices of hsps having the given context
883 (integer indices for the array returned by $self->hsps)
884 Returns : array of scalar context strings or
885 array of scalar positive integers
886 undef if no hsps in given context
887 Args : $type: one of 'query', 'hit', 'subject'
888 optional $context: context string
894 my ($type, $context) = @_;
895 $self->_check_type_arg(\
$type);
896 return keys %{$self->{"_contexts_$type"}} unless defined $context;
897 return undef unless $self->{"_contexts_$type"}{$context};
898 return @
{$self->{"_contexts_$type"}{$context}};
904 Usage : $tiling->mapping($type)
905 Function: Retrieve the mapping coefficient for the sequence type
906 based on the underlying algorithm
907 Returns : scalar integer (mapping coefficient)
908 Args : $type: one of 'query', 'hit', 'subject'
909 Note : getter only (set in constructor)
916 $self->_check_type_arg(\
$type);
917 return $self->{"_mapping_${type}"};
920 =head2 default_context
922 Title : default_context
923 Usage : $tiling->default_context($type)
924 Function: Retrieve the default strand/frame context string
925 for the sequence type based on the underlying algorithm
926 Returns : scalar string (context string)
927 Args : $type: one of 'query', 'hit', 'subject'
928 Note : getter only (set in constructor)
935 $self->_check_type_arg(\
$type);
936 return $self->{"_def_context_${type}"};
942 Usage : $tiling->algorithm
943 Function: Retrieve the algorithm name associated with the
944 invocant's hit object
945 Returns : scalar string
947 Note : getter only (set in constructor)
953 $self->warn("Getter only") if @_;
954 return $self->{"_algorithm"};
957 =head1 "PRIVATE" METHODS
961 See L<Bio::Search::Tiling::MapTileUtils> for lower level
964 =head2 _calc_coverage_map
966 Title : _calc_coverage_map
967 Usage : $tiling->_calc_coverage_map($type)
968 Function: Calculates the coverage map for the object's associated
969 hit from the perspective of the desired $type (see Args:)
970 and sets the coverage_map() property
971 Returns : True on success
972 Args : optional scalar $type: one of 'hit'|'subject'|'query'
974 Note : The "coverage map" is an array with the following format:
975 ( [ $component_interval => [ @containing_hsps ] ], ... ),
976 where $component_interval is a closed interval (see
977 DESCRIPTION) of the form [$a0, $a1] with $a0 <= $a1, and
978 @containing_hsps is an array of all HspI objects in the hit
979 which completely contain the $component_interval.
980 The set of $component_interval's is a disjoint decomposition
981 of the minimum set of minimal intervals that completely
982 cover the hit's HSPs (from the perspective of the $type)
983 Note : This calculates the map for all strand/frame contexts available
988 sub _calc_coverage_map
{
991 $self->_check_type_arg(\
$type);
993 # obtain the [start, end] intervals for all hsps in the hit (relative
995 unless ($self->{'hsps'}) {
996 $self->warn("No HSPs for this hit");
1000 my (@map, @hsps, %filters, @intervals);
1004 my $c = $self->mapping($type);
1006 # create the possible maps
1007 for my $context ($self->contexts($type)) {
1009 @hsps = ($self->hsps)[$self->contexts($type, $context)];
1010 @intervals = get_intervals_from_hsps
( $type, @hsps );
1012 my $f = ($intervals[0]->[0] - 1) % $c;
1014 # convert interval endpoints...
1016 $$_[0] = ($$_[0] - $f + $c - 1)/$c;
1017 $$_[1] = ($$_[1] - $f)/$c;
1020 # determine the minimal set of disjoint intervals that cover the
1021 # set of hsp intervals
1022 my @dj_set = interval_tiling
(\
@intervals);
1024 # decompose each disjoint interval into another set of disjoint
1025 # intervals, each of which is completely contained within the
1026 # original hsp intervals with which it overlaps
1029 for my $dj_elt (@dj_set) {
1030 my ($covering, $indices) = @
$dj_elt;
1031 my @covering_hsps = @hsps[@
$indices];
1032 my @coverers = @intervals[@
$indices];
1033 @decomp = decompose_interval
( \
@coverers );
1035 my ($component, $container_indices) = @
{$_};
1036 push @map, [ $component,
1037 [@covering_hsps[@
$container_indices]] ];
1042 # unconvert the components:
1045 $$_[0][0] = $c*$$_[0][0] - $c + 1 + $f;
1046 $$_[0][1] = $c*$$_[0][1] + $f;
1049 $$_[0][0] = $c*$$_[0][0] - $c + 1 + $f;
1050 $$_[0][1] = $c*$$_[0][1] + $f;
1053 # sort the map on the interval left-ends
1054 @map = sort { $a->[0][0]<=>$b->[0][0] } @map;
1055 $self->{"coverage_map_${type}_${context}"} = [@map];
1056 # set the _contig_intersection attribute here (side effect)
1057 $self->{"_contig_intersection_${type}_${context}"} = [map { $$_[0] } @map];
1066 Usage : $tiling->_calc_stats($type, $action, $context)
1067 Function: Calculates [estimated] tiling statistics (identities, conserved sites
1068 length) and sets the public accessors
1069 Returns : True on success
1070 Args : scalar $type: one of 'hit', 'subject', 'query'
1072 optional scalar $action: requests calculation method
1073 currently one of 'exact', 'est', 'fast', 'max'
1074 option scalar $context: strand/frame context string
1075 Note : Action: The statistics are calculated by summing quantities
1076 over the disjoint component intervals, taking into account
1077 coverage of those intervals by multiple HSPs. The action
1078 tells the algorithm how to obtain those quantities--
1079 'exact' will use Bio::Search::HSP::HSPI::matches
1080 to count the appropriate segment of the homology string;
1081 'est' will estimate the statistics by multiplying the
1082 fraction of the HSP overlapped by the component interval
1083 (see MapTileUtils) by the BLAST-reported identities/postives
1084 (this may be convenient for BLAST summary report formats)
1085 * Both exact and est take the average over the number of HSPs
1086 that overlap the component interval.
1087 'max' uses the exact method to calculate the statistics,
1088 and returns only the maximum identites/positives over
1089 overlapping HSP for the component interval. No averaging
1091 'fast' doesn't involve tiling at all (hence the name),
1092 but it seems like a very good estimate, and uses only
1093 reported values, and so does not require sequence data. It
1094 calculates an average of reported identities, conserved
1095 sites, and lengths, over unmodified hsps in the hit,
1096 weighted by the length of the hsps.
1102 my ($type, $action, $context) = @_;
1103 # need to check args here, in case method is called internally.
1104 $self->_check_type_arg(\
$type);
1105 $self->_check_action_arg(\
$action);
1106 $self->_check_context_arg($type, \
$context);
1107 my ($ident, $cons, $length) = (0,0,0);
1109 # fast : avoid coverage map altogether, get a pretty damn
1110 # good estimate with a weighted average of reported hsp
1113 ($action eq 'fast') && do {
1114 my @hsps = $self->hit->hsps;
1115 @hsps = @hsps[$self->contexts($type, $context)];
1116 # weights for averages
1117 my @wt = map {$_->length($type)} @hsps;
1118 my $sum = eval( join('+',@wt) );
1119 $_ /= $sum for (@wt);
1122 $ident += $wt*$_->matches_MT($type,'identities');
1123 $cons += $wt*$_->matches_MT($type,'conserved');
1124 $length += $wt*$_->length($type);
1130 # calculate identities/conserved sites in tiling
1131 # estimate based on the fraction of the component interval covered
1132 # and ident/cons reported by the HSPs
1133 ($action ne 'fast') && do {
1134 foreach ($self->coverage_map($type, $context)) {
1135 my ($intvl, $hsps) = @
{$_};
1136 my $len = ($$intvl[1]-$$intvl[0]+1);
1137 my $ncover = ($action eq 'max') ?
1 : scalar @
$hsps;
1138 my ($acc_i, $acc_c) = (0,0);
1139 foreach my $hsp (@
$hsps) {
1141 ($_ eq 'est') && do {
1142 my ($inc_i, $inc_c) = $hsp->matches_MT(
1144 -action
=> 'searchutils',
1146 my $frac = $len/$hsp->length($type);
1147 $acc_i += $inc_i * $frac;
1148 $acc_c += $inc_c * $frac;
1151 ($_ eq 'max') && do {
1152 my ($inc_i, $inc_c) = $hsp->matches_MT(
1154 -action
=> 'searchutils',
1155 -start
=> $$intvl[0],
1158 $acc_i = ($acc_i > $inc_i) ?
$acc_i : $inc_i;
1159 $acc_c = ($acc_c > $inc_c) ?
$acc_c : $inc_c;
1162 (!$_ || ($_ eq 'exact')) && do {
1163 my ($inc_i, $inc_c) = $hsp->matches_MT(
1165 -action
=> 'searchutils',
1166 -start
=> $$intvl[0],
1175 $ident += ($acc_i/$ncover);
1176 $cons += ($acc_c/$ncover);
1181 $self->{"identities_${type}_${action}_${context}"} = $ident;
1182 $self->{"conserved_${type}_${action}_${context}"} = $cons;
1183 $self->{"length_${type}_${action}_${context}"} = $length;
1188 =head2 Tiling Helper Methods
1192 # coverage_map is of the form
1193 # ( [ $interval, \@containing_hsps ], ... )
1195 # so, for each interval, pick one of the containing hsps,
1196 # and return the union of all the picks.
1198 # use the combinatorial generating iterator, with
1199 # the urns containing the @containing_hsps for each
1202 =head2 _make_tiling_iterator
1204 Title : _make_tiling_iterator
1205 Usage : $self->_make_tiling_iterator($type)
1206 Function: Create an iterator code ref that will step through all
1207 minimal combinations of HSPs that produce complete coverage
1208 of the $type ('hit', 'subject', 'query') sequence,
1209 and set the correct iterator property of the invocant
1211 Returns : The iterator
1212 Args : scalar $type, one of 'hit', 'subject', 'query';
1217 sub _make_tiling_iterator
{
1220 my ($type, $context) = @_;
1221 $self->_check_type_arg(\
$type);
1222 $self->_check_context_arg($type, \
$context);
1224 # initialize the urns
1225 my @urns = map { [0, $$_[1]] } $self->coverage_map($type, $context);
1230 if (my $rewind = shift) {
1231 # reinitialize urn indices
1232 $$_[0] = 0 for (@urns);
1237 return if $FINISHED;
1239 my $finished_incrementing = 0;
1240 # @ret is the collector of urn choices
1243 for my $urn (@urns) {
1244 my ($n, $hsps) = @
$urn;
1245 push @ret, $$hsps[$n];
1246 unless ($finished_incrementing) {
1247 if ($n == $#$hsps) { $$urn[0] = 0; }
1248 else { ($$urn[0])++; $finished_incrementing = 1 }
1253 $FINISHED = 1 unless $finished_incrementing;
1255 # $hsp->rank is a unique identifier for an hsp in a hit.
1256 # preserve order in @ret
1259 @order{(0..$#ret)} = @ret;
1260 $uniq{$order{$_}->rank} = $_ for (0..$#ret);
1261 @ret = @order{ sort {$a<=>$b} values %uniq };
1268 =head2 _tiling_iterator
1270 Title : _tiling_iterator
1271 Usage : $tiling->_tiling_iterator($type,$context)
1272 Function: Retrieve the tiling iterator coderef for the requested
1273 $type ('hit', 'subject', 'query')
1275 Returns : coderef to the desired iterator
1276 Args : scalar $type, one of 'hit', 'subject', 'query'
1278 option scalar $context: strand/frame context string
1283 sub _tiling_iterator
{
1285 my ($type, $context) = @_;
1286 $self->_check_type_arg(\
$type);
1287 $self->_check_context_arg($type, \
$context);
1289 if (!defined $self->{"_tiling_iterator_${type}_${context}"}) {
1290 $self->{"_tiling_iterator_${type}_${context}"} =
1291 $self->_make_tiling_iterator($type,$context);
1293 return $self->{"_tiling_iterator_${type}_${context}"};
1295 =head2 Construction Helper Methods
1297 See also L<Bio::Search::Tiling::MapTileUtils>.
1301 sub _check_type_arg
{
1303 my $typeref = shift;
1304 $$typeref ||= 'query';
1305 $self->throw("Unknown type '$$typeref'") unless grep(/^$$typeref$/, qw( hit query subject ));
1306 $$typeref = 'hit' if $$typeref eq 'subject';
1310 sub _check_action_arg
{
1312 my $actionref = shift;
1314 $$actionref = ($self->_has_sequence_data ?
'exact' : 'est');
1317 $self->throw("Calc action '$$actionref' unrecognized") unless grep /^$$actionref$/, qw( est exact fast max );
1318 if ($$actionref ne 'est' and !$self->_has_sequence_data) {
1319 $self->warn("Blast file did not possess sequence data; defaulting to 'est' action");
1320 $$actionref = 'est';
1326 sub _check_context_arg
{
1328 my ($type, $contextref) = @_;
1329 if (!$$contextref) {
1330 $self->throw("Type '$type' requires strand/frame context for algorithm ".$self->algorithm) unless ($self->mapping($type) == 1);
1331 # set default according to default_context attrib
1332 $$contextref = $self->default_context($type);
1335 ($$contextref =~ /^[mp]$/) && do { $$contextref .= '_' };
1336 $self->throw("Context '$$contextref' unrecognized") unless
1337 $$contextref =~ /all|[mp][0-2_]/;
1342 =head2 _make_context_key
1344 Title : _make_context_key
1346 Usage : $tiling->_make_context_key(-strand => $strand, -frame => $frame)
1347 Function: create a string indicating strand/frame context; serves as
1348 component of memoizing hash keys
1349 Returns : scalar string
1350 Args : -type => one of ('query', 'hit', 'subject')
1351 -strand => one of (1,0,-1)
1352 -frame => one of (-2, 1, 0, 1, -2)
1353 called w/o args: returns 'all'
1357 sub _make_context_key
{
1360 my ($type, $strand, $frame) = $self->_rearrange([qw(TYPE STRAND FRAME)], @args);
1361 _check_type_arg
(\
$type);
1362 return 'all' unless (defined $strand or defined $frame);
1363 if ( defined $strand && $self->_has_strand($type) ) {
1364 if (defined $frame && $self->_has_frame($type)) {
1365 return ($strand >= 0 ?
'p' : 'm').abs($frame);
1368 return ($strand >= 0 ?
'p_' : 'm_');
1372 if (defined $frame && $self->_has_frame($type)) {
1373 $self->warn("Frame defined without strand; punting with plus strand");
1374 return 'p'.abs($frame);
1385 Alias : _make_context_key
1386 Usage : $tiling->_make_context_key(-strand => $strand, -frame => $frame)
1387 Function: create a string indicating strand/frame context; serves as
1388 component of memoizing hash keys
1389 Returns : scalar string
1390 Args : -type => one of ('query', 'hit', 'subject')
1391 -strand => one of (1,0,-1)
1392 -frame => one of (-2, 1, 0, 1, -2)
1393 called w/o args: returns 'all'
1397 sub _context
{ shift->_make_context_key(@_) }
1401 Most based on a reading of the algorithm name with a configuration lookup.
1405 =item _has_sequence_data()
1409 sub _has_sequence_data
{
1411 $self->throw("Hit attribute not yet set") unless defined $self->hit;
1412 return (($self->hit->hsps)[0]->seq_str('match') ?
1 : 0);
1415 =item _has_logical_length()
1419 sub _has_logical_length
{
1422 $self->_check_type_arg(\
$type);
1423 # based on mapping coeff
1424 $self->throw("Mapping coefficients not yet set") unless defined $self->mapping($type);
1425 return ($self->mapping($type) > 1);
1435 $self->_check_type_arg(\
$type);
1436 return $self->{"_has_strand_${type}"};
1446 $self->_check_type_arg(\
$type);
1447 return $self->{"_has_frame_${type}"};
1452 =head1 Private Accessors
1454 =head2 _contig_intersection
1456 Title : _contig_intersection
1457 Usage : $tiling->_contig_intersection($type)
1458 Function: Return the minimal set of $type coordinate intervals
1459 covered by the invocant's HSPs
1460 Returns : array of intervals (2-member arrayrefs; see MapTileUtils)
1461 Args : scalar $type: one of 'query', 'hit', 'subject'
1465 sub _contig_intersection
{
1467 my ($type, $context) = @_;
1468 $self->_check_type_arg(\
$type);
1469 $self->_check_context_arg($type, \
$context);
1470 if (!defined $self->{"_contig_intersection_${type}_${context}"}) {
1471 $self->_calc_coverage_map($type);
1473 return @
{$self->{"_contig_intersection_${type}_${context}"}};
1476 =head2 _reported_length
1478 Title : _reported_length
1479 Usage : $tiling->_reported_length($type)
1480 Function: Get the total length of the seq $type
1481 for the invocant's hit object, as reported
1482 by (not calculated from) the input data file
1483 Returns : scalar int
1484 Args : scalar $type: one of 'query', 'hit', 'subject'
1485 Note : This is kludgy; the hit object does not currently
1486 maintain accessors for these values, but the
1487 hsps possess these attributes. This is a wrapper
1488 that allows a consistent access method in the
1490 Note : Since this number is based on a reported length,
1491 it is already a "logical length".
1495 sub _reported_length
{
1498 $self->_check_type_arg(\
$type);
1499 my $key = uc( $type."_LENGTH" );
1500 return ($self->hsps)[0]->{$key};