EnsEMBL/IdMapping/SyntenyFramework.pm untested

filter: Statementstmt 0.0% 0 / 177 Branchbran 0.0% 0 / 40 Conditioncond 0.0% 0 / 50 Subroutinesub 0.0% 0 / 20 Podpod 0.0% 0 / 10 totaltotal 0.0% 0 / 297 CC 21 SCAR 28.0
CC
21
Cov
0%
build_synteny
42.0
rescore_gene_matrix_lsf
30.0
new
20.0
CRAP 16.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 =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::IdMapping::SyntenyFramework - framework representing syntenic
34 regions across the genome
35  
36 =head1 SYNOPSIS
37  
38 # build the SyntenyFramework from unambiguous gene mappings
39 my $sf = Bio::EnsEMBL::IdMapping::SyntenyFramework->new(
40 -DUMP_PATH => $dump_path,
41 -CACHE_FILE => 'synteny_framework.ser',
42 -LOGGER => $self->logger,
43 -CONF => $self->conf,
44 -CACHE => $self->cache,
45 );
46 $sf->build_synteny($gene_mappings);
47  
48 # use it to rescore the genes
49 $gene_scores = $sf->rescore_gene_matrix_lsf($gene_scores);
50  
51 =head1 DESCRIPTION
52  
53 The SyntenyFramework is a set of SyntenyRegions. These are pairs of
54 locations very analoguous to the information in the assembly table (the
55 locations dont have to be the same length though). They are built from
56 genes that map uniquely between source and target.
57  
58 Once built, the SyntenyFramework is used to score source and target gene
59 pairs to determine whether they are similar. This process is slow (it
60 involves testing all gene pairs against all SyntenyRegions), this module
61 therefor has built-in support to run the process in parallel via LSF.
62  
63 =head1 METHODS
64  
65 new
66 build_synteny
67 _by_overlap
68 add_SyntenyRegion
69 get_all_SyntenyRegions
70 rescore_gene_matrix_lsf
71 rescore_gene_matrix
72 logger
73 conf
74 cache
75  
76 =cut
77  
78 package Bio::EnsEMBL::IdMapping::SyntenyFramework;
79 $Bio::EnsEMBL::IdMapping::SyntenyFramework::VERSION = '114.0.0_50'; # TRIAL
80 $Bio::EnsEMBL::IdMapping::SyntenyFramework::VERSION = '114.0.050';
81 use strict;
82 use warnings;
83 no warnings 'uninitialized';
84  
85 use Bio::EnsEMBL::IdMapping::Serialisable;
86 our @ISA = qw(Bio::EnsEMBL::IdMapping::Serialisable);
87  
88 use Bio::EnsEMBL::Utils::Argument qw(rearrange);
89 use Bio::EnsEMBL::Utils::Exception qw(throw warning);
90 use Bio::EnsEMBL::Utils::ScriptUtils qw(path_append);
91 use Bio::EnsEMBL::IdMapping::SyntenyRegion;
92 use Bio::EnsEMBL::IdMapping::ScoredMappingMatrix;
93  
94 use FindBin qw($Bin);
95 FindBin->again;
96  
97  
98 =head2 new
99  
100 Arg [LOGGER]: Bio::EnsEMBL::Utils::Logger $logger - a logger object
101 Arg [CONF] : Bio::EnsEMBL::Utils::ConfParser $conf - a configuration object
102 Arg [CACHE] : Bio::EnsEMBL::IdMapping::Cache $cache - a cache object
103 Arg [DUMP_PATH] : String - path for object serialisation
104 Arg [CACHE_FILE] : String - filename of serialised object
105 Example : my $sf = Bio::EnsEMBL::IdMapping::SyntenyFramework->new(
106 -DUMP_PATH => $dump_path,
107 -CACHE_FILE => 'synteny_framework.ser',
108 -LOGGER => $self->logger,
109 -CONF => $self->conf,
110 -CACHE => $self->cache,
111 );
112 Description : Constructor.
113 Return type : Bio::EnsEMBL::IdMapping::SyntenyFramework
114 Exceptions : thrown on wrong or missing arguments
115 Caller : InternalIdMapper plugins
116 Status : At Risk
117 : under development
118  
119 =cut
120  
121 sub new {
122 my $caller = shift;
123 my $class = ref($caller) || $caller;
124 my $self = $class->SUPER::new(@_);
125  
126 my ($logger, $conf, $cache) = rearrange(['LOGGER', 'CONF', 'CACHE'], @_);
127  
128 unless ($logger and ref($logger) and
129 $logger->isa('Bio::EnsEMBL::Utils::Logger')) {
130 throw("You must provide a Bio::EnsEMBL::Utils::Logger for logging.");
131 }
132
133 unless ($conf and ref($conf) and
134 $conf->isa('Bio::EnsEMBL::Utils::ConfParser')) {
135 throw("You must provide configuration as a Bio::EnsEMBL::Utils::ConfParser object.");
136 }
137
138 unless ($cache and ref($cache) and
139 $cache->isa('Bio::EnsEMBL::IdMapping::Cache')) {
140 throw("You must provide configuration as a Bio::EnsEMBL::IdMapping::Cache object.");
141 }
142
143 # initialise
144 $self->logger($logger);
145 $self->conf($conf);
146 $self->cache($cache);
147 $self->{'cache'} = [];
148  
149 return $self;
150 }
151  
152  
153 =head2 build_synteny
154  
155 Arg[1] : Bio::EnsEMBL::IdMapping::MappingList $mappings - gene mappings
156 to build the SyntenyFramework from
157 Example : $synteny_framework->build_synteny($gene_mappings);
158 Description : Builds the SyntenyFramework from unambiguous gene mappings.
159 SyntenyRegions are allowed to overlap. At most two overlapping
160 SyntenyRegions are merged (otherwise we'd get too large
161 SyntenyRegions with little information content).
162 Return type : none
163 Exceptions : thrown on wrong or missing argument
164 Caller : InternalIdMapper plugins
165 Status : At Risk
166 : under development
167  
168 =cut
169  
170 sub build_synteny {
171 my $self = shift;
172 my $mappings = shift;
173
174 unless ($mappings and
175 $mappings->isa('Bio::EnsEMBL::IdMapping::MappingList')) {
176 throw('Need a gene Bio::EnsEMBL::IdMapping::MappingList.');
177 }
178  
179 # create a synteny region for each mapping
180 my @synteny_regions = ();
181  
182 foreach my $entry (@{ $mappings->get_all_Entries }) {
183
184 my $source_gene = $self->cache->get_by_key('genes_by_id', 'source',
185 $entry->source);
186 my $target_gene = $self->cache->get_by_key('genes_by_id', 'target',
187 $entry->target);
188  
189 my $sr = Bio::EnsEMBL::IdMapping::SyntenyRegion->new_fast([
190 $source_gene->start,
191 $source_gene->end,
192 $source_gene->strand,
193 $source_gene->seq_region_name,
194 $target_gene->start,
195 $target_gene->end,
196 $target_gene->strand,
197 $target_gene->seq_region_name,
198 $entry->score,
199 ]);
200  
201 push @synteny_regions, $sr;
202 }
203  
204 unless (@synteny_regions) {
205 $self->logger->warning("No synteny regions could be identified.\n");
206 return;
207 }
208  
209 # sort synteny regions
210 #my @sorted = sort _by_overlap @synteny_regions;
211 my @sorted = reverse sort {
212 $a->source_seq_region_name cmp $b->source_seq_region_name ||
213 $a->source_start <=> $b->source_start ||
214 $a->source_end <=> $b->source_end } @synteny_regions;
215  
216 $self->logger->info("SyntenyRegions before merging: ".scalar(@sorted)."\n");
217
218 # now create merged regions from overlapping syntenies, but only merge a
219 # maximum of 2 regions (otherwise you end up with large synteny blocks which
220 # won't contain much information in this context)
221 my $last_merged = 0;
222 my $last_sr = shift(@sorted);
223  
224 while (my $sr = shift(@sorted)) {
225 #$self->logger->debug("this ".$sr->to_string."\n");
226
227 my $merged_sr = $last_sr->merge($sr);
228  
229 if (! $merged_sr) {
230 unless ($last_merged) {
231 $self->add_SyntenyRegion($last_sr->stretch(2));
232 #$self->logger->debug("nnn ".$last_sr->to_string."\n");
233 }
234 $last_merged = 0;
235 } else {
236 $self->add_SyntenyRegion($merged_sr->stretch(2));
237 #$self->logger->debug("mmm ".$merged_sr->to_string."\n");
238 $last_merged = 1;
239 }
240
241 $last_sr = $sr;
242 }
243  
244 # deal with last synteny region in @sorted
245 unless ($last_merged) {
246 $self->add_SyntenyRegion($last_sr->stretch(2));
247 $last_merged = 0;
248 }
249  
250 #foreach my $sr (@{ $self->get_all_SyntenyRegions }) {
251 # $self->logger->debug("SRs ".$sr->to_string."\n");
252 #}
253
254 $self->logger->info("SyntenyRegions after merging: ".scalar(@{ $self->get_all_SyntenyRegions })."\n");
255  
256 }
257  
258  
259 #
260 # sort SyntenyRegions by overlap
261 #
262 sub _by_overlap {
263 # first sort by seq_region
264 my $retval = ($b->source_seq_region_name cmp $a->source_seq_region_name);
265 return $retval if ($retval);
266  
267 # then sort by overlap:
268 # return -1 if $a is downstream, 1 if it's upstream, 0 if they overlap
269 if ($a->source_end < $b->source_start) { return 1; }
270 if ($a->source_start < $b->source_end) { return -1; }
271 return 0;
272 }
273  
274  
275 =head2 add_SyntenyRegion
276  
277 Arg[1] : Bio::EnsEMBL::IdMaping::SyntenyRegion - SyntenyRegion to add
278 Example : $synteny_framework->add_SyntenyRegion($synteny_region);
279 Description : Adds a SyntenyRegion to the framework. For speed reasons (and
280 since this is an internal method), no argument check is done.
281 Return type : none
282 Exceptions : none
283 Caller : internal
284 Status : At Risk
285 : under development
286  
287 =cut
288  
289 sub add_SyntenyRegion {
290 push @{ $_[0]->{'cache'} }, $_[1];
291 }
292  
293  
294 =head2 get_all_SyntenyRegions
295  
296 Example : foreach my $sr (@{ $sf->get_all_SyntenyRegions }) {
297 # do something with the SyntenyRegion
298 }
299 Description : Get a list of all SyntenyRegions in the framework.
300 Return type : Arrayref of Bio::EnsEMBL::IdMapping::SyntenyRegion
301 Exceptions : none
302 Caller : general
303 Status : At Risk
304 : under development
305  
306 =cut
307  
308 sub get_all_SyntenyRegions {
309 return $_[0]->{'cache'};
310 }
311  
312  
313 =head2 rescore_gene_matrix_lsf
314  
315 Arg[1] : Bio::EnsEMBL::IdMapping::ScoredmappingMatrix $matrix - gene
316 scores to rescore
317 Example : my $new_scores = $sf->rescore_gene_matrix_lsf($gene_scores);
318 Description : This method runs rescore_gene_matrix() (via the
319 synteny_resocre.pl script) in parallel with lsf, then combines
320 the results to return a single rescored scoring matrix.
321 Parallelisation is done by chunking the scoring matrix into
322 several pieces (determined by the --synteny_rescore_jobs
323 configuration option).
324 Return type : Bio::EnsEMBL::IdMapping::ScoredMappingMatrix
325 Exceptions : thrown on wrong or missing argument
326 thrown on filesystem I/O error
327 thrown on failure of one or mor lsf jobs
328 Caller : InternalIdMapper plugins
329 Status : At Risk
330 : under development
331  
332 =cut
333  
334 sub rescore_gene_matrix_lsf {
335 my $self = shift;
336 my $matrix = shift;
337  
338 unless ($matrix and
339 $matrix->isa('Bio::EnsEMBL::IdMapping::ScoredMappingMatrix')) {
340 throw('Need a Bio::EnsEMBL::IdMapping::ScoredMappingMatrix.');
341 }
342  
343 # serialise SyntenyFramework to disk
344 $self->logger->debug("Serialising SyntenyFramework...\n", 0, 'stamped');
345 $self->write_to_file;
346 $self->logger->debug("Done.\n", 0, 'stamped');
347  
348 # split the ScoredMappingMatrix into chunks and write to disk
349 my $matrix_size = $matrix->size;
350 $self->logger->debug("Scores before rescoring: $matrix_size.\n");
351  
352 my $num_jobs = $self->conf->param('synteny_rescore_jobs') || 20;
353 $num_jobs++;
354  
355 my $dump_path = path_append($self->conf->param('basedir'),
356 'matrix/synteny_rescore');
357  
358 $self->logger->debug("Creating sub-matrices...\n", 0, 'stamped');
359 foreach my $i (1..$num_jobs) {
360 my $start = (int($matrix_size/($num_jobs-1)) * ($i - 1)) + 1;
361 my $end = int($matrix_size/($num_jobs-1)) * $i;
362 $self->logger->debug("$start-$end\n", 1);
363 my $sub_matrix = $matrix->sub_matrix($start, $end);
364
365 $sub_matrix->cache_file_name("gene_matrix_synteny$i.ser");
366 $sub_matrix->dump_path($dump_path);
367
368 $sub_matrix->write_to_file;
369 }
370 $self->logger->debug("Done.\n", 0, 'stamped');
371  
372 # create an empty lsf log directory
373 my $logpath = path_append($self->logger->logpath, 'synteny_rescore');
374 system("rm -rf $logpath") == 0 or
375 $self->logger->error("Unable to delete lsf log dir $logpath: $!\n");
376 system("mkdir -p $logpath") == 0 or
377 $self->logger->error("Can't create lsf log dir $logpath: $!\n");
378  
379 # build lsf command
380 my $lsf_name = 'idmapping_synteny_rescore_'.time;
381  
382 my $options = $self->conf->create_commandline_options(
383 logauto => 1,
384 logautobase => "synteny_rescore",
385 logpath => $logpath,
386 interactive => 0,
387 is_component => 1,
388 );
389  
390 my $cmd = qq{$Bin/synteny_rescore.pl $options --index \$LSB_JOBINDEX};
391  
392 my $bsub_cmd =
393 sprintf( "|bsub -J '%s[1-%d]' "
394 . "-o %s/synteny_rescore.%%I.out "
395 . "-e %s/synteny_rescore.%%I.err %s",
396 $lsf_name, $num_jobs, $logpath, $logpath,
397 $self->conf()->param('lsf_opt_synteny_rescore') );
398  
399 # run lsf job array
400 $self->logger->info("Submitting $num_jobs jobs to lsf.\n");
401 $self->logger->debug("$cmd\n\n");
402  
403 local *BSUB;
404 open( BSUB, $bsub_cmd ) ## no critic
405 or $self->logger->error("Could not open open pipe to bsub: $!\n");
406  
407 print BSUB $cmd;
408 $self->logger->error("Error submitting synteny rescoring jobs: $!\n")
409 unless ($? == 0);
410 close BSUB;
411  
412 # submit dependent job to monitor finishing of jobs
413 $self->logger->info("Waiting for jobs to finish...\n", 0, 'stamped');
414  
415 my $dependent_job =
416 qq{bsub -K -w "ended($lsf_name)" -q production } .
417 qq{-M 1000 -R 'select[mem>1000]' -R 'rusage[mem=1000]' } .
418 qq{-o $logpath/synteny_rescore_depend.out /bin/true};
419  
420 system($dependent_job) == 0 or
421 $self->logger->error("Error submitting dependent job: $!\n");
422  
423 $self->logger->info("All jobs finished.\n", 0, 'stamped');
424  
425 # check for lsf errors
426 sleep(5);
427 my $err;
428 foreach my $i (1..$num_jobs) {
429 $err++ unless (-e "$logpath/synteny_rescore.$i.success");
430 }
431  
432 if ($err) {
433 $self->logger->error("At least one of your jobs failed.\nPlease check the logfiles at $logpath for errors.\n");
434 }
435  
436 # merge and return matrix
437 $self->logger->debug("Merging rescored matrices...\n");
438 $matrix->flush;
439  
440 foreach my $i (1..$num_jobs) {
441 # read partial matrix created by lsf job from file
442 my $sub_matrix = Bio::EnsEMBL::IdMapping::ScoredMappingMatrix->new(
443 -DUMP_PATH => $dump_path,
444 -CACHE_FILE => "gene_matrix_synteny$i.ser",
445 );
446 $sub_matrix->read_from_file;
447  
448 # merge with main matrix
449 $matrix->merge($sub_matrix);
450 }
451  
452 $self->logger->debug("Done.\n");
453 $self->logger->debug("Scores after rescoring: ".$matrix->size.".\n");
454
455 return $matrix;
456 }
457  
458  
459 #
460 #
461 =head2 rescore_gene_matrix
462  
463 Arg[1] : Bio::EnsEMBL::IdMapping::ScoredmappingMatrix $matrix - gene
464 scores to rescore
465 Example : my $new_scores = $sf->rescore_gene_matrix($gene_scores);
466 Description : Rescores a gene matrix. Retains 70% of old score and builds
467 other 30% from the synteny match.
468 Return type : Bio::EnsEMBL::IdMapping::ScoredMappingMatrix
469 Exceptions : thrown on wrong or missing argument
470 Caller : InternalIdMapper plugins
471 Status : At Risk
472 : under development
473  
474 =cut
475  
476 sub rescore_gene_matrix {
477 my $self = shift;
478 my $matrix = shift;
479  
480 unless ($matrix and
481 $matrix->isa('Bio::EnsEMBL::IdMapping::ScoredMappingMatrix')) {
482 throw('Need a Bio::EnsEMBL::IdMapping::ScoredMappingMatrix.');
483 }
484  
485 my $retain_factor = 0.7;
486  
487 foreach my $entry (@{ $matrix->get_all_Entries }) {
488 my $source_gene = $self->cache->get_by_key('genes_by_id', 'source',
489 $entry->source);
490  
491 my $target_gene = $self->cache->get_by_key('genes_by_id', 'target',
492 $entry->target);
493  
494 my $highest_score = 0;
495  
496 foreach my $sr (@{ $self->get_all_SyntenyRegions }) {
497 my $score = $sr->score_location_relationship($source_gene, $target_gene);
498 $highest_score = $score if ($score > $highest_score);
499 }
500  
501 #$self->logger->debug("highscore ".$entry->to_string." ".
502 # sprintf("%.6f\n", $highest_score));
503  
504 $matrix->set_score($entry->source, $entry->target,
505 ($entry->score * 0.7 + $highest_score * 0.3));
506 }
507  
508 return $matrix;
509 }
510  
511  
512 =head2 logger
513  
514 Arg[1] : (optional) Bio::EnsEMBL::Utils::Logger - the logger to set
515 Example : $object->logger->info("Starting ID mapping.\n");
516 Description : Getter/setter for logger object
517 Return type : Bio::EnsEMBL::Utils::Logger
518 Exceptions : none
519 Caller : constructor
520 Status : At Risk
521 : under development
522  
523 =cut
524  
525 sub logger {
526 my $self = shift;
527 $self->{'_logger'} = shift if (@_);
528 return $self->{'_logger'};
529 }
530  
531  
532 =head2 conf
533  
534 Arg[1] : (optional) Bio::EnsEMBL::Utils::ConfParser - the configuration
535 to set
536 Example : my $basedir = $object->conf->param('basedir');
537 Description : Getter/setter for configuration object
538 Return type : Bio::EnsEMBL::Utils::ConfParser
539 Exceptions : none
540 Caller : constructor
541 Status : At Risk
542 : under development
543  
544 =cut
545  
546 sub conf {
547 my $self = shift;
548 $self->{'_conf'} = shift if (@_);
549 return $self->{'_conf'};
550 }
551  
552  
553 =head2 cache
554  
555 Arg[1] : (optional) Bio::EnsEMBL::IdMapping::Cache - the cache to set
556 Example : $object->cache->read_from_file('source');
557 Description : Getter/setter for cache object
558 Return type : Bio::EnsEMBL::IdMapping::Cache
559 Exceptions : none
560 Caller : constructor
561 Status : At Risk
562 : under development
563  
564 =cut
565  
566 sub cache {
567 my $self = shift;
568 $self->{'_cache'} = shift if (@_);
569 return $self->{'_cache'};
570 }
571  
572  
573 1;
574