🦔

Nextflowの勉強2

に公開

はじめに

以前はNextflowの基本的な使用方法について学びました。

https://zenn.dev/edna_startup/articles/nextflow-demo01

2回目はより実用的なnextflowの使用方法について確認していきたいと思います。

nextflow.config

https://www.nextflow.io/docs/latest/developer/nextflow.config.html#nextflow-config

nextflow.config は、Directives で指定していた CPU やメモリに関する設定も含め、プロセス固有の設定以外にワークフロー全体のパラメーターを定義するための設定ファイルです。

基本的な記述形式は name = value です。また、パラメーターの設定には優先順位がある点に注意が必要です。

優先順位は以下の通りです(上の項目ほど優先されます):

  1. コマンドラインで指定されたパラメーター(例: --param_name value
  2. -params-file オプションで指定されたパラメーターファイル
  3. -c my_config オプションで指定された設定ファイル
  4. カレントディレクトリにある nextflow.config
  5. ワークフロープロジェクトディレクトリ$projectDir: 実行スクリプトが存在するディレクトリ)にある nextflow.config
  6. $HOME/.nextflow/config
  7. ワークフロースクリプト(例: main.nf)内で定義されたパラメーター

nextflow run ... 実行時にパラメーターを明示的に指定しない場合、初回の実行では通常、カレントディレクトリの nextflow.config の設定が優先的に使用されると考えて問題ないでしょう。ただし、そのファイルに設定が存在しない場合は、上記の優先順位に従って下位の設定が使用されます。

また、-C custom.config オプションを使えば、指定した設定ファイルのみを使用し、他の設定をすべて無視することも可能です。

processの動作を設定

nextflow.config でワークフローとして使用する各 process の動作をあらかじめ設定しておくことで、スクリプト本体(main.nf など)をより簡潔かつ柔軟に保つことができます。

例えば、CPU数やメモリ量、実行時間の制限、使用するコンテナの指定などを config ファイルでまとめて定義することができます。

以下に、典型的な process セクションの例を示します:

nextflow.config
process {
    withName: FASTP {
        cpus = 16
        memory = '16 GB'
        time = '1h'
        container = 'quay.io/biocontainers/fastp:0.23.2--h8b12597_0'
    }

    withName: MULTIQC {
        cpus = 4
        memory = '8 GB'
        time = '1h'
        container = 'quay.io/biocontainers/multiqc:1.13--pyhdfd78af_0'
    }

    executor = 'local'
    scratch = true
}

主な設定項目

  • cpus:使用するスレッド数
  • memory:使用する最大メモリ量。単位付き文字列(例: '8 GB')で指定。
  • time:プロセスごとの最大実行時間。タイムアウトを避けるために明示するのが望ましい。
  • container:使用する Singularity または Docker コンテナのイメージを指定。
  • executor:実行エンジン(例: local, slurm, pbs など)を指定。
  • scratch:一時ディレクトリを個別に確保するかどうかの指定(true にすると他プロセスと競合せずに済む)。

このようにして、各プロセスに固有の実行環境を柔軟に割り当てられるため、異なるツールを組み合わせた複雑なワークフローでも設定を一元管理しやすくなります。

また、process ブロック内で共通設定と withName 句を組み合わせることで、プロセス名ごとの個別調整も可能です。

withLabel

加えて、withLabel を使えば、複数のプロセスに共通する設定を一括で適用できます。

例えば、"heavy"な処理には多くのリソースを、"light"な処理には少なめのリソースを割り当てるといった運用が容易になります。

nextflow.config
process {
    withLabel: 'heavy' {
        cpus = 16
        memory = '64.GB'
        time = '6h'
    }
    withLabel: 'light' {
        cpus = 4
        memory = '8.GB'
        time = '30m'
    }
}

スクリプト内では以下のように label を付与することで適用されます:

process PREPROCESS_READ {
    label 'heavy'
    ...
}

process SUMMARIZE_STATS {
    label 'light'
    ...
}

executor

