4 tháng 02, 2026

Một template workflow bioinformatics có thể tái sử dụng

Một template workflow bioinformatics có thể tái sử dụng

Bắt đầu một dự án bioinformatics mới thường có nghĩa là phải quyết định lại xem script đặt ở đâu, viết kiểm thử thế nào và cấu hình continuous integration ra sao. Mỗi dự án có xu hướng trả lời những câu hỏi đó theo một cách khác nhau, khiến việc tiếp nhận và bảo trì khó hơn.

Bài viết này mô tả một template workflow viết bằng Python mà chúng tôi dùng làm điểm khởi đầu (bioinfor-wf-template). Template cung cấp một cấu trúc nhất quán cho các app và workflow, một cách tiếp cận kiểm thử duy nhất (pytest), và một workflow CI chỉ chạy kiểm thử cho những tệp đã thay đổi. Nó hướng tới các dự án proof-of-concept; những nguyên tắc tương tự có thể áp dụng cho dự án Snakemake hoặc Nextflow bằng cơ chế kiểm thử gốc của chúng, và việc hỗ trợ các framework đó là một hướng mở rộng có thể có.

Vấn đề

Một vài khó khăn lặp lại ở nhiều dự án bioinformatics:

Không có cấu trúc chuẩn

  • script nằm ở những thư mục khác nhau giữa các dự án
  • ranh giới giữa app tái sử dụng và workflow tổ hợp không phải lúc nào cũng rõ
  • kiểm thử không có chỗ đặt rõ ràng

Kiểm thử thiếu đồng đều

  • kiểm thử đơn vị cho việc kiểm tra dữ liệu
  • kiểm thử end-to-end cần dữ liệu thật (hoặc gần thật)
  • các framework khác nhau đòi hỏi cách kiểm thử khác nhau
  • công cụ dựa trên container thêm một lớp nữa

CI/CD thiếu nhất quán

  • mỗi dự án tự viết workflow GitHub Actions của mình
  • không có quy ước chung về việc cần kiểm thử gì khi có thay đổi
  • mở rộng lên nhiều app và workflow trở nên khó khăn

Tiếp nhận tốn thời gian

  • thành viên mới mất thời gian để biết cách chạy kiểm thử
  • tài liệu nằm rải rác

Template

Template cung cấp:

  • một cấu trúc dự án nhất quán cho app, workflow và kiểm thử
  • một framework kiểm thử duy nhất (pytest) cho mọi module
  • CI chỉ chạy kiểm thử cho những tệp đã thay đổi
  • tích hợp Docker cho môi trường công cụ tái lập
  • kiểm thử cục bộ bằng một lệnh với act
  • type hints và kiểm tra đầu vào
  • một cấu trúc dùng được cho vài app hoặc vài chục app

Phần 1: Cấu trúc

Bố cục kho

bioinfor-wf-template/
├── apps/ # Individual bioinformatics tools
│ ├── fastqc/ # Quality control
│ │ ├── main.py # Implementation
│ │ ├── tests/ # Unit + E2E tests
│ │ │ ├── test_fastq_in_pairs.py # Unit tests
│ │ │ └── test_e2e.py # Integration tests
│ │ └── Makefile # Local testing commands
│ ├── multiqc/ # Aggregation
│ │ ├── main.py
│ │ ├── tests/
│ │ └── Makefile
│ └── [your-tool]/ # Add more tools
│
├── workflows/ # Composed pipelines
│ ├── qc/ # Quality control workflow
│ │ ├── main.py # Orchestrates apps
│ │ ├── tests/
│ │ └── Makefile
│ └── [your-pipeline]/ # Add more workflows
│
├── .github/
│ └── workflows/
│ └── tests.yaml # GitHub Actions CI/CD
│
├── conftest.py # Shared pytest configuration
├── pytest.ini # Pytest settings
├── requirements.txt # Dependencies
├── pixi.toml # (Optional) Reproducible environment
└── README.md

Ý chính là app là những khối xây dựng tái sử dụng, còn workflow tổ hợp chúng thành pipeline.

