BaseFeatureAdaptor.pm 24.3 KB
Newer Older
1
#
Simon Potter's avatar
Simon Potter committed
2
# EnsEMBL module for Bio::EnsEMBL::DBSQL::BaseFeatureAdaptor
3
#
Graham McVicker's avatar
Graham McVicker committed
4
# Copyright (c) 2003 Ensembl
5 6 7 8 9
#
# You may distribute this module under the same terms as perl itself

=head1 NAME

10
Bio::EnsEMBL::DBSQL::BaseFeatureAdaptor - An Abstract Base class for all
Graham McVicker's avatar
Graham McVicker committed
11
FeatureAdaptors
12 13 14

=head1 SYNOPSIS

15
Abstract class - should not be instantiated.  Implementation of
16 17 18 19 20
abstract methods must be performed by subclasses.

=head1 DESCRIPTION

This is a base adaptor for feature adaptors. This base class is simply a way
21
of eliminating code duplication through the implementation of methods
22 23
common to all feature adaptors.

24 25
=head1 CONTACT

Graham McVicker's avatar
Graham McVicker committed
26
Contact Ensembl development list for info: <ensembl-dev@ebi.ac.uk>
27 28 29

=head1 METHODS

30 31 32
=cut

package Bio::EnsEMBL::DBSQL::BaseFeatureAdaptor;
33
use vars qw(@ISA @EXPORT);
34 35 36
use strict;

use Bio::EnsEMBL::DBSQL::BaseAdaptor;
37
use Bio::EnsEMBL::Utils::Cache;
38
use Bio::EnsEMBL::Utils::Exception qw(warning throw deprecate stack_trace_dump);
39
use Bio::EnsEMBL::Utils::Argument qw(rearrange);
40 41 42

@ISA = qw(Bio::EnsEMBL::DBSQL::BaseAdaptor);

43 44
@EXPORT = (@{$DBI::EXPORT_TAGS{'sql_types'}});

45 46
our $SLICE_FEATURE_CACHE_SIZE = 4;
our $MAX_SPLIT_QUERY_SEQ_REGIONS = 3;
47 48 49 50 51 52 53 54 55 56

=head2 new

  Arg [1]    : list of args @args
               Superclass constructor arguments
  Example    : none
  Description: Constructor which just initializes internal cache structures
  Returntype : Bio::EnsEMBL::BaseFeatureAdaptor
  Exceptions : none
  Caller     : implementing subclass constructors
57
  Status     : Stable
58 59 60 61

=cut

sub new {
62
  my $caller = shift;
63

64
  my $class = ref($caller) || $caller;
65

66
  my $self = $class->SUPER::new(@_);
67

68 69 70 71
  #initialize an LRU cache
  my %cache;
  tie(%cache, 'Bio::EnsEMBL::Utils::Cache', $SLICE_FEATURE_CACHE_SIZE);
  $self->{'_slice_feature_cache'} = \%cache;
72 73 74

  return $self;
}
75

76

77
=head2 fetch_all_by_Slice
78 79 80 81 82

  Arg [1]    : Bio::EnsEMBL::Slice $slice
               the slice from which to obtain features
  Arg [2]    : (optional) string $logic_name
               the logic name of the type of features to obtain
83 84 85 86 87 88
  Example    : $fts = $a->fetch_all_by_Slice($slice, 'Swall');
  Description: Returns a listref of features created from the database 
               which are on the Slice defined by $slice. If $logic_name is 
               defined only features with an analysis of type $logic_name 
               will be returned. 
  Returntype : listref of Bio::EnsEMBL::SeqFeatures in Slice coordinates
89 90
  Exceptions : none
  Caller     : Bio::EnsEMBL::Slice
91
  Status     : Stable
92 93 94

=cut

95
sub fetch_all_by_Slice {
96 97
  my ($self, $slice, $logic_name) = @_;
  #fetch by constraint with empty constraint
98
  return $self->fetch_all_by_Slice_constraint($slice, '', $logic_name);
99 100 101
}


