blib/lib/Bio/Graphics/Browser2/RegionSearch.pm untested

filter: Statementstmt 0.0% 0 / 376 Branchbran 0.0% 0 / 122 Conditioncond 0.0% 0 / 113 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 45 Podpod 0.0% 0 / 31 totaltotal 0.0% 0 / 687 CC 62 SCAR 42.8
CC
62
Cov
0%
_search_features_locally
272.0
search_features
90.0
search_features_remotely
90.0
CRAP 72.6
1 package Bio::Graphics::Browser2::RegionSearch;
2  
3 use strict;
4 use warnings;
5 use Bio::Graphics::GBrowseFeature;
6 use Bio::Graphics::Browser2::Region;
7 use Bio::Graphics::Browser2::RenderPanels;
8 use Bio::Graphics::Browser2::Util 'shellwords';
9 use Bio::Graphics::Browser2::Render::Slave::Status;
10 use LWP::UserAgent;
11 use HTTP::Request::Common 'POST';
12 use Carp 'cluck','croak';
13 use Storable 'nfreeze','thaw';
14  
15 use constant DEBUG => 0;
16  
17 # search multiple databases using crazy heuristics
18  
19 =head1 NAME
20  
21 Bio::Graphics::Browser2::RegionSearch -- Search through multiple databases for feature matches.
22  
23 =head1 SYNOPSIS
24  
25 my $dbs = Bio::Graphics::Browser2::RegionSearch->new(
26 { source => $data_source,
27 state => $session_state
28 });
29 $dbs->init_databases();
30 my $features = $dbs->search_features({-search_term=>'sma-3'});
31
32  
33 =head1 DESCRIPTION
34  
35 This implements a feature search based on the heuristics in
36 Bio::Graphics::Browser2::Region. The search is distributed across all
37 local and remote databases as specified in the data source.
38  
39 =head1 METHODS
40  
41 The remainder of this document describes the methods available to the
42 programmer.
43  
44 =cut
45  
46 =head2 $db = Bio::Graphics::Browser2::RegionSearch->new({opts})
47  
48 Create a new RegionSearch object. Required parameters are:
49  
50 Parameter Description
51  
52 source The Bio::Graphics::Browser2::DataSource
53 object describing the local and remote
54 databases for this source.
55  
56 state The page_settings document describing the
57 current state of the user session (for
58 looking up search_options and the like in the
59 future).
60  
61 =cut
62  
63 sub new {
64 my $self = shift;
65 my $args = shift;
66 my ($source,$state) = @{$args}{'source','state'};
67 return bless {
68 source => $source,
69 state => $state,
70 },ref($self) || $self;
71 }
72  
73 =head2 $db->init_databases(\@labels)
74  
75 This method will initialize all the databases in preparation for a
76 search. Pass it a list of track labels to search only in the databases
77 defined by those tracks. Otherwise it will sort all tracks into local
78 and remote ones.
79  
80 =cut
81  
82 sub init_databases {
83 my $self = shift;
84 my $track_labels = shift;
85 my $local_only = shift;
86  
87 my $state = $self->state;
88  
89 $self->{local_dbs} = {};
90 $self->{remote_dbs} = {};
91  
92 my %dbs;
93  
94 my $source = $self->source;
95 my $labels = $track_labels || [$source->labels];
96  
97 my $renderfarm = $self->source->global_setting('renderfarm');
98  
99 my $slave_status = Bio::Graphics::Browser2::Render::Slave::Status->new(
100 $source->globals->slave_status_path
101 );
102  
103 my %seenit;
104 for my $l (@$labels) {
105 next if $l =~ /^(_scale|builtin)/;
106 my ($dbid) = $source->db_settings($l) or next;
107 next if $seenit{$dbid}++;
108  
109 my $remote = $local_only || !$renderfarm
110 ? undef
111 : $source->fallback_setting($l => 'remote renderer');
112 if ($remote) {
113 my @remotes = shellwords($remote);
114 $remote = $slave_status->select(@remotes);
115 }
116  
117 my $search_options = $source->search_options($dbid);
118  
119 $dbs{$dbid}{options} ||= $search_options;
120 $dbs{$dbid}{remotes}{$remote}++ if $remote;
121 }
122  
123 # slightly roundabout way to get the default dbid, but this allows you
124 # to handle anonymous (unnamed) databases consistently.
125 my $default_dbid = $self->source->default_dbid;
126  
127 # try to spread the work out as much as possible among the remote renderers
128 my %remotes;
129 for my $dbid ($default_dbid,keys %dbs) {
130  
131 my $can_remote = keys %{$dbs{$dbid}{remotes}} && ($dbid ne $default_dbid);
132  
133 if ($can_remote) {
134 my @remote = keys %{$dbs{$dbid}{remotes}};
135 my ($least_used) = sort {($remotes{$a}||0) <=> ($remotes{$b}||0)} @remote;
136 $self->{remote_dbs}{$least_used}{$dbid}++;
137 $remotes{$least_used}++;
138 }
139
140 if (!$can_remote || $dbs{$dbid}{options} =~ /(?<!-)autocomplete/) {
141 $self->{local_dbs}{$dbid}++;
142 }
143 }
144 }
145  
146 =head2 $source = source()
147  
148 Return the data source.
149  
150 =cut
151  
152 sub source { shift->{source} }
153  
154 =head2 state()
155  
156 =cut
157  
158 sub state { shift->{state} }
159  
160 =head2 remote_dbs()
161  
162 =cut
163  
164 sub remote_dbs { shift->{remote_dbs} }
165  
166 =head2 local_dbs()
167  
168 =cut
169  
170 sub local_dbs { shift->{local_dbs} }
171  
172 =head2 @features = $db->features(@args)
173  
174 Pass @args to the underlying db adaptors' features() methods and return all
175 matching features. Example:
176  
177 @features = $db->features(-type=>'CDS')
178  
179 =cut
180  
181 sub features {
182 my $self = shift;
183  
184 my %args;
185 if (@_ == 0) {
186 %args = ();
187 }
188 elsif ($_[0] !~/^-/) {
189 my @types = @_;
190 %args = (-type=>\@types);
191 }
192 else {
193 %args = @_;
194 }
195 return $self->search_features(\%args);
196 }
197  
198 =head2 $meta_segment = $db->segment($segment)
199  
200 Given an existing segment, return a
201 Bio::Graphics::Browser2::MetaSegment object, which behaves more or
202 less like a regular Bio::Das::SegmentI object, but searches multiple
203 databases. Both iterative and non-iterative feature fetching is
204 supported.
205  
206 (The class definitions for Bio::Graphics::Browser2::MetaSegment are
207 located in the Bio/Graphics/Browser/RegionSearch.pm file.)
208  
209 =cut
210  
211 sub segment {
212 my $self = shift;
213 my $segment = shift;
214 return Bio::Graphics::Browser2::MetaSegment->new($self,$segment);
215 }
216  
217 =head2 $segment = $db->feature2segment($feature)
218  
219 Converts a feature into a segment in the database that the feature
220 corresponds to.
221  
222 =cut
223  
224 sub feature2segment {
225 my $self = shift;
226 my ($feature,$dbid) = @_;
227  
228 my $source = $self->source;
229 $dbid ||= $feature->gbrowse_dbid;
230 my $db = $source->open_database($dbid);
231  
232 my $region = Bio::Graphics::Browser2::Region->new(
233 { source => $source,
234 state => {},
235 db => $db,
236 searchopts => $source->search_options($dbid),
237 }
238 );
239 $region->features([$feature]);
240 return $region->seg;
241 }
242  
243 =head2 @segments = $db->features2segments($feature)
244  
245 As above, but takes an arrayref of features and returns an array of
246 segments.
247  
248 =cut
249  
250 sub features2segments {
251 my $self = shift;
252 my ($features,$dbid) = @_;
253  
254 my $source = $self->source;
255 my $db = $source->open_database($dbid);
256  
257 my $region = Bio::Graphics::Browser2::Region->new(
258 { source => $source,
259 state => {},
260 db => $db,
261 searchopts => $source->search_options($dbid),
262 }
263 );
264 my $s = $region->features2segments($features);
265 return unless $s;
266 return @$s;
267 }
268  
269  
270 =head2 $found = $db->search_features($args)
271  
272 This method will search all the databases for features matching the
273 search term and will return the results as an array ref of
274 Bio::SeqFeatureI objects. The arguments are a hash ref containing the
275 various options passed to the db adaptors' features() method
276 (e.g. "-type"), or a hashref with the key "-search_term", in which
277 case the search term is parsed as any of gbrowse's heuristic keyword
278 searches.
279  
280 If no args are provided, then the search term is taken from the "name"
281 field of the settings object.
282  
283 =cut
284  
285 sub search_features {
286 my $self = shift;
287 my $args = shift;
288 my $state = $self->state;
289 $args ||= {};
290  
291 if ($args && !ref($args)) {
292 $args = {-search_term=>$args}; #adjust for changed API
293 }
294  
295 unless (%$args) {
296 return unless $state->{name};
297 $args->{-search_term} = $state->{name}
298 }
299  
300 local $self->{shortcircuit} = 0;
301 my $local = $self->search_features_locally($args); # if default db has a hit, then we short circuit
302 my $remote = $self->search_features_remotely($args) unless $self->{shortcircuit};
303  
304 my @found;
305 push @found,@$local if $local && @$local;
306 push @found,@$remote if $remote && @$remote;
307  
308 # uniqueify features of the same type and name
309 my %seenit;
310  
311 @found = grep {
312 defined $_
313 && !$seenit{
314 (($state->{name} &&
315 lc $_->seq_id eq $state->{name}) # this hack gives special privileges to matches to seq_ids
316 ? 'region'
317 : $_->primary_tag),
318 $_->seq_id,
319 $_->start,
320 $_->end,
321 $_->strand}++} @found;
322 return wantarray ? @found : \@found;
323 }
324  
325 =head2 $found = $db->search_features_locally($args)
326  
327 Search only the local databases for the term.
328  
329 $Args is a hashref:
330  
331 Key Value
332 --- -----
333 -search_term term to search for
334 -shortcircuit stop searching if term is found in default db
335  
336 If -shortcircuit is not provided, it defaults to true.
337  
338 =cut
339  
340 sub search_features_locally {
341 my $self = shift;
342
343 my $timeout = $self->source->global_setting('search_timeout') || 10;
344  
345 my $result;
346  
347 warn "[$$] searching..." if DEBUG;
348  
349 # My oh my. block eval is not working as expected here. Sometimes the die is not caught.
350 my $status = eval <<'END';
351 local $SIG{ALRM} = sub { warn "alarm clock" ; die "The search timed out; try a more specific search\n"; die; };
352 alarm($timeout);
353 $result = $self->_search_features_locally(@_);
354 1;
355 END
356 alarm(0);
357 warn "[$$] search done..." if DEBUG;
358  
359 unless ($status) {
360 warn $@;
361 return;
362 }
363 return $result;
364 }
365  
366 sub _search_features_locally {
367 my $self = shift;
368 my $args = shift;
369 ref $args && %$args or return;
370  
371 my $shortcircuit = $args->{-shortcircuit};
372 $shortcircuit = 1 unless defined $shortcircuit;
373  
374 my $state = $self->state;
375 my $source = $self->source;
376  
377 my @found;
378  
379 # each local db gets a chance to search
380 my $local_dbs = $self->local_dbs;
381 return unless $local_dbs;
382  
383 warn "local dbs = ",join ' ',keys %{$local_dbs} if DEBUG;
384  
385 my @dbids = $state->{dbid} ? $state->{dbid}
386 : keys %{$local_dbs};
387  
388 # the default database is treated slightly differently - it is searched
389 # first, and finding a hit in it short-circuits other hits
390 my $default_dbid = $self->source->default_dbid;
391  
392 @dbids = sort {$a eq $default_dbid ? -1
393 :$b eq $default_dbid ? +1
394 :0} @dbids;
395  
396 warn "dbs = @dbids" if DEBUG;
397 my %seenit;
398  
399 for my $dbid (@dbids) {
400 my $opts = $self->source->search_options($dbid);
401 next if $opts =~ /none/i && ($args->{-name}||'') !~ /^id:/;
402 warn "searching in ",$dbid if DEBUG;
403 my $db = $self->source->open_database($dbid);
404 next if $seenit{$db}++;
405 my $region = Bio::Graphics::Browser2::Region->new(
406 { source => $self->source,
407 state => $self->state,
408 db => $db,
409 searchopts => $opts,
410 }
411 );
412 my $features = $region->search_features($args);
413 warn $features && @$features ? "[$$] got @$features" : "[$$] got no features" if DEBUG;
414 next unless $features && @$features;
415 $features = $self->filter_features($dbid,$features);
416 $self->add_dbid_to_features($dbid,$features);
417 push @found,@$features;
418
419 if ($dbid eq $default_dbid && $shortcircuit) {
420 warn "hit @found in the default database, so short-circuiting" if DEBUG;
421 last;
422 }
423
424 }
425  
426 return \@found;
427 }
428  
429 # remove any features in the database's "exclude types" list
430 sub filter_features {
431 my $self = shift;
432 my ($dbid,$features) = @_;
433 my %exclude = map {lc $_=> 1} $self->source->exclude_types($dbid);
434 return $features unless %exclude;
435 my @f = grep {!$exclude{lc $_->primary_tag}} @$features;
436 return \@f;
437 }
438  
439 =head2 $found = $db->search_features_remotely($args)
440  
441 Search only the remote databases for the term.
442  
443 =cut
444  
445 sub search_features_remotely {
446 my $self = shift;
447 my $args = shift;
448 ref $args && %$args or return;
449  
450 # each remote renderer gets a chance to search;
451 # we kick off these searches before we do local
452 # searches in order to take advantage of
453 # parallelism
454 my $remote_dbs = $self->remote_dbs;
455 return unless %$remote_dbs;
456  
457 warn "pid = $$: KICKING OFF A REMOTE SEARCH" if DEBUG;
458  
459 eval "require IO::Pipe;1;" unless IO::Pipe->can('new');
460 eval "require IO::Select;1;" unless IO::Select->can('new');
461  
462 my $select = IO::Select->new();
463  
464 for my $url (keys %$remote_dbs) {
465  
466 my $pipe = IO::Pipe->new();
467 my $child = Bio::Graphics::Browser2::Render->fork();
468 if ($child) { # parent
469 $pipe->reader();
470 $select->add($pipe);
471 }
472 else { # child
473 $pipe->writer();
474 $self->fetch_remote_features($args,$url,$pipe);
475 {
476 no warnings;
477 # bug workaround: prevent Session destroy method from
478 # flushing incomplete state!
479 *CGI::Session::DESTROY = sub { };
480 }
481 CORE::exit 0; # CORE::exit prevents modperl from running cleanup, etc
482 }
483 }
484  
485 my @found;
486 while ($select->count > 0) {
487  
488 my @ready = $select->can_read(5) or next;
489  
490 HANDLE:
491 for my $r (@ready) {
492 my $data;
493 my $bytes = $r->sysread($data,4);
494 unless ($bytes) { # eof
495 $select->remove($r);
496 $r->close;
497 next HANDLE;
498 }
499  
500 # This is not maximally efficient because we keep reading from the handle
501 # until we have gotten all the data. It would be more efficient to do a
502 # nonblocking read so that reads are interleaved, but it is MUCH harder
503 # to do.
504 my $data_len = unpack('N',$data);
505 $data = '';
506 while (length $data < $data_len) {
507 $bytes = $r->sysread($data,4096,length $data);
508 if ($bytes == 0) {
509 warn "premature EOF while reading search results: $!";
510 $select->remove($r);
511 $r->close;
512 next HANDLE;
513 }
514 }
515  
516 my $objects = thaw($data);
517 push @found,@$objects;
518 }
519 }
520  
521 if (my $fcgi = Bio::Graphics::Browser2::Render->fcgi_request()) {
522 $fcgi->Flush;
523 }
524  
525 return \@found;
526 }
527  
528 sub fetch_remote_features {
529 my $self = shift;
530 my ($args,$url,$outfh) = @_;
531  
532 $Storable::Deparse ||= 1;
533 my $s_dsn = nfreeze($self->source);
534 my $s_set = nfreeze($self->state);
535 my $s_args = nfreeze($args);
536 my %env = map {$_=>$ENV{$_}} grep /^GBROWSE/,keys %ENV;
537  
538 my @tracks = keys %{$self->remote_dbs->{$url}};
539 my $request = POST ($url,
540 Content_Type => 'form-data',
541 Content => [ operation => 'search_features',
542 settings => $s_set,
543 datasource => $s_dsn,
544 tracks => nfreeze(\@tracks),
545 env => nfreeze(\%env),
546 searchargs => $s_args,
547 ]);
548
549 my $ua = LWP::UserAgent->new();
550 my $timeout = $self->source->global_setting('slave_timeout')
551 || $self->source->global_setting('global_timeout') || 30;
552 $ua->timeout($timeout);
553  
554 $request->uri($url);
555 my $response = $ua->request($request);
556  
557 if ($response->is_success) {
558 my $content = $response->content;
559 $outfh->print(pack('N',length $content));
560 my $bytes = $outfh->print($content) or warn "write failed: $!";
561 } else {
562 my $uri = $request->uri;
563 warn "$uri; search failed: ",$response->status_line;
564 $outfh->close;
565 }
566 $outfh->close;
567 }
568  
569 =head2 $db->add_dbid_to_features($db,$features)
570  
571 Add a gbrowse_dbid() method to each of the features in the list.
572  
573 =cut
574  
575 sub add_dbid_to_features {
576 my $self = shift;
577 my ($dbid,$features) = @_;
578 return unless $features;
579 my $source = $self->source;
580 cluck "$dbid is not a dbid" if ref $dbid;
581 $source->add_dbid_to_feature($_,$dbid) foreach @$features;
582 }
583  
584 =head2 $mapper = $search->coordinate_mapper($segment,$optimize)
585  
586 Create a Bio::Graphics coordinator mapper on the current segment. If
587 optimize set to true, then features that map outside the current
588 segment's seqid and region are nulled.
589  
590 =cut
591  
592 sub coordinate_mapper {
593 my $self = shift;
594 my $current_segment = shift;
595 my $optimize = shift;
596  
597 my $db = $current_segment->factory;
598  
599 my ( $ref, $start, $stop ) = (
600 $current_segment->seq_id,
601 $current_segment->start,
602 $current_segment->end
603 );
604 my %segments;
605  
606 my $closure = sub {
607 my ( $refname, @ranges ) = @_;
608  
609 unless ( exists $segments{$refname} ) {
610 $segments{$refname} = $self->search_features({-search_term => $refname})->[0];
611 }
612 my $mapper = $segments{$refname} || return;
613 my $absref = $mapper->abs_ref;
614 my $cur_ref = eval { $current_segment->abs_ref }
615 || eval { $current_segment->ref }; # account for api changes in Bio::SeqI
616 return unless $absref eq $cur_ref;
617  
618 my @abs_segs;
619 if ( $absref eq $refname) { # doesn't need remapping
620 @abs_segs = @ranges;
621 }
622 elsif ($mapper->can('rel2abs')) {
623 @abs_segs
624 = map { [ $mapper->rel2abs( $_->[0], $_->[1] ) ] } @ranges;
625 } else {
626 my $map_start = $mapper->start;
627 my $map_strand = $mapper->strand;
628 if ($map_strand >= 0) {
629 @abs_segs = map {[$_->[0]+$map_start-1,$_->[1]+$map_start-1]} @ranges;
630 } else {
631 @abs_segs = map {[$map_start-$_->[0]+1,$map_start-$_->[1]+1]} @ranges;
632 $absref = $mapper->seq_id;
633 }
634 }
635  
636 # this inhibits mapping outside the displayed region
637 if ($optimize) {
638 my $in_window;
639 foreach (@abs_segs) {
640 next unless defined $_->[0] && defined $_->[1];
641 my ($left,$right) = sort {$a<=>$b} @$_;
642 $in_window ||= $_->[0] <= $right && $_->[1] >= $left;
643 }
644 return $in_window ? ( $absref, @abs_segs ) : ();
645 }
646 else {
647 return ( $absref, @abs_segs );
648 }
649 };
650 return $closure;
651 }
652  
653 sub features_by_prefix {
654 my $self = shift;
655 my $match = shift;
656 my $limit = shift;
657  
658 # do name search for autocomplete...
659 # only local databases for now
660 my $local_dbs = $self->local_dbs;
661 my (@f,$count);
662 my $source = $self->source;
663 for my $dbid (keys %{$local_dbs}) {
664 my $options =
665 Bio::Graphics::Browser2::Region->parse_searchopts($source->search_options($dbid));
666 next unless $options && $options->{autocomplete};
667  
668 my $db = $source->open_database($dbid);
669 eval {
670 my $i = $db->get_seq_stream(-name=>"${match}*",
671 -aliases=>1);
672 while (my $f = $i->next_seq) {
673 push @f,$f;
674 last if $limit && $count++ > $limit;
675 }
676 };
677 }
678 return \@f;
679 }
680  
681 sub get_seq_stream {
682 my $self = shift;
683  
684 my @search_args = @_;
685 my $local_dbs = $self->local_dbs;
686 my @dbs = map {$self->source->open_database($_)}keys %$local_dbs;
687 return Bio::Graphics::Browser2::MetaDB->new(\@search_args,\@dbs);
688 }
689  
690 ##################################################################33
691 # META SEGMENT DEFINITIONS
692 ##################################################################33
693 package Bio::Graphics::Browser2::MetaSegment;
694  
695 our $AUTOLOAD;
696 use overload
697 '""' => \&as_string,
698 fallback => 1;
699  
700 sub new {
701 my $class = shift;
702 my ($region_search,$segment) = @_;
703 return bless {db => $region_search,
704 segment => $segment},ref $class || $class;
705 }
706  
707 sub AUTOLOAD {
708 my($pack,$func_name) = $AUTOLOAD=~/(.+)::([^:]+)$/;
709 return if $func_name eq 'DESTROY';
710 my $self = shift or die;
711 $self->segment->$func_name(@_);
712 }
713  
714 sub db { shift->{db} }
715 sub segment { shift->{segment} }
716 sub as_string {
717 my $segment = shift->segment;
718 return $segment->seq_id.':'.$segment->start.'..'.$segment->end;
719 }
720  
721 sub features {
722 my $self = shift;
723 my $segment = $self->segment;
724 $self->db->features(-seq_id => $segment->seq_id,
725 -start => $segment->start,
726 -end => $segment->end,
727 # -class => eval {$segment->class} || 'Sequence',
728 @_
729 );
730 }
731  
732 sub get_seq_stream {
733 my $self = shift;
734 my $features = $self->features(@_);
735 return Bio::Graphics::Browser2::MetaSegment::Iterator->new($features);
736 }
737  
738 package Bio::Graphics::Browser2::MetaSegment::Iterator;
739  
740 sub new {
741 my $class = shift;
742 my $features = shift;
743 return bless {f=>$features},ref $class || $class;
744 }
745  
746 sub next_seq {
747 my $f = shift->{f};
748 return shift @$f;
749 }
750  
751 package Bio::Graphics::Browser2::MetaDB;
752  
753 sub new {
754 my $self = shift;
755 my ($search_args,$dbs) = @_;
756 return bless {
757 dbs => $dbs,
758 args => $search_args,
759 current => undef
760 },ref $self || $self;
761 }
762  
763 sub next_seq {
764 my $self = shift;
765 while (1) {
766 if (my $iterator = $self->{current}) {
767 my $f = $iterator->next_seq;
768 return $f if defined $f;
769 }
770  
771 my $next_db = shift @{$self->{dbs}} or return;
772 $self->{current} = $next_db->get_seq_stream(@{$self->{args}});
773 }
774 }
775  
776 1;
777  
778 __END__