App ví dụ: FastQC quality control

apps/fastqc/main.py

def validate_fastq_files(fastq1: str, fastq2: str):
"""Validate paired FASTQ files match naming convention."""
base1 = os.path.basename(fastq1)
base2 = os.path.basename(fastq2)
expected_base2 = base1.replace("_R1_", "_R2_")
if base2 != expected_base2:
raise ValueError(f"Expected '{expected_base2}', got '{base2}'")
def run_fastqc(fastq1: str, fastq2: str, output_dir: str):
"""Run FastQC on paired FASTQ files using Docker."""
validate_fastq_files(fastq1, fastq2)
cmd = [
"docker", "run", "--rm",
"-v", f"{cwd}:{cwd}",
"biocontainers/fastqc:v0.11.9_cv8",
"fastqc", fastq1, fastq2, "--outdir", output_dir
]
subprocess.run(cmd, check=True)

Các mẫu hình ở đây là kiểm tra trước khi thực thi, cô lập bằng Docker để tái lập, chữ ký hàm rõ ràng, và type hints cho trình soạn thảo.

Chiến lược kiểm thử: đơn vị và end-to-end

apps/fastqc/tests/test_fastq_in_pairs.py (kiểm thử đơn vị)

def test_validate_fastq_files_valid_pair():
"""Test that valid paired files pass validation."""
fastq1 = "/path/sample_R1_001.fastq.gz"
fastq2 = "/path/sample_R2_001.fastq.gz"
validate_fastq_files(fastq1, fastq2) # Should not raise
def test_validate_fastq_files_invalid_pair():
"""Test that mismatched files raise error."""
fastq1 = "/path/sample_R1_001.fastq.gz"
fastq2 = "/path/sample_R3_001.fastq.gz"
with pytest.raises(ValueError):
validate_fastq_files(fastq1, fastq2)

apps/fastqc/tests/test_e2e.py (kiểm thử end-to-end)

@pytest.fixture
def dummy_fastq_files():
"""Create minimal FASTQ files for testing."""
fastq1.write_text("@SEQ_ID\nGATTT...\n+\nIIIII...\n")
fastq2.write_text("@SEQ_ID\nGATTT...\n+\nIIIII...\n")
return str(fastq1), str(fastq2)
@pytest.mark.skipif(
not subprocess.run(["docker", "--version"]).returncode == 0,
reason="Docker is not available"
)
def test_run_fastqc_e2e(dummy_fastq_files, data_dir):
"""Test actual FastQC execution with real (dummy) data."""
fastq1, fastq2 = dummy_fastq_files
run_fastqc(fastq1, fastq2, str(data_dir / "results"))
# Assert output files exist

Hai lớp kiểm thử phục vụ những mục đích khác nhau:

  • Kiểm thử đơn vị (test_fastq_in_pairs.py): nhanh, không cần Docker
  • Kiểm thử end-to-end (test_e2e.py): chậm hơn, cần Docker, chạy chính các công cụ

Phần 2: Kiểm thử cục bộ

Thiết lập nhanh

Terminal window
# Clone the template
git clone git@github.com:riverxdata/bioinfor-wf-template.git my-pipeline
cd my-pipeline
# Install dependencies
pip install -r requirements.txt
# Run all tests locally
pytest -v
# Or with Pixi (recommended)
pixi global install act
pixi run tests

Kiểm thử bằng make

Mỗi app và workflow có một Makefile để các lệnh nhất quán:

apps/fastqc/Makefile

.PHONY: unittest e2e
unittest:
pytest -v -k "not e2e" tests/
e2e:
pytest -v -k "e2e" tests/

Chạy kiểm thử cục bộ:

Terminal window
# Unit tests only (fast - 10 seconds)
make -C apps/fastqc unittest
# End-to-end tests (slower - 2 minutes)
make -C apps/fastqc e2e
# All tests
make -C apps/fastqc unittest e2e

Chạy kiểm thử cho toàn bộ workflow:

