# Running Batch Jobs

To launch a DNAnexus application or workflow on many files automatically, one may write a short script to loop over the desired files in a project and launch jobs or analyses. Alternatively, the [DNAnexus SDK](https://documentation.dnanexus.com/downloads) provides a few handy utilities for batch processing. To use the GUI to run in batch mode, see these [instructions](https://documentation.dnanexus.com/getting-started/key-concepts/apps-and-workflows#batch-run).

## Overview

In this tutorial, you batch process a series of sample FASTQ files (forward and reverse reads). Use the `dx generate_batch_inputs` command to generate a *batch file* -- a tab-delimited (TSV) file where each row corresponds to a single run in the batch. Then you process the batch using the [`dx run`](https://documentation.dnanexus.com/helpstrings-of-sdk-command-line-utilities#run) command with the `--batch-tsv` options.

## Generate Batch File

The project *My Research Project* contains the following files in the project's root directory:

```shell
$ dx select "My Research Project"
Selected project My Research Project
$ dx ls /
RP10B_S1_R1_001.fastq.gz
RP10B_S1_R2_001.fastq.gz
RP10T_S5_R1_001.fastq.gz
RP10T_S5_R2_001.fastq.gz
RP15B_S4_R1_002.fastq.gz
RP15B_S4_R2_002.fastq.gz
RP15T_S8_R1_002.fastq.gz
RP15T_S8_R2_002.fastq.gz
```

Batch process these read pairs using [BWA-MEM](https://platform.dnanexus.com/app/bwa_mem_fastq_read_mapper) (link requires platform login). For a **single** execution of the BWA-MEM app, specify the following inputs:

* `reads_fastqgzs` - FASTQ containing the left mates
* `reads2_fastqgzs` - FASTQ containing the right mates
* `genomeindex_targz` - BWA reference genome index

The BWA reference genome index from the public [Reference Genome](https://platform.dnanexus.com/projects/BQpp3Y804Y0xbyG4GJPQ01xv/data/) (requires platform login) project is used for all runs. However, for the forward and reverse reads, the read pairs used vary from run to run. To generate a batch file that pairs the input reads:

```shell
$ dx generate_batch_inputs \
    -i reads_fastqgzs='RP(.*)_R1_(.*).fastq.gz' \
    -i reads2_fastqgzs='RP(.*)_R2_(.*).fastq.gz'
Found 4 valid batch IDs matching desired pattern.
Created batch file dx_batch.0000.tsv

CREATED 1 batch files each with at most 500 batch IDs.
```

{% hint style="info" %}
You can optionally provide a `--path` argument and provide a specific file and folder to search for recursively within your project. Specifically, the value for `--path` must be a directory specified as:

`/path/to/directory` or `project-xxxx:/path/to/directory`

Any file present within this directory or recursively within any subdirectory of this directory is considered a candidate for a batch run.
{% endhint %}

The `(.*)` are regular expression groups. You can provide arbitrary regular expressions as input. The first match in the group is the pattern used to group pairs in the batch. These matches are called *batch identifiers* (batch IDs). To explain this behavior in more detail, consider the output of the `dx generate_batch_inputs` command:

The `dx generate_batch_inputs` command creates the `dx_batch.0000.tsv` that looks like:

```tsv
$ cat dx_batch.0000.tsv
batch ID	reads_fastqgzs	reads2_fastqgzs	reads_fastqgzs ID	reads2_fastqgzs ID
10B_S1	RP10B_S1_R1_001.fastq.gz	RP10B_S1_R2_001.fastq.gz	file-aaa	file-bbb
10T_S5	RP10T_S5_R1_001.fastq.gz	RP10T_S5_R2_001.fastq.gz	file-ccc	file-ddd
15B_S4	RP15B_S4_R1_002.fastq.gz	RP15B_S4_R2_002.fastq.gz	file-eee	file-fff
15T_S8	RP15T_S8_R1_002.fastq.gz	RP15T_S8_R2_002.fastq.gz	file-ggg	file-hhh
```

Recall the regular expression was `RP(.*)_R1_(.*).fastq.gz`. Although there are two grouped matches in this example, only the first one is used as the pattern for the batch ID. For example, the pattern identified for `RP10B_S1_R1_001.fastq.gz` is `10B_S1` which corresponds to the first grouped match while the second one is ignored.

Examining the TSV file above, the files are grouped as expected, with the first match labeling the identifier of the group within the batch. The next two columns show the file names. The last two columns contain the IDs of the files on the DNAnexus Platform. You can either edit this file directly or import it into a spreadsheet to make any subsequent changes.

If an input for the app is an array, the input file IDs within the batch.tsv file need to be in square brackets to work. The following bash command adds brackets to the file IDs in column 4 and 5. You may need to change the variables in the command (`$4` and `$5`) to match the correct columns in your file. The command's output file, "new\.tsv", is ready for the `dx run --batch-tsv` command.

```shell
head -n 1 dx_batch.0000.tsv > temp.tsv && \
tail -n +2 dx_batch.0000.tsv | \
awk '{sub($4, "[&]"); print}' | \
awk '{sub($5, "[&]"); print}' >> temp.tsv && \
tr -d '\r' < temp.tsv > new.tsv && \
rm temp.tsv
```

The example above is for a case where all files have been paired properly. `dx generate_batch_inputs` creates a TSV for all files that can be successfully matched for a particular batch ID. Two classes of errors may occur for batch IDs that are not successfully matched:

* A particular input is missing. This could occur when `reads_fastqgzs` has a pattern but no corresponding match can be found for `reads2_fastqgzs`.
* More than one file ID matches the exact same name.

For both of these cases, `dx generate_batch_inputs` returns a description of these errors to `STDERR`.

{% hint style="info" %}
When matching more than 500 files, multiple batch files are generated in groups of 500 to limit the number of jobs in a single batch run.
{% endhint %}

## Run a Batch Job

With the batch file prepared, you can execute the BWA-MEM batch process:

```shell
dx run bwa_mem_fastq_read_mapper \
  -igenomeindex_targz="Reference Genome Files":\
"/H. Sapiens - GRCh38/GRCh38.no_alt_analysis_set.bwa-index.tar.gz" \
  --batch-tsv dx_batch.0000.tsv
```

Here, `genomeindex_targz` is a parameter set at execution time that is common to all groups in the batch and `--batch-tsv` corresponds to the input file generated above.

To monitor a batch job, use the 'Monitor' tab like you normally would for jobs you launch.

### Setting Output Folders for Batch Jobs

To direct the output of each run into a separate folder, the `--batch-folders` flag can be used, for example:

```shell
dx run bwa_mem_fastq_read_mapper \
  -igenomeindex_targz="project-BQpp3Y804Y0xbyG4GJPQ01xv:\
file-BFBy4G805pXZKqV1ZVGQ0FG8" \
  --batch-tsv dx_batch.0000.tsv \
  --batch-folders
```

This command outputs the results for each sample in folders named after batch IDs, such as `/10B_S1/`, `/10T_S5/`, `/15B_S4/`, and `/15T_S8/`. If the folders do not exist, they are created.

The output folders are created under a path defined with `--destination`, which by default is set to the current project and the "/" folder. For example, this command outputs the result files in `/run_01/10B_S1/`, `/run_01/10T_S5/`, and other sample-specific folders:

```shell
dx run bwa_mem_fastq_read_mapper \
  -igenomeindex_targz="project-BQpp3Y804Y0xbyG4GJPQ01xv:\
file-BFBy4G805pXZKqV1ZVGQ0FG8" \
  --batch-tsv dx_batch.0000.tsv \
  --batch-folders \
  --destination=My_project:/run_01
```

## Batching Multiple Inputs

The `dx generate_batch_inputs` command works well for batch processing with file inputs, but it has limitations. If you need to vary other input types (like strings, numbers, or file arrays), or want to customize run properties like job names, a `for` loop provides more flexibility.

Here's an example of using a loop to launch multiple jobs with different inputs:

```shell
for i in 1 2; do
    dx run swiss-army-knife -icmd="wc *>${i}.out" -iin="fileinput_batch${i}a" -iin="file_input_batch${i}b" --name "sak_batch${i}"
done
```

You can also use the `dx run` command to use `stage_id` . For example, if you create a workflow called "Trio Exome Workflow - Jan 1st 2020 9:00am" in your project, you can run it from the command line:

```shell
dx login
dx run "Trio Exome Workflow - Jan 1st 2020 9\:00am"
```

The `\` character is needed to escape the `:` in the workflow name.

Inputs to the workflow can be specified using `dx run <workflow> --input name=stage_id:value`, where `stage_id` is a numeric ID starting at 0. More help can be found by running the commands `dx run --help` and `dx run <workflow> --help`.

To batch multiple inputs then, do the following:

```shell
dx cd /path/to/inputs
for i in $(dx ls); do
    dx run "Trio Exome Workflow - Jan 1st 2020 9\:00am" --input 0.reads="$i"
done
```

## Additional Resources

For additional information and examples of how to run batch jobs, [Batch Processing on the Cloud](https://laderast.github.io/bash_for_dnanexus/05-batch-processing.html) may be useful. This material is not a part of the official DNAnexus documentation and is for reference only.
