EnsEMBL/DBSQL/SequenceAdaptor.pm untested

filter: Statementstmt 0.0% 0 / 234 Branchbran 0.0% 0 / 94 Conditioncond 0.0% 0 / 63 Subroutinesub 0.0% 0 / 16 Podpod 0.0% 0 / 9 totaltotal 0.0% 0 / 416 CC 48 SCAR 54.5
CC
48
Cov
0%
fetch_by_Slice_start_end_strand
462.0
_fetch_by_Slice_start_end_strand_circular
272.0
_rna_edit
56.0
CRAP 232.4
1 =head1 LICENSE
2  
3 See the NOTICE file distributed with this work for additional information
4 regarding copyright ownership.
5  
6 Licensed under the Apache License, Version 2.0 (the "License");
7 you may not use this file except in compliance with the License.
8 You may obtain a copy of the License at
9  
10 http://www.apache.org/licenses/LICENSE-2.0
11  
12 Unless required by applicable law or agreed to in writing, software
13 distributed under the License is distributed on an "AS IS" BASIS,
14 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 See the License for the specific language governing permissions and
16 limitations under the License.
17  
18 =head1 CONTACT
19  
20 Please email comments or questions to the public Ensembl
21 developers list at <dev@ensembl.org>.
22  
23 Questions may also be sent to the Ensembl help desk at
24 <helpdesk@ensembl.org>.
25  
26 =cut
27  
28 =head1 NAME
29  
30 Bio::EnsEMBL::DBSQL::SequenceAdaptor - produce sequence strings from locations
31  
32 =head1 SYNOPSIS
33  
34 my $sa = $registry->get_adaptor( 'Human', 'Core', 'Sequence' );
35  
36 my $dna =
37 ${ $sa->fetch_by_Slice_start_end_strand( $slice, 1, 1000, -1 ) };
38  
39 =head1 DESCRIPTION
40  
41 An adaptor for the retrieval of DNA sequence from the EnsEMBL database
42  
43 =head1 METHODS
44  
45 =cut
46  
47 package Bio::EnsEMBL::DBSQL::SequenceAdaptor;
48 $Bio::EnsEMBL::DBSQL::SequenceAdaptor::VERSION = '114.0.0_50'; # TRIAL
49 $Bio::EnsEMBL::DBSQL::SequenceAdaptor::VERSION = '114.0.050';
50 use strict;
51 use warnings;
52  
53 use Bio::EnsEMBL::Utils::Exception qw(throw);
54 use Bio::EnsEMBL::Utils::Sequence qw(reverse_comp);
55 use Bio::EnsEMBL::Utils::Scalar qw( assert_ref );
56 use DBI qw/:sql_types/;
57 use base qw(Bio::EnsEMBL::DBSQL::BaseAdaptor Bio::EnsEMBL::DBSQL::BaseSequenceAdaptor);
58 our @EXPORT = (@{$DBI::EXPORT_TAGS{'sql_types'}});
59  
60 =head2 new
61  
62 Arg [1] : none
63 Example : my $sa = $db_adaptor->get_SequenceAdaptor();
64 Description: Constructor. Calls superclass constructor and initialises
65 internal cache structure.
66 Returntype : Bio::EnsEMBL::DBSQL::SequenceAdaptor
67 Exceptions : none
68 Caller : DBAdaptor::get_SequenceAdaptor
69 Status : Stable
70  
71 =cut
72  
73 sub new {
74 my ($caller, $db, $chunk_power, $cache_size) = @_;
75 my $class = ref($caller) || $caller;
76 my $self = $class->SUPER::new($db);
77 $self->_init_seq_instance($chunk_power, $cache_size);
78 $self->_populate_seq_region_edits();
79 return $self;
80 }
81  
82 =head2 fetch_by_Slice_start_end_strand
83  
84 Arg [1] : Bio::EnsEMBL::Slice slice
85 The slice from which you want the sequence
86 Arg [2] : (optional) int startBasePair
87 The start base pair relative to the start of the slice. Negative
88 values or values greater than the length of the slice are fine.
89 default = 1
90 Arg [3] : (optional) int endBasePair
91 The end base pair relative to the start of the slice. Negative
92 values or values greater than the length of the slice are fine,
93 but the end must be greater than or equal to the start
94 count from 1
95 default = the length of the slice
96 Arg [4] : (optional) int strand
97 1, -1
98 default = 1
99 Example : $dna = $seq_adptr->fetch_by_Slice_start_end_strand($slice, 1,
100 1000, -1);
101 Description: Retrieves from db the sequence for this slice
102 uses AssemblyMapper to find the assembly
103 Returntype : string
104 Exceptions : endBasePair should be less or equal to length of slice
105 Caller : Bio::EnsEMBL::Slice::seq(), Slice::subseq()
106 Status : Stable
107  
108 =cut
109  
110 sub fetch_by_Slice_start_end_strand {
111 my ( $self, $slice, $start, $end, $strand ) = @_;
112  
113 if(!ref($slice) || !($slice->isa("Bio::EnsEMBL::Slice") or $slice->isa('Bio::EnsEMBL::LRGSlice')) ) {
114 throw("Slice argument is required.");
115 }
116  
117 $start = 1 if(!defined($start));
118  
119
120 if ( ( !defined($end) || $start > $end || $start < 0 || $end < 0 || $slice->start> $slice->end ) && $slice->is_circular ) {
121
122 if ( !defined($end) || ($start > $end ) ) {
123 return $self->_fetch_by_Slice_start_end_strand_circular( $slice, $start, $end, $strand );
124 }
125  
126 if ( defined($end) && ($end < 0) ) {
127 $end += $slice->seq_region_length;
128 }
129
130 if ($start < 0) {
131 $start += $slice->seq_region_length;
132 }
133  
134 if($slice->start> $slice->end) {
135 return $self->_fetch_by_Slice_start_end_strand_circular( $slice, $slice->start, $slice->end, $strand );
136 }
137 }
138
139 if ( ( !defined($end) ) && (not $slice->is_circular) ) {
140 $end = $slice->end() - $slice->start() + 1;
141 }
142  
143 if ( $start > $end ) {
144 throw("Start must be less than or equal to end.");
145 }
146  
147 $strand ||= 1;
148 #get a new slice that spans the exact region to retrieve dna from
149 my $right_expand = $end - $slice->length(); #negative is fine
150 my $left_expand = 1 - $start; #negative is fine
151  
152 if($right_expand || $left_expand) {
153 $slice = $slice->expand($left_expand, $right_expand);
154 }
155
156 #retrieve normalized 'non-symlinked' slices
157 #this allows us to support haplotypes and PARs
158 my $slice_adaptor = $slice->adaptor();
159 my @symproj=@{$slice_adaptor->fetch_normalized_slice_projection($slice)};
160  
161 if(@symproj == 0) {
162 throw('Could not retrieve normalized Slices. Database contains ' .
163 'incorrect assembly_exception information.');
164 }
165  
166 #call this method again with any slices that were 'symlinked' to by this
167 #slice
168 if(@symproj != 1 || $symproj[0]->[2] != $slice) {
169 my $seq;
170 foreach my $segment (@symproj) {
171 my $symlink_slice = $segment->[2];
172 #get sequence from each symlinked area
173 $seq .= ${$self->fetch_by_Slice_start_end_strand($symlink_slice,
174 1,undef,1)};
175 }
176 if($strand == -1) {
177 reverse_comp(\$seq);
178 }
179 return \$seq;
180 }
181  
182 # we need to project this slice onto the sequence coordinate system
183 # even if the slice is in the same coord system, we want to trim out
184 # flanking gaps (if the slice is past the edges of the seqregion)
185 my $csa = $self->db->get_CoordSystemAdaptor();
186 my $seqlevel = $csa->fetch_sequence_level();
187  
188 my @projection=@{$slice->project($seqlevel->name(), $seqlevel->version())};
189  
190 my $seq = '';
191 my $total = 0;
192 my $tmp_seq;
193  
194 #fetch sequence from each of the sequence regions projected onto
195 foreach my $segment (@projection) {
196 my ($start, $end, $seq_slice) = @$segment;
197  
198 #check for gaps between segments and pad them with Ns
199 my $gap = $start - $total - 1;
200 if($gap) {
201 $seq .= 'N' x $gap;
202 }
203  
204 my $seq_region_id = $slice_adaptor->get_seq_region_id($seq_slice);
205  
206 $tmp_seq = ${$self->_fetch_seq($seq_region_id,
207 $seq_slice->start, $seq_slice->length())};
208  
209 if(!defined $tmp_seq) {
210 throw('No sequence found for seq_region '.$seq_region_id.':'.$seq_slice->start);
211 }
212  
213 #reverse compliment on negatively oriented slices
214 if($seq_slice->strand == -1) {
215 reverse_comp(\$tmp_seq);
216 }
217  
218 $seq .= $tmp_seq;
219  
220 $total = $end;
221 }
222  
223 #check for any remaining gaps at the end
224 my $gap = $slice->length - $total;
225 if($gap) {
226 $seq .= 'N' x $gap;
227 }
228  
229 #if the sequence is too short it is because we came in with a seqlevel
230 #slice that was partially off of the seq_region. Pad the end with Ns
231 #to make long enough
232 if(length($seq) != $slice->length()) {
233 $seq .= 'N' x ($slice->length() - length($seq));
234 }
235  
236 if(defined($self->{_rna_edits_cache}) and defined($self->{_rna_edits_cache}->{$slice->get_seq_region_id})){
237 $self->_rna_edit($slice,\$seq);
238 }
239  
240 #if they asked for the negative slice strand revcomp the whole thing
241 reverse_comp(\$seq) if($strand == -1);
242  
243 return \$seq;
244 }
245  
246 =head2 can_access_Slice
247  
248 Description : Returns 1 since we can access any Slice's data
249  
250 =cut
251  
252 sub can_access_Slice {
253 return 1;
254 }
255  
256 sub _fetch_by_Slice_start_end_strand_circular {
257 my ( $self, $slice, $start, $end, $strand ) = @_;
258  
259 assert_ref( $slice, 'Bio::EnsEMBL::Slice' );
260
261 $strand ||= 1;
262 if ( !defined($start) ) {
263 $start ||= 1;
264 }
265  
266 if ( !defined($end) ) {
267 $end = $slice->end() - $slice->start() + 1;
268 }
269  
270 if ( $start > $end && $slice->is_circular() ) {
271 my ($seq, $seq1, $seq2);
272  
273 my $midpoint = $slice->seq_region_length - $slice->start + 1;
274 $seq1 = ${ $self->_fetch_by_Slice_start_end_strand_circular( $slice, 1, $midpoint, 1 )};
275 $seq2 = ${ $self->_fetch_by_Slice_start_end_strand_circular( $slice, $midpoint + 1, $slice->length(), 1 )};
276  
277 $seq = $slice->strand > 0 ? "$seq1$seq2" : "$seq2$seq1";
278  
279 reverse_comp( \$seq ) if ( $strand == -1 );
280  
281 return \$seq;
282 }
283  
284 # Get a new slice that spans the exact region to retrieve dna from
285 my $right_expand = $end - $slice->length(); #negative is fine
286 my $left_expand = 1 - $start; #negative is fine
287  
288 if ( $right_expand || $left_expand ) {
289 $slice =
290 $slice->strand > 0
291 ? $slice->expand( $left_expand, $right_expand )
292 : $slice->expand( $right_expand, $left_expand );
293 }
294  
295 # Retrieve normalized 'non-symlinked' slices. This allows us to
296 # support haplotypes and PARs.
297 my $slice_adaptor = $slice->adaptor();
298 my @symproj =
299 @{ $slice_adaptor->fetch_normalized_slice_projection($slice) };
300  
301 if ( @symproj == 0 ) {
302 throw( 'Could not retrieve normalized Slices. Database contains '
303 . 'incorrect assembly_exception information.' );
304 }
305  
306 # Call this method again with any slices that were 'symlinked' to by
307 # this slice.
308 if ( @symproj != 1 || $symproj[0]->[2] != $slice ) {
309 my $seq;
310 foreach my $segment (@symproj) {
311 my $symlink_slice = $segment->[2];
312  
313 # Get sequence from each symlinked area.
314 $seq .= ${
315 $self->fetch_by_Slice_start_end_strand( $symlink_slice, 1,
316 undef, 1 ) };
317 }
318 if ( $strand == -1 ) {
319 reverse_comp( \$seq );
320 }
321  
322 return \$seq;
323 }
324  
325 # We need to project this slice onto the sequence coordinate system
326 # even if the slice is in the same coord system, we want to trim out
327 # flanking gaps (if the slice is past the edges of the seqregion).
328 my $csa = $self->db->get_CoordSystemAdaptor();
329 my $seqlevel = $csa->fetch_sequence_level();
330  
331 my @projection =
332 @{ $slice->project( $seqlevel->name(), $seqlevel->version() ) };
333  
334 my $seq = '';
335 my $total = 0;
336 my $tmp_seq;
337  
338 # Fetch sequence from each of the sequence regions projected onto.
339 foreach my $segment (@projection) {
340 my ( $start, $end, $seq_slice ) = @{$segment};
341  
342 # Check for gaps between segments and pad them with Ns
343 my $gap = $start - $total - 1;
344 if ($gap) {
345 $seq .= 'N' x $gap;
346 }
347  
348 my $seq_region_id = $slice_adaptor->get_seq_region_id($seq_slice);
349  
350 $tmp_seq = ${
351 $self->_fetch_seq( $seq_region_id, $seq_slice->start(),
352 $seq_slice->length() ) };
353  
354 # Reverse compliment on negatively oriented slices.
355 if ( $seq_slice->strand == -1 ) {
356 reverse_comp( \$tmp_seq );
357 }
358  
359 $seq .= $tmp_seq;
360  
361 $total = $end;
362 }
363  
364 # Check for any remaining gaps at the end.
365 my $gap = $slice->length() - $total;
366  
367 if ($gap) {
368 $seq .= 'N' x $gap;
369 }
370  
371 # If the sequence is too short it is because we came in with a
372 # seqlevel slice that was partially off of the seq_region. Pad the
373 # end with Ns to make long enough
374 if ( length($seq) != $slice->length() ) {
375 $seq .= 'N' x ( $slice->length() - length($seq) );
376 }
377  
378 if ( defined( $self->{_rna_edits_cache} )
379 && defined(
380 $self->{_rna_edits_cache}->{ $slice->get_seq_region_id } ) )
381 {
382 $self->_rna_edit( $slice, \$seq );
383 }
384  
385 return \$seq;
386 } ## end sub _fetch_by_Slice_start_end_strand_circular
387  
388  
389  
390 =head2 _rna_edit
391  
392 Description : Performs within sequence region editting when
393 the underlying sequence is incorrect. Used by LRGs.
394  
395 =cut
396  
397 sub _rna_edit {
398 my $self = shift;
399 my $slice = shift;
400 my $seq = shift; #reference to string
401  
402 my $s_start = $slice->start; # substr start at 0 , but seq starts at 1 (so no -1 here)
403 my $s_end = $s_start+length($$seq) - 1; # But we do need -1 here to keep the coords closed
404  
405 foreach my $edit (@{$self->{_rna_edits_cache}->{$slice->get_seq_region_id}}){
406 # seq_region_attrib for an exit looks like
407 # <start> <end> <edit>
408 # 2568 2569 GT
409 my ($start, $end, $txt) = split (/\s+/, $edit);
410  
411 # check that RNA edit is not outside the requested region : happens quite often with LRG regions
412 next if ($end < $s_start);
413 next if ($s_end < $start);
414 # Length of the edit ($txt)
415 my $edit_length = length($txt);
416  
417 # If the edit isn't fully encompassed by the slice, we need to extract the
418 # edit's sub-sequence that we're patching on to the sequence
419 if($start < $s_start || $end > $s_end) {
420 my $edit_offset;
421 # Find the offset for the start of the edit, eg.
422 # seq slice: TC
423 # LRG edit : CG
424 # Offset should be 1 to extract starting at the G
425 # Formula: offset = max(s_start - start, 0)
426 $edit_offset = ($s_start - $start) < 0 ? 0 : $s_start - $start;
427  
428 # Find the length of the overlapping piece of the edit.
429 # This needs to take in to account the offset
430 # seq slice: TC
431 # LRG edit : GA
432 # Where we're want the length to be 1 from an existing offset of 1 to
433 # extract just G
434 # Forumla: length = length(edit) - offset - max(end - s_end, 0)
435 $edit_length = length($txt) - $edit_offset - ($end - $s_end < 0 ? 0 : $end - $s_end);
436  
437 # Extract the overlapping edit
438 $txt = substr($txt, $edit_offset, $edit_length);
439 }
440  
441 # Apply the patch, we don't want negative offsets as that's totally wrong.
442 # Do a max(start - s_start, 0) to prevent this
443 substr($$seq,($start-$s_start < 0 ? 0 : $start-$s_start),$edit_length, $txt);
444 }
445 return;
446 }
447  
448 =head2 _fetch_raw_seq
449  
450 Description : Communicates with the database to fetch back sequence
451  
452 =cut
453  
454 sub _fetch_raw_seq {
455 my ($self, $id, $start, $length) = @_;
456 my $sql = <<'SQL';
457 SELECT UPPER(SUBSTR(d.sequence, ?, ?))
458 FROM dna d
459 WHERE d.seq_region_id =?
460 SQL
461 my $seq = $self->dbc()->sql_helper()->execute_single_result(
462 -SQL => $sql,
463 -PARAMS => [[$start, SQL_INTEGER], [$length, SQL_INTEGER], [$id, SQL_INTEGER]],
464 -NO_ERROR => 1
465 );
466 return \$seq;
467 }
468  
469 =head2 store
470  
471 Arg [1] : int $seq_region_id the id of the sequence region this dna
472 will be associated with.
473 Arg [2] : string $sequence the dna sequence to be stored
474 in the database. Note that the sequence passed in will be
475 converted to uppercase.
476 Example : $seq_adaptor->store(11, 'ACTGGGTACCAAACAAACACAACA');
477 Description: stores a dna sequence in the databases dna table and returns the
478 database identifier for the new record.
479 Returntype : none
480 Exceptions : throw if the database insert fails
481 Caller : sequence loading scripts
482 Status : Stable
483  
484 =cut
485  
486 sub store {
487 my ($self, $seq_region_id, $sequence) = @_;
488  
489 if(!$seq_region_id) {
490 throw('seq_region_id is required');
491 }
492  
493 $sequence = uc($sequence);
494  
495 my $statement =
496 $self->prepare("INSERT INTO dna(seq_region_id, sequence) VALUES(?,?)");
497  
498 $statement->bind_param(1,$seq_region_id,SQL_INTEGER);
499 $statement->bind_param(2,$sequence,SQL_LONGVARCHAR);
500 $statement->execute();
501  
502 $statement->finish();
503  
504 return;
505 }
506  
507 =head2 remove
508
509 Arg [1] : int $seq_region_id the id of the sequence region this dna
510 is associated with.
511 Example : $seq_adaptor->remove(11);
512 Description: removes a dna sequence for a given seq_region_id
513 Returntype : none
514 Exceptions : throw if the database delete fails
515 Caller : Internal
516 Status : Stable
517
518 =cut
519
520 sub remove {
521 my ($self, $seq_region_id) = @_;
522
523 if(!$seq_region_id) {
524 throw('seq_region_id is required');
525 }
526
527 my $statement =
528 $self->prepare("DELETE FROM dna WHERE seq_region_id = ?");
529
530 $statement->bind_param(1,$seq_region_id,SQL_INTEGER);
531 $statement->execute();
532
533 $statement->finish();
534
535 return;
536 }
537  
538 =head2 _populate_seq_region_edits
539  
540 Description: Query the database for any _rna_edit attributes attached to a seq region
541  
542 =cut
543  
544 sub _populate_seq_region_edits {
545 my ($self) = @_;
546 my $sql;
547 my @params = ('_rna_edit');
548 if($self->db()->is_multispecies()) {
549 $sql = <<'SQL';
550 select sra.seq_region_id, sra.value
551 from seq_region_attrib sra
552 join attrib_type using (attrib_type_id)
553 join seq_region s using (seq_region_id)
554 join coord_system cs using (coord_system_id)
555 where code =?
556 and species_id =?
557 SQL
558 push(@params, $self->db()->species_id());
559 }
560 else {
561 $sql = <<'SQL';
562 select sra.seq_region_id, sra.value
563 from seq_region_attrib sra join attrib_type using (attrib_type_id)
564 where code = ?
565 SQL
566 }
567  
568 my $mapper = sub {
569 my ($row, $array) = @_;
570 my ($seq_region_id, $value) = @{$row};
571 my ($start, $end, $substring) = split (/\s+/, $value);
572 my $edit_length = ($end - $start) + 1;
573 my $substring_length = length($substring);
574 if($edit_length != $substring_length) {
575 throw "seq_region_id $seq_region_id has an attrib of type '_rna_edit' (value '$value'). Edit length ${edit_length} is not the same as the replacement's length ${substring_length}. Please fix. We only support substitutions via this mechanism";
576 }
577 if(defined $array) {
578 push(@{$array}, $value);
579 return;
580 }
581 return [$value];
582 };
583  
584 my $edits = $self->dbc()->sql_helper->execute_into_hash(-SQL => $sql, -PARAMS => ['_rna_edit'], -CALLBACK => $mapper);
585 $self->{_rna_edits_cache} = $edits if %{$edits};
586 return;
587 }
588  
589 1;