Skip to content

Job Arrays

A job array submits many similar jobs at once, each with a unique SLURM_ARRAY_TASK_ID. Arrays are the preferred way to run the same script across many input files on RCC, because they let you cap how many tasks run at once.

for/while loop vs job array

A common approach for running the same script across many input files is a for/while loop:

while read BAM_PATH
do
    sbatch extract_chromosome_from_bam_file_ssubmit.sh ${BAM_PATH} chr21
done

Upside: familiar, simple, straightforward, quick.

Downside: submitting 433 jobs each requesting 4 cores takes up the vast majority of available resources and can be disruptive to others. Prefer job arrays instead.

Job arrays with a file of file names (FOFN)

A common RCC pattern is to use a file of file names (FOFN) to feed a different input file to each task:

INPUT_BAM_FILE=$(sed -n "${SLURM_ARRAY_TASK_ID}p" ${1})

Breaking this command down:

sed
Stream editor used to parse and transform text.
-n
Suppresses automatic printing; only prints what you explicitly tell it to.
"${SLURM_ARRAY_TASK_ID}p"
Prints the line number matching the task ID.
${1}
The first argument passed to the script, expected to be the FOFN.

Full array script:

#!/bin/bash
#SBATCH --job-name=extract_chrom
#SBATCH --cpus-per-task=4
#SBATCH --mem-per-cpu=4G
#SBATCH --output=logs/%x-%A_%a.out
#SBATCH --error=logs/%x-%A_%a.err
#SBATCH --array=1-433
set -e

TARGET_CHR=${2}
INPUT_BAM_FILE=$(sed -n "${SLURM_ARRAY_TASK_ID}p" ${1})
OUTPUT_DIR="${HOME}/rcc_demo/outputs"
OUTPUT_FILE_PREFIX=$(basename ${INPUT_BAM_FILE} .bam)
OUTPUT_BAM_FILE="${OUTPUT_DIR}/${OUTPUT_FILE_PREFIX}.${TARGET_CHR}.bam"

samtools view --threads ${SLURM_CPUS_PER_TASK} \
    ${INPUT_BAM_FILE} \
    -o ${OUTPUT_BAM_FILE} \
    ${TARGET_CHR}

Note the log naming convention for arrays: %x-%A_%a, where %A is the array job ID and %a is the task ID. This gives each task its own log file. For regular (non-array) scripts, the convention is %x-%j.

Submit with:

sbatch extract_chromosome_from_bam_file_ssubmitArray.sh samples.fofn chr21

Array submission options

# submit all 433 tasks
sbatch --array=1-433 myscript_ssubmitArray.sh FOFN chr21

# rerun a single failed task
sbatch --array=21 myscript_ssubmitArray.sh FOFN chr21

# submit a range or non-consecutive list
sbatch --array=21-23,97 myscript_ssubmitArray.sh FOFN chr21

# run all 433 but only 10 at a time
sbatch --array=1-433%10 myscript_ssubmitArray.sh FOFN chr21

# step size — submit tasks 1, 3, 5, 7
sbatch --array=1-7:2 myscript_ssubmitArray.sh FOFN chr21

Canceling arrays

# cancel all tasks in an array
scancel 24668

# cancel a range of tasks
scancel 24668_[7-10]

# cancel specific tasks
scancel 24668_7 24668_10