10 tháng 02, 2026

Unix pipes trong bioinformatics: truyền dữ liệu dạng luồng để giảm bộ nhớ và dung lượng lưu trữ

Unix pipes trong bioinformatics: truyền dữ liệu dạng luồng để giảm bộ nhớ và dung lượng lưu trữ

Unix pipe (|) nối trực tiếp đầu ra của lệnh này với đầu vào của lệnh kế tiếp. Trong bioinformatics, nơi các tập dữ liệu giải trình tự rất lớn, đây là một cách thực tế để tránh ghi ra các tệp trung gian: dữ liệu chảy qua pipeline thay vì được ghi xuống đĩa rồi đọc lại ở mỗi bước. Bài viết này xem xét vì sao điều đó quan trọng, cách pipe hoạt động bên trong, và nơi mẫu hình tương tự xuất hiện trong các workflow thực tế như Sarek.

Vấn đề: các tệp trung gian

Một lần giải trình tự toàn bộ hệ gen người có thể tạo ra, theo bậc độ lớn gần đúng:

  • Read thô: hơn 100 GB tệp FASTQ
  • Căn chỉnh: 50-100 GB tệp BAM
  • Biến thể: 1-5 GB tệp VCF

Một workflow ghi một tệp trung gian ở mỗi bước sẽ nhân dung lượng lưu trữ lên:

Terminal window
# Traditional approach (❌ Wasteful)
bwa mem reference.fa reads.fastq > aligned.sam # 200 GB intermediate
samtools view -b aligned.sam > aligned.bam # 100 GB intermediate
samtools sort aligned.bam > sorted.bam # 100 GB intermediate
samtools index sorted.bam # Already indexed
# Total disk usage: 400 GB for processing 100 GB of raw data!

Các chi phí là:

  • Lưu trữ: tệp trung gian có thể lớn gấp vài lần dữ liệu gốc
  • Thời gian: ghi và đọc tệp trung gian làm tăng I/O
  • Thất bại: nếu một bước hỏng giữa chừng, thường phải dựng lại các tệp trung gian
  • Độ phức tạp: phải theo dõi và dọn dẹp các tệp trung gian

Truyền luồng bằng pipe

Một pipe nối đầu ra của lệnh này với đầu vào của lệnh kế tiếp, nên dữ liệu được xử lý ngay khi nó được sinh ra:

Terminal window
# Pipe approach (✓ Efficient)
bwa mem reference.fa reads.fastq | \
samtools view -b - | \
samtools sort -o sorted.bam -
samtools index sorted.bam
# Total disk usage: 100 GB (original data + final output)
# No intermediate files!

Các lợi ích được báo cáo là:

  • mỗi thời điểm chỉ có một bộ đệm dữ liệu nằm trong bộ nhớ
  • không có I/O đĩa cho các tệp trung gian
  • lỗi được báo ngay khi xảy ra
  • pipeline đọc như một chuỗi lệnh tuyến tính
  • chỉ giữ lại các đầu ra cuối cùng

Cách pipe hoạt động bên trong

Hiểu cơ chế giúp giải thích khi nào một pipeline hiệu quả và khi nào không.

1. File descriptor trong Unix

Mỗi tiến trình Unix có ba file descriptor chuẩn:

Descriptor Tên Mục đích Đích mặc định
0 stdin Đầu vào chuẩn Bàn phím
1 stdout Đầu ra chuẩn Terminal/Màn hình
2 stderr Lỗi chuẩn Terminal/Màn hình

Mặc định, tiến trình đọc từ stdin (file descriptor 0) và ghi ra stdout (file descriptor 1).

Terminal window
# Example: cat command
cat myfile.txt # Reads file, writes to stdout (terminal)
cat < myfile.txt # Explicitly redirect stdin from file
cat myfile.txt 1> output.txt # Redirect stdout to file

2. Tạo pipe bằng system call pipe

Khi gõ command1 | command2, shell:

  1. Tạo một pipe - một bộ đệm không tên, nằm trong bộ nhớ, nối hai tiến trình
  2. Fork tiến trình 1 - tạo một bản sao của shell để chạy command1
  3. Nối stdout của tiến trình 1 vào đầu ghi của pipe (file descriptor 1)
  4. Fork tiến trình 2 - tạo một bản sao của shell để chạy command2
  5. Nối stdin của tiến trình 2 vào đầu đọc của pipe (file descriptor 0)
  6. Thực thi cả hai tiến trình - chúng chạy song song

Sơ đồ một pipe:

