ConversionSupport.pm 52.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
package Bio::EnsEMBL::Utils::ConversionSupport;

=head1 NAME

Bio::EnsEMBL::Utils::ConversionSupport - Utility module for Vega release and
schema conversion scripts

=head1 SYNOPSIS

    my $serverroot = '/path/to/ensembl';
Steve Trevanion's avatar
Steve Trevanion committed
11
    my $support = new Bio::EnsEMBL::Utils::ConversionSupport($serverroot);
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36

    # parse common options
    $support->parse_common_options;

    # parse extra options for your script
    $support->parse_extra_options('string_opt=s', 'numeric_opt=n');

    # ask user if he wants to run script with these parameters
    $support->confirm_params;

    # see individual method documentation for more stuff

=head1 DESCRIPTION

This module is a collection of common methods and provides helper functions 
for the Vega release and schema conversion scripts. Amongst others, it reads
options from a config file, parses commandline options and does logging.

=head1 LICENCE

This code is distributed under an Apache style licence:
Please see http://www.ensembl.org/code_licence.html for details

=head1 AUTHOR

Steve Trevanion's avatar
Steve Trevanion committed
37 38
Steve Trevanion <st3@sanger.ac.uk
Patrick Meidl <meidl@ebi.ac.uk>
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54

=head1 CONTACT

Post questions to the EnsEMBL development list ensembl-dev@ebi.ac.uk

=cut

use strict;
use warnings;
no warnings 'uninitialized';

use Getopt::Long;
use Text::Wrap;
use Bio::EnsEMBL::Utils::Exception qw(throw warning);
use FindBin qw($Bin $Script);
use POSIX qw(strftime);
55
use Cwd qw(abs_path);
Patrick Meidl's avatar
Patrick Meidl committed
56
use DBI;
Web Admin's avatar
Web Admin committed
57
use Data::Dumper;
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72

=head2 new

  Arg[1]      : String $serverroot - root directory of your ensembl sandbox
  Example     : my $support = new Bio::EnsEMBL::Utils::ConversionSupport(
                                        '/path/to/ensembl');
  Description : constructor
  Return type : Bio::EnsEMBL::Utils::ConversionSupport object
  Exceptions  : thrown if no serverroot is provided
  Caller      : general

=cut

sub new {
    my $class = shift;
73
    (my $serverroot = shift) or throw("You must supply a serverroot.");
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
    my $self = {
        '_serverroot'   => $serverroot,
        '_param'        => { interactive => 1 },
        '_warnings'     => 0,
    };
    bless ($self, $class);
    return $self;
}

=head2 parse_common_options

  Example     : $support->parse_common_options;
  Description : This method reads options from a configuration file and parses
                some commandline options that are common to all scripts (like
                db connection settings, help, dry-run). Commandline options
                will override config file settings. 

                All options will be accessible via $self->param('name').
  Return type : true on success 
  Exceptions  : thrown if configuration file can't be opened
  Caller      : general

=cut

