Skip to content

Part 3: Hello Workflow

See the whole playlist on the Nextflow YouTube channel.

📗 The video transcript is available here.

Most real-world workflows involve more than one step. In this training module, you'll learn how to connect processes together in a multi-step workflow.

This will teach you the Nextflow way of achieving the following:

  1. Making data flow from one process to the next
  2. Running a process written in another language
  3. Passing more than one input to a process
  4. Collecting outputs from multiple process calls into a single process call
  5. Handling multiple outputs coming out of a process

To demonstrate, we will continue building on the Hello World example from Parts 1 and 2, and make the following changes to our workflow:

  1. Add a translation step, written in Python, that translates each greeting into another language.
  2. Add a collection step that gathers all the translated greetings into a single file named after the batch and the language.
  3. Add a report output to the collection step, with a simple statistic about what was processed.

Here is where this part fits in the course:

names.csv sayHello translateGreeting collectGreetings cowpy cowpy-batch-es- greetings.txt greet one name Part 1: Hello World read names.csv, in parallel Part 2: Hello Channels translate, then collect Part 3: Hello Workflow ← you are here cowpy in a container Part 4: Hello Containers
How to begin from this section

This section of the course assumes you have completed Parts 1-2 of the Hello Nextflow course, but if you are comfortable with the basics covered in those sections, you can start from here without doing anything special.


0. Warmup: Run hello-workflow.nf

We're going to use the workflow script hello-workflow.nf as a starting point. It is equivalent to the script produced by working through Part 2 of this training course, except we've removed the view() statements.

This diagram summarizes the current operation of the workflow. It should look familiar, except now we're explicitly showing that the outputs of the process are packaged in a channel, just like the inputs were. We're going to put that output channel to good use in a minute.

names.csv Mateo,es,squirrel Raphael,it,turtle Celine,fr,moose Mateo.txt Hello, Mateo! Raphael.txt Hello, Raphael! Celine.txt Hello, Celine! published outputs channel.fromPath() .splitCsv() .map { row -> row[0] } input channel process calls output channel Celine Raphael Mateo sayHello('Mateo') sayHello('Raphael') sayHello('Celine') Raphael.txt Celine.txt Mateo.txt

Just to make sure everything is working, run the script once before making any changes:

nextflow run hello-workflow.nf
Command output
 N E X T F L O W   ~  version 26.10.7

Launching `hello-workflow.nf` [hungry_curran] revision: 451e6bb952

executor >  local (3)
[3b/b013b6] sayHello (Raphael) | 3 of 3 ✔

Outputs:

  /workspaces/training/hello-nextflow/results

  greetings:
    - hello/Mateo.txt
    - hello/Celine.txt
    - hello/Raphael.txt

As previously, you will find the output files in the results/hello directory, alongside the outputs of the previous parts.

Directory contents
results
├── hello
│   ├── Celine.txt
│   ├── Mateo.txt
│   ├── output.txt
│   └── Raphael.txt
└── output.txt -> /workspaces/training/hello-nextflow/work/.../output.txt

If that worked for you, you're ready to learn how to assemble a multi-step workflow.


1. Add a translation step

We're going to add a step that translates each greeting into another language, for example from Hello, Mateo! to Hola, Mateo!. This step is a small Python script, which shows that a process can run code in other languages than the shell.

names.csv Mateo,es,squirrel Raphael,it,turtle Celine,fr,moose es-Mateo.txt Hola, Mateo! es-Raphael.txt Hola, Raphael! es-Celine.txt Hola, Celine! published outputs sayHello *.txt translateGreeting es-*

We'll build it in three steps:

  1. Write a process that translates into Spanish.
  2. Connect the process to the output of sayHello, and publish its outputs.
  3. Make the language an input of the process, set by a parameter.

From here on, diagrams show channels explicitly only where the text is about how steps are connected. Elsewhere, a file box such as *.txt stands for the channel of files that one step passes to the next.

1.1. Write the translation process

The translation is a simple text replacement: read the greeting, replace Hello with the word for hello in the target language, and write the result to a new file. We start with a version that always translates into Spanish. We won't add the language parameter yet; that comes in section 1.3.

The process will take each greeting file and produce a translated file:

Mateo.txt Hello, Mateo! translateGreeting es-Mateo.txt Hola, Mateo!

Add the following process definition to the workflow script, right under the sayHello process:

hello-workflow.nf
/*
 * Use Python to translate the greeting into Spanish
 */
process translateGreeting {

    tag "${input_file}"

    input:
    path input_file

    output:
    path "es-${input_file}"

    script:
    """
    #!/usr/bin/env python3

    with open('${input_file}') as greeting_file:
        greeting = greeting_file.read()

    with open('es-${input_file}', 'w') as translated_file:
        translated_file.write(greeting.replace('Hello', 'Hola'))
    """
}

The process definition is very similar to what we used for sayHello, with two differences.

First, the input is a file, so it uses the path qualifier, and we compose the output filename from the input filename, similarly to what we did for the output of the first process. We use the file name in the tag directive (introduced in Part 2) to label each task with the name of the file it translates.

Second, the script is written in Python. The first line of the script, #!/usr/bin/env python3, is called a shebang: it tells the system which program should run the script, instead of using the default setting (bash) as it did for sayHello.

The ${input_file} placeholders work the same way as in a shell script: Nextflow replaces them with the actual file name before running the script. Python never sees the placeholders, only the values.

Working with scripts

Which languages can I use? Any scripting language, such as Python, R or Perl, as long as it's available in the environment. Here Python is installed on our local machine; Part 5 covers how to supply software that isn't installed locally.

How long can my script be? There's no hard limit. Inline code is convenient for a few lines, but longer scripts are easier to maintain and test as separate files. For those, save the script in a directory named bin/ next to your workflow script, make it executable, and call it by name in the script block. Nextflow adds the bin/ directory to the PATH of every task automatically.

1.2. Connect the translation step to the workflow

Next, connect the new process to the output of sayHello, publish its outputs, and run the workflow.

