侧边栏壁纸
  • 累计撰写 218 篇文章
  • 累计创建 59 个标签
  • 累计收到 5 条评论
HPC

Snakemake 笔记 - 通配符

barwe
2023-05-29 / 0 评论 / 0 点赞 / 815 阅读 / 1,859 字
温馨提示:
本文最后更新于 2023-06-07,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。

通配符

直接用例子来说明通配符如何使用。

加上我们需要使用 cat 命令将样本 a 的 fq1 文件的多个分段文件拼接在一起,即将 a.1-1.fq, a.1-2.fq, ... 拼接成 a.1.fq 文件。

最直接的,我们列举出每一个文件:

rule cat_fq:
    input:
        "fq/a.1-1.fq",
        "fq/a.1-2.fq"
    output:
        "output/a.1.fq"
    shell:
        "cat {input} > {output}"

假设我们现在还需要处理样本 b,显然再写一个 Snakefile 有失优雅。此时只需要将上述与样本名称相关的部分改成通配符即可:

rule cat_fq:
    input:
        "fq/{sample}.1-1.fq",
        "fq/{sample}.1-2.fq",
    output:
        "output/{sample}.1.fq",
    shell:
        "cat {input} > {output}"

这样通配符 sample 的值自动从 snakemake 命令指定的路径中获取。

现在我们只能处理某个样本的 fq1 序列,稍微修改一下就能兼容对 fq2 文文件的处理:

rule cat_fq:
    input:
        "fq/{sample}.{index}-1.fq",
        "fq/{sample}.{index}-2.fq",
    output:
        "output/{sample}.{index}.fq",
    shell:
        "cat {input} > {output}"

这里可能存在一个问题:如果 sample 名称里面带句号,例如 sample.a.1.fq,"{sample}.{index}.fq"就会产生歧义:

  • sample = "sample.a"; index = "1"
  • sample = "sample"; index = "a.1"

为此我们需要消除这种歧义,比如限定 index 只匹配一位数字:

rule cat_fq:
    input:
        "fq/{sample}.{index}-1.fq",
        "fq/{sample}.{index}-2.fq",
    output:
        "output/{sample}.{index,\d}.fq",
    shell:
        "cat {input} > {output}"

除了 {index, \d} 这种形式外,还可以单独在 widlcard_constraints 字段中设置:

rule cat_fq:
    input:
        "fq/{sample}.{index}-1.fq",
        "fq/{sample}.{index}-2.fq",
    output:
        "output/{sample}.{index,\d}.fq",
    wildcard_constraints:
        dataset="\d"
    shell:
        "cat {input} > {output}"

还可以全局设置:

wildcard_constraints:
    dataset="\d"

rule cat_fq:
    input:
        "fq/{sample}.{index}-1.fq",
        "fq/{sample}.{index}-2.fq",
    output:
        "output/{sample}.{index,\d}.fq",
    
    shell:
        "cat {input} > {output}"

输入文件如果有多个,可以使用列表推导式或者 expand 函数简化:

rule cat_fq:
    input:
        expand("fq/{{sample}}.{{index}}-{i}.fq", i=[1,2])
    output:
        "output/{sample}.{index,\d}.fq",
    shell:
        "cat {input} > {output}"

通配符在 input/output 字段里写成 {sample},在 shell 部分写成 {wildcards.sample}

0

评论区