InputFunctionException 与 KeyError

InputFunctionException with KeyError

假设我在 python 中有一个代码生成字典作为结果。我需要将字典的每个元素写在一个单独的文件夹中,稍后将被 snakemake 中的其他规则集使用。 我写了下面的代码但是它不起作用!

simulation_index_dict={1:'test1',2:'test2'}


def indexer(wildcards):
    return(simulation_index_dict[wildcards.simulation_index])

rule SimulateAll:
       input:
        expand("{simulation_index}/ProteinCodingGene/alfsim.drw",simulation_index=simulation_index_dict.keys())



rule simulate_phylogeny:
    output:
        ProteinCodingGeneParams=expand("{{simulation_index}}/ProteinCodingGene/alfsim.drw"),
        IntergenicRegionParams=expand("{{simulation_index}}/IntergenicRegions/dawg_IR.dawg"),
        RNAGeneParams=expand("{{simulation_index}}/IntergenicRegions/dawg_RG.dawg"),
        RepeatRegionParams=expand("{{simulation_index}}/IntergenicRegions/dawg_RR.dawg"),
    params:
        value= indexer,
    shell:
        """
        echo {params.value} > {output.ProteinCodingGeneParams}
        echo {params.value} > {output.IntergenicRegionParams}
        echo {params.value} > {output.RNAGeneParams}
        echo {params.value} > {output.RepeatRegionParams}
        """

它 return 的错误是:

InputFunctionException in line 14 of /$/test.snake:
KeyError: '1'
Wildcards:
simulation_index=1

似乎问题出在规则的参数部分,因为删除它会消除错误,但我无法弄清楚参数有什么问题!

解决方案:使用字符串作为字典键

可以从错误消息 (KeyError: '1') 中猜测字典中的某些查询在 '1' 的键上出错,而​​该键恰好是一个字符串。

但是,indexer "params" 函数中使用的字典以整数作为键。

显然,使用字符串而不是整数作为此 simulation_index_dict 字典的键可以解决问题(请参阅问题下方的评论)。

原因:工作流推理过程中类型信息丢失

问题的原因可能是 SimulateAllexpandsimulation_index 参数赋值的整数性质(继承自 simulation_index_dict.keys())在工作流推理的后续步骤中 "forgotten"。

实际上,expand 会生成一个字符串列表,然后将其与其他规则(也包含在字符串中)的输出进行匹配,以推断出 wildcards 的值属性(也是字符串)。因此,当执行indexer函数时,wildcards.simulation_index是一个字符串,这会导致在simulation_index_dict.

中查找时出现KeyError