1.2.1. Connect the process calls

Now we need to call the new process in the workflow block, and make the output of the sayHello() process flow into it.

Conveniently, Nextflow automatically packages the output of a process into a channel, as shown in the diagram in the warmup section. The workflow already assigns the output channel of sayHello() to greetings_ch, so we can plug greetings_ch straight into the call to translateGreeting(). The call to translateGreeting() returns a channel in turn, which we assign to translated_ch.

names.csv Mateo,es,squirrel Raphael,it,turtle Celine,fr,moose sayHello greetings_ch translateGreeting translated_ch Raphael.txt Celine.txt Mateo.txt es-Raphael.txt es-Celine.txt es-Mateo.txt

In the workflow block, make the following code change:

hello-workflow.nf
workflow {

    main:
    // create a channel for inputs from a CSV file
    name_ch = channel.fromPath(params.input)
                        .splitCsv()
                        .map { row -> row[0] }
    // emit a greeting
    greetings_ch = sayHello(name_ch)
    // translate the greeting
    translated_ch = translateGreeting(greetings_ch)

    publish:
    greetings = greetings_ch
}
hello-workflow.nf
workflow {

    main:
    // create a channel for inputs from a CSV file
    name_ch = channel.fromPath(params.input)
                        .splitCsv()
                        .map { row -> row[0] }
    // emit a greeting
    greetings_ch = sayHello(name_ch)

    publish:
    greetings = greetings_ch
}

For a simple case like this (one output to one input), that's all we need to do to connect two processes!

1.2.2. Publish the outputs

Finally, update the workflow outputs to publish the results from the second process too.

In the publish: section of the workflow block, make the following code change:

hello-workflow.nf
    publish:
    greetings = greetings_ch
    translated = translated_ch
}
hello-workflow.nf
    publish:
    greetings = greetings_ch
}

Then, in the output block, make the following code change:

hello-workflow.nf
output {
    greetings {
        path 'hello'
        mode 'copy'
    }
    translated {
        path 'hello'
        mode 'copy'
    }
}
hello-workflow.nf
output {
    greetings {
        path 'hello'
        mode 'copy'
    }
}

Each output has its own entry, so you can set a different path for each one. For now they all go to the same hello subdirectory; in section 2.4, you'll organize them by batch.

1.2.3. Run the workflow

Run the workflow with the -resume flag, which reuses the results of steps that already ran successfully (Part 1 of Nextflow Run covers it in detail):

nextflow run hello-workflow.nf -resume
Command output
 N E X T F L O W   ~  version 26.10.7

Launching `hello-workflow.nf` [fabulous_jepsen] revision: 6666356a1f

executor >  local (3)
[ca/b33d6f] sayHello (Celine)              | 3 of 3, cached: 3 ✔
[a2/ba648d] translateGreeting (Celine.txt) | 3 of 3 ✔

Outputs:

  /workspaces/training/hello-nextflow/results

  greetings:
    - hello/Raphael.txt
    - hello/Mateo.txt
    - hello/Celine.txt

  translated:
    - hello/es-Raphael.txt
    - hello/es-Mateo.txt
    - hello/es-Celine.txt

There is now an extra line in the console output that corresponds to the new process we just added, and the sayHello tasks were retrieved from the cache.

You'll find the translated greetings in the results/hello directory, as set in the output block.

File contents
results/hello/es-Mateo.txt
Hola, Mateo!

It's also worth taking a look inside the work directory of one of the calls to the second process.

Directory contents
work/04/ed1af8616b521098c5d7755d1d18bd/
├── Mateo.txt -> /workspaces/training/hello-nextflow/work/c8/1d9afcca03e41f83ffb571fca25f01/Mateo.txt
└── es-Mateo.txt

Notice there are two output files: the output of the first process as well as the output of the second.

The output of the first process is in there because Nextflow staged it there in order to have everything needed for execution within the same subdirectory. It is a symbolic link pointing to the original file in the subdirectory of the first process call. By default, when running on a single machine as we're doing here, Nextflow uses symbolic links rather than copies to stage input and intermediate files.

The .command.sh file in the same directory shows the Python script that Nextflow ran, with the file names filled in:

work/04/ed1af8616b521098c5d7755d1d18bd/.command.sh
#!/usr/bin/env python3

with open('Mateo.txt') as greeting_file:
    greeting = greeting_file.read()

with open('es-Mateo.txt', 'w') as translated_file:
    translated_file.write(greeting.replace('Hello', 'Hola'))

All we did was connect the output of sayHello to the input of translateGreeting, and Nextflow handled the individual files and passed them between the two steps for us. This is one of the reasons Nextflow channels are so powerful: they take care of the busywork involved in connecting workflow steps together.

1.3. Add a language input

Our translation step always translates into Spanish. To make it translate into other languages, we'll give the process a second input, language, set by a pipeline parameter:

Mateo.txt Hello, Mateo! translateGreeting language fr fr-Mateo.txt Bonjour, Mateo!

1.3.1. Add the language input and a dictionary of translations

Good news: we can declare as many inputs as we want in the process definition.

In the translateGreeting process definition, make the following code changes:

hello-workflow.nf
/*
 * Use Python to translate the greeting into another language
 */
process translateGreeting {

    tag "${language}-${input_file}"

    input:
    path input_file
    val language

    output:
    path "${language}-${input_file}"

    script:
    """
    #!/usr/bin/env python3
    import sys

    translations = {
        'es': 'Hola',        # Spanish
        'fr': 'Bonjour',     # French
        'it': 'Ciao',        # Italian
        'nl': 'Hallo',       # Dutch
        'ar': 'Marhaban',    # Arabic
        'ja': 'Konnichiwa',  # Japanese
        'en': 'Hello',       # English
    }

    if '${language}' not in translations:
        sys.exit('Unsupported language code: ${language}')

    with open('${input_file}') as greeting_file:
        greeting = greeting_file.read()

    with open('${language}-${input_file}', 'w') as translated_file:
        translated_file.write(greeting.replace('Hello', translations['${language}']))
    """
}
hello-workflow.nf
/*
 * Use Python to translate the greeting into Spanish
 */
