def map_of_clusters_and_labels(stats, tail, tf, pcrit):
    """
    Generate a statistics map and a list of clusters based on the
    presence of clusters that exceed a critical p-value.

    Parameters
    ----------

    stats: a TimeFreqSnPMClusters object
    tail: str {'pos', 'neg'}
    tf: tuple (time,freq) index
    pcrit: float in (0.0,1.0)

    Returns
    -------

    stats_image, clusters

    The `stats_image` is the image of the statistical test values.
    `clusters` is a list of the significant clusters. If there
    are no cluster scores exceeding pcrit, then clusters returns as None.
    """
    g, m = calc_grid_and_map(stats.vox_idx)
    
    l_img = np.zeros(g)
    t_img = np.zeros(g)
    t, f = tf
    np.put(t_img, m, stats.t[:,t,f])
    scores = stats.pscore_clusters(tail)
    if tail.lower() == 'pos':
        print 'doing pos tail'
        clusters = stats.ptail_clusters
    else:
        print 'doing neg tail'
        clusters = stats.ntail_clusters
    if not clusters[t][f]:
        print 'no clusters!'
        return t_img, None, 0
    crit_scores = (scores[t][f] < pcrit)
    if not crit_scores.any():
        print 'no significant clusters!'
        return t_img, None, 0
    else:
        tfclusters = clusters[t][f]
        idx = np.argwhere(crit_scores).reshape(-1)
        critical_clusters = [clusters[t][f][i] for i in idx]
        return t_img, critical_clusters
def quick_plot_top_n(stats, tail, n=3):
    scores = stats.pscore_clusters(tail)
    clusters = stats.ptail_clusters if tail.lower()=='pos' \
               else stats.ntail_clusters

    # flatten score into a flat list of cluster scores
    flattened_scores = []
    # flatten clusters into a ntime x nfreq list of cluster sublists
    flattened_clusters = []
    for crow, srow in zip(clusters, scores):
        flattened_scores = np.r_[flattened_scores,
                                 reduce(lambda x, y: x+y,
                                        [ list(e) for e in srow ])]
        flattened_clusters += crow
    tf_map = []
    cluster_lookup = dict()
    nc = 0
    for i, cl in enumerate(flattened_clusters):
        nt, nf = stats.t.shape[1:]
        t, f = i / nf, i % nf
        tf_map += [ (t,f) ] * len(cl)
        cluster_lookup.update( dict( zip(xrange(nc, nc+len(cl)), cl) ) )
        nc += len(cl)

    n_idx = flattened_scores.argsort()[:n]
    g, m = calc_grid_and_map(stats.vox_idx)
    imgs = []
    tf_pts = []
    nclusters = []
    for i in n_idx:
        clst = cluster_lookup[i]
        tf_pts.append('(t,f) = %s, %d pts, p = %1.2f'%(str(tf_map[i]),
                                                       clst.size,
                                                       flattened_scores[i]))
        nclusters.append(cluster_lookup[i])
        t_img = np.zeros(g)
        t, f = tf_map[i]
        np.put(t_img, m, stats.t[:,t,f])
        imgs.append(t_img)
    quick_plot_clusters(imgs, nclusters, titles=tf_pts)