102
=head2 fetch_all_by_Slice_and_score
103 104 105

  Arg [1]    : Bio::EnsEMBL::Slice $slice
               the slice from which to obtain features
106
  Arg [2]    : (optional) float $score
107 108 109
               lower bound of the the score of the features retrieved
  Arg [3]    : (optional) string $logic_name
               the logic name of the type of features to obtain
110
  Example    : $fts = $a->fetch_all_by_Slice_and_score($slice,90,'Swall');
111 112
  Description: Returns a list of features created from the database which are 
               are on the Slice defined by $slice and which have a score 
113
               greater than $score. If $logic_name is defined, 
114 115
               only features with an analysis of type $logic_name will be 
               returned. 
116
  Returntype : listref of Bio::EnsEMBL::SeqFeatures in Slice coordinates
117 118
  Exceptions : none
  Caller     : Bio::EnsEMBL::Slice
119
  Status     : Stable
120 121 122

=cut

123
sub fetch_all_by_Slice_and_score {
124 125 126
  my ($self, $slice, $score, $logic_name) = @_;
  my $constraint;

127
  if(defined $score) {
128 129 130 131
    #get the synonym of the primary_table
    my @tabs = $self->_tables;
    my $syn = $tabs[0]->[1];
    $constraint = "${syn}.score > $score";
132
  }
133 134
  return $self->fetch_all_by_Slice_constraint($slice, $constraint, 
					      $logic_name);
135
}
136 137


138
=head2 fetch_all_by_Slice_constraint
139

140 141 142 143 144
  Arg [1]    : Bio::EnsEMBL::Slice $slice
               the slice from which to obtain features
  Arg [2]    : (optional) string $constraint
               An SQL query constraint (i.e. part of the WHERE clause)
  Arg [3]    : (optional) string $logic_name
145
               the logic name of the type of features to obtain
146 147
  Example    : $fs = $a->fetch_all_by_Slice_constraint($slc, 'perc_ident > 5');
  Description: Returns a listref of features created from the database which 
148 149 150 151
               are on the Slice defined by $slice and fulfill the SQL 
               constraint defined by $constraint. If logic name is defined, 
               only features with an analysis of type $logic_name will be 
               returned. 
152
  Returntype : listref of Bio::EnsEMBL::SeqFeatures in Slice coordinates
153 154
  Exceptions : thrown if $slice is not defined
  Caller     : Bio::EnsEMBL::Slice
155
  Status     : Stable
156 157 158

=cut

