LA_Wrapper 28.4 KB
Newer Older
1 2
#!/bin/bash

3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
# Copyright (c)     -2014, Christoph Martin, JGU Mainz
#               2014-2019, Christian Meesters, JGU Mainz
# All rights reserved.
# 
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 
#     * Redistributions of source code must retain the above copyright
#       notice, this list of conditions and the following disclaimer.
#     * Redistributions in binary form must reproduce the above copyright
#       notice, this list of conditions and the following disclaimer in the
#       documentation and/or other materials provided with the distribution.
#     * Neither the name of Christian Meesters or the JGU Mainz nor the names of
#       its contributors may be used to endorse or promote products derived
#       from this software without specific prior written permission.
# 
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
Christian Meesters's avatar
Christian Meesters committed
22
# ARE DISCLAIMED. IN NO EVENT SHALL CHRISTIAN MEESTERS OR THE JGU MAINZ BE LIABLE
23 24 25 26 27 28 29 30 31
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
# DAMAGE.


32
#set -x
33 34
set -e
PS4='Line ${LINENO}: '
35

Christian Meesters's avatar
Christian Meesters committed
36 37 38
# to measure the excecution time independent of SLURM
START=$(date +%s.%N)

39 40 41 42 43 44 45 46
# purging the module list, because interference with other modules
# should be avoided
module purge

# load the most current version of GNU parallel
module load tools/parallel

# load the most current version of BLAST +
47
#module load bio/BLAST+ # do not rely on most recent version
48
module load bio/BLAST+/2.9.0-foss-2018a
49 50 51

module load lang/Python/3.6.4-foss-2018a

52 53
### setup variable for THIS script; giving absolute path if necessary
SCRIPT="$0"
54
SCRIPT_VERSION="0.4"
55

56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 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
# TODO: delete the following 3 functions, once sbcast is working
function queue {
  QUEUE="$QUEUE $1"
  NUM=$((NUM+1))
}

function regeneratequeue {
  OLDREQUEUE=$QUEUE
  QUEUE=""
  NUM=0
  for PID in $OLDREQUEUE; do
    if [ -d /proc/$PID ]; then
      QUEUE="$QUEUE $PID"
      NUM=$((NUM+1))
    fi
  done
}

function checkqueue {
  OLDCHQUEUE=$QUEUE
  for PID in $OLDCHQUEUE; do
    if [ ! -d /proc/$PID ]; then
      regeneratequeue # at least one PID has finished
    fi
  done
}

die()
{
        local _ret=$2
        test -n "$_ret" || _ret=1
        test "$_PRINT_HELP" = yes && print_help >&2
        echo "$1" >&2
        exit ${_ret}
}

begins_with_short_option()
{
        local first_option all_short_options
        all_short_options='lqscmrh'
        first_option="${1:0:1}"
        test "$all_short_options" = "${all_short_options/$first_option/}" && return 1 || return 0
}

100 101 102 103
# function to redirect simple error messages to stderr
error() {
    (>&2 echo "ERROR: $1") 
}
104 105 106 107 108 109 110

# THE DEFAULTS INITIALIZATION - POSITIONALS
_positionals=()
_arg_leftovers=()
# THE DEFAULTS INITIALIZATION - OPTIONALS
declare -i _arg_runlimit=300
_arg_queue=nodeshort
111
# TODO: ask for account, if string is NULL
112 113
_arg_assoc=$(sacct -nu $USER -o Account | tail -n1)
declare -i _arg_nodes=1
114
_arg_reservation=''
Christian Meesters's avatar
Christian Meesters committed
115
declare _arg_mem=1G
116
declare -i _arg_blast_threads=1
117
_arg_blast_params=''
118 119 120
declare -i _arg_splitup_per_queryfile=20
declare _arg_ramdisk=40G
_arg_blastdir='.'
121
_arg_executable='blastx'
122
_arg_test=off
Christian Meesters's avatar
Christian Meesters committed
123
_arg_compress=off
124 125 126 127

