Python networkx.average_clustering() Examples

The following are 30 code examples of networkx.average_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: fitness.py    From cdlib with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def avg_transitivity(graph, communities, **kwargs):
    """Average transitivity.

    The average transitivity of a community is defined the as the average clustering coefficient of its nodes w.r.t. their connection within the community itself.

    :param graph: a networkx/igraph object
    :param communities: NodeClustering object
    :param summary: boolean. If **True** it is returned an aggregated score for the partition is returned, otherwise individual-community ones. Default **True**.
    :return: If **summary==True** a FitnessResult object, otherwise a list of floats.

    Example:

    >>> from cdlib.algorithms import louvain
    >>> from cdlib import evaluation
    >>> g = nx.karate_club_graph()
    >>> communities = louvain(g)
    >>> scd = evaluation.avg_transitivity(g,communities)
    """

    return __quality_indexes(graph, communities,
                             lambda graph, coms: nx.average_clustering(nx.subgraph(graph, coms)),
                             **kwargs) 
Example #2
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 #3
Source File: test_approx_clust_coeff.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_complete():
    G = nx.complete_graph(5)
    assert_equal(average_clustering(G, trials=int(len(G)/2)), 1)
    G = nx.complete_graph(7)
    assert_equal(average_clustering(G, trials=int(len(G)/2)), 1) 
Example #4
Source File: test_approx_clust_coeff.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_empty():
    G = nx.empty_graph(5)
    assert_equal(average_clustering(G, trials=int(len(G)/2)), 0) 
Example #5
Source File: test_approx_clust_coeff.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_dodecahedral():
    # Actual coefficient is 0
    G = nx.dodecahedral_graph()
    assert_equal(average_clustering(G, trials=int(len(G)/2)),
                 nx.average_clustering(G)) 
Example #6
Source File: test_approx_clust_coeff.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_petersen():
    # Actual coefficient is 0
    G = nx.petersen_graph()
    assert_equal(average_clustering(G, trials=int(len(G)/2)),
                 nx.average_clustering(G)) 
Example #7
Source File: test_cluster.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_average_clustering():
    G = nx.cycle_graph(3)
    G.add_edge(2, 3)
    assert_equal(nx.average_clustering(G), (1 + 1 + 1 / 3.0) / 4.0)
    assert_equal(nx.average_clustering(G, count_zeros=True), (1 + 1 + 1 / 3.0) / 4.0)
    assert_equal(nx.average_clustering(G, count_zeros=False), (1 + 1 + 1 / 3.0) / 3.0) 
Example #8
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).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 #9
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 #10
Source File: test_approx_clust_coeff.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_complete():
    G = nx.complete_graph(5)
    assert_equal(average_clustering(G, trials=int(len(G) / 2)), 1)
    G = nx.complete_graph(7)
    assert_equal(average_clustering(G, trials=int(len(G) / 2)), 1) 
Example #11
Source File: test_approx_clust_coeff.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_dodecahedral():
    # Actual coefficient is 0
    G = nx.dodecahedral_graph()
    assert_equal(average_clustering(G, trials=int(len(G) / 2)),
                 nx.average_clustering(G)) 
Example #12
Source File: test_approx_clust_coeff.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_tetrahedral():
    # Actual coefficient is 1
    G = nx.tetrahedral_graph()
    assert_equal(average_clustering(G, trials=int(len(G) / 2)),
                 nx.average_clustering(G)) 
Example #13
Source File: test_approx_clust_coeff.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_petersen_seed():
    # Actual coefficient is 0
    G = nx.petersen_graph()
    assert_equal(average_clustering(G, trials=int(len(G) / 2), seed=1),
                 nx.average_clustering(G)) 