[command1] [command2]
| |
stdout (fd 1) stdin (fd 0)
| |
v ^
[================================]
Pipe (kernel buffer)

3. Kernel quản lý dòng dữ liệu

Kernel Unix quản lý pipe như một bộ đệm FIFO (vào trước, ra trước):

  • Đầu ghi: command1 ghi dữ liệu vào đầu ghi của pipe
  • Bộ đệm pipe: dữ liệu nằm trong bộ nhớ kernel (thường từ vài chục KB tới khoảng 1 MB mỗi pipe)
  • Đầu đọc: command2 đọc dữ liệu từ đầu đọc của pipe

Một vài hành vi suy ra từ đó:

  1. Nếu pipe đầy: tiến trình ghi sẽ chặn cho tới khi có chỗ
  2. Nếu pipe rỗng: tiến trình đọc sẽ chặn cho tới khi có dữ liệu
  3. Nếu bên đọc đóng: bên ghi nhận tín hiệu SIGPIPE (broken pipe)
  4. Nếu bên ghi đóng: bên đọc nhận EOF và có thể kết thúc xử lý

Việc đồng bộ này do kernel đảm nhiệm.

4. Ví dụ: theo dõi một pipe

Với pipeline:

Terminal window
cat genome.fasta | grep ">chr1" | wc -l

Bước 1: shell tạo pipeline

User types: cat genome.fasta | grep ">chr1" | wc -l
↓
Shell creates:
- Pipe A (between cat and grep)
- Pipe B (between grep and wc)

Bước 2: các tiến trình fork và file descriptor được chuyển hướng

Process: cat genome.fasta
stdout (fd 1) → Pipe A write end
Process: grep ">chr1"
stdin (fd 0) ← Pipe A read end
stdout (fd 1) → Pipe B write end
Process: wc -l
stdin (fd 0) ← Pipe B read end
stdout (fd 1) → Terminal

Bước 3: dòng thực thi

Pipe A buffer: Pipe B buffer:
[data from cat] → [data to grep] → [data to wc] → [count to terminal]

Bước 4: đồng bộ bằng back pressure