print_help ()
{
        echo "This script's help msg"
Christian Meesters's avatar
Christian Meesters committed
128
        printf 'Usage: %s [-l|--runlimit <arg>] [-p|--partition <arg>] [-s|--splitup <arg>] [-N|--nodes <arg>] [--executable <arg>] [-m|--mem <arg>] [--blastparams <string>] [-r|--ramdisk <arg>] [--blastdir <arg>] [--(no-)test] [-h|--help] <FASTA> <DATABASE>\n' "$(basename $0)\n"
Christian Meesters's avatar
Christian Meesters committed
129
        printf 'HINT: The FASTA and DATABASE items need to be full paths to files.'
130
        printf "\t%s\n" "<FASTA>: path to the query FASTA file"
131 132 133 134 135
        printf "\t%s\n" "<DATABASE>: path to the database file"
        printf "\t%s\n" "-l,--runlimit: runlimit default is 300 min, queue will be nodeshort, if <= 300 (default)"
        printf "\t%s\n" "-p,--partition: queue (default is nodeshort)"
        printf "\t%s\n" "-A,--account: queue (default is the last submit account; an error is triggered if none specified nor can be deduced)"
        printf "\t%s\n" "-N,--nodes: number of nodes  (1 is the default)"
136
        printf "\t%s\n" "--reservation: reservation to use  (none is the default)"
137
        printf "\t%s\n" "--time: time in minutes  (300 is the default)"
Christian Meesters's avatar
Christian Meesters committed
138
        printf "\t%s\n" "-m,--mem: memory which is required per node (defaults to 115500 M, but should be min. 242500 M for blastn)"
139
        printf "\t%s\n" "-r,--ramdisk: ramdisk size in units of GiB (default is 40 GiB)"
140
        printf "\t%s\n" "-t,--threads: blast threads (default is 1)"
141
        printf "\t%s\n" "--blastparams: blast parameters (default is -outfmt 5 (for xml output))"
Christian Meesters's avatar
Christian Meesters committed
142 143
        printf "\t%s\n" "-s,--splitup: No. of FASTA sequences per query file (default is 20)"
        printf "\t%s\n" "--blastdir: output directory (default is composition of input names)"
144
        printf "\t%s\n" "--executable: choose executable (currently only from NCBI-BLAST, default: blastx)"
Christian Meesters's avatar
Christian Meesters committed
145
        printf "\t%s\n" "--compress: if set, the output files will be merged and compressed (time consuming!, defaultt: off)"
146
        printf "\t%s\n" "--test,--no-test: dry run, testing only (off by default)"
147
        printf "\t%s\n" "--credits,--version: Prints credits and a brief version history and exits"
148 149
        printf "\t%s\n" "-h,--help: Prints help"
        echo
Christian Meesters's avatar
Christian Meesters committed
150 151 152 153 154 155 156 157 158 159
        echo -e "\e[3mWARNINGS:\e[0m"
        echo -e "\e[3m- BLAST parameters:\e[0m"
        echo "  There are no BLAST default parameters, other than specifing XML output, the database and"
        echo "  queries as well as the numer of threads (all set by this script)."
        echo "  Detailed overview on parameters can be shown by entering <blastexecutable> -help"
        echo -e "\e[3m- Limitations:\e[0m"
        echo "  - Currently only NCBI-BLAST+ executables are supported."
        echo "  - References may be as big as 30G, 50G may also work."
        echo "    References beyond this this may or not work."
        echo "    Be sure to reserve sufficient RAM."
Christian Meesters's avatar
Christian Meesters committed
160 161 162 163 164 165 166 167 168 169
        echo 
        echo "Planned features for upcoming versions:"
        echo "- better, more stable user interface"
        echo "- support for alternate implementations, e.g. BLAT, diamond"
        echo "- automatic merging of xml output"
        echo "- restart capability to resume work in case of timelimits."
        echo "- beeond support for handling greater references"
        echo "- automatic reference database generation in case of version mismatches or similar"
        echo 
        echo "Minor improvements will be implemented as time permits. Yet, to make this possible,"
Christian Meesters's avatar
Christian Meesters committed
170
        echo -e "\e[1myou can request a collaboration\e[0m (for minor add ons an acknowladegement by name will do)."
171 172
}

