EnsEMBL/IdMapping/TranscriptScoreBuilder.pm untested

filter: Statementstmt 0.0% 0 / 209 Branchbran 0.0% 0 / 56 Conditioncond 0.0% 0 / 47 Subroutinesub 0.0% 0 / 16 Podpod 0.0% 0 / 9 totaltotal 0.0% 0 / 337 CC 29 SCAR 43.3
CC
29
Cov
0%
score_matrix_from_flag_matrix
210.0
different_translation_rescore
30.0
non_mapped_gene_rescore
20.0
CRAP 75.7
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  
34 =head1 SYNOPSIS
35  
36  
37 =head1 DESCRIPTION
38  
39 Combines ExonScoreBuilder, ExonDirectMapper and ExonerateRunner from
40 Java application.
41  
42 =head1 METHODS
43  
44 =cut
45  
46 package Bio::EnsEMBL::IdMapping::TranscriptScoreBuilder;
47 $Bio::EnsEMBL::IdMapping::TranscriptScoreBuilder::VERSION = '114.0.0_50'; # TRIAL
48 $Bio::EnsEMBL::IdMapping::TranscriptScoreBuilder::VERSION = '114.0.050';
49 use strict;
50 use warnings;
51 no warnings 'uninitialized';
52  
53 use Bio::EnsEMBL::IdMapping::ScoreBuilder;
54 our @ISA = qw(Bio::EnsEMBL::IdMapping::ScoreBuilder);
55  
56 use Bio::EnsEMBL::Utils::Exception qw(throw warning);
57 use Bio::EnsEMBL::Utils::ScriptUtils qw(path_append);
58 use Bio::EnsEMBL::IdMapping::ScoredMappingMatrix;
59  
60  
61 sub score_transcripts {
62 my $self = shift;
63 my $exon_matrix = shift;
64  
65 unless ($exon_matrix and
66 $exon_matrix->isa('Bio::EnsEMBL::IdMapping::ScoredMappingMatrix')) {
67 throw('Need a Bio::EnsEMBL::IdMapping::ScoredMappingMatrix.');
68 }
69  
70 $self->logger->info("-- Scoring transcripts...\n\n", 0, 'stamped');
71  
72 # build scores based on exon scores
73 my $matrix = $self->scores_from_exon_scores($exon_matrix);
74  
75 # debug logging
76 if ($self->logger->loglevel eq 'debug') {
77 $matrix->log('transcript', $self->conf->param('basedir'));
78 }
79  
80 # log stats of combined matrix
81 my $fmt = "%-40s%10.0f\n";
82  
83 $self->logger->info("Scoring matrix:\n");
84  
85 $self->logger->info(sprintf($fmt, "Total source transcripts:",
86 $self->cache->get_count_by_name('transcripts_by_id', 'source')), 1);
87  
88 $self->logger->info(sprintf($fmt, "Total target transcripts:",
89 $self->cache->get_count_by_name('transcripts_by_id', 'target')), 1);
90  
91 $self->log_matrix_stats($matrix);
92
93 $self->logger->info("\nDone with transcript scoring.\n\n");
94  
95 return $matrix;
96 }
97  
98  
99 sub scores_from_exon_scores {
100 my $self = shift;
101 my $exon_matrix = shift;
102  
103 unless ($exon_matrix and
104 $exon_matrix->isa('Bio::EnsEMBL::IdMapping::ScoredMappingMatrix')) {
105 throw('Need a Bio::EnsEMBL::IdMapping::ScoredMappingMatrix.');
106 }
107
108 my $dump_path = path_append($self->conf->param('basedir'), 'matrix');
109
110 my $matrix = Bio::EnsEMBL::IdMapping::ScoredMappingMatrix->new(
111 -DUMP_PATH => $dump_path,
112 -CACHE_FILE => 'transcript_matrix.ser',
113 );
114  
115 my $transcript_cache = $matrix->cache_file;
116  
117 if (-s $transcript_cache) {
118
119 # read from file
120 $self->logger->info("Reading transcript scoring matrix from file...\n", 0, 'stamped');
121 $self->logger->debug("Cache file $transcript_cache.\n", 1);
122 $matrix->read_from_file;
123 $self->logger->info("Done.\n\n", 0, 'stamped');
124
125 } else {
126
127 # build scoring matrix
128 $self->logger->info("No transcript scoring matrix found. Will build new one.\n");
129  
130 $self->logger->info("Transcript scoring...\n", 0, 'stamped');
131 $matrix = $self->build_scores($matrix, $exon_matrix);
132 $self->logger->info("Done.\n\n", 0, 'stamped');
133  
134 # write scoring matrix to file
135 $matrix->write_to_file;
136  
137 }
138  
139 return $matrix;
140 }
141  
142  
143 sub build_scores {
144 my $self = shift;
145 my $matrix = shift;
146 my $exon_matrix = shift;
147  
148 unless ($matrix and
149 $matrix->isa('Bio::EnsEMBL::IdMapping::ScoredMappingMatrix')) {
150 throw('Need a transcript Bio::EnsEMBL::IdMapping::ScoredMappingMatrix.');
151 }
152
153 unless ($exon_matrix and
154 $exon_matrix->isa('Bio::EnsEMBL::IdMapping::ScoredMappingMatrix')) {
155 throw('Need a exon Bio::EnsEMBL::IdMapping::ScoredMappingMatrix.');
156 }
157  
158 # first find out which source and target transcripts have scoring exons and
159 # build a "flag" matrix for these transcripts (all scores are 1)
160 $self->flag_matrix_from_exon_scores($matrix, $exon_matrix);
161  
162 # now calculate the actual scores for the transcripts in the flag matrix
163 my $final_matrix =
164 $self->score_matrix_from_flag_matrix($matrix, $exon_matrix);
165
166 return $final_matrix;
167 }
168  
169  
170 sub flag_matrix_from_exon_scores {
171 my $self = shift;
172 my $matrix = shift;
173 my $exon_matrix = shift;
174  
175 # initialise progress logger
176 my $i;
177 my $num_transcripts =
178 scalar(keys %{ $self->cache->get_by_name('transcripts_by_id', 'source') });
179 my $progress_id = $self->logger->init_progress($num_transcripts, 100);
180  
181 $self->logger->info("Creating flag matrix...\n", 1);
182  
183 # loop over source transcripts
184 foreach my $source_transcript (values %{ $self->cache->get_by_name('transcripts_by_id', 'source') }) {
185
186 # log progress
187 $self->logger->log_progress($progress_id, ++$i, 1);
188  
189 # get all exons for the source transcript
190 foreach my $source_exon (@{ $source_transcript->get_all_Exons }) {
191  
192 # get target exons for this source exon from scoring matrix
193 foreach my $target_exon_id (@{ $exon_matrix->get_targets_for_source($source_exon->id) }) {
194  
195 # get target transcripts that contain this exon
196 foreach my $target_transcript (@{ $self->cache->get_by_key('transcripts_by_exon_id', 'target', $target_exon_id) }) {
197
198 # add scoring flag for these two transcripts
199 $matrix->add_score($source_transcript->id, $target_transcript->id, 1);
200
201 }
202 }
203 }
204 }
205  
206 $self->logger->info("\n");
207  
208 return $matrix;
209 }
210  
211  
212 sub score_matrix_from_flag_matrix {
213 my $self = shift;
214 my $flag_matrix = shift;
215 my $exon_matrix = shift;
216  
217 unless ($flag_matrix and
218 $flag_matrix->isa('Bio::EnsEMBL::IdMapping::ScoredMappingMatrix')) {
219 throw('Need a transcript Bio::EnsEMBL::IdMapping::ScoredMappingMatrix.');
220 }
221
222 unless ($exon_matrix and
223 $exon_matrix->isa('Bio::EnsEMBL::IdMapping::ScoredMappingMatrix')) {
224 throw('Need an exon Bio::EnsEMBL::IdMapping::ScoredMappingMatrix.');
225 }
226  
227 my $transcript_score_threshold =
228 $self->conf->param('transcript_score_threshold') || 0;
229  
230 # create a new scoring matrix which will replace the flag matrix
231 my $matrix = Bio::EnsEMBL::IdMapping::ScoredMappingMatrix->new(
232 -DUMP_PATH => $flag_matrix->dump_path,
233 -CACHE_FILE => $flag_matrix->cache_file_name,
234 );
235  
236 # initialise progress logger
237 my $i;
238 my $num_transcripts =
239 scalar(keys %{ $self->cache->get_by_name('transcripts_by_id', 'source') });
240 my $progress_id = $self->logger->init_progress($num_transcripts, 100);
241  
242 $self->logger->info("Creating score matrix from flag matrix...\n", 1);
243  
244 # debug
245 my $fmt_d1 = "%-14s%-15s%-14s%-14s%-14s\n";
246 my $fmt_d2 = "%.6f";
247
248 # loop over source transcripts
249 foreach my $source_transcript (values %{ $self->cache->get_by_name('transcripts_by_id', 'source') }) {
250
251 # log progress
252 $self->logger->log_progress($progress_id, ++$i, 1);
253  
254 # We are only interested in scoring with exons that are in the target
255 # transcript. The ScoredMappingMatrix may contain scores for exons that
256 # aren't in this transcript so create a hash of the target transcript's
257 # exons
258 my %source_exons = map { $_->id => 1 }
259 @{ $source_transcript->get_all_Exons };
260  
261 my $source_transcript_length = $source_transcript->length;
262  
263 # get all corresponding target transcripts from the flag matrix
264 foreach my $target_transcript_id (@{ $flag_matrix->get_targets_for_source($source_transcript->id) }) {
265
266 my $target_transcript = $self->cache->get_by_key('transcripts_by_id', 'target', $target_transcript_id);
267  
268 my $source_transcript_score = 0;
269 my $target_transcript_score = 0;
270 my $target_transcript_length = $target_transcript->length;
271  
272 my %target_exons = map { $_->id => 1 }
273 @{ $target_transcript->get_all_Exons };
274  
275 # now loop over source exons and find the highest scoring target exon
276 # belonging to the target transcript
277
278 foreach my $source_exon (@{ $source_transcript->get_all_Exons }) {
279  
280 my $max_source_score = -1;
281
282 foreach my $target_exon_id (@{ $exon_matrix->get_targets_for_source($source_exon->id) }) {
283  
284 next unless ($target_exons{$target_exon_id});
285  
286 my $score = $exon_matrix->get_score($source_exon->id,
287 $target_exon_id);
288 $max_source_score = $score if ($score > $max_source_score);
289 }
290  
291 if ($max_source_score > 0) {
292 $source_transcript_score += ($max_source_score * $source_exon->length);
293  
294 }
295 }
296  
297 # now do the same for target exons
298
299 foreach my $target_exon (@{ $target_transcript->get_all_Exons }) {
300  
301 my $max_target_score = -1;
302
303 foreach my $source_exon_id (@{ $exon_matrix->get_sources_for_target($target_exon->id) }) {
304  
305 next unless ($source_exons{$source_exon_id});
306  
307 my $score = $exon_matrix->get_score(
308 $source_exon_id, $target_exon->id);
309 $max_target_score = $score if ($score > $max_target_score);
310 }
311  
312 if ($max_target_score > 0) {
313 $target_transcript_score += ($max_target_score * $target_exon->length);
314  
315 }
316 }
317  
318 #
319 # calculate transcript score and add to scoring matrix
320 #
321 if (($source_transcript_length + $target_transcript_length) > 0) {
322  
323 # sanity check
324 if (($source_transcript_score > $source_transcript_length) or
325 ($target_transcript_score > $target_transcript_length)) {
326  
327 $self->logger->warning("Score > length for source ($source_transcript_score <> $source_transcript_length) or target ($target_transcript_score <> $target_transcript_length).\n", 1);
328  
329 } else {
330  
331 my $source_transcript_biotype_group = $self->get_biotype_group($source_transcript->biotype());
332 my $target_transcript_biotype_group = $self->get_biotype_group($target_transcript->biotype());
333  
334 =cut
335 # debug
336 $self->logger->info($source_transcript->id.":".$target_transcript->id.
337 " source score: $source_transcript_score".
338 " source length: $source_transcript_length".
339 " source biotype:" . $source_transcript->biotype() .
340 " source group: $source_transcript_biotype_group".
341 " target score: $target_transcript_score".
342 " target biotype:" . $target_transcript->biotype() .
343 " target group: $target_transcript_biotype_group".
344 " target length: $target_transcript_length\n");
345 =cut
346
347 my $transcript_score =
348 ($source_transcript_score + $target_transcript_score) /
349 ($source_transcript_length + $target_transcript_length);
350  
351 ## Add penalty if biotypes are different
352 if ($source_transcript->biotype() ne $target_transcript->biotype()) {
353 $transcript_score = $transcript_score * 0.9;
354 }
355  
356 ## Add penalty if biotype groups are different
357 if ($source_transcript_biotype_group ne $target_transcript_biotype_group) {
358 $transcript_score = $transcript_score * 0.8;
359 }
360  
361 # everything is fine, add score to matrix
362 if ($transcript_score > $transcript_score_threshold) {
363 $matrix->add_score($source_transcript->id, $target_transcript->id,
364 $transcript_score);
365 }
366
367 }
368
369 } else {
370
371 $self->logger->warning("Combined length of source (".$source_transcript->id.") and target (".$target_transcript->id.") transcript is zero!\n", 1);
372
373 }
374  
375 }
376 }
377  
378 $self->logger->info("\n");
379  
380 return $matrix;
381
382 }
383  
384  
385 #
386 # penalise scores between genes with different biotypes.
387 # entries are modified in place
388 #
389 sub biotype_transcript_rescore {
390 my ( $self, $matrix ) = @_;
391  
392 if ( defined($matrix) &&
393 !$matrix->isa('Bio::EnsEMBL::IdMapping::ScoredMappingMatrix') )
394 {
395 throw('Exprected Bio::EnsEMBL::IdMapping::ScoredMappingMatrix');
396 }
397  
398 my $i = 0;
399  
400 foreach my $entry ( @{ $matrix->get_all_Entries } ) {
401  
402 my $source_transcript =
403 $self->cache->get_by_key( 'transcripts_by_id', 'source',
404 $entry->source() );
405  
406 my $target_transcript =
407 $self->cache->get_by_key( 'transcripts_by_id', 'target',
408 $entry->target() );
409  
410 if ($source_transcript->biotype() ne $target_transcript->biotype() )
411 {
412 # PENALTY: Lower the score for mappings to transcripts of
413 # different biotype.
414 $matrix->set_score( $entry->source(), $entry->target(),
415 0.9*$entry->score() );
416 $i++;
417 }
418 }
419  
420 $self->logger->debug("Scored transcripts with biotype mismatch: $i\n",
421 1 );
422 } ## end sub biotype_transcript_rescore
423  
424  
425 sub different_translation_rescore {
426 my $self = shift;
427 my $matrix = shift;
428  
429 unless ($matrix
430 and $matrix->isa('Bio::EnsEMBL::IdMapping::ScoredMappingMatrix') )
431 {
432 throw('Need a Bio::EnsEMBL::IdMapping::ScoredMappingMatrix.');
433 }
434  
435 my $i = 0;
436  
437 foreach my $entry ( sort { $b->score <=> $a->score }
438 @{ $matrix->get_all_Entries } )
439 {
440  
441 # we only do this for perfect matches, i.e. transcript score == 1
442 last if ( $entry->score < 1 );
443  
444 my $source_tl =
445 $self->cache->get_by_key( 'transcripts_by_id', 'source',
446 $entry->source )->translation;
447 my $target_tl =
448 $self->cache->get_by_key( 'transcripts_by_id', 'target',
449 $entry->target )->translation;
450  
451 # no penalty if both transcripts have no translation
452 next if ( !$source_tl and !$target_tl );
453  
454 if ( !$source_tl
455 or !$target_tl
456 or ( $source_tl->seq ne $target_tl->seq ) )
457 {
458 # PENALTY: The transcript stable ID is now on a transcript with a
459 # different translation.
460 $matrix->set_score( $entry->source(), $entry->target(),
461 0.9*$entry->score() );
462 $i++;
463 }
464  
465 } ## end foreach my $entry ( sort { ...})
466  
467 $self->logger->debug(
468 "Non-perfect translations on perfect transcripts: $i\n",
469 1 );
470 } ## end sub different_translation_rescore
471  
472  
473 sub non_mapped_gene_rescore {
474 my $self = shift;
475 my $matrix = shift;
476 my $gene_mappings = shift;
477  
478 # argument checks
479 unless ($matrix
480 and $matrix->isa('Bio::EnsEMBL::IdMapping::ScoredMappingMatrix') )
481 {
482 throw(
483 'Need a transcript Bio::EnsEMBL::IdMapping::ScoredMappingMatrix.'
484 );
485 }
486  
487 unless ( $gene_mappings
488 and $gene_mappings->isa('Bio::EnsEMBL::IdMapping::MappingList') )
489 {
490 throw('Need a gene Bio::EnsEMBL::IdMapping::MappingList.');
491 }
492  
493 # create of lookup hash of mapped source genes to target genes
494 my %gene_lookup =
495 map { $_->source => $_->target }
496 @{ $gene_mappings->get_all_Entries };
497  
498 my $i = 0;
499  
500 foreach my $entry ( @{ $matrix->get_all_Entries } ) {
501  
502 my $source_gene =
503 $self->cache->get_by_key( 'genes_by_transcript_id', 'source',
504 $entry->source );
505 my $target_gene =
506 $self->cache->get_by_key( 'genes_by_transcript_id', 'target',
507 $entry->target );
508  
509 my $mapped_target = $gene_lookup{ $source_gene->id };
510  
511 if ( !$mapped_target or ( $mapped_target != $target_gene->id ) ) {
512 # PENALTY: The transcript stable ID has been mapped to an
513 # un-mapped gene.
514 $matrix->set_score( $entry->source(), $entry->target(),
515 0.9*$entry->score() );
516 $i++;
517 }
518 }
519  
520 $self->logger->debug( "Scored transcripts in non-mapped genes: $i\n",
521 1 );
522 } ## end sub non_mapped_gene_rescore
523  
524  
525 sub get_biotype_group {
526 my ($self, $biotype) = @_;
527 my $dba = $self->cache->get_DBAdaptor('target');
528 my $biotype_adaptor = $dba->get_BiotypeAdaptor();
529 my $biotype_object = $biotype_adaptor->fetch_by_name_object_type($biotype, 'transcript');
530 return $biotype_object->biotype_group();
531
532 }
533  
534
535 1;
536