If grep is slow:
- Pipe A fills up
- cat blocks (can't write)
- System automatically waits for grep to catch up
If wc is slow:
- Pipe B fills up
- grep blocks (can't write)
- System waits for wc to catch up

5. Vì sao pipe không nạp tất cả vào RAM

Không dùng pipe (ghi xuống đĩa):

command1: Read all data → Write 100GB to disk
↓
Disk (100GB) ← Slow, uses storage
↓
command2: Read 100GB from disk → Process → Write results

Dùng pipe (truyền luồng):

command1: Read chunk → Write chunk to pipe buffer (64KB)
↓
Pipe buffer (kernel memory, reused)
↓
command2: Read chunk → Process → Write chunk to next pipe

Mỗi thời điểm chỉ có một lượng nhỏ dữ liệu (một bộ đệm, cỡ 64KB) nằm trong bộ nhớ. Bộ đệm được dùng lại khi dữ liệu chảy qua, nên mức dùng bộ nhớ gần như không đổi bất kể tổng kích thước dữ liệu, thay vì tăng tuyến tính theo nó.

Một ví dụ thực tế: xử lý một tệp FASTQ lớn

Phần dưới đây là một ví dụ minh hoạ cho sự khác biệt.

Không dùng pipe

Terminal window
# Step 1: Filter low-quality reads
fastqc reads.fastq --outdir=qc_before/
fastq_quality_filter -i reads.fastq -o reads_filtered.fastq -q 20 -p 80
# File created: reads_filtered.fastq (70 GB)
# Step 2: Count remaining reads
wc -l reads_filtered.fastq
# Temporary file: 70 GB on disk
# Step 3: Get sequence length distribution
awk 'NR%4==2 {print length}' reads_filtered.fastq | \
sort -n | uniq -c > length_dist.txt
# Processing reads_filtered.fastq again
# Cleanup
rm reads_filtered.fastq
# Total I/O: Read source (100GB) + Write filtered (70GB) + Read filtered (70GB) = 240GB
# Total disk: 170 GB (100 source + 70 intermediate)

Dùng pipe

Terminal window
# Single streaming pipeline: Filter → Count → Length distribution
fastq_quality_filter -i reads.fastq -q 20 -p 80 | \
tee >(wc -l > read_count.txt) | \
awk 'NR%4==2 {print length}' | \
sort -n | uniq -c > length_dist.txt
# Total I/O: Read source (100GB) = 100GB
# Total disk: 100 GB (source + final outputs only)
# Memory: ~100MB (pipe buffers)

So sánh minh hoạ:

Chỉ số Không dùng pipe Dùng pipe
Tổng I/O 240 GB 100 GB
Dung lượng đĩa 170 GB 100 GB
Thời gian xử lý Chậm hơn (đọc đĩa nhiều lần) Nhanh hơn (một lần đọc tuần tự)
Dùng bộ nhớ Truyền luồng OK Truyền luồng OK
Khôi phục lỗi Chạy lại toàn bộ pipeline Vấn đề tính nguyên tử của pipeline

Các con số ở trên là ước lượng theo bậc độ lớn cho ví dụ; con số thực tế phụ thuộc vào công cụ và dữ liệu.

Các mẫu hình pipe nâng cao

1. Xử lý song song với GNU Parallel

Xử lý nhiều tệp cùng lúc trong khi vẫn pipe:

Terminal window
# Process 1000 FASTQ files in parallel
find . -name "*.fastq" | \
parallel --pipe --block 10M \
'fastq_quality_filter -q 20 -p 80 | gzip' > all_filtered.fastq.gz

2. tee: phân nhánh một pipeline

tee gửi cùng một luồng tới nhiều đích:

Terminal window
# Simultaneously:
# 1. Count reads
# 2. Filter and output
# 3. Generate statistics
samtools view input.bam | \
tee >(samtools flagstat /dev/stdin > flagstat.txt) | \
samtools view -b -F 4 | \
samtools sort -o sorted_aligned.bam -
# The >(command) syntax is "process substitution"
# It creates a named pipe to a subprocess

3. Named pipe (mkfifo) cho workflow phức tạp

Với workflow cần nhiều đầu vào hoặc đầu ra:

Terminal window
# Create named pipes
mkfifo pipe1 pipe2
# Process A writes to pipe1, reads from pipe2
cat input.txt > pipe1 &
# Process B reads from pipe1, writes to pipe2
sort < pipe1 > pipe2 &
# Main process reads final result
uniq < pipe2
# Cleanup
rm pipe1 pipe2

4. Đệm dữ liệu và back pressure

Một lệnh phía sau chậm có thể trở thành nút thắt. buffer thêm bộ nhớ để hấp thụ điều đó:

Terminal window
# Without buffer: cat blocks if samtools is slow
cat large.bam | samtools view -c
# With buffer: Extra memory absorbs the blocking
cat large.bam | buffer -m 500M | samtools view -c

buffer hữu ích khi tiến trình phía sau chậm hơn nhiều so với phía trước, khi còn RAM trống, và khi dữ liệu phía trước tốn kém để tạo lại.

5. Process substitution cho nhiều đầu ra

Phân nhánh tới nhiều tiến trình từ một đầu vào:

Terminal window
# Single BAM file → Multiple statistics simultaneously
samtools view input.bam | \
tee >(samtools view -c > read_count.txt) \
>(awk '{print $3}' | sort | uniq -c > chromosome_dist.txt) \
>(awk '{print $4}' | sort -n > position_stats.txt) \
> /dev/null
# All three statistics generated from a single read of input.bam

Một số cạm bẫy thường gặp

1. Đệm dữ liệu (buffering)

Vấn đề: một lệnh tương tác có thể không xả đầu ra ở chế độ pipe.

Terminal window
# This might hang (python buffers output in pipe mode)
python long_script.py | tee output.log

Giải pháp: tắt đệm dữ liệu.

Terminal window
# Python: Use -u flag or stdbuf
python -u long_script.py | tee output.log
# Or use stdbuf
stdbuf -oL python long_script.py | tee output.log

2. Xử lý lỗi

Vấn đề: lỗi ở một lệnh giữa chuỗi có thể im lặng.

Terminal window
# If samtools fails, cat and downstream still succeed!
cat input.bam | samtools view -b - > output.bam 2>/dev/null

Giải pháp: đặt pipefail để pipeline thất bại nếu bất kỳ lệnh nào thất bại.

Terminal window
# If ANY command fails, the entire pipeline fails
set -o pipefail
cat input.bam | samtools view -b - > output.bam

3. Theo dõi tiến độ

Vấn đề: pipeline in ra rất ít trong khi chạy.

Terminal window
# No feedback on progress
cat input.fastq | process_cmd | sort > output.txt

Giải pháp: pv (pipe viewer) hiển thị thông lượng.

Terminal window
# Shows progress, speed, and ETA
cat input.fastq | pv | process_cmd | sort > output.txt
# Or with file size estimation
pv -N "Reading FASTQ" < input.fastq | process_cmd | \
pv -N "Sorting output" | sort > output.txt

4. Gỡ lỗi một pipeline thất bại

Vấn đề: không rõ lệnh nào đã thất bại.

Terminal window
# Unclear where failure occurred
cmd1 | cmd2 | cmd3 | cmd4 failed but which one?

Giải pháp: tee các đầu ra trung gian khi gỡ lỗi.

Terminal window
# Save intermediate outputs while piping
cmd1 | tee /tmp/debug1.txt | \
cmd2 | tee /tmp/debug2.txt | \
cmd3 | tee /tmp/debug3.txt | \
cmd4
# Later, inspect intermediates
cat /tmp/debug1.txt | head
cat /tmp/debug2.txt | head
cat /tmp/debug3.txt | head

Pipe trong các module Nextflow

Pipeline Nextflow được dựng từ các tiến trình riêng lẻ, và mỗi tiến trình có thể dùng pipe bên trong để nối công cụ. Tiến trình BWA_MEM trong pipeline nf-core Sarek là một ví dụ.

process BWA_MEM {
tag "$meta.id"
label 'process_high'
conda "${moduleDir}/environment.yml"
container "${ workflow.containerEngine == 'singularity' && !task.ext.singularity_pull_docker_container ?
'https://community-cr-prod.seqera.io/docker/registry/v2/blobs/sha256/bf/bf7890f8d4e38a7586581cb7fa13401b7af1582f21d94eef969df4cea852b6da/data' :
'community.wave.seqera.io/library/bwa_htslib_samtools:56c9f8d5201889a4' }"
input:
tuple val(meta) , path(reads)
tuple val(meta2), path(index)
tuple val(meta3), path(fasta)
val sort_bam
output:
tuple val(meta), path("*.bam") , emit: bam, optional: true
tuple val(meta), path("*.cram") , emit: cram, optional: true
tuple val(meta), path("*.csi") , emit: csi, optional: true
tuple val(meta), path("*.crai") , emit: crai, optional: true
path "versions.yml" , emit: versions
when:
task.ext.when == null || task.ext.when
script:
def args = task.ext.args ?: ''
def args2 = task.ext.args2 ?: ''
def prefix = task.ext.prefix ?: "${meta.id}"
def samtools_command = sort_bam ? 'sort' : 'view'
def extension = args2.contains("--output-fmt sam") ? "sam" :
args2.contains("--output-fmt cram") ? "cram":
sort_bam && args2.contains("-O cram")? "cram":
!sort_bam && args2.contains("-C") ? "cram":
"bam"
def reference = fasta && extension=="cram" ? "--reference ${fasta}" : ""
if (!fasta && extension=="cram") error "Fasta reference is required for CRAM output"
"""
INDEX=`find -L ./ -name "*.amb" | sed 's/\\.amb\$//'`
bwa mem \\
$args \\
-t $task.cpus \\
\$INDEX \\
$reads \\
| samtools $samtools_command $args2 ${reference} --threads $task.cpus -o ${prefix}.${extension} -
cat <<-END_VERSIONS > versions.yml
"${task.process}":
bwa: \$(echo \$(bwa 2>&1) | sed 's/^.*Version: //; s/Contact:.*\$//')
samtools: \$(echo \$(samtools --version 2>&1) | sed 's/^.*samtools //; s/Using.*\$//')
END_VERSIONS
"""
stub:
def args2 = task.ext.args2 ?: ''
def prefix = task.ext.prefix ?: "${meta.id}"
def extension = args2.contains("--output-fmt sam") ? "sam" :
args2.contains("--output-fmt cram") ? "cram":
sort_bam && args2.contains("-O cram")? "cram":
!sort_bam && args2.contains("-C") ? "cram":
"bam"
"""
touch ${prefix}.${extension}
touch ${prefix}.csi
touch ${prefix}.crai
cat <<-END_VERSIONS > versions.yml
"${task.process}":
bwa: \$(echo \$(bwa 2>&1) | sed 's/^.*Version: //; s/Contact:.*\$//')
samtools: \$(echo \$(samtools --version 2>&1) | sed 's/^.*samtools //; s/Using.*\$//')
END_VERSIONS
"""
}

Pipe trong BWA_MEM

Dòng liên quan nối trực tiếp bwa và samtools:

Terminal window
bwa mem $args -t $task.cpus $INDEX $reads | samtools $samtools_command $args2 ${reference} --threads $task.cpus -o ${prefix}.${extension} -

Điều gì xảy ra:

  1. bwa mem căn chỉnh read vào hệ gen tham chiếu và ghi SAM ra stdout. Với một hệ gen lớn, đây có thể là hàng trăm GB. Nếu không có pipe, nó sẽ được ghi xuống đĩa thành một tệp .sam trung gian.
  2. Pipe (|) nối đầu ra đó trực tiếp vào samtools, nên dữ liệu truyền từ bwa sang samtools mà không có tệp SAM trung gian, và bộ nhớ giữ gần như không đổi.
  3. samtools sort/view xử lý luồng, hoặc sắp xếp (khi sort_bam=true) hoặc chuyển định dạng, ghi trực tiếp ra .bam, .cram hoặc .sam và dùng --threads $task.cpus.

Lợi ích trong workflow này

Với một lần giải trình tự toàn bộ hệ gen người (~100GB read thô), một so sánh minh hoạ:

Không có pipe (giả định):

bwa mem $INDEX $reads > aligned.sam # 500+ GB intermediate
samtools sort aligned.sam > sorted.bam # 100+ GB final
rm aligned.sam
  • Lưu trữ cần: hàng trăm GB
  • I/O đĩa: đọc đầu vào (bwa) + ghi SAM + đọc SAM (samtools)
  • Thời gian: chậm hơn do I/O trung gian

Có pipe (cách làm của Sarek):

bwa mem $INDEX $reads | samtools sort -o sorted.bam -
  • Lưu trữ cần: chỉ đầu ra cuối cùng
  • I/O đĩa: đọc đầu vào + ghi BAM cuối cùng
  • Bộ nhớ: gần như không đổi bất kể kích thước hệ gen

Tính linh hoạt qua tham số

Tiến trình chuyển giữa đầu ra có sắp xếp và không sắp xếp chỉ bằng một giá trị:

def samtools_command = sort_bam ? 'sort' : 'view'

Định dạng đầu ra cũng được chọn lúc chạy:

def extension = args2.contains("--output-fmt cram") ? "cram" : "bam"

Do đó cùng một tiến trình có thể xuất BAM, CRAM hoặc SAM trong khi vẫn giữ cùng mẫu hình pipe.

Xử lý lỗi trong tiến trình Nextflow

Nextflow đánh dấu một task là thất bại nếu bất kỳ lệnh nào trong chuỗi thất bại:

Terminal window
bwa mem ... | samtools sort ... # If either fails, Nextflow catches it

Điều này rõ ràng hơn một script bash thông thường, nơi lỗi có thể im lặng. Để pipeline dừng khi có bất kỳ lỗi nào, có thể cấu hình shell dùng pipefail:

process {
shell = ['/bin/bash', '-euo', 'pipefail'] // -o pipefail catches pipe errors
}

Điều này đảm bảo rằng nếu bwa thất bại và không tạo ra gì, samtools coi đầu vào rỗng là lỗi thay vì xử lý thành công trên đó một cách im lặng.

Pipe cho tải lên, tải xuống và lưu trữ cloud

Kết hợp công cụ tải lên/tải xuống với xử lý dữ liệu là một cách phổ biến để tránh tệp trung gian, đặc biệt quan trọng khi làm việc với lưu trữ cloud như AWS S3.

Ví dụ 1: tải xuống, giải nén, xử lý (không tệp tạm)

Tình huống: tải một hệ gen tham chiếu đã nén, giải nén và đánh index mà không giữ lại tệp nén.

Terminal window
# Traditional approach (❌ Wasteful)
wget https://example.com/reference.fasta.gz # Downloads 5GB
gunzip reference.fasta.gz # Decompresses to 15GB
samtools faidx reference.fasta # Index the reference
rm reference.fasta # Cleanup takes time
# Total disk space needed: 20GB
# Pipe approach (✓ Efficient)
wget -q -O - https://example.com/reference.fasta.gz | \
gunzip | \
samtools faidx /dev/stdin
# Total disk space needed: 15GB (final reference only)
# No temporary files, no cleanup needed

Điều gì xảy ra:

  1. wget -O - tải về stdout thay vì ghi xuống đĩa
  2. gunzip giải nén luồng ngay khi nó tới
  3. samtools faidx /dev/stdin đọc từ luồng
  4. không có tệp nén trung gian nào được lưu

Ví dụ 2: xử lý, nén, tải lên S3 (một pipeline)

Tình huống: xử lý dữ liệu giải trình tự và tải kết quả đã nén lên AWS S3 mà không tạo tệp nén cục bộ.

Terminal window
# Traditional approach (❌ Wasteful)
bwa mem reference.fa reads.fastq | samtools sort -o aligned.bam -
gzip aligned.bam # Creates aligned.bam.gz (100+ GB)
aws s3 cp aligned.bam.gz s3://my-bucket/ # Upload
rm aligned.bam.gz # Cleanup
# Total disk space: 200+ GB (original BAM + compressed file)
# Pipe approach (✓ Efficient)
bwa mem reference.fa reads.fastq | \
samtools sort -b - | \
gzip | \
aws s3 cp - s3://my-bucket/aligned.bam.gz
# Total disk space: 0 GB temporary files
# Compressed data uploaded directly to S3
# Only stores the final index or metadata files locally

Điều gì xảy ra:

  1. bwa mem và samtools sort được nối với nhau
  2. gzip nén luồng BAM
  3. aws s3 cp - tải lên từ stdin
  4. dữ liệu không bao giờ được ghi đầy đủ xuống đĩa cục bộ

Ví dụ 3: tải từ S3, giải nén, phân tích

Tình huống: phân tích các tệp BAM trong S3 mà không tải toàn bộ tệp chưa nén về cục bộ.

Terminal window
# Traditional approach (❌ Wasteful)
aws s3 cp s3://my-bucket/sample.bam.gz . # Download 50GB
gunzip sample.bam.gz # Decompress to 150GB
samtools flagstat sample.bam # Analyze
# Local disk: 200GB, slow downloads
# Pipe approach (✓ Efficient)
aws s3 cp s3://my-bucket/sample.bam.gz - | \
gunzip | \
samtools flagstat /dev/stdin
# Local disk: 0 GB temporary files
# Stream analysis, no storage overhead

Ví dụ 4: tải tarball, giải nén, đánh index

Tình huống: tải một kho nén các trình tự tham chiếu, giải nén và đánh index trong một pipeline.

Terminal window
# Traditional approach (❌ Wasteful)
wget https://example.com/genomes.tar.gz # 10GB download
tar -xzf genomes.tar.gz # Extracts to 50GB
for ref in genomes/*.fasta; do
samtools faidx "$ref"
done
rm -rf genomes.tar.gz genomes/ # Cleanup
# Disk space: 60GB temporary files
# Pipe approach (✓ Efficient)
wget -q -O - https://example.com/genomes.tar.gz | \
tar -xz --to-stdout | \
while read -r line; do
echo "$line" >> current_genome.fasta
if [[ "$line" =~ ^> ]] && [ -s current_genome.fasta ]; then
samtools faidx current_genome.fasta
fi
done
# Or more elegantly with GNU tar:
wget -q -O - https://example.com/genomes.tar.gz | \
tar -xz -C /dev/shm # Extract to RAM disk (if available)
# Disk space: Only final index files

Truyền một tệp cụ thể từ tarball:

Terminal window
# Extract specific files from tarball without decompressing entire archive
wget -q -O - https://example.com/genomes.tar.gz | \
tar -xzf - genomes/reference.fasta --to-stdout | \
samtools faidx /dev/stdin

Ví dụ 5: xử lý nhiều tệp từ S3 với GNU Parallel

Tình huống: xử lý nhiều tệp trong S3 song song.

Terminal window
# List all BAM files in S3 and process in parallel
aws s3 ls s3://my-bucket/bams/ --recursive | awk '{print $4}' | \
parallel --pipe --block 10M \
'aws s3 cp "s3://my-bucket/{}" - | \
samtools view -b -F 4 | \
samtools sort -o {/.}.sorted.bam -'
# What happens:
# 1. List all S3 objects
# 2. Process up to N files in parallel
# 3. Each file is downloaded and piped directly to samtools
# 4. Results written back to disk (or piped to another command)

Ví dụ 6: tải kết quả lên ngay khi chúng được tạo ra

Tình huống: sinh kết quả phân tích và tải dần lên S3, hữu ích cho các tiến trình chạy dài.

Terminal window
# Real-time upload of VCF variants as they're discovered
bcftools mpileup -f reference.fa sample.bam | \
bcftools call -m | \
tee >(gzip | aws s3 cp - s3://my-bucket/variants.vcf.gz) | \
grep -v "^#" | \
wc -l
# What happens:
# 1. bcftools generates variants
# 2. tee splits the stream into two paths:
# - First path: gzip and upload to S3 in real-time
# - Second path: count total variants
# 3. Both operations happen simultaneously from a single bcftools stream
# 4. Results available in S3 even while analysis continues

Một biến thể để theo dõi:

Terminal window
# Start a 24-hour variant calling run with real-time uploading
samtools mpileup -f ref.fa *.bam | \
bcftools call -m -v 2>/tmp/variants.log | \
tee >(gzip | aws s3 cp - s3://bucket/live-variants.vcf.gz) | \
tail -100 | grep "PASS" > /tmp/latest_variants.txt
# In another terminal, monitor progress:
watch -n 10 "wc -l /tmp/latest_variants.txt && aws s3 ls s3://bucket/live-variants.vcf.gz"

Mẹo cho pipe tải lên/tải xuống đáng tin cậy

Tình huống Lệnh pipe Ghi chú
Tải xuống + giải nén wget -O - | gunzip | process Dùng -O - để xuất ra stdout
Tải lên + nén process | gzip | aws s3 cp - Pipe - cho stdin/stdout
Tải từ S3 + phân tích aws s3 cp s3://... - | process - đọc từ stdin ra stdout
Giải nén tar theo luồng wget -O - tar.gz | tar -xz -O file -O hoặc --to-stdout xuất ra stdout
Nhiều tệp S3 Dùng aws s3 ls + parallel Nối với aws s3 cp s3://... -
Theo dõi thời gian thực Dùng tee để phân nhánh Tải lên và xử lý cục bộ đồng thời
Xử lý lỗi Kiểm tra mã thoát với set -o pipefail Lỗi S3 cần làm pipeline thất bại

Cân nhắc cho pipe trên cloud

1. Nút thắt mạng so với đĩa

Terminal window
# If network is slower than local processing:
# Download once, process multiple times
wget -O - file.tar.gz | tee local.tar.gz | tar -xz | process1
tar -xz < local.tar.gz | process2
tar -xz < local.tar.gz | process3
# Tradeoff: Local storage vs. network bandwidth

2. Logic thử lại cho thao tác S3 thất bại

Terminal window
# Simple retry with exponential backoff
retry_count=0
while [ $retry_count -lt 3 ]; do
aws s3 cp s3://bucket/file - 2>/dev/null && break
retry_count=$((retry_count + 1))
sleep $((2 ** retry_count))
done | gunzip | process

3. Theo dõi tiến độ tải lên

Terminal window
# Use pv to monitor upload speed
process_data | \
pv -br | \
gzip | \
aws s3 cp - s3://bucket/file.gz
# Output: [1.2GB/s] or similar

4. Multipart upload cho tệp lớn

Với tệp lớn hơn vài GB, multipart upload của AWS S3 đáng tin cậy hơn:

Terminal window
# aws s3 cp already handles multipart, but for custom control:
process_data | \
gzip | \
aws s3 cp - s3://bucket/large-file.gz \
--sse AES256 \
--storage-class GLACIER # Optional: cheaper storage class

Một vài ví dụ khác

Quality control cho RNA-seq

Terminal window
# Process RNA-seq reads:
# 1. Filter low quality
# 2. Count valid reads
# 3. Extract length distribution
# 4. Detect adapters
fastq_quality_filter -i reads.fastq -q 20 -p 80 | \
tee >(wc -l | awk '{print "Valid reads: "$1/4}' > read_count.txt) | \
tee >(awk 'NR%4==2 {print length}' | \
sort -n | uniq -c > length_dist.txt) | \
fastx_collapser -o collapsed.fastq | \
fastx_clipper -a AGATCGGAAGAGC -o trimmed.fastq

Gọi biến thể

Terminal window
# Align reads, mark duplicates, and call variants in one pass
bwa mem -t 8 reference.fa reads.fastq | \
samtools view -b -S - | \
samtools sort -o sorted.bam - && \
samtools markdup sorted.bam marked.bam && \
samtools index marked.bam && \
bcftools mpileup -f reference.fa marked.bam | \
bcftools call -mv -o variants.vcf
# Memory: Constant (~1-2 GB for buffers)
# Disk: Only intermediate files marked.bam (necessary for bcftools indexing)

Xử lý FASTA kèm giải nén

Terminal window
# Decompress, process, and recompress in a single pipeline
zcat genome.fasta.gz | \
awk '/^>/{if(NR>1)print prev_seq; seq=""; prev_seq=$0; next} {seq=seq $0} END{print prev_seq; print seq}' | \
gzip > processed.fasta.gz
# No intermediate uncompressed files
# Entire genome processed with minimal disk space

Tóm lại

Vấn đề Giải pháp bằng pipe
Tệp trung gian Truyền trực tiếp giữa các công cụ
Dung lượng đĩa Không cần lưu trữ tạm
Dùng bộ nhớ Không đổi, độc lập với kích thước dữ liệu
Tốc độ xử lý Một lần đọc tuần tự dữ liệu
Khôi phục khi lỗi Lỗi được báo ngay
Dễ đọc mã Dòng dữ liệu rõ ràng, tuyến tính

Các điểm chính

1. Pipe xử lý dữ liệu như một luồng

  • dữ liệu chảy qua các bộ đệm trong bộ nhớ thay vì qua tệp trung gian
  • mỗi thời điểm chỉ có một bộ đệm nhỏ cho mỗi pipe nằm trong bộ nhớ
  • xử lý 1 GB hay 1 TB đều dùng mức bộ nhớ gần như không đổi
  • đây là khác biệt chính so với một workflow dựa trên tệp

2. Đồng bộ ở mức kernel là tự động

  • không cần quản lý thủ công
  • back pressure ngăn một lệnh chậm bị quá tải
  • nếu một lệnh thất bại, set -o pipefail làm cả pipeline thất bại

3. Mức giảm I/O có thể rất lớn

  • ví dụ minh hoạ: 100GB read → 500GB SAM → 100GB BAM khi có tệp trung gian, so với 100GB read → 100GB BAM khi dùng pipe
  • con số thực tế phụ thuộc vào công cụ và dữ liệu
  • ở các bước bị giới hạn bởi đĩa, khác biệt có thể thấy rõ

4. Pipe hoạt động với lưu trữ cloud

  • tải xuống bằng wget -O - hoặc aws s3 cp - s3://...
  • truyền trực tiếp từ S3 mà không cần bản sao cục bộ
  • tải kết quả lên trong khi xử lý
  • kết hợp với tee để vừa xử lý vừa tải lên

5. Các workflow thực tế dùng pipe

  • tiến trình BWA_MEM của Sarek pipe bwa mem | samtools sort
  • đây là mẫu hình phổ biến ở quy mô lớn hơn
  • Nextflow thêm lập lịch và xử lý lỗi lên trên
  • pipe và Nextflow không phải hai lựa chọn loại trừ nhau; chúng được dùng cùng nhau

6. Những mẫu hình dùng nhiều nhất

Mẫu hình Trường hợp dùng Lệnh
Chuỗi đơn giản Xử lý tuần tự cmd1 | cmd2 | cmd3
Phân nhánh Nhiều đầu ra từ một đầu vào cmd1 | tee >(cmd2) | cmd3
Tải xuống + xử lý Tệp từ xa không cần lưu trữ wget -O - url | gunzip | process
Tải lên + nén Trực tiếp lên lưu trữ cloud process | gzip | aws s3 cp -
An toàn lỗi Bắt lỗi trong pipe set -o pipefail
Xử lý song song Mở rộng qua nhiều core/máy input | parallel 'process'

7. Nơi pipe hữu ích, và nơi không phù hợp

Nơi pipe hữu ích:

  • tập dữ liệu lớn nơi I/O là nút thắt
  • workflow cloud nơi đĩa cục bộ đắt đỏ
  • theo dõi các phân tích chạy dài
  • chuỗi xử lý tuyến tính
  • script tiến trình Nextflow nối công cụ bên trong

Nơi pipe ít phù hợp:

  • workflow phân nhánh nhiều đường
  • trường hợp lỗi cần chạy lại từ giữa
  • dữ liệu phải đọc nhiều lần
  • trường hợp cần kiểm tra kỹ các kết quả trung gian

8. Các công cụ nên biết

Terminal window
set -o pipefail # Error handling
tee # Branching
pv # Progress monitoring
process substitution: >(cmd) # Streaming to files
AWS S3 pipes: aws s3 cp - s3://... # Cloud integration
GNU parallel # Scale across cores

Đôi lời kết

Unix pipe là một cú pháp nhỏ nhưng có ảnh hưởng lớn trong bioinformatics. Với một lệnh, nó giảm bớt mã và tránh một tệp tạm; ở quy mô lớn, nó có thể là khác biệt giữa một pipeline vừa với dung lượng đĩa hiện có và một pipeline thì không, và nó xuất hiện bên trong hầu hết các hệ thống workflow thực tế. Hiểu cách kernel quản lý file descriptor, đệm dữ liệu và áp dụng back pressure là một nền tảng hữu ích để viết những pipeline dễ suy luận hơn.

Tài liệu tham khảo

Bài viết liên quan

Xem tất cả bài viết →