process translateGreeting {

    tag "${input_file}"

    input:
    path input_file

    output:
    path "es-${input_file}"

    script:
    """
    #!/usr/bin/env python3

    with open('${input_file}') as greeting_file:
        greeting = greeting_file.read()

    with open('es-${input_file}', 'w') as translated_file:
        translated_file.write(greeting.replace('Hello', 'Hola'))
    """
}

The new input, language, is a plain value, so it uses the val qualifier, like the input of sayHello.

The script now looks up the word for hello in a Python dictionary called translations, using the language as the key. The keys are two-letter language codes, such as es for Spanish and ja for Japanese. Nextflow fills in ${language} before Python runs, so for Spanish, Python sees translations['es']. If the code is not in the dictionary, the script exits with an error message (sys.exit) instead of a Python traceback.

The output file name also starts with the language code, so the outputs of different languages don't overwrite each other. The tag now includes the language code too, matching the output file name; the language alone would give all the tasks of a run the same tag.

1.3.2. Add a language parameter

You already know how to use the params system to declare CLI parameters. Declare a language parameter, with Spanish (es) as the default value.

In the pipeline parameters section, make the following code change:

hello-workflow.nf
/*
 * Pipeline parameters
 */
params {
    input: Path = 'data/names.csv'
    language: String = 'es'
}
hello-workflow.nf
/*
 * Pipeline parameters
 */
params {
    input: Path = 'data/names.csv'
}

1.3.3. Pass the language to the process

To provide the value of the parameter to the process, add it to the process call.

In the workflow block, make the following code change:

hello-workflow.nf
    // translate the greeting
    translated_ch = translateGreeting(greetings_ch, params.language)
hello-workflow.nf
    // translate the greeting
    translated_ch = translateGreeting(greetings_ch)

To provide multiple inputs to a process, you simply list them in the call parentheses, separated by commas.

Warning

You MUST provide the inputs to the process in the EXACT SAME ORDER as they are listed in the input definition block of the process.

Notice that the two inputs are different kinds of things. greetings_ch is a channel that carries three files, one per greeting, while params.language is a single value. Nextflow calls the process once per file in the channel, and reuses the single value for every call. So each of the three greetings gets translated into the same language.

The workflow now looks like this:

names.csv Mateo,es,squirrel Raphael,it,turtle Celine,fr,moose --language fr fr-Mateo.txt Bonjour, Mateo! fr-Raphael.txt Bonjour, Raphael! fr-Celine.txt Bonjour, Celine! published outputs sayHello *.txt translateGreeting fr-*

1.3.4. Run the workflow in another language

Run the workflow with -resume, this time setting the language to French:

nextflow run hello-workflow.nf -resume --language fr
Command output
 N E X T F L O W   ~  version 26.10.7

Launching `hello-workflow.nf` [lonely_davinci] revision: 51cc879712

executor >  local (3)
[c8/1d9afc] sayHello (Mateo)                  | 3 of 3, cached: 3 ✔
[f9/3d09b5] translateGreeting (fr-Celine.txt) | 3 of 3 ✔

Outputs:

  /workspaces/training/hello-nextflow/results

  greetings:
    - hello/Raphael.txt
    - hello/Mateo.txt
    - hello/Celine.txt

  translated:
    - hello/fr-Raphael.txt
    - hello/fr-Mateo.txt
    - hello/fr-Celine.txt

The sayHello tasks were cached, and the translateGreeting tasks ran again, both because we changed the code of the process and because its language input is now fr.

File contents
results/hello/fr-Mateo.txt
Bonjour, Mateo!

Without --language, the workflow uses the default, Spanish.

Finally, try a language code that is not in the dictionary, such as de for German:

nextflow run hello-workflow.nf -resume --language de
Command output
 N E X T F L O W   ~  version 26.10.7

Launching `hello-workflow.nf` [spontaneous_bell] revision: 51cc879712

executor >  local (3)
[ca/b33d6f] sayHello (Celine)                 | 3 of 3, cached: 3 ✔
[0c/deee58] translateGreeting (de-Celine.txt) | 0 of 3 ✘
ERROR ~ Error executing process > 'translateGreeting (de-Raphael.txt)'

Caused by:
  Process `translateGreeting (de-Raphael.txt)` terminated with an error exit status (1)


Command executed:

  #!/usr/bin/env python3
  import sys

  translations = {
      'es': 'Hola',        # Spanish
      'fr': 'Bonjour',     # French
      'it': 'Ciao',        # Italian
      'nl': 'Hallo',       # Dutch
      'ar': 'Marhaban',    # Arabic
      'ja': 'Konnichiwa',  # Japanese
      'en': 'Hello',       # English
  }

  if 'de' not in translations:
      sys.exit('Unsupported language code: de')

  with open('Raphael.txt') as greeting_file:
      greeting = greeting_file.read()

  with open('de-Raphael.txt', 'w') as translated_file:
      translated_file.write(greeting.replace('Hello', translations['de']))

Command exit status:
  1

Command output:
  (empty)

Command error:
  Unsupported language code: de

Work dir:
  /workspaces/training/hello-nextflow/work/52/aa8f161d4a07b46eabb90f20c3a8b2

Tip: you can try to figure out what's wrong by changing to the process work dir and showing the script file named `.command.sh`

 -- Check '.nextflow.log' file for details

The run fails, and the error report shows the script as Nextflow ran it, with de filled in. The message from sys.exit appears under Command error:, since it was written to standard error. Nextflow also saves it in the .command.err file of the task directory listed under Work dir:.

Takeaway

You know how to chain processes together by providing the output of one step as input to the next step, how to write the script of a process in another language, and how to pass more than one input to a process.

What's next?

Learn how to collect outputs from batched process calls and feed them into a single process.


2. Add a collection step

When we use a process to apply a transformation to each of the elements in a channel, like we're doing here to the multiple greetings, we sometimes want to collect elements from the output channel of that process, and feed them into another process that performs some kind of analysis or summation.

