Python networkx.average_shortest_path_length() Examples

The following are 23 code examples of networkx.average_shortest_path_length(). 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: 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 #2
Source File: fitness.py    From cdlib with BSD 2-Clause "Simplified" License 7 votes vote down vote up
def avg_distance(graph, communities, **kwargs):
    """Average distance.

    The average distance of a community is defined average path length across all possible pair of nodes composing it.

    :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_distance(g,communities)
    """

    return __quality_indexes(graph, communities,
                             lambda graph, coms: nx.average_shortest_path_length(nx.subgraph(graph, coms)), **kwargs) 
Example #3
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 #4
Source File: test_generic.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_specified_methods(self):
        G = nx.Graph()
        nx.add_cycle(G, range(7), weight=2)
        ans = nx.average_shortest_path_length(G,
                                              weight='weight',
                                              method='dijkstra')
        assert_almost_equal(ans, 4)
        ans = nx.average_shortest_path_length(G,
                                              weight='weight',
                                              method='bellman-ford')
        assert_almost_equal(ans, 4)
        G = nx.Graph()
        nx.add_path(G, range(5), weight=2)
        ans = nx.average_shortest_path_length(G,
                                              weight='weight',
                                              method='dijkstra')
        assert_almost_equal(ans, 4)
        ans = nx.average_shortest_path_length(G,
                                              weight='weight',
                                              method='bellman-ford')
        assert_almost_equal(ans, 4) 
Example #5
Source File: test_generic.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_path_graph(self):
        ans = nx.average_shortest_path_length(nx.path_graph(5))
        assert_almost_equal(ans, 2) 
Example #6
Source File: test_generic.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_trivial_graph(self):
        """Tests that the trivial graph has average path length zero,
        since there is exactly one path of length zero in the trivial
        graph.

        For more information, see issue #1960.

        """
        G = nx.trivial_graph()
        assert_equal(nx.average_shortest_path_length(G), 0) 
Example #7
Source File: test_generic.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_disconnected(self):
        g = nx.Graph()
        g.add_nodes_from(range(3))
        g.add_edge(0, 1)
        assert_raises(nx.NetworkXError, nx.average_shortest_path_length, g)
        g = g.to_directed()
        assert_raises(nx.NetworkXError, nx.average_shortest_path_length, g) 
Example #8
Source File: test_generic.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_weighted(self):
        G = nx.Graph()
        nx.add_cycle(G, range(7), weight=2)
        l = nx.average_shortest_path_length(G, weight='weight')
        assert_almost_equal(l, 4)
        G = nx.Graph()
        nx.add_path(G, range(5), weight=2)
        l = nx.average_shortest_path_length(G, weight='weight')
        assert_almost_equal(l, 4) 
Example #9
Source File: test_generic.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_path_graph(self):
        l = nx.average_shortest_path_length(nx.path_graph(5))
        assert_almost_equal(l, 2) 
Example #10
Source File: test_generic.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_cycle_graph(self):
        l = nx.average_shortest_path_length(nx.cycle_graph(7))
        assert_almost_equal(l, 2) 
Example #11
Source File: test_smallworld.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_lattice_reference():
    G = nx.connected_watts_strogatz_graph(50, 6, 1, seed=rng)
    Gl = lattice_reference(G, niter=1, seed=rng)
    L = nx.average_shortest_path_length(G)
    Ll = nx.average_shortest_path_length(Gl)
    assert_true(Ll > L)

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

    H = nx.Graph(((0, 1), (2, 3)))
    Hl = lattice_reference(H, niter=1) 
Example #12
Source File: test_generic.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_bad_method(self):
        G = nx.path_graph(2)
        nx.average_shortest_path_length(G, weight='weight', method='SPAM') 
Example #13
Source File: test_generic.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_null_graph(self):
        nx.average_shortest_path_length(nx.null_graph()) 
Example #14
Source File: test_generic.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_disconnected(self):
        g = nx.Graph()
        g.add_nodes_from(range(3))
        g.add_edge(0, 1)
        assert_raises(nx.NetworkXError, nx.average_shortest_path_length, g)
        g = g.to_directed()
        assert_raises(nx.NetworkXError, nx.average_shortest_path_length, g) 