nextflow.configでは実行環境に応じてexecutorを指定できます。スパコンなどのクラスタ環境(SLURM, SGE,PBS)やクラウド(AWS Batch, Azure Batch)など、様々な環境に対応しています。詳細は以下のサイトを参照ください。

https://www.nextflow.io/docs/latest/executor.html#executors

process.executor = 'SGE'
process.queue = 'grid001'
process.clusterOptions = '-pe smp 32 -o /dev/null -e /dev/null'

また、プロセスごとに異なる executor を使いたい場合には、withName または withLabel と組み合わせて細かく設定可能です。

containerの一括指定とバージョン管理

後にワークフロー内での利用方法も確認しますが、複数のプロセスで同じコンテナを使う場合、共通コンテナを設定することで、記述の重複を避けられます:

process.container = 'docker.io/myorg/bioimage:latest'

あるいは、プロセス名やラベルごとに異なるイメージを指定できます:

process {
    withName: FASTP {
        container = 'quay.io/biocontainers/fastp:0.24.1--heae3180_0'
    }
    withName: MULTQC {
        container = 'quay.io/biocontainers/multiqc:1.28--pyhdfd78af_0'
    }
}

configファイルの分割

nextflow.configを役割ごとに分割して、-cオプションで読み込むことで、開発・本番などの複数環境に応じた構成管理が可能です。

例えば:

  • nextflow.config: 共通設定
  • slurm.config: Slurm用のexecutor設定
  • dev.config: 開発時の設定

実行時に利用する設定ファイルを指定します:

nextflow run main.nf -c slurm.config -c dev.config

containerの利用

Nextflowでは保守性・再現性・移管の容易度からコンテナイメージを使用することが推奨されています。

https://www.nextflow.io/docs/latest/container.html#containers

Singularity

Singulrityはルート権限無しで使用でき、バックグラウンドで常駐するデーモンプロセスを必要としません。この特徴はDockerと比べてスパコン(HPC)などの環境での使用に適しています。

前提としてSingularityが使用するPCにインストールされている必要があります。Docker Hubの使用にv2.3以降が必要なためこれ以降のバージョンをインストールします。2025/5 現在はv4.3.1が最新です。v4.1.2でもよければ以下も参考にしてください。

https://zenn.dev/edna_startup/articles/438d5d96342c29

Singulairtyの有効化

nextflow.configに以下のように記述して、Singularityを有効化します:

process {
    ...
    singularity.enable = true
}

もしは実行時に-with-singularityを指定することで有効化することも可能です:

nextflow run main.nf -with-singularity

プロセスごとに異なるコンテナを指定する場合、process.container を個別に定義します:

process FASTP {
    container = 'quay.io/biocontainers/fastp:0.24.1--heae3180_0'
    ...
}

process MULTIQC {
    container = 'quay.io/biocontainers/multiqc:1.28--pyhdfd78af_0'
    ...
}

Singularity は以下のような URI スキームに対応しています:

  • docker:// (DockerHub など): Docker Hubを利用する場合、自動で付与されるのであえて指定する必要は無い
  • library:// (Sylabs Cloud)
  • shub:// (Singularity Hub)
  • http(s):// (直接ダウンロード)
  • file (ローカルファイルイメージ)

Nextflow実行時に初回は自動的に.sifファイル(Singularity イメージ)が、~/.singularity以下にキャッシュされます。キャッシュディレクトリを変更したい場合はNXF_SINGULARITY_CACHEDIRに任意のパスを指定します:

export NXF_SINGULARITY_CACHEDIR="/path/to/cache"

Singularityを含むプロファイル設定例

Singularity自体のプロファイルをnextflow.configに定義しておきます。そうすることで、-profileでプロファイルを簡単に使用することが可能になります。

profiles {
    singularity {
        process.executor = 'local'
        singularity.enable = true
        singularity.autoMounts = true
        docker.enable = false
    }
}

実行例:

nextflow run main.nf -profile singularity

Singularityコンテナイメージの自作と利用