sub parse_common_options {
    my $self = shift;

    # read commandline options
    my %h;
    Getopt::Long::Configure("pass_through");
    &GetOptions( \%h,
        'dbname|db_name=s',
        'host|dbhost|db_host=s',
        'port|dbport|db_port=n',
        'user|dbuser|db_user=s',
        'pass|dbpass|db_pass=s',
        'conffile|conf=s',
        'logfile|log=s',
112
        'logpath=s',
113
        'logappend|log_append=s',
114
        'verbose|v=s',
115 116 117 118 119
        'interactive|i=s',
        'dry_run|dry|n=s',
        'help|h|?',
    );

Web Admin's avatar
Web Admin committed
120

121
    # reads config file
122
    my $conffile = $h{'conffile'} || $self->serverroot . "/sanger-plugins/vega/conf/ini-files/Conversion.ini";
123
    $conffile = abs_path($conffile);
124 125 126
    if (-e $conffile) {
        open(CONF, $conffile) or throw( 
            "Unable to open configuration file $conffile for reading: $!");
127
        my $serverroot = $self->serverroot;
128
        while (<CONF>) {
129 130
            chomp;

131
            # remove comments
132 133
            s/^[#;].*//;
            s/\s+[;].*$//;
134

Web Admin's avatar
Web Admin committed
135 136
            # read options into internal parameter datastructure, removing whitespace
            next unless (/(\w\S*)\s*=\s*(\S*)\s*/);
137 138 139 140 141 142 143
            my $name = $1;
            my $val = $2;
            if ($val =~ /\$SERVERROOT/) {
                $val =~ s/\$SERVERROOT/$serverroot/g;
                $val = abs_path($val);
            }
            $self->param($name, $val);
144
        }
145
        $self->param('conffile', $conffile);
Patrick Meidl's avatar
Patrick Meidl committed
146
    } elsif ($conffile) {
147 148
        warning("Unable to open configuration file $conffile for reading: $!");
    }
Web Admin's avatar
Web Admin committed
149

150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
    
    # override configured parameter with commandline options
    map { $self->param($_, $h{$_}) } keys %h;
    return(1);
}

=head2 parse_extra_options

  Arg[1-N]    : option descriptors that will be passed on to Getopt::Long
  Example     : $support->parse_extra_options('string_opt=s', 'numeric_opt=n');
  Description : Parse extra commandline options by passing them on to
                Getopt::Long and storing parameters in $self->param('name).
  Return type : true on success
  Exceptions  : none (caugth by $self->error)
  Caller      : general

=cut

sub parse_extra_options {
    my ($self, @params) = @_;
    Getopt::Long::Configure("no_pass_through");
    eval {
        # catch warnings to pass to $self->error
        local $SIG{__WARN__} = sub { die @_; };
        &GetOptions(\%{ $self->{'_param'} }, @params);
    };
    $self->error($@) if $@;
    return(1);
}

180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
=head2 allowed_params

  Arg[1-N]    : (optional) List of allowed parameters to set
  Example     : my @allowed = $self->allowed_params(qw(param1 param2));
  Description : Getter/setter for allowed parameters. This is used by
                $self->confirm_params() to avoid cluttering of output with
                conffile entries not relevant for a given script. You can use
                $self->get_common_params() as a shortcut to set them.
  Return type : Array - list of allowed parameters
  Exceptions  : none
  Caller      : general

=cut

sub allowed_params {
    my $self = shift;

    # setter
    if (@_) {
        @{ $self->{'_allowed_params'} } = @_;
    }

    # getter
    if (ref($self->{'_allowed_params'}) eq 'ARRAY') {
        return @{ $self->{'_allowed_params'} };
    } else {
        return ();
    }
}

=head2 get_common_params

  Example     : my @allowed_params = $self->get_common_params, 'extra_param';
  Description : Returns a list of commonly used parameters in the conversion
                scripts. Shortcut for setting allowed parameters with
                $self->allowed_params().
  Return type : Array - list of common parameters
  Exceptions  : none
  Caller      : general

=cut

sub get_common_params {
    return qw(
        conffile
        dbname
        host
        port
        user
        pass
        logpath
        logfile
        logappend
        verbose
        interactive
        dry_run
    );
}

Steve Trevanion's avatar
Steve Trevanion committed
239
=head2 get_loutre_params
Web Admin's avatar
Web Admin committed
240

Steve Trevanion's avatar
Steve Trevanion committed
241
  Example     : my @allowed_params = $self->get_loutre_params, 'extra_param';
Web Admin's avatar
Web Admin committed
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
  Description : Returns a list of commonly used parameters in for working with a loutre db
  Return type : Array - list of common parameters
  Exceptions  : none
  Caller      : general

=cut

sub get_loutre_params {
	return qw(
			  loutrehost
			  loutreport
			  loutreuser
			  loutrepass
			  loutredbname
		  );
}

Steve Trevanion's avatar
Steve Trevanion committed
259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
=head2 remove_vega_params

  Example     : $support->remove_vega_params;
  Description : Removes Vega db conection parameters. Usefull to avoid clutter in log files when
                working exclusively with loutre
  Return type : none
  Exceptions  : none
  Caller      : general

=cut

sub remove_vega_params {
	my $self = shift;
	foreach my $param (qw(dbname host port user pass)) {
		$self->{'_param'}{$param} = undef;
	}
}
Web Admin's avatar
Web Admin committed
276

277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295
=head2 confirm_params

  Example     : $support->confirm_params;
  Description : Prints a table of parameters that were collected from config
                file and commandline and asks user to confirm if he wants
                to proceed.
  Return type : true on success
  Exceptions  : none
  Caller      : general

=cut

sub confirm_params {
    my $self = shift;

    # print parameter table
    print "Running script with these parameters:\n\n";
    print $self->list_all_params;

296 297 298 299 300 301 302 303
	if ($self->param('host') eq 'web-4-11') {
		# ask user if he wants to proceed
		exit unless $self->user_proceed("**************\n\n You're working on web-4-11! Is that correct and you want to continue ?\n\n**************");
	}
	else {
		# ask user if he wants to proceed
		exit unless $self->user_proceed("Continue?");
    }
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318
    return(1);
}

=head2 list_all_params

  Example     : print LOG $support->list_all_params;
  Description : prints a table of the parameters used in the script
  Return type : String - the table to print
  Exceptions  : none
  Caller      : general

=cut

sub list_all_params {
    my $self = shift;
Steve Trevanion's avatar
Steve Trevanion committed
319 320
    my $txt = sprintf "    %-21s%-40s\n", qw(PARAMETER VALUE);
    $txt .= "    " . "-"x71 . "\n";
321
    $Text::Wrap::colums = 72;
322 323
    my @params = $self->allowed_params;
    foreach my $key (@params) {
324
        my @vals = $self->param($key);
325
        if (@vals) {
Steve Trevanion's avatar
Steve Trevanion committed
326
            $txt .= Text::Wrap::wrap( sprintf('   %-21s', $key),
327 328 329 330
                                      ' 'x24,
                                      join(", ", @vals)
                                    ) . "\n";
        }
331 332 333 334 335
    }
    $txt .= "\n";
    return $txt;
}

336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417
=head2 create_commandline_options

  Arg[1]      : Hashref $settings - hashref describing what to do
                Allowed keys:
                    allowed_params => 0|1   # use all allowed parameters
                    exclude => []           # listref of parameters to exclude
                    replace => {param => newval} # replace value of param with
                                                 # newval
  Example     : $support->create_commandline_options({
                    allowed_params => 1,
                    exclude => ['verbose'],
                    replace => { 'dbname' => 'homo_sapiens_vega_33_35e' }
                });
  Description : Creates a commandline options string that can be passed to any
                other script using ConversionSupport.
  Return type : String - commandline options string
  Exceptions  : none
  Caller      : general

=cut

sub create_commandline_options {
    my ($self, $settings) = @_;
    my %param_hash;

    # get all allowed parameters
    if ($settings->{'allowed_params'}) {
        # exclude params explicitly stated
        my %exclude = map { $_ => 1 } @{ $settings->{'exclude'} || [] };
        
        foreach my $param ($self->allowed_params) {
            unless ($exclude{$param}) {
                my ($first, @rest) = $self->param($param);
                next unless (defined($first));

                if (@rest) {
                    $first = join(",", $first, @rest);
                }
                $param_hash{$param} = $first;
            }
        }

    }

    # replace values
    foreach my $key (keys %{ $settings->{'replace'} || {} }) {
        $param_hash{$key} = $settings->{'replace'}->{$key};
    }

    # create the commandline options string
    my $options_string;
    foreach my $param (keys %param_hash) {
        $options_string .= sprintf("--%s %s ", $param, $param_hash{$param});
    }
    
    return $options_string;
}

=head2 check_required_params

  Arg[1-N]    : List @params - parameters to check
  Example     : $self->check_required_params(qw(dbname host port));
  Description : Checks $self->param to make sure the requested parameters
                have been set. Dies if parameters are missing.
  Return type : true on success
  Exceptions  : none
  Caller      : general

=cut

sub check_required_params {
    my ($self, @params) = @_;
    my @missing = ();
    foreach my $param (@params) {
        push @missing, $param unless $self->param($param);
    }
    if (@missing) {
        throw("Missing parameters: @missing.\nYou must specify them on the commandline or in your conffile.\n");
    }
    return(1);
}

418 419 420 421
=head2 user_proceed

  Arg[1]      : (optional) String $text - notification text to present to user
  Example     : # run a code snipped conditionally
422
                if ($support->user_proceed("Run the next code snipped?")) {
423 424
                    # run some code
                }
425

426 427
                # exit if requested by user
                exit unless ($support->user_proceed("Want to continue?"));
428
  Description : If running interactively, the user is asked if he wants to
429 430 431 432
                perform a script action. If he doesn't, this section is skipped
                and the script proceeds with the code. When running
                non-interactively, the section is run by default.
  Return type : TRUE to proceed, FALSE to skip.
433 434 435 436 437
  Exceptions  : none
  Caller      : general

=cut

438 439
sub user_proceed {
    my ($self, $text) = @_;
440 441

    if ($self->param('interactive')) {
442 443
        print "$text\n" if $text;
        print "[y/N] ";
444 445 446
        my $input = lc(<>);
        chomp $input;
        unless ($input eq 'y') {
447 448
            print "Skipping.\n";
            return(0);
449 450 451 452 453 454
        }
    }

    return(1);
}

455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492
=head2 user_confirm

  Description : DEPRECATED - please use user_proceed() instead

=cut

sub user_confirm {
    my $self = shift;
    exit unless $self->user_proceed("Continue?");
}

=head2 read_user_input

  Arg[1]      : (optional) String $text - notification text to present to user
  Example     : my $ret = $support->read_user_input("Choose a number [1/2/3]");
                if ($ret == 1) {
                    # do something
                } elsif ($ret == 2) {
                    # do something else
                }
  Description : If running interactively, the user is asked for input.
  Return type : String - user's input
  Exceptions  : none
  Caller      : general

=cut

sub read_user_input {
    my ($self, $text) = @_;

    if ($self->param('interactive')) {
        print "$text\n" if $text;
        my $input = <>;
        chomp $input;
        return $input;
    }
}

493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515
=head2 comma_to_list

  Arg[1-N]    : list of parameter names to parse
  Example     : $support->comma_to_list('chromosomes');
  Description : Transparently converts comma-separated lists into arrays (to
                allow different styles of commandline options, see perldoc
                Getopt::Long for details). Parameters are converted in place
                (accessible through $self->param('name')).
  Return type : true on success
  Exceptions  : none
  Caller      : general

=cut

sub comma_to_list {
    my $self = shift;
    foreach my $param (@_) {
        $self->param($param,
            split (/,/, join (',', $self->param($param))));
    }
    return(1);
}

516
=head2 list_or_file
517 518

  Arg[1]      : Name of parameter to parse
519
  Example     : $support->list_or_file('gene_stable_id');
520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554
  Description : Determines whether a parameter holds a list or it is a filename
                to read the list entries from.
  Return type : true on success
  Exceptions  : thrown if list file can't be opened
  Caller      : general

=cut

sub list_or_file {
    my ($self, $param) = @_;
    my @vals = $self->param($param);
    return unless (@vals);

    my $firstval = $vals[0];
    if (scalar(@vals) == 1 && -e $firstval) {
        # we didn't get a list of values, but a file to read values from
        @vals = ();
        open(IN, $firstval) or throw("Cannot open $firstval for reading: $!");
        while(<IN>){
            chomp;
            push(@vals, $_);
        }
        close(IN);
        $self->param($param, @vals);
    }
    $self->comma_to_list($param);
    return(1);
}

=head2 param

  Arg[1]      : Parameter name
  Arg[2-N]    : (optional) List of values to set
  Example     : my $dbname = $support->param('dbname');
                $support->param('port', 3306);
555
                $support->param('chromosomes', 1, 6, 'X');
556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575
  Description : Getter/setter for parameters. Accepts single-value params and
                list params.
  Return type : Scalar value for single-value parameters, array of values for
                list parameters
  Exceptions  : thrown if no parameter name is supplied
  Caller      : general

=cut

sub param {
    my $self = shift;
    my $name = shift or throw("You must supply a parameter name");

    # setter
    if (@_) {
        if (scalar(@_) == 1) {
            # single value
            $self->{'_param'}->{$name} = shift;
        } else {
            # list of values
576
            undef $self->{'_param'}->{$name};
577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649
            @{ $self->{'_param'}->{$name} } = @_;
        }
    }

    # getter
    if (ref($self->{'_param'}->{$name}) eq 'ARRAY') {
        # list parameter
        return @{ $self->{'_param'}->{$name} };
    } elsif (defined($self->{'_param'}->{$name})) {
        # single-value parameter
        return $self->{'_param'}->{$name};
    } else {
        return ();
    }
}

=head2 error

  Arg[1]      : (optional) String - error message
  Example     : $support->error("An error occurred: $@");
                exit(0) if $support->error;
  Description : Getter/setter for error messages
  Return type : String - error message
  Exceptions  : none
  Caller      : general

=cut

sub error {
    my $self = shift;
    $self->{'_error'} = shift if (@_);
    return $self->{'_error'};
}

=head2 warnings

  Example     : print LOG "There were ".$support->warnings." warnings.\n";
  Description : Returns the number of warnings encountered while running the
                script (the warning counter is increased by $self->log_warning).
  Return type : Int - number of warnings
  Exceptions  : none
  Caller      : general

=cut

sub warnings {
    my $self = shift;
    return $self->{'_warnings'};
}

=head2 serverroot

  Arg[1]      : (optional) String - root directory of your ensembl sandbox
  Example     : my $serverroot = $support->serverroot;
  Description : Getter/setter for the root directory of your ensembl sandbox.
                This is set when ConversionSupport object is created, so
                usually only used as a getter.
  Return type : String - the server root directory
  Exceptions  : none
  Caller      : general

=cut

sub serverroot {
    my $self = shift;
    $self->{'_serverroot'} = shift if (@_);
    return $self->{'_serverroot'};
}

=head2 get_database

  Arg[1]      : String $database - the type of database to connect to
                (eg core, otter)
650 651
  Arg[2]      : (optional) String $prefix - the prefix used for retrieving the
                connection settings from the configuration
652 653 654 655 656 657 658 659 660 661 662
  Example     : my $db = $support->get_database('core');
  Description : Connects to the database specified.
  Return type : DBAdaptor of the appropriate type
  Exceptions  : thrown if asking for unknown database
  Caller      : general

=cut

sub get_database {
    my $self = shift;
    my $database = shift or throw("You must provide a database");
Leo Gordon's avatar
Leo Gordon committed
663
    my $prefix = shift || '';
664 665 666 667 668 669 670
    $self->check_required_params(
        "${prefix}host",
        "${prefix}port",
        "${prefix}user",
        # "${prefix}pass", not required since might be empty
        "${prefix}dbname",
    );
671 672 673 674

    my %adaptors = (
        core    => 'Bio::EnsEMBL::DBSQL::DBAdaptor',
        ensembl => 'Bio::EnsEMBL::DBSQL::DBAdaptor',
675
        evega   => 'Bio::EnsEMBL::DBSQL::DBAdaptor',
676 677
        otter   => 'Bio::Otter::DBSQL::DBAdaptor',
        vega    => 'Bio::Otter::DBSQL::DBAdaptor',
678
		compara => 'Bio::EnsEMBL::DBSQL::DBAdaptor',
Web Admin's avatar
Web Admin committed
679
		loutre  => 'Bio::Vega::DBSQL::DBAdaptor',
680
    );
Leo Gordon's avatar
Leo Gordon committed
681
    throw("Unknown database: $database") unless $adaptors{$database};
682 683 684

    $self->dynamic_use($adaptors{$database});
    my $dba = $adaptors{$database}->new(
685 686 687
            -host   => $self->param("${prefix}host"),
            -port   => $self->param("${prefix}port"),
            -user   => $self->param("${prefix}user"),
688
            -pass   => $self->param("${prefix}pass") || '',
689 690
            -dbname => $self->param("${prefix}dbname"),
            -group  => $database,
691
    );
Steve Trevanion's avatar
Steve Trevanion committed
692

693 694 695 696
    # explicitely set the dnadb to itself - by default the Registry assumes
    # a group 'core' for this now
    $dba->dnadb($dba);

697 698 699 700 701
    $self->{'_dba'}->{$database} = $dba;
    $self->{'_dba'}->{'default'} = $dba unless $self->{'_dba'}->{'default'};
    return $self->{'_dba'}->{$database};
}

Patrick Meidl's avatar
Patrick Meidl committed
702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720

=head2 get_dbconnection

  Arg[1]      : (optional) String $prefix - the prefix used for retrieving the
                connection settings from the configuration
  Example     : my $dbh = $self->get_dbconnection;
  Description : Connects to the database server specified. You don't have to
                specify a database name (this is useful for running commands
                like $dbh->do('show databases')).
  Return type : DBI database handle
  Exceptions  : thrown if connection fails
  Caller      : general
  Status      : At Risk

=cut

sub get_dbconnection {
  my $self = shift;
  my $prefix = shift;
Web Admin's avatar
Web Admin committed
721
 
Patrick Meidl's avatar
Patrick Meidl committed
722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752
  $self->check_required_params(
      "${prefix}host",
      "${prefix}port",
      "${prefix}user",
  );

  my $dsn = "DBI:" . ($self->param('driver')||'mysql') .
            ":host=" . $self->param("${prefix}host") .
            ";port=" . $self->param("${prefix}port");

  if ($self->param("${prefix}dbname")) {
    $dsn .= ";dbname=".$self->param("${prefix}dbname");
  }

  my $dbh;
  eval{
    $dbh = DBI->connect($dsn, $self->param("${prefix}user"),
      $self->param("${prefix}pass"), {'RaiseError' => 1, 'PrintError' => 0});
  };

  if (!$dbh || $@ || !$dbh->ping) {
    $self->log_error("Could not connect to db server as user ".
      $self->param("${prefix}user") .
      " using [$dsn] as a locator:\n" . $DBI::errstr);
  }

  $self->{'_dbh'} = $dbh;
  return $self->{'_dbh'};

}

753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804
=head2 get_glovar_database

  Example     : my $dba = $support->get_glovar_database;
  Description : Connects to the Glovar database.
  Return type : Bio::EnsEMBL::ExternalData::Glovar::DBAdaptor
  Exceptions  : thrown if no connection to a core db exists
  Caller      : general

=cut

sub get_glovar_database {
    my $self = shift;
    $self->check_required_params(qw(
        glovarhost
        glovarport
        glovaruser
        glovarpass
        glovardbname
        oracle_home
        ld_library_path
        glovar_snp_consequence_exp
    ));

    # check for core dbadaptor
    my $core_db = $self->dba;
    unless ($core_db && (ref($core_db) =~ /Bio::.*::DBSQL::DBAdaptor/)) {
        $self->log_error("You have to connect to a core db before you can get a glovar dbadaptor.\n");
        exit;
    }
    
    # setup Oracle environment
    $ENV{'ORACLE_HOME'} = $self->param('oracle_home');
    $ENV{'LD_LIBRARY_PATH'} = $self->param('ld_library_path');

    # connect to Glovar db
    $self->dynamic_use('Bio::EnsEMBL::ExternalData::Glovar::DBAdaptor');
    my $dba = Bio::EnsEMBL::ExternalData::Glovar::DBAdaptor->new(
            -host   => $self->param("glovarhost"),
            -port   => $self->param("glovarport"),
            -user   => $self->param("glovaruser"),
            -pass   => $self->param("glovarpass"),
            -dbname => $self->param("glovardbname"),
            -group  => 'glovar',
    );

    # setup adaptor inter-relationships
    $dba->dnadb($core_db);
    $self->dynamic_use('Bio::EnsEMBL::ExternalData::Glovar::GlovarSNPAdaptor');
    my $glovar_snp_adaptor = $dba->get_GlovarSNPAdaptor;
    $glovar_snp_adaptor->consequence_exp($self->param('glovar_snp_consequence_exp'));
    $core_db->add_ExternalFeatureAdaptor($glovar_snp_adaptor);

805 806 807
    return $dba;
}

808
=head2 dba
809

810 811 812 813 814
  Arg[1]      : (optional) String $database - type of db apaptor to retrieve
  Example     : my $dba = $support->dba;
  Description : Getter for database adaptor. Returns default (i.e. created
                first) db adaptor if no argument is provided.
  Return type : Bio::EnsEMBL::DBSQL::DBAdaptor or Bio::Otter::DBSQL::DBAdaptor
815 816 817 818 819
  Exceptions  : none
  Caller      : general

=cut

820 821 822
sub dba {
    my ($self, $database) = shift;
    return $self->{'_dba'}->{$database} || $self->{'_dba'}->{'default'};
823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841
}

=head2 dynamic_use

  Arg [1]    : String $classname - The name of the class to require/import
  Example    : $self->dynamic_use('Bio::EnsEMBL::DBSQL::DBAdaptor');
  Description: Requires and imports the methods for the classname provided,
               checks the symbol table so that it doesnot re-require modules
               that have already been required.
  Returntype : true on success
  Exceptions : Warns to standard error if module fails to compile
  Caller     : internal

=cut

sub dynamic_use {
    my ($self, $classname) = @_;
    my ($parent_namespace, $module) = $classname =~/^(.*::)(.*)$/ ?
                                        ($1,$2) : ('::', $classname);
Steve Trevanion's avatar
Steve Trevanion committed
842

843 844
    no strict 'refs';
    # return if module has already been imported
Steve Trevanion's avatar
Steve Trevanion committed
845
    return 1 if $parent_namespace->{$module.'::'} && %{ $parent_namespace->{$module.'::'}||{} };
846 847 848 849
    
    eval "require $classname";
    throw("Failed to require $classname: $@") if ($@);
    $classname->import();
Steve Trevanion's avatar
Steve Trevanion committed
850

851 852 853 854 855
    return 1;
}

=head2 get_chrlength

856 857
  Arg[1]      : (optional) Bio::EnsEMBL::DBSQL::DBAdaptor $dba
  Arg[2]      : (optional) String $version - coord_system version
Web Admin's avatar
Web Admin committed
858 859
  Arg[3]      : (optional) String $type - type of region eg chromsome (defaults to 'toplevel')
  Arg[4]      : (optional) Boolean - return non reference slies as well (required for haplotypes eq 6-COX)
860 861 862 863 864 865 866 867 868 869 870
  Example     : my $chr_length = $support->get_chrlength($dba);
  Description : Get all chromosomes and their length from the database. Return
                chr_name/length for the chromosomes the user requested (or all
                chromosomes by default)
  Return type : Hashref - chromosome_name => length
  Exceptions  : thrown if not passing a Bio::EnsEMBL::DBSQL::DBAdaptor
  Caller      : general

=cut

sub get_chrlength {
Web Admin's avatar
Web Admin committed
871
    my ($self, $dba, $version,$type,$include_non_reference) = @_;
872
    $dba ||= $self->dba;
Web Admin's avatar
Web Admin committed
873
	$type ||= 'toplevel';
874 875 876 877
    throw("get_chrlength should be passed a Bio::EnsEMBL::DBSQL::DBAdaptor\n")
        unless ($dba->isa('Bio::EnsEMBL::DBSQL::DBAdaptor'));

    my $sa = $dba->get_SliceAdaptor;
Web Admin's avatar
Web Admin committed
878

879
    my @chromosomes = map { $_->seq_region_name } 
Web Admin's avatar
Web Admin committed
880 881
                            @{ $sa->fetch_all($type, $version,$include_non_reference) };
    my %chr = map { $_ => $sa->fetch_by_region($type, $_, undef, undef, undef, $version)->length } @chromosomes;
882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914

    my @wanted = $self->param('chromosomes');
    if (@wanted) {
        # check if user supplied invalid chromosome names
        foreach my $chr (@wanted) {
            my $found = 0;
            foreach my $chr_from_db (keys %chr) {
                if ($chr_from_db eq $chr) {
                    $found = 1;
                    last;
                }
            }
            unless ($found) {
                warning("Didn't find chromosome $chr in database " .
                         $self->param('dbname'));
            }
        }
        
        # filter to requested chromosomes only
        HASH: 
        foreach my $chr_from_db (keys %chr) {
            foreach my $chr (@wanted) {
                if ($chr_from_db eq $chr) {
                    next HASH;
                }
            }
            delete($chr{$chr_from_db});
        }
    }

    return \%chr;
}

915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950
=head2 get_ensembl_chr_mapping

  Arg[1]      : (optional) Bio::EnsEMBL::DBSQL::DBAdaptor $dba
  Arg[2]      : (optional) String $version - coord_system version
  Example     : my $ensembl_mapping = $support->get_ensembl_chr_mapping($dba);
  Description : Gets a mapping between Vega chromosome names and their
                equivalent Ensembl chromosomes.
  Return type : Hashref - Vega name => Ensembl name
  Exceptions  : thrown if not passing a Bio::EnsEMBL::DBSQL::DBAdaptor
  Caller      : general

=cut

sub get_ensembl_chr_mapping {
    my ($self, $dba, $version) = @_;
    $dba ||= $self->dba;
    throw("get_ensembl_chr_mapping should be passed a Bio::EnsEMBL::DBSQL::DBAdaptor\n") unless ($dba->isa('Bio::EnsEMBL::DBSQL::DBAdaptor'));

    my $sa = $dba->get_SliceAdaptor;
    my @chromosomes = map { $_->seq_region_name } 
                            @{ $sa->fetch_all('chromosome', $version) };

    my %chrs;
    foreach my $chr (@chromosomes) {
        my $sr = $sa->fetch_by_region('chromosome', $chr, undef, undef, undef, $version);
        my ($ensembl_name_attr) = @{ $sr->get_all_Attributes('ensembl_name') };
        if ($ensembl_name_attr) {
            $chrs{$chr} = $ensembl_name_attr->value;
        } else {
            $chrs{$chr} = $chr;
        }
    }

    return \%chrs;
}

951 952 953 954 955 956 957 958 959 960 961 962 963
=head2 get_taxonomy_id

  Arg[1]      : Bio::EnsEMBL::DBSQL::DBAdaptor $dba
  Example     : my $sid = $support->get_taxonony_id($dba);
  Description : Retrieves the taxononmy ID from the meta table
  Return type : Int - the taxonomy ID
  Exceptions  : thrown if no taxonomy ID is found in the database
  Caller      : general

=cut

sub get_taxonomy_id {
    my ($self, $dba) = @_;
964
    $dba ||= $self->dba;
965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980
    my $sql = 'SELECT meta_value FROM meta WHERE meta_key = "species.taxonomy_id"';
    my $sth = $dba->dbc->db_handle->prepare($sql);
    $sth->execute;
    my ($tid) = $sth->fetchrow_array;
    $sth->finish;
    $self->throw("Could not determine taxonomy_id from database.") unless $tid;
    return $tid;
}

=head2 get_species_scientific_name

  Arg[1]      : Bio::EnsEMBL::DBSQL::DBAdaptor $dba
  Example     : my $species = $support->get_species_scientific_name($dba);
  Description : Retrieves the species scientific name (Genus species) from the
                meta table
  Return type : String - species scientific name
981
  Exceptions  : thrown if species name can not be determined from db
982 983 984 985 986 987
  Caller      : general

=cut

sub get_species_scientific_name {
    my ($self, $dba) = @_;
988
    $dba ||= $self->dba;
989 990
    my $sql_tmp = "SELECT meta_value FROM meta WHERE meta_key = \'species.classification\' ORDER BY meta_id";
    my $sql = $dba->dbc->add_limit_clause($sql_tmp,2);
991 992 993 994 995 996 997 998 999 1000 1001 1002 1003
    my $sth = $dba->dbc->db_handle->prepare($sql);
    $sth->execute;
    my @sp;
    while (my @row = $sth->fetchrow_array) {
        push @sp, $row[0];
    }
    $sth->finish;
    my $species = join(" ", reverse @sp);
    $self->throw("Could not determine species scientific name from database.")
        unless $species;
    return $species;
}

1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027
=head2 species

  Arg[1]      : (optional) String $species - species name to set
  Example     : my $species = $support->species;
                my $url = "http://vega.sanger.ac.uk/$species/";
  Description : Getter/setter for species name (Genus_species). If not set, it's
                determined from database's meta table
  Return type : String - species name
  Exceptions  : none
  Caller      : general

=cut

sub species {
    my $self = shift;
    $self->{'_species'} = shift if (@_);
    # get species name from database if not set
    unless ($self->{'_species'}) {
        $self->{'_species'} = join('_',
            split(/ /, $self->get_species_scientific_name));
    }
    return $self->{'_species'};
}

1028 1029
=head2 sort_chromosomes

1030
  Arg[1]      : (optional) Hashref $chr_hashref - Hashref with chr_name as keys
1031 1032 1033
  Example     : my $chr = { '6-COX' => 1, '1' => 1, 'X' => 1 };
                my @sorted = $support->sort_chromosomes($chr);
  Description : Sorts chromosomes in an intuitive way (numerically, then
1034 1035
                alphabetically). If no chromosome hashref is passed, it's
                retrieve by calling $self->get_chrlength()
1036 1037 1038 1039 1040 1041 1042 1043
  Return type : List - sorted chromosome names
  Exceptions  : thrown if no hashref is provided
  Caller      : general

=cut

sub sort_chromosomes {
    my ($self, $chr_hashref) = @_;
1044
    $chr_hashref = $self->get_chrlength unless ($chr_hashref);
1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091
    throw("You have to pass a hashref of your chromosomes")
        unless ($chr_hashref and ref($chr_hashref) eq 'HASH');
    return (sort _by_chr_num keys %$chr_hashref);
}

=head2 _by_chr_num

  Example     : my @sorted = sort _by_chr_num qw(X, 6-COX, 14, 7);
  Description : Subroutine to use in sort for sorting chromosomes. Sorts
                numerically, then alphabetically
  Return type : values to be used by sort
  Exceptions  : none
  Caller      : internal ($self->sort_chromosomes)

=cut

sub _by_chr_num {
    my @awords = split /-/, $a;
    my @bwords = split /-/, $b;

    my $anum = $awords[0];
    my $bnum = $bwords[0];

    if ($anum !~ /^[0-9]*$/) {
        if ($bnum !~ /^[0-9]*$/) {
            return $anum cmp $bnum;
        } else {
            return 1;
        }
    }
    if ($bnum !~ /^[0-9]*$/) {
        return -1;
    }

    if ($anum <=> $bnum) {
        return $anum <=> $bnum;
    } else {
        if ($#awords == 0) {
            return -1;
        } elsif ($#bwords == 0) {
            return 1;
        } else {
            return $awords[1] cmp $bwords[1];
        }
    }
}

1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127
=head2 split_chromosomes_by_size

  Arg[1]      : (optional) Int $cutoff - the cutoff in bp between small and
                large chromosomes
  Example     : my $chr_slices = $support->split_chromosomes_by_size;
                foreach my $block_size (keys %{ $chr_slices }) {
                    print "Chromosomes with blocksize $block_size: ";
                    print join(", ", map { $_->seq_region_name }
                                        @{ $chr_slices->{$block_size} });
                }
  Description : Determines block sizes for storing DensityFeatures on
                chromosomes, and return slices for each chromosome. The block
                size is determined so that you have 150 bins for the smallest
                chromosome over 5 Mb in length. For chromosomes smaller than 5
                Mb, an additional smaller block size is used to yield 150 bins
                for the overall smallest chromosome. This will result in
                reasonable resolution for small chromosomes and high
                performance for big ones.
  Return type : Hashref (key: block size; value: Arrayref of chromosome
                Bio::EnsEMBL::Slices)
  Exceptions  : none
  Caller      : density scripts

=cut

sub split_chromosomes_by_size {
    my $self = shift;
    my $cutoff = shift || 5000000;
    
    my $slice_adaptor = $self->dba->get_SliceAdaptor;
    my $top_slices;
    if ($self->param('chromosomes')) {
        foreach my $chr ($self->param('chromosomes')) {
            push @{ $top_slices }, $slice_adaptor->fetch_by_region('chromosome', $chr);
        }
    } else {
Steve Trevanion's avatar
Steve Trevanion committed
1128
        $top_slices = $slice_adaptor->fetch_all('chromosome');
1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153
    }

    my ($big_chr, $small_chr, $min_big_chr, $min_small_chr);
    foreach my $slice (@{ $top_slices }) {
        if ($slice->length < $cutoff) {
            if (! $min_small_chr or ($min_small_chr > $slice->length)) {
                $min_small_chr = $slice->length;
            }
            # push small chromosomes onto $small_chr
            push @{ $small_chr }, $slice;
        }
        if (! $min_big_chr or ($min_big_chr > $slice->length) && $slice->length > $cutoff) {
            $min_big_chr = $slice->length;
        }
        # push _all_ chromosomes onto $big_chr
        push @{ $big_chr }, $slice;
    }

    my $chr_slices;
    $chr_slices->{int($min_big_chr/150)} = $big_chr if $min_big_chr;
    $chr_slices->{int($min_small_chr/150)} = $small_chr if $min_small_chr;

    return $chr_slices;
}

1154 1155 1156 1157
=head2 log

  Arg[1]      : String $txt - the text to log
  Arg[2]      : Int $indent - indentation level for log message
1158
  Example     : my $log = $support->log_filehandle;
1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171
                $support->log('Log foo.\n', 1);
  Description : Logs a message to the filehandle initialised by calling
                $self->log_filehandle(). You can supply an indentation level
                to get nice hierarchical log messages.
  Return type : true on success
  Exceptions  : thrown when no filehandle can be obtained
  Caller      : general

=cut

sub log {
    my ($self, $txt, $indent) = @_;
    $indent ||= 0;
1172 1173 1174 1175 1176
    
    # strip off leading linebreaks so that indenting doesn't break
    $txt =~ s/^(\n*)//;
    
    $txt = $1."    "x$indent . $txt;
1177 1178 1179 1180 1181 1182 1183 1184 1185 1186
    my $fh = $self->{'_log_filehandle'};
    throw("Unable to obtain log filehandle") unless $fh;
    print $fh "$txt";
    return(1);
}

=head2 log_warning

  Arg[1]      : String $txt - the warning text to log
  Arg[2]      : Int $indent - indentation level for log message
Web Admin's avatar
Web Admin committed
1187
  Arg[2]      : Bool - add a line break before warning if true
1188
  Example     : my $log = $support->log_filehandle;
1189 1190 1191 1192 1193 1194 1195 1196 1197
                $support->log_warning('Log foo.\n', 1);
  Description : Logs a message via $self->log and increases the warning counter.
  Return type : true on success
  Exceptions  : none
  Caller      : general

=cut

sub log_warning {
Web Admin's avatar
Web Admin committed
1198 1199 1200
    my ($self, $txt, $indent, $break) = @_;
    $txt = "WARNING: " . $txt;
	$txt = "\n$txt" if ($break);
1201 1202 1203 1204 1205
    $self->log($txt, $indent);
    $self->{'_warnings'}++;
    return(1);
}

1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273
=head2 log_error

  Arg[1]      : String $txt - the error text to log
  Arg[2]      : Int $indent - indentation level for log message
  Example     : my $log = $support->log_filehandle;
                $support->log_error('Log foo.\n', 1);
  Description : Logs a message via $self->log and exits the script.
  Return type : none
  Exceptions  : none
  Caller      : general

=cut

sub log_error {
    my ($self, $txt, $indent) = @_;
    $txt = "ERROR: ".$txt;
    $self->log($txt, $indent);
    $self->log("Exiting.\n");
    exit;
}

=head2 log_verbose

  Arg[1]      : String $txt - the warning text to log
  Arg[2]      : Int $indent - indentation level for log message
  Example     : my $log = $support->log_filehandle;
                $support->log_verbose('Log this verbose message.\n', 1);
  Description : Logs a message via $self->log if --verbose option was used
  Return type : TRUE on success, FALSE if not verbose
  Exceptions  : none
  Caller      : general

=cut

sub log_verbose {
    my ($self, $txt, $indent) = @_;

    return(0) unless $self->param('verbose');

    $self->log($txt, $indent);
    return(1);
}

=head2 log_stamped

  Arg[1]      : String $txt - the warning text to log
  Arg[2]      : Int $indent - indentation level for log message
  Example     : my $log = $support->log_filehandle;
                $support->log_stamped('Log this stamped message.\n', 1);
  Description : Appends timestamp and memory usage to a message and logs it via
                $self->log
  Return type : TRUE on success
  Exceptions  : none
  Caller      : general

=cut

sub log_stamped {
    my ($self, $txt, $indent) = @_;
    
    # append timestamp and memory usage to log text
    $txt =~ s/(\n*)$//;
    $txt .= " ".$self->date_and_mem.$1;
    
    $self->log($txt, $indent);
    return(1);
}

1274 1275
=head2 log_filehandle

1276 1277
  Arg[1]      : (optional) String $mode - file access mode
  Example     : my $log = $support->log_filehandle;
1278 1279 1280 1281 1282 1283
                # print to the filehandle
                print $log 'Lets start logging...\n';
                # log via the wrapper $self->log()
                $support->log('Another log message.\n');
  Description : Returns a filehandle for logging (STDERR by default, logfile if
                set from config or commandline). You can use the filehandle
1284 1285 1286 1287
                directly to print to, or use the smart wrapper $self->log().
                Logging mode (truncate or append) can be set by passing the
                mode as an argument to log_filehandle(), or with the
                --logappend commandline option (default: truncate)
1288 1289 1290 1291 1292 1293 1294 1295
  Return type : Filehandle - the filehandle to log to
  Exceptions  : thrown if logfile can't be opened
  Caller      : general

=cut

sub log_filehandle {
    my ($self, $mode) = @_;
1296 1297
    $mode ||= '>';
    $mode = '>>' if ($self->param('logappend'));
1298 1299
    my $fh = \*STDERR;
    if (my $logfile = $self->param('logfile')) {
1300
        if (my $logpath = $self->param('logpath')) {
Patrick Meidl's avatar
Patrick Meidl committed
1301 1302 1303 1304
            unless (-e $logpath) {
                system("mkdir $logpath") == 0 or
                    $self->log_error("Can't create log dir $logpath: $!\n");
            }
1305 1306
            $logfile = "$logpath/$logfile";
        }
1307 1308 1309 1310 1311 1312 1313
        open($fh, "$mode", $logfile) or throw(
            "Unable to open $logfile for writing: $!");
    }
    $self->{'_log_filehandle'} = $fh;
    return $self->{'_log_filehandle'};
}

1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343
=head2 filehandle

  Arg[1]      : String $mode - file access mode
  Arg[2]      : String $file - input or output file
  Example     : my $fh = $support->filehandle('>>', '/path/to/file');
                # print to the filehandle
                print $fh 'Your text goes here...\n';
  Description : Returns a filehandle (*STDOUT for writing, *STDIN for reading
                by default) to print to or read from.
  Return type : Filehandle - the filehandle
  Exceptions  : thrown if file can't be opened
  Caller      : general

=cut

sub filehandle {
    my ($self, $mode, $file) = @_;
    $mode ||= ">";
    my $fh;
    if ($file) {
        open($fh, "$mode", $file) or throw(
            "Unable to open $file for writing: $!");
    } elsif ($mode =~ />/) {
        $fh = \*STDOUT;
    } elsif ($mode =~ /</) {
        $fh = \*STDIN;
    }
    return $fh;
}

1344 1345
=head2 init_log

1346 1347 1348 1349 1350 1351
  Example     : $support->init_log;
  Description : Opens a filehandle to the logfile and prints some header
                information to this file. This includes script name, date, user
                running the script and parameters the script will be running
                with.
  Return type : Filehandle - the log filehandle
1352 1353 1354 1355 1356 1357 1358 1359
  Exceptions  : none
  Caller      : general

=cut

sub init_log {
    my $self = shift;

1360 1361 1362
    # get a log filehandle
    my $log = $self->log_filehandle;

1363 1364 1365 1366 1367 1368
    # print script name, date, user who is running it
    my $hostname = `hostname`;
    chomp $hostname;
    my $script = "$hostname:$Bin/$Script";
    my $user = `whoami`;
    chomp $user;
1369
    $self->log("Script: $script\nDate: ".$self->date."\nUser: $user\n");
1370 1371

    # print parameters the script is running with
1372 1373
    $self->log("Parameters:\n\n");
    $self->log($self->list_all_params);
1374

1375 1376 1377 1378
    # remember start time
    $self->{'_start_time'} = time;

    return $log;
1379 1380 1381 1382
}

=head2 finish_log

1383 1384 1385 1386
  Example     : $support->finish_log;
  Description : Writes footer information to a logfile. This includes the
                number of logged warnings, timestamp and memory footprint.
  Return type : TRUE on success
1387 1388 1389 1390 1391 1392 1393
  Exceptions  : none
  Caller      : general

=cut

sub finish_log {
    my $self = shift;
Patrick Meidl's avatar
Patrick Meidl committed
1394
    $self->log("\nAll done. ".$self->warnings." warnings. ");
1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405
    if ($self->{'_start_time'}) {
        $self->log("Runtime ");
        my $diff = time - $self->{'_start_time'};
        my $sec = $diff % 60;
        $diff = ($diff - $sec) / 60;
        my $min = $diff % 60;
        my $hours = ($diff - $min) / 60;
        $self->log("${hours}h ${min}min ${sec}sec ");
    }
    $self->log($self->date_and_mem."\n\n");
    return(1);
1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419
}

=head2 date_and_mem

  Example     : print LOG "Time, memory usage: ".$support->date_and_mem."\n";
  Description : Prints a timestamp and the memory usage of your script.
  Return type : String - timestamp and memory usage
  Exceptions  : none
  Caller      : general

=cut

sub date_and_mem {
    my $date = strftime "%Y-%m-%d %T", localtime;
Patrick Meidl's avatar
Patrick Meidl committed
1420
    my $mem = `ps -p $$ -o vsz |tail -1`;
1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450
    chomp $mem;
    return "[$date, mem $mem]";
}

=head2 date

  Example     : print "Date: " . $support->date . "\n";
  Description : Prints a nicely formatted timestamp (YYYY-DD-MM hh:mm:ss)
  Return type : String - the timestamp
  Exceptions  : none
  Caller      : general

=cut

sub date {
    return strftime "%Y-%m-%d %T", localtime;
}

=head2 mem

  Example     : print "Memory usage: " . $support->mem . "\n";
  Description : Prints the memory used by your script. Not sure about platform
                dependence of this call ...
  Return type : String - memory usage
  Exceptions  : none
  Caller      : general

=cut

sub mem {
Patrick Meidl's avatar
Patrick Meidl committed
1451
    my $mem = `ps -p $$ -o vsz |tail -1`;
1452 1453 1454 1455
    chomp $mem;
    return $mem;
}

Patrick Meidl's avatar
Patrick Meidl committed
1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478
=head2 commify

  Arg[1]      : Int $num - a number to commify
  Example     : print "An easy to read number: ".$self->commify(100000000);
                # will print 100,000,000
  Description : put commas into a number to make it easier to read
  Return type : a string representing the commified number
  Exceptions  : none
  Caller      : general
  Status      : stable

=cut

sub commify {
  my $self = shift;
  my $num = shift;

  $num = reverse($num);
  $num =~ s/(\d\d\d)(?=\d)(?!\d*\.)/$1,/g;

  return scalar reverse $num;
}

Web Admin's avatar
Web Admin committed
1479 1480 1481 1482 1483 1484 1485
=head2 fetch_non_hidden_slices

  Arg[1]      : B::E::SliceAdaptor
  Arg[2]      : B::E::AttributeAdaptor
  Arg[3]      : string $coord_system_name (optional) - 'chromosome' by default
  Arg[4]      : string $coord_system_version (optional) - 'otter' by default
  Example     : $chroms = $support->fetch_non_hidden_slice($sa);
Steve Trevanion's avatar
Steve Trevanion committed
1486
  Description : retrieve all slices from a loutra database that don't have a hidden attribute
Web Admin's avatar
Web Admin committed
1487 1488 1489 1490 1491 1492 1493 1494 1495 1496
  Return type : arrayref
  Caller      : general
  Status      : stable

=cut

sub fetch_non_hidden_slices {
	my $self = shift;
	my $aa   = shift or throw("You must supply an attribute adaptor");
	my $sa   = shift or throw("You must supply a slice adaptor");
Steve Trevanion's avatar
Steve Trevanion committed
1497 1498
	my $cs   = shift || 'chromosome';
	my $cv   = shift || 'Otter';
Web Admin's avatar
Web Admin committed
1499 1500
	my $visible_chroms;
	foreach my $chrom ( @{$sa->fetch_all($cs,$cv)} ) {
Steve Trevanion's avatar
Steve Trevanion committed
1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514
		my $chrom_name = $chrom->name;
		my $attribs = $aa->fetch_all_by_Slice($chrom,'hidden');
		if ( scalar(@$attribs) > 1 ) {
			$self->log_warning("More than one hidden attribute for chromosome $chrom_name\n");
		}
		elsif ($attribs->[0]->value == 0) {				
			push @$visible_chroms, $chrom;
		}
		elsif ($attribs->[0]->value == 1) {	
			$self->log_verbose("chromosome $chrom_name is hidden\n");	
		}
		else {
			$self->log_warning("No hidden attribute for chromosome $chrom_name\n");
		}
Web Admin's avatar
Web Admin committed
1515 1516 1517 1518
	}
	return $visible_chroms;
}

Steve Trevanion's avatar
Steve Trevanion committed
1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568
=head2 get_wanted_chromosomes

  Arg[1]      : B::E::U::ConversionSupport
  Arg[2]      : B::E::SliceAdaptor
  Arg[3]      : B::E::AttributeAdaptor
  Arg[4]      : string $coord_system_name (optional) - 'chromosome' by default
  Arg[5]      : string $coord_system_version (optional) - 'otter' by default
  Example     : @chr_names = &Slice::get_wanted_chromosomes($support,$laa,$lsa);
  Description : retrieve names of slices from a lutra database that are ready for dumping to Vega.
                Deals with list of names to ignore (ignore_chr = LIST)
  Return type : arrayref