code: def mapped(args):
      
      import pysam
      from jcvi.apps.grid import Jobs
  
      p = OptionParser(mapped.__doc__)
      p.set_sam_options(extra=False)
  
      opts, args = p.parse_args(args)
      if len(args) != 1:
          sys.exit(p.print_help())
  
      samfile, = args
  
      view_opts = []
      oext, mopts = (".sam", ["-S"]) \
              if samfile.endswith(".sam") else (".bam", [])
  
      flag, ext = ("-b", ".bam") if opts.bam else ("-h", ".sam")
      mopts.append(flag)
  
      if opts.uniq:
          mopts.append("-q1")
          ext = ".uniq{0}".format(ext)
  
      if opts.unmapped:
          uopts = [x for x in mopts]
          uoutfile = samfile.replace(oext, ".unmapped{0}".format(ext))
          uopts.extend(["-f4", samfile, "-o{0}".format(uoutfile)])
          view_opts.append(uopts)
  
      outfile = samfile.replace(oext, ".mapped{0}".format(ext))
      mopts.extend(["-F4", samfile, "-o{0}".format(outfile)])
      view_opts.append(mopts)
  
      for vo in view_opts:
          logging.debug('samtools view {0}'.format(" ".join(vo)))
  
      jobs = Jobs(pysam.view, [(z for z in x) for x in view_opts])
      jobs.run()
docs: %prog mapped sam/bamfile
  
      Given an input sam/bam file, output a sam/bam file containing only the mapped reads.
      Optionally, extract the unmapped reads into a separate file