To demonstrate, we'll add a new step to our pipeline that collects all the translated greetings produced by the translateGreeting process and writes them out to a single file. We'll also name that file after a batch name provided as a parameter and after the language, so that the results of different batches of inputs, and of different languages, don't overwrite each other.

collectGreetings batch-fr-greetings.txt names.csv Bonjour, Mateo! Bonjour, Raphael! Bonjour, Celine! Mateo,es,squirrel Raphael,it,turtle Celine,fr,moose --batch batch --language fr sayHello *.txt translateGreeting fr-*

Not to spoil the surprise, but this is going to involve a very useful operator.

2.1. Write the collection process

The collection uses the cat command to concatenate the translated greetings into a single file. The process will take all the translated files, plus a batch name and a language, and write the greetings into that file:

Bonjour, Raphael! Bonjour, Celine! Bonjour, Mateo! collectGreetings batch_name language trio-fr-greetings.txt Bonjour, Mateo! Bonjour, Raphael! Bonjour, Celine! fr-Raphael.txt fr-Celine.txt fr-Mateo.txt

Add the following process definition to the workflow script, right under the translateGreeting process:

hello-workflow.nf
/*
 * Collect translated greetings into a single output file
 */
process collectGreetings {

    tag "${batch_name}"

    input:
    path input_files
    val batch_name
    val language

    output:
    path "${batch_name}-${language}-greetings.txt"

    script:
    """
    cat ${input_files} > '${batch_name}-${language}-greetings.txt'
    """
}

This process has three inputs:

  • input_files will hold the files to collect. It uses the path qualifier even though we expect it to contain multiple files.
  • batch_name is the name of the batch, which we use in the output file name, so that each batch gets its own output file.
  • language is the language of the greetings, which we also use in the output file name. A batch names a group of samples, which you may translate into several languages; including the language in the file name keeps the results of different languages apart.

batch_name and language are plain values, so they use the val qualifier, like the language input of translateGreeting in section 1.3. The process runs only once per run, but tagging it with the batch name makes runs of different batches easy to tell apart.

The script needs to handle an arbitrary number of input files, so we can't write the command up front. In other words, if input_files contains [file1.txt, file2.txt, file3.txt], we need Nextflow to turn that into cat file1.txt file2.txt file3.txt.

Fortunately, Nextflow is quite happy to do that for us if we simply write cat ${input_files} in the script command.

Tip

Some command-line tools require providing an argument (like -input) for each input file. In that case, we would have to do a little bit of extra work to compose the command. You can see an example of this in the Nextflow for Genomics training course.

2.2. Connect the collection step to the workflow

Now we need a batch parameter, and a call to the collection process on the output of the translation step. That output is also a channel, translated_ch.

names.csv Mateo,es,squirrel Raphael,it,turtle Celine,fr,moose sayHello greetings_ch translateGreeting translated_ch Raphael.txt Celine.txt Mateo.txt fr-Raphael.txt fr-Celine.txt fr-Mateo.txt

2.2.1. Add a batch parameter

Declare a batch parameter, with a default value, in the pipeline parameters section:

hello-workflow.nf
/*
 * Pipeline parameters
 */
params {
    input: Path = 'data/names.csv'
    language: String = 'es'
    batch: String = 'batch'
}
hello-workflow.nf
/*
 * Pipeline parameters
 */
params {
    input: Path = 'data/names.csv'
    language: String = 'es'
}

2.2.2. Connect the process calls

In the workflow block, make the following code change:

hello-workflow.nf
    // translate the greeting
    translated_ch = translateGreeting(greetings_ch, params.language)
    // collect all the greetings into one file
    collected_ch = collectGreetings(translated_ch, params.batch, params.language)
hello-workflow.nf
    // translate the greeting
    translated_ch = translateGreeting(greetings_ch, params.language)

This connects the output of translateGreeting() to the first input of collectGreetings(), and passes the batch name and the language as the second and third inputs. The language comes from the same params.language parameter as for translateGreeting(), so the collected file is named after the language the greetings were translated into.

2.2.3. Publish the outputs

In the publish: section of the workflow block, make the following code change:

hello-workflow.nf
    publish:
    greetings = greetings_ch
    translated = translated_ch
    collected = collected_ch
}
hello-workflow.nf
    publish:
    greetings = greetings_ch
    translated = translated_ch
}

Then, in the output block, make the following code change:

hello-workflow.nf
output {
    greetings {
        path 'hello'
        mode 'copy'
    }
    translated {
        path 'hello'
        mode 'copy'
    }
    collected {
        path 'hello'
        mode 'copy'
    }
}
hello-workflow.nf
output {
    greetings {
        path 'hello'
        mode 'copy'
    }
    translated {
        path 'hello'
        mode 'copy'
    }
}

2.2.4. Run the workflow

Let's try it.

nextflow run hello-workflow.nf -resume --language fr
Command output
 N E X T F L O W   ~  version 26.10.7

Launching `hello-workflow.nf` [kickass_sanger] revision: 8d4f16d465

executor >  local (3)
[c8/1d9afc] sayHello (Mateo)                   | 3 of 3, cached: 3 ✔
[3a/f97a23] translateGreeting (fr-Raphael.txt) | 3 of 3, cached: 3 ✔
[d9/0afd55] collectGreetings (batch)           | 3 of 3 ✔

Outputs:

  /workspaces/training/hello-nextflow/results

  greetings:
    - hello/Celine.txt
    - hello/Raphael.txt
    - hello/Mateo.txt

  translated:
    - hello/fr-Celine.txt
    - hello/fr-Raphael.txt
    - hello/fr-Mateo.txt

  collected:
    - hello/batch-fr-greetings.txt
    - hello/batch-fr-greetings.txt
    - hello/batch-fr-greetings.txt

It runs successfully, including the third step.

However, look at the number of calls for collectGreetings() on the last line. We were only expecting one, but there are three.

Now have a look at the contents of the final output file.

File contents
results/hello/batch-fr-greetings.txt
Bonjour, Mateo!

