def clean_bam_file(bam_in, mask=None):
seq_obj = defaultdict(int)<EOL>if mask:<EOL><INDENT>mask_file = op.splitext(bam_in)[<NUM_LIT:0>] + "<STR_LIT>"<EOL>if not file_exists(mask_file):<EOL><INDENT>pybedtools.BedTool(bam_file).intersect(b=mask, v=True).saveas(mask_file)<EOL><DEDENT>bam_in = mask_file<EOL><DEDENT>out_file = op.splitext(bam_in)[<NUM_LIT:0>] + "<STR_LIT>"<EOL>run("<STR_LIT>" % bam_in)<EOL>if not file_exists(bam_in + "<STR_LIT>"):<EOL><INDENT>raise IOError("<STR_LIT>" % bam_in)<EOL><DEDENT>bam_handle = pysam.AlignmentFile(bam_in, "<STR_LIT:rb>")<EOL>with pysam.AlignmentFile(out_file, "<STR_LIT:wb>", template=bam_handle) as out_handle:<EOL><INDENT>for read in bam_handle.fetch():<EOL><INDENT>seq_name = int(read.query_name.replace('<STR_LIT>', '<STR_LIT>'))<EOL>match_size = [nts for oper, nts in read.cigartuples if oper == <NUM_LIT:0>]<EOL>subs_size = [nts for oper, nts in read.cigartuples if oper == <NUM_LIT:4>]<EOL>if match_size[<NUM_LIT:0>] < <NUM_LIT>:<EOL><INDENT>continue<EOL><DEDENT>if subs_size:<EOL><INDENT>if subs_size[<NUM_LIT:0>] > <NUM_LIT:3>:<EOL><INDENT>continue<EOL><DEDENT><DEDENT>try:<EOL><INDENT>nh = read.get_tag('<STR_LIT>')<EOL><DEDENT>except KeyError:<EOL><INDENT>nh = <NUM_LIT:1><EOL><DEDENT>seq_obj[seq_name] = sequence(seq_name)<EOL>seq_obj[seq_name].align = nh<EOL>out_handle.write(read)<EOL><DEDENT><DEDENT>return out_file, seq_obj<EOL>
Remove from alignment reads with low counts and highly # of hits