if statement to select a channel in input block with nextflow

Viewed 219

I am currently writing my first nextflow pipeline and I need to run different process in function of the parameter.

In fact, I would like, in one process, to select the channel where the input come from. I've tested like that :

process foo{

  input:
  if(params.bar && params.bar2)
  {
    file reads from channel1.flatten()
  }
  else
  {
    file reads from channel_2.flatten()
  }
 
output:
  publishDir "$params.output_dir"
  file "output_file" into channel_3

  """
  my command line
  """

I obtain this error and I don't understand why.

No such variable: reads

Is there a way to do something like that ? Thanks !

1 Answers

It's a bit of a weird error, but basically you just need to make sure your input declaration follows/matches the required syntax:

input:
  <input qualifier> <input name> [from <source channel>] [attributes]

One solution might be to use the ternary operator to replace your if/else branch, for example:

ch1 = Channel.of( 'hello', 'world' )
ch2 = Channel.of( 1, 3, 5, 7, 9 )

params.foo = false
params.bar = false


process test {

    echo true

    input:
    val myval from ( params.foo && params.bar ? ch1 : ch2 )

    """
    echo -n "${myval}"
    """
}

Results:

$ nextflow run script.nf
N E X T F L O W  ~  version 21.04.3
Launching `script.nf` [shrivelled_stone] - revision: 7b3f3a51df
executor >  local (5)
[3b/fafa5e] process > test (2) [100%] 5 of 5 ✔
1
5
9
7
3

$ nextflow run script.nf --foo --bar
N E X T F L O W  ~  version 21.04.3
Launching `script.nf` [irreverent_mahavira] - revision: 7b3f3a51df
executor >  local (2)
[d2/09d418] process > test (1) [100%] 2 of 2 ✔
world
hello


Note that the new DSL 2 decouples the channel inputs from the process declaration, which might help to keep things readable, especially if the condition or action statements are more complex. For example:

nextflow.enable.dsl=2

params.foo = false
params.bar = false


process test {

    echo true

    input:
    val myval 

    """
    echo -n "${myval}"
    """
}

workflow {

    ch1 = Channel.of( 'hello', 'world' )
    ch2 = Channel.of( 1, 3, 5, 7, 9 )

    if( params.foo && params.bar ) {
        test( ch1 )
    } else {
        test( ch2 )
    }
}

Results:

$ nextflow run script.nf
N E X T F L O W  ~  version 21.04.3
Launching `script.nf` [nauseous_pare] - revision: e1c4770ff1
executor >  local (5)
[36/49d8da] process > test (4) [100%] 5 of 5 ✔
9
1
3
5
7

$ nextflow run script.nf --foo --bar
N E X T F L O W  ~  version 21.04.3
Launching `script.nf` [goofy_euler] - revision: e1c4770ff1
executor >  local (2)
[56/e635e8] process > test (2) [100%] 2 of 2 ✔
world
hello

Related