Example #14
Source File: test_approx_clust_coeff.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_petersen():
    # Actual coefficient is 0
    G = nx.petersen_graph()
    assert_equal(average_clustering(G, trials=int(len(G) / 2)),
                 nx.average_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_average_clustering():
    G = nx.cycle_graph(3)
    G.add_edge(2, 3)
    assert_equal(nx.average_clustering(G), (1 + 1 + 1 / 3.0) / 4.0)
    assert_equal(nx.average_clustering(G, count_zeros=True), (1 + 1 + 1 / 3.0) / 4.0)
    assert_equal(nx.average_clustering(G, count_zeros=False), (1 + 1 + 1 / 3.0) / 3.0) 
Example #16
Source File: plot_distributions.py    From AMLSim with Apache License 2.0 5 votes vote down vote up
def plot_clustering_coefficient(_g, _plot_img, interval=30):
    """Plot the clustering coefficient transition
    :param _g: Transaction graph
    :param _plot_img: Output image file
    :param interval: Simulation step interval for plotting
    (it takes too much time to compute clustering coefficient)
    :return:
    """
    date_list = get_date_list(_g)

    gg = nx.Graph()
    edges = defaultdict(list)
    for k, v in nx.get_edge_attributes(_g, "date").items():
        e = (k[0], k[1])
        edges[v].append(e)

    sample_dates = list()
    values = list()
    for i, t in enumerate(date_list):
        gg.add_edges_from(edges[t])
        if i % interval == 0:
            v = nx.average_clustering(gg) if gg.number_of_nodes() else 0.0
            sample_dates.append(t)
            values.append(v)
            print("Clustering coefficient at %s: %f" % (str(t), v))

    plt.figure(figsize=(16, 12))
    plt.clf()
    plt.plot(sample_dates, values, 'bo-')
    plt.title("Clustering Coefficient Transition")
    plt.xlabel("date")
    plt.ylabel("Clustering Coefficient")
    plt.savefig(_plot_img) 
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, create_using=nx.DiGraph())
        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()),
                     [11. / 12., 1.0, 1.0, 11. / 12., 11. / 12.])
        assert_equal(nx.clustering(G, [1, 4], weight='weight'), {1: 1.0, 4: 11. /12.})
        G.remove_edge(2, 1)
        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_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 #19
Source File: test_smallworld.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_random_reference():
    G = nx.connected_watts_strogatz_graph(50, 6, 0.1, seed=rng)
    Gr = random_reference(G, niter=1, seed=rng)
    C = nx.average_clustering(G)
    Cr = nx.average_clustering(Gr)
    assert_true(C > Cr)

    assert_raises(nx.NetworkXError, random_reference, nx.Graph())
    assert_raises(nx.NetworkXNotImplemented, random_reference, nx.DiGraph())

    H = nx.Graph(((0, 1), (2, 3)))
    Hl = random_reference(H, niter=1, seed=rng) 
Example #20
Source File: test_approx_clust_coeff.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def test_complete():
    G = nx.complete_graph(5)
    assert_equal(average_clustering(G, trials=int(len(G)/2)), 1)
    G = nx.complete_graph(7)
    assert_equal(average_clustering(G, trials=int(len(G)/2)), 1) 
Example #21
Source File: test_approx_clust_coeff.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def test_empty():
    G = nx.empty_graph(5)
    assert_equal(average_clustering(G, trials=int(len(G)/2)), 0) 
Example #22
Source File: test_approx_clust_coeff.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def test_dodecahedral():
    # Actual coefficient is 0
    G = nx.dodecahedral_graph()
    assert_equal(average_clustering(G, trials=int(len(G)/2)),
                 nx.average_clustering(G)) 
Example #23
Source File: test_approx_clust_coeff.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def test_petersen():
    # Actual coefficient is 0
    G = nx.petersen_graph()
    assert_equal(average_clustering(G, trials=int(len(G)/2)),
                 nx.average_clustering(G)) 
Example #24
Source File: test_cluster.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def test_average_clustering():
    G=nx.cycle_graph(3)
    G.add_edge(2,3)
    assert_equal(nx.average_clustering(G),(1+1+1/3.0)/4.0)
    assert_equal(nx.average_clustering(G,count_zeros=True),(1+1+1/3.0)/4.0)
    assert_equal(nx.average_clustering(G,count_zeros=False),(1+1+1/3.0)/3.0) 
Example #25
Source File: test_cluster.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 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 #26
Source File: test_cluster.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.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 #27
Source File: plot_stats.py    From GEM-Benchmark with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_clustering_coeff(edge_list):
    G = nx.from_edgelist(edgelist=edge_list)
    clust_coeff = nx.average_clustering(G)
    # print(nx.number_of_nodes(G), ' : ',clust_coeff)
    return clust_coeff 
