Hello,

I have two questions regarding merging the `BAM` files. I have several libraries 4 lanes each. I demultiplexed, mapped against the reference genome, gave the read group name. I am using `snakemake` and `samtools merge`. 

These are my input files:

    Bob_1_CL1.bam
    Bob_2_CL1.bam
    Bob_3_CL1.bam
    Bob_4_CL1.bam
    John_1_CL40.bam
    John_2_CL40.bam
    John_3_CL40.bam
    John_4_CL40.bam

This is the code I am trying:

    library=["Bob", "John"]
    (LIBRARIES, SAMPLES)=glob_wildcards("path/to/{library}_1_{sample}.bam")
    
    rule all:
        input: 
            expand("{library}_{sample}.merged.bam", library=LIBRARIES, sample=SAMPLES)
    
    rule samtools merge:
        input:
            lane1="path/to/{library}_1_{sample}.bam",
            lane2="path/to/{library}_2_{sample}.bam",
            lane3="path/to/{library}_3_{sample}.bam",
            lane4="path/to/{library}_4_{sample}.bam"
        output:
            outf = "{library}_{sample}.merged.bam"
        threads: 4
        shell:
            """/Tools/samtools-1.10/samtools merge -@ {threads} {input.lane1} {input.lane2} {input.lane3} {input.lane4} -o {output.outf}"""

I am trying to merge 4 lanes in one single `BAM` file in order to get `Bob_CL1.merged.bam` and `John_CL40.merged.bam`, the problem is that CL number (NOTE: it is not always CL) is different for different libraries, i.e. CL1 is present in Bob, but not in John, and CL40 is for John but not in Bob. so it is giving me an error: 

    Missing input files for rule merge:
    John_1_CL1.bam
    John_2_CL1.bam
    John_3_CL1.bam
    John_4_CL1.bam
So my questions are:

1.  How to solve this?
2. Do I have to merge the lanes in one single `BAM` file prior to marking duplicates?
1. If you print the output of `expand("{library}_{sample}.merged.bam", library=LIBRARIES, sample=SAMPLES)` you'll see the problem. Replace `expand()` with something like `['{}_{}.merged.bam'.format(x, y) for x, y in zip(LIBRARIES, SAMPLES)]`
2. Yes, PCR duplicates are library-level events, so you need to process the entire library at once.