159
sub fetch_all_by_Slice_constraint {
160 161 162
  my($self, $slice, $constraint, $logic_name) = @_;

  my @result;
163

164
  if(!ref($slice) || !$slice->isa("Bio::EnsEMBL::Slice")) {
Graham McVicker's avatar
Graham McVicker committed
165
    throw("Bio::EnsEMBL::Slice argument expected.");
166 167
  }

168 169
  $constraint ||= '';
  $constraint = $self->_logic_name_to_constraint($constraint, $logic_name);
170 171

  #if the logic name was invalid, undef was returned
172
  return [] if(!defined($constraint));
173

174
  #check the cache and return if we have already done this query
175
  my $key = uc(join(':', $slice->name, $constraint));
176 177 178 179 180

  if(exists($self->{'_slice_feature_cache'}->{$key})) {
    return $self->{'_slice_feature_cache'}->{$key};
  }

181
  my $sa = $slice->adaptor();
182

183 184
  # Hap/PAR support: retrieve normalized 'non-symlinked' slices
  my @proj = @{$sa->fetch_normalized_slice_projection($slice)};
185

186
  if(@proj == 0) {
187 188 189
    throw('Could not retrieve normalized Slices. Database contains ' .
          'incorrect assembly_exception information.');
  }
Ian Longden's avatar
Ian Longden committed
190
  
191 192
  # Want to get features on the FULL original slice
  # as well as any symlinked slices
193

194 195
  # Filter out partial slices from projection that are on
  # same seq_region as original slice
196

197
  my $sr_id = $slice->get_seq_region_id();
Ian Longden's avatar
Ian Longden committed
198 199 200 201
  print STDERR "sr_id = $sr_id\n";
  foreach my $pro (@proj){
    print STDERR "projected slice -> ".$pro->to_Slice->get_seq_region_id()."\n";
  }
202

203
  @proj = grep { $_->to_Slice->get_seq_region_id() != $sr_id } @proj;
204

205 206 207
  my $segment = bless([1,$slice->length(),$slice ],
                      'Bio::EnsEMBL::ProjectionSegment');
  push( @proj, $segment );
208

209 210 211 212 213 214 215 216 217 218 219

  # construct list of Hap/PAR boundaries for entire seq region
  my @bounds;
  my $ent_slice = $sa->fetch_by_seq_region_id($sr_id);
  $ent_slice    = $ent_slice->invert() if($slice->strand == -1);
  my @ent_proj  = @{$sa->fetch_normalized_slice_projection($ent_slice)};

  shift @ent_proj; # skip first
  @bounds = map {$_->from_start - $slice->start() + 1} @ent_proj;


220
  # fetch features for the primary slice AND all symlinked slices
221 222 223
  foreach my $seg (@proj) {
    my $offset = $seg->from_start();
    my $seg_slice  = $seg->to_Slice();
Ian Longden's avatar
Ian Longden committed
224 225
    print STDERR "MORE: ".$seg_slice->name."\n";
    print STDERR "constraint :- $constraint\n";
226
    my $features = $self->_slice_fetch($seg_slice, $constraint); ## NO RESULTS
227

228 229
    # if this was a symlinked slice offset the feature coordinates as needed
    if($seg_slice->name() ne $slice->name()) {
230 231

    FEATURE:
232
      foreach my $f (@$features) {
Ian Longden's avatar
Ian Longden committed
233
	print STDERR "FEAT: ".ref($f)."\n";
234
        if($offset != 1) {
235

236 237 238
          $f->{'start'} += $offset-1;
          $f->{'end'}   += $offset-1;
        }
239 240 241 242

        # discard boundary crossing features from symlinked regions
        foreach my $bound (@bounds) {
          if($f->{'start'} < $bound && $f->{'end'} >= $bound) {
Ian Longden's avatar
Ian Longden committed
243
	    print STDERR "BOUNDRY CROSSED\n";
244 245 246 247
            next FEATURE;
          }
        }

248 249 250
        $f->{'slice'} = $slice;
        push @result, $f;
      }
251 252
    }
    else {
253 254 255 256 257
      push @result, @$features;
    }
  }

  $self->{'_slice_feature_cache'}->{$key} = \@result;
258

259

260 261
  return \@result;
}
262 263


264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
=head2 fetch_all_by_logic_name

  Arg [3]    : string $logic_name
               the logic name of the type of features to obtain
  Example    : $fs = $a->fetch_all_by_logic_name('foobar');
  Description: Returns a listref of features created from the database. 
               only features with an analysis of type $logic_name will be 
               returned. 
  Returntype : listref of Bio::EnsEMBL::SeqFeatures
  Exceptions : thrown if $logic_name
  Caller     : General
  Status     : Experimental

=cut

sub fetch_all_by_logic_name {
  my $self = shift;
  my $logic_name = shift || throw( "Need a logic_name" );
  my $constraint = $self->_logic_name_to_constraint( '',$logic_name );
  return $self->fetch_all( $constraint )
}

