import networkx as nx


def cluster(linkage):
    """
    Cluster all genomes based on established linkages using networkx

    :param linkage: Dictionary of dictionaries
    :return: A dictionary with cluster index and list of genomes
    """
    g = nx.from_dict_of_dicts(linkage)
    clustered = []
    clusters = {}
    clust_num = 1
    for n in g.nodes():
        c = [n]
        if n in clustered: continue
        edges = list(nx.dfs_edges(g, n))
        for e in edges:
            n1, n2 = e
            clustered += [n1, n2]
            c += [n1, n2]
        c = list(set(c))
        clusters[clust_num] = c[:]
        clust_num += 1
    return clusters