def determine_score_cutoff_by_n_peaks(ChIP, n_peaks= 1000, descend = True):
    """Determine the score cutoff when want to only include a certain number of peaks
    
    Parameters:
    1. ChIP: a Bed object
    2. n_peaks: the number of peaks that want to be kept
    3. descend: if True, count in the highest scores first
    """
    
    # 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 n_peaks is more than the actual scores, just return
    if n_peaks >= len(scores): 
        try:
            if descend:
                return scores[-1]
            else:
                return scores[0]
        except IndexError:
            return None
    else:
        if descend:
            return scores[-1*n_peaks]
        else:
            return scores[n_pekas]
dataset/ETHPy150Open taoliu/taolib/Assoc/inout.py/determine_score_cutoff_by_n_peaks/original