<s> """<STR_LIT>""" <EOL> import os <EOL> import sys <EOL> import pysam <EOL> import ngsutils . bam <EOL> def usage ( msg = None ) : <EOL> if msg : <EOL> print msg <EOL> print __doc__ <EOL> print """<STR_LIT>""" <EOL> sys . exit ( <NUM_LIT:1> ) <EOL> def bam_best ( infile , outfile , failfile = None , tags = [ '<STR_LIT>' , '<STR_LIT>' ] , quiet = False ) : <EOL> inbam = pysam . Samfile ( infile , "<STR_LIT:rb>" ) <EOL> outbam = pysam . Samfile ( '<STR_LIT>' % outfile , "<STR_LIT:wb>" , template = inbam ) <EOL> if failfile : <EOL> failbam = pysam . Samfile ( '<STR_LIT>' % failfile , "<STR_LIT:wb>" , template = inbam ) <EOL> for reads in ngsutils . bam . bam_batch_reads ( inbam , quiet = quiet ) : <EOL> best_val = None <EOL> best_reads = [ ] <EOL> failed = [ ] <EOL> for read in reads : <EOL> if not read . is_unmapped : <EOL> tag_val = [ ] <EOL> for tag in tags : <EOL> val = float ( read . opt ( tag [ : <NUM_LIT:2> ] ) ) <EOL> if tag [ - <NUM_LIT:1> ] == '<STR_LIT:->' : <EOL> val = - val <EOL> tag_val . append ( val ) <EOL> if not best_val or tag_val > best_val : <EOL> if best_reads and failfile : <EOL> failed . extend ( best_reads ) <EOL> best_val = tag_val <EOL> best_reads = [ read ] <EOL> elif tag_val == best_val : <EOL> best_reads . append ( read ) <EOL> elif failfile : <EOL> failed . append ( read ) <EOL> for read in best_reads : <EOL> outbam . write ( read ) <EOL> if failfile : <EOL> for read in failed : <EOL> failbam . write ( read ) <EOL> outbam . close ( ) <EOL> os . rename ( '<STR_LIT>' % outfile , outfile ) <EOL> if failfile : <EOL> failbam . close ( ) <EOL> os . rename ( '<STR_LIT>' % failfile , failfile ) <EOL> if __name__ == '<STR_LIT:__main__>' : <EOL> infile = None <EOL> outfile = None <EOL> failfile = None <EOL> last = None <EOL> tags = [ ] <EOL> for arg in sys . argv [ <NUM_LIT:1> : ] : <EOL> if arg == '<STR_LIT>' : <EOL> usage ( ) <EOL> elif last == '<STR_LIT>' : <EOL> tags . append ( arg ) <EOL> last = None <EOL> elif last == '<STR_LIT>' : <EOL> failfile = arg <EOL> last = None <EOL> elif arg in [ '<STR_LIT>' , '<STR_LIT>' ] : <EOL> last = arg <EOL> elif not infile and os . path . exists ( arg ) : <EOL> infile = arg <EOL> elif not outfile : <EOL> outfile = arg <EOL> else : <EOL> usage ( '<STR_LIT>' % arg ) <EOL> if not tags : <EOL> tags = [ '<STR_LIT>' , '<STR_LIT>' ] <EOL> if not infile or not outfile : <EOL> usage ( ) <EOL> else : <EOL> bam_best ( infile , outfile , failfile , tags ) </s>
