EnsEMBL/Utils/SeqDumper.pm untested

filter: Statementstmt 0.0% 0 / 529 Branchbran 0.0% 0 / 116 Conditioncond 0.0% 0 / 100 Subroutinesub 0.0% 0 / 27 Podpod 0.0% 0 / 22 totaltotal 0.0% 0 / 794 CC 59 SCAR 47.7
CC
59
Cov
0%
_dump_feature_table
420.0
annotation_source
72.0
dump_embl
42.0
CRAP 117.9
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::Utils::SeqDumper
34  
35 =head1 SYNOPSIS
36  
37 $seq_dumper = Bio::EnsEMBL::Utils::SeqDumper->new();
38  
39 # don't dump snps or repeats
40 $seq_dumper->disable_feature_type('repeat');
41 $seq_dumper->disable_feature_type('variation');
42  
43 # dump EMBL format to STDOUT
44 $seq_dumper->dump( $slice, 'EMBL' );
45  
46 # dump GENBANK format to a file
47 $seq_dumper->dump( $slice, 'GENBANK', 'out.genbank' );
48  
49 # dump FASTA format to a file
50 $seq_dumper->dump( $slice, 'FASTA', 'out.fasta' );
51  
52 =head1 DESCRIPTION
53  
54 A relatively simple and lite-weight flat file dumper for Ensembl slices.
55 The memory efficiency could be improved and this is currently not very
56 good for dumping very large sequences such as whole chromosomes.
57  
58 =head1 METHODS
59  
60 =cut
61  
62  
63 package Bio::EnsEMBL::Utils::SeqDumper;
64 $Bio::EnsEMBL::Utils::SeqDumper::VERSION = '114.0.0_50'; # TRIAL
65 $Bio::EnsEMBL::Utils::SeqDumper::VERSION = '114.0.050';
66 use strict;
67  
68 use IO::File;
69 use Fcntl qw( SEEK_SET SEEK_END );
70 use vars qw(@ISA);
71  
72 use Bio::EnsEMBL::Utils::Exception qw(throw warning);
73  
74 #keys must be uppercase
75 my $DUMP_HANDLERS =
76 { 'FASTA' => \&dump_fasta,
77 'EMBL' => \&dump_embl,
78 'GENBANK' => \&dump_genbank };
79  
80 my @COMMENTS =
81 ('This sequence was annotated by ###SOURCE###. Please visit ' .
82 'the Ensembl or EnsemblGenomes web site, http://www.ensembl.org/ or http://www.ensemblgenomes.org/ for more information.',
83  
84 'All feature locations are relative to the first (5\') base ' .
85 'of the sequence in this file. The sequence presented is '.
86 'always the forward strand of the assembly. Features ' .
87 'that lie outside of the sequence contained in this file ' .
88 'have clonal location coordinates in the format: ' .
89 '<clone accession>.<version>:<start>..<end>',
90  
91 'The /gene indicates a unique id for a gene, /note="transcript_id=..."' .
92 ' a unique id for a transcript, /protein_id a unique id for a peptide ' .
93 'and note="exon_id=..." a unique id for an exon. These ids are ' .
94 'maintained wherever possible between versions.',
95  
96 'All the exons and transcripts in Ensembl are confirmed by ' .
97 'similarity to either protein or cDNA sequences.');
98  
99 =head2 new
100  
101 Arg [1] : none
102 Example : $seq_dumper = Bio::EnsEMBL::Utils::SeqDumper->new;
103 Description: Creates a new SeqDumper
104 Returntype : Bio::EnsEMBL::Utils::SeqDumper
105 Exceptions : none
106 Caller : general
107  
108 =cut
109  
110 sub new {
111 my ($caller, $slice, $params) = @_;
112  
113 my $class = ref($caller) || $caller;
114  
115 my $feature_types = {'gene' => 1,
116 'genscan' => 1,
117 'repeat' => 1,
118 'similarity' => 1,
119 'variation' => 1,
120 'contig' => 1,
121 'marker' => 1,
122 'estgene' => 0,
123 'vegagene' => 0};
124  
125 my $self = bless {'feature_types' => $feature_types}, $class;
126  
127 foreach my $p (sort keys %{$params || {}}) {
128 $self->{$p} = $params->{$p};
129 }
130  
131 # default 60kb buffer
132 exists $self->{'chunk_factor'} and defined $self->{'chunk_factor'}
133 or $self->{'chunk_factor'} = 1000;
134  
135 return $self;
136 }
137  
138  
139  
140 =head2 enable_feature_type
141  
142 Arg [1] : string $type
143 Example : $seq_dumper->enable_feature_type('similarity');
144 Description: Enables the dumping of a specific type of feature
145 Returntype : none
146 Exceptions : warn if invalid feature type is passed,
147 thrown if no feature type is passed
148 Caller : general
149  
150 =cut
151  
152 sub enable_feature_type {
153 my ($self, $type) = @_;
154  
155 $type || throw("type arg is required");
156  
157 if(exists($self->{'feature_types'}->{$type})) {
158 $self->{'feature_types'}->{$type} = 1;
159 } else {
160 warning("unknown feature type '$type'\n" .
161 "valid types are: " . join(',', keys %{$self->{'feature_types'}}));
162 }
163 }
164  
165  
166  
167 =head2 attach_database
168  
169 Arg [1] : string name
170 Arg [2] : Bio::EnsEMBL::DBSQL::DBAdaptor
171 Example : $seq_dumper->attach_database('estgene', $estgene_db);
172 Description: Attaches a database to the seqdumper that can be used to
173 dump data which is external to the ensembl core database.
174 Currently this is necessary to dump est genes and vega genes
175 Returntype : none
176 Exceptions : thrown if incorrect argument is supplied
177 Caller : general
178  
179 =cut
180  
181 sub attach_database {
182 my ($self, $name, $db) = @_;
183  
184 $name || throw("name arg is required");
185 unless($db && ref($db) && $db->isa('Bio::EnsEMBL::DBSQL::DBAdaptor')) {
186 throw("db arg must be a Bio::EnsEMBL::DBSQL::DBAdaptor not a [$db]");
187 }
188  
189 $self->{'attached_dbs'}->{$name} = $db;
190 }
191  
192  
193  
194 =head2 get_database
195  
196 Arg [1] : string $name
197 Example : $db = $seq_dumper->get_database('vega');
198 Description: Retrieves a database that has been attached to the
199 seqdumper via the attach database call.
200 Returntype : Bio::EnsEMBL::DBSQL::DBAdaptor
201 Exceptions : thrown if incorrect argument is supplied
202 Caller : dump_feature_table
203  
204 =cut
205  
206 sub get_database {
207 my ($self, $name) = @_;
208  
209 $name || throw("name arg is required");
210
211 return $self->{'attached_dbs'}->{$name};
212 }
213  
214  
215  
216 =head2 remove_database
217  
218 Arg [1] : string $name
219 Example : $db = $seq_dumper->remove_database('estgene');
220 Description: Removes a database that has been attached to the seqdumper
221 via the attach database call. The database that is removed
222 is returned (or undef if it did not exist).
223 Returntype : Bio::EnsEMBL::DBSQL::DBAdaptor
224 Exceptions : thrown if incorrect argument is supplied
225 Caller : general
226  
227 =cut
228  
229 sub remove_database {
230 my ($self, $name) = @_;
231  
232 $name || throw("name arg is required");
233  
234 if(exists $self->{'attached_dbs'}->{$name}) {
235 return delete $self->{'attached_dbs'}->{$name};
236 }
237  
238 return undef;
239 }
240  
241  
242 =head2 disable_feature_type
243  
244 Arg [1] : string $type
245 Example : $seq_dumper->disable_feature_type('genes');
246 Description: Disables the dumping of a specific type of feature
247 Returntype : none
248 Exceptions : warn if an invalid feature type is passed,
249 thrown if no feature type is passed
250 Caller : general
251  
252 =cut
253  
254 sub disable_feature_type {
255 my ($self, $type) = @_;
256
257 $type || throw("type arg is required");
258  
259 if(exists($self->{'feature_types'}->{$type})) {
260 $self->{'feature_types'}->{$type} = 0;
261 } else {
262 warning("unknown feature type '$type'\n" .
263 "valid types are: " . join(',', keys %{$self->{'feature_types'}}));
264 }
265 }
266  
267  
268  
269 =head2 is_enabled
270  
271 Arg [1] : string $type
272 Example : do_something() if($seq_dumper->is_enabled('gene'));
273 Description: checks if a specific feature type is enabled
274 Returntype : none
275 Exceptions : warning if invalid type is passed,
276 thrown if no type is passed
277 Caller : general
278  
279 =cut
280  
281 sub is_enabled {
282 my ($self, $type) = @_;
283  
284 $type || throw("type arg is required");
285  
286 if(exists($self->{'feature_types'}->{$type})) {
287 return $self->{'feature_types'}->{$type};
288 } else {
289 warning("unknown feature type '$type'\n" .
290 "valid types are: " . join(',', keys %{$self->{'feature_types'}}));
291 }
292 }
293  
294  
295 =head2 dump
296  
297 Arg [1] : Bio::EnsEMBL::Slice slice
298 The slice to dump
299 Arg [2] : string $format
300 The name of the format to dump
301 Arg [3] : (optional) $outfile
302 The name of the file to dump to. If no file is specified STDOUT
303 is used
304 Arg [4] : (optional) $seq
305 Sequence to dump
306 Arg [4] : (optional) $no_append
307 Default action is to open the file in append mode. This will
308 turn that mode off
309 Example : $seq_dumper->dump($slice, 'EMBL');
310 Description: Dumps a region of a genome specified by the slice argument into
311 an outfile of the format $format
312 Returntype : none
313 Exceptions : thrown if slice or format args are not supplied
314 Caller : general
315  
316 =cut
317  
318  
319 sub dump {
320 my ($self, $slice, $format, $outfile, $seq, $no_append) = @_;
321  
322 $format || throw("format arg is required");
323 $slice || throw("slice arg is required");
324  
325 my $dump_handler = $DUMP_HANDLERS->{uc($format)};
326  
327 unless($dump_handler) {
328 throw("No dump handler is defined for format $format\n");
329 }
330  
331  
332 my $FH = IO::File->new;;
333 if($outfile) {
334 my $mode = ($no_append) ? '>' : '>>';
335 $FH->open("${mode}${outfile}") or throw("Could not open file $outfile: $!");
336 } else {
337 $FH = \*STDOUT;
338 #mod_perl did not like the following
339 #$FH->fdopen(fileno(STDOUT), "w")
340 # or throw("Could not open currently selected output filehandle " .
341 # "for writing");
342 }
343
344 &$dump_handler($self, $slice, $FH, $seq);
345  
346 $FH->close if ($outfile); #close if we were writing to a file
347 }
348  
349 =head2 dump_embl
350  
351 Arg [1] : Bio::EnsEMBL::Slice
352 Arg [2] : IO::File $FH
353 Arg [3] : optional sequence string
354 Example : $seq_dumper->dump_embl($slice, $FH);
355 Description: Dumps an EMBL flat file to an open file handle
356 Returntype : none
357 Exceptions : if calls to get/set the filehandle position fail
358 Caller : dump
359  
360 =cut
361  
362 sub dump_embl {
363 my $self = shift;
364 my $slice = shift;
365 my $FH = shift;
366  
367 my $len = $slice->length;
368  
369 my $version;
370 my $acc;
371  
372 my $cs = $slice->coord_system();
373 my $name_str = $cs->name() . ' ' . $slice->seq_region_name();
374 $name_str .= ' ' . $cs->version if($cs->version);
375  
376 my $start = $slice->start;
377 my $end = $slice->end;
378  
379 #determine if this slice is the entire seq region
380 #if it is then we just use the name as the id
381 my $slice_adaptor = $slice->adaptor();
382 my $full_slice =
383 $slice->adaptor->fetch_by_region($cs->name,
384 $slice->seq_region_name,
385 undef,undef,undef,
386 $cs->version);
387  
388 my $entry_name = $slice->seq_region_name();
389  
390 if($full_slice->name eq $slice->name) {
391 $name_str .= ' full sequence';
392 $acc = $slice->seq_region_name();
393 my @acc_ver = split(/\./, $acc);
394 if(@acc_ver == 2) {
395 $acc = $acc_ver[0];
396 $version = $acc_ver[0] . '.'. $acc_ver[1];
397 } elsif(@acc_ver == 1 && $cs->version()) {
398 $version = $acc . '.'. $cs->version();
399 } else {
400 $version = $acc;
401 }
402 } else {
403 $name_str .= ' partial sequence';
404 $acc = $slice->name();
405 $version = $acc;
406 }
407  
408 $acc = $slice->name();
409  
410 #line breaks are allowed near the end of the line on ' ', "\t", "\n", ','
411 $: = (" \t\n-,");
412  
413 #############
414 # dump header
415 #############
416  
417 # move at the end of file in case the file
418 # is open more than once (i.e. human chromosome Y,
419 # two chromosome slices
420 #
421 # WARNING
422 #
423 # When the file is open not for the first time,
424 # it must be in read/write mode
425 #
426 seek($FH, 0, SEEK_END);
427  
428 my $EMBL_HEADER =
429 '@< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<~
430 ';
431  
432 #ID and moltype
433 # HTG = High Throughput Genome division, probably most suitable
434 # and it would be hard to come up with another appropriate division
435 # that worked for all organisms (e.g. plants are in PLN but human is
436 # in HUM).
437 my $VALUE = "$entry_name standard; DNA; HTG; $len BP.";
438 $self->write($FH, $EMBL_HEADER, 'ID', $VALUE);
439 $self->print( $FH, "XX\n" );
440  
441 #Accession
442 $self->write($FH, $EMBL_HEADER, 'AC', $acc);
443 $self->print( $FH, "XX\n" );
444  
445 #Version
446 $self->write($FH, $EMBL_HEADER, 'SV', $version);
447 $self->print( $FH, "XX\n" );
448  
449 #Date
450 $self->write($FH, $EMBL_HEADER, 'DT', $self->_date_string);
451 $self->print( $FH, "XX\n" );
452  
453 my $meta_container = $slice->adaptor()->db()->get_MetaContainer();
454
455 #Description
456 $self->write($FH, $EMBL_HEADER, 'DE', $meta_container->get_scientific_name() .
457 " $name_str $start..$end annotated by Ensembl");
458 $self->print( $FH, "XX\n" );
459  
460 #key words
461 $self->write($FH, $EMBL_HEADER, 'KW', '.');
462 $self->print( $FH, "XX\n" );
463  
464 #Species
465 my $species_name = $meta_container->get_scientific_name();
466 if(my $cn = $meta_container->get_common_name()) {
467 $species_name .= " ($cn)";
468 }
469  
470 $self->write($FH, $EMBL_HEADER, 'OS', $species_name);
471  
472 #Classification
473 my @cls = @{$meta_container->get_classification()};
474 $self->write($FH, $EMBL_HEADER, 'OC', join('; ', reverse(@cls)) . '.');
475 $self->print( $FH, "XX\n" );
476
477 #References (we are not dumping refereneces)
478 #Database References (we are not dumping these)
479  
480 #comments
481 my $annotation_source = $self->annotation_source($meta_container);
482 foreach my $comment (@COMMENTS) {
483 $comment =~ s/\#\#\#SOURCE\#\#\#/$annotation_source/;
484 $self->write($FH, $EMBL_HEADER, 'CC', $comment);
485 $self->print( $FH, "XX\n" );
486 }
487  
488 ####################
489 # DUMP FEATURE TABLE
490 ####################
491 $self->print( $FH, "FH Key Location/Qualifiers\n" );
492  
493 my $FEATURE_TABLE =
494 'FT ^<<<<<<<<<<<<<<<^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<~
495 ';
496 $self->_dump_feature_table($slice, $FH, $FEATURE_TABLE);
497  
498 #write an XX after the feature tables
499 $self->print( $FH, "XX\n" );
500  
501 ###################
502 # DUMP SEQUENCE
503 ###################
504  
505 # record position before writing sequence header, so that
506 # after printing the sequence and having the base counts
507 # we can seek to this position and write the proper sequence
508 # header
509 my $sq_offset = tell($FH);
510 $sq_offset == -1 and throw "Unable to get offset for output fh";
511  
512 # print a sequence header template, to be replaced with a real
513 # one containing the base counts
514 $self->print($FH, "SQ Sequence ########## BP; ########## A; ########## C; ########## G; ########## T; ########## other;\n");
515
516 # dump the sequence and get the base counts
517 my $acgt = $self->write_embl_seq($slice, $FH);
518
519 # print the end of EMBL entry
520 $self->print( $FH, "//\n" );
521 my $end_of_entry_offset = tell($FH);
522 $end_of_entry_offset == -1 and throw "Unable to get offset for output fh";
523  
524 # seek backwards to the position of the sequence header and
525 # write it with the actual base counts
526 seek($FH, $sq_offset, SEEK_SET)
527 or throw "Cannot seek backward to sequence header position";
528 $self->print($FH, sprintf "SQ Sequence %10d BP; %10d A; %10d C; %10d G; %10d T; %10d other;",
529 $acgt->{tot}, $acgt->{a}, $acgt->{c}, $acgt->{g}, $acgt->{t}, $acgt->{n});
530  
531 # move forward to end of file to dump the next slice
532 seek($FH, $end_of_entry_offset, SEEK_SET)
533 or throw "Cannot seek forward to end of entry";
534  
535 # Set formatting back to normal
536 $: = " \n-";
537 }
538  
539 =head2 dump_genbank
540  
541 Arg [1] : Bio::EnsEMBL::Slice
542 Arg [2] : IO::File $FH
543 Example : $seq_dumper->dump_genbank($slice, $FH);
544 Description: Dumps a GENBANK flat file to an open file handle
545 Returntype : none
546 Exceptions : none
547 Caller : dump
548  
549 =cut
550  
551 sub dump_genbank {
552 my ($self, $slice, $FH) = @_;
553  
554 #line breaks are allowed near the end of the line on ' ', "\t", "\n", ','
555 $: = " \t\n-,";
556  
557 my $GENBANK_HEADER =
558 '^<<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<~~
559 ';
560  
561 my $GENBANK_SUBHEADER =
562 ' ^<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<~~
563 ';
564  
565 my $GENBANK_FT =
566 ' ^<<<<<<<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<~~
567 ';
568  
569 my $version;
570 my $acc;
571  
572 my $cs = $slice->coord_system();
573  
574 my $name_str = $cs->name() . ' ' . $slice->seq_region_name();
575  
576 $name_str .= ' ' . $cs->version if($cs->version);
577  
578 #determine if this slice is the entire seq region
579 #if it is then we just use the name as the id
580 my $slice_adaptor = $slice->adaptor();
581 my $full_slice =
582 $slice->adaptor->fetch_by_region($cs->name,
583 $slice->seq_region_name,
584 undef,undef,undef,
585 $cs->version);
586  
587  
588 my $entry_name = $slice->seq_region_name();
589  
590 if($full_slice->name eq $slice->name) {
591 $name_str .= ' full sequence';
592 $acc = $slice->seq_region_name();
593 my @acc_ver = split(/\./, $acc);
594 if(@acc_ver == 2) {
595 $acc = $acc_ver[0];
596 $version = $acc_ver[0] . $acc_ver[1];
597 } elsif(@acc_ver == 1 && $cs->version()) {
598 $version = $acc . $cs->version();
599 } else {
600 $version = $acc;
601 }
602 } else {
603 $name_str .= ' partial sequence';
604 $acc = $slice->name();
605 $version = $acc;
606 }
607  
608 $acc = $slice->name(); # to keep format consistent for all
609  
610 my $length = $slice->length;
611 my $start = $slice->start();
612 my $end = $slice->end();
613  
614 my $date = $self->_date_string;
615  
616 my $meta_container = $slice->adaptor()->db()->get_MetaContainer();
617  
618 # move at the end of file in case the file
619 # is open more than once (i.e. human chromosome Y,
620 # two chromosome slices
621 #
622 # WARNING
623 #
624 # When the file is open not for the first time,
625 # it must be in read/write mode
626 #
627 seek($FH, 0, SEEK_END);
628  
629 #LOCUS
630 my $tag = 'LOCUS';
631 my $value = "$entry_name $length bp DNA HTG $date";
632 $self->write($FH, $GENBANK_HEADER, $tag, $value);
633  
634 #DEFINITION
635 $tag = "DEFINITION";
636 $value = $meta_container->get_scientific_name() .
637 " $name_str $start..$end reannotated via EnsEMBL";
638 $self->write($FH, $GENBANK_HEADER, $tag, $value);
639  
640 #ACCESSION
641 $self->write($FH, $GENBANK_HEADER, 'ACCESSION', $acc);
642  
643 #VERSION
644 $self->write($FH, $GENBANK_HEADER, 'VERSION', $version);
645  
646 # KEYWORDS
647 $self->write($FH, $GENBANK_HEADER, 'KEYWORDS', '.');
648  
649 # SOURCE
650 my $common_name = $meta_container->get_common_name();
651 $common_name = $meta_container->get_scientific_name() unless $common_name;
652 $self->write($FH, $GENBANK_HEADER, 'SOURCE', $common_name);
653  
654 #organism
655 my @cls = @{$meta_container->get_classification()};
656 shift @cls;
657 $self->write($FH, $GENBANK_SUBHEADER, 'ORGANISM', $meta_container->get_scientific_name());
658 $self->write($FH, $GENBANK_SUBHEADER, '', join('; ', reverse @cls) . ".");
659  
660 #refereneces
661  
662 #comments
663 my $annotation_source = $self->annotation_source($meta_container);
664 foreach my $comment (@COMMENTS) {
665 $comment =~ s/\#\#\#SOURCE\#\#\#/$annotation_source/;
666 $self->write($FH, $GENBANK_HEADER, 'COMMENT', $comment);
667 }
668  
669 ####################
670 # DUMP FEATURE TABLE
671 ####################
672 $self->print( $FH, "FEATURES Location/Qualifiers\n" );
673 $self->_dump_feature_table($slice, $FH, $GENBANK_FT);
674  
675 ####################
676 # DUMP SEQUENCE
677 ####################
678  
679 # record position before writing sequence header, so that
680 # after printing the sequence and having the base counts
681 # we can seek to this position and write the proper sequence
682 # header
683 my $sq_offset = tell($FH);
684 $sq_offset == -1 and throw "Unable to get offset for output fh";
685  
686 # print a sequence header template, to be replaced with a real
687 # one containing the base counts
688 $self->print($FH, "BASE COUNT ########## a ########## c ########## g ########## t ########## n\nORIGIN\n");
689
690 # dump the sequence and get the base counts
691 my $acgt = $self->write_genbank_seq($slice, $FH);
692
693 # print the end of genbank entry
694 $self->print( $FH, "//\n" );
695 my $end_of_entry_offset = tell($FH);
696 $end_of_entry_offset == -1 and throw "Unable to get offset for output fh";
697  
698 # seek backwards to the position of the sequence header and
699 # write it with the actual base counts
700 seek($FH, $sq_offset, SEEK_SET)
701 or throw "Cannot seek backward to sequence header position";
702 $self->print($FH, sprintf "BASE COUNT %10d a %10d c %10d g %10d t %10d n",
703 $acgt->{a}, $acgt->{c}, $acgt->{g}, $acgt->{t}, $acgt->{n});
704  
705 seek($FH, $end_of_entry_offset, SEEK_SET)
706 or throw "Cannot seek forward to end of entry";
707  
708 # Set formatting back to normal
709 $: = " \n-";
710 }
711  
712  
713  
714 =head2 _dump_feature_table
715  
716 Arg [1] : Bio::EnsEMBL::Slice slice
717 Example : none
718 Description: Helper method used to dump feature tables used in EMBL, FASTA,
719 GENBANK. Assumes formating of file handle has been setup
720 already to use $FEAT and $VALUE values.
721 Returntype : none
722 Exceptions : none
723 Caller : internal
724  
725 =cut
726  
727 sub _dump_feature_table {
728 my $self = shift;
729 my $slice = shift;
730 my $FH = shift;
731 my $FORMAT = shift;
732  
733 #use only the core database to dump features (except for bloody snps)
734 my $lite = $slice->adaptor->db->remove_db_adaptor('lite');
735  
736 my $meta = $slice->adaptor->db->get_MetaContainer;
737  
738 #lump file handle and format string together for simpler method calls
739 my @ff = ($FH, $FORMAT);
740 my $value;
741  
742 #source
743 my $classification = join(', ', @{$meta->get_classification()});
744 $self->write(@ff,'source', "1.." . $slice->length());
745 $self->write(@ff,'' , '/organism="'.$meta->get_scientific_name(). '"');
746 $self->write(@ff,'' , '/db_xref="taxon:'.$meta->get_taxonomy_id().'"');
747  
748 #
749 # Transcripts & Genes
750 #
751 my @gene_slices;
752 if($self->is_enabled('gene')) {
753 push @gene_slices, $slice;
754 }
755  
756 # Retrieve slices of other database where we need to pull genes from
757  
758 my $gene_dbs = {'vegagene' => 'vega',
759 'estgene' => 'estgene'};
760  
761 foreach my $gene_type (keys %$gene_dbs) {
762 if($self->is_enabled($gene_type)) {
763 my $db = $self->get_database($gene_dbs->{$gene_type});
764 if($db) {
765 my $sa = $db->get_SliceAdaptor();
766 push @gene_slices, $sa->fetch_by_name($slice->name());
767 } else {
768 warning("A [". $gene_dbs->{$gene_type} ."] database must be " .
769 "attached to this SeqDumper\n(via a call to " .
770 "attach_database) to retrieve genes of type [$gene_type]");
771 }
772 }
773 }
774  
775 foreach my $gene_slice (@gene_slices) {
776 my @genes = @{$gene_slice->get_all_Genes(undef,undef, 1)};
777 while(my $gene = shift @genes) {
778 $value = $self->features2location( [$gene] );
779 $self->write( @ff, 'gene', $value );
780 $self->write( @ff, "", '/gene='.$gene->stable_id_version() );
781  
782  
783 if(defined($gene->display_xref)){
784 $self->write( @ff, "",'/locus_tag="'.$gene->display_xref->display_id.'"');
785 }
786 my $desc = $gene->description;
787 if(defined($desc) and $desc ne ""){
788 $desc =~ s/\"//;
789 $self->write( @ff, "", '/note="'.$gene->description.'"');
790 }
791  
792  
793  
794 foreach my $transcript (@{$gene->get_all_Transcripts}) {
795 my $translation = $transcript->translation;
796  
797 # normal transcripts get dumped differently than pseudogenes
798 if($translation) {
799 #normal transcript
800 $value = $self->features2location($transcript->get_all_Exons);
801 $self->write(@ff, 'mRNA', $value);
802 $self->write(@ff,'' , '/gene="'.$gene->stable_id_version().'"');
803 $self->write(@ff,''
804 ,'/standard_name="'.$transcript->stable_id_version().'"');
805  
806 # ...and a CDS section
807 $value =
808 $self->features2location($transcript->get_all_translateable_Exons);
809 $self->write(@ff,'CDS', $value);
810 my $codon_start = $self->transcript_to_codon_start($transcript);
811 $self->write(@ff,'' , qq{/codon_start="${codon_start}"}) if $codon_start > 1;
812  
813 my $codon_table_id = $self->_get_codon_table_id($slice);
814 if($codon_table_id > 1){
815 $self->write(@ff,'' , '/transl_table='.$codon_table_id);
816 }
817 $self->write(@ff,'' , '/gene="'.$gene->stable_id_version().'"');
818 $self->write(@ff,'' , '/protein_id="'.$translation->stable_id_version().'"');
819 $self->write(@ff,'' ,'/note="transcript_id='.$transcript->stable_id_version().'"');
820  
821 foreach my $dbl (@{$transcript->get_all_DBLinks}) {
822 my $db_xref = '/db_xref="'.$dbl->dbname().':'.$dbl->primary_id().'"';
823 my $go_db_xref = '/db_xref="'.$dbl->primary_id().'"';
824 $value = ($dbl->dbname()=~/GO/) ? $go_db_xref : $db_xref;
825 $self->write(@ff, '', $value);
826 }
827  
828 my $pep = $transcript->translate();
829 if ($pep) {
830 $value = '/translation="'.$pep->seq().'"';
831 $self->write(@ff, '', $value);
832 }
833 } else {
834 #pseudogene
835 $value = $self->features2location($transcript->get_all_Exons);
836 $self->write(@ff, 'misc_RNA', $value);
837 $self->write(@ff,'' , '/gene="'.$gene->stable_id_version().'"');
838 foreach my $dbl (@{$transcript->get_all_DBLinks}) {
839 $value = '/db_xref="'.$dbl->dbname().':'.$dbl->primary_id().'"';
840 $self->write(@ff, '', $value);
841 }
842 $self->write(@ff,'' , '/note="'.$transcript->biotype().'"');
843 $self->write(@ff,''
844 ,'/standard_name="'.$transcript->stable_id_version().'"');
845 }
846 }
847 }
848  
849 # exons
850 foreach my $gene (@{$gene_slice->get_all_Genes(undef,undef,1)}) {
851 foreach my $exon (@{$gene->get_all_Exons}) {
852 $self->write(@ff,'exon', $self->features2location([$exon]));
853 $self->write(@ff,'' , '/note="exon_id='.$exon->stable_id_version().'"');
854 }
855 }
856 }
857  
858 #
859 # genscans
860 #
861 if($self->is_enabled('genscan')) {
862 my @genscan_exons;
863 my @transcripts = @{$slice->get_all_PredictionTranscripts(undef,1)};
864 while(my $transcript = shift @transcripts) {
865 my $exons = $transcript->get_all_Exons();
866 push @genscan_exons, @$exons;
867 $self->write(@ff, 'mRNA', $self->features2location($exons));
868 $self->write(@ff, '', '/product="'.$transcript->translate()->seq().'"');
869 $self->write(@ff, '', '/note="identifier='.$transcript->stable_id_version.'"');
870 $self->write(@ff, '', '/note="Derived by automated computational' .
871 ' analysis using gene prediction method:' .
872 $transcript->analysis->logic_name . '"');
873 }
874 }
875  
876 #
877 # snps
878 #
879 if($self->is_enabled('variation') && $slice->can('get_all_VariationFeatures')) {
880 # $slice->adaptor->db->add_db_adaptor('lite', $lite) if $lite;
881  
882 my @variations = @{$slice->get_all_VariationFeatures()};
883 while(my $snp = shift @variations) {
884 my $ss = $snp->start;
885 my $se = $snp->end;
886 #skip snps that hang off edge of slice
887 next if($ss < 1 || $se > $slice->length);
888  
889 $self->write(@ff, 'variation', "$ss..$se");
890 $self->write(@ff, '' , '/replace="'.$snp->allele_string.'"');
891 #$self->write(@ff, '' , '/evidence="'.$snp->status.'"');
892 my $rs_id = $snp->variation_name();
893 my $db = $snp->source_name();
894 # foreach my $link ($snp->each_DBLink) {
895 # my $id = $link->primary_id;
896 # my $db = $link->database;
897 $self->write(@ff, '', "/db_xref=\"$db:$rs_id\"");
898 # }
899 }
900  
901 # $slice->adaptor->db->remove_db_adaptor('lite') if $lite;
902 }
903  
904 #
905 # similarity features
906 #
907 if($self->is_enabled('similarity')) {
908 foreach my $sim (@{$slice->get_all_SimilarityFeatures}) {
909 $self->write(@ff, 'misc_feature', $self->features2location([$sim]));
910 $self->write(@ff, '' , '/note="match: '.$sim->hseqname.
911 ' : '.$sim->hstart.'..'.$sim->hend.'('.$sim->hstrand.')"');
912 }
913 }
914  
915 #
916 # repeats
917 #
918 if($self->is_enabled('repeat')) {
919 my @rfs = @{$slice->get_all_RepeatFeatures()};
920  
921 while(my $repeat = shift @rfs) {
922 $self->write(@ff, 'repeat_region', $self->features2location([$repeat]));
923 $self->write(@ff, '' , '/note="' . $repeat->repeat_consensus->name.
924 ' repeat: matches ' . $repeat->hstart.'..'.$repeat->hend .
925 '('.$repeat->hstrand.') of consensus"');
926 }
927  
928 }
929  
930 #
931 # markers
932 #
933 if($self->is_enabled('marker') && $slice->can('get_all_MarkerFeatures')) {
934 my @markers = @{$slice->get_all_MarkerFeatures()};
935 while(my $mf = shift @markers) {
936 $self->write(@ff, 'STS', $self->features2location([$mf]));
937 if($mf->marker->display_MarkerSynonym) {
938 $self->write(@ff, '' , '/standard_name="' .
939 $mf->marker->display_MarkerSynonym->name . '"');
940 }
941  
942  
943 #grep out synonyms without a source
944 my @synonyms = @{$mf->marker->get_all_MarkerSynonyms};
945 @synonyms = grep {$_->source } @synonyms;
946 foreach my $synonym (@synonyms) {
947 $self->write(@ff, '', '/db_xref="'.$synonym->source.
948 ':'.$synonym->name.'"');
949 }
950 $self->write(@ff, '', '/note="map_weight='.$mf->map_weight.'"');
951 }
952 }
953  
954 #
955 # contigs
956 #
957 if($self->is_enabled('contig')) {
958 foreach my $segment (@{$slice->project('seqlevel')}) {
959 my ($start, $end, $slice) = @$segment;
960 $self->write(@ff, 'misc_feature',
961 $start .'..'. $end);
962 $self->write(@ff, '', '/note="contig '.$slice->seq_region_name .
963 ' ' . $slice->start . '..' . $slice->end .
964 '(' . $slice->strand . ')"');
965 }
966 }
967  
968 $slice->adaptor->db->add_db_adaptor('lite', $lite) if $lite;
969  
970 }
971  
972 # /codon_start= is the first base to start translating from. This maps
973 # Ensembl start exon phase to this concept. Here we present the usage
974 # of phase in this concept where each row shows the sequence the
975 # spliced_seq() method will return
976  
977 # 123456789
978 # ATTATGACG
979 # Phase == 0 ...+++### codon_start=0 // start from 1st A
980 # Phase == 1 ..+++### codon_start=3 // start from 2nd A (base 3 in the given spliced sequence)
981 # Phase == 2 .+++### codon_start=2 // start from 2nd A (base 2 in the spliced sequence)
982 #
983 # In the case of the final 2 phases we will generate a X codon
984 #
985  
986 sub transcript_to_codon_start {
987 my ($self, $transcript) = @_;
988 my $start_phase = $transcript->start_Exon()->phase();
989 return ( $start_phase == 1 ) ? 3 :
990 ( $start_phase == 2 ) ? 2 :
991 ( $start_phase == 0 ) ? 1 :
992 -1;
993 }
994  
995  
996 =head2 _get_codon_table_id
997  
998 Arg [1] : Bio::EnsEMBL::Slice slice
999 Example : none
1000 Description: Helper method to get codon_table seq region attribute
1001 codon_table defines the genetic code table used if other than the universal genetic code table (1)
1002 By default it is 1 and is not shown in flat files.
1003 If it is not equal to 1, then it is shown as a transl_table qualifier on the CDS feature.
1004 Returntype : int
1005 Caller : internal
1006  
1007 =cut
1008  
1009 sub _get_codon_table_id{
1010 my ($self, $slice) = @_;
1011 my $codon_table_id = 1;
1012 my $codon_table_attributes = $slice->get_all_Attributes("codon_table");
1013 if (@{$codon_table_attributes}) {
1014 $codon_table_id = $codon_table_attributes->[0]->value;
1015 }
1016 return $codon_table_id;
1017 }
1018  
1019 =head2 dump_fasta
1020  
1021 Arg [1] : Bio::EnsEMBL::Slice
1022 Arg [2] : IO::File $FH
1023 Example : $seq_dumper->dump_fasta($slice, $FH);
1024 Description: Dumps an FASTA flat file to an open file handle
1025 Returntype : none
1026 Exceptions : none
1027 Caller : dump
1028  
1029 =cut
1030  
1031 sub dump_fasta {
1032 my $self = shift;
1033 my $slice = shift;
1034 my $FH = shift;
1035  
1036 my $id = $slice->seq_region_name;
1037 my $seqtype = 'dna';
1038 my $idtype = $slice->coord_system->name;
1039 my $location = $slice->name;
1040 my $start = 1;
1041 my $end = $slice->length();
1042  
1043 my $header = ">$id $seqtype:$idtype $location\n";
1044 $self->print( $FH, $header );
1045  
1046 #set the formatting to FASTA
1047 my $FORMAT = '^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
1048 ';
1049  
1050 #chunk the sequence in 60kb chunks to use less memory
1051 my $cur = $start;
1052 while($cur <= $end) {
1053 my $to = $cur + 59_999;
1054 $to = $end if($to > $end);
1055 my $seq = $slice->subseq($cur, $to);
1056 $cur = $to + 1;
1057 $self->write($FH, $FORMAT, $seq);
1058 }
1059 }
1060  
1061  
1062  
1063 =head2 features2location
1064  
1065 Arg [1] : listref of Bio::EnsEMBL::SeqFeatures
1066 Example : $location = $self->features2location(\@features);
1067 Description: Constructs an EMBL location string from a list of features
1068 Returntype : string
1069 Exceptions : none
1070 Caller : internal
1071  
1072 =cut
1073  
1074 sub features2location {
1075 my $self = shift;
1076 my $features = shift;
1077  
1078 my @join = ();
1079  
1080 foreach my $f (@$features) {
1081 my $slice = $f->slice;
1082 my $start = $f->start();
1083 my $end = $f->end();
1084 my $strand = $f->strand();
1085  
1086 if($start >= 1 && $end <= $slice->length) {
1087 #this feature in on a slice and doesn't lie outside the boundary
1088
1089 if($strand == 1) {
1090 push @join, "$start..$end";
1091 } else {
1092 push @join, "complement($start..$end)";
1093 }
1094 } else {
1095 my @fs = ();
1096 #this feature is outside the boundary of the dump,
1097 # yet implemented and 'seqlevel' is guaranteed to be 1step
1098 my $projection = $f->project('seqlevel');
1099 foreach my $segment (@$projection) {
1100 my $slice = $segment->[2];
1101 my $slc_start = $slice->start();
1102 my $slc_end = $slice->end();
1103 my $seq_reg = $slice->seq_region_name();
1104 if($slice->strand == 1) {
1105 push @join, "$seq_reg:$slc_start..$slc_end";
1106 } else {
1107 push @join, "complement($seq_reg:$slc_start..$slc_end)";
1108 }
1109 }
1110 }
1111 }
1112  
1113 my $out = join ',', @join;
1114  
1115 if(scalar @join > 1) {
1116 $out = "join($out)";
1117 }
1118  
1119 return $out;
1120 }
1121  
1122 =head2 annotation_source
1123  
1124 Arg [1] : Bio::EnsEMBL::DBSQL::MetaContainer
1125 Example : $seq_dumper->annotation_source($meta_container);
1126 Description: Constructs a string with gene annotation sources
1127 Returntype : string
1128 Exceptions : none
1129 Caller : dump_embl, dump_genbank
1130  
1131 =cut
1132  
1133 sub annotation_source {
1134 my ($self, $meta_container) = @_;
1135  
1136 my @providers = ();
1137 my @provider_urls = ();
1138  
1139 foreach ( @{$meta_container->list_value_by_key('annotation.provider_name')} ) {
1140 push @providers, $_ if $_ ne '';
1141 }
1142 foreach ( @{$meta_container->list_value_by_key('annotation.provider_url')} ) {
1143 push @provider_urls, $_ if $_ ne '';
1144 }
1145 if ( ! scalar(@providers) ) {
1146 foreach ( @{$meta_container->list_value_by_key('assembly.provider_name')} ) {
1147 push @providers, $_ if $_ ne '';
1148 }
1149 foreach ( @{$meta_container->list_value_by_key('assembly.provider_url')} ) {
1150 push @provider_urls, $_ if $_ ne '';
1151 }
1152 }
1153 if ( ! scalar(@providers) ) {
1154 push @providers, 'Ensembl';
1155 }
1156  
1157 my $annotation_source = join(' and ', @providers);
1158 if (@provider_urls) {
1159 $annotation_source .= ' ' . sprintf(q{(%s)}, join(', ', @provider_urls));
1160 }
1161  
1162 return $annotation_source;
1163 }
1164  
1165 sub _date_string {
1166 my $self = shift;
1167  
1168 my ($sec, $min, $hour, $mday,$mon, $year) = localtime(time());
1169  
1170 my $month = ('JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL',
1171 'AUG', 'SEP', 'OCT', 'NOV', 'DEC')[$mon];
1172 $year += 1900;
1173
1174 return "$mday-$month-$year";
1175 }
1176  
1177 sub write {
1178 my ($self, $FH, $FORMAT, @values) = @_;
1179
1180 #while the last value still contains something
1181 while(defined($values[-1]) and $values[-1] ne '') {
1182 formline($FORMAT, @values);
1183 $self->print( $FH, $^A );
1184 $^A = '';
1185 }
1186 }
1187  
1188 sub write_genbank_seq {
1189 my $self = shift;
1190 my $FH = shift;
1191 my $seq = shift;
1192 my $base_total = shift;
1193  
1194 $base_total ||= 0;
1195  
1196 my $GENBANK_SEQ =
1197 '@>>>>>>>> ^<<<<<<<<< ^<<<<<<<<< ^<<<<<<<<< ^<<<<<<<<< ^<<<<<<<<< ^<<<<<<<<<~
1198 ';
1199  
1200 my $total = -59 + $base_total;
1201 #keep track of total and print lines of 60 bases with spaces every 10bp
1202 while($$seq) {
1203 $total += 60;
1204 formline($GENBANK_SEQ,$total, $$seq, $$seq, $$seq, $$seq, $$seq, $$seq);
1205 $self->print( $FH, $^A );
1206 $^A = '';
1207 }
1208 }
1209  
1210 sub write_genbank_seq {
1211 my $self = shift;
1212 my $slice = shift;
1213 my $FH = shift;
1214  
1215 my $width = 60;
1216  
1217 # set buffer size
1218 my $chunk_size = $self->{'chunk_factor'} * $width;
1219 $chunk_size > 0 or throw "Invalid chunk size: check chunk_factor parameter";
1220  
1221 my $start = 1;
1222 my $end = $slice->length;
1223 my $total = -59;
1224  
1225 # chunk the sequence to conserve memory, and print
1226 my $here = $start;
1227 my $GENBANK_SEQ =
1228 '@>>>>>>>> ^<<<<<<<<< ^<<<<<<<<< ^<<<<<<<<< ^<<<<<<<<< ^<<<<<<<<< ^<<<<<<<<<~
1229 ';
1230 my $acgt;
1231  
1232 while($here <= $end) {
1233 my $there = $here + $chunk_size - 1;
1234 $there = $end if($there > $end);
1235 my $sseq = $slice->subseq($here, $there);
1236  
1237 $acgt->{a} += $sseq =~ tr/Aa//;
1238 $acgt->{c} += $sseq =~ tr/Cc//;
1239 $acgt->{g} += $sseq =~ tr/Gg//;
1240 $acgt->{t} += $sseq =~ tr/Tt//;
1241  
1242 while($sseq) {
1243 $total += 60;
1244 formline($GENBANK_SEQ, $total, $sseq, $sseq, $sseq, $sseq, $sseq, $sseq);
1245 $self->print($FH, $^A);
1246 $^A = '';
1247 }
1248  
1249 $here = $there + 1;
1250 }
1251  
1252 $acgt->{n} = $end - ($acgt->{a} + $acgt->{c} + $acgt->{g} + $acgt->{t});
1253 $acgt->{tot} = $end;
1254  
1255 return $acgt;
1256 }
1257  
1258  
1259 sub write_embl_seq {
1260 my $self = shift;
1261 my $slice = shift;
1262 my $FH = shift;
1263  
1264 my $width = 60;
1265  
1266 # set buffer size
1267 my $chunk_size = $self->{'chunk_factor'} * $width;
1268 $chunk_size > 0 or throw "Invalid chunk size: check chunk_factor parameter";
1269  
1270 my $start = 1;
1271 my $end = $slice->length;
1272 my $total = $end;
1273  
1274 # chunk the sequence to conserve memory, and print
1275 my $here = $start;
1276 my $EMBL_SEQ =
1277 ' ^<<<<<<<<< ^<<<<<<<<< ^<<<<<<<<< ^<<<<<<<<< ^<<<<<<<<< ^<<<<<<<<< @>>>>>>>>>~
1278 ';
1279 my $acgt;
1280  
1281 while($here <= $end) {
1282 my $there = $here + $chunk_size - 1;
1283 $there = $end if($there > $end);
1284 my $sseq = $slice->subseq($here, $there);
1285  
1286 $acgt->{a} += $sseq =~ tr/Aa//;
1287 $acgt->{c} += $sseq =~ tr/Cc//;
1288 $acgt->{g} += $sseq =~ tr/Gg//;
1289 $acgt->{t} += $sseq =~ tr/Tt//;
1290  
1291 while($sseq) {
1292 $total -= 60;
1293 $total = 0 if $total < 0;
1294 formline($EMBL_SEQ,
1295 $sseq, $sseq, $sseq, $sseq, $sseq, $sseq,
1296 $end - $total);
1297 $self->print($FH, $^A);
1298 $^A = '';
1299 }
1300  
1301 $here = $there + 1;
1302 }
1303  
1304 $acgt->{n} = $end - ($acgt->{a} + $acgt->{c} + $acgt->{g} + $acgt->{t});
1305 $acgt->{tot} = $end;
1306  
1307 return $acgt;
1308 }
1309  
1310 sub print {
1311 my( $self, $FH, $string ) = @_;
1312 if(!print $FH $string){
1313 print STDERR "Problem writing to disk\n";
1314 print STDERR "the string is $string\n";
1315 die "Could not write to file handle";
1316 }
1317 }
1318  
1319  
1320 1;