Oh no. The collection step was run individually on each greeting, which is NOT what we wanted.

Without an operator translated_ch separate process calls collected_ch Bonjour, Mateo! Bonjour, Raphael! Bonjour, Celine! fr-Raphael.txt fr-Celine.txt fr-Mateo.txt collectGreetings collectGreetings collectGreetings batch-fr-greetings.txt batch-fr-greetings.txt batch-fr-greetings.txt

We need to do something to tell Nextflow explicitly that we want that third step to run on all the elements in the channel output by translateGreeting().

2.3. Collect the greetings into a single input

Yes, once again the answer to our problem is an operator.

Specifically, we are going to use the aptly-named collect() operator.

2.3.1. Add the collect() operator

This time it's going to look a bit different because we're not adding the operator in the context of a channel factory; we're adding it to an output channel.

We take translated_ch and append the collect() operator, which gives us translated_ch.collect(). We can plug that directly into the collectGreetings() process call.

In the workflow block, make the following code change:

hello-workflow.nf
    // collect all the greetings into one file
    collected_ch = collectGreetings(translated_ch.collect(), params.batch, params.language)
hello-workflow.nf
    // collect all the greetings into one file
    collected_ch = collectGreetings(translated_ch, params.batch, params.language)

2.3.2. Add some view() statements

Let's also include a couple of view() statements to visualize the before and after states of the channel contents.

hello-workflow.nf
    // collect all the greetings into one file
    collected_ch = collectGreetings(translated_ch.collect(), params.batch, params.language)

    // optional view statements
    translated_ch.view { filepath -> "Before collect: $filepath" }
    translated_ch.collect().view { filepaths -> "After collect: $filepaths" }
hello-workflow.nf
    // collect all the greetings into one file
    collected_ch = collectGreetings(translated_ch.collect(), params.batch, params.language)

The view() statements can go anywhere you want; we put them right after the call for readability. As in Part 2, the closure variables are named after what the channel contains: one file path per element before collect(), and a list of all the file paths after it.

2.3.3. Run the workflow

Let's try it:

nextflow run hello-workflow.nf -resume --language fr
Command output
 N E X T F L O W   ~  version 26.10.7

Launching `hello-workflow.nf` [loquacious_tuckerman] revision: 17c7a7ff85

executor >  local (1)
[c8/1d9afc] sayHello (Mateo)                  | 3 of 3, cached: 3 ✔
[54/9b3150] translateGreeting (fr-Celine.txt) | 3 of 3, cached: 3 ✔
[e2/56b5b1] collectGreetings (batch)          | 1 of 1 ✔
Before collect: /workspaces/training/hello-nextflow/work/a5/e7cd27b0e21c0f3f36831222d7de68/fr-Mateo.txt
Before collect: /workspaces/training/hello-nextflow/work/3a/f97a23653270f6a94ab11d07cf8b46/fr-Raphael.txt
Before collect: /workspaces/training/hello-nextflow/work/54/9b3150fc0eec1f7954d6da98da6300/fr-Celine.txt
After collect: [/workspaces/training/hello-nextflow/work/a5/e7cd27b0e21c0f3f36831222d7de68/fr-Mateo.txt, /workspaces/training/hello-nextflow/work/3a/f97a23653270f6a94ab11d07cf8b46/fr-Raphael.txt, /workspaces/training/hello-nextflow/work/54/9b3150fc0eec1f7954d6da98da6300/fr-Celine.txt]

Outputs:

  /workspaces/training/hello-nextflow/results

  greetings:
    - hello/Celine.txt
    - hello/Mateo.txt
    - hello/Raphael.txt

  translated:
    - hello/fr-Mateo.txt
    - hello/fr-Raphael.txt
    - hello/fr-Celine.txt

  collected: hello/batch-fr-greetings.txt

It runs successfully, although the log output may look a little messier than this (we cleaned it up for readability).

This time the third step was only called once! Looking at the output of the view() statements, we see the following:

  • Three Before collect: statements, one for each greeting: at that point the file paths are individual items in the channel.
  • A single After collect: statement: the three file paths are now packaged into a single element.

We can summarize that with the following diagram:

With the collect() operator translated_ch translated_ch.collect() .collect() collectGreetings single process call collected_ch Bonjour, Mateo! Bonjour, Raphael! Bonjour, Celine! fr-Raphael.txt fr-Celine.txt fr-Mateo.txt batch-fr-greetings.txt fr-Raphael.txt fr-Celine.txt fr-Mateo.txt

Finally, you can have a look at the contents of the output file to satisfy yourself that everything worked correctly.

File contents
results/hello/batch-fr-greetings.txt
Bonjour, Mateo!
Bonjour, Raphael!
Bonjour, Celine!

This time we have all three greetings in the final output file. Success!

Note

If you run this several times without -resume, you will see that the order of the greetings changes from one run to the next. This shows you that the order in which elements flow through process calls is not guaranteed to be consistent.

2.3.4. Remove view() statements for readability

Before you move on to the next section, we recommend you delete the view() statements to avoid cluttering the console output.

hello-workflow.nf
    // collect all the greetings into one file
    collected_ch = collectGreetings(translated_ch.collect(), params.batch, params.language)
hello-workflow.nf
    // collect all the greetings into one file
    collected_ch = collectGreetings(translated_ch.collect(), params.batch, params.language)

    // optional view statements
    translated_ch.view { filepath -> "Before collect: $filepath" }
    translated_ch.collect().view { filepaths -> "After collect: $filepaths" }

This is basically the reverse operation from point 2.4.2.

2.4. Organize the outputs by batch

The batch parameter is also a good way to keep the published results of different batches apart. Each output's path can include parameter values, so you can publish each batch to its own subdirectory, and group the intermediate files in a subdirectory of their own.

2.4.1. Update the output paths

In the output block, make the following code change:

