Python networkx.add_path() Examples

The following are 30 code examples of networkx.add_path(). 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_algebraic_connectivity.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_cycle(self):
        path = list(range(10))
        G = nx.Graph()
        nx.add_path(G, path, weight=5)
        G.add_edge(path[-1], path[0], weight=1)
        A = nx.laplacian_matrix(G).todense()
        for normalized in (False, True):
            for method in methods:
                try:
                    order = nx.spectral_ordering(G, normalized=normalized,
                                                 method=method)
                except nx.NetworkXError as e:
                    if e.args not in (('Cholesky solver unavailable.',),
                                      ('LU solver unavailable.',)):
                        raise
                else:
                    if not normalized:
                        ok_(order in [[1, 2, 0, 3, 4, 5, 6, 9, 7, 8],
                                      [8, 7, 9, 6, 5, 4, 3, 0, 2, 1]])
                    else:
                        ok_(order in [[1, 2, 3, 0, 4, 5, 9, 6, 7, 8],
                                      [8, 7, 6, 9, 5, 4, 0, 3, 2, 1]]) 
Example #2
Source File: test_shp.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def testload(self):

        def compare_graph_paths_names(g, paths, names):
            expected = nx.DiGraph()
            for p in paths:
                nx.add_path(expected, p)
            assert_equal(sorted(expected.nodes), sorted(g.nodes))
            assert_equal(sorted(expected.edges()), sorted(g.edges()))
            g_names = [g.get_edge_data(s, e)['Name'] for s, e in g.edges()]
            assert_equal(names, sorted(g_names))

        # simplified
        G = nx.read_shp(self.shppath)
        compare_graph_paths_names(G, self.simplified_paths,
                                  self.simplified_names)

        # unsimplified
        G = nx.read_shp(self.shppath, simplify=False)
        compare_graph_paths_names(G, self.paths, self.names)

        # multiline unsimplified
        G = nx.read_shp(self.multi_shppath, simplify=False)
        compare_graph_paths_names(G, self.paths, self.multi_names) 
Example #3
Source File: test_project.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_generic_weighted_projected_graph_simple(self):
        def shared(G, u, v):
            return len(set(G[u]) & set(G[v]))
        B = nx.path_graph(5)
        G = bipartite.generic_weighted_projected_graph(B, [0, 2, 4], weight_function=shared)
        assert_nodes_equal(list(G), [0, 2, 4])
        assert_edges_equal(list(list(G.edges(data=True))),
                           [(0, 2, {'weight': 1}), (2, 4, {'weight': 1})])

        G = bipartite.generic_weighted_projected_graph(B, [0, 2, 4])
        assert_nodes_equal(list(G), [0, 2, 4])
        assert_edges_equal(list(list(G.edges(data=True))),
                           [(0, 2, {'weight': 1}), (2, 4, {'weight': 1})])
        B = nx.DiGraph()
        nx.add_path(B, range(5))
        G = bipartite.generic_weighted_projected_graph(B, [0, 2, 4])
        assert_nodes_equal(list(G), [0, 2, 4])
        assert_edges_equal(list(G.edges(data=True)),
                           [(0, 2, {'weight': 1}), (2, 4, {'weight': 1})]) 
Example #4
Source File: test_gexf.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_default_attribute(self):
        G = nx.Graph()
        G.add_node(1, label='1', color='green')
        nx.add_path(G, [0, 1, 2, 3])
        G.add_edge(1, 2, foo=3)
        G.graph['node_default'] = {'color': 'yellow'}
        G.graph['edge_default'] = {'foo': 7}
        fh = io.BytesIO()
        nx.write_gexf(G, fh)
        fh.seek(0)
        H = nx.read_gexf(fh, node_type=int)
        assert_equal(sorted(G.nodes()), sorted(H.nodes()))
        assert_equal(
            sorted(sorted(e) for e in G.edges()),
            sorted(sorted(e) for e in H.edges()))
        # Reading a gexf graph always sets mode attribute to either
        # 'static' or 'dynamic'. Remove the mode attribute from the
        # read graph for the sake of comparing remaining attributes.
        del H.graph['mode']
        assert_equal(G.graph, H.graph) 
