code: def sub_sam(sam, percent, sort = True, sbuffer = False):
      
      mapping = sort_sam(sam, sort)
      pool = [1 for i in range(0, percent)] + [0 for i in range(0, 100 - percent)]
      c = cycle([1, 2])
      for line in mapping:
          line = line.strip().split()
          if line[0].startswith('@'): # get the sam header
              yield line
              continue
          if int(line[1]) <= 20: # is this from a single read?
              if random.choice(pool) == 1:
                  yield line
          else:
              n = next(c)
              if n == 1:
                  prev = line
              if n == 2 and random.choice(pool) == 1:
                  yield prev
                  yield line
docs: randomly subset sam file