EnsEMBL/Utils/ConversionSupport.pm untested

filter: Statementstmt 0.0% 0 / 780 Branchbran 0.0% 0 / 250 Conditioncond 0.0% 0 / 183 Subroutinesub 0.0% 0 / 78 Podpod 0.0% 0 / 65 totaltotal 0.0% 0 / 1356 CC 126 SCAR 34.4
CC
126
Cov
0%
fix_attrib_value
110.0
parse_common_options
90.0
split_chromosomes_by_size
90.0
CRAP 31.2
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::ConversionSupport - Utility module for Vega release and
34 schema conversion scripts
35  
36 =head1 SYNOPSIS
37  
38 my $serverroot = '/path/to/ensembl';
39 my $support = new Bio::EnsEMBL::Utils::ConversionSupport($serverroot);
40  
41 # parse common options
42 $support->parse_common_options;
43  
44 # parse extra options for your script
45 $support->parse_extra_options( 'string_opt=s', 'numeric_opt=n' );
46  
47 # ask user if he wants to run script with these parameters
48 $support->confirm_params;
49  
50 # see individual method documentation for more stuff
51  
52 =head1 DESCRIPTION
53  
54 This module is a collection of common methods and provides helper
55 functions for the Vega release and schema conversion scripts. Amongst
56 others, it reads options from a config file, parses commandline options
57 and does logging.
58  
59 =head1 METHODS
60  
61 =cut
62  
63 package Bio::EnsEMBL::Utils::ConversionSupport;
64 $Bio::EnsEMBL::Utils::ConversionSupport::VERSION = '114.0.0_50'; # TRIAL
65 $Bio::EnsEMBL::Utils::ConversionSupport::VERSION = '114.0.050';
66 use strict;
67 use warnings;
68 no warnings 'uninitialized';
69  
70 use Getopt::Long;
71 use Text::Wrap;
72 use Bio::EnsEMBL::Utils::Exception qw(throw warning);
73 use FindBin qw($Bin $Script);
74 use POSIX qw(strftime);
75 use Cwd qw(abs_path);
76 use DBI;
77 use Data::Dumper;
78 use Fcntl qw(:flock SEEK_END);
79  
80 my $species_c = 1; #counter to be used for each database connection made
81  
82 =head2 new
83  
84 Arg[1] : String $serverroot - root directory of your ensembl sandbox
85 Example : my $support = new Bio::EnsEMBL::Utils::ConversionSupport(
86 '/path/to/ensembl');
87 Description : constructor
88 Return type : Bio::EnsEMBL::Utils::ConversionSupport object
89 Exceptions : thrown if no serverroot is provided
90 Caller : general
91  
92 =cut
93  
94 sub new {
95 my $class = shift;
96 (my $serverroot = shift) or throw("You must supply a serverroot.");
97 my $self = {
98 '_serverroot' => $serverroot,
99 '_param' => { interactive => 1 },
100 '_warnings' => 0,
101 };
102 bless ($self, $class);
103 return $self;
104 }
105  
106 =head2 parse_common_options
107  
108 Example : $support->parse_common_options;
109 Description : This method reads options from a configuration file and parses
110 some commandline options that are common to all scripts (like
111 db connection settings, help, dry-run). Commandline options
112 will override config file settings.
113  
114 All options will be accessible via $self->param('name').
115 Return type : true on success
116 Exceptions : thrown if configuration file can't be opened
117 Caller : general
118  
119 =cut
120  
121 sub parse_common_options {
122 my $self = shift;
123  
124 # read commandline options
125 my %h;
126 Getopt::Long::Configure("pass_through");
127 &GetOptions( \%h,
128 'dbname|db_name=s',
129 'host|dbhost|db_host=s',
130 'port|dbport|db_port=n',
131 'user|dbuser|db_user=s',
132 'pass|dbpass|db_pass=s',
133 'prod_dbname=s',
134 'prod_host=s',
135 'prod_port=n',
136 'prod_user=s',
137 'prod_pass=s',
138 'conffile|conf=s',
139 'logfile|log=s',
140 'nolog',
141 'logpath=s',
142 'log_base_path=s',
143 'logappend|log_append',
144 'verbose|v',
145 'interactive|i=s',
146 'hideparamlist=s',
147 'joblog=s',
148 'dry_run|dry|n',
149 'help|h|?',
150 );
151  
152 # reads config file
153 my $conffile = $h{'conffile'} || $self->serverroot . "/sanger-plugins/vega/conf/ini-files/Conversion.ini";
154 $conffile = abs_path($conffile);
155 if (-e $conffile) {
156 open(my $fh, '<', $conffile) or throw(
157 "Unable to open configuration file $conffile for reading: $!");
158 my $serverroot = $self->serverroot;
159 while (<$fh>) {
160 chomp;
161  
162 # remove comments
163 s/^[#;].*//;
164 s/\s+[;].*$//;
165  
166 # read options into internal parameter datastructure, removing whitespace
167 next unless (/(\w\S*)\s*=\s*(\S*)\s*/);
168 my $name = $1;
169 my $val = $2;
170 if ($val =~ /\$SERVERROOT/) {
171 $val =~ s/\$SERVERROOT/$serverroot/g;
172 $val = abs_path($val);
173 }
174 $self->param($name, $val);
175 }
176 close $fh;
177 $self->param('conffile', $conffile);
178 }
179 elsif ($conffile) {
180 warning("Unable to open configuration file $conffile for reading: $!");
181 }
182  
183 # override configured parameter with commandline options
184 map { $self->param($_, $h{$_}) } keys %h;
185  
186 return (1) if $self->param('nolog');
187  
188 # if logpath & logfile are not set, set them here to /ensemblweb/vega_dev/shared/logs/conversion/DBNAME/SCRIPNAME_NN.log
189 if (! defined($self->param('log_base_path'))) {
190 $self->param('log_base_path','/ensemblweb/shared/logs/conversion/');
191 }
192 my $dbname = $self->param('dbname');
193 $dbname =~ s/^vega_//;
194 if (not (defined($self->param('logpath')) )){
195 $self->param('logpath', $self->param('log_base_path')."/".$dbname."/" );
196 }
197 if ( not defined $self->param('logfile') ){
198 my $log = $Script;
199 $log =~ s/.pl$//g;
200 my $counter;
201 for ($counter=1 ; (-e $self->param('logpath')."/".$log."_".sprintf("%03d", $counter).".log"); $counter++){
202 # warn $self->param('logpath')."/".$log."_".$counter.".log";
203 }
204 $self->param('logfile', $log."_".sprintf("%03d", $counter).".log");
205 }
206 return(1);
207 }
208  
209 =head2 parse_extra_options
210  
211 Arg[1-N] : option descriptors that will be passed on to Getopt::Long
212 Example : $support->parse_extra_options('string_opt=s', 'numeric_opt=n');
213 Description : Parse extra commandline options by passing them on to
214 Getopt::Long and storing parameters in $self->param('name).
215 If the last option is '...' then unknown options are kept
216 in @ARGV for future calls to this method. Without '...'
217 then it is an error to have further options.
218 Return type : true on success
219 Exceptions : none (caugth by $self->error)
220 Caller : general
221  
222 =cut
223  
224 sub parse_extra_options {
225 my ($self, @params) = @_;
226 if(@params and $params[-1] eq "...") {
227 pop @params;
228 Getopt::Long::Configure("pass_through");
229 } else {
230 Getopt::Long::Configure("no_pass_through");
231 }
232 eval {
233 # catch warnings to pass to $self->error
234 local $SIG{__WARN__} = sub { die @_; };
235 &GetOptions(\%{ $self->{'_param'} }, @params);
236 };
237 $self->error($@) if $@;
238 return(1);
239 }
240  
241 =head2 allowed_params
242  
243 Arg[1-N] : (optional) List of allowed parameters to set
244 Example : my @allowed = $self->allowed_params(qw(param1 param2));
245 Description : Getter/setter for allowed parameters. This is used by
246 $self->confirm_params() to avoid cluttering of output with
247 conffile entries not relevant for a given script. You can use
248 $self->get_common_params() as a shortcut to set them.
249 Return type : Array - list of allowed parameters
250 Exceptions : none
251 Caller : general
252  
253 =cut
254  
255 sub allowed_params {
256 my $self = shift;
257  
258 # setter
259 if (@_) {
260 @{ $self->{'_allowed_params'} } = @_;
261 }
262  
263 # getter
264 if (ref($self->{'_allowed_params'}) eq 'ARRAY') {
265 return @{ $self->{'_allowed_params'} };
266 } else {
267 return ();
268 }
269 }
270  
271 =head2 get_common_params
272  
273 Example : my @allowed_params = $self->get_common_params, 'extra_param';
274 Description : Returns a list of commonly used parameters in the conversion
275 scripts. Shortcut for setting allowed parameters with
276 $self->allowed_params().
277 Return type : Array - list of common parameters
278 Exceptions : none
279 Caller : general
280  
281 =cut
282  
283 sub get_common_params {
284 return qw(
285 conffile
286 dbname
287 host
288 port
289 user
290 pass
291 nolog
292 logpath
293 log_base_path
294 logfile
295 logappend
296 verbose
297 interactive
298 hideparamlist
299 joblog
300 dry_run
301 );
302 }
303  
304 =head2 get_loutre_params
305  
306 Arg : (optional) return a list to parse or not
307 Example : $support->parse_extra_options($support->get_loutre_params('parse'))
308 Description : Returns a list of commonly used loutre db parameters - parse option is
309 simply used to distinguish between reporting and parsing parameters
310 Return type : Array - list of common parameters
311 Exceptions : none
312 Caller : general
313  
314 =cut
315  
316 sub get_loutre_params {
317 my ($self,$p) = @_;
318 if ($p) {
319 return qw(
320 loutrehost=s
321 loutreport=s
322 loutreuser=s
323 loutrepass:s
324 loutredbname=s
325 );
326 }
327 else {
328 return qw(
329 loutrehost
330 loutreport
331 loutreuser
332 loutrepass
333 loutredbname
334 );
335 }
336 }
337  
338 =head2 get_annotrack_params
339  
340 Arg : (optional) return a list to parse or not
341 Example : $support->parse_extra_options($support->get_annotrack_params('parse'))
342 Description : Returns a list of parameters used to connect to annotrack
343 Return type : Array - list of common parameters
344 Exceptions : none
345 Caller : general
346  
347 =cut
348  
349 sub get_annotrack_params {
350 my ($self,$p) = @_;
351 if ($p) {
352 return qw(
353 annotrackhost=s
354 annotrackport=s
355 annotrackuser=s
356 annotrackpass=s
357 annotrackdbname=s
358 ignoreannotrack
359 );
360 }
361 else {
362 return qw(
363 annotrackhost
364 annotrackport
365 annotrackuser
366 annotrackpass
367 annotrackdbname
368 ignoreannotrack
369 );
370 }
371 }
372  
373 =head2 remove_vega_params
374  
375 Example : $support->remove_vega_params;
376 Description : Removes Vega db conection parameters. Usefull to avoid clutter in log files when
377 working exclusively with loutre
378 Return type : none
379 Exceptions : none
380 Caller : general
381  
382 =cut
383  
384 sub remove_vega_params {
385 my $self = shift;
386 foreach my $param (qw(dbname host port user pass)) {
387 $self->{'_param'}{$param} = undef;
388 }
389 }
390  
391 =head2 confirm_params
392  
393 Example : $support->confirm_params;
394 Description : Prints a table of parameters that were collected from config
395 file and commandline and asks user to confirm if he wants
396 to proceed.
397 Return type : true on success
398 Exceptions : none
399 Caller : general
400  
401 =cut
402  
403 sub confirm_params {
404 my $self = shift;
405  
406 # print parameter table
407 return 1 if($self->param('hideparamlist') and not $self->param('interactive'));
408 print "Running script with these parameters:\n\n";
409 print $self->list_all_params;
410  
411 if ($self->param('host') eq 'ensweb-1-10') {
412 # ask user if he wants to proceed
413 exit unless $self->user_proceed("**************\n\n You're working on ensdb-1-10! Is that correct and you want to continue ?\n\n**************");
414 }
415 else {
416 # ask user if he wants to proceed
417 exit unless $self->user_proceed("Continue?");
418 }
419 return(1);
420 }
421  
422 =head2 list_all_params
423  
424 Example : print LOG $support->list_all_params;
425 Description : prints a table of the parameters used in the script
426 Return type : String - the table to print
427 Exceptions : none
428 Caller : general
429  
430 =cut
431  
432 sub list_all_params {
433 my $self = shift;
434 my $txt = sprintf " %-25s%-110s\n", qw(PARAMETER VALUE);
435 $txt .= " " . "-"x136 . "\n";
436 $Text::Wrap::columns = 130;
437 my @params = $self->allowed_params;
438 foreach my $key (@params) {
439 my @vals = $self->param($key);
440 if (@vals) {
441 $txt .= Text::Wrap::wrap( sprintf(' %-25s', $key),
442 ' 'x28,
443 join(", ", @vals)
444 ) . "\n";
445 }
446 }
447 $txt .= "\n";
448 return $txt;
449 }
450  
451 =head2 create_commandline_options
452  
453 Arg[1] : Hashref $settings - hashref describing what to do
454 Allowed keys:
455 allowed_params => 0|1 # use all allowed parameters
456 exclude => [] # listref of parameters to exclude
457 replace => {param => newval} # replace value of param with
458 # newval
459 Example : $support->create_commandline_options({
460 allowed_params => 1,
461 exclude => ['verbose'],
462 replace => { 'dbname' => 'homo_sapiens_vega_33_35e' }
463 });
464 Description : Creates a commandline options string that can be passed to any
465 other script using ConversionSupport.
466 Return type : String - commandline options string
467 Exceptions : none
468 Caller : general
469  
470 =cut
471  
472 sub create_commandline_options {
473 my ($self, $settings, $param_hash) = @_;
474 my %param_hash = $param_hash ? %$param_hash : ();
475  
476 # get all allowed parameters
477 if ($settings->{'allowed_params'}) {
478 # exclude params explicitly stated
479 my %exclude = map { $_ => 1 } @{ $settings->{'exclude'} || [] };
480 foreach my $param ($self->allowed_params) {
481 unless ($exclude{$param}) {
482 my ($first, @rest) = $self->param($param);
483 next unless (defined($first));
484
485 if (@rest) {
486 $first = join(",", $first, @rest);
487 }
488 $param_hash{$param} = $first;
489 }
490 }
491 }
492  
493 # replace values
494 foreach my $key (keys %{ $settings->{'replace'} || {} }) {
495 $param_hash{$key} = $settings->{'replace'}->{$key};
496 }
497  
498 # create the commandline options string
499 my $options_string;
500 foreach my $param (keys %param_hash) {
501 $options_string .= sprintf("--%s %s ", $param, $param_hash{$param});
502 }
503 return $options_string;
504 }
505  
506 =head2 check_required_params
507  
508 Arg[1-N] : List @params - parameters to check
509 Example : $self->check_required_params(qw(dbname host port));
510 Description : Checks $self->param to make sure the requested parameters
511 have been set. Dies if parameters are missing.
512 Return type : true on success
513 Exceptions : none
514 Caller : general
515  
516 =cut
517  
518 sub check_required_params {
519 my ($self, @params) = @_;
520 my @missing = ();
521 foreach my $param (@params) {
522 push @missing, $param unless defined $self->param($param);
523 }
524 if (@missing) {
525 throw("Missing parameters: @missing.\nYou must specify them on the commandline or in your conffile.\n");
526 }
527 return(1);
528 }
529  
530 =head2 user_proceed
531  
532 Arg[1] : (optional) String $text - notification text to present to user
533 Example : # run a code snipped conditionally
534 if ($support->user_proceed("Run the next code snipped?")) {
535 # run some code
536 }
537  
538 # exit if requested by user
539 exit unless ($support->user_proceed("Want to continue?"));
540 Description : If running interactively, the user is asked if he wants to
541 perform a script action. If he doesn't, this section is skipped
542 and the script proceeds with the code. When running
543 non-interactively, the section is run by default.
544 Return type : TRUE to proceed, FALSE to skip.
545 Exceptions : none
546 Caller : general
547  
548 =cut
549  
550 sub user_proceed {
551 my ($self, $text) = @_;
552  
553 if ($self->param('interactive')) {
554 print "$text\n" if $text;
555 print "[y/N] ";
556 my $input = lc(<>);
557 chomp $input;
558 unless ($input eq 'y') {
559 print "Skipping.\n";
560 return(0);
561 }
562 }
563  
564 return(1);
565 }
566  
567  
568 =head2 read_user_input
569  
570 Arg[1] : (optional) String $text - notification text to present to user
571 Example : my $ret = $support->read_user_input("Choose a number [1/2/3]");
572 if ($ret == 1) {
573 # do something
574 } elsif ($ret == 2) {
575 # do something else
576 }
577 Description : If running interactively, the user is asked for input.
578 Return type : String - user's input
579 Exceptions : none
580 Caller : general
581  
582 =cut
583  
584 sub read_user_input {
585 my ($self, $text) = @_;
586  
587 if ($self->param('interactive')) {
588 print "$text\n" if $text;
589 my $input = <>;
590 chomp $input;
591 return $input;
592 }
593 }
594  
595 =head2 comma_to_list
596  
597 Arg[1-N] : list of parameter names to parse
598 Example : $support->comma_to_list('chromosomes');
599 Description : Transparently converts comma-separated lists into arrays (to
600 allow different styles of commandline options, see perldoc
601 Getopt::Long for details). Parameters are converted in place
602 (accessible through $self->param('name')).
603 Return type : true on success
604 Exceptions : none
605 Caller : general
606  
607 =cut
608  
609 sub comma_to_list {
610 my $self = shift;
611 foreach my $param (@_) {
612 $self->param($param,
613 split (/,/, join (',', $self->param($param))));
614 }
615 return(1);
616 }
617  
618 =head2 list_or_file
619  
620 Arg[1] : Name of parameter to parse
621 Example : $support->list_or_file('gene');
622 Description : Determines whether a parameter holds a list or it is a filename
623 to read the list entries from.
624 Return type : true on success
625 Exceptions : thrown if list file can't be opened
626 Caller : general
627  
628 =cut
629  
630 sub list_or_file {
631 my ($self, $param) = @_;
632 my @vals = $self->param($param);
633 return unless (@vals);
634  
635 my $firstval = $vals[0];
636 if (scalar(@vals) == 1 && -e $firstval) {
637 # we didn't get a list of values, but a file to read values from
638 @vals = ();
639 open(my $fh, '<', $firstval) or throw("Cannot open $firstval for reading: $!");
640 while(<$fh>){
641 chomp;
642 push(@vals, $_);
643 }
644 close($fh);
645 $self->param($param, @vals);
646 }
647 $self->comma_to_list($param);
648 return(1);
649 }
650  
651 =head2 param
652  
653 Arg[1] : Parameter name
654 Arg[2-N] : (optional) List of values to set
655 Example : my $dbname = $support->param('dbname');
656 $support->param('port', 3306);
657 $support->param('chromosomes', 1, 6, 'X');
658 Description : Getter/setter for parameters. Accepts single-value params and
659 list params.
660 Return type : Scalar value for single-value parameters, array of values for
661 list parameters
662 Exceptions : thrown if no parameter name is supplied
663 Caller : general
664  
665 =cut
666  
667 sub param {
668 my $self = shift;
669 my $name = shift or throw("You must supply a parameter name");
670  
671 # setter
672 if (@_) {
673 if (scalar(@_) == 1) {
674 # single value
675 $self->{'_param'}->{$name} = shift;
676 } else {
677 # list of values
678 undef $self->{'_param'}->{$name};
679 @{ $self->{'_param'}->{$name} } = @_;
680 }
681 }
682  
683 # getter
684 if (ref($self->{'_param'}->{$name}) eq 'ARRAY') {
685 # list parameter
686 return @{ $self->{'_param'}->{$name} };
687 } elsif (defined($self->{'_param'}->{$name})) {
688 # single-value parameter
689 return $self->{'_param'}->{$name};
690 } else {
691 return ();
692 }
693 }
694  
695 =head2 error
696  
697 Arg[1] : (optional) String - error message
698 Example : $support->error("An error occurred: $@");
699 exit(0) if $support->error;
700 Description : Getter/setter for error messages
701 Return type : String - error message
702 Exceptions : none
703 Caller : general
704  
705 =cut
706  
707 sub error {
708 my $self = shift;
709 $self->{'_error'} = shift if (@_);
710 return $self->{'_error'};
711 }
712  
713 =head2 warnings
714  
715 Example : print LOG "There were ".$support->warnings." warnings.\n";
716 Description : Returns the number of warnings encountered while running the
717 script (the warning counter is increased by $self->log_warning).
718 Return type : Int - number of warnings
719 Exceptions : none
720 Caller : general
721  
722 =cut
723  
724 sub warnings {
725 my $self = shift;
726 return $self->{'_warnings'};
727 }
728  
729 =head2 serverroot
730  
731 Arg[1] : (optional) String - root directory of your ensembl sandbox
732 Example : my $serverroot = $support->serverroot;
733 Description : Getter/setter for the root directory of your ensembl sandbox.
734 This is set when ConversionSupport object is created, so
735 usually only used as a getter.
736 Return type : String - the server root directory
737 Exceptions : none
738 Caller : general
739  
740 =cut
741  
742 sub serverroot {
743 my $self = shift;
744 $self->{'_serverroot'} = shift if (@_);
745 return $self->{'_serverroot'};
746 }
747  
748 =head2 get_database
749  
750 Arg[1] : String $database - the type of database to connect to
751 (eg core, otter)
752 Arg[2] : (optional) String $prefix - the prefix used for retrieving the
753 connection settings from the configuration
754 Example : my $db = $support->get_database('core');
755 Description : Connects to the database specified.
756 Return type : DBAdaptor of the appropriate type
757 Exceptions : thrown if asking for unknown database
758 Caller : general
759  
760 =cut
761  
762 sub get_database {
763 my $self = shift;
764 my $database = shift or throw("You must provide a database");
765 my $prefix = shift || '';
766 $self->check_required_params(
767 "${prefix}host",
768 "${prefix}port",
769 "${prefix}user",
770 "${prefix}dbname",
771 );
772 my %adaptors = (
773 core => 'Bio::EnsEMBL::DBSQL::DBAdaptor',
774 ensembl => 'Bio::EnsEMBL::DBSQL::DBAdaptor',
775 evega => 'Bio::EnsEMBL::DBSQL::DBAdaptor',
776 otter => 'Bio::Otter::DBSQL::DBAdaptor',
777 vega => 'Bio::Otter::DBSQL::DBAdaptor',
778 compara => 'Bio::EnsEMBL::Compara::DBSQL::DBAdaptor',
779 loutre => 'Bio::Vega::DBSQL::DBAdaptor',
780 );
781 throw("Unknown database: $database") unless $adaptors{$database};
782  
783 $self->dynamic_use($adaptors{$database});
784 my $species = 'species' . $species_c;
785 my $dba = $adaptors{$database}->new(
786 -host => $self->param("${prefix}host"),
787 -port => $self->param("${prefix}port"),
788 -user => $self->param("${prefix}user"),
789 -pass => $self->param("${prefix}pass") || '',
790 -dbname => $self->param("${prefix}dbname"),
791 -group => $database,
792 -species => $species,
793 );
794 #can use this approach to get dna from another db
795 # my $dna_db = $adaptors{$database}->new(
796 # -host => 'otterlive',
797 # -port => '3301',
798 # -user => $self->param("${prefix}user"),
799 # -pass => $self->param("${prefix}pass"),
800 # -dbname => 'loutre_human',
801 # );
802 # $dba->dnadb($dna_db);
803  
804 # otherwise explicitely set the dnadb to itself - by default the Registry assumes
805 # a group 'core' for this now
806 $dba->dnadb($dba);
807  
808 $species_c++;
809  
810 $self->{'_dba'}->{$database} = $dba;
811 $self->{'_dba'}->{'default'} = $dba unless $self->{'_dba'}->{'default'};
812 return $self->{'_dba'}->{$database};
813 }
814  
815  
816 =head2 get_dbconnection
817  
818 Arg[1] : (optional) String $prefix - the prefix used for retrieving the
819 connection settings from the configuration
820 Example : my $dbh = $self->get_dbconnection;
821 Description : Connects to the database server specified. You don't have to
822 specify a database name (this is useful for running commands
823 like $dbh->do('show databases')).
824 Return type : DBI database handle
825 Exceptions : thrown if connection fails
826 Caller : general
827 Status : At Risk
828  
829 =cut
830  
831 sub get_dbconnection {
832 my $self = shift;
833 my $prefix = shift;
834
835 $self->check_required_params(
836 "${prefix}host",
837 "${prefix}port",
838 "${prefix}user",
839 );
840  
841 my $dsn = "DBI:" . ($self->param('driver')||'mysql') .
842 ":host=" . $self->param("${prefix}host") .
843 ";port=" . $self->param("${prefix}port");
844  
845 if ($self->param("${prefix}dbname")) {
846 $dsn .= ";dbname=".$self->param("${prefix}dbname");
847 }
848  
849 # warn $dsn;
850  
851 my $dbh;
852 my $user = $self->param("${prefix}user");
853 my $pass = $self->param("${prefix}pass");
854 eval{
855 $dbh = DBI->connect($dsn, $user, $pass, {'RaiseError' => 1, 'PrintError' => 0});
856 };
857  
858 if (!$dbh || $@ || !$dbh->ping) {
859 $self->log_error("Could not connect to db server as user ".
860 $self->param("${prefix}user") .
861 " using [$dsn] as a locator:\n" . $DBI::errstr . $@);
862 }
863  
864 $self->{'_dbh'} = $dbh;
865 return $self->{'_dbh'};
866  
867 }
868  
869  
870 =head2 dba
871  
872 Arg[1] : (optional) String $database - type of db apaptor to retrieve
873 Example : my $dba = $support->dba;
874 Description : Getter for database adaptor. Returns default (i.e. created
875 first) db adaptor if no argument is provided.
876 Return type : Bio::EnsEMBL::DBSQL::DBAdaptor or Bio::Otter::DBSQL::DBAdaptor
877 Exceptions : none
878 Caller : general
879  
880 =cut
881  
882 sub dba {
883 my ($self, $database) = @_;
884 return $self->{'_dba'}->{$database} || $self->{'_dba'}->{'default'};
885 }
886  
887 =head2 dynamic_use
888  
889 Arg [1] : String $classname - The name of the class to require/import
890 Example : $self->dynamic_use('Bio::EnsEMBL::DBSQL::DBAdaptor');
891 Description: Requires and imports the methods for the classname provided,
892 checks the symbol table so that it doesnot re-require modules
893 that have already been required.
894 Returntype : true on success
895 Exceptions : Warns to standard error if module fails to compile
896 Caller : internal
897  
898 =cut
899  
900 sub dynamic_use {
901 my ($self, $classname) = @_;
902 my ($parent_namespace, $module) = $classname =~/^(.*::)(.*)$/ ? ($1,$2) : ('::', $classname);
903  
904 no strict 'refs'; ## no critic
905 # return if module has already been imported
906 return 1 if $parent_namespace->{$module.'::'} && %{ $parent_namespace->{$module.'::'}||{} };
907  
908 eval "require $classname"; ## no critic
909 throw("Failed to require $classname: $@") if ($@);
910 $classname->import();
911  
912 return 1;
913 }
914  
915 =head2 get_chrlength
916  
917 Arg[1] : (optional) Bio::EnsEMBL::DBSQL::DBAdaptor $dba
918 Arg[2] : (optional) String $version - coord_system version
919 Arg[3] : (optional) String $type - type of region eg chromsome (defaults to 'toplevel')
920 Arg[4] : (optional) Boolean - return non reference slies as well (required for haplotypes eq 6-COX)
921 Arg[5] : (optional) Override chromosome parameter filtering with this array reference. Empty denotes all.
922 Example : my $chr_length = $support->get_chrlength($dba);
923 Description : Get all chromosomes and their length from the database. Return
924 chr_name/length for the chromosomes the user requested (or all
925 chromosomes by default)
926 Return type : Hashref - chromosome_name => length
927 Exceptions : thrown if not passing a Bio::EnsEMBL::DBSQL::DBAdaptor
928 Caller : general
929  
930 =cut
931  
932 sub get_chrlength {
933 my ($self, $dba, $version,$type,$include_non_reference,$chroms) = @_;
934 $dba ||= $self->dba;
935 $type ||= 'toplevel';
936  
937 throw("get_chrlength should be passed a Bio::EnsEMBL::DBSQL::DBAdaptor\n")
938 unless ($dba->isa('Bio::EnsEMBL::DBSQL::DBAdaptor'));
939  
940 my $sa = $dba->get_SliceAdaptor;
941  
942 my @chromosomes = map { $_->seq_region_name }
943 @{ $sa->fetch_all($type,$version,$include_non_reference) };
944 my %chr = map { $_ => $sa->fetch_by_region($type, $_, undef, undef, undef, $version)->length } @chromosomes;
945  
946 my @wanted = $self->param('chromosomes');
947 @wanted = @$chroms if defined $chroms and ref($chroms) eq 'ARRAY';
948  
949 if (@wanted) {
950 # check if user supplied invalid chromosome names
951 foreach my $chr (@wanted) {
952 my $found = 0;
953 foreach my $chr_from_db (keys %chr) {
954 if ($chr_from_db eq $chr) {
955 $found = 1;
956 last;
957 }
958 }
959 unless ($found) {
960 #if you get this when using ensembl-vega then the dbname will be misleading.
961 warning("Didn't find chromosome $chr in database " .
962 $self->param('dbname'));
963 }
964 }
965  
966 # filter to requested chromosomes only
967 HASH:
968 foreach my $chr_from_db (keys %chr) {
969 foreach my $chr (@wanted) {
970 if ($chr_from_db eq $chr) {
971 next HASH;
972 }
973 }
974 delete($chr{$chr_from_db});
975 }
976 }
977  
978 return \%chr;
979 }
980  
981 =head2 get_ensembl_chr_mapping
982  
983 Arg[1] : (optional) Bio::EnsEMBL::DBSQL::DBAdaptor $dba
984 Arg[2] : (optional) String $version - coord_system version
985 Example : my $ensembl_mapping = $support->get_ensembl_chr_mapping($dba);
986 Description : Gets a mapping between Vega chromosome names and their
987 equivalent Ensembl chromosomes. Works with non-reference chromosomes
988 Return type : Hashref - Vega name => Ensembl name
989 Exceptions : thrown if not passing a Bio::EnsEMBL::DBSQL::DBAdaptor
990 Caller : general
991  
992 =cut
993  
994 sub get_ensembl_chr_mapping {
995 my ($self, $dba, $version) = @_;
996 $dba ||= $self->dba;
997 throw("get_ensembl_chr_mapping should be passed a Bio::EnsEMBL::DBSQL::DBAdaptor\n") unless ($dba->isa('Bio::EnsEMBL::DBSQL::DBAdaptor'));
998  
999 my $sa = $dba->get_SliceAdaptor;
1000 my @chromosomes = map { $_->seq_region_name }
1001 @{ $sa->fetch_all('chromosome', $version, 1) };
1002  
1003 my %chrs;
1004 foreach my $chr (@chromosomes) {
1005 my $sr = $sa->fetch_by_region('chromosome', $chr, undef, undef, undef, $version);
1006 my ($ensembl_name_attr) = @{ $sr->get_all_Attributes('ensembl_name') };
1007 if ($ensembl_name_attr) {
1008 $chrs{$chr} = $ensembl_name_attr->value;
1009 } else {
1010 $chrs{$chr} = $chr;
1011 }
1012 }
1013 return \%chrs;
1014 }
1015  
1016 =head2 get_taxonomy_id
1017  
1018 Arg[1] : Bio::EnsEMBL::DBSQL::DBAdaptor $dba
1019 Example : my $sid = $support->get_taxonony_id($dba);
1020 Description : Retrieves the taxononmy ID from the meta table
1021 Return type : Int - the taxonomy ID
1022 Exceptions : thrown if no taxonomy ID is found in the database
1023 Caller : general
1024  
1025 =cut
1026  
1027 sub get_taxonomy_id {
1028 my ($self, $dba) = @_;
1029 $dba ||= $self->dba;
1030 my $sql = 'SELECT meta_value FROM meta WHERE meta_key = "species.taxonomy_id"';
1031 my $sth = $dba->dbc->db_handle->prepare($sql);
1032 $sth->execute;
1033 my ($tid) = $sth->fetchrow_array;
1034 $sth->finish;
1035 $self->throw("Could not determine taxonomy_id from database.") unless $tid;
1036 return $tid;
1037 }
1038  
1039 =head2 get_species_scientific_name
1040  
1041 Arg[1] : Bio::EnsEMBL::DBSQL::DBAdaptor $dba
1042 Example : my $species = $support->get_species_scientific_name($dba);
1043 Description : Retrieves the species scientific name (Genus species) from the
1044 meta table
1045 Return type : String - species scientific name
1046 Exceptions : thrown if species name can not be determined from db
1047 Caller : general
1048  
1049 =cut
1050  
1051 sub get_species_scientific_name {
1052 my ($self, $dba) = @_;
1053 $dba ||= $self->dba;
1054 my $sql = "SELECT meta_value FROM meta WHERE meta_key = \'species.scientific_name\'";
1055 my $sth = $dba->dbc->db_handle->prepare($sql);
1056 $sth->execute;
1057 my @sp;
1058 while (my @row = $sth->fetchrow_array) {
1059 push @sp, $row[0];
1060 }
1061 if (! @sp || @sp > 1) {
1062 $self->throw("Could not retrieve a single species scientific name from database.");
1063 }
1064 $sth->finish;
1065 my $species = $sp[0];
1066 $species =~ s/ /_/g;
1067 return $species;
1068 }
1069  
1070 =head2 species
1071  
1072 Arg[1] : (optional) String $species - species name to set
1073 Example : my $species = $support->species;
1074 my $url = "http://vega.sanger.ac.uk/$species/";
1075 Description : Getter/setter for species name (Genus_species). If not set, it's
1076 determined from database's meta table
1077 Return type : String - species name
1078 Exceptions : none
1079 Caller : general
1080  
1081 =cut
1082  
1083 sub species {
1084 my $self = shift;
1085 $self->{'_species'} = shift if (@_);
1086 # get species name from database if not set
1087 unless ($self->{'_species'}) {
1088 $self->{'_species'} = $self->get_species_scientific_name;
1089 }
1090 return $self->{'_species'};
1091 }
1092  
1093 =head2 sort_chromosomes
1094  
1095 Arg[1] : (optional) Hashref $chr_hashref - Hashref with chr_name as keys
1096 Example : my $chr = { '6-COX' => 1, '1' => 1, 'X' => 1 };
1097 my @sorted = $support->sort_chromosomes($chr);
1098 Description : Sorts chromosomes in an intuitive way (numerically, then
1099 alphabetically). If no chromosome hashref is passed, it's
1100 retrieve by calling $self->get_chrlength()
1101 Return type : List - sorted chromosome names
1102 Exceptions : thrown if no hashref is provided
1103 Caller : general
1104  
1105 =cut
1106  
1107 sub sort_chromosomes {
1108 my ($self, $chr_hashref, $version, $include_non_reference) = @_;
1109 $chr_hashref = $self->get_chrlength($self->dba, $version, 'chromosome', $include_non_reference) unless ($chr_hashref);
1110 throw("You have to pass a hashref of your chromosomes")
1111 unless ($chr_hashref and ref($chr_hashref) eq 'HASH');
1112 return (sort _by_chr_num keys %$chr_hashref);
1113 }
1114  
1115 =head2 _by_chr_num
1116  
1117 Example : my @sorted = sort _by_chr_num qw(X, 6-COX, 14, 7);
1118 Description : Subroutine to use in sort for sorting chromosomes. Sorts
1119 numerically, then alphabetically
1120 Return type : values to be used by sort
1121 Exceptions : none
1122 Caller : internal ($self->sort_chromosomes)
1123  
1124 =cut
1125  
1126 sub _by_chr_num {
1127 my @awords = split /-/, $a;
1128 my @bwords = split /-/, $b;
1129  
1130 my $anum = $awords[0];
1131 my $bnum = $bwords[0];
1132  
1133 if ($anum !~ /^[0-9]*$/) {
1134 if ($bnum !~ /^[0-9]*$/) {
1135 return $anum cmp $bnum;
1136 } else {
1137 return 1;
1138 }
1139 }
1140 if ($bnum !~ /^[0-9]*$/) {
1141 return -1;
1142 }
1143  
1144 if ($anum <=> $bnum) {
1145 return $anum <=> $bnum;
1146 } else {
1147 if ($#awords == 0) {
1148 return -1;
1149 } elsif ($#bwords == 0) {
1150 return 1;
1151 } else {
1152 return $awords[1] cmp $bwords[1];
1153 }
1154 }
1155 }
1156  
1157 =head2 split_chromosomes_by_size
1158  
1159 Arg[1] : (optional) Int $cutoff - the cutoff in bp between small and
1160 large chromosomes
1161 Arg[2] : (optional) Boolean to include duplicate regions, ie PAR or not
1162 (default is no)
1163 Arg[3] : (optional) Coordsystem version to retrieve
1164  
1165 Example : my $chr_slices = $support->split_chromosomes_by_size;
1166 foreach my $block_size (keys %{ $chr_slices }) {
1167 print "Chromosomes with blocksize $block_size: ";
1168 print join(", ", map { $_->seq_region_name }
1169 @{ $chr_slices->{$block_size} });
1170 }
1171 Description : Determines block sizes for storing DensityFeatures on
1172 chromosomes, and return slices for each chromosome. The block
1173 size is determined so that you have 150 bins for the smallest
1174 chromosome over 5 Mb in length. For chromosomes smaller than 5
1175 Mb, an additional smaller block size is used to yield 150 bins
1176 for the overall smallest chromosome. This will result in
1177 reasonable resolution for small chromosomes and high
1178 performance for big ones. Does not return non-reference seq_regions
1179 Return type : Hashref (key: block size; value: Arrayref of chromosome
1180 Bio::EnsEMBL::Slices)
1181 Exceptions : none
1182 Caller : density scripts
1183  
1184 =cut
1185  
1186 sub split_chromosomes_by_size {
1187 my $self = shift;
1188 my $cutoff = shift || 5000000;
1189 my $dup = shift || 0;
1190 my $cs_version = shift;
1191 my $include_non_reference = 1; #get non reference slices
1192 my $slice_adaptor = $self->dba->get_SliceAdaptor;
1193 my ($top_slices, $wanted_slices, $missed_slices);
1194 if ($self->param('chromosomes')) {
1195 foreach my $chr ($self->param('chromosomes')) {
1196 push @{ $top_slices }, $slice_adaptor->fetch_by_region('chromosome', $chr);
1197 }
1198 }
1199 else {
1200 $top_slices = $slice_adaptor->fetch_all('chromosome',$cs_version,$include_non_reference,$dup);
1201 }
1202  
1203 # filter out patches, if present
1204 $wanted_slices = [ grep { $_->is_reference or $self->is_haplotype($_,$self->dba) } @$top_slices ];
1205  
1206 # make a note of which ones are excluded
1207 $missed_slices = [ grep { ! $_->is_reference and ! $self->is_haplotype($_,$self->dba) } @$top_slices ];
1208  
1209 #warn non PATCH toplevels slice that are excluded (could be haplotypes if an earlier stage has failed)
1210 foreach (@{$missed_slices || []}) {
1211 my $sr_name = $_->seq_region_name;
1212 if ($self->is_patch($_)) {
1213 $self->log("Excluding $sr_name\n");
1214 }
1215 else {
1216 $self->log_warning("Excluding $sr_name, are you sure ?\n");
1217 }
1218 }
1219  
1220 my ($big_chr, $small_chr, $min_big_chr, $min_small_chr);
1221 foreach my $slice (@{ $wanted_slices }) {
1222 next if ($slice->length eq 10000); #hack for chrY pseudoslice
1223 if ($slice->length < $cutoff) {
1224 if (! $min_small_chr or ($min_small_chr > $slice->length)) {
1225 $min_small_chr = $slice->length;
1226 }
1227 # push small chromosomes onto $small_chr
1228 push @{ $small_chr }, $slice;
1229 }
1230 elsif (! $min_big_chr or ($min_big_chr > $slice->length) ){
1231 $min_big_chr = $slice->length;
1232 }
1233 # push _all_ chromosomes onto $big_chr
1234 push @{ $big_chr }, $slice;
1235 }
1236 my $chr_slices;
1237 $chr_slices->{int($min_big_chr/150)} = $big_chr if $min_big_chr;
1238 $chr_slices->{int($min_small_chr/150)} = $small_chr if $min_small_chr;
1239 return $chr_slices;
1240 }
1241  
1242 =head2 is_patch
1243  
1244 Arg[1] : B::E::Slice
1245 Example : if ($support->is_patch($slice)) { ...
1246 Description : Looks at seq_region attributes to decide if a slice is a patch or not
1247 If PATCH seq_region_attrib is not there check to see if name suggests it is a PATCH
1248 Return type : true/false
1249  
1250 =cut
1251  
1252 sub is_patch {
1253 my ($self,$slice) = @_;
1254 my @patch_attrib_types = qw(patch_fix patch_novel); #seq_region_attribs used to define a patch
1255 foreach my $attrib_type (@patch_attrib_types) {
1256 if (@{$slice->get_all_Attributes($attrib_type)}) {
1257 return 1;
1258 }
1259 }
1260 return 0;
1261 }
1262  
1263  
1264 =head2 log
1265  
1266 Arg[1] : String $txt - the text to log
1267 Arg[2] : Int $indent - indentation level for log message
1268 Example : my $log = $support->log_filehandle;
1269 $support->log('Log foo.\n', 1);
1270 Description : Logs a message to the filehandle initialised by calling
1271 $self->log_filehandle(). You can supply an indentation level
1272 to get nice hierarchical log messages.
1273 Return type : true on success
1274 Exceptions : thrown when no filehandle can be obtained
1275 Caller : general
1276  
1277 =cut
1278  
1279 sub log {
1280 my ($self, $txt, $indent) = @_;
1281 $indent ||= 0;
1282  
1283 # strip off leading linebreaks so that indenting doesn't break
1284 $txt =~ s/^(\n*)//;
1285  
1286 $txt = $1." "x$indent . $txt;
1287 my $fh = $self->{'_log_filehandle'};
1288 throw("Unable to obtain log filehandle") unless $fh;
1289 print $fh "$txt";
1290 return(1);
1291 }
1292  
1293 =head2 lock_log
1294  
1295 Description : Use flock-style locks to lock log and fastforward to end.
1296 Useful if log is being written to by multiple processes.
1297 =cut
1298  
1299 sub lock_log {
1300 my ($self) = @_;
1301 ## no critic
1302 my $fh = $self->{'_log_filehandle'};
1303 return if -t $fh or -p $fh; # Shouldn't lock such things
1304 flock($self->{'_log_filehandle'},LOCK_EX) || return 0;
1305 seek($self->{'_log_filehandle'},0,SEEK_END); # fail ok, prob not reg file
1306 return 1;
1307 }
1308  
1309 =head2 unlock_log
1310  
1311 Description : Unlock log previously locked by lock_log.
1312  
1313 =cut
1314  
1315 sub unlock_log {
1316 my ($self) = @_;
1317 ## no critic
1318 my $fh = $self->{'_log_filehandle'};
1319 return if -t $fh or -p $fh; # We don't lock such things
1320 # flush is implicit in flock
1321 flock($self->{'_log_filehandle'},LOCK_UN) || return 0;
1322 return 1;
1323 }
1324  
1325 =head2 log_warning
1326  
1327 Arg[1] : String $txt - the warning text to log
1328 Arg[2] : Int $indent - indentation level for log message
1329 Arg[3] : Bool - add a line break before warning if true
1330 Example : my $log = $support->log_filehandle;
1331 $support->log_warning('Log foo.\n', 1);
1332 Description : Logs a message via $self->log and increases the warning counter.
1333 Return type : true on success
1334 Exceptions : none
1335 Caller : general
1336  
1337 =cut
1338  
1339 sub log_warning {
1340 my ($self, $txt, $indent, $break) = @_;
1341 $txt = "WARNING: " . $txt;
1342 $txt = "\n$txt" if ($break);
1343 $self->log($txt, $indent);
1344 $self->{'_warnings'}++;
1345 return(1);
1346 }
1347  
1348 =head2 log_error
1349  
1350 Arg[1] : String $txt - the error text to log
1351 Arg[2] : Int $indent - indentation level for log message
1352 Example : my $log = $support->log_filehandle;
1353 $support->log_error('Log foo.\n', 1);
1354 Description : Logs a message via $self->log and exits the script.
1355 Return type : none
1356 Exceptions : none
1357 Caller : general
1358  
1359 =cut
1360  
1361 sub log_error {
1362 my ($self, $txt, $indent) = @_;
1363 $txt = "ERROR: ".$txt;
1364 $self->log($txt, $indent);
1365 $self->log("Exiting.\n");
1366 exit;
1367 }
1368  
1369 =head2 log_verbose
1370  
1371 Arg[1] : String $txt - the warning text to log
1372 Arg[2] : Int $indent - indentation level for log message
1373 Example : my $log = $support->log_filehandle;
1374 $support->log_verbose('Log this verbose message.\n', 1);
1375 Description : Logs a message via $self->log if --verbose option was used
1376 Return type : TRUE on success, FALSE if not verbose
1377 Exceptions : none
1378 Caller : general
1379  
1380 =cut
1381  
1382 sub log_verbose {
1383 my ($self, $txt, $indent) = @_;
1384 return(0) unless $self->param('verbose');
1385 $self->log($txt, $indent);
1386 return(1);
1387 }
1388  
1389 =head2 log_stamped
1390  
1391 Arg[1] : String $txt - the warning text to log
1392 Arg[2] : Int $indent - indentation level for log message
1393 Example : my $log = $support->log_filehandle;
1394 $support->log_stamped('Log this stamped message.\n', 1);
1395 Description : Appends timestamp and memory usage to a message and logs it via
1396 $self->log
1397 Return type : TRUE on success
1398 Exceptions : none
1399 Caller : general
1400  
1401 =cut
1402  
1403 sub log_stamped {
1404 my ($self, $txt, $indent) = @_;
1405 # append timestamp and memory usage to log text
1406 $txt =~ s/(\n*)$//;
1407 $txt .= " ".$self->date_and_mem.$1;
1408 $self->log($txt, $indent);
1409 return(1);
1410 }
1411  
1412 =head2 log_filehandle
1413  
1414 Arg[1] : (optional) String $mode - file access mode
1415 Example : my $log = $support->log_filehandle;
1416 # print to the filehandle
1417 print $log 'Lets start logging...\n';
1418 # log via the wrapper $self->log()
1419 $support->log('Another log message.\n');
1420 Description : Returns a filehandle for logging (STDERR by default, logfile if
1421 set from config or commandline). You can use the filehandle
1422 directly to print to, or use the smart wrapper $self->log().
1423 Logging mode (truncate or append) can be set by passing the
1424 mode as an argument to log_filehandle(), or with the
1425 --logappend commandline option (default: truncate)
1426 Return type : Filehandle - the filehandle to log to
1427 Exceptions : thrown if logfile can't be opened
1428 Caller : general
1429  
1430 =cut
1431  
1432 sub log_filehandle {
1433 my ($self, $mode, $date) = @_;
1434 $mode ||= '>';
1435 $mode = '>>' if ($self->param('logappend'));
1436 my $fh = \*STDERR;
1437 if (my $logfile = $self->param('logfile')) {
1438 $logfile .= "_$date" if $date;
1439 if (my $logpath = $self->param('logpath')) {
1440 unless (-e $logpath) {
1441 system("mkdir $logpath") == 0 or
1442 $self->log_error("Can't create log dir $logpath: $!\n");
1443 }
1444 $logfile = "$logpath/$logfile";
1445 }
1446 open($fh, "$mode", $logfile) or throw(
1447 "Unable to open $logfile for writing: $!");
1448 }
1449 $self->{'_log_filehandle'} = $fh;
1450 return $self->{'_log_filehandle'};
1451 }
1452  
1453 =head2 filehandle
1454  
1455 Arg[1] : String $mode - file access mode
1456 Arg[2] : String $file - input or output file
1457 Example : my $fh = $support->filehandle('>>', '/path/to/file');
1458 # print to the filehandle
1459 print $fh 'Your text goes here...\n';
1460 Description : Returns a filehandle (*STDOUT for writing, *STDIN for reading
1461 by default) to print to or read from.
1462 Return type : Filehandle - the filehandle
1463 Exceptions : thrown if file can't be opened
1464 Caller : general
1465  
1466 =cut
1467  
1468 sub filehandle {
1469 my ($self, $mode, $file) = @_;
1470 $mode ||= ">";
1471 my $fh;
1472 if ($file) {
1473 open($fh, "$mode", $file) or throw(
1474 "Unable to open $file for writing: $!");
1475 } elsif ($mode =~ />/) {
1476 $fh = \*STDOUT;
1477 } elsif ($mode =~ /</) {
1478 $fh = \*STDIN;
1479 }
1480 return $fh;
1481 }
1482  
1483 =head2 init_log_date
1484  
1485 Example : $support->init_log_date;
1486 Description : Opens a filehandle to a logfile with the date in the file name
1487 Return type : Filehandle - the log filehandle
1488 Exceptions : none
1489 Caller : general
1490  
1491 =cut
1492  
1493 sub init_log_date {
1494 my $self = shift;
1495 my $date = $self->date;
1496 return $self->init_log($date);
1497 }
1498  
1499 =head2 init_log
1500  
1501 Example : $support->init_log;
1502 Description : Opens a filehandle to the logfile and prints some header
1503 information to this file. This includes script name, date, user
1504 running the script and parameters the script will be running
1505 with.
1506 Return type : Filehandle - the log filehandle
1507 Exceptions : none
1508 Caller : general
1509  
1510 =cut
1511  
1512 sub init_log {
1513 my $self = shift;
1514 my $date = shift;
1515  
1516 # get a log filehandle
1517 my $log = $self->log_filehandle(undef,$date);
1518  
1519 # print script name, date, user who is running it
1520 unless($self->param('hideparamlist')) {
1521 my $hostname = `hostname`;
1522 chomp $hostname;
1523 my $script = "$hostname:$Bin/$Script";
1524 my $user = `whoami`;
1525 chomp $user;
1526 $self->log("Script: $script\nDate: ".$self->date_and_time."\nUser: $user\n");
1527  
1528 # print parameters the script is running with
1529 $self->log("Parameters:\n\n");
1530 $self->log($self->list_all_params);
1531 }
1532 # remember start time
1533 $self->{'_start_time'} = time;
1534  
1535 return $log;
1536 }
1537  
1538 =head2 finish_log
1539  
1540 Example : $support->finish_log;
1541 Description : Writes footer information to a logfile. This includes the
1542 number of logged warnings, timestamp and memory footprint.
1543 Return type : TRUE on success
1544 Exceptions : none
1545 Caller : general
1546  
1547 =cut
1548  
1549 sub finish_log {
1550 my $self = shift;
1551  
1552 unless($self->param('hideparamlist')) {
1553 $self->log("\nAll done. ".$self->warnings." warnings. ");
1554 if ($self->{'_start_time'}) {
1555 $self->log("Runtime ");
1556 my $diff = time - $self->{'_start_time'};
1557 my $sec = $diff % 60;
1558 $diff = ($diff - $sec) / 60;
1559 my $min = $diff % 60;
1560 my $hours = ($diff - $min) / 60;
1561 $self->log("${hours}h ${min}min ${sec}sec ");
1562 }
1563 $self->log($self->date_and_mem."\n\n");
1564 }
1565 if($self->param('joblog')) {
1566 my $fh;
1567 unless(open($fh,'>',$self->param('joblog'))) {
1568 $self->log_warning("Could not log job to '".$self->param('joblog').
1569 "': $!");
1570 return 1;
1571 }
1572 my @keys;
1573 push @keys,"RUNTIME",(time - $self->{'_start_time'});
1574 my $mem = `ps -p $$ -o vsz |tail -1`;
1575 chomp $mem;
1576 push @keys,"MEMORY",$mem;
1577 push @keys,"WARNINGS",$self->warnings;
1578 push @keys,"START",$self->{'_start_time'};
1579 push @keys,"END",time;
1580 while(@keys) {
1581 my ($k,$v) = splice(@keys,0,2);
1582 print $fh "$k: $v\n";
1583 }
1584 close $fh;
1585 }
1586 return(1);
1587 }
1588  
1589 =head2 date_and_mem
1590  
1591 Example : print LOG "Time, memory usage: ".$support->date_and_mem."\n";
1592 Description : Prints a timestamp and the memory usage of your script.
1593 Return type : String - timestamp and memory usage
1594 Exceptions : none
1595 Caller : general
1596  
1597 =cut
1598  
1599 sub date_and_mem {
1600 my $date = strftime "%Y-%m-%d %T", localtime;
1601 my $mem = `ps -p $$ -o vsz |tail -1`;
1602 chomp $mem;
1603 return "[$date, mem $mem]";
1604 }
1605  
1606 =head2 date
1607  
1608 Example : print "Date: " . $support->date . "\n";
1609 Description : Prints a nicely formatted datetamp (YYYY-DD-MM)
1610 Return type : String - the timestamp
1611 Exceptions : none
1612 Caller : general
1613  
1614 =cut
1615  
1616 sub date {
1617 return strftime "%Y-%m-%d", localtime;
1618 }
1619  
1620 =head2 date_and_time
1621  
1622 Example : print "Date: " . $support->date . "\n";
1623 Description : Prints a nicely formatted timestamp (YYYY-DD-MM hh:mm:ss)
1624 Return type : String - the timestamp
1625 Exceptions : none
1626 Caller : general
1627  
1628 =cut
1629  
1630 sub date_and_time {
1631 return strftime "%Y-%m-%d %T", localtime;
1632 }
1633  
1634 =head2 format_time
1635  
1636 Example : print $support->format_time($gene->modifed_date) . "\n";
1637 Description : Prints timestamps from the database
1638 Return type : String - nicely formatted time stamp
1639 Exceptions : none
1640 Caller : general
1641  
1642 =cut
1643  
1644  
1645 sub date_format {
1646 my( $self, $time, $format ) = @_;
1647 my( $d,$m,$y) = (localtime($time))[3,4,5];
1648 my %S = ('d'=>sprintf('%02d',$d),'m'=>sprintf('%02d',$m+1),'y'=>$y+1900);
1649 (my $res = $format ) =~s/%(\w)/$S{$1}/ge;
1650 return $res;
1651 }
1652  
1653  
1654 =head2 mem
1655  
1656 Example : print "Memory usage: " . $support->mem . "\n";
1657 Description : Prints the memory used by your script. Not sure about platform
1658 dependence of this call ...
1659 Return type : String - memory usage
1660 Exceptions : none
1661 Caller : general
1662  
1663 =cut
1664  
1665 sub mem {
1666 my $mem = `ps -p $$ -o vsz |tail -1`;
1667 chomp $mem;
1668 return $mem;
1669 }
1670  
1671 =head2 commify
1672  
1673 Arg[1] : Int $num - a number to commify
1674 Example : print "An easy to read number: ".$self->commify(100000000);
1675 # will print 100,000,000
1676 Description : put commas into a number to make it easier to read
1677 Return type : a string representing the commified number
1678 Exceptions : none
1679 Caller : general
1680 Status : stable
1681  
1682 =cut
1683  
1684 sub commify {
1685 my $self = shift;
1686 my $num = shift;
1687  
1688 $num = reverse($num);
1689 $num =~ s/(\d\d\d)(?=\d)(?!\d*\.)/$1,/g;
1690  
1691 return scalar reverse $num;
1692 }
1693  
1694 =head2 fetch_non_hidden_slices
1695  
1696 Arg[1] : B::E::SliceAdaptor
1697 Arg[2] : B::E::AttributeAdaptor
1698 Arg[3] : string $coord_system_name (optional) - 'chromosome' by default
1699 Arg[4] : string $coord_system_version (optional) - 'otter' by default
1700 Example : $chroms = $support->fetch_non_hidden_slice($sa,$aa);
1701 Description : retrieve all slices from a loutre database that don't have a hidden attribute.
1702 Doesn't retrieve non-reference slices
1703 Return type : arrayref
1704 Caller : general
1705 Status : stable
1706  
1707 =cut
1708  
1709 sub fetch_non_hidden_slices {
1710 my $self = shift;
1711 my $aa = shift or throw("You must supply an attribute adaptor");
1712 my $sa = shift or throw("You must supply a slice adaptor");
1713 my $cs = shift || 'chromosome';
1714 my $cv = shift || 'Otter';
1715 my $visible_chroms;
1716 foreach my $chrom ( @{$sa->fetch_all($cs,$cv)} ) {
1717 my $chrom_name = $chrom->name;
1718 my $attribs = $aa->fetch_all_by_Slice($chrom,'hidden');
1719 if ( scalar(@$attribs) > 1 ) {
1720 $self->log_warning("More than one hidden attribute for chromosome $chrom_name\n");
1721 }
1722 elsif ($attribs->[0]->value == 0) {
1723 push @$visible_chroms, $chrom;
1724 }
1725 elsif ($attribs->[0]->value == 1) {
1726 $self->log_verbose("chromosome $chrom_name is hidden\n");
1727 }
1728 else {
1729 $self->log_warning("No hidden attribute for chromosome $chrom_name\n");
1730 }
1731 }
1732 return $visible_chroms;
1733 }
1734  
1735 =head2 get_non_hidden_slice_names
1736  
1737 Arg[1] : B::E::SliceAdaptor
1738 Arg[2] : B::E::AttributeAdaptor
1739 Arg[3] : string $coord_system_name (optional) - 'chromosome' by default
1740 Arg[4] : string $coord_system_version (optional) - 'otter' by default
1741 Example : $chrom_names = $support->get_non_hidden_slice_names($sa,$aa);
1742 Description : retrieve names of all slices from a loutre database that don't have a hidden attribute.
1743 Doesn't retrieve non-reference slices
1744 Return type : arrayref of names of all non-hidden slices
1745 Caller : general
1746 Status : stable
1747  
1748 =cut
1749  
1750 sub get_non_hidden_slice_names {
1751 my $self = shift;
1752 my $aa = shift or throw("You must supply an attribute adaptor");
1753 my $sa = shift or throw("You must supply a slice adaptor");
1754 my $cs = shift || 'chromosome';
1755 my $cv = shift || 'Otter';
1756 my $visible_chrom_names;
1757 foreach my $chrom ( @{$sa->fetch_all($cs,$cv)} ) {
1758 my $chrom_name = $chrom->seq_region_name;
1759 my $attribs = $aa->fetch_all_by_Slice($chrom,'hidden');
1760 if ( scalar(@$attribs) > 1 ) {
1761 $self->log_warning("More than one hidden attribute for chromosome $chrom_name\n");
1762 }
1763 elsif ($attribs->[0]->value == 0) {
1764 push @$visible_chrom_names, $chrom_name;
1765 }
1766 elsif ($attribs->[0]->value == 1) {
1767 $self->log_verbose("chromosome $chrom_name is hidden\n");
1768 }
1769 else {
1770 $self->log_warning("No hidden attribute for chromosome $chrom_name\n");
1771 }
1772 }
1773 return $visible_chrom_names;
1774 }
1775  
1776  
1777 =head2 get_wanted_chromosomes
1778  
1779 Arg[1] : B::E::SliceAdaptor
1780 Arg[2] : B::E::AttributeAdaptor
1781 Arg[3] : string $coord_system_name (optional) - 'chromosome' by default
1782 Arg[4] : string $coord_system_version (optional) - 'otter' by default
1783 Example : $chr_names = $support->get_wanted_chromosomes($laa,$lsa);
1784 Description : retrieve names of slices from a lutra database that are ready for dumping to Vega.
1785 Deals with list of names to ignore (ignore_chr = LIST)
1786 Return type : arrayref of slices
1787 Caller : general
1788 Status : stable
1789  
1790 =cut
1791  
1792 sub get_wanted_chromosomes {
1793 my $self = shift;
1794 my $aa = shift or throw("You must supply an attribute adaptor");
1795 my $sa = shift or throw("You must supply a slice adaptor");
1796 my $cs = shift || 'chromosome';
1797 my $cv = shift || 'Otter';
1798 my $export_mode = $self->param('release_type');
1799 my $release = $self->param('vega_release');
1800 my $names;
1801 my $chroms = $self->fetch_non_hidden_slices($aa,$sa,$cs,$cv);
1802 CHROM:
1803 foreach my $chrom (@$chroms) {
1804 my $attribs = $aa->fetch_all_by_Slice($chrom);
1805 my $vals = $self->get_attrib_values($attribs,'vega_export_mod');
1806 if (scalar(@$vals > 1)) {
1807 $self->log_warning ("Multiple attribs for \'vega_export_mod\', please fix before continuing");
1808 exit;
1809 }
1810 next CHROM if (! grep { $_ eq $export_mode} @$vals);
1811 $vals = $self->get_attrib_values($attribs,'vega_release',$release);
1812 if (scalar(@$vals > 1)) {
1813 $self->log_warning ("Multiple attribs for \'vega_release\' value = $release , please fix before continuing");
1814 exit;
1815 }
1816 next CHROM if (! grep { $_ eq $release} @$vals);
1817 my $name = $chrom->seq_region_name;
1818 if (my @ignored = $self->param('ignore_chr')) {
1819 next CHROM if (grep {$_ eq $name} @ignored);
1820 }
1821 push @{$names}, $name;
1822 }
1823 return $names;
1824 }
1825  
1826 =head2 is_haplotype
1827  
1828 Arg[1] : B::E::Slice
1829 Arg[2]: : B::E::DBAdaptor (optional, if you don't supply one then the *first* one you generated is returned, which may or may not be what you want!)
1830 Description : Is the slice a Vega haplotype? At the moment this is
1831 implemented by testing for presence of vega_ref_chrom but non_ref
1832 which is correct in practice, but really misses the prupose of
1833 vega_ref_chrom, so this might bite us if that changes.
1834 Return type : boolean
1835  
1836 =cut
1837  
1838 sub is_haplotype {
1839 my ($self,$slice,$dba) = @_;
1840  
1841 $dba ||= $self->dba;
1842 my $aa = $dba->get_adaptor('Attribute');
1843  
1844 my $attribs = $aa->fetch_all_by_Slice($slice);
1845 return (@{$self->get_attrib_values($attribs,'vega_ref_chrom')} and
1846 @{$self->get_attrib_values($attribs,'non_ref',1)});
1847 }
1848  
1849 =head2 get_unique_genes
1850  
1851 Arg[1] : B::E::Slice
1852 Arg[2] : B::E::DBAdaptor (optional, if you don't supply one then the *first* one you generated is returned, which may or may not be what you want!)
1853 Example : $genes = $support->get_unique_genes($slice,$dba);
1854 Description : Retrieve genes that are only on the slice itself - used for human where assembly patches
1855 are in the assembly_exception table. Needs the PATCHes to have 'non_ref' seq_region_attributes.
1856 Return type : arrayref of genes
1857 Caller : general
1858 Status : stable
1859  
1860 =cut
1861  
1862 sub get_unique_genes {
1863 my $self = shift;
1864 my ($slice,$dba) = @_;
1865 $slice or throw("You must supply a slice");
1866 $dba ||= $self->dba;
1867  
1868 my $sa = $dba->get_adaptor('Slice');
1869 my $ga = $dba->get_adaptor('Gene');
1870 my $patch = 0;
1871 my $genes = [];
1872 if ( ! $slice->is_reference() and ! $self->is_haplotype($slice,$dba) ) {
1873 # if ( 0 ) {
1874 $patch = 1;
1875 my $slices = $sa->fetch_by_region_unique( $slice->coord_system_name(),$slice->seq_region_name(),undef,undef,undef,$slice->coord_system()->version() );
1876 foreach my $slice ( @{$slices} ) {
1877 push @$genes,@{$ga->fetch_all_by_Slice($slice)};
1878 # my $start = $slice->start;
1879 }
1880 }
1881 else {
1882 $genes = $ga->fetch_all_by_Slice($slice);
1883 }
1884 return ($genes, $patch);
1885 }
1886  
1887  
1888  
1889 =head2 get_attrib_values
1890  
1891 Arg[1] : Arrayref of B::E::Attributes
1892 Arg[2] : 'code' to search for
1893 Arg[3] : 'value' to search for (optional)
1894 Example : my $c = $self->get_attrib_values($attribs,'name'));
1895 Description : (i) In the absence of an attribute value argument, examines an arrayref
1896 of B::E::Attributes for a particular attribute type, returning the values
1897 for each attribute of that type. Can therefore be used to test for the
1898 number of attributes of that type.
1899 (ii) In the presence of the optional value argument it returns all
1900 attributes with that value ie can be used to test for the presence of an
1901 attribute with that particular value.
1902 Return type : arrayref of values for that attribute
1903 Caller : general
1904 Status : stable
1905  
1906 =cut
1907  
1908 sub get_attrib_values {
1909 my $self = shift;
1910 my $attribs = shift;
1911 my $code = shift;
1912 my $value = shift;
1913 if (my @atts = grep {$_->code eq $code } @$attribs) {
1914 my $r = [];
1915 if ($value) {
1916 if (my @values = grep {$_->value eq $value} @atts) {
1917 foreach (@values) {
1918 push @$r, $_->value;
1919 }
1920 return $r;
1921 }
1922 else {
1923 return [];
1924 }
1925 }
1926 else {
1927 foreach (@atts) {
1928 push @$r, $_->value;
1929 }
1930 return $r;
1931 }
1932 }
1933 else {
1934 return [];
1935 }
1936 }
1937  
1938 =head2 fix_attrib_value
1939  
1940 Arg[1] : Arrayref of existing B::E::Attributes
1941 Arg[2] : dbID of object
1942 Arg[3] : name of object (just for reporting)
1943 Arg[4] : attrib_type.code
1944 Arg[5] : attrib_type.value
1945 Arg[6] : interactive ? (0 by default)
1946 Arg[7] : table
1947 Example : $support->fix_attrib_value($attribs,$chr_id,$chr_name,'vega_export_mod','N',1);
1948 Description : adds a new attribute to an object, or updates an existing attribute with a new value
1949 Can be run in interactive or non-interactive mode (default)
1950 Return type : arrayref of results
1951 Caller : general
1952 Status : only ever tested with seq_region_attributes to date
1953  
1954 =cut
1955  
1956 sub fix_attrib_value {
1957 my $self = shift;
1958 my $attribs = shift;
1959 my $id = shift;
1960 my $name = shift;
1961 my $code = shift;
1962 my $value = shift;
1963 my $interact = shift || 0;
1964 my $table = shift || 'seq_region_attrib';
1965  
1966 #transiently set interactive parameter to zero
1967 my $int_before;
1968 if (! $interact) {
1969 $int_before = $self->param('interactive');
1970 $self->param('interactive',0);
1971 }
1972  
1973 #get any existing value(s) for this attribute
1974 my $existings = $self->get_attrib_values($attribs,$code);
1975
1976 #add a new attribute if there is none...
1977 if (! @$existings ) {
1978 if ($self->user_proceed("Do you want to set $name attrib (code = $code) to value $value ?")) {
1979 my $r = $self->store_new_attribute($id,$code,$value);
1980  
1981 #reset interactive parameter
1982 $self->param('interactive',$int_before) if (! $interact);
1983 return $r;
1984 }
1985 }
1986 #...warn and exit if you're trying to update more than one value for the same attribute...
1987 elsif (scalar @$existings > 1) {
1988 $self->log_warning("You shouldn't be trying to update multiple attributes with the same code at once ($name:$code,$value), looks like you have duplicate entries in the (seq_region_)attrib table\n");
1989 exit;
1990 }
1991  
1992 #...or update an attribute with new values...
1993 else {
1994 my $existing = $existings->[0];
1995 if ($existing ne $value) {
1996 if ($self->user_proceed("Do you want to reset $name attrib (code = $code) from $existing to $value ?")) {
1997 my $r = $self->update_attribute($id,$code,$value);
1998 $self->param('interactive',$int_before) if (! $interact);
1999 push @$r, $existing;
2000 return $r;
2001 }
2002 }
2003 #...or make no change
2004 else {
2005 $self->param('interactive',$int_before) if (! $interact);
2006 return [];
2007 }
2008 }
2009 }
2010  
2011 =head2 _get_attrib_id
2012  
2013 Arg[1] : attrib_type.code
2014 Arg[2] : database handle
2015 Example : $self->_get_attrib_id('name',$dbh)
2016 Description : get attrib_type.attrib_type_id from a attrib_type.code
2017 Return type : attrib_type.attrib_type_id
2018 Caller : internal
2019 Status : stable
2020  
2021 =cut
2022  
2023 sub _get_attrib_id {
2024 my $self = shift;
2025 my $attrib_code = shift;
2026 my $dbh = shift;
2027 my ($attrib_id) = $dbh->selectrow_array(
2028 qq(select attrib_type_id
2029 from attrib_type
2030 where code = ?),
2031 {},
2032 ($attrib_code)
2033 );
2034 if (! $attrib_id) {
2035 $self->log_warning("There is no attrib_type_id for code $attrib_code, please patch the attrib_table\n");
2036 exit;
2037 }
2038 else {
2039 return $attrib_id;
2040 }
2041 }
2042  
2043 =head2 store_new_attribute
2044  
2045 Arg[1] : seq_region.seq_region_id
2046 Arg[2] : attrib_type.code
2047 Arg[3] : attrib_type.value
2048 ARG[4] : table to update (seq_region_attribute by default)
2049 Example : $support->store_new_attribute(23,name,5);
2050 Description : uses MySQL to store an entry (code and value) in an attribute table
2051 (seq_region_attrib by default)
2052 Return type : array_ref
2053 Caller : general
2054 Status : stable
2055  
2056 =cut
2057  
2058 sub store_new_attribute {
2059 my $self = shift;
2060 my $sr_id = shift;
2061 my $attrib_code = shift;
2062 my $attrib_value = shift || '';
2063 my $table = shift || 'seq_region_attrib';
2064  
2065 #get database handle
2066 my $dbh = $self->get_dbconnection('loutre');
2067 #get attrib_type_id for this particular attribute
2068 my $attrib_id = $self->_get_attrib_id($attrib_code,$dbh);
2069 #store
2070 my $r = $dbh->do(
2071 qq(insert into $table
2072 values (?,?,?)),
2073 {},
2074 ($sr_id,$attrib_id,$attrib_value)
2075 );
2076 return ['Stored',$r];
2077 }
2078  
2079 =head2 update_attribute
2080  
2081 Arg[1] : seq_region.seq_region_id
2082 Arg[2] : attrib_type.code
2083 Arg[3] : attrib_type.value
2084 ARG[4] : table to update (seq_region_attribute by default)
2085 Example : $support->update_attribute(23,name,5);
2086 Description : uses MySQL to update an attribute table (seq_region_attrib by default)
2087 Return type : array_ref
2088 Caller : general
2089 Status : stable
2090  
2091 =cut
2092  
2093 sub update_attribute {
2094 my $self = shift;
2095 my $sr_id = shift;
2096 my $attrib_code = shift;
2097 my $attrib_value = shift;
2098 my $table = shift || 'seq_region_attrib';
2099 my $dbh = $self->get_dbconnection('loutre');
2100 my $attrib_id = $self->_get_attrib_id($attrib_code,$dbh);
2101 #update
2102 my $r = $dbh->do(
2103 qq(update $table
2104 set value = ?
2105 where seq_region_id = $sr_id
2106 and attrib_type_id = $attrib_id),
2107 {},
2108 ($attrib_value)
2109 );
2110 return ['Updated',$r];
2111 }
2112  
2113  
2114 =head2 remove_duplicate_attribs
2115  
2116 Arg[1] : db handle
2117 Arg[2] : table
2118 Example : $support->remove_duplicate_attribs($dbh,'gene');
2119 Description : uses MySQL to remove duplicate entries from an attribute table
2120 Return type : none
2121 Caller : general
2122 Status : stable
2123  
2124 =cut
2125  
2126 sub remove_duplicate_attribs {
2127 my $self = shift;
2128 my $dbh = shift;
2129 my $table = shift;
2130 $dbh->do(qq(create table nondup_${table}_attrib like ${table}_attrib));
2131 $dbh->do(qq(insert into nondup_${table}_attrib (select ${table}_id, attrib_type_id, value from ${table}_attrib group by ${table}_id, attrib_type_id, value)));
2132 $dbh->do(qq(delete from ${table}_attrib));
2133 $dbh->do(qq(insert into ${table}_attrib (select ${table}_id, attrib_type_id, value from nondup_${table}_attrib)));
2134 $dbh->do(qq(drop table nondup_${table}_attrib));
2135 }
2136  
2137 =head2 sav_seq
2138  
2139 Arg[1] : string (sequence to save)
2140 Example : $support->save_seq('ACGT')
2141 Description : creates a temporary file containing the sequence you give it
2142 Return type : string (filename)
2143 Caller : general
2144 Status : stable
2145  
2146 =cut
2147  
2148 sub save_seq {
2149 my $self = shift;
2150 my $content = shift ;
2151 my $seq_file = $self->param('logpath') . '/SEQ_' . time() . int(rand()*100000000) . $$;
2152 open (my $fh,">$seq_file", $seq_file) or die("Cannot create working file.$!");
2153 print $fh $content;
2154 close $fh;
2155 return ($seq_file);
2156 }
2157  
2158 =head2 get_alignment
2159  
2160 Arg[1] : string (first sequence)
2161 Arg[1] : string (second sequence)
2162 Arg[1] : string (sequence type))
2163 Example : $support->get_alignment('AAAAA','CCCCCCC','DNA')
2164 Description : creates a temporary file containing the sequence you give it
2165 Return type : string (filename)
2166 Caller : general
2167 Status : stable
2168  
2169 =cut
2170  
2171 sub get_alignment {
2172 my $self = shift;
2173 my $ext_seq = shift || return undef;
2174 my $int_seq = shift || return undef;
2175 $int_seq =~ s/<br \/>//g;
2176 my $seq_type = shift || return undef;
2177  
2178  
2179 # To stop box running out of memory - put an upper limit on the size of sequence
2180 # that alignview can handle
2181 if (length $int_seq > 1e6 || length $ext_seq > 1e6) {
2182 $self->log_error('Cannot align if sequence > 1 Mbase');
2183 }
2184  
2185 my $int_seq_file = $self->save_seq($int_seq);
2186 my $ext_seq_file = $self->save_seq($ext_seq);
2187  
2188 my $label_width = '22'; # width of column for e! object label
2189 my $output_width = 61; # width of alignment
2190 my $dnaAlignExe = '/localsw/bin/emboss/bin/matcher -asequence %s -bsequence %s -outfile %s';
2191 my $pepAlignExe = '/localsw/bin/wise2/bin/psw -dymem explicit -m /localsw/bin/wise2/wisecfg/blosum62.bla %s %s -n %s -w %s > %s';
2192  
2193 my $out_file = time() . int(rand()*100000000) . $$;
2194 $out_file = $self->param('logpath').'/' . $out_file . '.out';
2195  
2196 my $command;
2197 my $fh;
2198 if ($seq_type eq 'DNA') {
2199 $command = sprintf $dnaAlignExe, $int_seq_file, $ext_seq_file, $out_file;
2200 `$command`;
2201 unless (open($fh, "<", $out_file)) {
2202 $command = sprintf $dnaAlignExe, $int_seq_file, $ext_seq_file, $out_file;
2203 `$command`;
2204 }
2205 }
2206 elsif ($seq_type eq 'PEP') {
2207 $command = sprintf $pepAlignExe, $int_seq_file, $ext_seq_file, $label_width, $output_width, $out_file;
2208 `$command`;
2209 unless (open($fh, "<", $out_file)) {
2210 $self->log_warning("Cannot open alignment file\n");
2211 }
2212 }
2213 my $alignment ;
2214 while (<$fh>) {
2215 next if $_ =~
2216 /\#Report_file
2217 |\#----.*
2218 |\/\/\s*
2219 |\#\#\#
2220 |^\#$
2221 |Rundate: #matcher
2222 |Commandline #matcher
2223 |asequence #matcher
2224 |bsequence #matcher
2225 |outfile #matcher
2226 |aformat #matcher
2227 |Align_format #matcher
2228 |Report_file #matcher
2229 /x;
2230 $alignment .= $_;
2231 }
2232  
2233 $alignment =~ s/\n+$//;
2234 unlink $out_file;
2235 unlink $int_seq_file;
2236 unlink $ext_seq_file;
2237 return $alignment;
2238 }
2239  
2240 sub allowed_duplicate_regions {
2241 my $self = shift;
2242  
2243 # set up lists of vega names of wanted haplotype / strains
2244 my $regions = {
2245 'human' => [
2246 {
2247 '6' => '28000000:34000000',
2248 '6-COX' => 'all',
2249 '6-QBL' => 'all',
2250 '6-APD' => 'all',
2251 '6-MANN' => 'all',
2252 '6-MCF' => 'all',
2253 '6-DBB' => 'all',
2254 '6-SSTO' => 'all',
2255 },
2256 {
2257 '19' => '54020000:54910000',
2258 '19-PGF_1' => 'all',
2259 '19-PGF_2' => 'all',
2260 '19-COX_1' => 'all',
2261 '19-COX_2' => 'all',
2262 '19-DM1A' => 'all',
2263 '19-DM1B' => 'all',
2264 '19-MC1A' => 'all',
2265 '19-MC1B' => 'all',
2266 },
2267 ],
2268 'mouse' => [
2269 {
2270 '1' => '60564732:63711641',
2271 '1-Idd5.1_DIL' => 'all',
2272 '1-Idd5.1_CHO' => 'all',
2273 },
2274 {
2275 '1' => '65533102:69307244',
2276 '1-Idd5.3_DIL' => 'all',
2277 },
2278 {
2279 '1' => '130232728:130661594',
2280 '1-Idd5.4_DIL' => 'all',
2281 },
2282 {
2283 '3' => '36492618:37600833',
2284 '3-Idd3_DIL' => 'all',
2285 '3-Idd3_129' => 'all',
2286 },
2287 {
2288 '3' => '99848826:101467080',
2289 '3-Idd10_DIL' => 'all',
2290 },
2291 {
2292 '3' => '109144756:109930492',
2293 '3-Idd18.1_DIL' => 'all',
2294 },
2295 {
2296 '3' => '103489414:104054885',
2297 '3-Idd18.2_DIL' => 'all',
2298 },
2299 {
2300 '4' => '128371876:131853368',
2301 '4-Idd9.1_DIL' => 'all',
2302 },
2303 {
2304 '4' => '134841437:135252443',
2305 '4-Idd9.1M_DIL' => 'all',
2306 },
2307 {
2308 '4' => '146049976:149895141',
2309 '4-Idd9.2_DIL' => 'all',
2310 },
2311 {
2312 '4' => '149556939:151385803',
2313 '4-Idd9.3_DIL' => 'all',
2314 },
2315 {
2316 '6' => '143550839:149565172',
2317 '6-Idd6.1_2_CHO' => 'all',
2318 },
2319 {
2320 '6' => '129593784:131241919',
2321 '6-Idd6.AM_CHO' => 'all',
2322 },
2323 {
2324 '11' => '69890356:71340035',
2325 '11-Idd4.1_DIL' => 'all'
2326 },
2327 {
2328 '11' => '72734492:74404570',
2329 '11-Idd4.2_DIL' => 'all',
2330 },
2331 {
2332 '11' => '86785996:90007691',
2333 '11-Idd4.2Q_CHO' => 'all',
2334 },
2335 {
2336 '17' => '27302611:29220265',
2337 '17-Idd16.1_CHO' => 'all',
2338 },
2339 {
2340 '17' => '33567721:38721962',
2341 '17-Idd1_CHO' => 'all',
2342 '17-Idd1_DIL' => 'all',
2343 },
2344 ],
2345 'pig' => [
2346 {
2347 '7' => '24728583:29807435',
2348 '7-LW' => 'all',
2349 },
2350 {
2351 'X' => 'all',
2352 'X-WTSI' => 'all',
2353 },
2354 ],
2355 'zebrafish' => [],
2356 'gorilla' => [],
2357 'wallaby' => [],
2358 'chimp' => [],
2359 'rat' => [],
2360 };
2361  
2362 return $regions;
2363  
2364 }
2365  
2366 1;