Example #5
Source File: test_generic.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_all_shortest_paths(self):
        G = nx.Graph()
        nx.add_path(G, [0, 1, 2, 3])
        nx.add_path(G, [0, 10, 20, 3])
        assert_equal([[0, 1, 2, 3], [0, 10, 20, 3]],
                     sorted(nx.all_shortest_paths(G, 0, 3)))
        # with weights
        G = nx.Graph()
        nx.add_path(G, [0, 1, 2, 3])
        nx.add_path(G, [0, 10, 20, 3])
        assert_equal([[0, 1, 2, 3], [0, 10, 20, 3]],
                     sorted(nx.all_shortest_paths(G, 0, 3, weight='weight')))
        # weights and method specified
        G = nx.Graph()
        nx.add_path(G, [0, 1, 2, 3])
        nx.add_path(G, [0, 10, 20, 3])
        assert_equal([[0, 1, 2, 3], [0, 10, 20, 3]],
                     sorted(nx.all_shortest_paths(G, 0, 3, weight='weight',
                                                  method='dijkstra')))
        G = nx.Graph()
        nx.add_path(G, [0, 1, 2, 3])
        nx.add_path(G, [0, 10, 20, 3])
        assert_equal([[0, 1, 2, 3], [0, 10, 20, 3]],
                     sorted(nx.all_shortest_paths(G, 0, 3, weight='weight',
                                                  method='bellman-ford'))) 
Example #6
Source File: test_multigraph.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def setup(self):
        # Create a doubly-linked path graph on five nodes.
        G = nx.MultiGraph()
        nx.add_path(G, range(5))
        nx.add_path(G, range(5))
        # Add some node, edge, and graph attributes.
        for i in range(5):
            G.nodes[i]['name'] = 'node{}'.format(i)
        G.adj[0][1][0]['name'] = 'edge010'
        G.adj[0][1][1]['name'] = 'edge011'
        G.adj[3][4][0]['name'] = 'edge340'
        G.adj[3][4][1]['name'] = 'edge341'
        G.graph['name'] = 'graph'
        # Get the subgraph induced by one of the first edges and one of
        # the last edges.
        self.G = G
        self.H = G.edge_subgraph([(0, 1, 0), (3, 4, 1)]) 
Example #7
Source File: test_betweenness_centrality.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_disconnected_path_endpoints(self):
        """Betweenness centrality: disconnected path endpoints"""
        G = nx.Graph()
        nx.add_path(G, [0, 1, 2])
        nx.add_path(G, [3, 4, 5, 6])
        b_answer = {0: 2, 1: 3, 2: 2, 3: 3, 4: 5, 5: 5, 6: 3}
        b = nx.betweenness_centrality(G,
                                      weight=None,
                                      normalized=False,
                                      endpoints=True)
        for n in sorted(G):
            assert_almost_equal(b[n], b_answer[n])
        # normalized = True case
        b = nx.betweenness_centrality(G,
                                      weight=None,
                                      normalized=True,
                                      endpoints=True)
        for n in sorted(G):
            assert_almost_equal(b[n], b_answer[n] / 21) 
Example #8
Source File: test_simple_paths.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_bidirectional_dijkstra_ignore():
    G = nx.Graph()
    nx.add_path(G, [1, 2, 10])
    nx.add_path(G, [1, 3, 10])
    assert_raises(
        nx.NetworkXNoPath,
        _bidirectional_dijkstra,
        G,
        1, 2,
        ignore_nodes=[1],
    )
    assert_raises(
        nx.NetworkXNoPath,
        _bidirectional_dijkstra,
        G,
        1, 2,
        ignore_nodes=[2],
    )
    assert_raises(
        nx.NetworkXNoPath,
        _bidirectional_dijkstra,
        G,
        1, 2,
        ignore_nodes=[1, 2],
    ) 
