当未在输出文件中使用时,从输入文件中获取通配符



我有一个蛇形规则,每个研究将几个结果文件聚合到一个文件中。因此,为了让它更容易理解;我有两个角色["big","mall"],每个角色为5项研究["a","b","c","d","e"]生成数据,每个研究生成3个输出文件,每个表型一个["xxx","yyy","zzz"]。现在我想要的是一个规则,将每个研究的表型结果汇总到每个研究的一个摘要文件中(因此将表型合并到一个表中(。在merge_results规则中,我为该规则提供了一个文件列表(每个研究和角色(,并使用panda框架聚合这些文件,然后将结果作为单个文件输出。

在合并结果的过程中,我需要迭代输入文件中的"pheno"变量。由于pheno在聚合输出文件中不需要,因此它不会在输出中提供,因此它在通配符对象中也不可用。现在,为了掌握这个现象,我解析了文件名来获取它,然而这一切都让人觉得很棘手,我怀疑这里有一些我没有正确理解的地方。有没有更好的方法从没有在输出文件中使用的输入文件中获取通配符?

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')

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

为了获得表型,如果你的for循环,你可以像现在这样解析文件名,也可以直接重建文件名,因为你知道pheno采用的不同值,你可以访问通配符:

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')

我不知道这是否比像您那样解析文件名更好。我想展示一下您可以在代码中访问通配符。无论哪种方式,都可以正确地定义输入和输出。

最新更新