Example #28
Source File: cluster.py    From Carnets with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def average_clustering(G, nodes=None, weight=None, count_zeros=True):
    r"""Compute the average clustering coefficient for the graph G.

    The clustering coefficient for the graph is the average,

    .. math::

       C = \frac{1}{n}\sum_{v \in G} c_v,

    where :math:`n` is the number of nodes in `G`.

    Parameters
    ----------
    G : graph

    nodes : container of nodes, optional (default=all nodes in G)
       Compute average clustering for nodes in this container.

    weight : string or None, optional (default=None)
       The edge attribute that holds the numerical value used as a weight.
       If None, then each edge has weight 1.

    count_zeros : bool
       If False include only the nodes with nonzero clustering in the average.

    Returns
    -------
    avg : float
       Average clustering

    Examples
    --------
    >>> G=nx.complete_graph(5)
    >>> print(nx.average_clustering(G))
    1.0

    Notes
    -----
    This is a space saving routine; it might be faster
    to use the clustering function to get a list and then take the average.

    Self loops are ignored.

    References
    ----------
    .. [1] Generalizations of the clustering coefficient to weighted
       complex networks by J. Saramäki, M. Kivelä, J.-P. Onnela,
       K. Kaski, and J. Kertész, Physical Review E, 75 027105 (2007).
       http://jponnela.com/web_documents/a9.pdf
    .. [2] Marcus Kaiser,  Mean clustering coefficients: the role of isolated
       nodes and leafs on clustering measures for small-world networks.
       https://arxiv.org/abs/0802.2512
    """
    c = clustering(G, nodes, weight=weight).values()
    if not count_zeros:
        c = [v for v in c if v > 0]
    return sum(c) / len(c) 
Example #29
Source File: cluster.py    From aws-kube-codesuite with Apache License 2.0 4 votes vote down vote up
def average_clustering(G, nodes=None, weight=None, count_zeros=True):
    r"""Compute the average clustering coefficient for the graph G.

    The clustering coefficient for the graph is the average,

    .. math::

       C = \frac{1}{n}\sum_{v \in G} c_v,

    where `n` is the number of nodes in `G`.

    Parameters
    ----------
    G : graph

    nodes : container of nodes, optional (default=all nodes in G)
       Compute average clustering for nodes in this container.

    weight : string or None, optional (default=None)
       The edge attribute that holds the numerical value used as a weight.
       If None, then each edge has weight 1.

    count_zeros : bool
       If False include only the nodes with nonzero clustering in the average.

    Returns
    -------
    avg : float
       Average clustering

    Examples
    --------
    >>> G=nx.complete_graph(5)
    >>> print(nx.average_clustering(G))
    1.0

    Notes
    -----
    This is a space saving routine; it might be faster
    to use the clustering function to get a list and then take the average.

    Self loops are ignored.

    References
    ----------
    .. [1] Generalizations of the clustering coefficient to weighted
       complex networks by J. Saramäki, M. Kivelä, J.-P. Onnela,
       K. Kaski, and J. Kertész, Physical Review E, 75 027105 (2007).
       http://jponnela.com/web_documents/a9.pdf
    .. [2] Marcus Kaiser,  Mean clustering coefficients: the role of isolated
       nodes and leafs on clustering measures for small-world networks.
       https://arxiv.org/abs/0802.2512
    """
    c = clustering(G, nodes, weight=weight).values()
    if not count_zeros:
        c = [v for v in c if v > 0]
    return sum(c) / len(c) 
Example #30
Source File: cluster.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 4 votes vote down vote up
def average_clustering(G, nodes=None, weight=None, count_zeros=True):
    r"""Compute the average clustering coefficient for the graph G.

    The clustering coefficient for the graph is the average, 

    .. math::

       C = \frac{1}{n}\sum_{v \in G} c_v,
       
    where `n` is the number of nodes in `G`.

    Parameters
    ----------
    G : graph

    nodes : container of nodes, optional (default=all nodes in G)
       Compute average clustering for nodes in this container. 

    weight : string or None, optional (default=None)
       The edge attribute that holds the numerical value used as a weight.
       If None, then each edge has weight 1.

    count_zeros : bool
       If False include only the nodes with nonzero clustering in the average.

    Returns
    -------
    avg : float
       Average clustering
    
    Examples
    --------
    >>> G=nx.complete_graph(5)
    >>> print(nx.average_clustering(G))
    1.0

    Notes
    -----
    This is a space saving routine; it might be faster
    to use the clustering function to get a list and then take the average.

    Self loops are ignored.

    References
    ----------
    .. [1] Generalizations of the clustering coefficient to weighted 
       complex networks by J. Saramäki, M. Kivelä, J.-P. Onnela, 
       K. Kaski, and J. Kertész, Physical Review E, 75 027105 (2007).  
       http://jponnela.com/web_documents/a9.pdf
    .. [2] Marcus Kaiser,  Mean clustering coefficients: the role of isolated 
       nodes and leafs on clustering measures for small-world networks.
       http://arxiv.org/abs/0802.2512
    """
    c=clustering(G,nodes,weight=weight).values()
    if not count_zeros:
        c = [v for v in c if v > 0]
    return sum(c)/float(len(c))