Example #9
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 #10
Source File: test_multidigraph.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def setup(self):
        # Create a quadruply-linked path graph on five nodes.
        G = nx.MultiDiGraph()
        nx.add_path(G, range(5))
        nx.add_path(G, range(5))
        nx.add_path(G, reversed(range(5)))
        nx.add_path(G, reversed(range(5)))
        # Add some node, edge, and graph attributes.
        for i in range(5):
            G.nodes[i]['name'] = 'node{}'.format(i)
        G.adj[0][1][0]['name'] = 'edge010'
        G.adj[0][1][1]['name'] = 'edge011'
        G.adj[3][4][0]['name'] = 'edge340'
        G.adj[3][4][1]['name'] = 'edge341'
        G.graph['name'] = 'graph'
        # Get the subgraph induced by one of the first edges and one of
        # the last edges.
        self.G = G
        self.H = G.edge_subgraph([(0, 1, 0), (3, 4, 1)]) 
Example #11
Source File: test_function.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_info_digraph(self):
        G = nx.DiGraph(name='path_graph(5)')
        nx.add_path(G, [0, 1, 2, 3, 4])
        info = nx.info(G)
        expected_graph_info = '\n'.join(['Name: path_graph(5)',
                                         'Type: DiGraph',
                                         'Number of nodes: 5',
                                         'Number of edges: 4',
                                         'Average in degree:   0.8000',
                                         'Average out degree:   0.8000'])
        assert_equal(info, expected_graph_info)

        info = nx.info(G, n=1)
        expected_node_info = '\n'.join(
            ['Node 1 has the following properties:',
             'Degree: 2',
             'Neighbors: 2'])
        assert_equal(info, expected_node_info)

        assert_raises(nx.NetworkXError, nx.info, G, n=-1) 
Example #12
Source File: test_cuts.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_not_connected():
    G = nx.Graph()
    nx.add_path(G, [1, 2, 3])
    nx.add_path(G, [4, 5])
    for interface_func in [nx.minimum_edge_cut, nx.minimum_node_cut]:
        for flow_func in flow_funcs:
            assert_raises(nx.NetworkXError, interface_func, G,
                          flow_func=flow_func) 
Example #13
Source File: test_disjoint_paths.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_isolated_edges():
    G = nx.Graph()
    G.add_node(1)
    nx.add_path(G, [4, 5])
    list(nx.edge_disjoint_paths(G, 1, 5)) 
Example #14
Source File: test_connectivity.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_not_connected():
    G = nx.Graph()
    nx.add_path(G, [1, 2, 3])
    nx.add_path(G, [4, 5])
    for flow_func in flow_funcs:
        assert_equal(nx.node_connectivity(G), 0,
                     msg=msg.format(flow_func.__name__))
        assert_equal(nx.edge_connectivity(G), 0,
                     msg=msg.format(flow_func.__name__)) 
Example #15
Source File: test_connectivity.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_all_pairs_connectivity(self):
        G = nx.Graph()
        nodes = [0, 1, 2, 3]
        nx.add_path(G, nodes)
        A = {n: {} for n in G}
        for u, v in itertools.combinations(nodes, 2):
            A[u][v] = A[v][u] = nx.node_connectivity(G, u, v)
        C = nx.all_pairs_node_connectivity(G)
        assert_equal(sorted((k, sorted(v)) for k, v in A.items()),
                     sorted((k, sorted(v)) for k, v in C.items())) 
Example #16
Source File: test_simple_paths.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_bidirectional_dijkstra_no_path():
    G = nx.Graph()
    nx.add_path(G, [1, 2, 3])
    nx.add_path(G, [4, 5, 6])
    path = _bidirectional_dijkstra(G, 1, 6) 
Example #17
Source File: test_betweenness_centrality.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_directed_path_normalized(self):
        """Betweenness centrality: directed path normalized"""
        G = nx.DiGraph()
        nx.add_path(G, [0, 1, 2])
        b = nx.betweenness_centrality(G,
                                      weight=None,
                                      normalized=True)
        b_answer = {0: 0.0, 1: 0.5, 2: 0.0}
        for n in sorted(G):
            assert_almost_equal(b[n], b_answer[n]) 
Example #18
Source File: test_betweenness_centrality.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_directed_path(self):
        """Betweenness centrality: directed path"""
        G = nx.DiGraph()
        nx.add_path(G, [0, 1, 2])
        b = nx.betweenness_centrality(G,
                                      weight=None,
                                      normalized=False)
        b_answer = {0: 0.0, 1: 1.0, 2: 0.0}
        for n in sorted(G):
            assert_almost_equal(b[n], b_answer[n]) 
