Skip to main content

Nextflow

The volume of the unit ball as a Nextflow pipeline: processes and channels, the plan as channel operators, flatMap then groupTuple with groupKey, an environment for each process and how to pin it, a preview of the graph, what -resume reuses and why a copied directory runs everything again, and the records of a run.

The previous page wrote the pipeline of this section as a Snakefile. This page writes it in Nextflow, where each step is a process, and the data flows between processes through channels.

The pipeline

// The volume of the unit ball in d dimensions: for each d, a pilot batch, a
// plan that reads it, as many batches as the plan says, and a reduce; then the
// table, and its plot.
params {
    // The largest dimension.
    dmax: Integer = 12
}

process PILOT {
    conda "${moduleDir}/envs/count.yml"

    input:
    val d

    output:
    tuple val(d), path('pilot.txt')

    script:
    """
    ball.py count ${d} 0 > pilot.txt
    """
}

process PLAN {
    input:
    tuple val(d), path(pilot)

    output:
    tuple val(d), stdout

    script:
    """
    ball.py plan ${pilot}
    """
}

process COUNT {
    conda "${moduleDir}/envs/count.yml"

    input:
    tuple val(d), val(k)

    output:
    tuple val(d), path('count.txt')

    script:
    """
    ball.py count ${d} ${k} > count.txt
    """
}

process REDUCE {
    input:
    tuple val(d), path('count*.txt')

    output:
    path 'volume.txt'

    script:
    """
    ball.py reduce ${d} count*.txt > volume.txt
    """
}

process TABLE {
    input:
    path 'volume*.txt'

    output:
    path 'volumes.tsv'

    script:
    """
    ball.py table volume*.txt > volumes.tsv
    """
}

process PLOT {
    conda "${moduleDir}/envs/plot.yml"

    input:
    path table

    output:
    path 'volumes.svg'

    script:
    """
    ball.py plot ${table} volumes.svg
    """
}

workflow {
    main:
    dims = channel.of(2..params.dmax)
    plans = PLAN(PILOT(dims))
    // One item per batch, each with a key that says how many batches its d has.
    batches = plans.flatMap { d, n ->
        def size = n.trim().toInteger()
        (1..size).collect { k -> tuple(groupKey(d, size), k) }
    }
    // Each d's batches, grouped as soon as the last of them is counted.
    volumes = REDUCE(COUNT(batches).groupTuple())
    table = TABLE(volumes.collect())
    plot = PLOT(table)

    publish:
    table = table
    plot = plot
}

output {
    table {
        path '.'
    }
    plot {
        path '.'
    }
}

The params block declares the pipeline’s one parameter, the largest d, an Integer, 12 unless the command line says otherwise, e.g. with --dmax 13. Each process is a step: its input: says what it takes from each item of its channel, its output: what it emits on its own channel, and its script: is the command, which runs in a directory of its own under work/. A val is a value, a path is a file, which Nextflow links into the task’s directory under the name given, and stdout is what the script prints. A tuple keeps several together, so that the file of each batch travels with its d. ball.py is on the PATH of every task because it is in the pipeline’s bin directory, which Nextflow adds to it, and bin/ball.py is a link to the ball.py of the intro. A conda line names the environment of its process, relative to the pipeline’s directory, moduleDir.

The workflow block connects them. channel.of(2..params.dmax) emits each d, and calling a process on a channel runs a task for each of its items, and returns the channel of their outputs, so PLAN(PILOT(dims)) runs a pilot and then a plan for each d, and emits a d with its number of batches, as soon as each plan is done.

The plan needs nothing more than two channel operators. flatMap turns each d and its number of batches, n, into n items, one for each batch to count. Each carries groupKey(d, size) rather than d alone: a key that also says how many items share it. groupTuple collects the counted batches of each d into one item, for its reduce, and with a plain key it would wait until every input has arrived, all 79 batches of all 11 dimensions, before it emitted any group. With the size in the key, it emits each d’s group as soon as its last batch is counted. collect then gathers every row into one list, for the table. The publish: section and the output block make the table and the plot the pipeline’s outputs, which Nextflow copies into results/.

The configuration turns on the conda lines, and has every task use one CPU:

// Create the environment each process names with its conda directive.
conda.enabled = true

// Each task uses one CPU, so as many run at a time as the job has CPUs.
process.cpus = 1

// Copy the published files, rather than link to them in the work directory.
workflow.output.mode = 'copy'

Without the last line, the outputs in results/ are links into work/, and are gone when it is cleaned.

Running it

The environment has Nextflow, which brings its own Java, and Python for the steps that need only the standard library:

name: ball-nextflow
channels:
  - conda-forge
  - bioconda