Christian Meesters's avatar
Christian Meesters committed
173 174 175 176 177 178
credits()
{
        echo "The original implementation (2013/2014) was written by Christoph Martin (ZDV, UNIX group)"
        echo "Benjamin Rieger (Institut für Molekulargenetik) contributed a perl implementation"
        echo "of a format conform splitting of FASTA files."
        echo "The original implemenation was a LSF chain job. It was eventually adopted and maintained by"
179
        echo "Christian Meesters (ZDV, HPC group) from 2017 onwards."
Christian Meesters's avatar
Christian Meesters committed
180 181
        echo 
        echo "History of the re-implementation:"
182 183 184 185
        echo "- v0.1   -- 27. Sep. 2017 -- release of the re-implementation for SLURM supporting the"
        echo "                             ability to compute accross nodes."
        echo "- v0.1.1 -- 19. Oct. 2017 -- bug fix: blast parameters now correctly transferred to"
        echo "                             blast(x)."
Christian Meesters's avatar
Christian Meesters committed
186
        echo "- v0.1.2 -- 25. Oct. 2017 -- minor fixes and clarifications"
187
        echo "- v0.2.b -- 18. Jan. 2018 -- new features:"
188 189 190
        echo "                             - possible to choose between NCBI-BLAST executables"
        echo "                             - better user feedback / self documentation \(at least a start\)"
        echo "                             - error messages are now directed to stderr"
191
        echo "                             - jobs may use reservations (e.g. for courses)"
192 193 194
        echo "                             changes:"
        echo "                             - deleted default evalue and max_target_seqs settings"
        echo "                             - XML output is mandatory"
195 196
        echo "                             fix:"
        echo "                             - introduced missing --time option"
197
        echo "                             - changed the blast parameter interface"
Christian Meesters's avatar
Christian Meesters committed
198
        echo "- v0.3   -- 21. Feb. 2018 -- faster merging of output files, parallel zipping"
199 200 201 202
        echo "- v0.3.1 -- 15. May  2018 -- bugfixes in handling the blast executables"
        echo "- v0.3.2 -- 16. Jan. 2019 -- hot fix for new ramdisk and slurmstepd support"
        echo "- v0.4   -- 06. Mar. 2019 -- refactored version:"
        echo "                             - executables now pluggable"
203 204
        echo 
        echo "Current version is: $SCRIPT_VERSION"
Christian Meesters's avatar
Christian Meesters committed
205 206 207 208 209
        echo
        echo "The re-implementation supporting parallel BLAST+ jobs accross several compute nodes has been"
        echo "written and is maintained by Christian Meesters (ZDV, HPC group)."
        echo "A (personal) acknowledgement is welcomed. Please refer to:"
        echo "https://hpc.uni-mainz.de/high-performance-computing/publikationen/"
210
        exit
Christian Meesters's avatar
Christian Meesters committed
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 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281
# command line parsing
while test $# -gt 0
do
        _key="$1"
        case "$_key" in
                -l*|--runlimit|--runlimit=*)
                        _val_from_long="${_key##--runlimit=}"
                        _val_from_short="${_key##-l}"
                        if test "$_val_from_long" != "$_key"
                        then
                                _val="$_val_from_long"
                        elif test "$_val_from_short" != "$_key" -a -n "$_val_from_short"
                        then
                                _val="$_val_from_short"
                        else
                                test $# -lt 2 && die "Missing value for the optional argument '$_key'." 1
                                _val="$2"
                                shift
                        fi
                        _arg_runlimit="$_val"
                        ;;
                -p*|--partition|--partition=*)
                        _val_from_long="${_key##--partition=}"
                        _val_from_short="${_key##-p}"
                        if test "$_val_from_long" != "$_key"
                        then
                                _val="$_val_from_long"
                        elif test "$_val_from_short" != "$_key" -a -n "$_val_from_short"
                        then
                                _val="$_val_from_short"
                        else
                                test $# -lt 2 && die "Missing value for the optional argument '$_key'." 1
                                _val="$2"
                                shift
                        fi
                        _arg_queue="$_val"
                        ;;
                -A*|--account|--account=*)
                        _val_from_long="${_key##--account=}"
                        _val_from_short="${_key##-A}"
                        if test "$_val_from_long" != "$_key"
                        then
                                _val="$_val_from_long"
                        elif test "$_val_from_short" != "$_key" -a -n "$_val_from_short"
                        then
                                _val="$_val_from_short"
                        else
                                test $# -lt 2 && die "Missing value for the optional argument '$_key'." 1
                                _val="$2"
                                shift
                        fi
                        _arg_assoc="$_val"
                        ;;
                -N*|--nodes|--nodes=*)
                        _val_from_long="${_key##--nodes=}"
                        _val_from_short="${_key##-N}"
                        if test "$_val_from_long" != "$_key"
                        then
                                _val="$_val_from_long"
                        elif test "$_val_from_short" != "$_key" -a -n "$_val_from_short"
                        then
                                _val="$_val_from_short"
                        else
                                test $# -lt 2 && die "Missing value for the optional argument '$_key'." 1
                                _val="$2"
                                shift
                        fi
                        _arg_nodes="$_val"
                        ;;
