Snakemake提取fastq输入文件名片段生成简化输出文件名的问题求助
问题1:expand实现同索引配对的方法
Snakemake的expand函数内置了zip参数,设置为zip=True即可实现多列表同索引元素一一配对,不会生成笛卡尔积。
针对你方案二的场景,修改写法如下即可:
ID = ["1000_John","1200_Smith"] INFO = ["brain_1-hiseq_2500-LAB_KA-","Liver_5-Novaseq_6000-LAB_RH"] # 同索引配对生成R1/R2文件路径 f1 = expand("start-{sample}_{info}-end_R1.fastq.gz", sample=ID, info=INFO, zip=True) f2 = expand("start-{sample}_{info}-end_R2.fastq.gz", sample=ID, info=INFO, zip=True)
问题2:方案一的修复方法
你方案一的报错核心原因是find_fastq函数的通配符匹配规则错误:你当前的匹配规则为f"{wildcards.sample}*.fastq.gz",但所有fastq文件前缀都是start-,导致匹配不到任何文件,返回空列表,因此bwa命令没有传入fastq参数。另外shell命令中重复写了两次{input.fastqs}属于冗余错误,不需要重复输入。
修正后的完整代码如下:
import pathlib indir = pathlib.Path("FASTQ/chr1/") paths = indir.glob("start-*R?.fastq.gz") # 提取Number_NAME格式的样本ID SAMPLES = set([x.stem.split("-")[1] for x in paths]) rule all: input: expand("output/{sample}_mapped.bam", sample=SAMPLES) def find_fastq(wildcards): # 补全start-前缀,匹配对应样本的R1/R2文件 fastqs = sorted(indir.glob(f"start-{wildcards.sample}*.fastq.gz")) # 可选加校验逻辑,确保匹配到2个双端文件 assert len(fastqs) == 2, f"样本{wildcards.sample}匹配到{len(fastqs)}个fastq文件,应为2个" return [str(f) for f in fastqs] rule bwa: input: fastqs = find_fastq output: mapped = "output/{sample}_mapped.bam" params: ref = "ref.fa" threads: 8 # 可选配置线程数,提升运行效率 shell: "bwa mem -t {threads} {params.ref} {input.fastqs} | samtools sort -@ {threads} -o {output.mapped} -"
如果想要更稳妥的方案,也可以提前构造样本ID到R1/R2路径的映射字典,避免运行时动态匹配路径的不确定性:
import pathlib indir = pathlib.Path("FASTQ/chr1/") # 构造样本ID到R1/R2的映射 sample_fq_map = {} for fq in indir.glob("*_R1.fastq.gz"): sample_id = fq.stem.split("-")[1] r1 = str(fq) r2 = r1.replace("_R1.fastq.gz", "_R2.fastq.gz") assert pathlib.Path(r2).exists(), f"样本{sample_id}的R2文件不存在" sample_fq_map[sample_id] = [r1, r2] SAMPLES = sample_fq_map.keys() rule all: input: expand("output/{sample}_mapped.bam", sample=SAMPLES) rule bwa: input: fastqs = lambda wildcards: sample_fq_map[wildcards.sample] output: mapped = "output/{sample}_mapped.bam" params: ref = "ref.fa" threads: 8 shell: "bwa mem -t {threads} {params.ref} {input.fastqs} | samtools sort -@ {threads} -o {output.mapped} -"
内容的提问来源于stack exchange,提问作者RAHenriksen
相关产品推荐
相关产品推荐

