EnsEMBL/DBSQL/BaseFeatureAdaptor.pm untested

filter: Statementstmt 0.0% 0 / 644 Branchbran 0.0% 0 / 238 Conditioncond 0.0% 0 / 219 Subroutinesub 0.0% 0 / 49 Podpod 0.0% 0 / 41 totaltotal 0.0% 0 / 1191 CC 120 SCAR 47.0
CC
120
Cov
0%
fetch_all_nearest_by_Feature
380.0
_get_by_Slice
306.0
fetch_all_by_Slice_constraint
156.0
CRAP 109.4
1 =head1 LICENSE
2  
3 See the NOTICE file distributed with this work for additional information
4 regarding copyright ownership.
5  
6 Licensed under the Apache License, Version 2.0 (the "License");
7 you may not use this file except in compliance with the License.
8 You may obtain a copy of the License at
9  
10 http://www.apache.org/licenses/LICENSE-2.0
11  
12 Unless required by applicable law or agreed to in writing, software
13 distributed under the License is distributed on an "AS IS" BASIS,
14 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 See the License for the specific language governing permissions and
16 limitations under the License.
17  
18 =cut
19  
20  
21 =head1 CONTACT
22  
23 Please email comments or questions to the public Ensembl
24 developers list at <http://lists.ensembl.org/mailman/listinfo/dev>.
25  
26 Questions may also be sent to the Ensembl help desk at
27 <http://www.ensembl.org/Help/Contact>.
28  
29 =cut
30  
31 =head1 NAME
32  
33 Bio::EnsEMBL::DBSQL::BaseFeatureAdaptor - An Abstract Base class for all
34 FeatureAdaptors
35  
36 =head1 SYNOPSIS
37  
38 Abstract class - should not be instantiated. Implementation of
39 abstract methods must be performed by subclasses.
40  
41 =head1 DESCRIPTION
42  
43 This is a base adaptor for feature adaptors. This base class is simply a way
44 of eliminating code duplication through the implementation of methods
45 common to all feature adaptors.
46  
47 =head1 METHODS
48  
49 =cut
50  
51 package Bio::EnsEMBL::DBSQL::BaseFeatureAdaptor;
52 $Bio::EnsEMBL::DBSQL::BaseFeatureAdaptor::VERSION = '114.0.0_50'; # TRIAL
53 $Bio::EnsEMBL::DBSQL::BaseFeatureAdaptor::VERSION = '114.0.050';
54 use vars qw(@ISA @EXPORT);
55 use strict;
56  
57 use Bio::EnsEMBL::DBSQL::BaseAdaptor;
58 use Bio::EnsEMBL::Utils::Cache;
59 use Bio::EnsEMBL::Utils::Exception qw(warning throw);
60 use Bio::EnsEMBL::Utils::Argument qw(rearrange);
61 use Bio::EnsEMBL::Utils::Iterator;
62 use Bio::EnsEMBL::Utils::Scalar qw/assert_ref/;
63  
64 @ISA = qw(Bio::EnsEMBL::DBSQL::BaseAdaptor);
65  
66 @EXPORT = (@{$DBI::EXPORT_TAGS{'sql_types'}});
67  
68 our $SLICE_FEATURE_CACHE_SIZE = 4;
69 our $MAX_SPLIT_QUERY_SEQ_REGIONS = 3;
70 our $SILENCE_CACHE_WARNINGS = 0;
71  
72 =head2 new
73  
74 Arg [1] : list of args @args
75 Superclass constructor arguments
76 Example : none
77 Description: Constructor which warns if caching has been switched off
78 Returntype : Bio::EnsEMBL::BaseFeatureAdaptor
79 Exceptions : none
80 Caller : implementing subclass constructors
81 Status : Stable
82  
83 =cut
84  
85 sub new {
86 my ($class, @args) = @_;
87 my $self = $class->SUPER::new(@args);
88 if ( defined $self->db->no_cache() && $self->db->no_cache() && ! $SILENCE_CACHE_WARNINGS) {
89 warning( "You are using the API without caching most recent features. "
90 . "Performance might be affected." );
91 }
92 return $self;
93 }
94  
95 =head2 start_equals_end
96  
97 Arg [1] : (optional) boolean $newval
98 Example : $bfa->start_equals_end(1);
99 Description: Getter/Setter for the start_equals_end flag. If set
100 to true sub _slice_fetch will use a simplified sql to retrieve 1bp slices.
101 Returntype : boolean
102 Exceptions : none
103 Caller : EnsemblGenomes variation DB build
104 Status : Stable
105
106 =cut
107  
108 sub start_equals_end {
109 my ( $self, $value ) = @_;
110  
111 if ( defined($value) ) {
112 $self->{'start_equals_end'} = $value;
113 }
114 return $self->{'start_equals_end'};
115 }
116  
117  
118 =head2 clear_cache
119  
120 Args : None
121 Example : my $sa =
122 $registry->get_adaptor( 'Mus musculus', 'Core',
123 'Slice' );
124 my $ga =
125 $registry->get_adaptor( 'Mus musculus', 'Core',
126 'Gene' );
127  
128 my $slice =
129 $sa->fetch_by_region( 'Chromosome', '1', 1e8,
130 1.05e8 );
131  
132 my $genes = $ga->fetch_all_by_Slice($slice);
133  
134 $ga->clear_cache();
135  
136 Description : Empties the feature cache associated with this
137 feature adaptor.
138 Return type : None
139 Exceptions : None
140 Caller : General
141 Status : At risk (under development)
142  
143 =cut
144  
145 sub clear_cache {
146 my ($self) = @_;
147 $self->_clear_slice_feature_cache();
148 if(!$self->_no_id_cache()) {
149 $self->_id_cache()->clear_cache();
150 }
151 return;
152 }
153  
154 sub _clear_slice_feature_cache {
155 my ($self) = @_;
156 %{$self->{_slice_feature_cache}} = ();
157 return;
158 }
159  
160 =head2 _slice_feature_cache
161
162 Description : Returns the feature cache if we are allowed to cache and
163 will build it if we need to. We will never return a reference
164 to the hash to avoid unintentional auto-vivfying caching
165 Returntype : Bio::EnsEMBL::Utils::Cache
166 Exceptions : None
167 Caller : Internal
168  
169 =cut
170  
171 sub _slice_feature_cache {
172 my ($self) = @_;
173 return if $self->db()->no_cache();
174 if(! exists $self->{_slice_feature_cache}) {
175 tie my %cache, 'Bio::EnsEMBL::Utils::Cache', $SLICE_FEATURE_CACHE_SIZE;
176 $self->{_slice_feature_cache} = \%cache;
177 }
178 return $self->{_slice_feature_cache};
179 }
180  
181 =head2 fetch_all_by_Slice
182  
183 Arg [1] : Bio::EnsEMBL::Slice $slice
184 the slice from which to obtain features
185 Arg [2] : (optional) string $logic_name
186 the logic name of the type of features to obtain
187 Example : $fts = $a->fetch_all_by_Slice($slice, 'Swall');
188 Description: Returns a listref of features created from the database
189 which are on the Slice defined by $slice. If $logic_name is
190 defined only features with an analysis of type $logic_name
191 will be returned.
192 NOTE: only features that are entirely on the slice's seq_region
193 will be returned (i.e. if they hang off the start/end of a
194 seq_region they will be discarded). Features can extend over the
195 slice boundaries though (in cases where you have a slice that
196 doesn't span the whole seq_region).
197 Returntype : listref of Bio::EnsEMBL::SeqFeatures in Slice coordinates
198 Exceptions : none
199 Caller : Bio::EnsEMBL::Slice
200 Status : Stable
201  
202 =cut
203  
204 sub fetch_all_by_Slice {
205 my ($self, $slice, $logic_name) = @_;
206 #fetch by constraint with empty constraint
207 return $self->fetch_all_by_Slice_constraint($slice, '', $logic_name);
208 }
209  
210  
211  
212 =head2 fetch_Iterator_by_Slice_method
213  
214 Arg [1] : CODE ref of Slice fetch method
215 Arg [2] : ARRAY ref of parameters for Slice fetch method
216 Arg [3] : Optional int: Slice index in parameters array
217 Arg [4] : Optional int: Slice chunk size. Default=500000
218 Example : my $slice_iter = $feature_adaptor->fetch_Iterator_by_Slice_method
219 ($feature_adaptor->can('fetch_all_by_Slice_Arrays'),
220 \@fetch_method_params,
221 0,#Slice idx
222 );
223  
224 while(my $feature = $slice_iter->next && defined $feature){
225 #Do something here
226 }
227  
228 Description: Creates an Iterator which chunks the query Slice to facilitate
229 large Slice queries which would have previously run out of memory
230 Returntype : Bio::EnsEMBL::Utils::Iterator
231 Exceptions : Throws if mandatory params not valid
232 Caller : general
233 Status : at risk
234  
235 =cut
236  
237 #Does not support Collections. See Funcgen ResultFeatureAdaptor::fetch_collection_Iterator_by_Slice_method
238  
239 sub fetch_Iterator_by_Slice_method{
240 my ($self, $slice_method_ref, $params_ref, $slice_idx, $chunk_size) = @_;
241  
242 if(! ( defined $slice_method_ref &&
243 ref($slice_method_ref) eq 'CODE')
244 ){
245 throw('Must pass a valid Slice fetch method CODE ref');
246 }
247  
248 if (! ($params_ref &&
249 ref($params_ref) eq 'ARRAY')) {
250 #Don't need to check size here so long as we have valid Slice
251 throw('You must pass a method params ARRAYREF');
252 }
253
254 $slice_idx = 0 if(! defined $slice_idx);
255 my $slice = $params_ref->[$slice_idx];
256 $chunk_size ||= 1000000;
257
258 my @feat_cache;
259 my $finished = 0;
260 my $start = 1; #local coord for sub slice
261 my $end = $slice->length;
262 my $num_overlaps = 0;
263
264 my $coderef =
265 sub {
266
267 while (scalar(@feat_cache) == 0 &&
268 ! $finished) {
269
270 my $new_end = ($start + $chunk_size - 1);
271
272 if ($new_end >= $end) {
273 # this is our last chunk
274 $new_end = $end;
275 $finished = 1;
276 }
277
278 #Chunk by sub slicing
279 my $sub_slice = $slice->sub_Slice($start, $new_end);
280 $params_ref->[$slice_idx] = $sub_slice;
281 @feat_cache = @{ $slice_method_ref->($self, @$params_ref)};
282
283 #Remove & count overlapping features
284 splice(@feat_cache, 0, $num_overlaps) if($num_overlaps);
285 my $i;
286
287 if (scalar(@feat_cache) > 0) {
288
289 my $feat_end = $feat_cache[$#feat_cache]->seq_region_end;
290 my $slice_end = $sub_slice->end;
291 $num_overlaps = 0;
292 for ($i = $#feat_cache; $i >=0; $i--) {
293 $feat_end = $feat_cache[$i]->seq_region_end;
294
295 if ($feat_end > $slice_end) {
296 $num_overlaps ++;
297 } else {
298 last;
299 }
300
301 }
302 }
303
304 # update the start coordinate
305 $start = $new_end + 1;
306 }
307
308 #this maybe returning from an undef cache
309 #Need to sub this out even more?
310 return shift @feat_cache;
311 };
312  
313 return Bio::EnsEMBL::Utils::Iterator->new($coderef);
314 }
315  
316  
317 =head2 fetch_Iterator_by_Slice
318  
319 Arg [1] : Bio::EnsEMBL::Slice
320 Arg [2] : Optional string: logic name of analysis
321 Arg [3] : Optional int: Chunk size to iterate over. Default is 500000
322 Example : my $slice_iter = $feature_adaptor->fetch_Iterator_by_Slice($slice);
323  
324 while(my $feature = $slice_iter->next && defined $feature){
325 #Do something here
326 }
327  
328 Description: Creates an Iterator which chunks the query Slice to facilitate
329 large Slice queries which would have previously run out of memory
330 Returntype : Bio::EnsEMBL::Utils::Iterator
331 Exceptions : None
332 Caller : general
333 Status : at risk
334  
335 =cut
336  
337 sub fetch_Iterator_by_Slice{
338 my ($self, $slice, $logic_name, $chunk_size) = @_;
339  
340 my $method_ref = $self->can('fetch_all_by_Slice');
341  
342 return $self->fetch_Iterator_by_Slice_method($method_ref, [$slice, $logic_name], 0, $chunk_size);
343 }
344  
345  
346 =head2 fetch_all_by_Slice_and_score
347  
348 Arg [1] : Bio::EnsEMBL::Slice $slice
349 the slice from which to obtain features
350 Arg [2] : (optional) float $score
351 lower bound of the the score of the features retrieved
352 Arg [3] : (optional) string $logic_name
353 the logic name of the type of features to obtain
354 Example : $fts = $a->fetch_all_by_Slice_and_score($slice,90,'Swall');
355 Description: Returns a list of features created from the database which are
356 are on the Slice defined by $slice and which have a score
357 greater than $score. If $logic_name is defined,
358 only features with an analysis of type $logic_name will be
359 returned.
360 Returntype : listref of Bio::EnsEMBL::SeqFeatures in Slice coordinates
361 Exceptions : none
362 Caller : Bio::EnsEMBL::Slice
363 Status : Stable
364  
365 =cut
366  
367 sub fetch_all_by_Slice_and_score {
368 my ( $self, $slice, $score, $logic_name ) = @_;
369  
370 my $constraint;
371 if ( defined($score) ) {
372 # Get the synonym of the primary_table
373 my @tabs = $self->_tables();
374 my $syn = $tabs[0]->[1];
375  
376 $constraint = sprintf( "%s.score > %s",
377 $syn,
378 $self->dbc()->db_handle()->quote( $score, SQL_FLOAT ) );
379 }
380  
381 return
382 $self->fetch_all_by_Slice_constraint( $slice, $constraint,
383 $logic_name );
384 }
385  
386  
387 =head2 fetch_all_by_Slice_constraint
388  
389 Arg [1] : Bio::EnsEMBL::Slice $slice
390 the slice from which to obtain features
391 Arg [2] : (optional) string $constraint
392 An SQL query constraint (i.e. part of the WHERE clause)
393 Arg [3] : (optional) string $logic_name
394 the logic name of the type of features to obtain
395 Example : $fs = $a->fetch_all_by_Slice_constraint($slc, 'perc_ident > 5');
396 Description: Returns a listref of features created from the database which
397 are on the Slice defined by $slice and fulfill the SQL
398 constraint defined by $constraint. If logic name is defined,
399 only features with an analysis of type $logic_name will be
400 returned.
401 Returntype : listref of Bio::EnsEMBL::SeqFeatures in Slice coordinates
402 Exceptions : thrown if $slice is not defined
403 Caller : Bio::EnsEMBL::Slice
404 Status : Stable
405  
406 =cut
407  
408 sub fetch_all_by_Slice_constraint {
409 my ( $self, $slice, $constraint, $logic_name ) = @_;
410  
411 my @result;
412  
413 #Pull out here as we need to remember them & reset accordingly
414 my $bind_params = $self->bind_param_generic_fetch();
415  
416 if ( !ref($slice)
417 || !( $slice->isa('Bio::EnsEMBL::Slice')
418 or $slice->isa('Bio::EnsEMBL::LRGSlice') ) )
419 {
420 throw("Bio::EnsEMBL::Slice argument expected.");
421 }
422  
423 $constraint ||= '';
424 $constraint =
425 $self->_logic_name_to_constraint( $constraint, $logic_name );
426  
427 # If the logic name was invalid, undef was returned
428 if ( !defined($constraint) ) { return [] }
429  
430 my $key;
431 my $cache;
432  
433 # Will only use feature_cache if hasn't been no_cache attribute set
434 if (
435 !( defined( $self->db()->no_cache() ) && $self->db()->no_cache() ) )
436 {
437  
438 #strain test and add to constraint if so to stop caching.
439 if ( $slice->isa('Bio::EnsEMBL::Variation::StrainSlice') ) {
440 my $string =
441 $self->dbc()->db_handle()->quote( $slice->strain_name() );
442  
443 if ( $constraint ne "" ) {
444 $constraint .= " AND $string = $string ";
445 } else {
446 $constraint .= " $string = $string ";
447 }
448 }
449  
450 # Check the cache and return the cached results if we have already
451 # done this query. The cache key is the made up from the slice
452 # name, the constraint, and the bound parameters (if there are any).
453 $key = uc( join( ':', $slice->name(), $constraint ) );
454  
455 if ( defined($bind_params) ) {
456 $key .= ':'
457 . join( ':', map { $_->[0] . '/' . $_->[1] } @{$bind_params} );
458 }
459  
460 $cache = $self->_slice_feature_cache();
461 if ( exists( $cache->{$key} ) ) {
462 # Clear the bound parameters and return the cached data.
463 $self->{'_bind_param_generic_fetch'} = ();
464 #IMPORTANT: NEVER EVER RETURN A COPY OF THE DATA STRUCTURE.
465 # This will hold arrays of values. Since we've been doing
466 # this for so long people are expecting multiple calls
467 # to fetch_by_SliceXXXXX() methods to return the same
468 # array reference.
469 return $cache->{$key};
470 }
471 } ## end if ( !( defined( $self...)))
472  
473  
474 my $proj_ref = $self->_get_and_filter_Slice_projections($slice);
475 my $bounds = $self->_generate_feature_bounds($slice);
476  
477 # fetch features for the primary slice AND all symlinked slices
478 foreach my $seg (@{$proj_ref}) {
479 # re-bind the params
480 $self->_bind_param_generic_fetch($bind_params);
481 my $offset = $seg->from_start();
482 my $seg_slice = $seg->to_Slice();
483 my $features =
484 $self->_slice_fetch( $seg_slice, $constraint );
485  
486 # If this was a symlinked slice offset the feature coordinates as
487 # needed.
488 if ( $seg_slice->name() ne $slice->name() ) {
489  
490 FEATURE:
491 foreach my $f ( @{$features} ) {
492 if ( $offset != 1 ) {
493 $f->{'start'} += $offset - 1;
494 $f->{'end'} += $offset - 1;
495 }
496  
497 # discard boundary crossing features from symlinked regions
498 foreach my $bound (@{$bounds}) {
499 if ( $f->{'start'} < $bound && $f->{'end'} >= $bound ) {
500 next FEATURE;
501 }
502 }
503  
504 $f->{'slice'} = $slice;
505 push( @result, $f );
506 }
507 } else {
508 push( @result, @{$features} );
509 }
510 } ## end foreach my $seg (@proj)
511  
512 # Will only use feature_cache when set attribute no_cache in DBAdaptor
513 if ( defined($key) ) {
514 $cache->{$key} = \@result;
515 }
516  
517 return \@result;
518 } ## end sub fetch_all_by_Slice_constraint
519  
520  
521 =head2 fetch_all_by_logic_name
522  
523 Arg [1] : string $logic_name
524 the logic name of the type of features to obtain
525 Example : $fs = $a->fetch_all_by_logic_name('foobar');
526 Description: Returns a listref of features created from the database.
527 only features with an analysis of type $logic_name will
528 be returned. If the logic name is invalid (not in the
529 analysis table), a reference to an empty list will be
530 returned.
531 Returntype : listref of Bio::EnsEMBL::SeqFeatures
532 Exceptions : thrown if no $logic_name
533 Caller : General
534 Status : Stable
535  
536 =cut
537  
538 sub fetch_all_by_logic_name {
539 my ( $self, $logic_name ) = @_;
540  
541 if ( !defined($logic_name) ) {
542 throw("Need a logic_name");
543 }
544  
545 my $constraint = $self->_logic_name_to_constraint( '', $logic_name );
546  
547 if ( !defined($constraint) ) {
548 warning("Invalid logic name: $logic_name");
549 return [];
550 }
551  
552 return $self->generic_fetch($constraint);
553 }
554  
555 =head2 fetch_all_by_stable_id_list
556  
557 Arg [1] : string $logic_name
558 the logic name of the type of features to obtain
559 Arg [2] : Bio::EnsEMBL::Slice $slice
560 the slice from which to obtain features
561 Example : $fs = $a->fetch_all_by_stable_id_list(["ENSG00001","ENSG00002", ...]);
562 Description: Returns a listref of features identified by their stable IDs.
563 This method only fetches features of the same type as the calling
564 adaptor.
565 Results are constrained to a slice if the slice is provided.
566 Returntype : listref of Bio::EnsEMBL::Feature
567 Exceptions : thrown if no stable ID list is provided.
568 Caller : General
569 Status : Stable
570  
571 =cut
572  
573 # Adapted from BaseAdaptor->uncached_fetch_all_by_dbID_list
574 sub fetch_all_by_stable_id_list {
575 my ( $self, $id_list_ref, $slice ) = @_;
576  
577 return $self->_uncached_fetch_all_by_id_list($id_list_ref,$slice,"stable_id");
578 }
579  
580 # Method that creates an object. Called by the _objs_from_sth() method
581 # in the sub-classes (the various feature adaptors). Overridden by the
582 # feature collection classes.
583  
584 sub _create_feature {
585 my ( $self, $feature_type, $args ) = @_;
586 return $feature_type->new( %{$args} );
587 }
588  
589 # This is the same as the above, but calls the new_fast() constructor of
590 # the feature type.
591  
592 sub _create_feature_fast {
593 my ( $self, $feature_type, $args ) = @_;
594 return $feature_type->new_fast($args);
595 }
596  
597 =head2 count_by_Slice_constraint
598  
599 Arg [1] : Bio::EnsEMBL::Slice
600 Arg [2] : String Custom SQL constraint
601 Arg [3] : String Logic name to search by
602 Description : Finds all features with at least partial overlap to the given
603 slice and sums them up.
604 Explanation of workings with projections:
605
606 |-------------------------Constraint Slice---------------------------------|
607 | | | |
608 |--Segment 1--| | |
609 | |--Segment 2, on desired Coordinate System--| |
610 | | |---Segment 3----|
611 #Feature 1# #Feature 2# #Feature 3# |
612 | #####################Feature 4#################### |
613 | #Feature 5# | | |
614
615 Feature 1 is overlapping the original constraint. Counted in Segment 1
616 Feature 2,3 and 4 are counted when inspecting Segment 2
617 Feature 5 is counted in Segment 1
618
619 Returntype : Integer
620 =cut
621  
622 sub count_by_Slice_constraint {
623 my ($self, $slice, $constraint, $logic_name) = @_;
624
625 assert_ref($slice, 'Bio::EnsEMBL::Slice', 'slice');
626
627 my $count = 0;
628
629 #Remember the bind params
630 my $bind_params = $self->bind_param_generic_fetch();
631
632 #Table synonym
633 my @tables = $self->_tables;
634 my ($table_name, $table_synonym) = @{ $tables[0] };
635
636 # Basic constraints limit the feature hits to the starting Slice constraint
637 $constraint ||= '';
638 $constraint = $self->_logic_name_to_constraint( $constraint, $logic_name );
639
640 return $count if ! defined $constraint;
641
642 #Query logic
643 my $sa = $slice->adaptor();
644 my $projections = $self->_get_and_filter_Slice_projections($slice);
645  
646 my $segment_count = @{$projections};
647 #Manual loop to support look-ahead/behind
648 for (my $i = 0; $i < $segment_count; $i++) {
649 my $seg = $projections->[$i];
650 my $seg_slice = $seg->to_Slice();
651 $self->_bind_param_generic_fetch($bind_params);
652
653 # We cannot filter boundary crossing features in code, so we constrain the
654 # SQL. We detect when we are not on the original query Slice and manually
655 # filter by the segment Slice's start and end. If we are on "earlier" (5')
656 # projection segments, we only limit by the *end* and when we are on the later
657 # projection segments, we filter by the *start*.
658
659 # This is the same as fetch_all_by_Slice_constraint()'s in-memory filtering
660 # except we need to alter projected features in that code with an offset
661 my $local_constraint = $constraint;
662 if ( $seg_slice->name() ne $slice->name() ) {
663 my ($limit_start, $limit_end) = (1,1); #fully constrained by default, flags are reset every iteration
664 if($i == 0) {
665 $limit_start = 0;
666 } elsif ($i == ($segment_count - 1)) {
667 $limit_end = 0; #don't check end as we are on the final projection
668 }
669 $local_constraint .= ' AND ' if $local_constraint;
670 my @conditionals;
671
672 if($limit_end) {
673 # Restrict features to the end of this projection segment when after the named segment
674 push(@conditionals, sprintf('%1$s.seq_region_end <= %2$d', $table_synonym, $seg_slice->end));
675 }
676 if($limit_start) {
677 #Do not cross the start boundary on this projection segment
678 push(@conditionals, sprintf('%1$s.seq_region_start >= %2$d', $table_synonym, $seg_slice->start));
679 }
680
681 $local_constraint .= join(q{ AND }, @conditionals);
682 }
683
684 my $count_array = $self->_get_by_Slice($seg_slice, $local_constraint, 'count');
685 $count += $_ for @$count_array;
686 }
687
688 return $count;
689 }
690  
691 =head2 _get_and_filter_Slice_projections
692  
693 Arg [1] : Bio::EnsEMBL::Slice
694 Description : Delegates onto SliceAdaptor::fetch_normalized_slice_projection()
695 with filtering on
696 Returntype : ArrayRef Bio::EnsEMBL::ProjectionSegment; Returns an array
697 of projected segments
698 =cut
699  
700 sub _get_and_filter_Slice_projections {
701 my ($self, $slice) = @_;
702 my $sa = $slice->adaptor();
703 my $filter_projections = 1;
704 return $sa->fetch_normalized_slice_projection($slice, $filter_projections);
705 }
706  
707 =head2 _generate_feature_bounds
708  
709 Arg [1] : Bio::EnsEMBL::Slice
710 Description : Performs a projection of Slice and records the bounds
711 of that projection. This can be used later on to restrict
712 Features which overlap into unwanted areas such as
713 regions which exist on another HAP/PAR region.
714
715 Bounds are defined as projection_start - slice_start + 1.
716 Example : my $bounds = $self->_generate_feature_bounds($slice);
717 Returntype : ArrayRef Integer; Returns the location of the bounds.
718 =cut
719  
720 sub _generate_feature_bounds {
721 my ($self, $slice) = @_;
722 my $sa = $slice->adaptor();
723 # construct list of Hap/PAR boundaries for entire seq region
724 my @bounds;
725  
726 my $sr_id = $slice->get_seq_region_id();
727 my $ent_slice = $sa->fetch_by_seq_region_id($sr_id);
728 if ( $slice->strand() == -1 ) {
729 $ent_slice = $ent_slice->invert();
730 }
731  
732 my @ent_proj = @{ $sa->fetch_normalized_slice_projection($ent_slice) };
733 shift(@ent_proj); # skip first; 1st does not have bounds normally; may change if we ever have a patch a pos 1
734  
735 @bounds = map { $_->from_start() - $slice->start() + 1 } @ent_proj;
736
737 return \@bounds;
738 }
739  
740 =head2 _get_by_Slice
741 Arg [0] : Bio::EnsEMBL::Slice to find all the features within
742 Arg [1] : SQL constraint string
743 Arg [2] : Type of query to run. Default behaviour is to select, but
744 'count' is also valid
745 Description: Abstracted logic from _slice_fetch
746 Returntype : Listref of Bio::EnsEMBL::Feature, or integers for counting mode
747 =cut
748  
749 sub _get_by_Slice {
750 my ($self, $slice, $orig_constraint, $query_type) = @_;
751
752 # features can be scattered across multiple coordinate systems
753 my @tables = $self->_tables;
754 my ($table_name, $table_synonym) = @{ $tables[0] };
755 my $mapper;
756 my @feature_coord_systems;
757
758 my $meta_values = $self->db->get_MetaContainer->list_value_by_key( $table_name."build.level");
759 if ( @$meta_values and $slice->is_toplevel() ) {
760 push @feature_coord_systems, $slice->coord_system();
761 } else {
762 @feature_coord_systems = @{ $self->db->get_MetaCoordContainer->fetch_all_CoordSystems_by_feature_type($table_name)};
763 }
764
765 my $assembly_mapper_adaptor = $self->db->get_AssemblyMapperAdaptor();
766 my @pan_coord_features;
767
768 COORD_SYSTEM: foreach my $coord_system (@feature_coord_systems) {
769 my @query_accumulator;
770 # Build up a combination of query constraints that will quickly establish the result set
771 my $constraint = $orig_constraint;
772 if ( $coord_system->equals( $slice->coord_system ) ) {
773 my $max_len = $self->_max_feature_length
774 || $self->db->get_MetaCoordContainer
775 ->fetch_max_length_by_CoordSystem_feature_type( $coord_system,$table_name );
776
777 my $seq_region_id;
778 if ( $slice->adaptor ) {
779 $seq_region_id = $slice->adaptor->get_seq_region_id($slice);
780 } else {
781 $seq_region_id = $self->db->get_SliceAdaptor->get_seq_region_id($slice);
782 }
783
784 my @seq_region_ids = ($seq_region_id);
785 while (1) {
786 my $ext_seq_region_id = $self->get_seq_region_id_external($seq_region_id);
787
788 if ( $ext_seq_region_id == $seq_region_id ) { last }
789
790 push( @seq_region_ids, $ext_seq_region_id );
791 $seq_region_id = $ext_seq_region_id;
792 }
793
794 $constraint .= " AND " if ($constraint);
795  
796 $constraint .= ${table_synonym}.".seq_region_id IN (". join( ',', @seq_region_ids ) . ") AND ";
797
798 #faster query for 1bp slices where SNP data is not compressed
799 if ( $self->start_equals_end && $slice->start == $slice->end ) {
800 $constraint .= " AND ".$table_synonym.".seq_region_start = ".$slice->end .
801 " AND ".$table_synonym.".seq_region_end = ".$slice->start;
802
803 } else {
804 if ( !$slice->is_circular() ) {
805 # Deal with the default case of a non-circular chromosome.
806 $constraint .= $table_synonym.".seq_region_start <= ".$slice->end." AND "
807 .$table_synonym.".seq_region_end >= ".$slice->start;
808
809 if ( $max_len ) {
810 my $min_start = $slice->start - $max_len;
811 $constraint .= " AND ".$table_synonym.".seq_region_start >= ".$min_start;
812 }
813
814 } else {
815 # Deal with the case of a circular chromosome.
816 if ( $slice->start > $slice->end ) {
817 $constraint .= " ( ".$table_synonym.".seq_region_start >= ".$slice->start
818 . " OR ".$table_synonym.".seq_region_start <= ".$slice->end
819 . " OR ".$table_synonym.".seq_region_end >= ".$slice->start
820 . " OR ".$table_synonym.".seq_region_end <= ".$slice->end
821 . " OR ".$table_synonym.".seq_region_start > ".$table_synonym.".seq_region_end)";
822 } else {
823 $constraint .= " ((".$table_synonym.".seq_region_start <= ".$slice->end
824 . " AND ".$table_synonym.".seq_region_end >= ".$slice->start.") "
825 . "OR (".$table_synonym.".seq_region_start > ".$table_synonym.".seq_region_end"
826 . " AND (".$table_synonym.".seq_region_start <= ".$slice->end
827 . " OR ".$table_synonym.".seq_region_end >= ".$slice->start.")))";
828 }
829 }
830 }
831 push @query_accumulator, [$constraint,undef,$slice]; # $mapper intentionally absent here.
832
833 } else {
834 #coordinate systems do not match
835 $mapper = $assembly_mapper_adaptor->fetch_by_CoordSystems( $slice->coord_system(), $coord_system );
836 next unless defined $mapper;
837  
838 # Get list of coordinates and corresponding internal ids for
839 # regions the slice spans
840 my @coords = $mapper->map( $slice->seq_region_name, $slice->start, $slice->end,
841 $slice->strand, $slice->coord_system );
842  
843 @coords = grep { !$_->isa('Bio::EnsEMBL::Mapper::Gap') } @coords;
844  
845 next COORD_SYSTEM if ( !@coords );
846  
847 my @ids = map { $_->id() } @coords;
848 #coords are now id rather than name
849
850 if ( @coords > $MAX_SPLIT_QUERY_SEQ_REGIONS && ! $slice->isa('Bio::EnsEMBL::LRGSlice')
851 && $slice->coord_system->name() ne 'lrg') {
852 $constraint = $orig_constraint;
853 my $id_str = join( ',', @ids );
854 $constraint .= " AND " if ($constraint);
855 $constraint .= $table_synonym.".seq_region_id IN ($id_str)";
856
857 push @query_accumulator, [$constraint,$mapper,$slice];
858 } else {
859 my $max_len = (
860 $self->_max_feature_length()
861 || $self->db->get_MetaCoordContainer
862 ->fetch_max_length_by_CoordSystem_feature_type($coord_system, $table_name)
863 );
864  
865 my $length = @coords;
866 for ( my $i = 0; $i < $length; $i++ ) {
867 $constraint = $orig_constraint;
868 $constraint .= " AND " if ($constraint);
869 $constraint .= $table_synonym.".seq_region_id = "
870 . $ids[$i] . " AND "
871 . $table_synonym.".seq_region_start <= "
872 . $coords[$i]->end() . " AND "
873 . $table_synonym.".seq_region_end >= "
874 . $coords[$i]->start();
875  
876 if ($max_len) {
877 my $min_start = $coords[$i]->start() - $max_len;
878 $constraint .= " AND ".$table_synonym.".seq_region_start >= ".$min_start;
879 }
880
881 push @query_accumulator, [$constraint,$mapper,$slice];
882 } # end multi-query cycle
883 } # end else
884
885 } # end else (coord sytems not matching)
886
887 #Record the bind params if we have to do multiple queries
888 my $bind_params = $self->bind_param_generic_fetch();
889
890 foreach my $query (@query_accumulator) {
891 my ($local_constraint,$local_mapper,$local_slice) = @$query;
892 $self->_bind_param_generic_fetch($bind_params);
893 if ($query_type and $query_type eq 'count') {
894 push @pan_coord_features, $self->generic_count($local_constraint);
895 }
896 else {
897 my $features = $self->generic_fetch( $local_constraint, $local_mapper, $local_slice );
898 $features = $self->_remap( $features, $local_mapper, $local_slice );
899 push @pan_coord_features, @$features;
900 }
901 }
902 $mapper = undef;
903 } # End foreach
904 $self->{_bind_param_generic_fetch} = undef;
905 return \@pan_coord_features;
906 }
907 #
908 # helper function used by fetch_all_by_Slice_constraint method
909 #
910 sub _slice_fetch {
911 my ( $self, $slice, $orig_constraint ) = @_;
912  
913 my $features = $self->_get_by_Slice($slice,$orig_constraint);
914  
915 return $features;
916 } ## end sub _slice_fetch
917  
918  
919 #for a given seq_region_id, gets the one used in an external database, if present, otherwise, returns the internal one
920 sub get_seq_region_id_external {
921 my ( $self, $sr_id ) = @_;
922 my $cs_a = $self->db()->get_CoordSystemAdaptor();
923 return ( exists( $cs_a->{'_internal_seq_region_mapping'}->{$sr_id} )
924 ? $cs_a->{'_internal_seq_region_mapping'}->{$sr_id}
925 : $sr_id );
926 }
927  
928 #for a given seq_region_id and coord_system, gets the one used in the internal (core) database
929 sub get_seq_region_id_internal{
930 my ( $self, $sr_id ) = @_;
931 my $cs_a = $self->db()->get_CoordSystemAdaptor();
932 return ( exists $cs_a->{'_external_seq_region_mapping'}->{$sr_id}
933 ? $cs_a->{'_external_seq_region_mapping'}->{$sr_id}
934 : $sr_id);
935 }
936  
937 #
938 # Helper function containing some common feature storing functionality
939 #
940 # Given a Feature this will return a copy (or the same feature if no changes
941 # to the feature are needed) of the feature which is relative to the start
942 # of the seq_region it is on. The seq_region_id of the seq_region it is on
943 # is also returned.
944 #
945 # This method will also ensure that the database knows which coordinate
946 # systems that this feature is stored in.
947 #
948  
949 sub _pre_store {
950 my $self = shift;
951 my $feature = shift;
952  
953 if(!ref($feature) || !$feature->isa('Bio::EnsEMBL::Feature')) {
954 throw('Expected Feature argument.');
955 }
956 my $slice = $feature->slice();
957  
958 $self->_check_start_end_strand($feature->start(),$feature->end(),
959 $feature->strand(), $slice);
960  
961  
962 my $db = $self->db();
963  
964 my $slice_adaptor = $db->get_SliceAdaptor();
965  
966 if(!ref($slice) || !($slice->isa('Bio::EnsEMBL::Slice') or $slice->isa('Bio::EnsEMBL::LRGSlice')) ) {
967 throw('Feature must be attached to Slice to be stored.');
968 }
969  
970 # make sure feature coords are relative to start of entire seq_region
971  
972 if($slice->start != 1 || $slice->strand != 1) {
973 #move feature onto a slice of the entire seq_region
974 $slice = $slice_adaptor->fetch_by_region($slice->coord_system->name(),
975 $slice->seq_region_name(),
976 undef, #start
977 undef, #end
978 undef, #strand
979 $slice->coord_system->version());
980  
981 $feature = $feature->transfer($slice);
982  
983 if(!$feature) {
984 throw('Could not transfer Feature to slice of ' .
985 'entire seq_region prior to storing');
986 }
987 }
988  
989 # Ensure this type of feature is known to be stored in this coord system.
990 my $cs = $slice->coord_system;
991  
992 my ($tab) = $self->_tables();
993 my $tabname = $tab->[0];
994  
995 my $mcc = $db->get_MetaCoordContainer();
996  
997 $mcc->add_feature_type($cs, $tabname, $feature->length);
998  
999 my $seq_region_id = $slice_adaptor->get_seq_region_id($slice);
1000  
1001 if(!$seq_region_id) {
1002 throw('Feature is associated with seq_region which is not in this DB.');
1003 }
1004  
1005 return ($feature, $seq_region_id);
1006 }
1007  
1008  
1009 # The same function as _pre_store
1010 # This one is used to store user uploaded features in XXX_userdata db
1011  
1012 sub _pre_store_userdata {
1013 my $self = shift;
1014 my $feature = shift;
1015  
1016 if(!ref($feature) || !$feature->isa('Bio::EnsEMBL::Feature')) {
1017 throw('Expected Feature argument.');
1018 }
1019  
1020 my $slice = $feature->slice();
1021 my $slice_adaptor = $slice->adaptor;
1022
1023 $self->_check_start_end_strand($feature->start(),$feature->end(),
1024 $feature->strand(), $slice);
1025  
1026  
1027 if(!ref($slice) || !($slice->isa('Bio::EnsEMBL::Slice') or $slice->isa('Bio::EnsEMBL::LRGSlice')) ) {
1028 throw('Feature must be attached to Slice to be stored.');
1029 }
1030  
1031 # make sure feature coords are relative to start of entire seq_region
1032  
1033 if($slice->start != 1 || $slice->strand != 1) {
1034 #move feature onto a slice of the entire seq_region
1035 $slice = $slice_adaptor->fetch_by_region($slice->coord_system->name(),
1036 $slice->seq_region_name(),
1037 undef, #start
1038 undef, #end
1039 undef, #strand
1040 $slice->coord_system->version());
1041  
1042 $feature = $feature->transfer($slice);
1043  
1044 if(!$feature) {
1045 throw('Could not transfer Feature to slice of ' .
1046 'entire seq_region prior to storing');
1047 }
1048 }
1049  
1050 # Ensure this type of feature is known to be stored in this coord system.
1051 my $cs = $slice->coord_system;
1052  
1053 my ($tab) = $self->_tables();
1054 my $tabname = $tab->[0];
1055  
1056 my $db = $self->db;
1057 my $mcc = $db->get_MetaCoordContainer();
1058  
1059 $mcc->add_feature_type($cs, $tabname, $feature->length);
1060  
1061 my $seq_region_id = $slice_adaptor->get_seq_region_id($slice);
1062  
1063 if(!$seq_region_id) {
1064 throw('Feature is associated with seq_region which is not in this DB.');
1065 }
1066  
1067 return ($feature, $seq_region_id);
1068 }
1069  
1070  
1071 #
1072 # helper function used to validate start/end/strand and
1073 # hstart/hend/hstrand etc.
1074 #
1075 sub _check_start_end_strand {
1076 my ($self, $start, $end, $strand, $slice) = @_;
1077  
1078 #
1079 # Make sure that the start, end, strand are valid
1080 #
1081 if(int($start) != $start) {
1082 throw("Invalid Feature start [$start]. Must be integer.");
1083 }
1084 if(int($end) != $end) {
1085 throw("Invalid Feature end [$end]. Must be integer.");
1086 }
1087 if(int($strand) != $strand || $strand < -1 || $strand > 1) {
1088 throw("Invalid Feature strand [$strand]. Must be -1, 0 or 1.");
1089 }
1090 if($end < $start && ! (defined $slice && $slice->is_circular())) {
1091 throw("Invalid Feature start/end [$start/$end]. Start must be less " .
1092 "than or equal to end.");
1093 }
1094  
1095 return 1;
1096 }
1097  
1098  
1099 #
1100 # Given a list of features checks if they are in the correct coord system
1101 # by looking at the first features slice. If they are not then they are
1102 # converted and placed on the slice.
1103 #
1104 sub _remap {
1105 my ( $self, $features, $mapper, $slice ) = @_;
1106  
1107 #check if any remapping is actually needed
1108 if(@$features && (!$features->[0]->isa('Bio::EnsEMBL::Feature') ||
1109 $features->[0]->slice == $slice)) {
1110 return $features;
1111 }
1112  
1113 #remapping has not been done, we have to do our own conversion from
1114 #to slice coords
1115  
1116 my @out;
1117  
1118 my $slice_start = $slice->start();
1119 my $slice_end = $slice->end();
1120 my $slice_strand = $slice->strand();
1121 my $slice_cs = $slice->coord_system();
1122  
1123 my ($seq_region_id, $start, $end, $strand);
1124  
1125 my $slice_seq_region_id = $slice->get_seq_region_id();
1126  
1127 foreach my $f (@$features) {
1128 #since feats were obtained in contig coords, attached seq is a contig
1129 my $fslice = $f->slice();
1130 if(!$fslice) {
1131 throw("Feature does not have attached slice.\n");
1132 }
1133 my $fseq_region_id = $fslice->get_seq_region_id();
1134 my $fcs = $fslice->coord_system();
1135  
1136 if(!$slice_cs->equals($fcs)) {
1137 #slice of feature in different coord system, mapping required
1138 # $seq_region comes out as an integer not a string
1139 ($seq_region_id, $start, $end, $strand) =
1140 $mapper->fastmap($fslice->seq_region_name(),$f->start(),$f->end(),$f->strand(),$fcs);
1141  
1142 # undefined start means gap
1143 next if(!defined $start);
1144 } else {
1145 $start = $f->start();
1146 $end = $f->end();
1147 $strand = $f->strand();
1148 $seq_region_id = $fseq_region_id;
1149 }
1150  
1151 # maps to region outside desired area
1152 next if ($start > $slice_end) || ($end < $slice_start) ||
1153 ($slice_seq_region_id != $seq_region_id);
1154  
1155 #shift the feature start, end and strand in one call
1156 if($slice_strand == -1) {
1157 $f->move( $slice_end - $end + 1, $slice_end - $start + 1, $strand * -1 );
1158 } else {
1159 $f->move( $start - $slice_start + 1, $end - $slice_start + 1, $strand );
1160 }
1161  
1162 $f->slice($slice);
1163  
1164 push @out,$f;
1165 }
1166  
1167 return \@out;
1168 }
1169  
1170 #
1171 # get seq region boundary (start|end) for a feature
1172 # the method attempts to retrieve the boundary directly from the db
1173 # return undef if cannot determine the associated feature table
1174 #
1175 sub _seq_region_boundary_from_db {
1176 my ($self, $feature, $boundary) = @_;
1177  
1178 if(!ref($feature) || !$feature->isa('Bio::EnsEMBL::Feature')) {
1179 throw('Expected Feature argument.');
1180 }
1181  
1182 throw "Undefined boundary"
1183 unless defined $boundary;
1184  
1185 $boundary eq 'start' or $boundary eq 'end'
1186 or throw "Wrong boundary: select start|end";
1187  
1188 $boundary = 'seq_region_' . $boundary;
1189  
1190 my $sql_helper = $self->dbc->sql_helper;
1191 throw "Unable to get SqlHelper instance" unless defined $sql_helper;
1192  
1193 my $feature_table = ($self->_tables)[0]->[0];
1194 warning (sprintf "Unable to get %s for %s instance\nCould not find associated feature table, returning undef", $boundary, ref $feature)
1195 and return undef unless defined $feature_table;
1196  
1197 my $db_id = $feature->dbID;
1198 my $attrib_id = $feature_table . '_id';
1199 my $query = "SELECT ${boundary} from ${feature_table} WHERE ${attrib_id} = ${db_id}";
1200  
1201 return $sql_helper->execute_single_result(-SQL => $query);
1202 }
1203  
1204 =head2 store
1205  
1206 Arg [1] : list of Bio::EnsEMBL::SeqFeature
1207 Example : $adaptor->store(@feats);
1208 Description: ABSTRACT Subclasses are responsible for implementing this
1209 method. It should take a list of features and store them in
1210 the database.
1211 Returntype : none
1212 Exceptions : thrown method is not implemented by subclass
1213 Caller : general
1214 Status : At Risk
1215 : throws if called.
1216  
1217 =cut
1218  
1219 sub store{
1220 my $self = @_;
1221  
1222 throw("Abstract method store not defined by implementing subclass\n");
1223 }
1224  
1225  
1226 =head2 remove
1227  
1228 Arg [1] : A feature $feature
1229 Example : $feature_adaptor->remove($feature);
1230 Description: This removes a feature from the database. The table the
1231 feature is removed from is defined by the abstract method
1232 _tablename, and the primary key of the table is assumed
1233 to be _tablename() . '_id'. The feature argument must
1234 be an object implementing the dbID method, and for the
1235 feature to be removed from the database a dbID value must
1236 be returned.
1237 Returntype : none
1238 Exceptions : thrown if $feature arg does not implement dbID(), or if
1239 $feature->dbID is not a true value
1240 Caller : general
1241 Status : Stable
1242  
1243 =cut
1244  
1245  
1246 sub remove {
1247 my ($self, $feature) = @_;
1248  
1249 if(!$feature || !ref($feature) || !$feature->isa('Bio::EnsEMBL::Feature')) {
1250 throw('Feature argument is required');
1251 }
1252  
1253 if(!$feature->is_stored($self->db)) {
1254 throw("This feature is not stored in this database");
1255 }
1256  
1257 my @tabs = $self->_tables;
1258 my ($table) = @{$tabs[0]};
1259  
1260 my $sth = $self->prepare("DELETE FROM $table WHERE ${table}_id = ?");
1261 $sth->bind_param(1,$feature->dbID,SQL_INTEGER);
1262 $sth->execute();
1263  
1264 #unset the feature dbID ad adaptor
1265 $feature->dbID(undef);
1266 $feature->adaptor(undef);
1267  
1268 return;
1269 }
1270  
1271  
1272 =head2 remove_by_Slice
1273  
1274 Arg [1] : Bio::Ensembl::Slice $slice
1275 Example : $feature_adaptor->remove_by_Slice($slice);
1276 Description: This removes features from the database which lie on a region
1277 represented by the passed in slice. Only features which are
1278 fully contained by the slice are deleted; features which overlap
1279 the edge of the slice are not removed.
1280 The table the features are removed from is defined by
1281 the abstract method_tablename.
1282 Returntype : none
1283 Exceptions : thrown if no slice is supplied
1284 Caller : general
1285 Status : Stable
1286  
1287 =cut
1288  
1289 sub remove_by_Slice {
1290 my ($self, $slice) = @_;
1291  
1292 if(!$slice || !ref($slice) || !($slice->isa('Bio::EnsEMBL::Slice') or $slice->isa('Bio::EnsEMBL::LRGSlice')) ) {
1293 throw("Slice argument is required");
1294 }
1295  
1296 my @tabs = $self->_tables;
1297 my ($table_name) = @{$tabs[0]};
1298  
1299 my $seq_region_id = $self->db->get_SliceAdaptor->get_seq_region_id($slice);
1300 my $start = $slice->start();
1301 my $end = $slice->end();
1302  
1303 #
1304 # Delete only features fully on the slice, not overlapping ones
1305 #
1306 my $sth = $self->prepare("DELETE FROM $table_name " .
1307 "WHERE seq_region_id = ? " .
1308 "AND seq_region_start >= ? " .
1309 "AND seq_region_end <= ?");
1310  
1311 $sth->bind_param(1,$seq_region_id,SQL_INTEGER);
1312 $sth->bind_param(2,$start,SQL_INTEGER);
1313 $sth->bind_param(3,$end,SQL_INTEGER);
1314 $sth->execute();
1315 $sth->finish();
1316 }
1317  
1318  
1319 #
1320 # Internal function. Allows the max feature length which is normally
1321 # retrieved from the meta_coord table to be overridden. This allows
1322 # for some significant optimizations to be put in when it is known
1323 # that requested features will not be over a certain size.
1324 #
1325 sub _max_feature_length {
1326 my $self = shift;
1327 return $self->{'_max_feature_length'} = shift if(@_);
1328 return $self->{'_max_feature_length'};
1329 }
1330  
1331  
1332 #
1333 # Lists all seq_region_ids that a particular feature type is found on.
1334 # Useful e.g. for finding out which seq_regions have genes.
1335 # Returns a listref of seq_region_ids.
1336 #
1337 sub _list_seq_region_ids {
1338 my ($self, $table) = @_;
1339
1340 my @out;
1341
1342 my $sql = qq(
1343 SELECT DISTINCT
1344 sr.seq_region_id
1345 FROM seq_region sr,
1346 $table a,
1347 coord_system cs
1348 WHERE sr.seq_region_id = a.seq_region_id
1349 AND sr.coord_system_id = cs.coord_system_id
1350 AND cs.species_id = ?);
1351  
1352 my $sth = $self->prepare($sql);
1353  
1354 $sth->bind_param( 1, $self->species_id(), SQL_INTEGER );
1355  
1356 $sth->execute();
1357  
1358 while (my ($id) = $sth->fetchrow) {
1359 push(@out, $id);
1360 }
1361  
1362 $sth->finish;
1363  
1364 return \@out;
1365 }
1366  
1367  
1368 sub remove_by_analysis_id {
1369 my ($self, $analysis_id) = @_;
1370  
1371 $analysis_id or throw("Must call with analysis id");
1372  
1373 my @tabs = $self->_tables;
1374 my ($tablename) = @{$tabs[0]};
1375  
1376 my $sql = "DELETE FROM $tablename WHERE analysis_id = $analysis_id";
1377 # warn "SQL : $sql";
1378
1379 my $sth = $self->prepare($sql);
1380 $sth->execute();
1381 $sth->finish();
1382 }
1383  
1384 sub remove_by_feature_id {
1385 my ($self, $features_list) = @_;
1386  
1387 my @feats = @$features_list or throw("Must call store with features");
1388  
1389 my @tabs = $self->_tables;
1390 my ($tablename) = @{$tabs[0]};
1391  
1392 my $sql = sprintf "DELETE FROM $tablename WHERE ${tablename}_id IN (%s)", join ', ', @feats;
1393 # warn "SQL : $sql";
1394
1395 my $sth = $self->prepare($sql);
1396 $sth->execute();
1397 $sth->finish();
1398 }
1399  
1400 =head2 fetch_nearest_by_Feature
1401  
1402 Arg [1] : Reference Feature to start the search from
1403 Description: Searches iteratively outward from the starting feature until a nearby Feature is found
1404 If you require more than one result or more control of which features are returned, see
1405 fetch_all_nearest_by_Feature and fetch_all_by_outward_search. fetch_nearest_by_Feature
1406 is a convenience method.
1407 ReturnType : Bio::EnsEMBL::Feature
1408 =cut
1409  
1410 sub fetch_nearest_by_Feature {
1411 my $self = shift;
1412 my $feature = shift;
1413 my @hits = @{ $self->fetch_all_by_outward_search(-FEATURE => $feature, -MAX_RANGE => 1000000, -RANGE => 1000, -LIMIT => 1) };
1414 return $hits[0] if (scalar @hits > 0);
1415 return;
1416 }
1417  
1418  
1419 =head2 fetch_all_by_outward_search
1420  
1421 Arguments the same as fetch_all_nearest_by_Feature
1422 Arg [0] : -MAX_RANGE : Set an upper limit on the search range, defaults to 10000 bp
1423 Arg [1] : -FEATURE ,Bio::EnsEMBL::Feature : 'Source' Feature to anchor the search for nearest Features
1424 Arg [2] : -SAME_STRAND, Boolean (optional) : Respect the strand of the source Feature with ref, only
1425 returning Features on the same strand.
1426 Arg [3] : -OPPOSITE_STRAND, Boolean (optional) : Find features on the opposite strand of the same
1427 Arg [4] : -DOWNSTREAM/-UPSTREAM, (optional) : Search ONLY downstream or upstream from the source Feature.
1428 Can be omitted for searches in both directions.
1429 Arg [5] : -RANGE, Int : The size of the space to search for Features. Defaults to 1000 as a sensible starting point
1430 Arg [6] : -NOT_OVERLAPPING, Boolean (optional) : Do not return Features that overlap the source Feature
1431 Arg [7] : -FIVE_PRIME, Boolean (optional) : Determine range to a Feature by the 5' end, respecting strand
1432 Arg [8] : -THREE_PRIME, Boolean (optional): Determine range to a Feature by the 3' end, respecting strand
1433 Arg [9] : -LIMIT, Int : The maximum number of Features to return, defaulting to one. Equally near features are all returned
1434  
1435 Description: Searches for features within the suggested -RANGE, and if it finds none, expands the search area
1436 until it satisfies -LIMIT or hits -MAX_RANGE. Useful if you don't know how far away the features
1437 might be, or if dealing with areas of high feature density. In the case of Variation Features, it is
1438 conceivable that a 2000 bp window might contain very many features, resulting in a slow and bloated
1439 response, thus the ability to explore outward in smaller sections can be useful.
1440 Returntype : Listref of [$feature,$distance]
1441 =cut
1442  
1443 sub fetch_all_by_outward_search {
1444 my $self = shift;
1445 my ($ref_feature, $respect_strand, $opposite_strand, $downstream, $upstream, $start_search_range,
1446 $limit,$not_overlapping,$five_prime,$three_prime, $max_range) =
1447 rearrange([qw(FEATURE SAME_STRAND OPPOSITE_STRAND DOWNSTREAM UPSTREAM RANGE LIMIT NOT_OVERLAPPING FIVE_PRIME THREE_PRIME MAX_RANGE)], @_);
1448 my $factor = 1;
1449 $limit ||= 1;
1450 $start_search_range ||= 1000;
1451 my $current_search_range = $start_search_range;
1452 $max_range ||= 10000;
1453 my @results;
1454 while (scalar @results < $limit && $current_search_range < $max_range) {
1455 $current_search_range = $start_search_range * $factor;
1456 @results = @{
1457 $self->fetch_all_nearest_by_Feature(-RANGE => $current_search_range,
1458 -FEATURE => $ref_feature,
1459 -SAME_STRAND => $respect_strand,
1460 -OPPOSITE_STRAND => $opposite_strand,
1461 -DOWNSTREAM => $downstream,
1462 -UPSTREAM => $upstream,
1463 -LIMIT => $limit,
1464 -NOT_OVERLAPPING => $not_overlapping,
1465 -FIVE_PRIME => $five_prime,
1466 -THREE_PRIME => $three_prime,
1467 )
1468 };
1469 $factor++;
1470 }
1471 return \@results;
1472 }
1473  
1474 =head2 fetch_all_nearest_by_Feature
1475  
1476 Arg [1] : -FEATURE ,Bio::EnsEMBL::Feature : 'Source' Feature to anchor the search for nearest Features
1477 Arg [2] : -SAME_STRAND, Boolean (optional): Respect the strand of the source Feature with ref, only
1478 returning Features on the same strand
1479 Arg [3] : -OPPOSITE_STRAND, Boolean (optional) : Find features on the opposite strand of the same
1480 Arg [4] : -DOWNSTREAM/-UPSTREAM, (optional) : Search ONLY downstream or upstream from the source Feature.
1481 Can be omitted for searches in both directions.
1482 Arg [5] : -RANGE, Int : The size of the space to search for Features. Defaults to 1000 as a sensible starting point
1483 Arg [6] : -NOT_OVERLAPPING, Boolean (optional) : Do not return Features that overlap the source Feature
1484 Arg [7] : -FIVE_PRIME, Boolean (optional) : Determine range to a Feature by its 5' end, respecting strand
1485 Arg [8] : -THREE_PRIME, Boolean (optional): Determine range to a Feature by its 3' end, respecting strand
1486 Arg [9] : -LIMIT, Int : The maximum number of Features to return, defaulting to one. Equally near features are all returned
1487 Example : #To fetch the gene(s) with the nearest 5' end:
1488 $genes = $gene_adaptor->fetch_all_nearest_by_Feature(-FEATURE => $feat, -FIVE_PRIME => 1);
1489  
1490 Description: Gets the nearest Features to a given 'source' Feature. The Feature returned and the format of the result
1491 are non-obvious, please read on.
1492  
1493 When looking beyond the boundaries of the source Feature, the distance is measured to the nearest end
1494 of that Feature to the nearby Feature's nearest end.
1495 If Features overlap the source Feature, then they are given a distance of zero but ordered by
1496 their proximity to the centre of the Feature.
1497
1498 Features are found and prioritised within 1000 base pairs unless a -RANGE is given to the method. Any overlap with
1499 the search region is included, and the results can be restricted to upstream, downstream, forward strand or reverse
1500  
1501 The -FIVE_PRIME and -THREE_PRIME options allow searching for specific ends of nearby features, but still needs
1502 a -DOWN/UPSTREAM value and/or -NOT_OVERLAPPING to fulfil its most common application.
1503  
1504  
1505 Returntype : Listref containing an Arrayref of Bio::EnsEMBL::Feature objects and the distance
1506 [ [$feature, $distance] ... ]
1507 Caller : general
1508  
1509 =cut
1510 sub fetch_all_nearest_by_Feature{
1511 my $self = shift;
1512 my ($ref_feature, $respect_strand, $opposite_strand, $downstream, $upstream, $search_range,$limit,$not_overlapping,$five_prime,$three_prime) =
1513 rearrange([qw(FEATURE SAME_STRAND OPPOSITE_STRAND DOWNSTREAM UPSTREAM RANGE LIMIT NOT_OVERLAPPING FIVE_PRIME THREE_PRIME)], @_);
1514 if ( !defined($search_range)) {
1515 $search_range ||= 1000;
1516 }
1517 $limit ||= 1;
1518  
1519 unless (defined($ref_feature) && $ref_feature->isa('Bio::EnsEMBL::Feature')) {
1520 throw ('fetch_all_nearest_by_Feature method requires a valid Ensembl Feature object to operate');
1521 }
1522 throw ('Do not specify both -upstream and -downstream. This is the same as no arguments') if ($upstream && $downstream);
1523 throw ('Do not use both -SAME_STRAND and -OPPOSITE_STRAND in one query') if ($opposite_strand && $respect_strand);
1524 my ($region_start,$region_end);
1525
1526 # Define search box. Features overlapping the boundaries are found and considered
1527 my $slice = $ref_feature->feature_Slice;
1528  
1529 my $five_prime_expansion = 0;
1530 my $three_prime_expansion = 0;
1531 if ($upstream) {
1532 $five_prime_expansion = $search_range;
1533 $three_prime_expansion = $slice->length * -1;
1534 # shrinks the slice to exclude the features that do not exist beyond the end of the
1535 # considered feature
1536 }
1537 elsif ($downstream) {
1538 $three_prime_expansion = $search_range;
1539 $five_prime_expansion = $slice->length * -1;
1540 }
1541 else {
1542 $five_prime_expansion = $search_range;
1543 $three_prime_expansion = $search_range;
1544 }
1545  
1546 $slice = $slice->expand( $five_prime_expansion, $three_prime_expansion);
1547 my $sa = $self->db->get_SliceAdaptor;
1548 my @candidates; # Features in the search region
1549 @candidates = @{$self->fetch_all_by_Slice($slice)};
1550 if ($respect_strand) { @candidates = grep {$_->strand == $ref_feature->strand} @candidates }
1551 if ($opposite_strand) { @candidates = grep {$_->strand != $ref_feature->strand} @candidates }
1552 # When user chooses UPSTREAM/DOWNSTREAM && FIVE_PRIME/THREE_PRIME, discount any features with
1553 # their other end in the overlap region. fetch_all_by_Slice cannot filter these out.
1554 # fetch_all_by_Slice_constraint could in principle with the correct constraint.
1555 if (($upstream && $ref_feature->strand == 1) || ($downstream && $ref_feature->strand == -1)) {
1556 if ($five_prime) {
1557 @candidates = grep { ($_->strand == 1) ? $_->seq_region_start < $ref_feature->start : $_->seq_region_end < $ref_feature->start} @candidates;
1558 } elsif ($three_prime) {
1559 @candidates = grep { ($_->strand == 1) ? $_->seq_region_end < $ref_feature->start : $_->seq_region_start < $ref_feature->start} @candidates;
1560 }
1561 }
1562 if (($downstream && $ref_feature->strand == 1)|| ($upstream && $ref_feature->strand == -1)) {
1563 if ($five_prime) {
1564 @candidates = grep { ($_->strand == 1) ? $_->seq_region_start > $ref_feature->end : $_->seq_region_end > $ref_feature->end } @candidates;
1565 } elsif ($three_prime) {
1566 @candidates = grep { ($_->strand == 1) ? $_->seq_region_end > $ref_feature->end : $_->seq_region_start > $ref_feature->end } @candidates;
1567 }
1568 }
1569 # Then sort and prioritise the candidates
1570 my $finalists; # = [[feature, distance, centre-weighted distance, length, dbID],..]
1571 $finalists = $self->select_nearest($ref_feature,\@candidates,$limit,$not_overlapping,$five_prime,$three_prime);
1572 $finalists = [ map { [ splice @$_,0,2 ]} @$finalists ]; # Remove the ugly bits from the sight of users.
1573 return $finalists;
1574 }
1575  
1576  
1577 =head2 select_nearest
1578  
1579 Arg [1] : Bio::Ensembl::Feature, a Feature to find the nearest neighbouring feature to.
1580 Arg [2] : Listref of Features to be considered for nearness.
1581 Arg [3] : Integer, limited number of Features to return. Equally near features are all returned in spite of this limit
1582 Arg [4] : Boolean, Overlapping prohibition. Overlapped Features are forgotten
1583 Arg [5] : Boolean, use the 5' ends of the nearby features for distance calculation
1584 Arg [6] : Boolean, use the 3' ends of the nearby features for distance calculation
1585 Example : $feature_list = $feature_adaptor->select_nearest($ref_feature,\@candidates,$limit,$not_overlapping)
1586 Description: Take a list of possible features, and determine which is nearest. Nearness is a
1587 tricky concept. Beware of using the distance between Features, as it may not be the number you think
1588 it should be.
1589 Returntype : listref of Features ordered by proximity
1590 Caller : BaseFeatureAdaptor->fetch_all_nearest_by_Feature
1591  
1592 =cut
1593  
1594 sub select_nearest {
1595 my $self = shift;
1596 my $ref_feature = shift;
1597 my $candidates = shift;
1598 my $limit = shift;
1599 my $not_overlapping = shift;
1600 my $five_prime = shift;
1601 my $three_prime = shift;
1602
1603 # Convert circular coordinates to linear ones for distance calculation
1604 my $ref_start = ($ref_feature->start < $ref_feature->end) ? $ref_feature->start : $ref_feature->start - $ref_feature->length; # Not ->end, in case circular
1605 my $ref_end = $ref_feature->end;
1606 my $ref_midpoint = $self->_compute_midpoint($ref_feature);
1607  
1608 my $position_matrix = [];
1609 my $shortest_distance;
1610 my $adjusted_distance; # for when features overlap and we need another metric to order by
1611  
1612 foreach my $neighbour (@$candidates) {
1613 # rearrange coordinates into forward-stranded orientation, plus flatten circular features.
1614 my $neigh_start = ($neighbour->seq_region_start < $neighbour->seq_region_end)
1615 ? $neighbour->seq_region_start : $neighbour->seq_region_start - $neighbour->length; # Not ->end, in case it is circular
1616 my $neigh_midpoint = $self->_compute_midpoint($neighbour);
1617 my $neigh_end = $neighbour->seq_region_end;
1618  
1619 # discard overlaps early if not required.
1620 next if ( $not_overlapping
1621 && (
1622 ( $neigh_start >= $ref_start && $neigh_end <= $ref_end )
1623 || ( $neigh_end <= $ref_end && $neigh_end >= $ref_start )
1624 )
1625 );
1626 my @args = ($ref_start,$ref_midpoint,$ref_end,$neigh_start,$neigh_midpoint,$neigh_end,$neighbour->strand);
1627 if ($five_prime || $three_prime) {
1628 my $five = $five_prime ? 1 : 0; # Choose 5' or 3' end
1629 ($shortest_distance,$adjusted_distance) = $self->_compute_prime_distance($five,@args);
1630 next unless ($shortest_distance || $adjusted_distance);
1631 }
1632 else {
1633 ($shortest_distance,$adjusted_distance) = $self->_compute_nearest_end(@args);
1634 }
1635 push @$position_matrix,[ $neighbour, $shortest_distance, $adjusted_distance, $neighbour->length, $neighbour->display_id] unless ($not_overlapping && $shortest_distance == 0);
1636 }
1637
1638 # Order by distance, then centre-to-centre distance, then smallest feature first, then an arbitrary ID.
1639 # $position_matrix looks like this:
1640 # [ [ $feature, closest measure of distance, size, dbID ] ]
1641 # Not proud of this line. It re-emits the original array in sorted order to favour better measures of order.
1642 my @ordered_matrix = map { [$_->[0],$_->[1],$_->[2],$_->[3],$_->[4]] }
1643 sort { abs($a->[1]) <=> abs($b->[1]) || abs($a->[2]) <=> abs($b->[2]) || $a->[3] <=> $b->[3] || $a->[4] <=> $b->[4]} @$position_matrix;
1644 # Knock off unwanted hits. Equal distances are included, so more can be returned than asked for.
1645 @ordered_matrix = $self->_discard_excess_features_from_matrix(\@ordered_matrix,$limit);
1646 return \@ordered_matrix;
1647 }
1648  
1649 =head2 _compute_nearest_end
1650  
1651 Arg [1] : Reference feature start
1652 Arg [2] : Reference feature mid-point
1653 Arg [3] : Reference feature end
1654 Arg [4] : Considered feature start
1655 Arg [5] : Considered feature mid-point
1656 Arg [6] : Considered feature end
1657 Example : $distance = $feature_adaptor->_compute_nearest_end($ref_start,$ref_midpoint,$ref_end,$f_start,$f_midpoint,$f_end)
1658 Description: For a given feature, calculate the smallest legitimate distance to a reference feature
1659 Calculate by mid-points to accommodate overlaps
1660 Returntype : Integer distance in base pairs
1661 Caller : BaseFeatureAdaptor->select_nearest()
1662  
1663 =cut
1664 sub _compute_nearest_end {
1665 my ($self,$ref_start,$ref_midpoint,$ref_end,$f_start,$f_midpoint,$f_end) = @_;
1666 my ($effective_distance,$weighted_distance);
1667 if ($ref_start > $f_end ) {
1668 # upstream, no overlap
1669 $effective_distance = $f_end - $ref_start; # negative result for upstream
1670 } elsif ( $ref_end < $f_start ) {
1671 # downstream
1672 $effective_distance = $f_start - $ref_end; # positive result for downstream
1673 } else {
1674 # overlap,
1675 $effective_distance = 0;
1676 $weighted_distance = $f_midpoint - $ref_midpoint;
1677 }
1678 return $effective_distance, $weighted_distance;
1679 }
1680  
1681 =head2 _compute_prime_distance
1682  
1683 Arg [1] : Reference feature start
1684 Arg [2] : Reference feature mid-point
1685 Arg [3] : Reference feature end
1686 Arg [4] : Considered feature start
1687 Arg [5] : Considered feature mid-point
1688 Arg [6] : Considered feature end
1689 Arg [7] : Considered feature strand
1690 Example : $distance,$weighted_centre_distance = $feature_adaptor->_compute_prime_distance($ref_start,$ref_midpoint,$ref_end,$f_start,$f_midpoint,$f_end,$f_strand)
1691 Description: Calculate the smallest distance to the 5' end of the considered feature
1692 Returntype : Integer distance in base pairs or a string warning that the result doesn't mean anything.
1693 Nearest 5' and 3' features shouldn't reside inside the reference Feature
1694 Caller : BaseFeatureAdaptor->select_nearest()
1695  
1696 =cut
1697 sub _compute_prime_distance {
1698 my ($self,$five_prime,$ref_start,$ref_midpoint,$ref_end,$f_start,$f_midpoint,$f_end,$f_strand) = @_;
1699
1700 my $f_coord;
1701 my $effective_distance;
1702 my $weighted_distance;
1703  
1704 if ($five_prime) {
1705 $f_coord = ($f_strand == 1) ? $f_start : $f_end;
1706 } else { # three prime end required
1707 $f_coord = ($f_strand ==1 ) ? $f_end : $f_start;
1708 }
1709  
1710 if ($ref_start > $f_coord) {
1711 # n' end of feature upstream of reference
1712 $effective_distance = $f_coord - $ref_start;
1713 if ($f_end < $ref_start) {
1714 $weighted_distance = $f_coord - $ref_midpoint;
1715 }
1716 } elsif ($ref_end < $f_coord && $f_start > $ref_end) {
1717 # n' end of feature downstream of reference
1718 $effective_distance = $ref_end - $f_coord;
1719 if ($f_start > $ref_end) {
1720 $weighted_distance = $f_coord - $ref_midpoint;
1721 }
1722 } elsif ($ref_start < $f_coord && $ref_end > $f_coord) {
1723 # total overlap condition
1724 $effective_distance = 0;
1725 $weighted_distance = $f_coord - $ref_midpoint;
1726 }
1727 # If feature's end falls outside of the reference feature, compute distance to reference midpoint.
1728 return $effective_distance, $weighted_distance;
1729 }
1730  
1731 =head2 _compute_midpoint
1732  
1733 Arg [1] : Bio::EnsEMBL::Feature
1734 Example : $middle = $feature_adaptor->_compute_midpoint($feature);
1735 Description: Calculate the mid-point of a Feature. Used for comparing Features that overlap each other
1736 and determining a canonical distance between two Features for the majority of use cases.
1737 Returntype : Integer coordinate rounded down.
1738 Caller : BaseFeatureAdaptor->select_nearest()
1739  
1740 =cut
1741 sub _compute_midpoint {
1742 my $self = shift;
1743 my $feature = shift;
1744 my $start = $feature->seq_region_start;
1745 my $end = $feature->seq_region_end;
1746 my $midpoint;
1747 # consider circular slice
1748 if ($start > $end) {
1749 $midpoint = int($end + ($start - $end) / 2);
1750 } else {
1751 $midpoint = int($start + ($end - $start) / 2);
1752 }
1753 return $midpoint;
1754 }
1755  
1756 sub _discard_excess_features_from_matrix {
1757 my $self = shift;
1758 my $list = shift;
1759 my @ordered_matrix = @$list;
1760 my $limit = shift;
1761 return @ordered_matrix if $#ordered_matrix == 0 || !defined($limit) || $limit > scalar @ordered_matrix;
1762 # cut off excess elements
1763 my @spares = splice @ordered_matrix, $limit, scalar @ordered_matrix - $limit;
1764 # Check nearest distance of the last member of ordered_matrix against spares and include those that match
1765 # This prevents first past the post.
1766 if (scalar @ordered_matrix > 0) {
1767 my $threshold_distance = $ordered_matrix[-1]->[1];
1768 my $i = 0;
1769 while ($i <= $#spares && $spares[$i]->[1] == $threshold_distance) {
1770 # printf "Considering option %s, %s\n",$spares[$i]->[0]->stable_id,$spares[$i]->[1];
1771 push @ordered_matrix, $spares[$i];
1772 $i++;
1773 }
1774
1775 }
1776 return @ordered_matrix;
1777 }
1778  
1779 1;