282 283 284 285 286 287 288 289 290 291
                --reservation|--reservation=*)
                        _val="${_key##--reservation=}"
                        if test "$_val" = "$_key"
                        then
                                test $# -lt 2 && die "Missing value for the optional argument '$_key'." 1
                                _val="$2"
                                shift
                        fi
                        _arg_reservation="$_val"
                        ;;
292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307
                --time|--time=*)
                        _val_from_long="${_key##--time=}"
                        _val_from_short="${_key##-N}"
                        if test "$_val_from_long" != "$_key"
                        then
                                _val="$_val_from_long"
                        elif test "$_val_from_short" != "$_key" -a -n "$_val_from_short"
                        then
                                _val="$_val_from_short"
                        else
                                test $# -lt 2 && die "Missing value for the optional argument '$_key'." 1
                                _val="$2"
                                shift
                        fi
                        _arg_runlimit="$_val"
                        ;;
Christian Meesters's avatar
Christian Meesters committed
308 309
                -m*|--mem|--mem=*)
                        _val_from_long="${_key##--mem=}"
310 311 312 313 314 315 316 317
                        if test "$_val_from_long" != "$_key"
                        then
                                _val="$_val_from_long"
                        else
                                test $# -lt 2 && die "Missing value for the optional argument '$_key'." 1
                                _val="$2"
                                shift
                        fi
Christian Meesters's avatar
Christian Meesters committed
318
                        _arg_mem="$_val"
319
                        ;;
320 321 322 323 324 325 326 327 328 329 330 331
                --blastparams|--blastparams=*)
                        _val_from_long="${_key##--blastparams=}"
                        if test "$_val_from_long" != "$_key"
                        then
                                _val="$_val_from_long"
                        else
                                test $# -lt 2 && die "Missing value for the optional argument '$_key'." 1
                                _val="$2"
                                shift
                        fi
                        _arg_blastparams="$_val"
                        ;;
332 333 334 335 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
                -t*|--threads|--threads=*)
                        _val_from_long="${_key##--threads=}"
                        _val_from_short="${_key##-t}"
                        if test "$_val_from_long" != "$_key"
                        then
                                _val="$_val_from_long"
                        elif test "$_val_from_short" != "$_key" -a -n "$_val_from_short"
                        then
                                _val="$_val_from_short"
                        else
                                test $# -lt 2 && die "Missing value for the optional argument '$_key'." 1
                                _val="$2"
                                shift
                        fi
                        _arg_blast_threads="$_val"
                        ;;
                -s*|--splitup|--splitup=*)
                        _val_from_long="${_key##--splitup=}"
                        _val_from_short="${_key##-s}"
                        if test "$_val_from_long" != "$_key"
                        then
                                _val="$_val_from_long"
                        elif test "$_val_from_short" != "$_key" -a -n "$_val_from_short"
                        then
                                _val="$_val_from_short"
                        else
                                test $# -lt 2 && die "Missing value for the optional argument '$_key'." 1
                                _val="$2"
                                shift
                        fi
                        _arg_splitup_per_queryfile="$_val"
                        ;;
                --blastdir|--blastdir=*)
                        _val="${_key##--blastdir=}"
                        if test "$_val" = "$_key"
                        then
                                test $# -lt 2 && die "Missing value for the optional argument '$_key'." 1
                                _val="$2"
                                shift
                        fi
                        _arg_blastdir="$_val"
                        ;;
