code: def swap(args):
      
      from jcvi.utils.range import range_interleave
  
      p = OptionParser(swap.__doc__)
      opts, args = p.parse_args(args)
  
      if len(args) != 1:
          sys.exit(not p.print_help())
  
      agpfile, = args
  
      agp = AGP(agpfile, nogaps=True, validate=False)
      agp.sort(key=lambda x: (x.component_id, x.component_beg))
  
      newagpfile = agpfile.rsplit(".", 1)[0] + ".swapped.agp"
      fw = open(newagpfile, "w")
      agp.transfer_header(fw)
      for cid, aa in groupby(agp, key=(lambda x: x.component_id)):
          aa = list(aa)
          aranges = [(x.component_id, x.component_beg, x.component_end) \
                      for x in aa]
          gaps = range_interleave(aranges)
          for a, g in zip_longest(aa, gaps):
              a.object, a.component_id = a.component_id, a.object
              a.component_beg = a.object_beg
              a.component_end = a.object_end
              print(a, file=fw)
              if not g:
                  continue
  
              aline = [cid, 0, 0, 0]
              gseq, ga, gb = g
              cspan = gb - ga + 1
              aline += ["N", cspan, "fragment", "yes"]
              print("\t".join(str(x) for x in aline), file=fw)
  
      fw.close()
      # Reindex
      idxagpfile = reindex([newagpfile, "--inplace"])
  
      return newagpfile
docs: %prog swap agpfile
  
      Swap objects and components. Will add gap lines. This is often used in
      conjuction with formats.chain.fromagp() to convert between different
      coordinate systems.