def select_ChIP_by_n_peaks(ChIP, n_peaks = 1000, descend=True):
    """Select n_peaks ChIP regions by score
    
    Parameters:
    1. ChIP: a Bed object
    2. n_peaks: the number of peaks to be selected
    3. descend: if True, from the top; otherwise from the bottom of scores
    """
    
     # if no chroms, just return None
    chroms = ChIP.get_chroms()
    if not chroms: return None
    
    # if any of chroms does not have 'score', just return None
    YESSCORE = True
    for chrom in chroms:
        YESSCORE = YESSCORE and ChIP[chrom].has_key('score')
    if not YESSCORE: return None
    
    # concatenate the scores and sort
    scores = []
    for chrom in chroms:
        scores += ChIP[chrom]['score']
    scores.sort()
    
    # if more peaks will be kept than we have, just return ChIP
    if n_peaks >= len(scores):
        return ChIP
    
    # get the cutoff 
    if descend:
        cutoff = scores[-1*n_peaks]
    else:
        cutoff = scores[n_peaks]
    
    # select ChIP regions        
    newChIP = Bed()
    for chrom in chroms:
        if descend:
            b = map(lambda x: x>= cutoff, ChIP[chrom]['score'])
        else:
            b = map(lambda x: x<= cutoff, ChIP[chrom]['score'])
        newChIP.bed = {}
        newChIP.bed[chrom]={}
        for key in ChIP[chrom].keys():
            if key == 'start' or key =='end':
                newChIP.bed[chrom][key] = array('l', array_extractor(ChIP[chrom]['start'], b))
            elif key == 'score':
                newChIP.bed[chrom][key] = array('d', array_extractor(ChIP[chrom]['score'], b))
            else:
                newChIP.bed[chrom][key] = array_extractor(ChIP[chrom][key], b)
                
    return newChIP
dataset/ETHPy150Open taoliu/taolib/Assoc/inout.py/select_ChIP_by_n_peaks/original