286 287 288 289 290 291 292 293 294 295 296 297 298
#
# helper function used by fetch_all_by_Slice_constraint method
#
sub _slice_fetch {
  my $self = shift;
  my $slice = shift;
  my $orig_constraint = shift;

  my $slice_start  = $slice->start();
  my $slice_end    = $slice->end();
  my $slice_strand = $slice->strand();
  my $slice_cs     = $slice->coord_system();
  my $slice_seq_region = $slice->seq_region_name();
Ian Longden's avatar
Ian Longden committed
299
  my $slice_seq_region_id = $slice->get_seq_region_id();
300 301 302 303 304 305 306 307 308 309 310

  #get the synonym and name of the primary_table
  my @tabs = $self->_tables;
  my ($tab_name, $tab_syn) = @{$tabs[0]};

  #find out what coordinate systems the features are in
  my $mcc = $self->db->get_MetaCoordContainer();
  my @feat_css = @{$mcc->fetch_all_CoordSystems_by_feature_type($tab_name)};

  my $asma = $self->db->get_AssemblyMapperAdaptor();
  my @features;
Ian Longden's avatar
Ian Longden committed
311
warn "jere are $self, @feat_css\n";
312 313 314 315 316 317 318 319
  # fetch the features from each coordinate system they are stored in
 COORD_SYSTEM: foreach my $feat_cs (@feat_css) {
    my $mapper;
    my @coords;
    my @ids;

    if($feat_cs->equals($slice_cs)) {
      # no mapping is required if this is the same coord system
320

321
      my $max_len = $self->_max_feature_length() ||
322 323
        $mcc->fetch_max_length_by_CoordSystem_feature_type($feat_cs,$tab_name);

324 325
      my $constraint = $orig_constraint;

326 327 328 329 330 331 332
      my $sr_id;
      if( $slice->adaptor() ) {
	$sr_id = $slice->adaptor()->get_seq_region_id($slice);
      } else {
	$sr_id = $self->db()->get_SliceAdaptor()->get_seq_region_id($slice);
      }

333 334 335
      $constraint .= " AND " if($constraint);
      $constraint .=
          "${tab_syn}.seq_region_id = $sr_id AND " .
336 337
          "${tab_syn}.seq_region_start <= $slice_end AND " .
          "${tab_syn}.seq_region_end >= $slice_start";
338 339 340 341 342 343 344

      if($max_len) {
        my $min_start = $slice_start - $max_len;
        $constraint .=
          " AND ${tab_syn}.seq_region_start >= $min_start";
      }

Ian Longden's avatar
Ian Longden committed
345
      print STDERR "#constraint $constraint\n";
346
      my $fs = $self->generic_fetch($constraint,undef,$slice);
347

348 349
      # features may still have to have coordinates made relative to slice
      # start
Ian Longden's avatar
Ian Longden committed
350
      print STDERR"#number of features is :- ".scalar(@$fs)."\n";
Graham McVicker's avatar
Graham McVicker committed
351
      $fs = _remap($fs, $mapper, $slice);
352

353
      push @features, @$fs;
Ian Longden's avatar
Ian Longden committed
354
      print STDERR "#number of features is :- ".scalar(@$fs)."\n";
355 356
    } else {
      $mapper = $asma->fetch_by_CoordSystems($slice_cs, $feat_cs);
357

358 359
      next unless defined $mapper;

360 361 362 363
      # Get list of coordinates and corresponding internal ids for
      # regions the slice spans
      @coords = $mapper->map($slice_seq_region, $slice_start, $slice_end,
                             $slice_strand, $slice_cs);
364

365
      @coords = grep {!$_->isa('Bio::EnsEMBL::Mapper::Gap')} @coords;
366

367 368 369
      next COORD_SYSTEM if(!@coords);

      @ids = map {$_->id()} @coords;
Ian Longden's avatar
Ian Longden committed
370 371
#coords are now id rather than name
#      @ids = @{$asma->seq_regions_to_ids($feat_cs, \@ids)};
372 373 374 375 376 377 378 379 380 381 382 383

      # When regions are large and only partially spanned by slice
      # it is faster to to limit the query with start and end constraints.
      # Take simple approach: use regional constraints if there are less
      # than a specific number of regions covered.

      if(@coords > $MAX_SPLIT_QUERY_SEQ_REGIONS) {
        my $constraint = $orig_constraint;
        my $id_str = join(',', @ids);
        $constraint .= " AND " if($constraint);
        $constraint .= "${tab_syn}.seq_region_id IN ($id_str)";

Ian Longden's avatar
Ian Longden committed
384
	print STDERR ".con: $constraint\n";
385
        my $fs = $self->generic_fetch($constraint, $mapper, $slice);
386

Ian Longden's avatar
Ian Longden committed
387
	print STDERR ".number of features is :- ".scalar(@$fs)."\n";
Graham McVicker's avatar
Graham McVicker committed
388
        $fs = _remap($fs, $mapper, $slice);
389 390

        push @features, @$fs;
Ian Longden's avatar
Ian Longden committed
391
	print STDERR ".number of features is :- ".scalar(@features)."\n";
392 393 394

      } else {
        # do multiple split queries using start / end constraints
395

396
        my $max_len = $self->_max_feature_length() ||
397 398
          $mcc->fetch_max_length_by_CoordSystem_feature_type($feat_cs,
                                                             $tab_name);
399 400 401 402 403
        my $len = @coords;
        for(my $i = 0; $i < $len; $i++) {
          my $constraint = $orig_constraint;
          $constraint .= " AND " if($constraint);
          $constraint .=
404 405 406
              "${tab_syn}.seq_region_id = "     . $ids[$i] . " AND " .
              "${tab_syn}.seq_region_start <= " . $coords[$i]->end() . " AND ".
              "${tab_syn}.seq_region_end >= "   . $coords[$i]->start();
407 408 409 410 411 412 413

          if($max_len) {
            my $min_start = $coords[$i]->start() - $max_len;
            $constraint .=
              " AND ${tab_syn}.seq_region_start >= $min_start";
          }

Ian Longden's avatar
Ian Longden committed
414
	print STDERR "~con: $constraint\n";
415
          my $fs = $self->generic_fetch($constraint,$mapper,$slice);
416

Ian Longden's avatar
Ian Longden committed
417
	  print STDERR "~number of features is :- ".scalar(@$fs)."\n";
Graham McVicker's avatar
Graham McVicker committed
418
          $fs = _remap($fs, $mapper, $slice);
Ian Longden's avatar
Ian Longden committed
419
	  print STDERR "~number after _remap features is :- ".scalar(@$fs)."\n";
420

421
          push @features, @$fs;
422 423 424
        }
      }
    }
425
  } #COORD system loop
426

427
  return \@features;
428
}
429

