EnsEMBL/IdMapping/InternalIdMapper.pm untested

filter: Statementstmt 0.0% 0 / 279 Branchbran 0.0% 0 / 80 Conditioncond 0.0% 0 / 60 Subroutinesub 0.0% 0 / 20 Podpod 0.0% 0 / 10 totaltotal 0.0% 0 / 449 CC 41 SCAR 36.9
CC
41
Cov
0%
map_genes
56.0
map_transcripts
56.0
map_exons
56.0
CRAP 40.0
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 =head1 SYNOPSIS
34  
35 =head1 DESCRIPTION
36  
37 =head1 METHODS
38  
39 =cut
40  
41  
42 package Bio::EnsEMBL::IdMapping::InternalIdMapper;
43 $Bio::EnsEMBL::IdMapping::InternalIdMapper::VERSION = '114.0.0_50'; # TRIAL
44 $Bio::EnsEMBL::IdMapping::InternalIdMapper::VERSION = '114.0.050';
45 use strict;
46 use warnings;
47 no warnings 'uninitialized';
48  
49 use Bio::EnsEMBL::IdMapping::BaseObject;
50 our @ISA = qw(Bio::EnsEMBL::IdMapping::BaseObject);
51  
52 use Bio::EnsEMBL::Utils::Exception qw(throw warning);
53 use Bio::EnsEMBL::Utils::ScriptUtils qw(inject path_append);
54 use Bio::EnsEMBL::IdMapping::Entry;
55 use Bio::EnsEMBL::IdMapping::MappingList;
56 use Bio::EnsEMBL::IdMapping::SyntenyFramework;
57  
58  
59 # scores are considered the same if (2.0 * (s1-s2))/(s1 + s2) < this
60 use constant SIMILAR_SCORE_RATIO => 0.01;
61  
62
63 sub map_genes {
64 my $self = shift;
65 my $gene_scores = shift;
66 my $transcript_scores = shift;
67 my $gsb = shift;
68  
69 # argument checks
70 unless ($gene_scores and
71 $gene_scores->isa('Bio::EnsEMBL::IdMapping::ScoredMappingMatrix')) {
72 throw('Need a gene Bio::EnsEMBL::IdMapping::ScoredMappingMatrix.');
73 }
74
75 unless ($transcript_scores and
76 $transcript_scores->isa('Bio::EnsEMBL::IdMapping::ScoredMappingMatrix')) {
77 throw('Need a transcript Bio::EnsEMBL::IdMapping::ScoredMappingMatrix.');
78 }
79  
80 unless ($gsb and
81 $gsb->isa('Bio::EnsEMBL::IdMapping::GeneScoreBuilder')) {
82 throw('Need a Bio::EnsEMBL::IdMapping::GeneScoreBuilder.');
83 }
84
85 $self->logger->info("== Internal ID mapping for genes...\n\n", 0, 'stamped');
86  
87 my $dump_path = path_append($self->conf->param('basedir'), 'mapping');
88  
89 my $mappings = Bio::EnsEMBL::IdMapping::MappingList->new(
90 -DUMP_PATH => $dump_path,
91 -CACHE_FILE => 'gene_mappings.ser',
92 );
93  
94 my $mapping_cache = $mappings->cache_file;
95  
96 if (-s $mapping_cache) {
97
98 # read from file
99 $self->logger->info("Reading gene mappings from file...\n", 0, 'stamped');
100 $self->logger->debug("Cache file $mapping_cache.\n", 1);
101 $mappings->read_from_file;
102 $self->logger->info("Done.\n\n", 0, 'stamped');
103
104 } else {
105
106 # create gene mappings
107 $self->logger->info("No gene mappings found. Will calculate them now.\n");
108  
109 # determine which plugin methods to run
110 my @default_plugins = (qw(
111 Bio::EnsEMBL::IdMapping::InternalIdMapper::EnsemblGeneGeneric::init_basic
112 Bio::EnsEMBL::IdMapping::InternalIdMapper::EnsemblGeneGeneric::location
113 Bio::EnsEMBL::IdMapping::InternalIdMapper::EnsemblGeneGeneric::best_transcript
114 Bio::EnsEMBL::IdMapping::InternalIdMapper::EnsemblGeneGeneric::biotype
115 Bio::EnsEMBL::IdMapping::InternalIdMapper::EnsemblGeneGeneric::synteny
116 Bio::EnsEMBL::IdMapping::InternalIdMapper::EnsemblGeneGeneric::internal_id
117 ));
118  
119 my @plugins = $self->conf->param('plugin_internal_id_mappers_gene');
120 @plugins = @default_plugins unless (defined($plugins[0]));
121  
122 my $new_mappings = Bio::EnsEMBL::IdMapping::MappingList->new(
123 -DUMP_PATH => $dump_path,
124 -CACHE_FILE => 'gene_mappings0.ser',
125 );
126 my @mappings = ();
127 my $i = 0;
128  
129 #
130 # run the scoring chain
131 #
132 foreach my $plugin (@plugins) {
133 ($gene_scores, $new_mappings) = $self->delegate_to_plugin($plugin, $i++,
134 $gsb, $new_mappings, $gene_scores, $transcript_scores);
135  
136 push(@mappings, $new_mappings);
137 }
138  
139 # report remaining ambiguities
140 $self->logger->info($gene_scores->get_source_count.
141 " source genes are ambiguous with ".
142 $gene_scores->get_target_count." target genes.\n\n");
143  
144 $self->log_ambiguous($gene_scores, 'gene');
145
146 # merge mappings and write to file
147 $mappings->add_all(@mappings);
148 $mappings->write_to_file;
149  
150 if ($self->logger->loglevel eq 'debug') {
151 $mappings->log('gene', $self->conf->param('basedir'));
152 }
153  
154 $self->logger->info("Done.\n\n", 0, 'stamped');
155  
156 }
157  
158 return $mappings;
159 }
160  
161  
162 sub map_transcripts {
163 my $self = shift;
164 my $transcript_scores = shift;
165 my $gene_mappings = shift;
166 my $tsb = shift;
167  
168 # argument checks
169 unless ($transcript_scores and
170 $transcript_scores->isa('Bio::EnsEMBL::IdMapping::ScoredMappingMatrix')) {
171 throw('Need a transcript Bio::EnsEMBL::IdMapping::ScoredMappingMatrix.');
172 }
173  
174 unless ($gene_mappings and
175 $gene_mappings->isa('Bio::EnsEMBL::IdMapping::MappingList')) {
176 throw('Need a gene Bio::EnsEMBL::IdMapping::MappingList.');
177 }
178
179 unless ($tsb and
180 $tsb->isa('Bio::EnsEMBL::IdMapping::TranscriptScoreBuilder')) {
181 throw('Need a Bio::EnsEMBL::IdMapping::TranscriptScoreBuilder.');
182 }
183
184 $self->logger->info("== Internal ID mapping for transcripts...\n\n", 0, 'stamped');
185  
186 my $dump_path = path_append($self->conf->param('basedir'), 'mapping');
187  
188 my $mappings = Bio::EnsEMBL::IdMapping::MappingList->new(
189 -DUMP_PATH => $dump_path,
190 -CACHE_FILE => 'transcript_mappings.ser',
191 );
192  
193 my $mapping_cache = $mappings->cache_file;
194  
195 if (-s $mapping_cache) {
196
197 # read from file
198 $self->logger->info("Reading transcript mappings from file...\n", 0,
199 'stamped');
200 $self->logger->debug("Cache file $mapping_cache.\n", 1);
201 $mappings->read_from_file;
202 $self->logger->info("Done.\n\n", 0, 'stamped');
203
204 } else {
205
206 # create transcript mappings
207 $self->logger->info("No transcript mappings found. Will calculate them now.\n");
208  
209 # determine which plugin methods to run
210 my @default_plugins = (qw(
211 Bio::EnsEMBL::IdMapping::InternalIdMapper::EnsemblTranscriptGeneric::init_basic
212 Bio::EnsEMBL::IdMapping::InternalIdMapper::EnsemblTranscriptGeneric::non_exact_translation
213 Bio::EnsEMBL::IdMapping::InternalIdMapper::EnsemblTranscriptGeneric::biotype
214 Bio::EnsEMBL::IdMapping::InternalIdMapper::EnsemblTranscriptGeneric::mapped_gene
215 Bio::EnsEMBL::IdMapping::InternalIdMapper::EnsemblTranscriptGeneric::single_gene
216 Bio::EnsEMBL::IdMapping::InternalIdMapper::EnsemblTranscriptGeneric::internal_id
217 ));
218  
219 my @plugins = $self->conf->param('plugin_internal_id_mappers_transcript');
220 @plugins = @default_plugins unless (defined($plugins[0]));
221  
222 my $new_mappings = Bio::EnsEMBL::IdMapping::MappingList->new(
223 -DUMP_PATH => $dump_path,
224 -CACHE_FILE => 'transcript_mappings0.ser',
225 );
226 my @mappings = ();
227 my $i = 0;
228  
229 #
230 # run the scoring chain
231 #
232 foreach my $plugin (@plugins) {
233 ($transcript_scores, $new_mappings) = $self->delegate_to_plugin($plugin,
234 $i++, $tsb, $new_mappings, $transcript_scores, $gene_mappings);
235  
236 push(@mappings, $new_mappings);
237 }
238  
239 # report remaining ambiguities
240 $self->logger->info($transcript_scores->get_source_count.
241 " source transcripts are ambiguous with ".
242 $transcript_scores->get_target_count." target transcripts.\n\n");
243  
244 $self->log_ambiguous($transcript_scores, 'transcript');
245  
246 # merge mappings and write to file
247 $mappings->add_all(@mappings);
248 $mappings->write_to_file;
249  
250 if ($self->logger->loglevel eq 'debug') {
251 $mappings->log('transcript', $self->conf->param('basedir'));
252 }
253  
254 $self->logger->info("Done.\n\n", 0, 'stamped');
255  
256 }
257  
258 return $mappings;
259  
260 }
261  
262  
263 sub map_exons {
264 my $self = shift;
265 my $exon_scores = shift;
266 my $transcript_mappings = shift;
267 my $esb = shift;
268  
269 # argument checks
270 unless ($exon_scores and
271 $exon_scores->isa('Bio::EnsEMBL::IdMapping::ScoredMappingMatrix')) {
272 throw('Need a Bio::EnsEMBL::IdMapping::ScoredMappingMatrix of exons.');
273 }
274  
275 unless ($transcript_mappings and
276 $transcript_mappings->isa('Bio::EnsEMBL::IdMapping::MappingList')) {
277 throw('Need a Bio::EnsEMBL::IdMapping::MappingList of transcripts.');
278 }
279
280 unless ($esb and
281 $esb->isa('Bio::EnsEMBL::IdMapping::ExonScoreBuilder')) {
282 throw('Need a Bio::EnsEMBL::IdMapping::ExonScoreBuilder.');
283 }
284
285 $self->logger->info("== Internal ID mapping for exons...\n\n", 0, 'stamped');
286  
287 my $dump_path = path_append($self->conf->param('basedir'), 'mapping');
288  
289 my $mappings = Bio::EnsEMBL::IdMapping::MappingList->new(
290 -DUMP_PATH => $dump_path,
291 -CACHE_FILE => 'exon_mappings.ser',
292 );
293  
294 my $mapping_cache = $mappings->cache_file;
295  
296 if (-s $mapping_cache) {
297
298 # read from file
299 $self->logger->info("Reading exon mappings from file...\n", 0,
300 'stamped');
301 $self->logger->debug("Cache file $mapping_cache.\n", 1);
302 $mappings->read_from_file;
303 $self->logger->info("Done.\n\n", 0, 'stamped');
304
305 } else {
306
307 # create exon mappings
308 $self->logger->info("No exon mappings found. Will calculate them now.\n");
309  
310 # determine which plugin methods to run
311 my @default_plugins = (qw(
312 Bio::EnsEMBL::IdMapping::InternalIdMapper::EnsemblExonGeneric::init_basic
313 Bio::EnsEMBL::IdMapping::InternalIdMapper::EnsemblExonGeneric::mapped_transcript
314 Bio::EnsEMBL::IdMapping::InternalIdMapper::EnsemblExonGeneric::single_transcript
315 Bio::EnsEMBL::IdMapping::InternalIdMapper::EnsemblExonGeneric::internal_id
316 ));
317  
318 my @plugins = $self->conf->param('plugin_internal_id_mappers_exon');
319 @plugins = @default_plugins unless (defined($plugins[0]));
320  
321 my $new_mappings = Bio::EnsEMBL::IdMapping::MappingList->new(
322 -DUMP_PATH => $dump_path,
323 -CACHE_FILE => 'exon_mappings0.ser',
324 );
325 my @mappings = ();
326 my $i = 0;
327  
328 #
329 # run the scoring chain
330 #
331 foreach my $plugin (@plugins) {
332 ($exon_scores, $new_mappings) = $self->delegate_to_plugin($plugin, $i++,
333 $esb, $new_mappings, $exon_scores, $transcript_mappings);
334  
335 push(@mappings, $new_mappings);
336 }
337  
338 # report remaining ambiguities
339 $self->logger->info($exon_scores->get_source_count.
340 " source exons are ambiguous with ".
341 $exon_scores->get_target_count." target exons.\n\n");
342  
343 $self->log_ambiguous($exon_scores, 'exon');
344  
345 # merge mappings and write to file
346 $mappings->add_all(@mappings);
347 $mappings->write_to_file;
348  
349 if ($self->logger->loglevel eq 'debug') {
350 $mappings->log('exon', $self->conf->param('basedir'));
351 }
352  
353 $self->logger->info("Done.\n\n", 0, 'stamped');
354  
355 }
356  
357 return $mappings;
358  
359 }
360  
361  
362 #
363 # this is not implemented as a plugin, since a) it's too simple and b) it's
364 # tied to transcripts so there are no translation scores or score builder.
365 #
366 sub map_translations {
367 my $self = shift;
368 my $transcript_mappings = shift;
369  
370 # argument checks
371 unless ($transcript_mappings and
372 $transcript_mappings->isa('Bio::EnsEMBL::IdMapping::MappingList')) {
373 throw('Need a Bio::EnsEMBL::IdMapping::MappingList of transcripts.');
374 }
375
376 $self->logger->info("== Internal ID mapping for translations...\n\n", 0, 'stamped');
377  
378 my $dump_path = path_append($self->conf->param('basedir'), 'mapping');
379  
380 my $mappings = Bio::EnsEMBL::IdMapping::MappingList->new(
381 -DUMP_PATH => $dump_path,
382 -CACHE_FILE => 'translation_mappings.ser',
383 );
384  
385 my $mapping_cache = $mappings->cache_file;
386  
387 if (-s $mapping_cache) {
388
389 # read from file
390 $self->logger->info("Reading translation mappings from file...\n", 0,
391 'stamped');
392 $self->logger->debug("Cache file $mapping_cache.\n", 1);
393 $mappings->read_from_file;
394 $self->logger->info("Done.\n\n", 0, 'stamped');
395
396 } else {
397
398 # create translation mappings
399 $self->logger->info("No translation mappings found. Will calculate them now.\n");
400  
401 $self->logger->info("Translation mapping...\n", 0, 'stamped');
402  
403 #
404 # map translations for mapped transcripts
405 #
406 my $i = 0;
407  
408 foreach my $entry (@{ $transcript_mappings->get_all_Entries }) {
409  
410 my $source_tl = $self->cache->get_by_key('transcripts_by_id',
411 'source', $entry->source)->translation;
412 my $target_tl = $self->cache->get_by_key('transcripts_by_id',
413 'target', $entry->target)->translation;
414  
415 if ($source_tl and $target_tl) {
416
417 # add mapping for the translations; note that the score is taken from
418 # the transcript mapping
419 my $tl_entry = Bio::EnsEMBL::IdMapping::Entry->new_fast([
420 $source_tl->id, $target_tl->id, $entry->score
421 ]);
422 $mappings->add_Entry($tl_entry);
423
424 } else {
425 $i++;
426 }
427  
428 }
429  
430 $self->logger->debug("Skipped transcripts without translation: $i\n", 1);
431 $self->logger->info("New mappings: ".$mappings->get_entry_count."\n\n");
432  
433 $mappings->write_to_file;
434  
435 if ($self->logger->loglevel eq 'debug') {
436 $mappings->log('translation', $self->conf->param('basedir'));
437 }
438  
439 $self->logger->info("Done.\n\n", 0, 'stamped');
440  
441 }
442  
443 return $mappings;
444  
445 }
446  
447  
448 sub delegate_to_plugin {
449 my $self = shift;
450 my $plugin = shift;
451 my $num = shift;
452 my $score_builder = shift;
453 my $mappings = shift;
454 my $scores = shift;
455  
456 # argument checks
457 unless ($score_builder and
458 $score_builder->isa('Bio::EnsEMBL::IdMapping::ScoreBuilder')) {
459 throw('Need a Bio::EnsEMBL::IdMapping::ScoreBuilder.');
460 }
461  
462 unless ($mappings and
463 $mappings->isa('Bio::EnsEMBL::IdMapping::MappingList')) {
464 throw('Need a Bio::EnsEMBL::IdMapping::MappingList.');
465 }
466
467 unless ($scores and
468 $scores->isa('Bio::EnsEMBL::IdMapping::ScoredMappingMatrix')) {
469 throw('Need a Bio::EnsEMBL::IdMapping::ScoredMappingMatrix.');
470 }
471  
472 # split plugin name into module and method
473 $plugin =~ /(.*)::(\w+)$/;
474 my $module = $1;
475 my $method = $2;
476  
477 unless ($module and $method) {
478 throw("Unable to determine module and method name from $plugin.\n");
479 }
480  
481 # instantiate the plugin unless we already have an instance
482 my $plugin_instance;
483 if ($self->has_plugin($module)) {
484
485 # re-use an existing plugin instance
486 $plugin_instance = $self->get_plugin($module);
487
488 } else {
489
490 # inject and instantiate the plugin module
491 inject($module);
492 $plugin_instance = $module->new(
493 -LOGGER => $self->logger,
494 -CONF => $self->conf,
495 -CACHE => $self->cache
496 );
497 $self->add_plugin($plugin_instance);
498  
499 }
500  
501 # run the method on the plugin
502 #
503 # pass in a sequence number (number of method run, used for generating
504 # checkpoint files), the scores used for determining the mapping, and all
505 # other arguments passed to this method (these will vary for different object
506 # types)
507 #
508 # return the scores and mappings to feed into the next plugin in the chain
509 return $plugin_instance->$method($num, $score_builder, $mappings, $scores, @_);
510 }
511  
512  
513 sub has_plugin {
514 my $self = shift;
515 my $module = shift;
516  
517 defined($self->{'_plugins'}->{$module}) ? (return 1) : (return 0);
518 }
519  
520  
521 sub get_plugin {
522 my $self = shift;
523 my $module = shift;
524  
525 return $self->{'_plugins'}->{$module};
526 }
527  
528  
529 sub add_plugin {
530 my $self = shift;
531 my $plugin_instance = shift;
532  
533 $self->{'_plugins'}->{ref($plugin_instance)} = $plugin_instance;
534 }
535  
536  
537 sub log_ambiguous {
538 my $self = shift;
539 my $matrix = shift;
540 my $type = shift;
541  
542 unless ($matrix and
543 $matrix->isa('Bio::EnsEMBL::IdMapping::ScoredMappingMatrix')) {
544 throw('Need a Bio::EnsEMBL::IdMapping::ScoredMappingMatrix.');
545 }
546
547 # create dump directory if it doesn't exist
548 my $debug_path = $self->conf->param('basedir').'/debug';
549 unless (-d $debug_path) {
550 system("mkdir -p $debug_path") == 0 or
551 throw("Unable to create directory $debug_path.\n");
552 }
553
554 my $logfile = "$debug_path/ambiguous_${type}.txt";
555
556 open(my $fh, '>', $logfile) or
557 throw("Unable to open $logfile for writing: $!");
558  
559 my @low_scoring = ();
560 my @high_scoring = ();
561 my $last_id;
562  
563 # log by source
564 foreach my $entry (sort { $a->source <=> $b->source }
565 @{ $matrix->get_all_Entries }) {
566
567 $last_id ||= $entry->target;
568  
569 if ($last_id != $entry->source) {
570 $self->write_ambiguous($type, 'source', $fh, \@low_scoring,
571 \@high_scoring);
572 $last_id = $entry->source;
573 }
574
575 if ($entry->score < 0.5) {
576 push @low_scoring, $entry;
577 } else {
578 push @high_scoring, $entry;
579 }
580 }
581  
582 # write last source
583 $self->write_ambiguous($type, 'source', $fh, \@low_scoring, \@high_scoring);
584  
585 # now do the same by target
586 $last_id = undef;
587 foreach my $entry (sort { $a->target <=> $b->target }
588 @{ $matrix->get_all_Entries }) {
589  
590 $last_id ||= $entry->target;
591  
592 if ($last_id != $entry->target) {
593 $self->write_ambiguous($type, 'target', $fh, \@low_scoring,
594 \@high_scoring);
595 $last_id = $entry->target;
596 }
597
598 if ($entry->score < 0.5) {
599 push @low_scoring, $entry;
600 } else {
601 push @high_scoring, $entry;
602 }
603 }
604  
605 # write last target
606 $self->write_ambiguous($type, 'target', $fh, \@low_scoring, \@high_scoring);
607  
608 close($fh);
609 }
610  
611  
612 sub write_ambiguous {
613 my ($self, $type, $db_type, $fh, $low, $high) = @_;
614
615 # if only source or target are ambiguous (i.e. you have only one mapping from
616 # this perspective) then log from the other perspective
617 if (scalar(@$low) + scalar(@$high) <= 1) {
618 @$low = ();
619 @$high = ();
620 return;
621 }
622  
623 my $first_id;
624 if (@$low) {
625 $first_id = $low->[0]->$db_type;
626 } else {
627 $first_id = $high->[0]->$db_type;
628 }
629  
630 my $other_db_type;
631 if ($db_type eq 'source') {
632 $other_db_type = 'target';
633 } else {
634 $other_db_type = 'source';
635 }
636  
637 print $fh "$db_type $type $first_id scores ambiguously:\n";
638  
639 # high scorers
640 if (@$high) {
641 print $fh " high scoring ${other_db_type}s\n";
642  
643 while (my $e = shift(@$high)) {
644 print $fh " ", $e->$other_db_type, " ", $e->score, "\n";
645 }
646 }
647  
648 # low scorers
649 if (@$low) {
650 print $fh " low scoring ${other_db_type}s\n ";
651  
652 my $i = 1;
653  
654 while (my $e = shift(@$low)) {
655 print $fh "\n " unless (($i++)%10);
656 print $fh $e->$other_db_type, ", ";
657 }
658 print $fh "\n";
659 }
660  
661 print $fh "\n";
662 }
663  
664  
665 1;
666