How to use the igraph.VertexClustering function in igraph

To help you get started, we’ve selected a few igraph examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github SergiuTripon / msc-thesis-na-epsrc / analysis / src / communities.py View on Github external
# variable to hold leading eigenvector communities
        leading_eigen_c = community.community_leading_eigenvector()
        # variable to hold leading eigenvector modularity
        leading_eigen_m = leading_eigen_c.modularity

        # variable to hold walktrap communities
        walktrap_c = community.community_walktrap(steps=4).as_clustering()
        # variable to hold walktrap modularity
        walktrap_m = walktrap_c.modularity

        # variable to hold fast greedy communities
        fastgreedy_c = community.community_fastgreedy().as_clustering()
        # variable to hold fast greedy modularity
        fastgreedy_m = fastgreedy_c.modularity

        edge_betweenness_c = ig.VertexClustering
        edge_betweenness_m = float

        # if network is connected and number of components is less than or equal to 2
        if community.is_connected() or len(community.components()) <= 2:
            # variable to hold edge betweenness communities
            edge_betweenness_c = community.community_edge_betweenness(directed=False).as_clustering()
            # variable to hold edge betweenness modularity
            edge_betweenness_m = edge_betweenness_c.modularity

    ####################################################################################################################

    # variable to hold output file
    output_file = open('../../data/networks/{}/communities/txt/'
                       '{}/{}/modularity.txt'.format(path, edge_type, method, count1), mode='a')

    # write modularity to file
github SergiuTripon / msc-thesis-na-epsrc / analysis / src / network.py View on Github external
# if network is connected and number of components is less than or equal to 2
        if network.is_connected() or len(network.components()) <= 2:
            # variable to hold edge betweenness communities
            edge_betweenness_c = network.community_edge_betweenness(directed=False, weights='weight').as_clustering()
            # variable to hold edge betweenness modularity
            edge_betweenness_m = edge_betweenness_c.modularity

    # if network is not weighted
    else:

        # variable to hold infomap communities
        infomap_c = network.community_infomap()
        # variable to hold infomap modularity
        infomap_m = infomap_c.modularity

        spinglass_c = ig.VertexClustering
        spinglass_m = float

        # if network is connected
        if network.is_connected():
            # variable to hold spinglass communities
            spinglass_c = network.community_spinglass()
            # variable to hold spinglass modularity
            spinglass_m = spinglass_c.modularity

        # variable to hold louvain communities
        louvain_c = network.community_multilevel()
        # variable to hold louvain modularity
        louvain_m = louvain_c.modularity

        # variable to hold label propagation communities
        label_prop_c = network.community_label_propagation()
github theislab / scanpy / scanpy / tools / _paga.py View on Github external
)
        if self._adata.uns[vkey].shape != (self._adata.n_obs, self._adata.n_obs):
            raise ValueError(
                f"The passed 'velocity_graph' have shape {self._adata.uns[vkey].shape} "
                f"but shoud have shape {(self._adata.n_obs, self._adata.n_obs)}"
            )
        # restore this at some point
        # if 'expected_n_edges_random' not in self._adata.uns['paga']:
        #     raise ValueError(
        #         'Before running PAGA with `use_rna_velocity=True`, run it with `False`.')
        import igraph
        g = _utils.get_igraph_from_adjacency(
            self._adata.uns[vkey].astype('bool'),
            directed=True,
        )
        vc = igraph.VertexClustering(
            g, membership=self._adata.obs[self._groups_key].cat.codes.values
        )
        # set combine_edges to False if you want self loops
        cg_full = vc.cluster_graph(combine_edges='sum')
        transitions = _utils.get_sparse_from_igraph(cg_full, weight_attr='weight')
        transitions = transitions - transitions.T
        transitions_conf = transitions.copy()
        transitions = transitions.tocoo()
        total_n = self._neighbors.n_neighbors * np.array(vc.sizes())
        # total_n_sum = sum(total_n)
        # expected_n_edges_random = self._adata.uns['paga']['expected_n_edges_random']
        for i, j, v in zip(transitions.row, transitions.col, transitions.data):
            # if expected_n_edges_random[i, j] != 0:
            #     # factor 0.5 because of asymmetry
            #     reference = 0.5 * expected_n_edges_random[i, j]
            # else:
github Lab41 / Circulo / circulo / algorithms / radicchi.py View on Github external
g = G.copy()
    g.vs['id'] = list(range(g.vcount()))

    if measure=='weak':
        result = radicchi_internal(G, g, 0, measure=measure, clustering=4)
    elif measure=='strong':
        result = radicchi_internal(G, g, 0, measure=measure, clustering=3)
    else:
        raise Exception('Other measures of community not yet supported')

    clustering = [0] * G.vcount()
    for i,l in enumerate(result):
        for v in l:
            clustering[v] = i

    return ig.VertexClustering(G, clustering)
github SergiuTripon / msc-thesis-na-epsrc / analysis / src / communities.py View on Github external
if community.is_connected() or len(community.components()) <= 2:
            # variable to hold edge betweenness communities
            edge_betweenness_c = community.community_edge_betweenness(directed=False,
                                                                      weights='weight').as_clustering()
            # variable to hold edge betweenness modularity
            edge_betweenness_m = edge_betweenness_c.modularity

    # if community is not weighted
    else:

        # variable to hold infomap communities
        infomap_c = community.community_infomap()
        # variable to hold infomap modularity
        infomap_m = infomap_c.modularity

        spinglass_c = ig.VertexClustering
        spinglass_m = float

        # if network is connected
        if community.is_connected():
            # variable to hold spinglass communities
            spinglass_c = community.community_spinglass()
            # variable to hold spinglass modularity
            spinglass_m = spinglass_c.modularity

        # variable to hold louvain communities
        louvain_c = community.community_multilevel()
        # variable to hold louvain modularity
        louvain_m = louvain_c.modularity

        # variable to hold label propagation communities
        label_prop_c = community.community_label_propagation()
github theislab / scanpy / scanpy / tools / _paga.py View on Github external
def _compute_connectivities_v1_0(self):
        import igraph
        ones = self._neighbors.connectivities.copy()
        ones.data = np.ones(len(ones.data))
        g = _utils.get_igraph_from_adjacency(ones)
        vc = igraph.VertexClustering(
            g, membership=self._adata.obs[self._groups_key].cat.codes.values
        )
        ns = vc.sizes()
        cg = vc.cluster_graph(combine_edges='sum')
        inter_es = _utils.get_sparse_from_igraph(cg, weight_attr='weight') / 2
        connectivities = inter_es.copy()
        inter_es = inter_es.tocoo()
        n_neighbors_sq = self._neighbors.n_neighbors**2
        for i, j, v in zip(inter_es.row, inter_es.col, inter_es.data):
            # have n_neighbors**2 inside sqrt for backwards compat
            geom_mean_approx_knn = np.sqrt(
                n_neighbors_sq * ns[i] * ns[j])
            if geom_mean_approx_knn != 0:
                scaled_value = v / geom_mean_approx_knn
            else:
                scaled_value = 1
github theislab / scanpy / scanpy / tools / _paga.py View on Github external
def compute_transitions_old(self):
        import igraph
        g = _utils.get_igraph_from_adjacency(
            self._adata.uns['velocyto_transitions'],
            directed=True,
        )
        vc = igraph.VertexClustering(
            g, membership=self._adata.obs[self._groups_key].cat.codes.values)
        # this stores all single-cell edges in the cluster graph
        cg_full = vc.cluster_graph(combine_edges=False)
        # this is the boolean version that simply counts edges in the clustered graph
        g_bool = _utils.get_igraph_from_adjacency(
            self._adata.uns['velocyto_transitions'].astype('bool'),
            directed=True,
        )
        vc_bool = igraph.VertexClustering(
            g_bool,
            membership=self._adata.obs[self._groups_key].cat.codes.values
        )
        cg_bool = vc_bool.cluster_graph(combine_edges='sum')  # collapsed version
        transitions = _utils.get_sparse_from_igraph(cg_bool, weight_attr='weight')
        total_n = self._neighbors.n_neighbors * np.array(vc_bool.sizes())
        transitions_ttest = transitions.copy()