430

431

432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449
#
# Helper function containing some common feature storing functionality
#
# Given a Feature this will return a copy (or the same feature if no changes 
# to the feature are needed) of the feature which is relative to the start
# of the seq_region it is on. The seq_region_id of the seq_region it is on
# is also returned.
#
# This method will also ensure that the database knows which coordinate
# systems that this feature is stored in.
#

sub _pre_store {
  my $self    = shift;
  my $feature = shift;

  if(!ref($feature) || !$feature->isa('Bio::EnsEMBL::Feature')) {
    throw('Expected Feature argument.');
450
  }
451

452 453 454
  $self->_check_start_end_strand($feature->start(),$feature->end(),
                                 $feature->strand());

455 456 457 458

  my $db = $self->db();

  my $slice_adaptor = $db->get_SliceAdaptor();
459 460 461 462 463 464
  my $slice = $feature->slice();

  if(!ref($slice) || !$slice->isa('Bio::EnsEMBL::Slice')) {
    throw('Feature must be attached to Slice to be stored.');
  }

465
  # make sure feature coords are relative to start of entire seq_region
466
  if($slice->start != 1 || $slice->strand != 1) {
467
    #move feature onto a slice of the entire seq_region
468 469 470 471 472 473 474 475 476 477 478 479 480 481 482
    $slice = $slice_adaptor->fetch_by_region($slice->coord_system->name(),
                                             $slice->seq_region_name(),
                                             undef, #start
                                             undef, #end
                                             undef, #strand
                                             $slice->coord_system->version());

    $feature = $feature->transfer($slice);

    if(!$feature) {
      throw('Could not transfer Feature to slice of ' .
            'entire seq_region prior to storing');
    }
  }

483
  # Ensure this type of feature is known to be stored in this coord system.
484 485 486 487 488
  my $cs = $slice->coord_system;

  my ($tab) = $self->_tables();
  my $tabname = $tab->[0];

489 490
  my $mcc = $db->get_MetaCoordContainer();

Laura Clarke's avatar
 
Laura Clarke committed
491
  $mcc->add_feature_type($cs, $tabname, $feature->length);
492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539

  my $seq_region_id = $slice_adaptor->get_seq_region_id($slice);

  if(!$seq_region_id) {
    throw('Feature is associated with seq_region which is not in this DB.');
  }

  return ($feature, $seq_region_id);
}