Terminal window
# All unit tests in all apps
for app in apps/*; do make -C $app unittest; done
# All E2E tests in all workflows
for workflow in workflows/*; do make -C $workflow e2e; done

Phần 3: CI/CD với GitHub Actions

Tệp workflow

.github/workflows/tests.yaml chỉ chạy kiểm thử cho những tệp đã thay đổi:

jobs:
unittest_and_e2e:
runs-on: ubuntu-latest
steps:
# 1. Detect changed files
- uses: tj-actions/changed-files@v46.0.5
id: changed-files
with:
files: apps/**
base: ${{ github.event.pull_request.base.ref }}
# 2. Run unit tests for changed apps
- name: Unit tests
if: steps.changed-files.outputs.all_changed_files != ''
run: |
for app in ${{ steps.changed-files.outputs.all_changed_files }}; do
make -C $app unittest
done
# 3. Run E2E tests for changed apps
- name: E2E tests
if: steps.changed-files.outputs.all_changed_files != ''
run: |
for app in ${{ steps.changed-files.outputs.all_changed_files }}; do
make -C $app e2e
done
# 4. Run all workflow E2E tests
- name: Workflow tests
run: |
for workflow in workflows/*; do
make -C $workflow e2e
done

Cách nó hoạt động

Sửa apps/fastqc/main.py

GitHub detects change → Run only fastqc tests

Sửa workflows/qc/main.py

GitHub detects change → Run qc workflow E2E
Includes fastqc + multiqc + orchestration

Sửa README.md

GitHub detects no code changes → Skip all tests

Việc chỉ chạy những kiểm thử bị ảnh hưởng là điều giữ cho thời gian CI tỉ lệ với kích thước thay đổi, thay vì kích thước kho.

Phần 4: App và mẫu hình ví dụ

Template dùng được cho bất kỳ công cụ bioinformatics nào được bọc trong Python. Một vài mẫu hình:

Mẫu hình 1: bọc công cụ dựa trên Docker

Hầu hết công cụ bioinformatics được đóng gói trong container. Bọc chúng trong Python giữ một quy ước gọi duy nhất:

apps/bowtie2/main.py
def run_bowtie2_alignment(reference, fastq1, fastq2, output_bam):
"""Align reads using Bowtie2 via Docker."""
cmd = [
"docker", "run", "--rm",
"-v", f"{Path.cwd()}:{Path.cwd()}",
"biocontainers/bowtie2:v2.5.1_cv1",
"bowtie2-build", reference, "index",
"-x", "index", "-1", fastq1, "-2", fastq2, "-S", output_bam
]
subprocess.run(cmd, check=True)
# apps/bowtie2/tests/test_e2e.py
def test_bowtie2_alignment_e2e(reference_fasta, fastq_files):
"""Test alignment with real (dummy) data."""
run_bowtie2_alignment(*reference_fasta, *fastq_files, "output.bam")
assert Path("output.bam").exists()

Mẫu hình 2: bọc thư viện Python

Một số công cụ có gói Python, có thể dùng trực tiếp:

apps/cutadapt/main.py
import cutadapt
def trim_adapters(fastq1, fastq2, output_dir):
"""Trim adapters from FASTQ files."""
Path(output_dir).mkdir(exist_ok=True)
# Use cutadapt Python API
adapter = "AGATCGGAAGAGC" # Common Illumina adapter
results = cutadapt.main([
"-a", adapter,
"-A", adapter,
"-o", f"{output_dir}/trimmed_R1.fastq.gz",
"-p", f"{output_dir}/trimmed_R2.fastq.gz",
fastq1, fastq2
])
return results
# apps/cutadapt/tests/test_e2e.py
def test_trim_adapters_e2e(fastq_files, tmp_path):
"""Test adapter trimming."""
trim_adapters(fastq_files[0], fastq_files[1], str(tmp_path))
assert (tmp_path / "trimmed_R1.fastq.gz").exists()
assert (tmp_path / "trimmed_R2.fastq.gz").exists()

Mẫu hình 3: phân tích tự viết

Mã phân tích tự viết nằm trong cùng cấu trúc:

apps/gene_counter/main.py
import pandas as pd
def count_genes(bam_file, annotation_gtf, output_csv):
"""Count reads per gene from BAM file."""
# Load annotation
gtf = pd.read_csv(annotation_gtf, sep="\t", comment="#")
# Count using samtools + Python
import pysam
bam = pysam.AlignmentFile(bam_file)
counts = {}
for read in bam:
gene = read.get_tag("XG") if read.has_tag("XG") else "unknown"
counts[gene] = counts.get(gene, 0) + 1
# Save results
df = pd.DataFrame(list(counts.items()), columns=["gene", "count"])
df.to_csv(output_csv, index=False)
return df
# apps/gene_counter/tests/test_e2e.py
def test_gene_counting_e2e(bam_file, annotation_gtf, tmp_path):
"""Test gene counting."""
output_csv = tmp_path / "counts.csv"
count_genes(bam_file, annotation_gtf, str(output_csv))
results = pd.read_csv(output_csv)
assert len(results) > 0
assert "count" in results.columns

Phần 5: Thêm app và workflow mới

Template cho một app Python mới

Tạo cấu trúc:

Terminal window
mkdir -p apps/myapp/tests
touch apps/myapp/__init__.py
touch apps/myapp/main.py
touch apps/myapp/tests/test_unit.py
touch apps/myapp/tests/test_e2e.py
touch apps/myapp/Makefile

apps/myapp/main.py

import subprocess
from pathlib import Path
def validate_input(input_file: str):
"""Validate input data format."""
if not Path(input_file).exists():
raise FileNotFoundError(f"Input file not found: {input_file}")
def run_myapp(input_file: str, output_dir: str):
"""Run my bioinformatics tool."""
Path(output_dir).mkdir(parents=True, exist_ok=True)
cmd = [
"docker", "run", "--rm",
"-v", f"{Path.cwd()}:{Path.cwd()}",
"myregistry/myapp:latest",
"myapp", input_file, "--output", output_dir
]
subprocess.run(cmd, check=True)

apps/myapp/tests/test_unit.py

from apps.myapp.main import validate_input
import pytest
def test_validate_input_exists():
"""Test validation of existing file."""
# Create temp file
with open("/tmp/test_input.txt", "w") as f:
f.write("test data")
# Should not raise
validate_input("/tmp/test_input.txt")
def test_validate_input_missing():
"""Test validation of missing file."""
with pytest.raises(FileNotFoundError):
validate_input("/nonexistent/file.txt")

apps/myapp/tests/test_e2e.py

import pytest
from pathlib import Path
import subprocess
from apps.myapp.main import run_myapp
@pytest.mark.skipif(
not subprocess.run(["docker", "--version"]).returncode == 0,
reason="Docker not available"
)
def test_run_myapp_e2e(tmp_path):
"""Test complete myapp execution."""
input_file = tmp_path / "input.txt"
input_file.write_text("test data")
output_dir = tmp_path / "output"
run_myapp(str(input_file), str(output_dir))
# Verify output
assert output_dir.exists()
assert (output_dir / "result.txt").exists()

apps/myapp/Makefile

.PHONY: unittest e2e
unittest:
pytest -v -k "not e2e" tests/
e2e:
pytest -v -k "e2e" tests/

Template cho một workflow mới

Tạo cấu trúc:

Terminal window
mkdir -p workflows/mypipeline/tests
touch workflows/mypipeline/main.py
touch workflows/mypipeline/tests/test_e2e.py
touch workflows/mypipeline/Makefile

workflows/mypipeline/main.py

import argparse
from apps.myapp.main import run_myapp
from apps.anotherap.main import run_anotherap
def run_mypipeline(input_file, output_dir):
"""Compose myapp and anotherap into a pipeline."""
# Step 1: Run first app
intermediate_dir = f"{output_dir}/intermediate"
run_myapp(input_file, intermediate_dir)
# Step 2: Run second app with output from first
final_dir = f"{output_dir}/final"
run_anotherap(f"{intermediate_dir}/result.txt", final_dir)
print(f"Pipeline complete. Results in: {final_dir}")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="My bioinformatics pipeline")
parser.add_argument("input_file")
parser.add_argument("output_dir")
args = parser.parse_args()
run_mypipeline(args.input_file, args.output_dir)

workflows/mypipeline/tests/test_e2e.py

import subprocess
from pathlib import Path
from workflows.mypipeline.main import run_mypipeline
def test_mypipeline_e2e(tmp_path):
"""Test complete pipeline execution."""
input_file = tmp_path / "input.txt"
input_file.write_text("test data")
output_dir = tmp_path / "output"
run_mypipeline(str(input_file), str(output_dir))
# Verify all outputs exist
assert (output_dir / "intermediate").exists()
assert (output_dir / "final").exists()

workflows/mypipeline/Makefile

.PHONY: e2e
e2e:
pytest -v -k "e2e" tests/

Phần 6: Môi trường tái lập với Pixi

Để tái lập môi trường, có thể thêm Pixi vào template:

pixi.toml

[project]
name = "bioinfor-wf"
version = "0.1.0"
channels = ["conda-forge", "bioconda"]
[dependencies]
python = "3.12"
pytest = ">=7.0"
numpy = ">=1.24"
pandas = ">=1.5"
[tasks]
test = "pytest -v"
unittest = "pytest -v -k 'not e2e'"
e2e = "pytest -v -k 'e2e'"
ci = "act push"
[environments]
test = { channels = ["conda-forge", "bioconda", "nvidia"], features = ["gpu"] }
dev = { features = ["dev"] }

Cách dùng:

Terminal window
# Install dependencies
pixi install
# Run tests
pixi run test
# Run GitHub Actions locally
pixi run ci

Hiệu quả kỳ vọng

Bảng dưới đây mang tính minh hoạ, không phải một kết quả đo được; con số thực tế phụ thuộc vào nhóm và dự án.

Khía cạnh Trước Sau
Thời gian tiếp nhận thường tính bằng ngày khoảng nửa ngày
Thiết lập kiểm thử khác nhau theo dự án pytest chuẩn hoá
Thiết lập CI/CD viết từ đầu sao chép workflow
Chạy kiểm thử cục bộ "Làm sao để kiểm thử cái này?" make -C apps/fastqc unittest
Tính nhất quán của mã tuỳ nơi type hints, kiểm tra đầu vào
Tạo app mới sao chép mã có sẵn dùng cấu trúc template
Tái sử dụng app script dùng một lần thành phần mô-đun
Tiếp nhận trong nhóm mất nhiều thời gian cấu trúc kèm tài liệu

Thực hành khi áp dụng template

1. Mỗi hàm một mục đích

Mỗi hàm nên làm một việc:

# Avoid: multiple responsibilities
def process_fastq_and_align(fastq1, fastq2, ref, output):
validate_fastq(fastq1, fastq2)
align(fastq1, fastq2, ref, output)
quality_check(output)
# Prefer: single responsibility
def validate_fastq(fastq1, fastq2): ...
def run_alignment(fastq1, fastq2, ref, output): ...
def quality_check(bam_file): ...

2. Kiểm tra đầu vào

def run_analysis(input_file: str):
"""Validate before processing."""
input_path = Path(input_file)
if not input_path.exists():
raise FileNotFoundError(f"Input file not found: {input_file}")
if input_path.stat().st_size == 0:
raise ValueError("Input file is empty")

3. Dùng type hints

from pathlib import Path
from typing import List, Tuple
def process_samples(samples: List[str], output_dir: str) -> Tuple[Path, Path]:
"""Type hints help catch errors early."""
...

4. Tách kiểm thử đơn vị và end-to-end

# Unit: Fast, no Docker needed
def test_validation():
assert validate(valid_input) == True
# E2E: Slow, includes Docker
@pytest.mark.skipif(no_docker, reason="Docker required")
def test_full_workflow_e2e():
...

5. Ghi lại các phụ thuộc

Giữ requirements.txt được cập nhật:

pytest>=7.0
docker>=6.0
numpy>=1.24
pandas>=1.5

Một số mẫu hình thường gặp

Xử lý lỗi

import subprocess
import sys
def run_command(cmd: List[str]) -> bool:
"""Run shell command with proper error handling."""
try:
result = subprocess.run(cmd, check=True, capture_output=True, text=True)
return True
except subprocess.CalledProcessError as e:
print(f"Error: Command failed with exit code {e.returncode}")
print(f"stderr: {e.stderr}")
sys.exit(1)

Ghi log

import logging
logger = logging.getLogger(__name__)
def process_pipeline(samples: List[str]):
"""Process with logging."""
for i, sample in enumerate(samples, 1):
logger.info(f"Processing sample {i}/{len(samples)}: {sample}")
# Process...
logger.info(f"✓ Completed {sample}")

Tệp tạm

from pathlib import Path
import tempfile
def run_with_temp_files(input_file: str) -> str:
"""Create and clean temporary files automatically."""
with tempfile.TemporaryDirectory() as tmp_dir:
tmp_path = Path(tmp_dir)
# Work with temp files
intermediate = tmp_path / "intermediate.txt"
# ... process ...
# Copy final result to output
final_output = "final_result.txt"
# ... copy ...
# Temp dir automatically cleaned up when exiting with block
return final_output

Mở rộng lên nhiều app và workflow

Khi số lượng app tăng, nhóm chúng theo lĩnh vực giúp kho dễ điều hướng hơn:

Tổ chức thư mục

apps/
├── alignment/ # Group by domain
│ ├── bowtie2/
│ ├── bwa/
│ └── hisat2/
├── quality_control/
│ ├── fastqc/
│ ├── multiqc/
│ └── qualimap/
└── variant_calling/
├── gatk/
└── samtools/
workflows/
├── rnaseq/
├── wgs/
├── amplicon/
└── metagenomics/

Kiểm thử tự động

#!/bin/bash
# test_all.sh - Run all tests
failed_tests=0
total_tests=0
for app in apps/*/*/; do
if [ -f "$app/Makefile" ]; then
total_tests=$((total_tests + 1))
if ! make -C "$app" unittest; then
failed_tests=$((failed_tests + 1))
echo "❌ Failed: $app"
else
echo "✓ Passed: $app"
fi
fi
done
echo "Tests: $((total_tests - failed_tests))/$total_tests passed"
exit $failed_tests

