def tiling(args):
    p = OptionParser(tiling.__doc__)
    p.add_option("--overlap", default=3000, type="int",
                 help="Minimum amount of overlaps required")
    p.set_verbose()
    opts, args = p.parse_args(args)

    if len(args) != 1:
        sys.exit(not p.print_help())

    bedfile, = args
    ov = opts.overlap

    bed = Bed(bedfile)
    inf = len(bed)
    selected = Bed()
    for seqid, sbed in bed.sub_beds():
        g = Grouper()
        current = sbed[0]
        # Partition connected features
        for a in sbed:
            g.join(a)
            # requires a real overlap
            if a.start < current.end - ov:
                g.join(a, current)
            if a.end > current.end:
                current = a

        # Process per partition
        for gbed in g:
            end = max(x.end for x in gbed)
            gbed.sort(key=lambda x: (x.start, -x.end))
            entries = len(gbed)
            counts = [inf] * entries
            counts[0] = 1
            traceback = [-1] * entries
            for i, a in enumerate(gbed):
                for j in xrange(i + 1, entries):
                    b = gbed[j]
                    if b.start >= a.end - ov:
                        break
                    # Two ranges overlap!
                    if counts[i] + 1 < counts[j]:
                        counts[j] = counts[i] + 1
                        traceback[j] = i
            endi = [i for i, a in enumerate(gbed) if a.end == end]
            last = min((traceback[i], i) for i in endi)[1]
            chain = []
            while last != -1:
                chain.append(last)
                last = traceback[last]
            chain = chain[::-1]
            selected.extend([gbed[x] for x in chain])

            if opts.verbose:
                print counts
                print traceback
                print chain
                print "\n".join(str(x) for x in gbed)
                print "*" * 30
                print "\n".join(str(gbed[x]) for x in chain)
                print

    tilingbedfile = bedfile.rsplit(".", 1)[0] + ".tiling.bed"
    selected.print_to_file(filename=tilingbedfile, sorted=True)
    logging.debug("A total of {} tiling features written to `{}`"\
                    .format(len(selected), tilingbedfile))
%prog tiling bedfile
dataset/ETHPy150Open tanghaibao/jcvi/formats/bed.py/tiling