#
# helper function used to validate start/end/strand and 
# hstart/hend/hstrand etc.
#
sub _check_start_end_strand {
  my $self = shift;
  my $start = shift;
  my $end   = shift;
  my $strand = shift;

  #
  # Make sure that the start, end, strand are valid
  #
  if(int($start) != $start) {
    throw("Invalid Feature start [$start].  Must be integer.");
  }
  if(int($end) != $end) {
    throw("Invalid Feature end [$end]. Must be integer.");
  }
  if(int($strand) != $strand || $strand < -1 || $strand > 1) {
    throw("Invalid Feature strand [$strand]. Must be -1, 0 or 1.");
  }
  if($end < $start) {
    throw("Invalid Feature start/end [$start/$end]. Start must be less " .
          "than or equal to end.");
  }

  return 1;
}


#
# Given a list of features checks if they are in the correct coord system
# by looking at the first features slice.  If they are not then they are
# converted and placed on the slice.
#
sub _remap {
Graham McVicker's avatar
Graham McVicker committed
540
  my ($features, $mapper, $slice) = @_;
541 542 543 544 545

  #check if any remapping is actually needed
  if(@$features && (!$features->[0]->isa('Bio::EnsEMBL::Feature') ||
                    $features->[0]->slice == $slice)) {
    return $features;
546
  }
547

548
  #remapping has not been done, we have to do our own conversion from
549 550 551 552 553 554 555 556 557 558
  #to slice coords

  my @out;

  my $slice_start = $slice->start();
  my $slice_end   = $slice->end();
  my $slice_strand = $slice->strand();
  my $slice_cs    = $slice->coord_system();

  my ($seq_region, $start, $end, $strand);
559

Ian Longden's avatar
Ian Longden committed
560
  my $slice_seq_region_id = $slice->get_seq_region_id();
561
  my $slice_seq_region = $slice->seq_region_name();
562

563
  foreach my $f (@$features) {
564
    #since feats were obtained in contig coords, attached seq is a contig
565 566 567 568 569
    my $fslice = $f->slice();
    if(!$fslice) {
      throw("Feature does not have attached slice.\n");
    }
    my $fseq_region = $fslice->seq_region_name();
Ian Longden's avatar
Ian Longden committed
570
    my $fseq_region_id = $fslice->get_seq_region_id();
571
    my $fcs = $fslice->coord_system();
572

573 574
    if(!$slice_cs->equals($fcs)) {
      #slice of feature in different coord system, mapping required
575

576
      ($seq_region, $start, $end, $strand) =
Ian Longden's avatar
Ian Longden committed
577
        $mapper->fastmap($fseq_region_id,$f->start(),$f->end(),$f->strand(),$fcs);
578 579 580 581 582 583 584 585 586 587 588

      # undefined start means gap
      next if(!defined $start);
    } else {
      $start      = $f->start();
      $end        = $f->end();
      $strand     = $f->strand();
      $seq_region = $f->slice->seq_region_name();
    }

    # maps to region outside desired area
589 590
    next if ($start > $slice_end) || ($end < $slice_start) || 
      ($slice_seq_region ne $seq_region);
591

592
    #shift the feature start, end and strand in one call
593
    if($slice_strand == -1) {
594
      $f->move( $slice_end - $end + 1, $slice_end - $start + 1, $strand * -1 );
595 596 597
    } else {
      $f->move( $start - $slice_start + 1, $end - $slice_start + 1, $strand );
    }
598 599 600

    $f->slice($slice);

Web Admin's avatar
Web Admin committed
601
    push @out,$f;
602
  }
603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652

  return \@out;
}


