filter secondary alignments using pysam I am new to python and trying to learn. The below is an attempt to filter out secondary reads in a bam using pysam. I ran mark duplicates and got an error on several bam files due to secondary alignments. I added comments to each line to illustrate my thought process.  Thank you :).

The specific mark duplicates error:

Value was put into PairInfoMap more than once


Here is the script:

#! /usr/bin/python  ## call python script
import sys ## import python system functions
import pysam  ## import module

bam = pysam.AlignmentFile(*.bam, "rb")  ## open bam and read
click.echo("Reading BAM file")  ## output message
for read in bam:  ## start loop and iterate over each bam
    if read.is_secondary=true  ## not the primary alignment
    if read.has_tag('XS')  ## look for Secondary Alignment Score tag
        XS = read.get_tag('XS')  ## read and store AS value
    if read.has_tag('AS')  ## look for Alignment Score tag
        AS = read.get_tag('AS')  ## read and store value os XS tag  
    if AS &lt; XS  ## Alignment score less then 
        read.write(read)  ## only print primary alignments
bam.close()  ## end processing
Quick look at your script suggests that you are comparing the XS and AS from different reads. I would recommend removing the continue from the read.has_tag('XS') continue block.

I think that if you filter out is_secondary and is_supplementary you don't need to do the XS to AS comparison assuming whatever generated for BAM did so correctly.

for read in bam.fetch()  
    if read.is_secondary=true  
        continue
    if read.has_tag('XS') &lt;- This block stores XS and then moves on to the next read
        XS = read.get_tag('XS')  
        continue 
    if read.has_tag('AS') 
        AS = read.get_tag('AS')  
    if AS &lt; XS  &lt;- This block compares the AS of the current read to the XS of the previous read that had one.
        read.write(read)  
bam.close()