def downsample_ChIP(ChIP, interval = 5000):
    """Down-sample the ChIP regions according to the given interval
    
    Parameters:
    1. ChIP: a Bed object
    2. interval: an interval in bp. within this interval, only one ChIP region remains. Default = 5kb
    
    NOTE that the input bed object must be sorted by 'start'
    """
    
    chroms = ChIP.get_chroms()
    if not chroms: return None
    
    sampledChIP = Bed()
    sampledChIP.bed = {}
    for chrom in chroms:
        sampledChIP.bed[chrom] = {}
        
        # initialize
        keys = ChIP[chrom].keys()
        for key in keys:
            if key == 'start' or key == 'end':
                sampledChIP[chrom][key] = array('l', [])
            elif key == 'score':
                sampledChIP[chrom][key] = array('d', [])
            else:
                sampledChIP[chrom][key] = []
                
        # if there is only one ChIP region, just copy and go
        len_this_chrom = len(ChIP[chrom]['start'])
        if len_this_chrom == 1:
            sampledChIP.bed[chrom] = copy.deepcopy(ChIP.bed[chrom])
            continue
        
        # downsampling
        prev = ChIP[chrom]['start'][0]
        # update the first element for each column
        for key in keys: sampledChIP[chrom][key].append(ChIP[chrom][key][0])
        
        # iterate through this chromosome
        for i, start in itertools.izip(xrange(1,len_this_chrom), ChIP[chrom]['start'][1:]):

            # keep only if the new bed region is far enough from the previously sampled point
            if interval > start - prev:
                for key in keys: sampledChIP[chrom][key].append(ChIP[chrom][key][i])
                prev = start
    
    return sampledChIP
                
#-------------------------------------
# functions related to R script out
#-------------------------------------
dataset/ETHPy150Open taoliu/taolib/Assoc/inout.py/downsample_ChIP/swapped operands of `>`