374 375 376 377 378 379 380 381 382 383
                --executable|--executable=*)
                        _val="${_key##--executable=}"
                        if test "$_val" = "$_key"
                        then
                                test $# -lt 2 && die "Missing value for the optional argument '$_key'." 1
                                _val="$2"
                                shift
                        fi
                        _arg_executable="$_val"
                        ;;
Christian Meesters's avatar
Christian Meesters committed
384 385 386 387
                --no-compress|--compress)
                        _arg_compress="on"
                        test "${1:0:5}" = "--no-" && _arg_compress="off"
                        ;;
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
                --no-test|--test)
                        _arg_test="on"
                        test "${1:0:5}" = "--no-" && _arg_test="off"
                        ;;
                --credits|--version)
                        credits
                        exit 0
                        ;;
                -h*|--help)
                        print_help
                        exit 0
                        ;;
                *)
                        _positionals+=("$1")
                        ;;
        esac
        shift
done

_positional_names=('_arg_fasta' '_arg_database' )
_required_args_string="'FASTA' and 'DATABASE'"
#test ${#_positionals[@]} -lt 2 && _PRINT_HELP=yes die "FATAL ERROR: Not enough positional arguments - we require exactly 2 (namely: $_required_args_string), but got only ${#_positionals[@]}." 1
#test ${#_positionals[@]} -gt 2 && _PRINT_HELP=yes die "FATAL ERROR: There were spurious positional arguments --- we expect exactly 2 (namely: $_required_args_string), but got ${#_positionals[@]} (the last one was: '${_positionals[*]: -1}')." 1
#for (( ii = 0; ii < ${#_positionals[@]}; ii++))
for (( ii = 0; ii < 2; ii++))
do
        eval "${_positional_names[ii]}=\${_positionals[ii]}" || die "Error during argument parsing, possibly an Argbash bug." 1