dependencies:
  # for the steps that need only the standard library
  - python=3.13
  - nextflow

The job runs the whole pipeline inside one allocation, with the default executor, local, which runs each task as a process on the node Nextflow runs on, as many at a time as there are CPUs it may use, here the job’s 8:

#!/bin/bash
#SBATCH --job-name=ball-nextflow
#SBATCH --nodes=1
#SBATCH --ntasks=1
#SBATCH --cpus-per-task=8
#SBATCH --time=00:10:00
set -eo pipefail

source "$(conda info --base)/etc/profile.d/conda.sh"
conda activate "${CONDA_ENV:-ball-nextflow}"
# Every task is a process with one thread, so as many tasks as CPUs at a time.
source ../pi/num-threads.sh 1

# The whole workflow inside this job, with the local executor: each task a
# process on this node, as many at a time as the job has CPUs.
nextflow run main.nf -ansi-log false
cat results/volumes.tsv

-ansi-log false prints a line for each task, rather than a summary redrawn in place, which suits a job’s output file. Nextflow creates the two environments the first time a task needs them, under work/conda/, and the job ends with

  table: volumes.tsv

  plot: volumes.svg

[SUCCESS] completed=114 failed=0 cached=0

and the table of the intro.

A preview of the graph

nextflow run main.nf -preview -with-dag dag.html runs none of the tasks, and draws the graph of the pipeline, its processes from PILOT to PLOT and the channels and operators between them. It cannot draw the tasks, 114 of them in this run, since how many batches each d has is known only once its pilot has run.

An environment for each process

A conda line can name a list of packages, an environment file, or a lockfile, in the format of conda list --explicit, and Nextflow creates the environment from it the first time a task needs it. The environment file is a recipe, a list of names, so which packages it gives depends on when it is created, as Freezing an environment explains. To pin it, point the conda line at a lockfile instead:

conda "${moduleDir}/envs/count.linux-64.txt"

made from the environment with conda list --explicit --md5. A lockfile is for one platform, so on a cluster with nodes of another, the conda lines for each belong in a profile of the configuration. Nextflow keeps the environments in work/, unless conda.cacheDir says otherwise, and on a cluster that has to be a filesystem every node sees, as in the questions specific to a cluster.

A process can run in a container instead, with container and apptainer.enabled = true in the configuration, and the image is pinned by its digest, python@sha256:.... Or it can load modules, with module, which pins nothing, so record them.

Resuming

With -resume, the same job runs nothing,

[SUCCESS] completed=0 failed=0 cached=114

and with -resume --dmax 13, it runs d = 13’s pilot, plan, 134 batches and reduce, and the table and the plot again:

[SUCCESS] completed=139 failed=0 cached=112

Each task is identified by a hash of the run’s session, the name of its process, its script, its inputs, its environment, and the scripts from bin it uses, and -resume reuses each task whose hash is in the cache of the last run. An input file goes into the hash by its full path, size and modification time, and so does each script from bin.

So a change to ball.py reruns every task, since every task runs it from bin. A copy of the pipeline’s directory reruns every task too, since every path in it is a different one, the path of bin/ball.py among them, so resume a run where it ran, and copy its results afterwards.

On a shared filesystem that reports inconsistent modification times, the hash of a file can change when the file has not, and tasks rerun for no reason. cache 'lenient' in a process, or process.cache = 'lenient' in the configuration, leaves the time out of the hash, and cache 'deep' hashes the contents of each file instead, which reads every byte.

The records of a run

Each task’s directory under work/ keeps what it ran: .command.sh is the script, .command.run the wrapper that activated its environment and ran it, .command.out, .command.err and .command.log its output, and .exitcode its exit status. nextflow log lists the runs in the directory, and nextflow log <run name> -f name,hash,status,exit,workdir lists each task of one run, with the fields you ask for. For a report of a run, add -with-report report.html, an HTML page with every task’s status, script and use of CPU and memory, -with-trace, a table of every task, in trace.txt, or -with-timeline timeline.html.

On Slurm

To make each task a Slurm job of its own, set process.executor = 'slurm', and its throttles, as on the page on workflow managers, which also covers where to run Nextflow itself, and the file locking its cache in .nextflow needs. On nodes of the same kind, the table is the same either way, since each batch is seeded by its (d, k). Across kinds of node, it is the same within a tolerance, as the page on the machine explains.

Limitations

The cache is tied to paths, so a run can be resumed only where it ran. groupTuple has to know how big each group is, from groupKey, to emit it early, and without the size, the reduce of every d waits for the last batch of all. And there is no dry run of the tasks, only a preview of the processes.

The next page writes the same pipeline in Parsl.