Example #15
Source File: test_generic.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_weighted(self):
        G = nx.Graph()
        nx.add_cycle(G, range(7), weight=2)
        ans = nx.average_shortest_path_length(G, weight='weight')
        assert_almost_equal(ans, 4)
        G = nx.Graph()
        nx.add_path(G, range(5), weight=2)
        ans = nx.average_shortest_path_length(G, weight='weight')
        assert_almost_equal(ans, 4) 
Example #16
Source File: test_generic.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_cycle_graph(self):
        ans = nx.average_shortest_path_length(nx.cycle_graph(7))
        assert_almost_equal(ans, 2) 
Example #17
Source File: test_generic.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def test_average_shortest_disconnected(self):
        g = nx.Graph()
        g.add_nodes_from(range(3))
        g.add_edge(0, 1)
        assert_raises(nx.NetworkXError,nx.average_shortest_path_length,g)
        g = g.to_directed()
        assert_raises(nx.NetworkXError,nx.average_shortest_path_length,g) 
Example #18
Source File: test_generic.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def test_weighted_average_shortest_path(self):
        G=nx.Graph()
        G.add_cycle(range(7),weight=2)
        l=nx.average_shortest_path_length(G,weight='weight')
        assert_almost_equal(l,4)
        G=nx.Graph()
        G.add_path(range(5),weight=2)
        l=nx.average_shortest_path_length(G,weight='weight')
        assert_almost_equal(l,4) 
Example #19
Source File: test_generic.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def test_average_shortest_path(self):
        l=nx.average_shortest_path_length(self.cycle)
        assert_almost_equal(l,2)
        l=nx.average_shortest_path_length(nx.path_graph(5))
        assert_almost_equal(l,2) 
Example #20
Source File: network_analysis.py    From ditto with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def average_path_length(self, *args):
        """Returns the average path length of the network."""
        if args:
            try:
                return nx.average_shortest_path_length(args[0])
            except ZeroDivisionError:
                return 0
        else:
            return nx.average_shortest_path_length(self.G.graph) 
Example #21
Source File: generic.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 4 votes vote down vote up
def average_shortest_path_length(G, weight=None):
    r"""Return the average shortest path length.

    The average shortest path length is

    .. math::

       a =\sum_{s,t \in V} \frac{d(s, t)}{n(n-1)}

    where `V` is the set of nodes in `G`,
    `d(s, t)` is the shortest path from `s` to `t`,
    and `n` is the number of nodes in `G`.

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

    weight : None or string, optional (default = None)
       If None, every edge has weight/distance/cost 1.
       If a string, use this edge attribute as the edge weight.
       Any edge attribute not present defaults to 1.

    Raises
    ------
    NetworkXError:
       if the graph is not connected.

    Examples
    --------
    >>> G=nx.path_graph(5)
    >>> print(nx.average_shortest_path_length(G))
    2.0

    For disconnected graphs you can compute the average shortest path
    length for each component:
    >>> G=nx.Graph([(1,2),(3,4)])
    >>> for g in nx.connected_component_subgraphs(G):
    ...     print(nx.average_shortest_path_length(g))
    1.0
    1.0

    """
    if G.is_directed():
        if not nx.is_weakly_connected(G):
            raise nx.NetworkXError("Graph is not connected.")
    else:
        if not nx.is_connected(G):
            raise nx.NetworkXError("Graph is not connected.")
    avg=0.0
    if weight is None:
        for node in G:
            path_length=nx.single_source_shortest_path_length(G, node)
            avg += sum(path_length.values())
    else:
        for node in G:
            path_length=nx.single_source_dijkstra_path_length(G, node, weight=weight)
            avg += sum(path_length.values())
    n=len(G)
    return avg/(n*(n-1)) 