#
# Given a logic name and an existing constraint this will
# add an analysis table constraint to the feature.  Note that if no
# analysis_id exists in the columns of the primary table then no
# constraint is added at all
#
sub _logic_name_to_constraint {
  my $self = shift;
  my $constraint = shift;
  my $logic_name = shift;

  return $constraint if(!$logic_name);

  #make sure that an analysis_id exists in the primary table
  my ($prim_tab) = $self->_tables();
  my $prim_synonym = $prim_tab->[1];

  my $found_analysis=0;
  foreach my $col ($self->_columns) {
    my ($syn,$col_name) = split(/\./,$col);
    next if($syn ne $prim_synonym);
    if($col_name eq 'analysis_id') {
      $found_analysis = 1;
      last;
    }
  }

  if(!$found_analysis) {
    warning("This feature is not associated with an analysis.\n" .
            "Ignoring logic_name argument = [$logic_name].\n");
    return $constraint;
  }

  my $aa = $self->db->get_AnalysisAdaptor();
  my $an = $aa->fetch_by_logic_name($logic_name);

  if(!$an) {
    return undef;
  }

  my $an_id = $an->dbID();

  $constraint .= ' AND' if($constraint);
  $constraint .= " ${prim_synonym}.analysis_id = $an_id";
  return $constraint;
653 654 655
}


656
=head2 store
657

658
  Arg [1]    : list of Bio::EnsEMBL::SeqFeature
659 660 661 662 663 664 665
  Example    : $adaptor->store(@feats);
  Description: ABSTRACT  Subclasses are responsible for implementing this 
               method.  It should take a list of features and store them in 
               the database.
  Returntype : none
  Exceptions : thrown method is not implemented by subclass
  Caller     : general
666 667
  Status     : At Risk
             : throws if called.
668 669 670 671 672 673

=cut

sub store{
  my $self = @_;

674
  throw("Abstract method store not defined by implementing subclass\n");
675 676 677
}


678 679 680 681 682 683 684 685 686
=head2 remove

  Arg [1]    : A feature $feature 
  Example    : $feature_adaptor->remove($feature);
  Description: This removes a feature from the database.  The table the
               feature is removed from is defined by the abstract method
               _tablename, and the primary key of the table is assumed
               to be _tablename() . '_id'.  The feature argument must 
               be an object implementing the dbID method, and for the
687
               feature to be removed from the database a dbID value must
688 689
               be returned.
  Returntype : none
690 691
  Exceptions : thrown if $feature arg does not implement dbID(), or if
               $feature->dbID is not a true value
692
  Caller     : general
693
  Status     : Stable
694 695 696

=cut

697

698 699 700
sub remove {
  my ($self, $feature) = @_;

701 702
  if(!$feature || !ref($feature) || !$feature->isa('Bio::EnsEMBL::Feature')) {
    throw('Feature argument is required');
703 704
  }

705 706
  if(!$feature->is_stored($self->db)) {
    throw("This feature is not stored in this database");
707 708
  }

709 710
  my @tabs = $self->_tables;
  my ($table) = @{$tabs[0]};
711 712

  my $sth = $self->prepare("DELETE FROM $table WHERE ${table}_id = ?");
713 714
  $sth->bind_param(1,$feature->dbID,SQL_INTEGER);
  $sth->execute();
715

716 717 718 719
  #unset the feature dbID ad adaptor
  $feature->dbID(undef);
  $feature->adaptor(undef);

720 721 722 723
  return;
}