github theislab / scanpy / scanpy / tools / _paga.py View on Github external
def _compute_connectivities_v1_2(self):
        import igraph
        ones = self._neighbors.distances.copy()
        ones.data = np.ones(len(ones.data))
        # should be directed if we deal with distances
        g = _utils.get_igraph_from_adjacency(ones, directed=True)
        vc = igraph.VertexClustering(
            g, membership=self._adata.obs[self._groups_key].cat.codes.values
        )
        ns = vc.sizes()
        n = sum(ns)
        es_inner_cluster = [vc.subgraph(i).ecount() for i in range(len(ns))]
        cg = vc.cluster_graph(combine_edges='sum')
        inter_es = _utils.get_sparse_from_igraph(cg, weight_attr='weight')
        es = np.array(es_inner_cluster) + inter_es.sum(axis=1).A1
        inter_es = inter_es + inter_es.T  # \epsilon_i + \epsilon_j
        connectivities = inter_es.copy()
        expected_n_edges = inter_es.copy()
        inter_es = inter_es.tocoo()
        for i, j, v in zip(inter_es.row, inter_es.col, inter_es.data):
            expected_random_null = (es[i]*ns[j] + es[j]*ns[i])/(n - 1)
            if expected_random_null != 0:
                scaled_value = v / expected_random_null
github SergiuTripon / msc-thesis-na-epsrc / analysis / src / communities.py View on Github external
# variable to hold leading eigenvector communities
        leading_eigen_c = community.community_leading_eigenvector(weights='weight')
        # variable to hold leading eigenvector modularity
        leading_eigen_m = leading_eigen_c.modularity

        # variable to hold walktrap communities
        walktrap_c = community.community_walktrap(weights='weight', steps=4).as_clustering()
        # variable to hold walktrap modularity
        walktrap_m = walktrap_c.modularity

        # variable to hold fast greedy communities
        fastgreedy_c = community.community_fastgreedy(weights='weight').as_clustering()
        # variable to hold fast greedy modularity
        fastgreedy_m = fastgreedy_c.modularity

        edge_betweenness_c = ig.VertexClustering
        edge_betweenness_m = float

        # if network is connected and number of components is less than or equal to 2
        if community.is_connected() or len(community.components()) <= 2:
            # variable to hold edge betweenness communities
            edge_betweenness_c = community.community_edge_betweenness(directed=False,
                                                                      weights='weight').as_clustering()
            # variable to hold edge betweenness modularity
            edge_betweenness_m = edge_betweenness_c.modularity

    # if community is not weighted
    else:

        # variable to hold infomap communities
        infomap_c = community.community_infomap()
        # variable to hold infomap modularity
github Lab41 / Circulo / experiments / time_accuracy.py View on Github external
def eval_data(title, G, ground_truth, algo_list):

    print("\n======== {} ========\n".format(title))
    for algo in algos:

        print("Testing \"{}\"".format(algo.__name__))

        t0 = time.time()
        result = algo(G)
        t_diff = time.time() - t0
        clustering = None

        if isinstance(result, VertexClustering):
            clustering = result
        elif isinstance(result, VertexDendrogram):
            clustering = result.as_clustering()
        else:
            raise Exception("Algorithm output type not recognized")


        f1 = metrics.f1(clustering, ground_truth)

        print("\t[*] Execution time: {}".format(t_diff))
        print("\t[*] F1 Score: {}".format(f1))