Python networkx.clustering() Examples

The following are 30 code examples of networkx.clustering(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module networkx , or try the search function .
Example #1
Source File: test_cluster.py    From Carnets with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
def test_k5(self):
        G = nx.complete_graph(5)
        assert_equal(nx.transitivity(G), 1.0)
        G.remove_edge(1, 2)
        assert_equal(nx.transitivity(G), 0.875)

    # def test_clustering_transitivity(self):
    #     # check that weighted average of clustering is transitivity
    #     G = nx.complete_graph(5)
    #     G.remove_edge(1,2)
    #     t1=nx.transitivity(G)
    #     (cluster_d2,weights)=nx.clustering(G,weights=True)
    #     trans=[]
    #     for v in G.nodes():
    #         trans.append(cluster_d2[v]*weights[v])
    #     t2=sum(trans)
    #     assert_almost_equal(abs(t1-t2),0) 
Example #2
Source File: utils.py    From GraphRNN with MIT License 7 votes vote down vote up
def decode_graph(adj, prefix):
    adj = np.asmatrix(adj)
    G = nx.from_numpy_matrix(adj)
    # G.remove_nodes_from(nx.isolates(G))
    print('num of nodes: {}'.format(G.number_of_nodes()))
    print('num of edges: {}'.format(G.number_of_edges()))
    G_deg = nx.degree_histogram(G)
    G_deg_sum = [a * b for a, b in zip(G_deg, range(0, len(G_deg)))]
    print('average degree: {}'.format(sum(G_deg_sum) / G.number_of_nodes()))
    if nx.is_connected(G):
        print('average path length: {}'.format(nx.average_shortest_path_length(G)))
        print('average diameter: {}'.format(nx.diameter(G)))
    G_cluster = sorted(list(nx.clustering(G).values()))
    print('average clustering coefficient: {}'.format(sum(G_cluster) / len(G_cluster)))
    cycle_len = []
    cycle_all = nx.cycle_basis(G, 0)
    for item in cycle_all:
        cycle_len.append(len(item))
    print('cycles', cycle_len)
    print('cycle count', len(cycle_len))
    draw_graph(G, prefix=prefix) 
Example #3
Source File: cluster.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _directed_triangles_and_degree_iter(G, nodes=None):
    """ Return an iterator of
    (node, total_degree, reciprocal_degree, directed_triangles).

    Used for directed clustering.

    """
    nodes_nbrs = ((n, G._pred[n], G._succ[n]) for n in G.nbunch_iter(nodes))

    for i, preds, succs in nodes_nbrs:
        ipreds = set(preds) - {i}
        isuccs = set(succs) - {i}

        directed_triangles = 0
        for j in chain(ipreds, isuccs):
            jpreds = set(G._pred[j]) - {j}
            jsuccs = set(G._succ[j]) - {j}
            directed_triangles += sum((1 for k in
                                       chain((ipreds & jpreds),
                                             (ipreds & jsuccs),
                                             (isuccs & jpreds),
                                             (isuccs & jsuccs))))
        dtotal = len(ipreds) + len(isuccs)
        dbidirectional = len(ipreds & isuccs)
        yield (i, dtotal, dbidirectional, directed_triangles) 
Example #4
Source File: test_cluster.py    From aws-kube-codesuite with Apache License 2.0 6 votes vote down vote up
def test_k5(self):
        G = nx.complete_graph(5)
        assert_equal(nx.transitivity(G), 1.0)
        G.remove_edge(1, 2)
        assert_equal(nx.transitivity(G), 0.875)

    # def test_clustering_transitivity(self):
    #     # check that weighted average of clustering is transitivity
    #     G = nx.complete_graph(5)
    #     G.remove_edge(1,2)
    #     t1=nx.transitivity(G)
    #     (cluster_d2,weights)=nx.clustering(G,weights=True)
    #     trans=[]
    #     for v in G.nodes():
    #         trans.append(cluster_d2[v]*weights[v])
    #     t2=sum(trans)
    #     assert_almost_equal(abs(t1-t2),0) 
Example #5
Source File: utils.py    From graph-generation with MIT License 6 votes vote down vote up
def decode_graph(adj, prefix):
    adj = np.asmatrix(adj)
    G = nx.from_numpy_matrix(adj)
    # G.remove_nodes_from(nx.isolates(G))
    print('num of nodes: {}'.format(G.number_of_nodes()))
    print('num of edges: {}'.format(G.number_of_edges()))
    G_deg = nx.degree_histogram(G)
    G_deg_sum = [a * b for a, b in zip(G_deg, range(0, len(G_deg)))]
    print('average degree: {}'.format(sum(G_deg_sum) / G.number_of_nodes()))
    if nx.is_connected(G):
        print('average path length: {}'.format(nx.average_shortest_path_length(G)))
        print('average diameter: {}'.format(nx.diameter(G)))
    G_cluster = sorted(list(nx.clustering(G).values()))
    print('average clustering coefficient: {}'.format(sum(G_cluster) / len(G_cluster)))
    cycle_len = []
    cycle_all = nx.cycle_basis(G, 0)
    for item in cycle_all:
        cycle_len.append(len(item))
    print('cycles', cycle_len)
    print('cycle count', len(cycle_len))
    draw_graph(G, prefix=prefix) 
Example #6
Source File: test_cluster.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_cubical(self):
        G = nx.cubical_graph()
        assert_equal(list(nx.clustering(G).values()),
                     [0, 0, 0, 0, 0, 0, 0, 0])
        assert_equal(nx.clustering(G, 1), 0)
        assert_equal(list(nx.clustering(G, [1, 2]).values()), [0, 0])
        assert_equal(nx.clustering(G, 1), 0)
        assert_equal(nx.clustering(G, [1, 2]), {1: 0, 2: 0}) 
Example #7
Source File: feathergraph.py    From karateclub with GNU General Public License v3.0 5 votes vote down vote up
def _create_node_feature_matrix(self, graph):
        """
        Calculating the node features.

        Arg types:
            * **graph** *(NetworkX graph)* - The graph of interest.

        Return types:
            * **X** *(NumPy array)* - The node features.
        """
        log_degree = np.array([math.log(graph.degree(node)+1) for node in range(graph.number_of_nodes())]).reshape(-1, 1)
        clustering_coefficient = np.array([nx.clustering(graph, node) for node in range(graph.number_of_nodes())]).reshape(-1, 1)
        X = np.concatenate([log_degree, clustering_coefficient], axis=1)
        return X 
Example #8
Source File: test_cluster.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_path(self):
        G = nx.path_graph(10, create_using=nx.DiGraph())
        assert_equal(list(nx.clustering(G).values()),
                     [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0])
        assert_equal(nx.clustering(G),
                     {0: 0.0, 1: 0.0, 2: 0.0, 3: 0.0, 4: 0.0,
                      5: 0.0, 6: 0.0, 7: 0.0, 8: 0.0, 9: 0.0}) 
Example #9
Source File: test_cluster.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_k5(self):
        G = nx.complete_graph(5, create_using=nx.DiGraph())
        assert_equal(list(nx.clustering(G).values()), [1, 1, 1, 1, 1])
        assert_equal(nx.average_clustering(G), 1)
        G.remove_edge(1, 2)
        assert_equal(list(nx.clustering(G).values()),
                     [11. / 12., 1.0, 1.0, 11. / 12., 11. / 12.])
        assert_equal(nx.clustering(G, [1, 4]), {1: 1.0, 4: 11. /12.})
        G.remove_edge(2, 1)
        assert_equal(list(nx.clustering(G).values()),
                     [5. / 6., 1.0, 1.0, 5. / 6., 5. / 6.])
        assert_equal(nx.clustering(G, [1, 4]), {1: 1.0, 4: 0.83333333333333337}) 
Example #10
Source File: test_cluster.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_triangle_and_edge(self):
        G = nx.cycle_graph(3, create_using=nx.DiGraph())
        G.add_edge(0, 4)
        assert_equal(nx.clustering(G)[0], 1.0 / 6.0) 
Example #11
Source File: test_cluster.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_clustering(self):
        G = nx.DiGraph()
        assert_equal(list(nx.clustering(G, weight='weight').values()), [])
        assert_equal(nx.clustering(G), {}) 
Example #12
Source File: test_cluster.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_path(self):
        G = nx.path_graph(10, create_using=nx.DiGraph())
        assert_equal(list(nx.clustering(G, weight='weight').values()),
                     [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0])
        assert_equal(nx.clustering(G, weight='weight'),
                     {0: 0.0, 1: 0.0, 2: 0.0, 3: 0.0, 4: 0.0,
                      5: 0.0, 6: 0.0, 7: 0.0, 8: 0.0, 9: 0.0}) 
Example #13
Source File: test_cluster.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_triangle_and_edge(self):
        G = nx.cycle_graph(3, create_using=nx.DiGraph())
        G.add_edge(0, 4, weight=2)
        assert_equal(nx.clustering(G)[0], 1.0 / 6.0)
        assert_equal(nx.clustering(G, weight='weight')[0], 1.0 / 12.0) 
Example #14
Source File: test_cluster.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_clustering(self):
        G = nx.Graph()
        assert_equal(list(nx.clustering(G, weight='weight').values()), [])
        assert_equal(nx.clustering(G), {}) 
Example #15
Source File: test_cluster.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_path(self):
        G = nx.path_graph(10)
        assert_equal(list(nx.clustering(G, weight='weight').values()),
                     [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0])
        assert_equal(nx.clustering(G, weight='weight'),
                     {0: 0.0, 1: 0.0, 2: 0.0, 3: 0.0, 4: 0.0,
                      5: 0.0, 6: 0.0, 7: 0.0, 8: 0.0, 9: 0.0}) 
Example #16
Source File: test_cluster.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_cubical(self):
        G = nx.cubical_graph()
        assert_equal(list(nx.clustering(G, weight='weight').values()),
                     [0, 0, 0, 0, 0, 0, 0, 0])
        assert_equal(nx.clustering(G, 1), 0)
        assert_equal(list(nx.clustering(G, [1, 2], weight='weight').values()), [0, 0])
        assert_equal(nx.clustering(G, 1, weight='weight'), 0)
        assert_equal(nx.clustering(G, [1, 2], weight='weight'), {1: 0, 2: 0}) 
Example #17
Source File: test_cluster.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_k5(self):
        G = nx.complete_graph(5)
        assert_equal(list(nx.clustering(G, weight='weight').values()), [1, 1, 1, 1, 1])
        assert_equal(nx.average_clustering(G, weight='weight'), 1)
        G.remove_edge(1, 2)
        assert_equal(list(nx.clustering(G, weight='weight').values()),
                     [5. / 6., 1.0, 1.0, 5. / 6., 5. / 6.])
        assert_equal(nx.clustering(G, [1, 4], weight='weight'), {1: 1.0, 4: 0.83333333333333337}) 
Example #18
Source File: test_cluster.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_clustering(self):
        G = nx.Graph()
        assert_equal(list(nx.clustering(G).values()), [])
        assert_equal(nx.clustering(G), {}) 
Example #19
Source File: test_cluster.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_path(self):
        G = nx.path_graph(10)
        assert_equal(list(nx.clustering(G).values()),
                     [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0])
        assert_equal(nx.clustering(G),
                     {0: 0.0, 1: 0.0, 2: 0.0, 3: 0.0, 4: 0.0,
                      5: 0.0, 6: 0.0, 7: 0.0, 8: 0.0, 9: 0.0}) 
Example #20
Source File: test_threshold.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_fast_versions_properties_threshold_graphs(self):
        cs = 'ddiiddid'
        G = nxt.threshold_graph(cs)
        assert_equal(nxt.density('ddiiddid'), nx.density(G))
        assert_equal(sorted(nxt.degree_sequence(cs)),
                     sorted(d for n, d in G.degree()))

        ts = nxt.triangle_sequence(cs)
        assert_equal(ts, list(nx.triangles(G).values()))
        assert_equal(sum(ts) // 3, nxt.triangles(cs))

        c1 = nxt.cluster_sequence(cs)
        c2 = list(nx.clustering(G).values())
        assert_almost_equal(sum([abs(c - d) for c, d in zip(c1, c2)]), 0)

        b1 = nx.betweenness_centrality(G).values()
        b2 = nxt.betweenness_sequence(cs)
        assert_true(sum([abs(c - d) for c, d in zip(b1, b2)]) < 1e-14)

        assert_equal(nxt.eigenvalues(cs), [0, 1, 3, 3, 5, 7, 7, 8])

        # Degree Correlation
        assert_true(abs(nxt.degree_correlation(cs) + 0.593038821954) < 1e-12)
        assert_equal(nxt.degree_correlation('diiiddi'), -0.8)
        assert_equal(nxt.degree_correlation('did'), -1.0)
        assert_equal(nxt.degree_correlation('ddd'), 1.0)
        assert_equal(nxt.eigenvalues('dddiii'), [0, 0, 0, 0, 3, 3])
        assert_equal(nxt.eigenvalues('dddiiid'), [0, 1, 1, 1, 4, 4, 7]) 
Example #21
Source File: test_cluster.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_k5(self):
        G = nx.complete_graph(5)
        assert_equal(list(nx.clustering(G).values()), [1, 1, 1, 1, 1])
        assert_equal(nx.average_clustering(G), 1)
        G.remove_edge(1, 2)
        assert_equal(list(nx.clustering(G).values()),
                     [5. / 6., 1.0, 1.0, 5. / 6., 5. / 6.])
        assert_equal(nx.clustering(G, [1, 4]), {1: 1.0, 4: 0.83333333333333337}) 
Example #22
Source File: scd.py    From karateclub with GNU General Public License v3.0 5 votes vote down vote up
def fit(self, graph):
        """
        Fitting a Label Propagation clustering model.

        Arg types:
            * **graph** *(NetworkX graph)* - The graph to be clustered.
        """
        self._set_seed()
        self._check_graph(graph)
        self._graph = graph
        self._create_initial_partition()
        self._set_omega()
        self._set_nodes()
        for _ in range(self.iterations):
            self._do_refinement() 
Example #23
Source File: refex.py    From RolX with GNU General Public License v3.0 5 votes vote down vote up
def basic_stat_extractor(self):
        self.base_features = []
        self.sub_graph_container = {}
        for node in tqdm(range(0,len(self.nodes))):
            sub_g, overall_counts, nebs = inducer(self.graph, node)
            in_counts = len(nx.edges(sub_g))
            self.sub_graph_container[node] = nebs
            deg = nx.degree(sub_g, node)
            trans = nx.clustering(sub_g, node)
            self.base_features.append([in_counts, overall_counts, float(in_counts)/float(overall_counts), float(overall_counts - in_counts)/float(overall_counts),deg, trans])
        self.features = {}
        self.features[0] = np.array(self.base_features)
        print("") 
        del self.base_features 
Example #24
Source File: cluster.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def _weighted_triangles_and_degree_iter(G, nodes=None, weight='weight'):
    """ Return an iterator of (node, degree, weighted_triangles).

    Used for weighted clustering.

    """
    if weight is None or G.number_of_edges() == 0:
        max_weight = 1
    else:
        max_weight = max(d.get(weight, 1) for u, v, d in G.edges(data=True))
    if nodes is None:
        nodes_nbrs = G.adj.items()
    else:
        nodes_nbrs = ((n, G[n]) for n in G.nbunch_iter(nodes))

    def wt(u, v):
        return G[u][v].get(weight, 1) / max_weight

    for i, nbrs in nodes_nbrs:
        inbrs = set(nbrs) - {i}
        weighted_triangles = 0
        seen = set()
        for j in inbrs:
            seen.add(j)
            # This prevents double counting.
            jnbrs = set(G[j]) - seen
            # Only compute the edge weight once, before the inner inner
            # loop.
            wij = wt(i, j)
            weighted_triangles += sum((wij * wt(j, k) * wt(k, i)) ** (1 / 3)
                                      for k in inbrs & jnbrs)
        yield (i, len(inbrs), 2 * weighted_triangles) 
Example #25
Source File: test_threshold.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_fast_versions_properties_threshold_graphs(self):
        cs = 'ddiiddid'
        G = nxt.threshold_graph(cs)
        assert_equal(nxt.density('ddiiddid'), nx.density(G))
        assert_equal(sorted(nxt.degree_sequence(cs)),
                     sorted(d for n, d in G.degree()))

        ts = nxt.triangle_sequence(cs)
        assert_equal(ts, list(nx.triangles(G).values()))
        assert_equal(sum(ts) // 3, nxt.triangles(cs))

        c1 = nxt.cluster_sequence(cs)
        c2 = list(nx.clustering(G).values())
        assert_almost_equal(sum([abs(c - d) for c, d in zip(c1, c2)]), 0)

        b1 = nx.betweenness_centrality(G).values()
        b2 = nxt.betweenness_sequence(cs)
        assert_true(sum([abs(c - d) for c, d in zip(b1, b2)]) < 1e-14)

        assert_equal(nxt.eigenvalues(cs), [0, 1, 3, 3, 5, 7, 7, 8])

        # Degree Correlation
        assert_true(abs(nxt.degree_correlation(cs) + 0.593038821954) < 1e-12)
        assert_equal(nxt.degree_correlation('diiiddi'), -0.8)
        assert_equal(nxt.degree_correlation('did'), -1.0)
        assert_equal(nxt.degree_correlation('ddd'), 1.0)
        assert_equal(nxt.eigenvalues('dddiii'), [0, 0, 0, 0, 3, 3])
        assert_equal(nxt.eigenvalues('dddiiid'), [0, 1, 1, 1, 4, 4, 7]) 
Example #26
Source File: test_cluster.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_clustering(self):
        G = nx.Graph()
        assert_equal(list(nx.clustering(G, weight='weight').values()), [])
        assert_equal(nx.clustering(G), {}) 
Example #27
Source File: test_cluster.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_path(self):
        G = nx.path_graph(10)
        assert_equal(list(nx.clustering(G, weight='weight').values()),
                     [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0])
        assert_equal(nx.clustering(G, weight='weight'),
                     {0: 0.0, 1: 0.0, 2: 0.0, 3: 0.0, 4: 0.0,
                      5: 0.0, 6: 0.0, 7: 0.0, 8: 0.0, 9: 0.0}) 
Example #28
Source File: test_cluster.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_k5(self):
        G = nx.complete_graph(5)
        assert_equal(list(nx.clustering(G, weight='weight').values()), [1, 1, 1, 1, 1])
        assert_equal(nx.average_clustering(G, weight='weight'), 1)
        G.remove_edge(1, 2)
        assert_equal(list(nx.clustering(G, weight='weight').values()),
                     [5. / 6., 1.0, 1.0, 5. / 6., 5. / 6.])
        assert_equal(nx.clustering(G, [1, 4], weight='weight'), {1: 1.0, 4: 0.83333333333333337}) 
Example #29
Source File: test_cluster.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_triangle_and_edge(self):
        G = nx.cycle_graph(3)
        G.add_edge(0, 4, weight=2)
        assert_equal(nx.clustering(G)[0], 1.0 / 3.0)
        assert_equal(nx.clustering(G, weight='weight')[0], 1.0 / 6.0) 
Example #30
Source File: test_cluster.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_clustering(self):
        G = nx.Graph()
        assert_equal(list(nx.clustering(G).values()), [])
        assert_equal(nx.clustering(G), {})