dists_nc = squareform(0.5 * (1.0 - m.noise_corr))
    m.linkage_nc = hac.linkage(dists_nc, method='complete')
    m.hac_idxs_nc = hac.dendrogram(m.linkage_nc)['leaves']
    hac_response_nc = m.data[:,m.hac_idxs_nc,:,:]
    m.noise_corr_hac = noise_correlation(hac_response_nc)
    
    # Cluster reliability.
    # From signal correlations.
    m.cl_idxs_sc = hac.fcluster(m.linkage_sc, n_clusters, criterion='maxclust')
    m.sc_cluster_reliability = np.zeros((n_clusters+1,S))
    m.mean_cluster_rsp_sc = np.zeros((S, n_clusters, L, R))
    for i in range(1, n_clusters+1):
        idxs = np.arange(N)
        idxs = idxs[m.cl_idxs_sc == i]
        m.mean_cluster_rsp_sc[:,i-1,:,:] = m.data[:,idxs,:,:].mean(axis=1)
    m.sc_cluster_reliability = reliability(m.mean_cluster_rsp_sc)
    
    # From noise correlations.
    m.cl_idxs_nc = hac.fcluster(m.linkage_nc, n_clusters, criterion='maxclust')
    m.nc_cluster_reliability = np.zeros((n_clusters+1,S))
    m.mean_cluster_rsp_nc = np.zeros((S, n_clusters, L, R))
    for i in range(1, n_clusters+1):
        idxs = np.arange(N)
        idxs = idxs[m.cl_idxs_nc == i]
        m.mean_cluster_rsp_nc[:,i-1,:,:] = m.data[:,idxs,:,:].mean(axis=1)
    m.nc_cluster_reliability = reliability(m.mean_cluster_rsp_nc)

    ############################################################################
    # Plotting
    if not os.path.isdir(os.path.join(PLOTS_DIR,'clustering')):
        os.makedirs(os.path.join(PLOTS_DIR, 'clustering'))
for index in range(len(data)):
    m = data[index]
    print 'Mouse %s' % m.name

    # Smoothing responses. Some unnecessarily clunky stuff here as well.
    # Will do something about that later.
    data[index] = smooth_responses(m)
    m = data[index]
    if exp_type == 'natural':
        m.data = m.data[:5,:,:,:] # Remove K0, K1, etc.
    
    S, N, L, R = m.data.shape
    avg_response = np.mean(m.data, axis=(2,3))

    m.reliability = reliability(m.data)

    # Reliability-tuning curve correlation
    if exp_type == 'grating':
        m.tuning_curve = np.zeros((N,S))
        m.rel_tc_corr = np.zeros(N)
        for i in range(N):
            m.tuning_curve[i,:] = avg_response[:,i]
            r = m.reliability[i,:]
            tc = m.tuning_curve[i,:]
            r -= r.mean()
            tc -= tc.mean()
            m.rel_tc_corr[i] = np.dot(r,tc) / np.sqrt(np.dot(r,r)*np.dot(tc,tc))
    
    ############################################################################
    # Plot