hello-workflow.nf
output {
    greetings {
        path "${params.batch}/intermediates"
        mode 'copy'
    }
    translated {
        path "${params.batch}/intermediates"
        mode 'copy'
    }
    collected {
        path "${params.batch}/intermediates"
        mode 'copy'
    }
}
hello-workflow.nf
output {
    greetings {
        path 'hello'
        mode 'copy'
    }
    translated {
        path 'hello'
        mode 'copy'
    }
    collected {
        path 'hello'
        mode 'copy'
    }
}

The double quotes are required for Nextflow to insert the parameter value into the path, as in a process script.

This is how a pipeline author decides how the results are organized. The person running the pipeline can change the location of the output directory, as Part 2 of Nextflow Run shows, but not the organization within it, except through parameters like batch that the author builds into the paths.

The workflow now looks like this:

collectGreetings trio-fr-greetings.txt names.csv Bonjour, Mateo! Bonjour, Raphael! Bonjour, Celine! Mateo,es,squirrel Raphael,it,turtle Celine,fr,moose --batch trio --language fr sayHello *.txt translateGreeting fr-*

2.4.2. Run the workflow with a batch name

Run the workflow with a batch name on the command line:

nextflow run hello-workflow.nf -resume --language fr --batch trio
Command output
 N E X T F L O W   ~  version 26.10.7

Launching `hello-workflow.nf` [nostalgic_williams] revision: 71acf8e3a3

executor >  local (1)
[c8/1d9afc] sayHello (Mateo)                  | 3 of 3, cached: 3 ✔
[54/9b3150] translateGreeting (fr-Celine.txt) | 3 of 3, cached: 3 ✔
[f3/63fec2] collectGreetings (trio)           | 1 of 1 ✔

Outputs:

  /workspaces/training/hello-nextflow/results

  greetings:
    - trio/intermediates/Raphael.txt
    - trio/intermediates/Mateo.txt
    - trio/intermediates/Celine.txt

  translated:
    - trio/intermediates/fr-Mateo.txt
    - trio/intermediates/fr-Raphael.txt
    - trio/intermediates/fr-Celine.txt

  collected: trio/intermediates/trio-fr-greetings.txt

The collection step ran again, since its batch name input changed, and all the outputs of this batch are now under results/trio/. As long as you specify a different batch name, subsequent runs on other batches of inputs won't clobber previous results.

Takeaway

You know how to collect outputs from a batch of process calls and feed them into a joint analysis or summation step, and how to use a parameter to organize the published outputs.

What's next?

Learn how to emit multiple outputs and handle them conveniently.


3. Add a report output

So far we've been using processes that only produced one output each. We assigned the output of each call to a channel name, which we used both in the context of passing an output to the next process (e.g. translateGreeting(greetings_ch, params.language)) and in the context of the publish: section (e.g. greetings = greetings_ch).

What happens when a process produces more than one? How do we handle the multiple outputs? Can we select and use a specific output?

All excellent questions, and the short answer is yes we can!

Multiple outputs will be packaged into separate channels. We can either choose to give those output channels names, which makes it easy to refer to them individually later on, or we can refer to them by index.

For demonstration purposes, let's say we want to count the number of greetings that are being collected for a given batch of inputs and report it in a file.

3.1. Update the collection process

This will require two key changes to the process definition: we need a way to count the greetings and write a report file, then we need to add that report file to the output block of the process.

The process will produce the report as a second output:

Bonjour, Raphael! Bonjour, Celine! Bonjour, Mateo! collectGreetings batch_name language trio-fr-greetings.txt Bonjour, Mateo! Bonjour, Raphael! Bonjour, Celine! trio-fr-report.txt Number of greetings processed: 3 fr-Raphael.txt fr-Celine.txt fr-Mateo.txt

3.1.1. Count the number of greetings collected

Conveniently, Nextflow lets us add arbitrary code in the script: block of the process definition, which comes in really handy for doing things like this.

That means we can use Nextflow's built-in size() function to get the number of files in the input_files list, and write the result to file with an echo command.

In the collectGreetings process block, make the following code changes:

hello-workflow.nf
    script:
    count_greetings = input_files.size()
    """
    cat ${input_files} > '${batch_name}-${language}-greetings.txt'
    echo 'Number of greetings processed: ${count_greetings}' > '${batch_name}-${language}-report.txt'
    """
hello-workflow.nf
    script:
    """
    cat ${input_files} > '${batch_name}-${language}-greetings.txt'
    """

The count_greetings variable will be computed at runtime.

What if there is only one greeting?

If you run the workflow on a CSV file that contains a single name, the report claims a much larger number of greetings. With a single item in the channel, input_files holds one file instead of a list of files, and size() returns the size of that file in bytes.

To make Nextflow always provide a list, declare how many files the input accepts with the arity option:

input:
path input_files, arity: '1..*'

A value of '1..*' means one or more files.

3.1.2. Emit the report file and name outputs

In principle all we need to do is to add the report file to the output: block.

However, while we're at it, we're also going to add some emit: labels to our output declarations. These will enable us to select the outputs by name instead of having to use positional indices.

In the process block, make the following code change:

hello-workflow.nf
    output:
    path "${batch_name}-${language}-greetings.txt", emit: outfile
    path "${batch_name}-${language}-report.txt", emit: report
hello-workflow.nf
    output:
    path "${batch_name}-${language}-greetings.txt"

The emit: labels are optional, and we could have added a label to only one of the outputs. But as the saying goes, why not both?

Tip

If you don't name the outputs of a process using emit:, you can still access them individually by using their respective (zero-based) index. For example, with collected_out = collectGreetings(...), you would use collected_out[0] to get the first output, collected_out[1] to get the second output, and so on.

We prefer naming outputs because otherwise, it's too easy to grab the wrong index by error, especially when the process produces a lot of outputs.

3.2. Publish the report

Now that the collectGreetings process has two outputs, calling it returns two channels instead of one. You assign the result to a name as before, here collected_out, and read each channel by its emit: name:

  • collected_out.outfile contains the final output file
  • collected_out.report contains the report file

The _out suffix signals that collected_out holds several outputs rather than a single channel. Existing pipelines often write collectGreetings.out.outfile and collectGreetings.out.report instead, which refer to the same channels.

