You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Snakemake中复用规则处理独立文件与合并文件?

解决Snakemake规则复用问题:同时处理单个文件与合并文件

核心思路是泛化规则的输入匹配逻辑,把合并后的文件当成一个特殊的"样本",让原规则do_stuff_on_list既能匹配单个样本的输出,也能匹配合并后的文件,无需重复编写规则。

修改后的完整代码

config_file = {
    "result_files": [
        {
            "id": 0,
            "path": "/path/to/readonly/location/1.txt"
        },
        {
            "id": 8,
            "path": "/path/to/readonly/location/2.txt"
        },
        {
            "id": 4,
            "path": "/path/to/readonly/location/3.txt"
        }
    ]
}

SAMPLES = {str(x["id"]): x["path"] for x in config_file["result_files"]}
# 添加特殊的"merged"目标,代表合并后的文件
ALL_TARGETS = list(SAMPLES.keys()) + ["merged"]

rule all:
    input:
        "AAA_finalResult.txt"

rule create_list:
    input:
        sample_path = lambda wildcards: SAMPLES[wildcards.sample]
    output:
        "{sample}_mut_list.json"
    shell:
        "touch {output}"

rule merge_lists:
    input:
        expand(rules.create_list.output, sample=SAMPLES.keys())
    output:
        "merged_mut_list.json"
    shell:
        "touch {output}"

# 泛化规则输入,支持单个样本和合并文件
rule do_stuff_on_list:
    input:
        lambda wildcards: "merged_mut_list.json" if wildcards.sample == "merged" else f"{wildcards.sample}_mut_list.json"
    output:
        "{sample}_stuff.json"
    shell:
        "touch {output}"

rule merge_all_results:
    input:
        # 包含所有单个样本的处理结果和合并文件的处理结果
        expand(rules.do_stuff_on_list.output, sample=ALL_TARGETS),
    output:
        "AAA_finalResult.txt"
    shell:
        "touch {output}"

关键修改点说明

  • 新增ALL_TARGETS集合:把原有的样本ID和特殊值"merged"合并,统一作为do_stuff_on_list规则的处理目标。
  • 泛化do_stuff_on_list的输入:用lambda函数根据通配符sample的值动态匹配输入文件:
    • 当sample是普通样本ID时,匹配create_list生成的单个样本列表文件
    • 当sample是"merged"时,匹配merge_lists生成的合并列表文件
  • 更新merge_all_results的输入:将合并文件的处理结果也纳入最终合并范围,确保Snakemake会自动触发对合并文件的处理。

这个方案完全复用了原规则,逻辑简洁,符合Snakemake的依赖自动推导机制,不需要额外的冗余代码。

内容的提问来源于stack exchange,提问作者Plopp

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 13:24:56