Tài liệu

Một CONTRIBUTING.md trung tâm giúp quy trình dễ tìm thấy:

## Adding a New App
1. Create directory: `mkdir -p apps/category/myapp/tests`
2. Copy template: `cp -r apps/fastqc/* apps/category/myapp/`
3. Edit `main.py` with your logic
4. Write tests in `tests/`
5. Update `README.md`
6. Create PR
## Adding a New Workflow
1. Create directory: `mkdir -p workflows/mypipeline/tests`
2. Create `main.py` that composes apps
3. Write E2E test in `tests/`
4. Add to `.github/workflows/tests.yaml`

Tóm lại

  1. Một cấu trúc nhất quán rút ngắn thời gian thiết lập cho một dự án mới.
  2. App có thể tái sử dụng, và workflow tổ hợp chúng.
  3. Kiểm thử đơn vị và end-to-end đều được tự động hoá, trong hai lớp riêng.
  4. CI chỉ chạy những kiểm thử bị ảnh hưởng bởi thay đổi, giúp nó nhanh.
  5. Docker và Pixi giữ môi trường tái lập giữa các máy.

Bắt đầu

Terminal window
# Clone the template
git clone git@github.com:riverxdata/bioinfor-wf-template.git my-analysis
# Install dependencies
cd my-analysis
pip install -r requirements.txt
# Run tests
pytest -v
# Or with Pixi
pixi global install act
pixi run test
# Or locally simulate GitHub Actions
act push

Tài liệu tham khảo

Bài viết liên quan

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