translated_ch.collect() collectGreetings --batch trio --language fr collected_out.outfile Bonjour, Mateo! Bonjour, Raphael! Bonjour, Celine! collected_out.report Number of greetings processed: 3 trio-fr-greetings.txt trio-fr-report.txt fr-Raphael.txt fr-Celine.txt fr-Mateo.txt

We need to update the workflow outputs accordingly.

3.2.1. Update the publish: section

In the workflow block, rename the result of the collectGreetings() call and publish both outputs:

hello-workflow.nf
    // collect all the greetings into one file
    collected_out = collectGreetings(translated_ch.collect(), params.batch, params.language)

    publish:
    greetings = greetings_ch
    translated = translated_ch
    collected = collected_out.outfile
    batch_report = collected_out.report
hello-workflow.nf
    // collect all the greetings into one file
    collected_ch = collectGreetings(translated_ch.collect(), params.batch, params.language)

    publish:
    greetings = greetings_ch
    translated = translated_ch
    collected = collected_ch

As you can see, referring to specific process outputs is now trivial. When we go to add one more step to our pipeline in Part 4 (Containers), we'll be able to easily refer to collected_out.outfile and hand it to the new process (spoiler: the new process is called cowpy).

But for now, let's finish updating the workflow-level outputs.

3.2.2. Update the output block

In the output block, make the following code change:

hello-workflow.nf
output {
    greetings {
        path "${params.batch}/intermediates"
        mode 'copy'
    }
    translated {
        path "${params.batch}/intermediates"
        mode 'copy'
    }
    collected {
        path "${params.batch}/intermediates"
        mode 'copy'
    }
    batch_report {
        path "${params.batch}"
        mode 'copy'
    }
}
hello-workflow.nf
output {
    greetings {
        path "${params.batch}/intermediates"
        mode 'copy'
    }
    translated {
        path "${params.batch}/intermediates"
        mode 'copy'
    }
    collected {
        path "${params.batch}/intermediates"
        mode 'copy'
    }
}

We don't need to update the collected output definition since that name hasn't changed. We just need to add the new output, which we publish at the top level of the batch directory, since it is a final result rather than an intermediate file.

3.3. Run the workflow

Run the workflow with the same batch name as before:

nextflow run hello-workflow.nf -resume --language fr --batch trio
Command output
 N E X T F L O W   ~  version 26.10.7

Launching `hello-workflow.nf` [stoic_bell] revision: 894719601e

executor >  local (1)
[c8/1d9afc] sayHello (Mateo)                   | 3 of 3, cached: 3 ✔
[3a/f97a23] translateGreeting (fr-Raphael.txt) | 3 of 3, cached: 3 ✔
[50/966f92] collectGreetings (trio)            | 1 of 1 ✔

Outputs:

  /workspaces/training/hello-nextflow/results

  greetings:
    - trio/intermediates/Raphael.txt
    - trio/intermediates/Mateo.txt
    - trio/intermediates/Celine.txt

  translated:
    - trio/intermediates/fr-Mateo.txt
    - trio/intermediates/fr-Celine.txt
    - trio/intermediates/fr-Raphael.txt

  collected: trio/intermediates/trio-fr-greetings.txt

  batch_report: trio/trio-fr-report.txt

If you look in the results/trio/ directory, you'll find the new report file, trio-fr-report.txt. Open it to verify that the workflow correctly reported the count of greetings that were processed.

File contents
trio-fr-report.txt
Number of greetings processed: 3
collectGreetings trio-fr-greetings.txt names.csv trio-fr-report.txt Bonjour, Mateo! Bonjour, Raphael! Bonjour, Celine! Mateo,es,squirrel Raphael,it,turtle Celine,fr,moose --batch trio Number of greetings processed: 3 --language fr sayHello *.txt translateGreeting fr-*

Feel free to try the workflow on more names, for example with the data/names-extended.csv file, which adds two names to the original three. Use -resume, and see which tasks Nextflow runs again.

Takeaway

You know how to make a process emit multiple named outputs and how to handle them appropriately at the workflow level.

More generally, you understand the key principles involved in connecting processes together in common ways.

What's next?

Take an extra long break, you've earned it.

When you're ready, move on to Part 4: Hello Containers to learn how to use containers to manage software dependencies more conveniently and reproducibly.


Bonus exercises

These optional exercises let you practice what you learned in this part. Each one can be solved with what this part covered; open the hint if you get stuck. The solutions are also in solutions/3-hello-workflow/bonus/.

Exercise 1: Put the translations in their own folder

Starting from hello-workflow.nf as it stands at the end of this part, change where the translated greetings are published, so that they go to a translations subdirectory of the batch directory instead of intermediates. Run the workflow with --batch trio -resume and check results/trio/.

Hint

Where each output is published is set in the output block, not in the processes.

Solution

Change the path of the translated output:

hello-workflow.nf
    translated {
        path "${params.batch}/translations"
        mode 'copy'
    }
hello-workflow.nf
    translated {
        path "${params.batch}/intermediates"
        mode 'copy'
    }

Run the workflow:

nextflow run hello-workflow.nf --language fr --batch trio -resume
Output (excerpt)
[c8/1d9afc] sayHello (Mateo)                   | 3 of 3, cached: 3 ✔
[3a/f97a23] translateGreeting (fr-Raphael.txt) | 3 of 3, cached: 3 ✔
[50/966f92] collectGreetings (trio)            | 1 of 1, cached: 1 ✔

Outputs:

  /workspaces/training/hello-nextflow/results

  greetings:
    - trio/intermediates/Celine.txt
    - trio/intermediates/Raphael.txt
    - trio/intermediates/Mateo.txt

  translated:
    - trio/translations/fr-Mateo.txt
    - trio/translations/fr-Celine.txt
    - trio/translations/fr-Raphael.txt

  collected: trio/intermediates/trio-fr-greetings.txt

  batch_report: trio/trio-fr-report.txt

