def test_directed_graph(self): G = nx.DiGraph() edges = [(1, 3), (1, 4), (2, 4), (2, 5), (3, 5), (1, 2)] G.add_edges_from(edges) p = nx.builtin.voterank(G, 3) assert p == [1, 2, 3] p = nx.builtin.voterank(G, 2) assert p == [1, 2] p = nx.builtin.voterank(G, 4) assert p == [1, 2, 3] p = nx.builtin.voterank(G) assert p == [1, 2, 3] G = nx.DiGraph() G.add_edge(1, 2, weight=1) G.add_edge(1, 3, weight=1) G.add_edge(3, 1, weight=1) p = nx.builtin.voterank(G, 4) assert p == [1] G = nx.DiGraph() edges = [(21, 91), (89, 20), (12, 21), (92, 12), (20, 21), (89, 91)] G.add_edges_from(edges) p = nx.builtin.voterank(G, 1) assert p == [89]
def setup_class(cls): global np np = pytest.importorskip('numpy') scipy = pytest.importorskip('scipy') G = nx.DiGraph() edges = [(1, 2), (1, 3), (2, 4), (3, 2), (3, 5), (4, 2), (4, 5), (4, 6), (5, 6), (5, 7), (5, 8), (6, 8), (7, 1), (7, 5), (7, 8), (8, 6), (8, 7)] G.add_edges_from(edges, weight=2.0) cls.G = G.reverse() cls.G.alpha = 0.1 cls.G.evc = [ 0.3289589783189635, 0.2832077296243516, 0.3425906003685471, 0.3970420865198392, 0.41074871061646284, 0.272257430756461, 0.4201989685435462, 0.34229059218038554, ] H = nx.DiGraph(edges) cls.H = G.reverse() cls.H.alpha = 0.1 cls.H.evc = [ 0.3289589783189635, 0.2832077296243516, 0.3425906003685471, 0.3970420865198392, 0.41074871061646284, 0.272257430756461, 0.4201989685435462, 0.34229059218038554, ]
def setup_method(self): data_dir = os.path.expandvars("${GS_TEST_DIR}/networkx") self.Graph = nx.DiGraph # build K3 self.k3edges = [(0, 1), (0, 2), (1, 2)] self.k3nodes = [0, 1, 2] self.k3 = k3_graph(data_dir, True) self.K3 = nx.DiGraph(self.k3, default_label="vertex") self.p3 = p3_graph(data_dir, True) self.P3 = nx.DiGraph(self.p3, default_label="vertex")
def setup_class(cls): from networkx import convert_node_labels_to_integers as cnlti from networkx import grid_2d_graph grid = cnlti(grid_2d_graph(4, 4), first_label=1, ordering="sorted") cls.grid = nx.Graph(grid) cls.cycle = nx.cycle_graph(7) cls.directed_cycle = nx.cycle_graph(7, create_using=nx.DiGraph()) cls.neg_weights = nx.DiGraph() cls.neg_weights.add_edge(0, 1, weight=1) cls.neg_weights.add_edge(0, 2, weight=3) cls.neg_weights.add_edge(1, 3, weight=1) cls.neg_weights.add_edge(2, 3, weight=-2)
def gnm_random_graph(n, m, seed=None, directed=False): if directed: G = nx.DiGraph() else: G = nx.Graph() G.add_nodes_from(range(n)) if n == 1: return G max_edges = n * (n - 1) if not directed: max_edges /= 2.0 if m >= max_edges: return complete_graph(n, create_using=G) nlist = list(G) edge_count = 0 while edge_count < m: # generate random edge,u,v u = seed.choice(nlist) v = seed.choice(nlist) if u == v: continue else: G.add_edge(u, v) edge_count = edge_count + 1 return G
def _relabel_inplace(G, mapping): old_labels = set(mapping.keys()) new_labels = set(mapping.values()) if len(old_labels & new_labels) > 0: # labels sets overlap # can we topological sort and still do the relabeling? D = nx.DiGraph(list(mapping.items())) D.remove_edges_from(nx.selfloop_edges(D)) try: nodes = reversed(list(nx.topological_sort(D))) except nx.NetworkXUnfeasible as e: raise nx.NetworkXUnfeasible( "The node label sets are overlapping and no ordering can " "resolve the mapping. Use copy=True.") from e else: # non-overlapping label sets nodes = old_labels multigraph = G.is_multigraph() directed = G.is_directed() for old in nodes: # Test that old is in both mapping and G, otherwise ignore. try: new = mapping[old] G.add_node(new, **G.nodes[old]) except KeyError: continue if new == old: continue if multigraph: new_edges = [(new, new if old == target else target, key, data) for (_, target, key, data) in G.edges(old, data=True, keys=True)] if directed: new_edges += [ (new if old == source else source, new, key, data) for (source, _, key, data) in G.in_edges(old, data=True, keys=True) ] # Ensure new edges won't overwrite existing ones seen = set() for i, (source, target, key, data) in enumerate(new_edges): if target in G[source] and key in G[source][target]: new_key = 0 if not isinstance(key, (int, float)) else key while new_key in G[source][target] or (target, new_key) in seen: new_key += 1 new_edges[i] = (source, target, new_key, data) seen.add((target, new_key)) else: new_edges = [(new, new if old == target else target, data) for (_, target, data) in G.edges(old, data=True)] if directed: new_edges += [(new if old == source else source, new, data) for (source, _, data) in G.in_edges(old, data=True)] G.remove_node(old) G.add_edges_from(new_edges) return G
def test_directed(self): """Tests the edge boundary of a directed graph.""" G = nx.DiGraph([(0, 1), (1, 2), (2, 3), (3, 4), (4, 0)]) S = [0, 1] boundary = list(nx.builtin.edge_boundary(G, S)) expected = [(1, 2)] assert boundary == expected
def test_directed(self): """Tests the node boundary of a directed graph.""" G = nx.DiGraph([(0, 1), (1, 2), (2, 3), (3, 4), (4, 0)]) S = [0, 1] boundary = nx.builtin.node_boundary(G, S) expected = {2} assert boundary == expected
def test_zero_deg(self): G = nx.DiGraph() G.add_edge(1, 2) G.add_edge(1, 3) G.add_edge(1, 4) c = nx.builtin.average_degree_connectivity(G) assert c == {1: 0, 3: 1} c = nx.builtin.average_degree_connectivity(G, source="in", target="in") assert c == {0: 0, 1: 0} c = nx.builtin.average_degree_connectivity(G, source="in", target="out") assert c == {0: 0, 1: 3} c = nx.builtin.average_degree_connectivity(G, source="in", target="in+out") assert c == {0: 0, 1: 3} c = nx.builtin.average_degree_connectivity(G, source="out", target="out") assert c == {0: 0, 3: 0} c = nx.builtin.average_degree_connectivity(G, source="out", target="in") assert c == {0: 0, 3: 1} c = nx.builtin.average_degree_connectivity(G, source="out", target="in+out") assert c == {0: 0, 3: 1}
def bfs_tree(G, source, reverse=False, depth_limit=None): """Returns an oriented tree constructed from of a breadth-first-search starting at source. Parameters ---------- G : networkx graph source : node Specify starting node for breadth-first search depth_limit : int, optional(default=len(G)) Specify the maximum search depth Returns ------- T: networkx DiGraph An oriented tree Notes ----- Based on http://www.ics.uci.edu/~eppstein/PADS/BFS.py by D. Eppstein, July 2004. The modifications to allow depth limits based on the Wikipedia article "`Depth-limited-search`_". .. _Depth-limited-search: https://en.wikipedia.org/wiki/Depth-limited_search """ T = nx.DiGraph() T.add_node(source) edges_gen = bfs_edges(G, source, depth_limit=depth_limit) T.add_edges_from(edges_gen) return T
def setup_method(cls): G = nx.Graph() G.add_nodes_from([0, 1], fish='one') G.add_nodes_from([2, 3], fish='two') G.add_nodes_from([4], fish='red') G.add_nodes_from([5], fish='blue') G.add_edges_from([(0, 1), (2, 3), (0, 4), (2, 5)]) cls.G = G D = nx.DiGraph() D.add_nodes_from([0, 1], fish='one') D.add_nodes_from([2, 3], fish='two') D.add_nodes_from([4], fish='red') D.add_nodes_from([5], fish='blue') D.add_edges_from([(0, 1), (2, 3), (0, 4), (2, 5)]) cls.D = D S = nx.Graph() S.add_nodes_from([0, 1], fish='one') S.add_nodes_from([2, 3], fish='two') S.add_nodes_from([4], fish='red') S.add_nodes_from([5], fish='blue') S.add_edge(0, 0) S.add_edge(2, 2) cls.S = S
def test_all_simple_edge_paths_on_non_trivial_graph(self): """you may need to draw this graph to make sure it is reasonable""" G = nx.path_graph(5, create_using=nx.DiGraph()) G.add_edges_from([(0, 5), (1, 5), (1, 3), (5, 4), (4, 2), (4, 3)]) paths = nx.builtin.all_simple_edge_paths(G, 1, [2, 3]) assert {tuple(p) for p in paths} == { ((1, 2), ), ((1, 3), (3, 4), (4, 2)), ((1, 5), (5, 4), (4, 2)), ((1, 3), ), ((1, 2), (2, 3)), ((1, 5), (5, 4), (4, 3)), ((1, 5), (5, 4), (4, 2), (2, 3)), } paths = nx.builtin.all_simple_edge_paths(G, 1, [2, 3], cutoff=3) assert {tuple(p) for p in paths} == { ((1, 2), ), ((1, 3), (3, 4), (4, 2)), ((1, 5), (5, 4), (4, 2)), ((1, 3), ), ((1, 2), (2, 3)), ((1, 5), (5, 4), (4, 3)), } paths = nx.builtin.all_simple_edge_paths(G, 1, [2, 3], cutoff=2) assert {tuple(p) for p in paths} == {((1, 2), ), ((1, 3), ), ((1, 2), (2, 3))}
def test_all_simple_edge_paths_with_two_targets_inside_cycle_emits_two_paths( self): G = nx.cycle_graph(3, create_using=nx.DiGraph()) G.add_edge(1, 3) paths = nx.builtin.all_simple_edge_paths(G, 0, [2, 3]) assert {tuple(p) for p in paths} == {((0, 1), (1, 2)), ((0, 1), (1, 3))}
def test_error_with_multigraph(self): with pytest.raises( NetworkXError, match= "Graph is multigraph, cannot be converted to networkx graph", ): MSG = nx.DiGraph(self.multi_simple)
def test_path(self): G = nx.path_graph(10, create_using=nx.DiGraph()) assert list(nx.builtin.clustering(G).values()) == [ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, ] assert nx.builtin.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, }
def test_reverse_copy(self): G = nx.DiGraph([(0, 1), (1, 2)]) R = G.reverse() assert sorted(R.edges()) == [(1, 0), (2, 1)] R.remove_edge(1, 0) assert sorted(R.edges()) == [(2, 1)] assert sorted(G.edges()) == [(0, 1), (1, 2)]
def test_reverse_hashable(self): x = True y = False G = nx.DiGraph() G.add_edge(x, y) assert_nodes_equal(G.nodes(), G.reverse().nodes()) assert [(y, x)] == list(G.reverse().edges())
def setup_method(self): N = nx.Graph() N.add_nodes_from([0, 1], margin=-2) N.add_nodes_from([2, 3], margin=-2) N.add_nodes_from([4], margin=-3) N.add_nodes_from([5], margin=-4) N.add_edges_from([(0, 1), (2, 3), (0, 4), (2, 5)]) self.N = N F = nx.Graph() F.add_node(1, margin=0.5) F.add_nodes_from([0, 2, 3], margin=1.5) F.add_edges_from([(0, 3), (1, 3), (2, 3)], weight=0.5) F.add_edge(0, 2, weight=1) self.F = F M = nx.Graph() M.add_nodes_from([1, 2], margin=-1) M.add_nodes_from([3], margin=1) M.add_nodes_from([4], margin=2) M.add_edges_from([(3, 4), (1, 2), (1, 3)]) self.M = M P = nx.DiGraph() P.add_nodes_from([1, 2], margin=-1) P.add_nodes_from([3], margin=1) P.add_nodes_from([4], margin=2) P.add_edges_from([(3, 4), (1, 2), (1, 3)]) self.P = P
def test_pred_succ(self): G = nx.DiGraph() G.add_edge(0, 1) H = G.edge_subgraph([(0, 1)]) assert list(H.predecessors(0)) == [] assert list(H.successors(0)) == [1] assert list(H.predecessors(1)) == [0] assert list(H.successors(1)) == []
def test_is_empty(): graphs = [nx.Graph(), nx.DiGraph()] for G in graphs: assert nx.is_empty(G) G.add_nodes_from(range(5)) assert nx.is_empty(G) G.add_edges_from([(1, 2), (3, 4)]) assert not nx.is_empty(G)
def test_directed_path_normalized(self): """Betweenness centrality: directed path normalized""" G = nx.DiGraph() nx.add_path(G, [0, 1, 2]) b = nx.builtin.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])
def setup_class(cls): cls.edges = [(0, 1), (0, 2), (1, 2), (2, 3), (1, 4)] G = nx.Graph() G.add_edges_from(cls.edges, weight=1) DG = nx.DiGraph() DG.add_edges_from(cls.edges, weight=1) cls.G = G cls.DG = DG
def test_out_edges_data(self): G = nx.DiGraph([(0, 1, {"data": 0}), (1, 0, {})]) assert sorted(G.out_edges(data=True)) == [(0, 1, { "data": 0 }), (1, 0, {})] assert sorted(G.out_edges(0, data=True)) == [(0, 1, {"data": 0})] assert sorted(G.out_edges(data="data")) == [(0, 1, 0), (1, 0, None)] assert sorted(G.out_edges(0, data="data")) == [(0, 1, 0)]
def setup_class(cls): data_dir = os.path.expandvars("${GS_TEST_DIR}/networkx") p2p_dir = os.path.expandvars("${GS_TEST_DIR}") cls.simple = simple_label_graph(data_dir, True) cls.multi_simple = simple_label_multigraph(data_dir, True) cls.K3 = k3_graph(data_dir, False) cls.SG = nx.DiGraph(cls.simple, default_label="v-0") cls.SG.pagerank = { 1: 0.03721197, 2: 0.05395735, 3: 0.04150565, 4: 0.37508082, 5: 0.20599833, 6: 0.28624589, } cls.SG.auth = { 1: 0.165000, 2: 0.243018, 3: 0.078017, 4: 0.078017, 5: 0.270943, 6: 0.165000, } cls.SG.hub = { 1: 0.182720, 2: 0.0, 3: 0.386437, 4: 0.248121, 5: 0.138316, 6: 0.044404, } cls.SG.eigen = { 1: 3.201908045277076e-06, 2: 6.4038160905537886e-06, 3: 3.201908045277076e-06, 5: 0.40044823300165794, 4: 0.6479356498234745, 6: 0.6479356498234745, } cls.SG.katz = { 1: 0.37871516522035104, 2: 0.4165866814015425, 3: 0.37871516522035104, 5: 0.42126739520601203, 4: 0.4255225997990211, 6: 0.4255225997990211, } cls.p2p_31 = p2p_31_graph(p2p_dir, False) cls.P2P = nx.Graph(cls.p2p_31, default_label="vertex") cls.P2P.sssp = dict( pd.read_csv( "{}/p2p-31-sssp".format(os.path.expandvars("${GS_TEST_DIR}")), sep=" ", header=None, prefix="", ).values)
def test_disconnected_graph(): # https://github.com/networkx/networkx/issues/1144 G = nx.Graph() G.add_edges_from([(0, 1), (1, 2), (2, 0), (3, 4)]) assert not nx.is_tree(G) G = nx.DiGraph() G.add_edges_from([(0, 1), (1, 2), (2, 0), (3, 4)]) assert not nx.is_tree(G)
def test_digraph_all_simple_edge_paths_with_two_targets_cutoff(self): G = nx.path_graph(4, create_using=nx.DiGraph()) G.add_edge(2, 4) paths = nx.builtin.all_simple_edge_paths(G, 0, [3, 4], cutoff=3) assert {tuple(p) for p in paths} == { ((0, 1), (1, 2), (2, 3)), ((0, 1), (1, 2), (2, 4)), }
def test_digraph(self): G = nx.path_graph(3, create_using=nx.DiGraph()) c = nx.builtin.closeness_centrality(G) cr = nx.builtin.closeness_centrality(G.reverse()) d = {0: 0.0, 1: 0.500, 2: 0.667} dr = {0: 0.667, 1: 0.500, 2: 0.0} for n in sorted(self.P3): assert almost_equal(c[n], d[n], places=3) assert almost_equal(cr[n], dr[n], places=3)
def setup_class(cls): cls.G = nx.path_graph(9) cls.DG = nx.path_graph(9, create_using=nx.DiGraph()) cls.Gv = nx.to_undirected(cls.DG) cls.DGv = nx.to_directed(cls.G) cls.Rv = cls.DG.reverse() cls.graphs = [cls.G, cls.DG, cls.Gv, cls.DGv, cls.Rv] for G in cls.graphs: print(G.edges, G.nodes, G.degree)
def setup_method(self): self.G = nx.Graph({0: [1, 2, 3], 1: [1, 2, 0], 4: []}, name="Test") self.Gdegree = {0: 3, 1: 2, 2: 2, 3: 1, 4: 0} self.Gnodes = list(range(5)) self.Gedges = [(0, 1), (0, 2), (0, 3), (1, 0), (1, 1), (1, 2)] self.DG = nx.DiGraph({0: [1, 2, 3], 1: [1, 2, 0], 4: []}) self.DGin_degree = {0: 1, 1: 2, 2: 2, 3: 1, 4: 0} self.DGout_degree = {0: 3, 1: 3, 2: 0, 3: 0, 4: 0} self.DGnodes = list(range(5)) self.DGedges = [(0, 1), (0, 2), (0, 3), (1, 0), (1, 1), (1, 2)]
def test_in_out_weight(self): G = nx.DiGraph() G.add_edge(1, 2, weight=1) G.add_edge(1, 3, weight=1) G.add_edge(3, 1, weight=1) for s, t in permutations(["in", "out", "in+out"], 2): c = nx.builtin.average_degree_connectivity(G, source=s, target=t) cw = nx.builtin.average_degree_connectivity( G, source=s, target=t, weight="weight" ) assert c == cw