724
=head2 remove_by_Slice
725

726
  Arg [1]    : Bio::Ensembl::Slice $slice
727
  Example    : $feature_adaptor->remove_by_Slice($slice);
728 729 730 731 732 733
  Description: This removes features from the database which lie on a region
               represented by the passed in slice.  Only features which are
               fully contained by the slice are deleted; features which overlap
               the edge of the slice are not removed.
               The table the features are removed from is defined by
               the abstract method_tablename.
734
  Returntype : none
735
  Exceptions : thrown if no slice is supplied
736
  Caller     : general
737
  Status     : Stable
738 739 740

=cut

741 742
sub remove_by_Slice {
  my ($self, $slice) = @_;
743

744 745
  if(!$slice || !ref($slice) || !$slice->isa('Bio::EnsEMBL::Slice')) {
    throw("Slice argument is required");
746 747
  }

748 749
  my @tabs = $self->_tables;
  my ($table_name) = @{$tabs[0]};
750

751 752 753
  my $seq_region_id = $self->db->get_SliceAdaptor->get_seq_region_id($slice);
  my $start = $slice->start();
  my $end   = $slice->end();
754

755 756 757 758 759 760 761
  #
  # Delete only features fully on the slice, not overlapping ones
  #
  my $sth = $self->prepare("DELETE FROM $table_name " .
                           "WHERE seq_region_id = ? " .
                           "AND   seq_region_start >= ? " .
                           "AND   seq_region_end <= ?");
762

763 764 765 766
  $sth->bind_param(1,$seq_region_id,SQL_INTEGER);
  $sth->bind_param(2,$start,SQL_INTEGER);
  $sth->bind_param(3,$end,SQL_INTEGER);
  $sth->execute();
767
  $sth->finish();
768 769 770
}


771 772 773 774 775 776 777 778 779 780 781 782 783 784
#
# Internal function. Allows the max feature length which is normally
# retrieved from the meta_coord table to be overridden.  This allows
# for some significant optimizations to be put in when it is known
# that requested features will not be over a certain size.
#
sub _max_feature_length {
  my $self = shift;
  return $self->{'_max_feature_length'} = shift if(@_);
  return $self->{'_max_feature_length'};
}



Graham McVicker's avatar
Graham McVicker committed
785
=head1 DEPRECATED METHODS
786

Graham McVicker's avatar
Graham McVicker committed
787
=cut
788

789 790 791 792

=head2 fetch_all_by_RawContig_constraint

  Description: DEPRECATED use fetch_all_by_RawContig_constraint instead
793 794 795

=cut

796
sub fetch_all_by_RawContig_constraint {
797
  my $self = shift;
798 799
  deprecate('Use fetch_all_by_Slice_constraint() instead.');
  return $self->fetch_all_by_slice_constraint(@_);
800 801
}

802
=head2 fetch_all_by_RawContig
803

804
  Description: DEPRECATED use fetch_all_by_Slice instead
805 806 807

=cut

808
sub fetch_all_by_RawContig {
809
  my $self = shift;
810 811 812
  deprecate('Use fetch_all_by_Slice() instead.');
  return $self->fetch_all_by_Slice(@_);
}
813

814
=head2 fetch_all_by_RawContig_and_score
815

816
  Description: DEPRECATED use fetch_all_by_Slice_and_score instead
817

818
=cut
819

820 821 822 823 824 825 826 827 828
sub fetch_all_by_RawContig_and_score{
  my $self = shift;
  deprecate('Use fetch_all_by_Slice_and_score() instead.');
  return $self->fetch_all_by_Slice_and_score(@_);
}

=head2 remove_by_RawContig

  Description: DEPRECATED use remove_by_Slice instead
829 830 831

=cut

832
sub remove_by_RawContig {
833
  my $self = shift;
834 835
  deprecate("Use remove_by_Slice instead");
  return $self->remove_by_Slice(@_);
836 837
}

838

839 840 841
1;