Example #22
Source File: data.py    From GraphRNN with MIT License 4 votes vote down vote up
def Graph_synthetic(seed):
    G = nx.Graph()
    np.random.seed(seed)
    base = np.repeat(np.eye(5), 20, axis=0)
    rand = np.random.randn(100, 5) * 0.05
    node_features = base + rand

    # # print('node features')
    # for i in range(node_features.shape[0]):
    #     print(np.around(node_features[i], decimals=4))

    node_distance_l1 = np.ones((node_features.shape[0], node_features.shape[0]))
    node_distance_np = np.zeros((node_features.shape[0], node_features.shape[0]))
    for i in range(node_features.shape[0]):
        for j in range(node_features.shape[0]):
            if i != j:
                node_distance_l1[i,j] = np.sum(np.abs(node_features[i] - node_features[j]))
                # print('node distance', node_distance_l1[i,j])
                node_distance_np[i, j] = 1 / np.sum(np.abs(node_features[i] - node_features[j]) ** 2)

    print('node distance max', np.max(node_distance_l1))
    print('node distance min', np.min(node_distance_l1))
    node_distance_np_sum = np.sum(node_distance_np, axis=1, keepdims=True)
    embedding_dist = node_distance_np / node_distance_np_sum

    # generate the graph
    average_degree = 9
    for i in range(node_features.shape[0]):
        for j in range(i + 1, embedding_dist.shape[0]):
            p = np.random.rand()
            if p < embedding_dist[i, j] * average_degree:
                G.add_edge(i, j)

    G.remove_nodes_from(nx.isolates(G))
    print('num of nodes', G.number_of_nodes())
    print('num of edges', 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', sum(G_deg_sum) / G.number_of_nodes())
    print('average path length', nx.average_shortest_path_length(G))
    print('diameter', nx.diameter(G))
    G_cluster = sorted(list(nx.clustering(G).values()))
    print('average clustering coefficient', sum(G_cluster) / len(G_cluster))
    print('Graph generation complete!')
    # node_features = np.concatenate((node_features, np.zeros((1,node_features.shape[1]))),axis=0)

    return G, node_features

# G = Graph_synthetic(10)



# return adj and features from a single graph 
Example #23
Source File: data.py    From graph-generation with MIT License 4 votes vote down vote up
def Graph_synthetic(seed):
    G = nx.Graph()
    np.random.seed(seed)
    base = np.repeat(np.eye(5), 20, axis=0)
    rand = np.random.randn(100, 5) * 0.05
    node_features = base + rand

    # # print('node features')
    # for i in range(node_features.shape[0]):
    #     print(np.around(node_features[i], decimals=4))

    node_distance_l1 = np.ones((node_features.shape[0], node_features.shape[0]))
    node_distance_np = np.zeros((node_features.shape[0], node_features.shape[0]))
    for i in range(node_features.shape[0]):
        for j in range(node_features.shape[0]):
            if i != j:
                node_distance_l1[i,j] = np.sum(np.abs(node_features[i] - node_features[j]))
                # print('node distance', node_distance_l1[i,j])
                node_distance_np[i, j] = 1 / np.sum(np.abs(node_features[i] - node_features[j]) ** 2)

    print('node distance max', np.max(node_distance_l1))
    print('node distance min', np.min(node_distance_l1))
    node_distance_np_sum = np.sum(node_distance_np, axis=1, keepdims=True)
    embedding_dist = node_distance_np / node_distance_np_sum

    # generate the graph
    average_degree = 9
    for i in range(node_features.shape[0]):
        for j in range(i + 1, embedding_dist.shape[0]):
            p = np.random.rand()
            if p < embedding_dist[i, j] * average_degree:
                G.add_edge(i, j)

    G.remove_nodes_from(nx.isolates(G))
    print('num of nodes', G.number_of_nodes())
    print('num of edges', 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', sum(G_deg_sum) / G.number_of_nodes())
    print('average path length', nx.average_shortest_path_length(G))
    print('diameter', nx.diameter(G))
    G_cluster = sorted(list(nx.clustering(G).values()))
    print('average clustering coefficient', sum(G_cluster) / len(G_cluster))
    print('Graph generation complete!')
    # node_features = np.concatenate((node_features, np.zeros((1,node_features.shape[1]))),axis=0)

    return G, node_features

# G = Graph_synthetic(10)



# return adj and features from a single graph