def main_cc(mesh, mask):
    """Filter the mask to keep only the main connected component"""
    mg = mep.mesh_to_graph(mesh).subgraph(mask.ravel())
    u = mg.cc()
    size_u = np.array([np.sum(u == k) for k in np.unique(u) if k > -1])
    mask[mask] = (u == size_u.argmax())
    return mask
def phase_unwrapping(phase, mesh, mask, path=None):
    """ This aims at solging 2-pi phase shifts
    """
    for iteri in range(5):
        mg = mep.mesh_to_graph(mesh).subgraph(mask.ravel())
        diff = np.ravel(phase[mg.edges.T[0]] - 
                        phase[mg.edges.T[1]])
        pos_vertex = np.zeros(mg.V)
        pos_vertex[np.unique(mg.edges.T[0, diff > np.pi])] = 1
        pos_vertex[np.unique(mg.edges.T[0, diff < - np.pi])] = - 1
        mg.remove_edges(np.abs(diff) < np.pi / 2)
        u = mg.cc()
        change = False
        for k in np.unique(u):
            if np.sum(u == k) < np.size(u) / 2:
                disc = pos_vertex[u == k].sum() / (
                    1.e-6 + np.abs(pos_vertex[u == k]).sum())
                if np.abs(disc) > .75:
                    change = True
                if (disc > .75):
                    phase[u == k] -= 2 * np.pi   
                if (disc < -.75):
                    phase[u == k] += 2 * np.pi
        if path is not None: 
            ex = - 1 * np.ones(np.size(mask))
            ex[mask.squeeze()] = u
            save_texture(path, ex, 'estimate')
        if change == False:
            break
    phase[phase < - np.pi] = - np.pi + 1.e-6
    phase[phase > np.pi] = np.pi - 1.e-6
    return phase
def cc_mesh_mask(mesh, mask, size_threshold):
    """Filter the mask to keep only connected components above a given size"""
    return cc_mask(mep.mesh_to_graph(mesh), mask, size_threshold)
    threshold_path = 'surface_threshold_smooth.con'
    # output dir
    swd = '/data/home/virgile/virgile_internship/group_analysis/smoothed_FWHM5'
else:
    threshold_path = 'surface_threshold.con'
    # output dir
    swd = '/data/home/virgile/virgile_internship/group_analysis/smoothed_FWHM0'


################################################################
# Create a topological model from the mesh
################################################################
# buils graph from meshes
R = aims.Reader()
left_mesh = R.read(left_meshes[0])
lg = mep.mesh_to_graph(left_mesh)
right_mesh = R.read(right_meshes[0])
rg = mep.mesh_to_graph(right_mesh)
gg = fg.concatenate_graphs(lg,rg)

area = np.ones(gg.V)
if b_cached==True:
    area = np.load('area.npz')
elif b_cached==False:
    area = np.zeros(gg.V)
    for s in range(nsubj):
        area[:lg.V] += mep.node_area(R.read(left_meshes[s]))
        area[lg.V:] += mep.node_area(R.read(right_meshes[s]))
    area /= nsubj
    area.dump('area.npz')