EnsEMBL/DBSQL/SliceAdaptor.pm untested

filter: Statementstmt 0.0% 0 / 1025 Branchbran 0.0% 0 / 374 Conditioncond 0.0% 0 / 213 Subroutinesub 0.0% 0 / 52 Podpod 0.0% 0 / 41 totaltotal 0.0% 0 / 1705 CC 188 SCAR 52.9
CC
188
Cov
0%
fetch_by_region
930.0
store
240.0
fetch_normalized_slice_projection
210.0
CRAP 197.8
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::SliceAdaptor - A database aware adaptor responsible for
34 the creation of Slice objects.
35  
36 =head1 SYNOPSIS
37  
38 use Bio::EnsEMBL::Utils::Slice qw(split_Slices);
39 use Bio::EnsEMBL::Registry;
40  
41 Bio::EnsEMBL::Registry->load_registry_from_db(
42 -host => 'ensembldb.ensembl.org',
43 -user => 'anonymous'
44 );
45  
46 $slice_adaptor =
47 Bio::EnsEMBL::Registry->get_adaptor( "human", "core", "slice" );
48  
49 # get a slice on the entire chromosome X
50 $chr_slice = $slice_adaptor->fetch_by_region( 'chromosome', 'X' );
51  
52 # get a slice for each clone in the database
53 foreach $cln_slice ( @{ $slice_adaptor->fetch_all('clone') } ) {
54 # do something with clone
55 }
56  
57 # get a slice which is part of NT_004321
58 $spctg_slice =
59 $slice_adaptor->fetch_by_region( 'supercontig', 'NT_004321',
60 200_000, 600_000 );
61  
62 # get all non-redundant slices from the highest possible coordinate
63 # systems
64 $slices = $slice_adaptor->fetch_all('toplevel');
65  
66 # include non-reference regions
67 $slices = $slice_adaptor->fetch_all( 'toplevel', undef, 1 );
68  
69 # include duplicate regions
70 $slices = $slice_adaptor->fetch_all( 'toplevel', undef, 0, 1 );
71  
72 # split up a list of slices into smaller slices
73 $overlap = 1000;
74 $max_length = 1e6;
75 $slices = split_Slices( $slices, $max_length, $overlap );
76  
77 # store a list of slice names in a file
78 open( FILE, ">$filename" ) or die("Could not open file $filename");
79 foreach my $slice (@$slices) {
80 print FILE $slice->name(), "\n";
81 }
82 close FILE;
83  
84 # retrieve a list of slices from a file
85 open( FILE, $filename ) or die("Could not open file $filename");
86 while ( $name = <FILE> ) {
87 chomp($name);
88 $slice = $slice_adaptor->fetch_by_name($name);
89 # do something with slice
90 }
91  
92 =head1 DESCRIPTION
93  
94 This module is responsible for fetching Slices representing genomic
95 regions from a database. A Details on how slices can be used are in the
96 Bio::EnsEMBL::Slice module.
97  
98 =head1 METHODS
99  
100 =cut
101  
102  
103 package Bio::EnsEMBL::DBSQL::SliceAdaptor;
104 $Bio::EnsEMBL::DBSQL::SliceAdaptor::VERSION = '114.0.0_50'; # TRIAL
105 $Bio::EnsEMBL::DBSQL::SliceAdaptor::VERSION = '114.0.050';
106 use vars qw(@ISA);
107 use strict;
108  
109  
110 use Bio::EnsEMBL::DBSQL::BaseAdaptor;
111 use Bio::EnsEMBL::Slice;
112 use Bio::EnsEMBL::CircularSlice;
113 use Bio::EnsEMBL::Mapper;
114 use Bio::EnsEMBL::LRGSlice;
115 use Bio::EnsEMBL::Utils::Exception qw(throw warning);
116 use Bio::EnsEMBL::ProjectionSegment;
117 use Scalar::Util qw/looks_like_number/;
118 use Bio::EnsEMBL::Utils::Scalar qw/assert_integer/;
119  
120 @ISA = ('Bio::EnsEMBL::DBSQL::BaseAdaptor');
121  
122 sub new {
123 my $caller = shift;
124  
125 my $class = ref($caller) || $caller;
126  
127 my $self = $class->SUPER::new(@_);
128  
129 # use a cache which is shared and also used by the assembly
130 # mapper adaptor
131  
132 my $seq_region_cache = $self->db->get_SeqRegionCache();
133  
134 $self->{'sr_name_cache'} = $seq_region_cache->{'name_cache'};
135 $self->{'sr_id_cache'} = $seq_region_cache->{'id_cache'};
136  
137 $self->{'lrg_region_test'} = undef;
138 my $meta_container = $self->db->get_MetaContainer();
139 my @values = $meta_container->list_value_by_key("LRG");
140 if(scalar(@values) and $values[0]->[0]){
141 $self->{'lrg_region_test'} = $values[0]->[0];
142 }
143 return $self;
144 }
145  
146  
147 =head2 fetch_by_region
148  
149 Arg [1] : string $coord_system_name (optional)
150 The name of the coordinate system of the slice to be created
151 This may be a name of an actual coordinate system or an alias
152 to a coordinate system. Valid aliases are 'seqlevel' or
153 'toplevel'.
154 Arg [2] : string $seq_region_name
155 The name of the sequence region that the slice will be
156 created on.
157 Arg [3] : int $start (optional, default = 1)
158 The start of the slice on the sequence region
159 Arg [4] : int $end (optional, default = seq_region length)
160 The end of the slice on the sequence region
161 Arg [5] : int $strand (optional, default = 1)
162 The orientation of the slice on the sequence region
163 Arg [6] : string $version (optional, default = default version)
164 The version of the coordinate system to use (e.g. NCBI33)
165 Arg [7] : boolean $no_fuzz (optional, default = undef (false))
166 If true (non-zero), do not use "fuzzy matching" (see below).
167 Example : $slice = $slice_adaptor->fetch_by_region('chromosome', 'X');
168 $slice = $slice_adaptor->fetch_by_region('clone', 'AC008066.4');
169 Description: Retrieves a slice on the requested region. At a minimum the
170 name the name of the seq_region to fetch must be provided.
171  
172 If no coordinate system name is provided than a slice on the
173 highest ranked coordinate system with a matching
174 seq_region_name will be returned. If a version but no
175 coordinate system name is provided, the same behaviour will
176 apply, but only coordinate systems of the appropriate version
177 are considered. The same applies if the 'toplevel' coordinate
178 system is specified, however in this case the version is
179 ignored. The coordinate system should always be specified if
180 it is known, since this is unambiguous and faster.
181  
182 Some fuzzy matching is performed if no exact match for
183 the provided name is found. This allows clones to be
184 fetched even when their version is not known. For
185 example fetch_by_region('clone', 'AC008066') will
186 retrieve the sequence_region with name 'AC008066.4'.
187  
188 The fuzzy matching can be turned off by setting the
189 $no_fuzz argument to a true value.
190  
191 If the requested seq_region is not found in the database undef
192 is returned.
193  
194 Returntype : Bio::EnsEMBL::Slice or undef
195 Exceptions : throw if no seq_region_name is provided
196 throw if invalid coord_system_name is provided
197 throw if start > end is provided
198 Caller : general
199 Status : Stable
200  
201 =cut
202  
203  
204 #
205 # ARNE: This subroutine needs simplification!!
206 #
207 sub fetch_by_region {
208 my ( $self, $coord_system_name, $seq_region_name, $start, $end,
209 $strand, $version, $no_fuzz )
210 = @_;
211  
212 assert_integer($start, 'start') if defined $start;
213 assert_integer($end, 'end') if defined $end;
214  
215 if ( !defined($start) ) { $start = 1 }
216 if ( !defined($strand) ) { $strand = 1 }
217  
218 if ( !defined($seq_region_name) ) {
219 throw('seq_region_name argument is required');
220 }
221  
222 my $cs;
223 my $csa = $self->db->get_CoordSystemAdaptor();
224  
225 if ( defined($coord_system_name) ) {
226 $cs = $csa->fetch_by_name( $coord_system_name, $version );
227  
228 if ( !defined($cs) ) {
229 # deal with cases where undefined coordsystem name requested is 'chromosome'
230 if ( $coord_system_name eq "chromosome" ) {
231  
232 # set the 'chromosome' alias, if not yet set
233 $cs = $self->_create_chromosome_alias();
234  
235 } else {
236 throw( sprintf( "Unknown coordinate system:\n"
237 . "name='%s' version='%s' seq region name='%s'\n",
238 $coord_system_name, $version, $seq_region_name ) );
239 }
240 }
241  
242 # fetching by toplevel is same as fetching w/o name or version
243 if ( $cs->is_top_level() ) {
244 $cs = undef;
245 $version = undef;
246 }
247  
248 } ## end if ( defined($coord_system_name...))
249  
250 my $constraint;
251 my $sql;
252 my @bind_params;
253 my $key;
254  
255 if ( defined($cs) ) {
256  
257 # if chromosome alias is defined, use karyotype_cache to access seq region data
258 # rather than a database query
259 if ( defined($cs->alias_to()) && $cs->alias_to() eq "chromosome" ) {
260  
261 $key = "karyotype_cache";
262  
263 } else { # otherwise, search database to access seq region data, etc.
264  
265 $sql = sprintf( "SELECT sr.name, sr.seq_region_id, sr.length, %d "
266 . "FROM seq_region sr ",
267 $cs->dbID() );
268  
269 $constraint = "AND sr.coord_system_id = ?";
270 push( @bind_params, [ $cs->dbID(), SQL_INTEGER ] );
271  
272 $key = "$seq_region_name:" . $cs->dbID();
273
274 }
275 } else {
276 $sql =
277 "SELECT sr.name, sr.seq_region_id, sr.length, cs.coord_system_id "
278 . "FROM seq_region sr, coord_system cs ";
279  
280 $constraint = "AND sr.coord_system_id = cs.coord_system_id "
281 . "AND cs.species_id = ? ";
282 push( @bind_params, [ $self->species_id(), SQL_INTEGER ] );
283  
284 if ( defined($version) ) {
285 $constraint .= "AND cs.version = ? ";
286 push( @bind_params, [ $version, SQL_VARCHAR ] );
287 }
288  
289 $constraint .= "ORDER BY cs.rank ASC";
290 }
291  
292 # check the cache so we only go to the db if necessary
293 my $length;
294 my $arr;
295  
296 # use $key to access karyotype cache and define $arr
297 if ( defined($key) && ($key eq "karyotype_cache") ) {
298
299 my $coord_system_id = $cs->dbID();
300
301 # retrieve values from karyotype cache
302 my $seq_region_id = $cs->{$key}{$seq_region_name}{$coord_system_id}{'seq_region_id'};
303 $length = $cs->{$key}{$seq_region_name}{$coord_system_id}{'length'};
304  
305 # populate $arr with values from karyotype cache
306 $arr = [ $seq_region_name, $seq_region_id, $length, $coord_system_id ];
307  
308 # define $end, if not yet defined
309 if ( !defined($end) ) { $end = $length }
310  
311 # add in check that $arr is populated
312 throw("Unable to popular $arr with values from karyotype cache") unless $arr;
313  
314 } else {
315  
316 if ( defined($key) ) { $arr = $self->{'sr_name_cache'}->{$key} }
317  
318 if ( defined($arr) ) {
319 $length = $arr->[3];
320 } else {
321 my $sth =
322 $self->prepare( $sql . "WHERE sr.name = ? " . $constraint );
323  
324 unshift( @bind_params, [ $seq_region_name, SQL_VARCHAR ] );
325  
326 my $pos = 0;
327 foreach my $param (@bind_params) {
328 $sth->bind_param( ++$pos, $param->[0], $param->[1] );
329 }
330  
331 $sth->execute();
332 my @row = $sth->fetchrow_array();
333 $sth->finish();
334  
335 unless ( @row ) {
336  
337 # deal with cases where a coordsystem might not be defined by user
338 my $slice;
339 if (!defined $cs) {
340 $slice = $self->_fetch_by_seq_region_synonym( undef, $seq_region_name, $start, $end, $strand, $version, $no_fuzz );
341 } else {
342 $slice = $self->_fetch_by_seq_region_synonym( $cs, $seq_region_name, $start, $end, $strand, $version, $no_fuzz );
343 }
344  
345 # check whether any slice data has been returned
346 if ( $slice && $slice->seq_region_name ) {
347 my $matched_name = $slice->seq_region_name;
348  
349 # if matched name is different to query name, skip fuzzy matching
350 if ( $matched_name ne $seq_region_name ) {
351 $seq_region_name = $matched_name;
352  
353 # define $arr
354 my $tmp_key_string = "$seq_region_name:" . $slice->coord_system()->dbID();
355 $arr = $self->{'sr_name_cache'}->{$tmp_key_string};
356 $length = $arr->[3];
357 $cs = $slice->coord_system() if (!$cs);
358 }
359  
360 } else { # if no slice object with a match returned, try using a fuzzy match
361 if (!$no_fuzz) {
362  
363 my ($fuzzy_matched_name, $cs_new) = $self->_fetch_by_fuzzy_matching( $cs, $seq_region_name, $sql, $constraint, \@bind_params );
364 $cs = $cs_new;
365
366 if (!$fuzzy_matched_name) {
367 return;
368 }
369  
370 # define arr
371 my $tmp_key_string = $fuzzy_matched_name . ":" . $cs_new->dbID();
372 if (exists $self->{'sr_name_cache'}->{$tmp_key_string}) {
373 $seq_region_name = $fuzzy_matched_name;
374 $arr = $self->{'sr_name_cache'}->{$tmp_key_string};
375 $length = $arr->[3];
376 } else {
377 return;
378 }
379 } else {
380 return;
381 }
382 }
383 } else {
384  
385 my ( $id, $cs_id );
386 ( $seq_region_name, $id, $length, $cs_id ) = @row;
387  
388 # cache to speed up for future queries
389 my $arr = [ $id, $seq_region_name, $cs_id, $length ];
390 $self->{'sr_name_cache'}->{"$seq_region_name:$cs_id"} = $arr;
391 $self->{'sr_id_cache'}->{"$id"} = $arr;
392 $cs = $csa->fetch_by_dbID($cs_id);
393 }
394 } ## end else [ if ( defined($arr) ) ]
395 }
396  
397 if ( !defined($end) ) { $end = $length }
398  
399 #If this was given then check if we've got a circular seq region otherwise
400 #let it fall through to the normal Slice method
401 if ( $end + 1 < $start ) {
402 my $cs_id = $cs->dbID();
403 my $seq_region_id = $self->{'sr_name_cache'}->{"$seq_region_name:$cs_id"}->[0];
404 if($self->is_circular($seq_region_id)) {
405 my $new_sl =
406 Bio::EnsEMBL::CircularSlice->new(
407 -COORD_SYSTEM => $cs,
408 -SEQ_REGION_NAME => $seq_region_name,
409 -SEQ_REGION_LENGTH => $length,
410 -START => $start,
411 -END => $end,
412 -STRAND => 1,
413 -ADAPTOR => $self );
414
415 return $new_sl;
416 }
417 }
418  
419 if ( defined( $self->{'lrg_region_test'} )
420 and substr( $cs->name, 0, 3 ) eq $self->{'lrg_region_test'} )
421 {
422 return
423 Bio::EnsEMBL::LRGSlice->new( -COORD_SYSTEM => $cs,
424 -SEQ_REGION_NAME => $seq_region_name,
425 -SEQ_REGION_LENGTH => $length,
426 -START => $start,
427 -END => $end,
428 -STRAND => $strand,
429 -ADAPTOR => $self );
430 } else {
431 return
432 Bio::EnsEMBL::Slice->new_fast( {
433 'coord_system' => $cs,
434 'seq_region_name' => $seq_region_name,
435 'seq_region_length' => $length,
436 'start' => $start,
437 'end' => $end,
438 'strand' => $strand,
439 'adaptor' => $self } );
440 }
441 } ## end sub fetch_by_region
442  
443 =head2 fetch_by_toplevel_location
444  
445 Arg [1] : string $location
446 Ensembl formatted location. Can be a format like
447 C<name:start-end>, C<name:start..end>, C<name:start:end>,
448 C<name:start>, C<name>. We can also support strand
449 specification as a +/- or 1/-1.
450
451 Location names must be separated by a C<:>. All others can be
452 separated by C<..>, C<:> or C<->.
453 Arg[2] : boolean $no_warnings
454 Suppress warnings from this method
455 Arg[3] : boolean $no_fuzz
456 Stop fuzzy matching of sequence regions from occuring
457 Arg[4] : boolean $ucsc
458 If we are unsuccessful at retriving a location retry taking any
459 possible chr prefix into account e.g. chrX and X are treated as
460 equivalents
461 Example : my $slice = $sa->fetch_by_toplevel_location('X:1-10000')
462 my $slice = $sa->fetch_by_toplevel_location('X:1-10000:-1')
463 Description : Converts an Ensembl location/region into the sequence region
464 name, start and end and passes them onto C<fetch_by_region()>.
465 The code assumes that the required slice is on the top level
466 coordinate system. The code assumes that location formatting
467 is not perfect and will perform basic cleanup before parsing.
468 Returntype : Bio::EnsEMBL::Slice
469 Exceptions : If $location is false otherwise see C<fetch_by_location()>
470 or C<fetch_by_region()>
471 Caller : General
472 Status : Beta
473  
474 =cut
475  
476 sub fetch_by_toplevel_location {
477 my ($self, $location, $no_warnings, $no_fuzz, $ucsc) = @_;
478 return $self->fetch_by_location($location, 'toplevel', undef, $no_warnings, $no_fuzz, $ucsc);
479 }
480  
481 =head2 fetch_by_location
482  
483 Arg [1] : string $location
484 Ensembl formatted location. Can be a format like
485 C<name:start-end>, C<name:start..end>, C<name:start:end>,
486 C<name:start>, C<name>. We can also support strand
487 specification as a +/- or 1/-1.
488
489 Location names must be separated by a C<:>. All others can be
490 separated by C<..>, C<:>, C<_> or C<->.
491 Arg[2] : String $coord_system_name
492 The coordinate system to retrieve
493 Arg[3] : String $coord_system_version
494 Optional parameter. Version of the coordinate system to fetch
495 Arg[4] : boolean $no_warnings
496 Suppress warnings from this method
497 Arg[5] : boolean $no_fuzz
498 Stop fuzzy matching of sequence regions from occuring
499 Arg[6] : boolean $ucsc
500 If we are unsuccessful at retriving a location retry taking any
501 possible chr prefix into account e.g. chrX and X are treated as
502 equivalents
503 Example : my $slice = $sa->fetch_by_location('X:1-10000','chromosome')
504 my $slice = $sa->fetch_by_location('X:1-10000:-1','toplevel')
505 Description : Converts an Ensembl location/region into the sequence region
506 name, start and end and passes them onto C<fetch_by_region()>.
507 The code assumes that location formatting is not perfect and
508 will perform basic cleanup before parsing.
509 Returntype : Bio::EnsEMBL::Slice
510 Exceptions : If $location or coordinate system is false otherwise
511 see C<fetch_by_region()>
512 Caller : General
513 Status : Beta
514  
515 =cut
516  
517 sub fetch_by_location {
518 my ($self, $location, $coord_system_name, $coord_system_version, $no_warnings, $no_fuzz, $ucsc) = @_;
519 throw "No coordinate system name specified" unless $coord_system_name;
520
521 my ($seq_region_name, $start, $end, $strand) = $self->parse_location_to_values($location, $no_warnings);
522  
523 if(! $seq_region_name) {
524 return;
525 }
526
527 if(defined $start && defined $end && $start > $end) {
528 throw "Cannot request a slice whose start is greater than its end. Start: $start. End: $end";
529 }
530
531 $seq_region_name =~ s/^chr// if ($ucsc);
532 my $slice = $self->fetch_by_region($coord_system_name, $seq_region_name, $start, $end, $strand, $coord_system_version, $no_fuzz);
533 if(! defined $slice) {
534 if($ucsc) {
535 my $ucsc_seq_region_name = $seq_region_name;
536 $ucsc_seq_region_name =~ s/^chr//;
537 if($ucsc_seq_region_name ne $seq_region_name) {
538 $slice = $self->fetch_by_region($coord_system_name, $ucsc_seq_region_name, $start, $end, $strand, $coord_system_version, $no_fuzz);
539 return if ! defined $slice; #if we had no slice still then bail
540 }
541 else {
542 return; #If it was not different then we didn't have the prefix so just return (same bail as before)
543 }
544 }
545 else {
546 return; #We didn't have a slice and no UCSC specifics are being triggered
547 }
548 }
549
550 my $srl = $slice->seq_region_length();
551 my $name = $slice->seq_region_name();
552 if(defined $start && $start > $srl) {
553 throw "Cannot request a slice whose start ($start) is greater than $srl for $name.";
554 }
555 if(defined $end && $end > $srl) {
556 warning "Requested end ($end) is greater than $srl for $name. Resetting to $srl" if ! $no_warnings;
557 $slice->{end} = $srl;
558 }
559
560 return $slice;
561 }
562  
563 =head2 parse_location_to_values
564  
565 Arg [1] : string $location
566 Ensembl formatted location. Can be a format like
567 C<name:start-end>, C<name:start..end>, C<name:start:end>,
568 C<name:start>, C<name>. We can also support strand
569 specification as a +/- or 1/-1.
570
571 Location names must be separated by a C<:>. All others can be
572 separated by C<..>, C<:> C<_>, or C<->.
573  
574 If the start is negative, start will be reset to 1 (e.g.: 1: -10-1,000')
575 If both start and end are negative, returns undef (e.g.: 1: -10--1,000')
576 Arg[2] : boolean $no_warnings
577 Suppress warnings from this method
578 Arg[3] : boolean $no_errors
579 Supress errors being thrown from this method
580 Example : my ($name, $start, $end, $strand) = $sa->parse_location_to_values('X:1..100:1);
581 Description : Takes in an Ensembl location String and returns the parsed
582 values
583 Returntype : List. Contains name, start, end and strand
584  
585 =cut
586  
587  
588 sub parse_location_to_values {
589 my ($self, $location, $no_warnings, $no_errors) = @_;
590
591 throw 'You must specify a location' if ! $location;
592
593 #cleanup any nomenclature like 1 000 or 1,000
594 my $number_seps_regex = qr/\s+|,/;
595 my $separator_regex = qr/(?:-|[.]{2}|\:|_)?/; # support -, .., : and _ as separators
596 my $hgvs_nomenclature_regex = qr/(?:g\.)?/; # check for HGVS looking locations e.g. X:g.1-100
597 my $number_regex = qr/[0-9, EMKG]+/xmsi;
598 my $number_regex_signed = qr/-?[0-9, EMKG]+/xmsi; # to capture negative locations as sometimes we end up in negative location if the location is padded
599 my $strand_regex = qr/[+-1]|-1/xms;
600
601 my $regex = qr/^((?:\w|\.|_|-)+) \s* :? \s* $hgvs_nomenclature_regex ($number_regex_signed)? $separator_regex ($number_regex)? $separator_regex ($strand_regex)? $/xms;
602 my ($seq_region_name, $start, $end, $strand);
603 if(($seq_region_name, $start, $end, $strand) = $location =~ $regex) {
604
605 if(defined $strand) {
606 if(!looks_like_number($strand)) {
607 $strand = ($strand eq '+') ? 1 : -1;
608 }
609 }
610
611 if(defined $start) {
612 $start =~ s/$number_seps_regex//g;
613 if($start < 1) {
614 warning "Start was less than 1 (${start}) which is not allowed. Resetting to 1" if ! $no_warnings;
615  
616 unless(defined $end) {
617 # We will reach here only when the location is given without start and '-' is used as seperator eg: 1:-10 (expected to return 1:1-10)
618 $end = abs($start);
619 }
620 $start = 1;
621 }
622 }
623 if(defined $end) {
624 $end =~ s/$number_seps_regex//g;
625 if($end < 1) {
626 throw "Cannot request negative or 0 end indexes through this interface. Given $end but expected something greater than 0" unless $no_errors;
627 }
628 }
629
630 }
631
632 return ($seq_region_name, $start, $end, $strand);
633 }
634  
635 =head2 fetch_by_region_unique
636  
637 Arg [1] : string $coord_system_name (optional)
638 The name of the coordinate system of the slice to be created
639 This may be a name of an actual coordinate system or an alias
640 to a coordinate system. Valid aliases are 'seqlevel' or
641 'toplevel'.
642 Arg [2] : string $seq_region_name
643 The name of the sequence region that the slice will be
644 created on.
645 Arg [3] : int $start (optional, default = 1)
646 The start of the slice on the sequence region
647 Arg [4] : int $end (optional, default = seq_region length)
648 The end of the slice on the sequence region
649 Arg [5] : int $strand (optional, default = 1)
650 The orientation of the slice on the sequence region
651 Arg [6] : string $version (optional, default = default version)
652 The version of the coordinate system to use (e.g. NCBI33)
653 Arg [7] : boolean $no_fuzz (optional, default = undef (false))
654 If true (non-zero), do not use "fuzzy matching" (see below).
655 Example : $slice = $slice_adaptor->fetch_by_region_unique('chromosome', 'HSCHR6_MHC_COX');
656 Description: Retrieves a slice on the requested region but returns only the unique
657 parts of the slice. At a minimum the
658 name the name of the seq_region to fetch must be provided.
659  
660 If no coordinate system name is provided than a slice on the
661 highest ranked coordinate system with a matching
662 seq_region_name will be returned. If a version but no
663 coordinate system name is provided, the same behaviour will
664 apply, but only coordinate systems of the appropriate version
665 are considered. The same applies if the 'toplevel' coordinate
666 system is specified, however in this case the version is
667 ignored. The coordinate system should always be specified if
668 it is known, since this is unambiguous and faster.
669  
670 Some fuzzy matching is performed if no exact match for
671 the provided name is found. This allows clones to be
672 fetched even when their version is not known. For
673 example fetch_by_region('clone', 'AC008066') will
674 retrieve the sequence_region with name 'AC008066.4'.
675  
676 The fuzzy matching can be turned off by setting the
677 $no_fuzz argument to a true value.
678  
679 If the requested seq_region is not found in the database undef
680 is returned.
681  
682 Returntype : listref Bio::EnsEMBL::Slice
683 Exceptions : throw if no seq_region_name is provided
684 throw if invalid coord_system_name is provided
685 throw if start > end is provided
686 Caller : general
687 Status : Stable
688  
689 =cut
690  
691 sub fetch_by_region_unique {
692 my $self = shift;
693  
694 my @out = ();
695 my $slice = $self->fetch_by_region(@_);
696  
697  
698 if ( !exists( $self->{'asm_exc_cache'} ) ) {
699 $self->_build_exception_cache();
700 }
701  
702 if ( exists(
703 $self->{'asm_exc_cache'}->{ $self->get_seq_region_id($slice) }
704 ) )
705 {
706 # Dereference symlinked assembly regions. Take out any regions
707 # which are symlinked because these are duplicates.
708 my @projection =
709 @{ $self->fetch_normalized_slice_projection($slice) };
710  
711 foreach my $segment (@projection) {
712 if ( $segment->[2]->seq_region_name() eq $slice->seq_region_name()
713 && $segment->[2]->coord_system->equals( $slice->coord_system ) )
714 {
715 push( @out, $segment->[2] );
716 }
717 }
718 } else {
719 @out = ($slice);
720 }
721  
722 return \@out;
723 } ## end sub fetch_by_region_unique
724  
725 =head2 fetch_by_name
726  
727 Arg [1] : string $name
728 Example : $name = 'chromosome:NCBI34:X:1000000:2000000:1';
729 $slice = $slice_adaptor->fetch_by_name($name);
730 $slice2 = $slice_adaptor->fetch_by_name($slice3->name());
731 Description: Fetches a slice using a slice name (i.e. the value returned by
732 the Slice::name method). This is useful if you wish to
733 store a unique identifier for a slice in a file or database or
734 pass a slice over a network.
735 Slice::name allows you to serialise/marshall a slice and this
736 method allows you to deserialise/unmarshal it.
737  
738 Returns undef if no seq_region with the provided name exists in
739 the database.
740  
741 Returntype : Bio::EnsEMBL::Slice or undef
742 Exceptions : throw if incorrent arg provided
743 Caller : Pipeline
744 Status : Stable
745  
746 =cut
747  
748 sub fetch_by_name {
749 my $self = shift;
750 my $name = shift;
751  
752 if(!$name) {
753 throw("name argument is required");
754 }
755  
756 my @array = split(/:/,$name);
757  
758 if(scalar(@array) < 3 || scalar(@array) > 6) {
759 throw("Malformed slice name [$name]. Format is " .
760 "coord_system:version:name:start:end:strand");
761 }
762  
763 # Rearrange arguments to suit fetch_by_region
764  
765 my @targetarray;
766  
767 $targetarray[0]=$array[0];
768 $targetarray[5]=(($array[1]&&$array[1] ne "")?$array[1]:undef);
769 $targetarray[1]=(($array[2]&&$array[2] ne "")?$array[2]:undef);
770 $targetarray[2]=(($array[3]&&$array[3] ne "")?$array[3]:undef);
771 $targetarray[3]=(($array[4]&&$array[4] ne "")?$array[4]:undef);
772 $targetarray[4]=(($array[5]&&$array[5] ne "")?$array[5]:undef);
773 return $self->fetch_by_region(@targetarray);
774 }
775  
776  
777  
778 =head2 fetch_by_seq_region_id
779  
780 Arg [1] : string $seq_region_id
781 The internal identifier of the seq_region to create this slice
782 on
783 Arg [2] : optional start
784 Arg [3] : optional end
785 Arg [4] : optional strand
786 Example : $slice = $slice_adaptor->fetch_by_seq_region_id(34413);
787 Description: Creates a slice object of an entire seq_region using the
788 seq_region internal identifier to resolve the seq_region.
789 Returns undef if no such slice exists.
790 Returntype : Bio::EnsEMBL::Slice or undef
791 Exceptions : none
792 Caller : general
793 Status : Stable
794  
795 =cut
796  
797 sub fetch_by_seq_region_id {
798 my ( $self, $seq_region_id, $start, $end, $strand, $check_prior_ids ) = @_;
799  
800 my $csa = $self->db->get_CoordSystemAdaptor();
801 my $arr = $self->{'sr_id_cache'}->{$seq_region_id};
802 my ( $name, $length, $cs, $cs_id );
803  
804  
805 if ( $arr && defined( $arr->[2] ) ) {
806 ( $name, $cs_id, $length ) = ( $arr->[1], $arr->[2], $arr->[3] );
807 $cs = $self->db->get_CoordSystemAdaptor->fetch_by_dbID($cs_id);
808 } else {
809 my $sth =
810 $self->prepare( "SELECT sr.name, sr.coord_system_id, sr.length "
811 . "FROM seq_region sr "
812 . "WHERE sr.seq_region_id = ? " );
813  
814 $sth->bind_param( 1, $seq_region_id, SQL_INTEGER );
815 $sth->execute();
816  
817 my @row = $sth->fetchrow_array();
818 unless ( @row ) {
819 # This could have been an old seq region id so see if we can
820 # translate it into a more recent version.
821 if($check_prior_ids) {
822 if(exists $csa->{_external_seq_region_mapping}->{$seq_region_id}) {
823 my $new_seq_region_id = $csa->{_external_seq_region_mapping}->{$seq_region_id};
824 # No need to pass check prior ids flag because it's a 1 step relationship
825 return $self->fetch_by_seq_region_id($new_seq_region_id, $start, $end, $strand);
826 }
827 }
828 return undef;
829 }
830  
831 ( $name, $cs_id, $length ) = @row;
832 $sth->finish();
833  
834 $cs = $self->db->get_CoordSystemAdaptor->fetch_by_dbID($cs_id);
835  
836 #cache results to speed up repeated queries
837 my $arr = [ $seq_region_id, $name, $cs_id, $length ];
838  
839 $self->{'sr_name_cache'}->{"$name:$cs_id"} = $arr;
840 $self->{'sr_id_cache'}->{"$seq_region_id"} = $arr;
841 }
842  
843 return
844 Bio::EnsEMBL::Slice->new_fast({
845 'coord_system' => $cs,
846 'seq_region_name' => $name,
847 'seq_region_length'=> $length,
848 'start' => $start || 1,
849 'end' => $end || $length,
850 'strand' => $strand || 1,
851 'adaptor' => $self} );
852 } ## end sub fetch_by_seq_region_id
853  
854  
855  
856 =head2 get_seq_region_id
857  
858 Arg [1] : Bio::EnsEMBL::Slice $slice
859 The slice to fetch a seq_region_id for
860 Example : $srid = $slice_adaptor->get_seq_region_id($slice);
861 Description: Retrieves the seq_region id (in this database) given a slice
862 Seq region ids are not stored on the slices themselves
863 because they are intended to be somewhat database independant
864 and seq_region_ids vary accross databases.
865 Returntype : int
866 Exceptions : throw if the seq_region of the slice is not in the db
867 throw if incorrect arg provided
868 Caller : BaseFeatureAdaptor
869 Status : Stable
870  
871 =cut
872  
873 sub get_seq_region_id {
874 my $self = shift;
875 my $slice = shift;
876  
877 if(!$slice || !ref($slice) || !($slice->isa('Bio::EnsEMBL::Slice') or $slice->isa('Bio::EnsEMBL::LRGSlice'))) {
878 throw('Slice argument is required');
879 }
880
881 my $seq_region_name = $slice->seq_region_name();
882 my $key = $seq_region_name.":".$slice->coord_system->dbID();
883 my $arr = $self->{'sr_name_cache'}->{"$key"};
884  
885 if( $arr ) {
886 return $arr->[0];
887 }
888  
889 my $cs_id = $slice->coord_system->dbID();
890  
891 my $sth = $self->prepare("SELECT seq_region_id, length " .
892 "FROM seq_region " .
893 "WHERE name = ? AND coord_system_id = ?");
894  
895 #force seq_region_name cast to string so mysql cannot treat as int
896 $sth->bind_param(1,"$seq_region_name",SQL_VARCHAR);
897 $sth->bind_param(2,$cs_id,SQL_INTEGER);
898 $sth->execute();
899  
900 my @row = $sth->fetchrow_array();
901 unless ( @row ) {
902 throw("No-existent seq_region [$seq_region_name] in coord system [$cs_id]");
903 }
904 my @more = $sth->fetchrow_array();
905 if ( @more ) {
906 throw("Ambiguous seq_region [$seq_region_name] in coord system [$cs_id]");
907 }
908  
909 my($seq_region_id, $length) = @row;
910 $sth->finish();
911  
912 #cache information for future requests
913 $arr = [ $seq_region_id, $seq_region_name, $cs_id, $length ];
914  
915 $self->{'sr_name_cache'}->{"$seq_region_name:$cs_id"} = $arr;
916 $self->{'sr_id_cache'}->{"$seq_region_id"} = $arr;
917  
918 return $seq_region_id;
919 }
920  
921  
922  
923 =head2 fetch_all
924  
925 Arg [1] : string $coord_system_name
926 The name of the coordinate system to retrieve slices of.
927 This may be a name of an acutal coordinate system or an alias
928 to a coordinate system. Valid aliases are 'seqlevel' or
929 'toplevel'.
930 Arg [2] : string $coord_system_version (optional)
931 The version of the coordinate system to retrieve slices of
932 Arg [3] : bool $include_non_reference (optional)
933 If this argument is not provided then only reference slices
934 will be returned. If set, both reference and non reference
935 slices will be returned.
936 Arg [4] : int $include_duplicates (optional)
937 If set duplicate regions will be returned.
938
939 NOTE: if you do not use this option and you have a PAR
940 (pseudo-autosomal region) at the beginning of your seq_region
941 then your slice will not start at position 1, so coordinates
942 retrieved from this slice might not be what you expected.
943  
944 Arg[5] : bool $include_lrg (optional) (default 0)
945 If set lrg regions will be returned aswell.
946  
947  
948 Example : @chromos = @{$slice_adaptor->fetch_all('chromosome','NCBI33')};
949 @contigs = @{$slice_adaptor->fetch_all('contig')};
950  
951 # get even non-reference regions
952 @slices = @{$slice_adaptor->fetch_all('toplevel',undef,1)};
953  
954 # include duplicate regions (such as pseudo autosomal regions)
955 @slices = @{$slice_adaptor->fetch_all('toplevel', undef,0,1)};
956  
957 Description: Retrieves slices of all seq_regions for a given coordinate
958 system. This is analagous to the methods fetch_all which were
959 formerly on the ChromosomeAdaptor, RawContigAdaptor and
960 CloneAdaptor classes. Slices fetched span the entire
961 seq_regions and are on the forward strand.
962 If the coordinate system with the provided name and version
963 does not exist an empty list is returned.
964 If the coordinate system name provided is 'toplevel', all
965 non-redundant toplevel slices are returned (note that any
966 coord_system_version argument is ignored in that case).
967  
968 Retrieved slices can be broken into smaller slices using the
969 Bio::EnsEMBL::Utils::Slice module.
970  
971 Returntype : listref of Bio::EnsEMBL::Slices
972 Exceptions : none
973 Caller : general
974 Status : Stable
975  
976 =cut
977  
978 sub fetch_all {
979 my $self = shift;
980 my $cs_name = shift;
981 my $cs_version = shift || '';
982  
983 my ($include_non_reference, $include_duplicates, $include_lrg) = @_;
984  
985 #
986 # verify existance of requested coord system and get its id
987 #
988 my $csa = $self->db->get_CoordSystemAdaptor();
989 my $orig_cs = $csa->fetch_by_name($cs_name, $cs_version);
990  
991 return [] if ( !$orig_cs );
992  
993 my %bad_vals=();
994  
995  
996 #
997 # Get a hash of non reference seq regions
998 #
999 if ( !$include_non_reference ) {
1000 my $sth =
1001 $self->prepare( 'SELECT sr.seq_region_id '
1002 . 'FROM seq_region sr, seq_region_attrib sra, '
1003 . 'attrib_type at, coord_system cs '
1004 . 'WHERE at.code = "non_ref" '
1005 . 'AND sra.seq_region_id = sr.seq_region_id '
1006 . 'AND at.attrib_type_id = sra.attrib_type_id '
1007 . 'AND sr.coord_system_id = cs.coord_system_id '
1008 . 'AND cs.species_id = ?' );
1009  
1010 $sth->bind_param( 1, $self->species_id(), SQL_INTEGER );
1011 $sth->execute();
1012  
1013 my ($seq_region_id);
1014 $sth->bind_columns( \$seq_region_id );
1015  
1016 while ( $sth->fetch() ) {
1017 $bad_vals{$seq_region_id} = 1;
1018 }
1019 }
1020  
1021 #
1022 # if we do not want lrg's then add them to the bad list;
1023 #
1024 if ( !$include_lrg ) {
1025 my $sth =
1026 $self->prepare( 'SELECT sr.seq_region_id '
1027 . 'FROM seq_region sr, seq_region_attrib sra, '
1028 . 'attrib_type at, coord_system cs '
1029 . 'WHERE at.code = "LRG" '
1030 . 'AND sra.seq_region_id = sr.seq_region_id '
1031 . 'AND at.attrib_type_id = sra.attrib_type_id '
1032 . 'AND sr.coord_system_id = cs.coord_system_id '
1033 . 'AND cs.species_id = ?' );
1034  
1035 $sth->bind_param( 1, $self->species_id(), SQL_INTEGER );
1036 $sth->execute();
1037  
1038 my ($seq_region_id);
1039 $sth->bind_columns( \$seq_region_id );
1040  
1041 while ( $sth->fetch() ) {
1042 $bad_vals{$seq_region_id} = 1;
1043 }
1044 }
1045  
1046 #
1047 # Retrieve the seq_regions from the database
1048 #
1049  
1050 my $sth;
1051 if ( $orig_cs->is_top_level() ) {
1052 $sth =
1053 $self->prepare( 'SELECT sr.seq_region_id, sr.name, '
1054 . 'sr.length, sr.coord_system_id '
1055 . 'FROM seq_region sr, seq_region_attrib sra, '
1056 . 'attrib_type at, coord_system cs '
1057 . 'WHERE at.code = "toplevel" '
1058 . 'AND at.attrib_type_id = sra.attrib_type_id '
1059 . 'AND sra.seq_region_id = sr.seq_region_id '
1060 . 'AND sr.coord_system_id = cs.coord_system_id '
1061 . 'AND cs.species_id = ?' );
1062  
1063 $sth->bind_param( 1, $self->species_id(), SQL_INTEGER );
1064 $sth->execute();
1065 } else {
1066 $sth =
1067 $self->prepare( 'SELECT sr.seq_region_id, sr.name, '
1068 . 'sr.length, sr.coord_system_id '
1069 . 'FROM seq_region sr '
1070 . 'WHERE sr.coord_system_id = ?' );
1071  
1072 $sth->bind_param( 1, $orig_cs->dbID, SQL_INTEGER );
1073 $sth->execute();
1074 }
1075  
1076 my ( $seq_region_id, $name, $length, $cs_id );
1077 $sth->bind_columns( \( $seq_region_id, $name, $length, $cs_id ) );
1078  
1079 my $cache_count = 0;
1080  
1081 my @out;
1082 while($sth->fetch()) {
1083 if(!defined($bad_vals{$seq_region_id})){
1084 my $cs = $csa->fetch_by_dbID($cs_id);
1085  
1086 if(!$cs) {
1087 throw("seq_region $name references non-existent coord_system $cs_id.");
1088 }
1089  
1090 #cache values for future reference, but stop adding to the cache once we
1091 #we know we have filled it up
1092 if($cache_count < $Bio::EnsEMBL::Utils::SeqRegionCache::SEQ_REGION_CACHE_SIZE) {
1093 my $arr = [ $seq_region_id, $name, $cs_id, $length ];
1094  
1095 $self->{'sr_name_cache'}->{"$name:$cs_id"} = $arr;
1096 $self->{'sr_id_cache'}->{"$seq_region_id"} = $arr;
1097  
1098 $cache_count++;
1099 }
1100  
1101 my $slice = Bio::EnsEMBL::Slice->new_fast({
1102 'start' => 1,
1103 'end' => $length,
1104 'strand' => 1,
1105 'seq_region_name' => $name,
1106 'seq_region_length'=> $length,
1107 'coord_system' => $cs,
1108 'adaptor' => $self});
1109  
1110 if(!defined($include_duplicates) or !$include_duplicates){
1111 # test if this slice *could* have a duplicate (exception) region
1112 $self->_build_exception_cache() if(!exists $self->{'asm_exc_cache'});
1113 if(exists $self->{asm_exc_cache}->{$seq_region_id}) {
1114  
1115 # Dereference symlinked assembly regions. Take out
1116 # any regions which are symlinked because these are duplicates
1117 my @projection = @{$self->fetch_normalized_slice_projection($slice)};
1118 foreach my $segment ( @projection) {
1119 if($segment->[2]->seq_region_name() eq $slice->seq_region_name() &&
1120 $segment->[2]->coord_system->equals($slice->coord_system)) {
1121 push @out, $segment->[2];
1122 }
1123 }
1124 } else {
1125 # no duplicate regions
1126 push @out, $slice;
1127 }
1128 } else {
1129 # we want duplicates anyway so do not do any checks
1130 push @out, $slice;
1131 }
1132 }
1133 }
1134  
1135 return \@out;
1136 }
1137  
1138 =head2 fetch_all_by_genome_component
1139  
1140 Arg [1] : string $genome_component_name
1141 The name of the genome component to retrieve slices of.
1142 Example : @slices = @{$slice_adaptor->fetch_all_by_genome_component('A')};
1143 Description: Returns the list of all top level slices for a a given
1144 genome component
1145 Returntype : listref of Bio::EnsEMBL::Slices
1146 Exceptions : If argument is not provided or is not a valid genome
1147 component
1148 Caller : general
1149 Status : Stable
1150  
1151 =cut
1152  
1153 sub fetch_all_by_genome_component {
1154 my $self = shift;
1155 my $genome_component = shift;
1156 defined $genome_component or
1157 throw "Undefined genome component";
1158  
1159 # check the provided genome component is valid
1160 my $gc = $self->db->get_adaptor('GenomeContainer');
1161 my $is_valid_component = grep { $_ eq $genome_component }
1162 @{$gc->get_genome_components};
1163 throw "Invalid genome component"
1164 unless $is_valid_component;
1165
1166 #
1167 # Retrieve the toplevel seq_regions from the database
1168 #
1169 my $sth =
1170 $self->prepare( "SELECT sr.seq_region_id, sr.name, sr.length, sr.coord_system_id "
1171 . "FROM seq_region sr "
1172 . "JOIN seq_region_attrib sa1 USING (seq_region_id) "
1173 . "JOIN attrib_type a1 ON sa1.attrib_type_id = a1.attrib_type_id "
1174 . "JOIN seq_region_attrib sa2 USING (seq_region_id) "
1175 . "JOIN attrib_type a2 ON sa2.attrib_type_id = a2.attrib_type_id "
1176 . "WHERE sa2.value=? and a1.code='toplevel' and a2.code='genome_component'"
1177 );
1178
1179 if (looks_like_number($genome_component)) {
1180 $sth->bind_param( 1, $genome_component, SQL_INTEGER );
1181 } else {
1182 $sth->bind_param( 1, $genome_component, SQL_VARCHAR );
1183 }
1184
1185 $sth->execute();
1186  
1187 my ( $seq_region_id, $name, $length, $cs_id );
1188 $sth->bind_columns( \( $seq_region_id, $name, $length, $cs_id ) );
1189  
1190 my $cache_count = 0;
1191  
1192 my @out;
1193 my $csa = $self->db->get_CoordSystemAdaptor();
1194  
1195 while($sth->fetch()) {
1196 my $cs = $csa->fetch_by_dbID($cs_id);
1197 throw("seq_region $name references non-existent coord_system $cs_id.")
1198 unless $cs;
1199
1200 # cache values for future reference, but stop adding to the cache once we
1201 # we know we have filled it up
1202 if($cache_count < $Bio::EnsEMBL::Utils::SeqRegionCache::SEQ_REGION_CACHE_SIZE) {
1203 my $arr = [ $seq_region_id, $name, $cs_id, $length ];
1204  
1205 $self->{'sr_name_cache'}->{"$name:$cs_id"} = $arr;
1206 $self->{'sr_id_cache'}->{"$seq_region_id"} = $arr;
1207  
1208 $cache_count++;
1209 }
1210  
1211 push @out, Bio::EnsEMBL::Slice->new_fast({
1212 'start' => 1,
1213 'end' => $length,
1214 'strand' => 1,
1215 'seq_region_name' => $name,
1216 'seq_region_length'=> $length,
1217 'coord_system' => $cs,
1218 'adaptor' => $self});
1219 }
1220  
1221 return \@out;
1222 }
1223  
1224 =head2 get_genome_component_for_slice
1225  
1226 Arg [1] : An object of type Bio::EnsEMBL::Slice
1227 Example : my $component = $slice->get_genome_component();
1228 Description: Returns the genome component of a slice
1229 Returntype : Scalar; the identifier of the genome component of the slice
1230 Exceptions : none
1231 Caller : general
1232 Status : Stable
1233  
1234 =cut
1235  
1236 sub get_genome_component_for_slice {
1237 my ($self, $slice) = @_;
1238  
1239 throw "Undefined slice" unless defined $slice;
1240 throw "Argument is not a slice"
1241 unless $slice->isa("Bio::EnsEMBL::Slice");
1242  
1243 my $seq_region_id = $self->get_seq_region_id($slice);
1244  
1245 my $sth =
1246 $self->prepare( "SELECT sa.value "
1247 . "FROM seq_region_attrib sa "
1248 . "JOIN seq_region sr USING (seq_region_id) "
1249 . "JOIN attrib_type at ON sa.attrib_type_id = at.attrib_type_id "
1250 . "WHERE sr.seq_region_id=? AND at.code='genome_component'"
1251 );
1252 $sth->bind_param( 1, $seq_region_id, SQL_INTEGER );
1253 $sth->execute();
1254  
1255 my $genome_component;
1256 $sth->bind_columns( \( $genome_component ) );
1257 $sth->fetch();
1258  
1259 return $genome_component;
1260 }
1261  
1262 =head2 fetch_all_karyotype
1263  
1264 Example : my $top = $slice_adptor->fetch_all_karyotype()
1265 Description: returns the list of all slices which are part of the karyotype
1266 Returntype : listref of Bio::EnsEMBL::Slices
1267 Caller : general
1268 Status : At Risk
1269  
1270 =cut
1271  
1272 sub fetch_all_karyotype {
1273 my $self = shift;
1274  
1275 my $csa = $self->db->get_CoordSystemAdaptor();
1276  
1277 my $sth =
1278 $self->prepare( 'SELECT sr.seq_region_id, sr.name, '
1279 . 'sr.length, sr.coord_system_id, sra.value '
1280 . 'FROM seq_region sr, seq_region_attrib sra, '
1281 . 'attrib_type at, coord_system cs '
1282 . 'WHERE at.code = "karyotype_rank" '
1283 . 'AND at.attrib_type_id = sra.attrib_type_id '
1284 . 'AND sra.seq_region_id = sr.seq_region_id '
1285 . 'AND sr.coord_system_id = cs.coord_system_id '
1286 . 'AND cs.species_id = ?');
1287 $sth->bind_param( 1, $self->species_id(), SQL_INTEGER );
1288 $sth->execute();
1289 my ( $seq_region_id, $name, $length, $cs_id, $rank );
1290 $sth->bind_columns( \( $seq_region_id, $name, $length, $cs_id, $rank ) );
1291  
1292 my @out;
1293 while($sth->fetch()) {
1294 my $cs = $csa->fetch_by_dbID($cs_id);
1295  
1296 my $slice = Bio::EnsEMBL::Slice->new_fast({
1297 'start' => 1,
1298 'end' => ($length+0),
1299 'strand' => 1,
1300 'seq_region_name' => $name,
1301 'seq_region_length'=> ($length+0),
1302 'coord_system' => $cs,
1303 'adaptor' => $self,
1304 'karyotype' => 1,
1305 'karyotype_rank' => ($rank+0),
1306 });
1307  
1308 push @out, $slice;
1309 }
1310  
1311 #Sort using Perl as value in MySQL is a text field and not portable
1312 @out = sort { $a->{karyotype_rank} <=> $b->{karyotype_rank} } @out;
1313  
1314 return \@out;
1315 }
1316  
1317 =head2 is_toplevel
1318 Arg : int seq_region_id
1319 Example : my $top = $slice_adptor->is_toplevel($seq_region_id)
1320 Description: Returns 1 if slice is a toplevel slice else 0
1321 Returntype : int
1322 Caller : Slice method is_toplevel
1323 Status : At Risk
1324  
1325 =cut
1326  
1327 sub is_toplevel {
1328 my $self = shift;
1329 my $id = shift;
1330  
1331 my $sth = $self->prepare(
1332 "SELECT at.code from seq_region_attrib sra, attrib_type at "
1333 . "WHERE sra.seq_region_id = ? "
1334 . "AND at.attrib_type_id = sra.attrib_type_id "
1335 . "AND at.code = 'toplevel'" );
1336  
1337 $sth->bind_param( 1, $id, SQL_INTEGER );
1338 $sth->execute();
1339  
1340 my $code;
1341 $sth->bind_columns( \$code );
1342  
1343 while ( $sth->fetch ) {
1344 $sth->finish;
1345 return 1;
1346 }
1347  
1348 $sth->finish;
1349 return 0;
1350 }
1351  
1352  
1353 =head2 has_karyotype
1354 Arg : int seq_region_id
1355 Example : my $karyotype = $slice_adptor->has_karyotype($seq_region_id)
1356 Description: Returns 1 if slice is a part of a karyotype else 0
1357 Returntype : int
1358 Caller : Slice method has_karyotype
1359 Status : At Risk
1360  
1361 =cut
1362  
1363 sub has_karyotype {
1364 my $self = shift;
1365 my $id = shift;
1366  
1367 my $sth = $self->prepare(
1368 "SELECT at.code from seq_region_attrib sra, attrib_type at "
1369 . "WHERE sra.seq_region_id = ? "
1370 . "AND at.attrib_type_id = sra.attrib_type_id "
1371 . "AND at.code = 'karyotype_rank'" );
1372  
1373 $sth->bind_param( 1, $id, SQL_INTEGER );
1374 $sth->execute();
1375  
1376 my $code;
1377 $sth->bind_columns( \$code );
1378  
1379 while ( $sth->fetch ) {
1380 $sth->finish;
1381 return 1;
1382 }
1383  
1384 $sth->finish;
1385 return 0;
1386 }
1387  
1388 =head2 get_karyotype_rank
1389 Arg : int seq_region_id
1390 Example : my $rank = $slice_adptor->get_karyotype_rank($seq_region_id)
1391 Description: Returns the rank of a slice if it is part of the karyotype else 0
1392 Returntype : int
1393 Caller : Slice method get_karyotype_rank
1394 Status : At Risk
1395  
1396 =cut
1397  
1398 sub get_karyotype_rank {
1399 my $self = shift;
1400 my $id = shift;
1401  
1402 my $sth = $self->prepare(
1403 "SELECT sra.value from seq_region_attrib sra, attrib_type at "
1404 . "WHERE sra.seq_region_id = ? "
1405 . "AND at.attrib_type_id = sra.attrib_type_id "
1406 . "AND at.code = 'karyotype_rank'" );
1407  
1408 $sth->bind_param( 1, $id, SQL_INTEGER );
1409 $sth->execute();
1410  
1411 my $code;
1412 $sth->bind_columns( \$code );
1413  
1414 my $rank = $sth->fetchrow_array();
1415 $sth->finish();
1416  
1417 return $rank;
1418 }
1419  
1420  
1421  
1422 =head2 is_reference
1423 Arg : int seq_region_id
1424 Example : my $reference = $slice_adptor->is_reference($seq_region_id)
1425 Description: Returns 1 if slice is a reference slice else 0
1426 Returntype : int
1427 Caller : Slice method is_reference
1428 Status : At Risk
1429  
1430 =cut
1431  
1432 sub is_reference {
1433 my $self = shift;
1434 my $id = shift;
1435  
1436 my $sth = $self->prepare(
1437 "SELECT at.code from seq_region_attrib sra, attrib_type at "
1438 . "WHERE sra.seq_region_id = ? "
1439 . "AND at.attrib_type_id = sra.attrib_type_id "
1440 . "AND at.code = 'non_ref'" );
1441  
1442 $sth->bind_param( 1, $id, SQL_INTEGER );
1443 $sth->execute();
1444  
1445 my $code;
1446 $sth->bind_columns( \$code );
1447  
1448 while ( $sth->fetch ) {
1449 $sth->finish;
1450 return 0;
1451 }
1452  
1453 $sth->finish;
1454 return 1;
1455 }
1456  
1457 =head2 is_circular
1458  
1459 Arg[1] : int seq_region_id
1460 Example : my $circular = $slice_adptor->is_circular($seq_region_id);
1461 Description : Indicates if the sequence region was circular or not
1462 Returntype : Boolean
1463
1464 =cut
1465  
1466 sub is_circular {
1467 my ($self, $id) = @_;
1468
1469 if (! defined $self->{is_circular}) {
1470 $self->_build_circular_slice_cache();
1471 }
1472
1473 return 0 if $self->{is_circular} == 0;
1474 return (exists $self->{circular_sr_id_cache}->{$id}) ? 1 : 0;
1475 }
1476  
1477  
1478 =head2 fetch_by_chr_band
1479  
1480 Title : fetch_by_chr_band
1481 Usage :
1482 Function: create a Slice representing a series of bands
1483 Example :
1484 Returns : Bio::EnsEMBL::Slice
1485 Args : the band name
1486 Status : Stable
1487  
1488 =cut
1489  
1490 sub fetch_by_chr_band {
1491 my ( $self, $chr, $band ) = @_;
1492  
1493 my $chr_slice = $self->fetch_by_region( 'toplevel', $chr );
1494 my $seq_region_id = $self->get_seq_region_id($chr_slice);
1495  
1496 my $sth =
1497 $self->prepare( 'SELECT MIN(k.seq_region_start), '
1498 . 'MAX(k.seq_region_end) '
1499 . 'FROM karyotype k '
1500 . 'WHERE k.seq_region_id = ? '
1501 . 'AND k.band LIKE ?' );
1502  
1503 $sth->bind_param( 1, $seq_region_id, SQL_INTEGER );
1504 $sth->bind_param( 2, "$band%", SQL_VARCHAR );
1505 $sth->execute();
1506  
1507 my ( $slice_start, $slice_end ) = $sth->fetchrow_array;
1508  
1509 if ( defined $slice_start ) {
1510 return
1511 $self->fetch_by_region( 'toplevel', $chr,
1512 $slice_start, $slice_end );
1513 }
1514  
1515 throw("Band not recognised in database");
1516 } ## end sub fetch_by_chr_band
1517  
1518  
1519  
1520 =head2 fetch_by_exon_stable_id
1521  
1522 Arg [1] : string $exonid
1523 The stable id of the exon around which the slice is
1524 desired
1525 Arg [2] : (optional) int $size
1526 The length of the flanking regions the slice should encompass
1527 on either side of the exon (0 by default)
1528 Example : $slc = $sa->fetch_by_exon_stable_id('ENSE00000302930',10);
1529 Description: Creates a slice around the region of the specified exon.
1530 If a context size is given, the slice is extended by that
1531 number of basepairs on either side of the exon.
1532
1533 The slice will be created in the exon's native coordinate system
1534 and in the forward orientation.
1535 Returntype : Bio::EnsEMBL::Slice
1536 Exceptions : Thrown if the exon is not in the database.
1537 Caller : general
1538 Status : Stable
1539  
1540 =cut
1541  
1542 sub fetch_by_exon_stable_id{
1543 my ($self,$exonid,$size) = @_;
1544  
1545 throw('Exon argument is required.') if(!$exonid);
1546  
1547 my $ea = $self->db->get_ExonAdaptor;
1548 my $exon = $ea->fetch_by_stable_id($exonid);
1549  
1550 throw("Exon [$exonid] does not exist in DB.") if(!$exon);
1551  
1552 return $self->fetch_by_Feature($exon, $size);
1553 }
1554  
1555 =head2 fetch_by_transcript_stable_id
1556  
1557 Arg [1] : string $transcriptid
1558 The stable id of the transcript around which the slice is
1559 desired
1560 Arg [2] : (optional) int $size
1561 The length of the flanking regions the slice should encompass
1562 on either side of the transcript (0 by default)
1563 Example : $slc = $sa->fetch_by_transcript_stable_id('ENST00000302930',10);
1564 Description: Creates a slice around the region of the specified transcript.
1565 If a context size is given, the slice is extended by that
1566 number of basepairs on either side of the
1567 transcript.
1568
1569 The slice will be created in the transcript's native coordinate
1570 system and in the forward orientation.
1571 Returntype : Bio::EnsEMBL::Slice
1572 Exceptions : Thrown if the transcript is not in the database.
1573 Caller : general
1574 Status : Stable
1575  
1576 =cut
1577  
1578 sub fetch_by_transcript_stable_id{
1579 my ($self,$transcriptid,$size) = @_;
1580  
1581 throw('Transcript argument is required.') if(!$transcriptid);
1582  
1583 my $ta = $self->db->get_TranscriptAdaptor;
1584 my $transcript = $ta->fetch_by_stable_id($transcriptid);
1585  
1586 throw("Transcript [$transcriptid] does not exist in DB.") if(!$transcript);
1587  
1588 return $self->fetch_by_Feature($transcript, $size);
1589 }
1590  
1591 =head2 fetch_by_transcript_id
1592  
1593 Arg [1] : int $transcriptid
1594 The unique database identifier of the transcript around which
1595 the slice is desired
1596 Arg [2] : (optional) int $size
1597 The length of the flanking regions the slice should encompass
1598 on either side of the transcript (0 by default)
1599 Example : $slc = $sa->fetch_by_transcript_id(24, 1000);
1600 Description: Creates a slice around the region of the specified transcript.
1601 If a context size is given, the slice is extended by that
1602 number of basepairs on either side of the
1603 transcript.
1604
1605 The slice will be created in the transcript's native coordinate
1606 system and in the forward orientation.
1607 Returntype : Bio::EnsEMBL::Slice
1608 Exceptions : throw on incorrect args
1609 throw if transcript is not in database
1610 Caller : general
1611 Status : Stable
1612  
1613 =cut
1614  
1615 sub fetch_by_transcript_id {
1616 my ($self,$transcriptid,$size) = @_;
1617  
1618 throw('Transcript id argument is required.') if(!$transcriptid);
1619  
1620 my $transcript_adaptor = $self->db()->get_TranscriptAdaptor();
1621 my $transcript = $transcript_adaptor->fetch_by_dbID($transcriptid);
1622  
1623 throw("Transcript [$transcriptid] does not exist in DB.") if(!$transcript);
1624  
1625 return $self->fetch_by_Feature($transcript, $size);
1626 }
1627  
1628  
1629  
1630 =head2 fetch_by_gene_stable_id
1631  
1632 Arg [1] : string $geneid
1633 The stable id of the gene around which the slice is
1634 desired
1635 Arg [2] : (optional) int $size
1636 The length of the flanking regions the slice should encompass
1637 on either side of the gene (0 by default)
1638 Example : $slc = $sa->fetch_by_gene_stable_id('ENSG00000012123',10);
1639 Description: Creates a slice around the region of the specified gene.
1640 If a context size is given, the slice is extended by that
1641 number of basepairs on either side of the gene.
1642
1643 The slice will be created in the gene's native coordinate system
1644 and in the forward orientation.
1645 Returntype : Bio::EnsEMBL::Slice
1646 Exceptions : throw on incorrect args
1647 throw if transcript does not exist
1648 Caller : general
1649 Status : Stable
1650  
1651 =cut
1652  
1653 sub fetch_by_gene_stable_id {
1654 my ($self,$geneid,$size) = @_;
1655  
1656 throw('Gene argument is required.') if(!$geneid);
1657  
1658 my $gene_adaptor = $self->db->get_GeneAdaptor();
1659 my $gene = $gene_adaptor->fetch_by_stable_id($geneid);
1660  
1661 throw("Gene [$geneid] does not exist in DB.") if(!$gene);
1662  
1663 return $self->fetch_by_Feature($gene, $size);
1664 }
1665  
1666  
1667  
1668 =head2 fetch_by_Feature
1669  
1670 Arg [1] : Bio::EnsEMBL::Feature $feat
1671 The feature to fetch the slice around
1672 Arg [2] : int size (optional)
1673 The desired number of flanking basepairs around the feature.
1674 The size may also be provided as a percentage of the feature
1675 size such as 200% or 80.5%.
1676 Example : $slice = $slice_adaptor->fetch_by_Feature($feat, 100);
1677 Description: Retrieves a slice around a specific feature. All this really
1678 does is return a resized version of the slice that the feature
1679 is already on. Note that slices returned from this method
1680 are always on the forward strand of the seq_region regardless of
1681 the strandedness of the feature passed in.
1682 Returntype : Bio::EnsEMBL::Slice
1683 Exceptions : throw if the feature does not have an attached slice
1684 throw if feature argument is not provided
1685 Caller : fetch_by_gene_stable_id, fetch_by_transcript_stable_id,
1686 fetch_by_gene_id, fetch_by_transcript_id
1687 Status : Stable
1688  
1689 =cut
1690  
1691 sub fetch_by_Feature{
1692 my ($self, $feature, $size) = @_;
1693  
1694 $size ||= 0;
1695  
1696 if(!ref($feature) || !$feature->isa('Bio::EnsEMBL::Feature')) {
1697 throw('Feature argument expected.');
1698 }
1699  
1700 my $slice = $feature->slice();
1701 if(!$slice || !($slice->isa('Bio::EnsEMBL::Slice') or $slice->isa('Bio::EnsEMBL::LRGSlice') )) {
1702 throw('Feature must be attached to a valid slice.');
1703 }
1704  
1705  
1706 my $fstart = $feature->start();
1707 my $fend = $feature->end();
1708 if(!defined($fstart) || !defined($fend)) {
1709 throw('Feature must have defined start and end.');
1710 }
1711  
1712 #convert the feature slice coordinates to seq_region coordinates
1713 my $slice_start = $slice->start();
1714 my $slice_end = $slice->end();
1715 my $slice_strand = $slice->strand();
1716 if($slice_start != 1 || $slice_strand != 1) {
1717 if($slice_strand == 1) {
1718 $fstart = $fstart + $slice_start - 1;
1719 $fend = $fend + $slice_start - 1;
1720 } else {
1721 my $tmp_start = $fstart;
1722 $fstart = $slice_end - $fend + 1;
1723 $fend = $slice_end - $tmp_start + 1;
1724 }
1725 }
1726  
1727 ## Size may be stored as a %age of the length of the feature
1728 ## Size = 100% gives no context
1729 ## Size = 200% gives context - 50% the size of the feature either side of
1730 ## feature
1731  
1732 $size = int( ($1-100)/200 * ($fend-$fstart+1) ) if( $size =~/([\d+\.]+)%/ );
1733  
1734 #return a new slice covering the region of the feature
1735 my $S = Bio::EnsEMBL::Slice->new_fast({
1736 'seq_region_name' => $slice->seq_region_name,
1737 'seq_region_length' => $slice->seq_region_length,
1738 'coord_system' => $slice->coord_system,
1739 'start' => $fstart - $size,
1740 'end' => $fend + $size,
1741 'strand' => 1,
1742 'adaptor' => $self});
1743 $S->{'_raw_feature_strand'} = $feature->strand * $slice_strand if $feature->can('strand');
1744 return $S;
1745 }
1746  
1747  
1748  
1749 =head2 fetch_by_misc_feature_attribute
1750  
1751 Arg [1] : string $attribute_type
1752 The code of the attribute type
1753 Arg [2] : (optional) string $attribute_value
1754 The value of the attribute to fetch by
1755 Arg [3] : (optional) int $size
1756 The amount of flanking region around the misc feature desired.
1757 Example : $slice = $sa->fetch_by_misc_feature_attribute('superctg',
1758 'NT_030871');
1759 $slice = $sa->fetch_by_misc_feature_attribute('synonym',
1760 'AL00012311',
1761 $flanking);
1762 Description: Fetches a slice around a MiscFeature with a particular
1763 attribute type and value. If no value is specified then
1764 the feature with the particular attribute is used.
1765 If no size is specified then 0 is used.
1766 Returntype : Bio::EnsEMBL::Slice
1767 Exceptions : Throw if no feature with the specified attribute type and value
1768 exists in the database
1769 Warning if multiple features with the specified attribute type
1770 and value exist in the database.
1771 Caller : webcode
1772 Status : Stable
1773  
1774 =cut
1775  
1776 sub fetch_by_misc_feature_attribute {
1777 my ($self, $attrib_type_code, $attrib_value, $size) = @_;
1778  
1779 my $mfa = $self->db()->get_MiscFeatureAdaptor();
1780  
1781 my $feats = $mfa->fetch_all_by_attribute_type_value($attrib_type_code,
1782 $attrib_value);
1783  
1784 if(@$feats == 0) {
1785 throw("MiscFeature with $attrib_type_code=$attrib_value does " .
1786 "not exist in DB.");
1787 }
1788  
1789 if(@$feats > 1) {
1790 warning("MiscFeature with $attrib_type_code=$attrib_value is " .
1791 "ambiguous - using first one found.");
1792 }
1793  
1794 my ($feat) = @$feats;
1795  
1796 return $self->fetch_by_Feature($feat, $size);
1797 }
1798  
1799 =head2 fetch_by_misc_feature_set
1800  
1801 Arg [1] : string $attribute_type
1802 The code of the attribute type
1803 Arg [2] : (optional) string $attribute_value
1804 The value of the attribute to fetch by
1805 Arg [3] : (optional) the name of the set
1806 Arg [4] : (optional) int $size
1807 The amount of flanking region around the misc feature desired.
1808 Example : $slice = $sa->fetch_by_misc_feature_set('clone',
1809 'RP11-411G9'
1810 'tilepath');
1811 Description: Fetches a slice around a MiscFeature with a particular
1812 attribute type, value and set. If no value is specified then
1813 the feature with the particular attribute is used.
1814 A size can be specified to include flanking region
1815 If no size is specified then 0 is used.
1816 Returntype : Bio::EnsEMBL::Slice
1817 Exceptions : Throw if no feature with the specified attribute type, value and set
1818 exists in the database
1819 Warning if multiple features with the specified attribute type, set
1820 and value exist in the database.
1821 Caller : webcode
1822 Status : Stable
1823  
1824 =cut
1825  
1826 sub fetch_by_misc_feature_set {
1827 my ($self, $attrib_type_code, $attrib_value, $misc_set, $size) = @_;
1828  
1829 my $mfa = $self->db()->get_MiscFeatureAdaptor();
1830  
1831 my $feat = $mfa->fetch_by_attribute_set_value($attrib_type_code,
1832 $attrib_value,
1833 $misc_set);
1834  
1835 return $self->fetch_by_Feature($feat, $size);
1836 }
1837  
1838 =head2 fetch_normalized_slice_projection
1839  
1840 Arg [1] : Bio::EnsEMBL::Slice $slice
1841 Arg [2] : boolean $filter_projections
1842 Optionally filter the projections to remove anything
1843 which is the same sequence region as the given slice
1844 Example : ( optional )
1845 Description: gives back a project style result. The returned slices
1846 represent the areas to which there are symlinks for the
1847 given slice. start, end show which area on given slice is
1848 symlinked
1849 Returntype : [[start,end,$slice][]]
1850 Exceptions : none
1851 Caller : BaseFeatureAdaptor
1852 Status : Stable
1853  
1854 =cut
1855  
1856  
1857 sub fetch_normalized_slice_projection {
1858 my $self = shift;
1859 my $slice = shift;
1860 my $filter_projections = shift;
1861  
1862 my $slice_seq_region_id = $self->get_seq_region_id( $slice );
1863  
1864 $self->_build_exception_cache() if(!exists($self->{'asm_exc_cache'}));
1865  
1866 my $result = $self->{'asm_exc_cache'}->{$slice_seq_region_id};
1867  
1868 $result ||= [];
1869  
1870 my (@haps, @pars);
1871  
1872 foreach my $row (@$result) {
1873 my ( $seq_region_id, $seq_region_start, $seq_region_end,
1874 $exc_type, $exc_seq_region_id, $exc_seq_region_start,
1875 $exc_seq_region_end ) = @$row;
1876  
1877 # need overlapping PAR and all HAPs if any
1878 if( $exc_type eq "PAR" ) {
1879 if( $seq_region_start <= $slice->end() &&
1880 $seq_region_end >= $slice->start() ) {
1881 push( @pars, [ $seq_region_start, $seq_region_end, $exc_seq_region_id,
1882 $exc_seq_region_start, $exc_seq_region_end ] );
1883 }
1884 } else {
1885 push( @haps, [ $seq_region_start, $seq_region_end, $exc_seq_region_id,
1886 $exc_seq_region_start, $exc_seq_region_end ] );
1887 }
1888 }
1889  
1890 if(!@pars && !@haps) {
1891 #just return this slice, there were no haps or pars
1892 return [bless ( [1,$slice->length, $slice], "Bio::EnsEMBL::ProjectionSegment")];
1893 }
1894  
1895 my @syms;
1896 if( @haps >= 1 ) {
1897 my @sort_haps = sort { $a->[1] <=> $b->[1] } @haps;
1898  
1899 my $count =0;
1900 my $chr_start = 1;
1901 my $hap_start = 1;
1902 my $last = 0;
1903  
1904 my $seq_region_slice = $self->fetch_by_seq_region_id($slice_seq_region_id);
1905 my $exc_slice = $self->fetch_by_seq_region_id( $sort_haps[0][2] );
1906 my $len1 = $seq_region_slice->length();
1907 my $len2 = $exc_slice->length();
1908 my $max_len = ($len1 > $len2) ? $len1 : $len2;
1909  
1910 while($count <= scalar(@sort_haps) and !$last){
1911 my $chr_end;
1912 my $hap_end;
1913 if(defined($sort_haps[$count]) and defined($sort_haps[$count][0]) ){
1914 $hap_end = $sort_haps[$count][0]-1;
1915 $chr_end = $sort_haps[$count][3]-1
1916 }
1917 else{
1918 $last = 1;
1919 $hap_end = $len1;
1920 $chr_end = $len2;
1921 my $diff = ($hap_end-$hap_start)-($chr_end-$chr_start);
1922 if($diff > 0){
1923 push( @syms, [ $hap_start, $hap_end, $sort_haps[0][2], $chr_start, $chr_end+$diff] );
1924 }
1925 elsif($diff < 0){
1926 push( @syms, [ $hap_start, $hap_end - $diff, $sort_haps[0][2], $chr_start, $chr_end] );
1927 }
1928 else{
1929 push( @syms, [ $hap_start, $hap_end, $sort_haps[0][2], $chr_start, $chr_end] );
1930 }
1931 next;
1932 }
1933 if($hap_end and $hap_start < $len1){ # if hap at start or end of chromosome
1934 push( @syms, [ $hap_start, $hap_end, $sort_haps[0][2], $chr_start, $chr_end] );
1935 }
1936 $chr_start = $chr_end + ($sort_haps[$count][4]-$sort_haps[$count][3]) + 2;
1937 $hap_start = $hap_end + ($sort_haps[$count][1]-$sort_haps[$count][0]) + 2;
1938 $count++;
1939 }
1940  
1941  
1942 }
1943  
1944  
1945 # for now haps and pars should not be both there, but in theory we
1946 # could handle it here by cleverly merging the pars into the existing syms,
1947 # for now just:
1948 push( @syms, @pars );
1949  
1950 my $mapper = Bio::EnsEMBL::Mapper->new( "sym", "org" );
1951 my $count = 0;
1952 for my $sym ( @syms ) {
1953 $mapper->add_map_coordinates( $slice_seq_region_id, $sym->[0], $sym->[1],
1954 1, $sym->[2], $sym->[3], $sym->[4] );
1955 }
1956  
1957 my @linked = $mapper->map_coordinates( $slice_seq_region_id,
1958 $slice->start(), $slice->end(),
1959 $slice->strand(), "sym" );
1960  
1961 # gaps are regions where there is no mapping to another region
1962 my $rel_start = 1;
1963  
1964 #if there was only one coord and it is a gap, we know it is just the
1965 #same slice with no overlapping symlinks
1966 if(@linked == 1 && $linked[0]->isa('Bio::EnsEMBL::Mapper::Gap')) {
1967 return [bless( [1,$slice->length, $slice], "Bio::EnsEMBL::ProjectionSegment" )];
1968 }
1969  
1970 my @out;
1971 for my $coord ( @linked ) {
1972 if( $coord->isa( "Bio::EnsEMBL::Mapper::Gap" )) {
1973 my $exc_slice = Bio::EnsEMBL::Slice->new_fast({
1974 'start' => $coord->start(),
1975 'end' => $coord->end(),
1976 'strand' => $slice->strand(),
1977 'coord_system' => $slice->coord_system(),
1978 'adaptor' => $self,
1979 'seq_region_name' => $slice->seq_region_name(),
1980 'seq_region_length' => $slice->seq_region_length()});
1981 push( @out, bless ( [ $rel_start, $coord->length()+$rel_start-1,
1982 $exc_slice ], "Bio::EnsEMBL::ProjectionSegment") );
1983 } else {
1984 my $exc_slice = $self->fetch_by_seq_region_id( $coord->id() );
1985 my $exc2_slice = Bio::EnsEMBL::Slice->new_fast({
1986
1987 'start' => $coord->start(),
1988 'end' => $coord->end(),
1989 'strand' => $coord->strand(),
1990 'seq_region_name' => $exc_slice->seq_region_name(),
1991 'seq_region_length' => $exc_slice->seq_region_length(),
1992 'coord_system' => $exc_slice->coord_system(),
1993 'adaptor' => $self
1994 });
1995
1996 push( @out, bless( [ $rel_start, $coord->length() + $rel_start - 1,
1997 $exc2_slice ], "Bio::EnsEMBL::ProjectionSegment") );
1998 }
1999 $rel_start += $coord->length();
2000 }
2001
2002 if($filter_projections) {
2003 return $self->_filter_Slice_projections($slice, \@out);
2004 }
2005 return \@out;
2006 }
2007  
2008 =head2 _filter_Slice_projections
2009  
2010 Arg [1] : Bio::EnsEMBL::Slice The slice the projections were made from
2011 Arg [2] : Array The projections which were fetched from the previous slice
2012 Description : Removes any projections which occur within the same sequence
2013 region as the given Slice object
2014 Returntype : ArrayRef Bio::EnsEMBL::ProjectionSegment; Returns an array
2015 of projected segments
2016 =cut
2017  
2018 sub _filter_Slice_projections {
2019 my ($self, $slice, $projections) = @_;
2020 my @proj = @{ $projections };
2021 if ( !@proj ) {
2022 throw('Was not given any projections to filter. Database may have incorrect assembly_exception information loaded');
2023 }
2024
2025 # Want to get features on the FULL original slice as well as any
2026 # symlinked slices.
2027
2028 # Filter out partial slices from projection that are on same
2029 # seq_region as original slice.
2030  
2031 my $sr_id = $slice->get_seq_region_id();
2032  
2033 @proj = grep { $_->to_Slice->get_seq_region_id() != $sr_id } @proj;
2034  
2035 my $segment = bless( [ 1, $slice->length(), $slice ],
2036 'Bio::EnsEMBL::ProjectionSegment' );
2037 push( @proj, $segment );
2038 return \@proj;
2039 }
2040  
2041  
2042 =head2 store
2043  
2044 Arg [1] : Bio::EnsEMBL::Slice $slice
2045 Arg [2] : (optional) $seqref reference to a string
2046 The sequence associated with the slice to be stored.
2047 Example : $slice = Bio::EnsEMBL::Slice->new(...);
2048 $seq_region_id = $slice_adaptor->store($slice, \$sequence);
2049 Description: This stores a slice as a sequence region in the database
2050 and returns the seq region id. The passed in slice must
2051 start at 1, and must have a valid seq_region name and coordinate
2052 system. The attached coordinate system must already be stored in
2053 the database. The sequence region is assumed to start at 1 and
2054 to have a length equalling the length of the slice. The end of
2055 the slice must equal the seq_region_length.
2056 If the slice coordinate system is the sequence level coordinate
2057 system then the seqref argument must also be passed. If the
2058 slice coordinate system is NOT a sequence level coordinate
2059 system then the sequence argument cannot be passed.
2060 Returntype : int
2061 Exceptions : throw if slice has no coord system.
2062 throw if slice coord system is not already stored.
2063 throw if slice coord system is seqlevel and no sequence is
2064 provided.
2065 throw if slice coord system is not seqlevel and sequence is
2066 provided.
2067 throw if slice does not start at 1
2068 throw if sequence is provided and the sequence length does not
2069 match the slice length.
2070 throw if the SQL insert fails (e.g. on duplicate seq region)
2071 throw if slice argument is not passed
2072 throw if the slice end is not equal to seq_region_length
2073 Caller : database loading scripts
2074 Status : Stable
2075  
2076 =cut
2077  
2078  
2079  
2080 sub store {
2081 my $self = shift;
2082 my $slice = shift;
2083 my $seqref = shift;
2084 my $not_dna = shift;
2085  
2086 #
2087 # Get all of the sanity checks out of the way before storing anything
2088 #
2089  
2090 if(!ref($slice) || !($slice->isa('Bio::EnsEMBL::Slice') or $slice->isa('Bio::EnsEMBL::LRGSlice'))) {
2091 throw('Slice argument is required');
2092 }
2093  
2094 my $cs = $slice->coord_system();
2095 throw("Slice must have attached CoordSystem.") if(!$cs);
2096  
2097 my $db = $self->db();
2098 if(!$cs->is_stored($db)) {
2099 throw("Slice CoordSystem must already be stored in DB.")
2100 }
2101  
2102 if($slice->start != 1 || $slice->strand != 1) {
2103 throw("Slice must have start==1 and strand==1.");
2104 }
2105  
2106 if($slice->end() != $slice->seq_region_length()) {
2107 throw("Slice must have end==seq_region_length");
2108 }
2109  
2110 my $sr_len = $slice->length();
2111 my $sr_name = $slice->seq_region_name();
2112  
2113 if($sr_name eq '') {
2114 throw("Slice must have valid seq region name.");
2115 }
2116  
2117 if($cs->is_sequence_level() && !$not_dna) {
2118 if(!$seqref) {
2119 throw("Must provide sequence for sequence level coord system.");
2120 }
2121 if(ref($seqref) ne 'SCALAR') {
2122 throw("Sequence must be a scalar reference.");
2123 }
2124 my $seq_len = length($$seqref);
2125  
2126 if($seq_len != $sr_len) {
2127 throw("Sequence length ($seq_len) must match slice length ($sr_len).");
2128 }
2129 } else {
2130 if($seqref) {
2131 throw("Cannot provide sequence for non-sequence level seq regions.");
2132 }
2133 }
2134  
2135 #store the seq_region
2136  
2137 my $sth = $db->dbc->prepare("INSERT INTO seq_region " .
2138 " ( name, length, coord_system_id ) " .
2139 " VALUES ( ?, ?, ? )"
2140 );
2141  
2142 $sth->bind_param(1,$sr_name,SQL_VARCHAR);
2143 $sth->bind_param(2,$sr_len,SQL_INTEGER);
2144 $sth->bind_param(3,$cs->dbID,SQL_INTEGER);
2145  
2146 $sth->execute();
2147  
2148 my $seq_region_id = $self->last_insert_id('seq_region_id', undef, 'seq_region');
2149  
2150 if(!$seq_region_id) {
2151 throw("Database seq_region insertion failed.");
2152 }
2153  
2154 if($cs->is_sequence_level() && !$not_dna) {
2155 #store sequence if it was provided
2156 my $seq_adaptor = $db->get_SequenceAdaptor();
2157 $seq_adaptor->store($seq_region_id, $$seqref);
2158 }
2159  
2160 #synonyms
2161 if(defined($slice->{'synonym'})){
2162 foreach my $syn (@{$slice->{'synonym'}} ){
2163 $syn->seq_region_id($seq_region_id); # set the seq_region_id
2164 $syn->adaptor->store($syn);
2165 }
2166 }
2167
2168
2169 $slice->adaptor($self);
2170  
2171 return $seq_region_id;
2172 }
2173  
2174  
2175 sub update {
2176 my $self = shift;
2177 my $slice = shift;
2178  
2179 #
2180 # Get all of the sanity checks out of the way before storing anything
2181 #
2182  
2183 if(!ref($slice) || !($slice->isa('Bio::EnsEMBL::Slice') or $slice->isa('Bio::EnsEMBL::LRGSlice'))) {
2184 throw('Slice argument is required');
2185 }
2186  
2187 my $cs = $slice->coord_system();
2188 throw("Slice must have attached CoordSystem.") if(!$cs);
2189  
2190 my $db = $self->db();
2191  
2192 if($slice->start != 1 || $slice->strand != 1) {
2193 throw("Slice must have start==1 and strand==1.");
2194 }
2195  
2196 if($slice->end() != $slice->seq_region_length()) {
2197 throw("Slice must have end==seq_region_length");
2198 }
2199  
2200 my $sr_len = $slice->length();
2201 my $sr_name = $slice->seq_region_name();
2202  
2203 if(!$sr_name) {
2204 throw("Slice must have valid seq region name.");
2205 }
2206  
2207 #update the seq_region
2208  
2209 my $seq_region_id = $slice->get_seq_region_id();
2210 my $update_sql = qq(
2211 UPDATE seq_region
2212 SET name = ?,
2213 length = ?,
2214 coord_system_id = ?
2215 WHERE seq_region_id = ?
2216 );
2217  
2218 my $sth = $db->dbc->prepare($update_sql);
2219  
2220 $sth->bind_param(1,$sr_name,SQL_VARCHAR);
2221 $sth->bind_param(2,$sr_len,SQL_INTEGER);
2222 $sth->bind_param(3,$cs->dbID,SQL_INTEGER);
2223  
2224 $sth->bind_param(4, $seq_region_id, SQL_INTEGER);
2225  
2226 $sth->execute();
2227  
2228 #synonyms
2229 if(defined($slice->{'synonym'})){
2230 foreach my $syn (@{$slice->{'synonym'}} ){
2231 $syn->seq_region_id($seq_region_id); # set the seq_region_id
2232 my $syn_adaptor = $db->get_SeqRegionSynonymAdaptor();
2233 $syn_adaptor->store($syn);
2234 }
2235 }
2236 }
2237  
2238 =head2 remove
2239  
2240 Arg [1] : Bio::EnsEMBL::Slice $slice
2241 The slice to remove from the database
2242 Example : $slice_adaptor->remove($slice);
2243 Description: Removes a slice completely from the database.
2244 All associated seq_region_attrib are removed as well.
2245 If dna is attached to the slice, it is also removed.
2246 Returntype : none
2247 Exceptions : throw if slice has no coord system.
2248 throw if slice argument is not passed
2249 warning if slice is not stored in this database
2250 Caller : general
2251 Status : Stable
2252  
2253 =cut
2254  
2255  
2256 sub remove {
2257 my $self = shift;
2258 my $slice = shift;
2259  
2260 #
2261 # Get all of the sanity checks out of the way before storing anything
2262 #
2263  
2264 if(!ref($slice) || !($slice->isa('Bio::EnsEMBL::Slice') or $slice->isa('Bio::EnsEMBL::LRGSlice'))) {
2265 throw('Slice argument is required');
2266 }
2267  
2268 my $cs = $slice->coord_system();
2269 throw("Slice must have attached CoordSystem.") if(!$cs);
2270  
2271 my $db = $self->db();
2272 my $seq_region_id = $slice->get_seq_region_id();
2273  
2274 if ($cs->is_sequence_level()) {
2275 my $seq_adaptor = $db->get_SequenceAdaptor();
2276 $seq_adaptor->remove($seq_region_id);
2277 }
2278  
2279 if(defined($slice->{'synonym'})){
2280 foreach my $syn (@{$slice->{'synonym'}} ){
2281 $syn->seq_region_id($seq_region_id); # set the seq_region_id
2282 $syn->adaptor->remove($syn);
2283 }
2284 }
2285  
2286 my $attrib_adaptor = $self->db->get_AttributeAdaptor();
2287 $attrib_adaptor->remove_from_Slice($slice);
2288 $self->remove_assembly($slice);
2289  
2290 my $sr_name = $slice->seq_region_name();
2291  
2292 #remove the seq_region
2293  
2294 my $sth = $db->dbc->prepare("DELETE FROM seq_region " .
2295 "WHERE name = ? AND " .
2296 " coord_system_id = ?" );
2297  
2298 $sth->bind_param(1,$sr_name,SQL_VARCHAR);
2299 $sth->bind_param(2,$cs->dbID,SQL_INTEGER);
2300  
2301 $sth->execute();
2302  
2303 return;
2304 }
2305  
2306  
2307 =head2 remove_assembly
2308  
2309 Arg [1] : Bio::EnsEMBL::Slice $asm_slice or $cmp_slice
2310 Example : $slice_adaptor->remove_assembly( $slice );
2311 Description: Deletes from the assembly table
2312 where asm or cmp corresponds to slice
2313 Do not call this method unless you really know what you are doing
2314 Returntype : none
2315 Exceptions : throw if slice has no coord system (cs).
2316 throw if no slice provided, or argument is not a slice
2317 Caller : Internal
2318 Status : Experimental
2319  
2320 =cut
2321  
2322  
2323 sub remove_assembly {
2324 my $self = shift;
2325 my $slice = shift;
2326  
2327 if(!ref($slice) || !($slice->isa('Bio::EnsEMBL::Slice') or $slice->isa('Bio::EnsEMBL::LRGSlice'))) {
2328 throw('Slice argument is required');
2329 }
2330  
2331 my $cs = $slice->coord_system();
2332 throw("Slice must have attached CoordSystem.") if(!$cs);
2333  
2334 #
2335 # Checks complete. Delete the data
2336 #
2337 my $sth = $self->db->dbc->prepare
2338 ("DELETE FROM assembly " .
2339 "WHERE asm_seq_region_id = ? OR " .
2340 " cmp_seq_region_id = ? ");
2341  
2342 my $asm_seq_region_id = $self->get_seq_region_id( $slice );
2343 my $cmp_seq_region_id = $self->get_seq_region_id( $slice );
2344  
2345 $sth->bind_param(1,$asm_seq_region_id,SQL_INTEGER);
2346 $sth->bind_param(2,$cmp_seq_region_id,SQL_INTEGER);
2347  
2348 $sth->execute();
2349 $sth->finish();
2350  
2351 return;
2352  
2353 }
2354  
2355 =head2 fetch_assembly
2356  
2357 Arg [1] : Bio::EnsEMBL::Slice $asm_slice
2358 Arg [2] : Bio::EnsEMBL::Slice $cmp_slice
2359 Example : $asm = $slice_adaptor->fetch_assembly( $slice1, $slice2 );
2360 Description: Fetches from the assembly table based on the
2361 coordinates of the two slices supplied.
2362 Returns a mapper object mapping the two slices
2363 Do not call this method unless you really know what you are doing
2364 Returntype : Bio::EnsEMBL::Mapper
2365 Exceptions : throw if either slice has no coord system (cs).
2366 throw if there is no mapping path between coord systems
2367 throw if there are existing mappings between either slice
2368 and the oposite cs
2369 Caller : Internal
2370 Status : Experimental
2371  
2372 =cut
2373  
2374  
2375 sub fetch_assembly {
2376 my $self = shift;
2377 my $asm_slice = shift;
2378 my $cmp_slice = shift;
2379  
2380 if(!ref($asm_slice) || !($asm_slice->isa('Bio::EnsEMBL::Slice') or $asm_slice->isa('Bio::EnsEMBL::LRGSlice'))) {
2381 throw('Assembled Slice argument is required');
2382 }
2383 if(!ref($cmp_slice) || !($cmp_slice->isa('Bio::EnsEMBL::Slice') or $cmp_slice->isa('Bio::EnsEMBL::LRGSlice')) ) {
2384 throw('Assembled Slice argument is required');
2385 }
2386  
2387 my $asm_cs = $asm_slice->coord_system();
2388 throw("Slice must have attached CoordSystem.") if(!$asm_cs);
2389 my $cmp_cs = $cmp_slice->coord_system();
2390 throw("Slice must have attached CoordSystem.") if(!$cmp_cs);
2391  
2392 my @path =
2393 @{ $asm_cs->adaptor()->get_mapping_path( $asm_cs, $cmp_cs ) };
2394  
2395 if ( !@path ) {
2396 throw("No mapping path defined between "
2397 . $asm_cs->name() . " and "
2398 . $cmp_cs->name() );
2399 }
2400  
2401 #
2402 # Checks complete. Fetch the data
2403 #
2404 my $sth = $self->db->dbc->prepare
2405 ("SELECT * FROM assembly " .
2406 "WHERE asm_seq_region_id = ? AND " .
2407 " cmp_seq_region_id = ? AND " .
2408 " asm_start = ? AND " .
2409 " asm_end = ? AND " .
2410 " cmp_start = ? AND " .
2411 " cmp_end = ? AND " .
2412 " ori = ?" );
2413  
2414 my $asm_seq_region_id = $self->get_seq_region_id( $asm_slice );
2415 my $cmp_seq_region_id = $self->get_seq_region_id( $cmp_slice );
2416 my $ori = $asm_slice->strand * $cmp_slice->strand;
2417  
2418 $sth->bind_param(1,$asm_seq_region_id,SQL_INTEGER);
2419 $sth->bind_param(2,$cmp_seq_region_id,SQL_INTEGER);
2420 $sth->bind_param(3,$asm_slice->start,SQL_INTEGER);
2421 $sth->bind_param(4,$asm_slice->end,SQL_INTEGER);
2422 $sth->bind_param(5,$cmp_slice->start,SQL_INTEGER);
2423 $sth->bind_param(6,$cmp_slice->end,SQL_INTEGER);
2424 $sth->bind_param(7,$ori,SQL_INTEGER);
2425  
2426 $sth->execute();
2427  
2428 my $results = $sth->fetchrow_array();
2429 $sth->finish();
2430  
2431 my $mapper;
2432 if ($results) {
2433 $mapper = Bio::EnsEMBL::Mapper->new($asm_slice, $cmp_slice, $asm_cs, $cmp_cs);
2434 }
2435  
2436 return $mapper;
2437  
2438 }
2439  
2440 =head2 store_assembly
2441  
2442 Arg [1] : Bio::EnsEMBL::Slice $asm_slice
2443 Arg [2] : Bio::EnsEMBL::Slice $cmp_slice
2444 Example : $asm = $slice_adaptor->store_assembly( $slice1, $slice2 );
2445 Description: Creates an entry in the assembly table based on the
2446 coordinates of the two slices supplied. Returns a string
2447 representation of the assembly that gets created.
2448 Returntype : string
2449 Exceptions : throw if either slice has no coord system (cs).
2450 throw unless the cs rank of the asm_slice is lower than the
2451 cmp_slice.
2452 throw if there is no mapping path between coord systems
2453 throw if the lengths of each slice are not equal
2454 throw if there are existing mappings between either slice
2455 and the oposite cs
2456 Caller : database loading scripts
2457 Status : Experimental
2458  
2459 =cut
2460  
2461 sub store_assembly{
2462 my $self = shift;
2463 my $asm_slice = shift;
2464 my $cmp_slice = shift;
2465  
2466 #
2467 # Get all of the sanity checks out of the way before storing anything
2468 #
2469  
2470 if(!ref($asm_slice) || !($asm_slice->isa('Bio::EnsEMBL::Slice') or $asm_slice->isa('Bio::EnsEMBL::LRGSlice'))) {
2471 throw('Assembled Slice argument is required');
2472 }
2473 if(!ref($cmp_slice) || !($cmp_slice->isa('Bio::EnsEMBL::Slice') or $cmp_slice->isa('Bio::EnsEMBL::LRGSlice')) ) {
2474 throw('Assembled Slice argument is required');
2475 }
2476  
2477 my $asm_cs = $asm_slice->coord_system();
2478 throw("Slice must have attached CoordSystem.") if(!$asm_cs);
2479 my $cmp_cs = $cmp_slice->coord_system();
2480 throw("Slice must have attached CoordSystem.") if(!$cmp_cs);
2481  
2482 my @path =
2483 @{ $asm_cs->adaptor()->get_mapping_path( $asm_cs, $cmp_cs ) };
2484  
2485 if ( !@path ) {
2486 throw("No mapping path defined between "
2487 . $asm_cs->name() . " and "
2488 . $cmp_cs->name() );
2489 }
2490  
2491 if( $asm_slice->length != $cmp_slice->length ){
2492 throw("The lengths of the assembled and component slices are not equal" );
2493 }
2494  
2495 # For now we disallow any existing mappings between the asm slice and cmp
2496 # CoordSystem and vice-versa.
2497 # Some cases of multiple mappings may be allowable by the API, but their
2498 # logic needs to be coded below.
2499  
2500 my $asm_proj = $asm_slice->project( $cmp_cs->name, $cmp_cs->version );
2501 if( @$asm_proj && $cmp_cs->name ne 'lrg' && $asm_cs->name ne 'lrg'){
2502 throw("Regions of the assembled slice are already assembled ".
2503 "into the component CoordSystem" );
2504 }
2505 my $cmp_proj = $cmp_slice->project( $asm_cs->name, $asm_cs->version );
2506 if( @$cmp_proj && $cmp_cs->name ne 'lrg' && $asm_cs->name ne 'lrg'){
2507 throw("Regions of the component slice are already assembled ".
2508 "into the assembled CoordSystem" );
2509 }
2510  
2511 #
2512 # Checks complete. Store the data
2513 #
2514 my $sth = $self->db->dbc->prepare
2515 ("INSERT INTO assembly " .
2516 " ( asm_seq_region_id, " .
2517 " cmp_seq_region_id, " .
2518 " asm_start, " .
2519 " asm_end , " .
2520 " cmp_start, " .
2521 " cmp_end , " .
2522 " ori )" .
2523 "VALUES ( ?, ?, ?, ?, ?, ?, ? )");
2524  
2525 my $asm_seq_region_id = $self->get_seq_region_id( $asm_slice );
2526 my $cmp_seq_region_id = $self->get_seq_region_id( $cmp_slice );
2527 my $ori = $asm_slice->strand * $cmp_slice->strand;
2528  
2529 $sth->bind_param(1,$asm_seq_region_id,SQL_INTEGER);
2530 $sth->bind_param(2,$cmp_seq_region_id,SQL_INTEGER);
2531 $sth->bind_param(3,$asm_slice->start,SQL_INTEGER);
2532 $sth->bind_param(4,$asm_slice->end,SQL_INTEGER);
2533 $sth->bind_param(5,$cmp_slice->start,SQL_INTEGER);
2534 $sth->bind_param(6,$cmp_slice->end,SQL_INTEGER);
2535 $sth->bind_param(7,$ori,SQL_INTEGER);
2536  
2537 $sth->execute();
2538  
2539 #use Data::Dumper qw( Dumper );
2540 #warn Dumper( $self->db->{seq_region_cache} );
2541 #$self->db->{seq_region_cache} = undef;
2542 #$self->_cache_seq_regions();
2543  
2544 my $ama = $self->db->get_AssemblyMapperAdaptor();
2545 $ama->delete_cache();
2546  
2547  
2548 return $asm_slice->name . "<>" . $cmp_slice->name;
2549  
2550 }
2551  
2552  
2553 =head2 prepare
2554  
2555 Arg [1] : String $sql
2556 Example : ( optional )
2557 Description: overrides the default adaptor prepare method.
2558 All slice sql will usually use the dna_db.
2559 Returntype : DBD::sth
2560 Exceptions : none
2561 Caller : internal, convenience method
2562 Status : Stable
2563  
2564 =cut
2565  
2566 sub prepare {
2567 my ( $self, $sql ) = @_;
2568 return $self->db()->dnadb()->dbc->prepare($sql);
2569 }
2570  
2571 sub _build_exception_cache {
2572 my $self = shift;
2573  
2574 # build up a cache of the entire assembly exception table
2575 # it should be small anyway
2576 my $sth =
2577 $self->prepare( 'SELECT ae.seq_region_id, ae.seq_region_start, '
2578 . 'ae.seq_region_end, ae.exc_type, ae.exc_seq_region_id, '
2579 . 'ae.exc_seq_region_start, ae.exc_seq_region_end '
2580 . 'FROM assembly_exception ae, '
2581 . 'seq_region sr, coord_system cs '
2582 . 'WHERE sr.seq_region_id = ae.seq_region_id '
2583 . 'AND sr.coord_system_id = cs.coord_system_id '
2584 . 'AND cs.species_id = ?' );
2585  
2586 $sth->bind_param( 1, $self->species_id(), SQL_INTEGER );
2587 $sth->execute();
2588  
2589 my %hash;
2590 $self->{'asm_exc_cache'} = \%hash;
2591  
2592 my $row;
2593 while ( $row = $sth->fetchrow_arrayref() ) {
2594 my @result = @$row;
2595 $hash{ $result[0] } ||= [];
2596 push( @{ $hash{ $result[0] } }, \@result );
2597 }
2598 $sth->finish();
2599 } ## end sub _build_exception_cache
2600  
2601 =head2 cache_toplevel_seq_mappings
2602  
2603 Args : none
2604 Example : $slice_adaptor->cache_toplevel_seq_mappings();
2605 Description: caches all the assembly mappings needed for genes
2606 Returntype : None
2607 Exceptions : None
2608 Caller : general
2609 Status : At Risk
2610 : New experimental code
2611  
2612 =cut
2613  
2614 sub cache_toplevel_seq_mappings {
2615 my ($self) = @_;
2616  
2617 # Get the sequence level to map too
2618  
2619 my $sql = (<<SSQL);
2620 SELECT name
2621 FROM coord_system
2622 WHERE attrib like "%sequence_level%"
2623 AND species_id = ?
2624 SSQL
2625  
2626 my $sth = $self->prepare($sql);
2627 $sth->bind_param( 1, $self->species_id(), SQL_INTEGER );
2628 $sth->execute();
2629  
2630 my $sequence_level = $sth->fetchrow_array();
2631  
2632 $sth->finish();
2633  
2634 my $csa = $self->db->get_CoordSystemAdaptor();
2635 my $ama = $self->db->get_AssemblyMapperAdaptor();
2636  
2637 my $cs1 = $csa->fetch_by_name($sequence_level);
2638  
2639 #get level to map too.
2640  
2641 $sql = (<<LSQL);
2642 SELECT DISTINCT(cs.name)
2643 FROM seq_region sr,
2644 seq_region_attrib sra,
2645 attrib_type at,
2646 coord_system cs
2647 WHERE sra.seq_region_id = sr.seq_region_id
2648 AND sra.attrib_type_id = at.attrib_type_id
2649 AND at.code = "toplevel"
2650 AND cs.coord_system_id = sr.coord_system_id
2651 AND cs.species_id = ?
2652 LSQL
2653  
2654 $sth = $self->prepare($sql);
2655 $sth->bind_param( 1, $self->species_id(), SQL_INTEGER );
2656 $sth->execute();
2657  
2658 while ( my $csn = $sth->fetchrow_array() ) {
2659 if ( $csn eq $sequence_level ) { next }
2660 my $cs2 = $csa->fetch_by_name($csn);
2661 my $am = $ama->fetch_by_CoordSystems( $cs1, $cs2 );
2662 $am->register_all();
2663 }
2664  
2665 } ## end sub cache_toplevel_seq_mappings
2666  
2667  
2668 sub _build_circular_slice_cache {
2669 my $self = shift;
2670  
2671 # build up a cache of circular sequence region ids
2672 my $sth =
2673 $self->prepare( "SELECT sra.seq_region_id FROM seq_region_attrib sra "
2674 . "INNER JOIN attrib_type at ON sra.attrib_type_id = at.attrib_type_id "
2675 . "INNER JOIN seq_region sr ON sra.seq_region_id = sr.seq_region_id "
2676 . "INNER JOIN coord_system cs ON sr.coord_system_id = cs.coord_system_id "
2677 . "WHERE code = 'circular_seq' and cs.species_id = ?");
2678  
2679 $sth->bind_param( 1, $self->species_id(), SQL_INTEGER );
2680 $sth->execute();
2681  
2682 my $id;
2683 my %hash;
2684 if ( ($id) = $sth->fetchrow_array() ) {
2685 $self->{'circular_sr_id_cache'} = \%hash;
2686 $self->{'is_circular'} = 1;
2687 $hash{ $id } = $id;
2688 while ( ($id) = $sth->fetchrow_array() ) {
2689 $hash{ $id } = $id;
2690 }
2691 } else {
2692 $self->{'is_circular'} = 0;
2693 }
2694 $sth->finish();
2695 } ## end _build_circular_slice_cache
2696  
2697 =head2 _create_chromosome_alias
2698  
2699 Args : none
2700 Example : $self->create_chromosome_alias();
2701 Description: create chromosome alias in coordinate system with karyotype attributes
2702 Returntype : Bio::EnsEMBL::CoordSystem, or none
2703 Exceptions : None
2704 Caller : general
2705 Status : in testing
2706  
2707 =cut
2708  
2709 sub _create_chromosome_alias {
2710 my $self = shift;
2711 my $csa = $self->db->get_CoordSystemAdaptor();
2712  
2713 # to store reformatted db query results
2714 my $karyotype_seq_regions;
2715
2716 my $karyotype_rank_string = "karyotype_rank";
2717  
2718 # to store coord_system_id to alias
2719 my $cs_id;
2720 my %cs_id_rank;
2721  
2722 # check whether seq region cache exists, otherwise run database query
2723 if ( $self->{'karyotype_cache'} ) {
2724 $karyotype_seq_regions = $self->{'karyotype_cache'};
2725  
2726 # get candidate coordSystem(s) to alias
2727 foreach my $seq_region_name ( keys %{$karyotype_seq_regions} ) {
2728 foreach my $coord_system_id ( keys %{ $karyotype_seq_regions->{ $seq_region_name } } ) {
2729 my $rank = $karyotype_seq_regions->{ $seq_region_name }->{ $coord_system_id }->{ rank };
2730 $cs_id_rank{ $coord_system_id } = $rank;
2731 }
2732 }
2733 } else {
2734 # cannot find a coordssystem called chromosome
2735 # look through attribs to find seq_regions with karyotype
2736  
2737 my $sth =
2738 $self->prepare( "SELECT sr.seq_region_id, sr.name, sr.coord_system_id, sr.length, a.code, cs.rank "
2739 . "FROM seq_region sr, seq_region_attrib sra, attrib_type a, coord_system cs "
2740 . "WHERE sr.seq_region_id = sra.seq_region_id "
2741 . "AND a.attrib_type_id = sra.attrib_type_id "
2742 . "AND cs.coord_system_id = sr.coord_system_id "
2743 . "AND a.code = ?" );
2744  
2745 $sth->bind_param( 1, $karyotype_rank_string );
2746 $sth->execute();
2747  
2748 # fetch SQL results and identify coord_system_id(s) that
2749 # has(have) karyotype attribs
2750 while ( my $hashref = $sth->fetchrow_hashref() ) {
2751 my $seq_region_id = $hashref->{ seq_region_id };
2752 my $seq_region_name = $hashref->{ name };
2753 my $coord_system_id = $hashref->{ coord_system_id };
2754 my $length = $hashref->{ length };
2755 my $code = $hashref->{ code };
2756 my $rank = $hashref->{ rank };
2757  
2758 # account for possibility of multiple coord_system_ids returned from db query
2759 $karyotype_seq_regions->{ $seq_region_name }->{ $coord_system_id } = {
2760 code => $code,
2761 length => $length,
2762 seq_region_id => $seq_region_id,
2763 rank => $rank
2764 };
2765  
2766 # hash to help decide which cs id to use, if multiple
2767 $cs_id_rank{ $coord_system_id } = $rank;
2768 }
2769 $sth->finish();
2770 }
2771  
2772 my $cs_id_count = keys %cs_id_rank;
2773 # if number of coordSystem ids retrieved is one, simply use this coordSystem id
2774 # otherwise, choose the coordSystem with the best-rank (i.e. lowest number)
2775 if ( $cs_id_count == 1 ) {
2776 $cs_id = (keys %cs_id_rank)[0]; # get only key name in hash
2777 } else {
2778 foreach my $id (sort { $cs_id_rank{$a} <=> $cs_id_rank{$b} } keys %cs_id_rank) {
2779 $cs_id = $id;
2780 last; # exit loop after getting lowest-ranked coordSystem id
2781 }
2782 }
2783  
2784 if ( !$cs_id ) {
2785 throw("No coordinate system to create a chromosome slice from (because there is no suitable coordinate system to create an alias to).\n");
2786 } else {
2787  
2788 # use appropriate 'coord_system_id' to set 'alias_to' variable
2789 # first check that a chromosome object does not already exist
2790 my $cs = $csa->fetch_by_dbID( $cs_id );
2791 if ( !$cs ) {
2792 throw("Unable to retrieve CoordSystem object using dbID: $cs_id");
2793 }
2794 if ( $cs->name eq "chromosome" ) {
2795 throw("A chromosome CoordSystem object already exists. Cannot create chromosome alias.");
2796 }
2797 $cs->alias_to('chromosome');
2798  
2799 # create karyotype cache in retrieved coordsystem
2800 $cs->{'karyotype_cache'} = $karyotype_seq_regions;
2801  
2802 return $cs;
2803 }
2804 } ## end create_chromosome_alias
2805  
2806  
2807 =head2 _fetch_by_seq_region_synonym
2808 Args : $cs, $seq_region_name, $start, $end, $strand, $version, $no_fuzz
2809 Example : $self->fetch_by_seq_region_synonym( $cs, $seq_region_name, $start, $end, $strand, $version, $no_fuzz );
2810 Description: fetches all the seq region synonyms (or uses wildcard) when requested
2811 Returntype : Bio::EnsEMBL::SliceAdaptor, or none
2812 Exceptions : None
2813 Caller : general
2814 Status : (refactored from fetch_by_region)
2815 =cut
2816  
2817 sub _fetch_by_seq_region_synonym {
2818  
2819 my ( $self, $cs, $seq_region_name, $start, $end, $strand, $version, $no_fuzz ) = @_;
2820
2821 # check input
2822 assert_integer($start, 'start') if defined $start;
2823 assert_integer($end, 'end') if defined $end;
2824  
2825 if ( !defined($start) ) { $start = 1 }
2826 if ( !defined($strand) ) { $strand = 1 }
2827  
2828 if ( !defined($seq_region_name) ) {
2829 throw('seq_region_name argument is required');
2830 }
2831  
2832 my $coord_system_name;
2833 # try synonyms
2834 my $syn_sql = "select s.name, cs.name, cs.version from seq_region s join seq_region_synonym ss using (seq_region_id) join coord_system cs using (coord_system_id) where ss.synonym like ? and cs.species_id =? ";
2835 if (defined $cs) {
2836 $coord_system_name = $cs->name;
2837 $syn_sql .= "AND cs.name = '" . $coord_system_name . "' ";
2838 }
2839 if (defined $version) {
2840 $syn_sql .= "AND cs.version = '" . $version . "' ";
2841 }
2842 $syn_sql .= "ORDER BY cs.rank ASC";
2843 my $syn_sql_sth = $self->prepare($syn_sql);
2844 $syn_sql_sth->bind_param(1, $seq_region_name, SQL_VARCHAR);
2845 $syn_sql_sth->bind_param(2, $self->species_id(), SQL_INTEGER);
2846 $syn_sql_sth->execute();
2847 my ($new_name, $new_coord_system, $new_version);
2848 $syn_sql_sth->bind_columns( \$new_name, \$new_coord_system, \$new_version);
2849  
2850 # we want to see if there was an exact match for the seq_region_synonym.
2851 # The overall logic is:
2852 # Case 1 - A synonym exactly matches the query, and either:
2853 # a - the coord_system matches
2854 # or
2855 # b - the user is looking for toplevel
2856 # In this case, we now have the real seq_region name, so we can re-run
2857 # fetch_by_region using that name, coord_system, and version
2858 # Case 2 - A synonym exactly matches, but none of the coord_systems match
2859 # and the user is not looking for toplevel.
2860 # In this case, we return nothing, and move on to try fuzzy-matching
2861 # if requested.
2862 # Case 3 - No synonyms match, so repeat the query using wildcards
2863 my $matched_synonym = 0;
2864 while ($syn_sql_sth->fetch){
2865 $matched_synonym = 1;
2866 if ((not defined($cs)) || ($cs->name eq $new_coord_system && $cs->version eq $new_version)) {
2867 return $self->fetch_by_region($new_coord_system, $new_name, $start, $end, $strand, $new_version, $no_fuzz);
2868 }
2869 }
2870  
2871 if ($matched_synonym == 0) {
2872 # Try wildcard searching if no exact synonym was found
2873 $syn_sql_sth = $self->prepare($syn_sql);
2874 my $escaped_seq_region_name = $seq_region_name;
2875 my $escape_char = $self->dbc->db_handle->get_info(14);
2876 $escaped_seq_region_name =~ s/([_%])/$escape_char$1/g;
2877 $syn_sql_sth->bind_param(1, "$escaped_seq_region_name%", SQL_VARCHAR);
2878 $syn_sql_sth->bind_param(2, $self->species_id(), SQL_INTEGER);
2879 $syn_sql_sth->execute();
2880 $syn_sql_sth->bind_columns( \$new_name, \$new_coord_system, \$new_version);
2881  
2882 my @matched_syn_wrong_cs;
2883 while ($syn_sql_sth->fetch){
2884 if ((not defined($cs)) || ($cs->name eq $new_coord_system && $cs->version eq $new_version)) {
2885 return $self->fetch_by_region($new_coord_system, $new_name, $start, $end, $strand, $new_version, $no_fuzz);
2886 } else {
2887 push(@matched_syn_wrong_cs, [$new_coord_system, $new_version]);
2888 }
2889 }
2890  
2891 if (scalar(@matched_syn_wrong_cs) > 0) {
2892 my $cs_warning_text = "Searched for a known feature on coordniate system: " .
2893 $cs->dbID .
2894 " but found it on " .
2895 join(", ", map {if ($_->[1]) {
2896 $_->[0] . ":" . $_->[1]
2897 } else {
2898 $_->[0]
2899 }
2900 } @matched_syn_wrong_cs) .
2901 "\n No result returned, consider searching without coordinate system or use toplevel.";
2902 warning($cs_warning_text);
2903 return;
2904 }
2905 }
2906 $syn_sql_sth->finish;
2907 return;
2908 }
2909
2910
2911 =head2 _fetch_by_fuzzy_matching
2912 Args : $cs, $seq_region_name, $sql, $constraint, $bind_params
2913 Example : my $fuzzy_matched_name = $self->fetch_by_fuzzy_matching( $cs, $seq_region_name, $sql, $constraint, $bind_params );
2914 Description: fetches all the fuzzy matches for a given seq_region_name when requested
2915 Returntype : string, Bio::EnsEMBL::CoordSystem
2916 Exceptions : None
2917 Caller : general
2918 Status : (refactored from fetch_by_region)
2919 =cut
2920  
2921 sub _fetch_by_fuzzy_matching {
2922  
2923 my ($self, $cs, $seq_region_name, $sql, $constraint, $bind_params) = @_;
2924  
2925 my $csa = $self->db->get_CoordSystemAdaptor();
2926 my $length;
2927  
2928 # Do fuzzy matching, assuming that we are just missing a version
2929 # on the end of the seq_region name.
2930  
2931 my $sth =
2932 $self->prepare( $sql . " WHERE sr.name LIKE ? " . $constraint );
2933  
2934 @$bind_params[0] = [ sprintf( '%s.%%', $seq_region_name ), SQL_VARCHAR ];
2935
2936 my $pos = 0;
2937 foreach my $param (@$bind_params) {
2938 $sth->bind_param( ++$pos, $param->[0], $param->[1] );
2939 }
2940  
2941 $sth->execute();
2942  
2943 my $prefix_len = length($seq_region_name) + 1;
2944 my $high_ver = undef;
2945 my $high_cs = $cs;
2946  
2947 # Find the fuzzy-matched seq_region with the highest postfix
2948 # (which ought to be a version).
2949  
2950 my ( $tmp_name, $id, $tmp_length, $cs_id );
2951 $sth->bind_columns( \( $tmp_name, $id, $tmp_length, $cs_id ) );
2952  
2953 my $i = 0;
2954  
2955 while ( $sth->fetch ) {
2956 my $tmp_cs =
2957 ( defined($cs) ? $cs : $csa->fetch_by_dbID($cs_id) );
2958  
2959 # cache values for future reference
2960 my $arr = [ $id, $tmp_name, $cs_id, $tmp_length ];
2961 $self->{'sr_name_cache'}->{"$tmp_name:$cs_id"} = $arr;
2962 $self->{'sr_id_cache'}->{"$id"} = $arr;
2963  
2964 my $tmp_ver = substr( $tmp_name, $prefix_len );
2965  
2966 # skip versions which are non-numeric and apparently not
2967 # versions
2968 if ( $tmp_ver !~ /^\d+$/ ) { next }
2969  
2970 # take version with highest num, if two versions match take one
2971 # with highest ranked coord system (lowest num)
2972 if ( !defined($high_ver)
2973 || $tmp_ver > $high_ver
2974 || ( $tmp_ver == $high_ver && $tmp_cs->rank < $high_cs->rank )
2975 )
2976 {
2977 $seq_region_name = $tmp_name;
2978 $length = $tmp_length;
2979 $high_ver = $tmp_ver;
2980 $high_cs = $tmp_cs;
2981 }
2982  
2983 $i++;
2984 } ## end while ( $sth->fetch )
2985 $sth->finish();
2986  
2987 # warn if fuzzy matching found more than one result
2988 if ( $i > 1 ) {
2989 warning(
2990 sprintf(
2991 "Fuzzy matching of seq_region_name "
2992 . "returned more than one result.\n"
2993 . "You might want to check whether the returned seq_region\n"
2994 . "(%s:%s) is the one you intended to fetch.\n",
2995 $high_cs->name(), $seq_region_name ) );
2996 }
2997  
2998 $cs = $high_cs;
2999  
3000 # return if we did not find any appropriate match:
3001 if ( !defined($high_ver) ) { return; }
3002  
3003 return ($seq_region_name, $cs);
3004 }
3005  
3006 1;