Perform binning with a fixed genomic length in
    kilobase pairs (kb). Fragments will be binned such
    that their total length is closest to the specified input.
    If a contig list is specified, binning will be performed
    such that fragments never overlap two contigs.

def bin_kb_dense(M, positions, length=10, contigs=None):
    """Perform binning with a fixed genomic length in
    kilobase pairs (kb). Fragments will be binned such
    that their total length is closest to the specified input.
    If a contig list is specified, binning will be performed
    such that fragments never overlap two contigs.
    """

    unit = 10**3
    ul = unit * length
    unit = positions / ul
    n = len(positions)
    idx = [i for i in range(
        n - 1) if np.ceil(unit[i]) < np.ceil(unit[i + 1])]
    binned_positions = positions[idx]
    m = len(idx) - 1
    N = np.zeros((m, m))
    for i in range(m):
        N[i] = np.array([M[idx[j]:idx[j + 1], idx[i]:idx[i + 1]].sum()
                        for j in range(m)])

    return N, binned_positions