Every task was cached, yet the translated files were published to the new location: Nextflow publishes the outputs of cached tasks too. The copies published to results/trio/intermediates/ by earlier runs are still there.

Exercise 2: Add a language, and predict what reruns

Starting from hello-workflow.nf as it stands at the end of this part, add Portuguese to the languages that translateGreeting can translate into, using the code pt and the greeting Ola. Run the workflow with --language pt -resume before and after your change.

Then, before running each of the following commands, predict which steps will run again and which will be cached, and check your predictions:

  1. nextflow run hello-workflow.nf --language pt -resume (right after adding Portuguese)
  2. nextflow run hello-workflow.nf --language es -resume
  3. nextflow run hello-workflow.nf --language es --batch spanish -resume
Hint

Before your change, the run fails the same way as the --language de example in section 1.3.4. To predict what reruns, ask for each step whether its inputs or its code changed since a previous run.

Solution

Before the change, the run fails with Unsupported language code: pt.

Add an entry to the dictionary:

hello-workflow.nf
        'en': 'Hello',       # English
        'pt': 'Ola',         # Portuguese
    }
  1. --language pt: sayHello is cached; translateGreeting and collectGreetings run. The collected file contains the Portuguese greetings:

    Output (excerpt)
    [c8/1d9afc] sayHello (Mateo)                  | 3 of 3, cached: 3 ✔
    [33/0f91cc] translateGreeting (pt-Celine.txt) | 3 of 3 ✔
    [37/9922fd] collectGreetings (batch)          | 1 of 1 ✔
    
    results/batch/intermediates/batch-pt-greetings.txt
    Ola, Raphael!
    Ola, Mateo!
    Ola, Celine!
    
  2. --language es: translateGreeting runs again, even though Spanish translations were computed in earlier runs. Adding Portuguese changed the code of translateGreeting, and a change to a process's code invalidates all of its cached results. collectGreetings runs again because its inputs changed: the files are new, and the language is different. Since the language is part of the collected file names, the Spanish results are published next to the Portuguese ones instead of replacing them.

    Output (excerpt)
    [3b/b013b6] sayHello (Raphael)               | 3 of 3, cached: 3 ✔
    [13/0dc549] translateGreeting (es-Mateo.txt) | 3 of 3 ✔
    [53/c05537] collectGreetings (batch)         | 1 of 1 ✔
    
  3. --batch spanish: only collectGreetings runs, because the batch name is one of its inputs; the other steps are cached.

    Output (excerpt)
    [c8/1d9afc] sayHello (Mateo)                   | 3 of 3, cached: 3 ✔
    [45/54b0b3] translateGreeting (es-Raphael.txt) | 3 of 3, cached: 3 ✔
    [38/ec2e7e] collectGreetings (spanish)         | 1 of 1 ✔
    

Exercise 3: Collect both versions of the greetings

Starting from hello-workflow.nf as it stands at the end of this part, add a step that writes all the original greetings and all the translated greetings into a single file called <batch>-<language>-bilingual.txt, published at the top level of the batch directory. Run it with --batch trio -resume.

Hint

The new process needs two collections of files as inputs, one from sayHello and one from translateGreeting, plus the batch name and the language for the output file name, as in collectGreetings. Its script only needs a cat command.

Solution

Define the new process after collectGreetings:

hello-workflow.nf
/*
 * Combine the original and translated greetings into a single file
 */
process collectBilingual {

    tag "${batch_name}"

    input:
    path greetings
    path translations
    val batch_name
    val language

    output:
    path "${batch_name}-${language}-bilingual.txt"

    script:
    """
    cat ${greetings} ${translations} > '${batch_name}-${language}-bilingual.txt'
    """
}

Call it in the workflow, collecting the outputs of both upstream processes, and publish its output:

hello-workflow.nf
    // collect all the greetings into one file
    collected_out = collectGreetings(translated_ch.collect(), params.batch, params.language)
    // combine the original and translated greetings
    bilingual_ch = collectBilingual(greetings_ch.collect(), translated_ch.collect(), params.batch, params.language)

    publish:
    greetings = greetings_ch
    translated = translated_ch
    collected = collected_out.outfile
    batch_report = collected_out.report
    bilingual = bilingual_ch
}

Add the matching entry to the output block:

hello-workflow.nf
    batch_report {
        path "${params.batch}"
        mode 'copy'
    }
    bilingual {
        path "${params.batch}"
        mode 'copy'
    }
}

Run the workflow:

nextflow run hello-workflow.nf --language fr --batch trio -resume
Output (excerpt)
[c8/1d9afc] sayHello (Mateo)                   | 3 of 3, cached: 3 ✔
[3a/f97a23] translateGreeting (fr-Raphael.txt) | 3 of 3, cached: 3 ✔
[50/966f92] collectGreetings (trio)            | 1 of 1, cached: 1 ✔
[21/ee476b] collectBilingual (trio)            | 1 of 1 ✔

Only the new step runs; everything upstream is cached.

results/trio/trio-fr-bilingual.txt
Hello, Raphael!
Hello, Mateo!
Hello, Celine!
Bonjour, Mateo!
Bonjour, Celine!
Bonjour, Raphael!

Quiz

#

In the workflow block, which line makes the output of sayHello(name_ch) available to the next step?

#

Why does the task directory of a translateGreeting call also contain the greeting file produced by sayHello?

#

What does the line #!/usr/bin/env python3 at the start of a process script do?

#

A process is called with translateGreeting(greetings_ch, params.language), where greetings_ch carries three files and params.language is a single value. How many times does the process run?

#

When providing multiple inputs to a process, what must be true?

#

Which operator should replace ??? to gather all outputs into a single list for the downstream process?

workflow {
    names_ch = channel.of('Mateo', 'Raphael', 'Celine')
    greetings_ch = sayHello(names_ch)
    gatherAll(greetings_ch.???)
}
#

When should you use the collect() operator?

#

A process with named outputs is called as collected_out = collectGreetings(...). How do you access its report output?

#

What is the correct syntax for naming an output in a process?