首页
/ Snakemake中如何从指定规则重新运行流程并忽略上游依赖

Snakemake中如何从指定规则重新运行流程并忽略上游依赖

2025-07-01 21:32:25作者:温玫谨Lighthearted

在Snakemake工作流管理系统中,有时我们需要从某个特定规则重新运行流程,而不关心其上游依赖是否完整。这种需求常见于以下场景:上游规则生成了大型临时文件,这些文件在流程完成后已被删除,但我们希望仅重新执行下游规则。

问题背景

假设我们有一个典型的Snakemake工作流,包含四个规则a、b、c、d,其中每个规则的输出都是下一个规则的输入:

rule a → rule b → rule c → rule d

当我们需要重新运行rule d时,默认情况下Snakemake会检查整个依赖链,包括rule b的输出。但如果rule b生成了大型临时文件且已被删除,这种检查就会导致问题。

解决方案:使用ancient函数

Snakemake提供了ancient()函数来解决这个问题。该函数可以标记输入文件,告诉Snakemake忽略这些文件的时间戳检查,仅检查文件是否存在。

基本用法

对于简单的规则依赖,可以直接在输入文件前使用ancient()

rule d:
    input:  
        ancient("path/to/output/of/c")
    output: 
        "path/to/output/of/d"
    shell:  
        "..."

复杂场景:动态输入文件列表

当rule d的输入是通过函数动态生成的文件列表时,可以将整个列表包裹在ancient()中:

def get_lst_of_c_output(wildcards):
    smpl_list = sample_list[wildcards.tag]
    return expand("path/to/output/of/c/{smpl}.txt", smpl=smpl_list)

rule d:
    input:  
        ancient(get_lst_of_c_output)
    output: 
        "path/to/output/of/d"
    shell:  
        "..."

重要注意事项

  1. rule all的输入:确保rule all仅依赖于最终输出文件(如rule d的输出),而不是中间文件。如果rule all依赖于中间文件,Snakemake仍会尝试重建这些文件。

  2. 命令行参数:运行时需要添加--rerun-triggers mtime参数,确保Snakemake仅检查文件存在性而不检查时间戳。

  3. 文件存在性:虽然ancient()跳过了时间戳检查,但输入文件必须实际存在,否则会报错。

实际应用示例

以下是一个完整的工作示例,展示了如何正确使用ancient()

rule all:
    input:
        "d/output.txt"

rule a:
    output:
        "a/output.txt"
    shell:
        "echo a > {output}"

rule b:
    input:
        rules.a.output
    output:
        "b/output.txt"
    shell:
        "echo b > {output}"

rule c:
    input:
        rules.b.output
    output:
        "c/{smpl}.txt"
    shell:
        "echo c > {output}"

def get_lst_of_c_output(wildcards):
    return expand("c/{smpl}.txt", smpl=range(3))

rule d:
    input:
        ancient(get_lst_of_c_output)
    output:
        "d/output.txt"
    shell:
        "echo d > {output}"

在这个例子中,即使删除了rule b的输出文件,只要rule c的输出文件存在,就可以直接运行rule d:

snakemake --rerun-triggers mtime

总结

通过使用ancient()函数,我们可以灵活控制Snakemake工作流的执行方式,在需要时跳过对上游依赖的检查。这种方法特别适用于处理大型中间文件的场景,可以显著提高工作流的执行效率。记住要正确设置rule all的依赖关系,并添加必要的命令行参数,才能确保这一机制正常工作。

登录后查看全文
热门项目推荐
相关项目推荐