done
_our_args=$((${#_positionals[@]} - ${#_positional_names[@]}))
417 418
for (( ii = 0; ii < _our_args; ii++)); do
    _positional_names+=("_arg_leftovers[(($ii + 1))]")
419 420 421 422 423 424 425 426
done

### get query and database files
FASTA=$_arg_fasta
DATABASE=$_arg_database

### check if query & database exist
if [ ! -e "$FASTA" ]; then
427
    error "FASTA input was: '$FASTA' - no such file!"
428 429 430
    exit 1
fi

431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460
#TODO: differentiate between blastn,x,p -- for now, all are equal
if [ "blastx" = "${_arg_executable,,}" ]; then
    executable="blastx"
    threads=2
    if [ -z "$SLURM_JOB_ID" ]; then
        source $(dirname "$0")/blast_wrap.sh
    else
        source "${SCRIPT_PATH}"/blast_wrap.sh
    fi
elif [ "blastn" = "${_arg_executable,,}" ]; then
    executable="blastn"
    threads=8
    if [ -z "$SLURM_JOB_ID" ]; then
        source $(dirname "$0")/blast_wrap.sh
    else
        source "${SCRIPT_PATH}"/blast_wrap.sh
    fi
elif [ "blastp" = "${_arg_executable,,}" ]; then
    executable="blastp"
    threads=2
    if [ -z "$SLURM_JOB_ID" ]; then
        source $(dirname "$0")/blast_wrap.sh
    else
        source "${SCRIPT_PATH}"/blast_wrap.sh
    fi
else 
    error "executable '$_arg_executable' not recognized."
    print_help
    exit 2
fi   
461 462 463

### prepare filepath and -names for creating working folder
FASTAPATH=$(dirname $FASTA)
464
DATABASEPATH=$(realpath $DATABASE)
465 466 467 468 469 470 471 472 473 474 475

FASTAID=$(basename $FASTA)
DATABASEID=$(basename $DATABASE)

FA=${FASTAID%%.*}
DB=${DATABASEID%.*}

JOBTAG="BLAST_${FA}_VS_${DB}"

# default values, see:
#  https://www.ncbi.nlm.nih.gov/books/NBK279675/
476
DEFAULT_BLASTPARAMS='-outfmt 5'
477 478 479 480
# sanity check: '-outfmt' in blast parameters?
if [[ "$_arg_blastparams" =~ "outfmt" ]]; then
    BLASTPARAMS=$_arg_blastparams
else
Christian Meesters's avatar
Christian Meesters committed
481 482 483 484 485 486 487
    BLASTPARAMS="${_arg_blastparams} $DEFAULT_BLASTPARAMS"
fi
# test whether the output is xml or not
if [[ '-outfmt 5' =~ "$BLASTPARAMS" ]]; then
    XMLOUT=1
else
    XMLOUT=0
488
fi
489

490
# TODO: port to M2
491 492 493 494 495 496 497 498 499 500 501 502 503 504
### Auto-Adjust the Queue
if [ $_arg_runlimit -le 300 ]; then
    if [ "$_arg_queue" != "nodeshort" ]; then
        _arg_queue="${_arg_queue/long/short}"
    fi
else
    if [ "$_arg_queue" != "nodeslong" ]; then
        _arg_queue="${_arg_queue/short/long}"
    fi
fi

### check if working directory already exists
if [ -z "$SLURM_JOB_ID" ] && [[ $_arg_test == "off" ]]; then
    if [ -d "$JOBTAG" ]; then
505
        echo "$JOBTAG : directory already exists! Remove? (y/[n])"
506 507 508
        echo -n '>'
        read ENTER
        
509
        if [[ ${ENTER,,} = 'y' ||  ${ENTER,,} == 'yes' ]]; then
510 511 512
            echo "removing directory $JOBTAG"
            rm -r $JOBTAG
        else
513
            echo "So you want to continue regardless? (e.g. scratch files already existing) ([y]/n)"
514 515
            echo -n '>'
            read ENTER
Christian Meesters's avatar
Christian Meesters committed
516
            if [[ ${ENTER,,} = 'n' || ${ENTER,,} == 'no' ]] ; then
517 518
                exit
            fi
519 520 521 522 523 524 525 526 527 528 529 530
        fi
    fi
fi

# we just keep the current working directory
PWD=$(pwd)

### give query and database absolute path if necessary
if [[ ! $FASTAPATH == /* ]]; then
    FASTAPATH="$PWD/$FASTAPATH";
fi

531 532 533
#if [[ ! $DATABASEPATH == /* ]]; then
#    DATABASEPATH="$PWD/$DATABASEPATH";
#fi
534 535

FASTA="$FASTAPATH/$FASTAID"
536
#DATABASE="$DATABASEPATH/$DATABASEID"
537 538

### setup blast and splitup executable; check if exist
539
allowed_executables="blastx blastp blastn"
540 541 542 543
if [[ ! $allowed_executables =~ (^|[[:space:]])"$_arg_executable"($|[[:space:]]) ]]; then
#    BLASTEXE=$(which $_arg_executable)
#else
    error "$_arg_executable ought to be one of [$allowed_executables]"
544
fi
545
BLASTEXE=$(which $_arg_executable)
546
if [ -z $BLASTEXE ] && [[ $_arg_test == "off" ]]; then
547
    error "'$BLASTEXE' : not found, please load an appropriate module before restarting."
548 549 550
    exit
fi

551
### which is the reference directory size?
552
_arg_ramdisk=$(du -shL --block-size=1M "$_arg_database" | cut -f1 )M
553

554
if [[ ! $SCRIPT == /* ]]; then
555
   SCRIPT="$PWD/$SCRIPT";
556 557 558 559
fi

### check if this script is on node by checking env-variable $SLURM_JOB_ID, else send it to SLURM with given parameters and exit
if [ -z "$SLURM_JOB_ID" ]; then
560 561 562 563 564 565 566 567 568 569
    export SCRIPT_PATH=$(dirname $0)
    submit_statement="sbatch --no-requeue -o ${JOBTAG}_%j.out -J $JOBTAG -p $_arg_queue -A $_arg_assoc -t $_arg_runlimit -N $_arg_nodes -n $((64 * $_arg_nodes / $threads)) --mem=$_arg_mem --ramdisk=${_arg_ramdisk} -c $threads"

    script_statement="$SCRIPT --partition $_arg_queue --account $_arg_assoc --nodes $_arg_nodes --time $_arg_runlimit --reservation=$_arg_reservation  --threads $_arg_blast_threads --splitup $_arg_splitup_per_queryfile --blastparams=\"$BLASTPARAMS\" --executable=$_arg_executable $FASTA $DATABASE"
    if [ -n "$_arg_reservation" ]; then
        submit_statement="${submit_statement} --reservation=${_arg_reservation}"
    fi

    # paste them together
    submit_call="${submit_statement} ${script_statement}"
570 571 572 573 574
    if [[ $_arg_test == "on" ]]; then
        echo "Just testing - this command would be submitted:"
        echo $submit_call
        exit
    fi
575
    echo "sending job:"
576
    echo $submit_call
577
    eval $submit_call
578 579 580
    exit
fi

581 582 583 584 585 586 587 588 589 590 591
#### Self-Documentation
echo "You are using $0, version $SCRIPT_VERSION"
echo 
echo "Self-Documentation (on $(date))"
[[ $_arg_test == "on" ]] && echo "  - This is a test-run, only"
echo "  - The query input is '$FASTA'"
echo "  - The database is '$DATABASE'"
BLASTVERSION=$($BLASTEXE -version | head -n1 | cut -f2 -d' ')
echo "  - The executable is '$BLASTEXE', version: $BLASTVERSION"
echo "  - Parameters to your call are: $BLASTPARAMS"

592 593 594 595 596 597 598 599 600 601
### set variables for lokal (node side) directories (working & ramdisk)
JOBDIR=/localscratch/$SLURM_JOB_ID
RAMDISK=$JOBDIR/ramdisk

# copy DB onto ramdisk
# TODO: change to sbcast, once available
HOSTLIST=$(scontrol show hostname $SLURM_JOB_NODELIST | paste -d, -s | tr ',', ' ')
QUEUE=''

for HOST in $HOSTLIST; do
602 603 604 605
   # when copying dereference putative links!
   eval "ssh $HOST cp -Lr $DATABASEPATH $RAMDISK/. &"
   PID=$!
   queue $PID 
606
   # outcommented because of bug in slurm 16.05, see TODO-item
607
   # TODO: check for dereferencing links, before enabling
608 609 610
   #sbcast $FILE $RAMDISK/$(basename $FILE)
done

611 612
#DATABASE=$RAMDISK/$DATABASE
DATABASE=$RAMDISK/$(basename $DATABASEPATH)
613 614

WORKDIR=$PWD/$BLASTDIR/$SLURM_JOB_NAME
615 616 617 618
# this script may never output to a user's $HOME
if [[ *"$WORKDIR"* = 'home' ]]; then
    eror "Cowardly refusing to operate in a home directory."
fi
619 620 621 622 623 624 625
# set path names to ease maintance
SPLITFILEDIR=scratch

### check if exists, if no -> firsttime run, create subdirs and enter, split query file, else just enter
if [ ! -d "$WORKDIR/$SPLITFILEDIR" ]; then
    mkdir -p "$WORKDIR/$SPLITFILEDIR" || exit 1;
    mkdir -p "$WORKDIR/output" || exit 1;
626
    cd "$WORKDIR"
627
    echo "executing scratch generator on $FASTA ($_arg_splitup_per_queryfile entries per file)"
628
    eval "${SCRIPT_PATH}/splitter.py $FASTA $_arg_splitup_per_queryfile" &     # splitup queryfile
629 630
    PID=$!
    queue $PID
631 632
fi

633 634 635 636 637 638
# wait until the copy and a possible scratch generation are finished
while  [[ ! -z "$(echo $QUEUE| tr -d ' ')" ]]; do
   checkqueue
   sleep 5
done

639 640 641 642 643 644 645 646
cd "$WORKDIR"

# calculating the degree of parallelism is necessary in order not to oversaturate with srun processes.
# As $SLURM_CPUS_PER_TASK can be unset, we need to set it in those cases
if [[ -z "$SLURM_CPUS_PER_TASK" ]]; then
   declare -i SLURM_CPUS_PER_TASK=1
fi

647 648 649 650
if [[ -z $DATABASE ]]; then
    error "Unable to recognize database, please get in touch with hpc@uni-mainz.de"
fi

651 652
# see whether we find a  file in the db
tmp=$(find $DATABASE -type f -print -quit)
653 654
# remove the 2nd suffix
DATABASE=${tmp%.*}
Christian Meesters's avatar
Christian Meesters committed
655

656 657 658 659 660 661 662 663 664 665 666 667 668 669
### a temporary script to conduct the alignment
cmdfile=/localscratch/$SLURM_JOB_ID/dummy.sh
cmdfilewriter

chmod +x $cmdfile

newcmd=/localscratch/$SLURM_JOBID/dummy_wrapper.sh
sbcast $cmdfile $newcmd

rm $cmdfile
cmdfile=$newcmd

### append a finishing token to the samples
samples+=('done')
Christian Meesters's avatar
Christian Meesters committed
670 671 672

parallel="parallel --no-notice -j $SLURM_NTASKS -P $SLURM_NTASKS "

673 674
srun="srun --cpu-bind=q --mem-bind=q -n 1 -N1 --exclusive -c $SLURM_CPUS_PER_TASK --jobid $SLURM_JOBID --mem-per-cpu=$((SLURM_MEM_PER_NODE / SLURM_CPUS_ON_NODE))"
$parallel "$srun" "$cmdfile" ::: $(find $(pwd) -type f -name 'group*.fasta') 
675 676

wait
677

678
set -x
679
n_unfinished_files=$(comm -3 <(cd output && find .| grep -o '[0-9]*' |sort ) <(cd scratch && find . | grep -o '[0-9]*' |sort )|wc -l)
Christian Meesters's avatar
Christian Meesters committed
680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698
if [ $n_unfinished_files -eq 0 ] && [[ $_arg_compress == "on" ]] && [ $XMLOUT -eq 1 ]; then
    # shrink the alloction, such that only the minimum necessary is accounted for
    #scontrol update job=$SLURM_JOB_ID NumNodes=1  
    pwd
    # merge all xml files
    STARTC=$(date +%s.%N)
    outfile="${JOBTAG}.xml"
    # select the first of all files
    some_file=$(find ./output -name 'group*' | head -n1)
    zcat $some_file | head -n21 > $outfile
    # extract header information and write to outfile
    for split_file in ./output/group_*.xml.gz; do
        zcat $split_file | tail -n+22  |head -n-3 >> $outfile
    done
    # extract footer information and write to outfile
    zcat $some_file | tail -n3 >> $outfile
    pigz -p 16 $outfile &
    ENDC=$(date +%s.%N)
    elapsedc=$(bc <<< "scale=1; (($ENDC-$STARTC))/60")
699
    rm -rf $WORKDIR/$SPLITFILEDIR &
Christian Meesters's avatar
Christian Meesters committed
700 701
    #rm ./output/group_*.xml &
    #rm -rf ./scratch &
702 703
    wait
fi
Christian Meesters's avatar
Christian Meesters committed
704 705 706 707 708 709

# marks the end of this run
END=$(date +%s.%N)
elapsed=$(bc <<< "scale=1; (($END-$START))/60")

echo "parallel_BLAST took $elapsed minutes to run"
710
    
711 712
# TODO: Check: 1 output item per input scratch file?
# TODO: If not re-submit with correct/adjusted job size