Example #19
Source File: test_betweenness_centrality_subset.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_P5_directed(self):
        """Betweenness centrality: P5 directed"""
        G = nx.DiGraph()
        nx.add_path(G, range(5))
        b_answer = {0: 0, 1: 1, 2: 1, 3: 0, 4: 0, 5: 0}
        b = nx.betweenness_centrality_subset(G, sources=[0], targets=[3],
                                             weight=None)
        for n in sorted(G):
            assert_almost_equal(b[n], b_answer[n]) 
Example #20
Source File: test_cuts.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_not_weakly_connected():
    G = nx.DiGraph()
    nx.add_path(G, [1, 2, 3])
    nx.add_path(G, [4, 5])
    for interface_func in [nx.minimum_edge_cut, nx.minimum_node_cut]:
        for flow_func in flow_funcs:
            assert_raises(nx.NetworkXError, interface_func, G,
                          flow_func=flow_func) 
Example #21
Source File: test_disjoint_paths.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_isolated_nodes():
    G = nx.Graph()
    G.add_node(1)
    nx.add_path(G, [4, 5])
    list(nx.node_disjoint_paths(G, 1, 5)) 
Example #22
Source File: test_connectivity.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_all_pairs_connectivity_directed(self):
        G = nx.DiGraph()
        nodes = [0, 1, 2, 3]
        nx.add_path(G, nodes)
        A = {n: {} for n in G}
        for u, v in itertools.permutations(nodes, 2):
            A[u][v] = nx.node_connectivity(G, u, v)
        C = nx.all_pairs_node_connectivity(G)
        assert_equal(sorted((k, sorted(v)) for k, v in A.items()),
                     sorted((k, sorted(v)) for k, v in C.items())) 
Example #23
Source File: test_disjoint_paths.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_not_connected_nodes():
    G = nx.Graph()
    nx.add_path(G, [1, 2, 3])
    nx.add_path(G, [4, 5])
    list(nx.node_disjoint_paths(G, 1, 5)) 
Example #24
Source File: test_disjoint_paths.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_not_weakly_connected_nodes():
    G = nx.DiGraph()
    nx.add_path(G, [1, 2, 3])
    nx.add_path(G, [4, 5])
    list(nx.node_disjoint_paths(G, 1, 5)) 
Example #25
Source File: test_disjoint_paths.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_not_weakly_connected_edges():
    G = nx.DiGraph()
    nx.add_path(G, [1, 2, 3])
    nx.add_path(G, [4, 5])
    list(nx.edge_disjoint_paths(G, 1, 5)) 
Example #26
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 #27
Source File: test_weighted.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_bidirectional_dijkstra_no_path(self):
        G = nx.Graph()
        nx.add_path(G, [1, 2, 3])
        nx.add_path(G, [4, 5, 6])
        path = nx.bidirectional_dijkstra(G, 1, 6) 
Example #28
Source File: test_dfs.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def setUp(self):
        # a tree
        G = nx.Graph()
        nx.add_path(G, [0, 1, 2, 3, 4, 5, 6])
        nx.add_path(G, [2, 7, 8, 9, 10])
        self.G = G
        # a disconnected graph
        D = nx.Graph()
        D.add_edges_from([(0, 1), (2, 3)])
        nx.add_path(D, [2, 7, 8, 9, 10])
        self.D = D 
Example #29
Source File: test_edgebfs.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_digraph_ignore2(self):
        G = nx.DiGraph()
        nx.add_path(G, range(4))
        x = list(edge_bfs(G, [0], orientation='ignore'))
        x_ = [(0, 1, FORWARD), (1, 2, FORWARD), (2, 3, FORWARD)]
        assert_equal(x, x_) 
Example #30
Source File: test_edgebfs.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_digraph_rev2(self):
        G = nx.DiGraph()
        nx.add_path(G, range(4))
        x = list(edge_bfs(G, [3], orientation='reverse'))
        x_ = [(2, 3, REVERSE), (1, 2, REVERSE), (0, 1, REVERSE)]
        assert_equal(x, x_)