不用于输出文件时从输入文件获取通配符

时间:2020-03-02 18:27:16

标签: snakemake

每个研究中,我都有一条蛇形规则,将多个结果文件聚合到一个文件中。因此,使其更易于理解;我有两个角色['big','small'],分别产生5个研究的数据['a','b','c','d','e'],每个研究产生3个输出文件,每个表型['xxx','yyy','zzz']一个。现在,我想要的是一个规则,将每个研究的表型结果汇总到每个研究的单个摘要文件中(因此将表型合并到一个表中)。在merge_results规则中,我为该规则提供文件列表(按研究和角色),并使用熊猫框架进行汇总,然后将结果作为单个文件吐出。

在合并结果的过程中,我需要对输入文件中的“ pheno”变量进行迭代。由于聚合输出文件中不需要pheno,因此输出中不提供pheno,因此通配符对象中也不提供pheno。现在,为了掌握现象,我分析了文件名以获取它,但是,这一切感觉都很hacky,我怀疑这里有些东西我不太了解。是否有更好的方法可以更好地从输出文件中未使用的输入文件中获取通配符?

runstudy = ['a','b','c','d','e']
runpheno = ['xxx','yyy','zzz']
runrole  = ['big','small']

rule all:
    input:
        expand(os.path.join(output, '{role}-additive', '{study}', '{study}-summary-merge.txt'), role=runrole, study=runstudy)

rule merge_results:
    input:
        expand(os.path.join(output, '{{role}}', '{{study}}', '{pheno}', '{pheno}.summary'), pheno=runpheno)
    output:
        os.path.join(output, '{role}', '{study}', '{study}-summary-merge.txt')
    run:
        import pandas as pd
        import os

        # Iterate over input files, read into pandas df
        tmplist = []
        for f in input:
            data = pd.read_csv(f, sep='\t')

            # getting the pheno from the input file and adding it to the data frame
            pheno = os.path.split(f)[1].split('.')[0]
            data['pheno'] = pheno

            tmplist.append(data)

        resmerged = pd.concat(tmplist)

        resmerged.to_csv(output, sep='\t')

1 个答案:

答案 0 :(得分:1)

您做对了!
您所在的行:
expand(os.path.join(output, '{{role}}', '{{study}}', '{pheno}', '{pheno}.summary'), pheno=runpheno)
您必须了解rolestudy是通配符。 pheno不是通配符,由expand函数的第二个参数设置。

要获取表型(如果您有for循环),您可以像正在做的那样解析文件名,也可以直接重构文件名,因为您知道表名需要不同的值,并且可以访问通配符:

run:
    import pandas as pd
    import os

    # Iterate over phenotypes, read into pandas df
    tmplist = []
    for pheno in runpheno:

        # conflicting variable name 'output' between a global variable and the rule variable here. Renamed global var outputDir for example 
        file = os.path.join(outputDir, wildcards.role, wildcards.study, pheno, pheno+'.summary')

        data = pd.read_csv(file, sep='\t')
        data['pheno'] = pheno

        tmplist.append(data)

    resmerged = pd.concat(tmplist)

    resmerged.to_csv(output, sep='\t')

我不知道这是否比解析文件名要好。我想表明您可以在代码中访问通配符。无论哪种方式,您都可以正确定义输入和输出。