当不需要通配符的某些特定组合时,如何在snakemake中使用expand?

bli*_*bli 3 python wildcard python-itertools higher-order-functions snakemake

假设我有以下文件,我想使用snakemake自动对其进行一些处理:

test_input_C_1.txt
test_input_B_2.txt
test_input_A_2.txt
test_input_A_1.txt
Run Code Online (Sandbox Code Playgroud)

以下snakefile用于expand确定所有可能的最终结果文件:

rule all:
    input: expand("test_output_{text}_{num}.txt", text=["A", "B", "C"], num=[1, 2])

rule make_output:
    input: "test_input_{text}_{num}.txt"
    output: "test_output_{text}_{num}.txt"
    shell:
        """
        md5sum {input} > {output}
        """
Run Code Online (Sandbox Code Playgroud)

执行上面的snakefile会导致以下错误:

test_input_C_1.txt
test_input_B_2.txt
test_input_A_2.txt
test_input_A_1.txt
Run Code Online (Sandbox Code Playgroud)

其中的原因错误是expand使用itertools.product引擎盖下产生的通配符的组合,其中一些发生在对应于丢失的文件。

如何过滤掉不想要的通配符组合?

bli*_*bli 5

expand函数接受第二个可选的非关键字参数,以使用与默认参数不同的函数来组合通配符值。

可以itertools.product通过将其包装在更高阶的生成器中来创建的过滤版本,该生成器检查产生的通配符组合是否不在预先建立的黑名单中:

from itertools import product

def filter_combinator(combinator, blacklist):
    def filtered_combinator(*args, **kwargs):
        for wc_comb in combinator(*args, **kwargs):
            # Use frozenset instead of tuple
            # in order to accomodate
            # unpredictable wildcard order
            if frozenset(wc_comb) not in blacklist:
                yield wc_comb
    return filtered_combinator

# "B_1" and "C_2" are undesired
forbidden = {
    frozenset({("text", "B"), ("num", 1)}),
    frozenset({("text", "C"), ("num", 2)})}

filtered_product = filter_combinator(product, forbidden)

rule all:
    input:
        # Override default combination generator
        expand("test_output_{text}_{num}.txt", filtered_product, text=["A", "B", "C"], num=[1, 2])

rule make_output:
    input: "test_input_{text}_{num}.txt"
    output: "test_output_{text}_{num}.txt"
    shell:
        """
        md5sum {input} > {output}
        """
Run Code Online (Sandbox Code Playgroud)

可以从配置文件中读取缺少的通配符组合。

这是json格式的示例:

{
    "missing" :
    [
        {
            "text" : "B",
            "num" : 1
        },
        {
            "text" : "C",
            "num" : 2
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

forbidden集合将在snakefile中读取如下:

forbidden = {frozenset(wc_comb.items()) for wc_comb in config["missing"]}
Run Code Online (Sandbox Code Playgroud)