Singularityは既成のイメージを使うだけでなく、自身でカスタムイメージを作成して利用することが可能です。FastpとMultiqcをインストールしたイメージファイルを作成して使用してみます。

  1. 定義ファイル
data_qc.def
Bootstrap: docker
From: debian:bookworm-slim

%post
    # 必要なツールと依存をインストール
    apt update && apt install -y wget curl git ca-certificates \
        python3 python3-venv python3-pip unzip

    # 仮想環境の作成と MultiQC のインストール
    python3 -m venv /opt/venv
    /opt/venv/bin/pip install --upgrade pip
    /opt/venv/bin/pip install multiqc==1.28

    # fastp バイナリをダウンロードして /usr/local/bin に配置
    wget -O /usr/local/bin/fastp http://opengene.org/fastp/fastp.0.23.4
    chmod a+x /usr/local/bin/fastp

%environment
    export LC_ALL=C.UTF-8
    export PATH=/opt/venv/bin:$PATH

%labels
    Author your name
    Version 1.0


  1. .sifファイルをビルド
singularity build --fakeroot data_qc.sif data_qc.def

出力:

INFO:    Adding labels
INFO:    Adding environment to container
INFO:    Creating SIF file...
INFO:    Build complete: data_qc.sif
  1. ワークフローで利用
nextflow.config
process {
    executor = 'local'
    container = 'data_qc.sif'
    containerEngine = 'singularity'
    singularity.enabled = true
    withName: FASTP {
        cpus = 16
    }
    withName: MULTIQC {
        cpus = 4
    }
}
singularity {
    enabled = true
    autoMounts = true
    runOptions = '--cleanenv'
}

実行するメインスクリプト

main.nf
nextflow.enable.dsl=2

process FASTP {
    tag "$sample_id"
    publishDir "Results/fastp/fastq", pattern: "*_R{1,2}.fastq.gz", mode: "copy"
    publishDir "Results/fastp/summary", pattern: "*.{html,json}", mode: "copy"

    input:
        tuple val(sample_id), path(read1), path(read2)

    output:
        path("${sample_id}_R{1,2}.fastq.gz"), emit: 'fastp_fastq'
        path("${sample_id}_report.html"), emit: 'fastp_summary'
        path("${sample_id}_report.json"), emit: 'fastp_report'

    script:
        """
        fastp \
        --in1 ${read1} \
        --in2 ${read2} \
        --out1 ${sample_id}_R1.fastq.gz \
        --out2 ${sample_id}_R2.fastq.gz \
        --html ${sample_id}_report.html \
        --json ${sample_id}_report.json \
        --qualified_quality_phred 30 \
        --length_required 50 \
        --detect_adapter_for_pe \
        --trim_poly_g \
        --cut_front \
        --thread ${task.cpus}
        """
}

process MULTIQC {
    publishDir "Results/Multiqc", mode: 'copy'
    input:
        path fastp_report
    output:
        path "multiqc_report.html"
    script:
        """
        multiqc .
        """
}
workflow {
    read_ch=Channel
        .fromPath('sample.csv')
        .splitCsv(header:true)
        .map {
            row -> tuple(row.sample_id, file(row.read1), file(row.read2))
        }
    FASTP(read_ch)
    MULTIQC(FASTP.out.fastp_report.collect())
}

出力:

executor >  local (5)
[30/a3d8f9] process > FASTP (SRR18585216) [100%] 4 of 4 ✔
[90/416b96] process > MULTIQC             [100%] 1 of 1 ✔
Completed at: 07-May-2025 01:16:08
Duration    : 1m 23s
CPU hours   : 0.5
Succeeded   : 5

問題なく完了していることを確認。

感想

Configの簡単な設定や一般的にHPCの利用環境で利用されるSingularityコンテナイメージを使った処理の実行について把握することができました。

現状興味があるのは、Git/GitHubリポジトリで管理されているスクリプトの直接実行nf-coreのパイプライン作成方法の活用AWSでのクラウド実行です。難易度も挙げた順だと思うので随時取り組んでいきたいと思います。

参照・出典

Discussion