desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Test that setting dtype int actually gives an integer matrix. For more information, see GitHub pull request #1363.'
def test_dtype_int_multigraph(self):
G = nx.MultiGraph(nx.complete_graph(3)) A = nx.to_numpy_matrix(G, dtype=int) assert_equal(A.dtype, int)
'Conversion from non-square array.'
def test_shape(self):
A = np.array([[1, 2, 3], [4, 5, 6]]) assert_raises(nx.NetworkXError, nx.from_numpy_array, A)
'Conversion from graph to array to graph.'
def test_identity_graph_array(self):
A = nx.to_numpy_array(self.G1) self.identity_conversion(self.G1, A, nx.Graph())
'Conversion from digraph to array to digraph.'
def test_identity_digraph_array(self):
A = nx.to_numpy_array(self.G2) self.identity_conversion(self.G2, A, nx.DiGraph())
'Conversion from weighted graph to array to weighted graph.'
def test_identity_weighted_graph_array(self):
A = nx.to_numpy_array(self.G3) self.identity_conversion(self.G3, A, nx.Graph())
'Conversion from weighted digraph to array to weighted digraph.'
def test_identity_weighted_digraph_array(self):
A = nx.to_numpy_array(self.G4) self.identity_conversion(self.G4, A, nx.DiGraph())
'Conversion from graph to array to graph with nodelist.'
def test_nodelist(self):
P4 = path_graph(4) P3 = path_graph(3) nodelist = list(P3) A = nx.to_numpy_array(P4, nodelist=nodelist) GA = nx.Graph(A) self.assert_equal(GA, P3) nodelist += [nodelist[0]] assert_raises(nx.NetworkXError, nx.to_numpy_array, P3, nodelist=nodelist)
'Tests that the :func:`networkx.from_numpy_array` function interprets integer weights as the number of parallel edges when creating a multigraph.'
def test_from_numpy_array_parallel_edges(self):
A = np.array([[1, 1], [1, 2]]) expected = nx.DiGraph() edges = [(0, 0), (0, 1), (1, 0)] expected.add_weighted_edges_from([(u, v, 1) for (u, v) in edges]) expected.add_edge(1, 1, weight=2) actual = nx.from_numpy_array(A, parallel_edges=True, create_using=nx.DiGraph()) assert_graphs_equal(actu...
'Tests that a symmetric array has edges added only once to an undirected multigraph when using :func:`networkx.from_numpy_array`.'
def test_symmetric(self):
A = np.array([[0, 1], [1, 0]]) G = nx.from_numpy_array(A, create_using=nx.MultiGraph()) expected = nx.MultiGraph() expected.add_edge(0, 1, weight=1) assert_graphs_equal(G, expected)
'Test that setting dtype int actually gives an integer array. For more information, see GitHub pull request #1363.'
def test_dtype_int_graph(self):
G = nx.complete_graph(3) A = nx.to_numpy_array(G, dtype=int) assert_equal(A.dtype, int)
'Test that setting dtype int actually gives an integer array. For more information, see GitHub pull request #1363.'
def test_dtype_int_multigraph(self):
G = nx.MultiGraph(nx.complete_graph(3)) A = nx.to_numpy_array(G, dtype=int) assert_equal(A.dtype, int)
'Conversion from non-square sparse array.'
def test_shape(self):
A = sp.sparse.lil_matrix([[1, 2, 3], [4, 5, 6]]) assert_raises(nx.NetworkXError, nx.from_scipy_sparse_matrix, A)
'Conversion from graph to sparse matrix to graph.'
def test_identity_graph_matrix(self):
A = nx.to_scipy_sparse_matrix(self.G1) self.identity_conversion(self.G1, A, nx.Graph())
'Conversion from digraph to sparse matrix to digraph.'
def test_identity_digraph_matrix(self):
A = nx.to_scipy_sparse_matrix(self.G2) self.identity_conversion(self.G2, A, nx.DiGraph())
'Conversion from weighted graph to sparse matrix to weighted graph.'
def test_identity_weighted_graph_matrix(self):
A = nx.to_scipy_sparse_matrix(self.G3) self.identity_conversion(self.G3, A, nx.Graph())
'Conversion from weighted digraph to sparse matrix to weighted digraph.'
def test_identity_weighted_digraph_matrix(self):
A = nx.to_scipy_sparse_matrix(self.G4) self.identity_conversion(self.G4, A, nx.DiGraph())
'Conversion from graph to sparse matrix to graph with nodelist.'
def test_nodelist(self):
P4 = path_graph(4) P3 = path_graph(3) nodelist = list(P3.nodes()) A = nx.to_scipy_sparse_matrix(P4, nodelist=nodelist) GA = nx.Graph(A) self.assert_isomorphic(GA, P3) nodelist += [nodelist[0]] assert_raises(nx.NetworkXError, nx.to_numpy_matrix, P3, nodelist=nodelist)
'Tests that the :func:`networkx.from_scipy_sparse_matrix` function interprets integer weights as the number of parallel edges when creating a multigraph.'
def test_from_scipy_sparse_matrix_parallel_edges(self):
A = sparse.csr_matrix([[1, 1], [1, 2]]) expected = nx.DiGraph() edges = [(0, 0), (0, 1), (1, 0)] expected.add_weighted_edges_from([(u, v, 1) for (u, v) in edges]) expected.add_edge(1, 1, weight=2) actual = nx.from_scipy_sparse_matrix(A, parallel_edges=True, create_using=nx.DiGraph()) assert_...
'Tests that a symmetric matrix has edges added only once to an undirected multigraph when using :func:`networkx.from_scipy_sparse_matrix`.'
def test_symmetric(self):
A = sparse.csr_matrix([[0, 1], [1, 0]]) G = nx.from_scipy_sparse_matrix(A, create_using=nx.MultiGraph()) expected = nx.MultiGraph() expected.add_edge(0, 1, weight=1) assert_graphs_equal(G, expected)
'Modularity matrix'
def test_modularity(self):
B = numpy.matrix([[(-1.125), 0.25, 0.25, 0.625, 0.0], [0.25, (-0.5), 0.5, (-0.25), 0.0], [0.25, 0.5, (-0.5), (-0.25), 0.0], [0.625, (-0.25), (-0.25), (-0.125), 0.0], [0.0, 0.0, 0.0, 0.0, 0.0]]) permutation = [4, 0, 1, 2, 3] assert_equal(nx.modularity_matrix(self.G), B) assert_equal(nx.modularity_matrix(...
'Modularity matrix with weights'
def test_modularity_weight(self):
B = numpy.matrix([[(-1.125), 0.25, 0.25, 0.625, 0.0], [0.25, (-0.5), 0.5, (-0.25), 0.0], [0.25, 0.5, (-0.5), (-0.25), 0.0], [0.625, (-0.25), (-0.25), (-0.125), 0.0], [0.0, 0.0, 0.0, 0.0, 0.0]]) G_weighted = self.G.copy() for (n1, n2) in G_weighted.edges(): G_weighted.edge[(n1, n2)]['weight'] = 0.5 ...
'Directed Modularity matrix'
def test_directed_modularity(self):
B = numpy.matrix([[(-0.2), 0.6, 0.8, (-0.4), (-0.4), (-0.4)], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.7, 0.4, (-0.3), (-0.6), 0.4, (-0.6)], [(-0.2), (-0.4), (-0.2), (-0.4), 0.6, 0.6], [(-0.2), (-0.4), (-0.2), 0.6, (-0.4), 0.6], [(-0.1), (-0.2), (-0.1), 0.8, (-0.2), (-0.2)]]) node_permutation = [5, 1, 2, 3, 4, 6] ...
'Graph Laplacian'
def test_laplacian(self):
NL = numpy.array([[3, (-1), (-1), (-1), 0], [(-1), 2, (-1), 0, 0], [(-1), (-1), 2, 0, 0], [(-1), 0, 0, 1, 0], [0, 0, 0, 0, 0]]) WL = (0.5 * NL) OL = (0.3 * NL) assert_equal(nx.laplacian_matrix(self.G).todense(), NL) assert_equal(nx.laplacian_matrix(self.MG).todense(), NL) assert_equal(nx.laplaci...
'Generalized Graph Laplacian'
def test_normalized_laplacian(self):
GL = numpy.array([[1.0, (-0.408), (-0.408), (-0.577), 0.0], [(-0.408), 1.0, (-0.5), 0.0, 0.0], [(-0.408), (-0.5), 1.0, 0.0, 0.0], [(-0.577), 0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0]]) Lsl = numpy.array([[0.75, (-0.2887), (-0.2887), (-0.3536), 0.0], [(-0.2887), 0.6667, (-0.3333), 0.0, 0.0], [(-0.2887), (-0...
'Directed Laplacian'
def test_directed_laplacian(self):
G = nx.DiGraph() G.add_edges_from(((1, 2), (1, 3), (3, 1), (3, 2), (3, 5), (4, 5), (4, 6), (5, 4), (5, 6), (6, 4))) GL = numpy.array([[0.9833, (-0.2941), (-0.3882), (-0.0291), (-0.0231), (-0.0261)], [(-0.2941), 0.8333, (-0.2339), (-0.0536), (-0.0589), (-0.0554)], [(-0.3882), (-0.2339), 0.9833, (-0.0278), (-...
'Laplacian eigenvalues'
def test_laplacian_spectrum(self):
evals = numpy.array([0, 0, 1, 3, 4]) e = sorted(nx.laplacian_spectrum(self.G)) assert_almost_equal(e, evals) e = sorted(nx.laplacian_spectrum(self.WG, weight=None)) assert_almost_equal(e, evals) e = sorted(nx.laplacian_spectrum(self.WG)) assert_almost_equal(e, (0.5 * evals)) e = sorted(n...
'Adjacency eigenvalues'
def test_adjacency_spectrum(self):
evals = numpy.array([(- numpy.sqrt(2)), 0, numpy.sqrt(2)]) e = sorted(nx.adjacency_spectrum(self.P)) assert_almost_equal(e, evals)
'Modularity eigenvalues'
def test_modularity_spectrum(self):
evals = numpy.array([(-1.5), 0.0, 0.0]) e = sorted(nx.modularity_spectrum(self.P)) assert_almost_equal(e, evals) evals = numpy.array([(-0.5), 0.0, 0.0]) e = sorted(nx.modularity_spectrum(self.DG)) assert_almost_equal(e, evals)
'Conversion to incidence matrix'
def test_incidence_matrix(self):
I = nx.incidence_matrix(self.G, nodelist=sorted(self.G), edgelist=sorted(self.G.edges()), oriented=True).todense().astype(int) assert_equal(I, self.OI) I = nx.incidence_matrix(self.G, nodelist=sorted(self.G), edgelist=sorted(self.G.edges()), oriented=False).todense().astype(int) assert_equal(I, numpy.ab...
'Conversion to adjacency matrix'
def test_adjacency_matrix(self):
assert_equal(nx.adj_matrix(self.G).todense(), self.A) assert_equal(nx.adj_matrix(self.MG).todense(), self.A) assert_equal(nx.adj_matrix(self.MG2).todense(), self.MG2A) assert_equal(nx.adj_matrix(self.G, nodelist=[0, 1]).todense(), self.A[:2, :2]) assert_equal(nx.adj_matrix(self.WG).todense(), self.W...
'Fixture defining the `pydot` global to be the `pydot` module if both importable and of sufficient version _or_ skipping this test.'
@classmethod def setupClass(cls):
global pydot pydot = nx.nx_pydot.setup_module(sys.modules[__name__]) assert (pydot is not None)
'Validate :mod:`pydot`-based usage of the passed NetworkX graph with the passed basename of an external GraphViz command (e.g., `dot`, `neato`).'
def pydot_checks(self, G, prog):
G.graph['name'] = 'G' G.add_edges_from([('A', 'B'), ('A', 'C'), ('B', 'C'), ('A', 'D')]) G.add_node('E') graph_layout = nx.nx_pydot.pydot_layout(G, prog=prog) assert_is_instance(graph_layout, dict) P = nx.nx_pydot.to_pydot(G) G2 = G.__class__(nx.nx_pydot.from_pydot(P)) assert_graphs_equa...
'Return a dict of neighbors of node n in the dense graph. Parameters n : node A node in the graph. Returns adj_dict : dictionary The adjacency dictionary for nodes connected to n.'
def __getitem__(self, n):
all_edge_dict = self.all_edge_dict return dict(((node, all_edge_dict) for node in ((set(self._adj) - set(self._adj[n])) - set([n]))))
'Return an iterator over all neighbors of node n in the dense graph.'
def neighbors(self, n):
try: return iter(((set(self._adj) - set(self._adj[n])) - set([n]))) except KeyError: raise NetworkXError(('The node %s is not in the graph.' % (n,)))
'Return an iterator for (node, degree) and degree for single node. The node degree is the number of edges adjacent to the node. Parameters nbunch : iterable container, optional (default=all nodes) A container of nodes. The container will be iterated through once. weight : string or None, optional (default=None) The ed...
@property def degree(self):
return self.AntiDegreeView(self)
'Return an iterator of (node, adjacency set) tuples for all nodes in the dense graph. This is the fastest way to look at every edge. For directed graphs, only outgoing adjacencies are included. Returns adj_iter : iterator An iterator of (node, adjacency set) for all nodes in the graph.'
def adjacency(self):
for n in self._adj: (yield (n, ((set(self._adj) - set(self._adj[n])) - set([n]))))
'Tests that the maximal clique is computed according to maximum cardinality of the sets. For more information, see pull request #1531.'
def test_maximal_by_cardinality(self):
G = nx.complete_graph(5) G.add_edge(4, 5) clique = max_clique(G) assert_greater(len(clique), 1) G = nx.lollipop_graph(30, 2) clique = max_clique(G) assert_greater(len(clique), 2)
'Tests that an approximate dominating set for the star graph, even when the center node does not have the smallest integer label, gives just the center node. For more information, see #1527.'
def test_star_graph(self):
G = nx.star_graph(10) G = nx.relabel_nodes(G, {0: 9, 9: 0}) eq_(min_weighted_dominating_set(G), {9})
'Creates some graphs for use in the unit tests.'
def setup(self):
cnlti = nx.convert_node_labels_to_integers self.grid = cnlti(nx.grid_2d_graph(4, 4), first_label=1, ordering='sorted') self.cycle = nx.cycle_graph(7) self.directed_cycle = nx.cycle_graph(7, create_using=nx.DiGraph()) self.XG = nx.DiGraph() self.XG.add_weighted_edges_from([('s', 'u', 10), ('s', '...
'Tests that a callable weight is interpreted as a weight function instead of an edge attribute.'
def test_weight_function(self):
G = nx.complete_graph(3) G.adj[0][2]['weight'] = 10 G.adj[0][1]['weight'] = 1 G.adj[1][2]['weight'] = 1 weight = (lambda u, v, d: (1 / d['weight'])) (distance, path) = nx.single_source_dijkstra(G, 0, 2) assert_equal(distance, 2) assert_equal(path, [0, 1, 2]) (distance, path) = nx.sin...
'Tests for computing the length of the shortest path using Dijkstra\'s algorithm with a user-defined weight function.'
def test_weight_function(self):
G = nx.complete_graph(3) G.adj[0][2]['weight'] = 10 G.adj[0][1]['weight'] = 1 G.adj[1][2]['weight'] = 1 weight = (lambda u, v, d: (1 / d['weight'])) length = nx.dijkstra_path_length(G, 0, 2, weight=weight) assert_equal(length, (1 / 10))
'Tests that the A* shortest path agrees with Dijkstra\'s shortest path for a random graph.'
def test_random_graph(self):
G = nx.Graph() points = [(random(), random()) for _ in range(100)] for (p1, p2) in pairwise(points): G.add_edge(p1, p2, weight=dist(p1, p2)) for _ in range(100): (p1, p2) = (choice(points), choice(points)) G.add_edge(p1, p2, weight=dist(p1, p2)) path = nx.astar_path(G, points...
'Tests that A* accomodates nodes that are not orderable. For more information, see issue #554.'
def test_unorderable_nodes(self):
class Unorderable(object, ): def __le__(self): raise NotImplemented def __ge__(self): raise NotImplemented nodes = [Unorderable() for n in range(4)] G = nx.Graph() G.add_edges_from(pairwise(nodes, cyclic=True)) path = nx.astar_path(G, nodes[0], nodes[2]) a...
'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.'
def test_trivial_graph(self):
G = nx.trivial_graph() assert_equal(nx.average_shortest_path_length(G), 0)
'Tests that a narrow beam width may cause an incomplete search.'
def test_narrow(self):
G = nx.cycle_graph(4) edges = nx.bfs_beam_edges(G, 0, identity, width=1) assert_equal(list(edges), [(0, 3), (3, 2)])
'Creates a bipartite graph for use in testing matching algorithms. The bipartite graph has a maximum cardinality matching that leaves vertex 1 and vertex 10 unmatched. The first six numbers are the left vertices and the next six numbers are the right vertices.'
def setup(self):
self.simple_graph = nx.complete_bipartite_graph(2, 3) self.simple_solution = {0: 2, 1: 3, 2: 0, 3: 1} edges = [(0, 7), (0, 8), (2, 6), (2, 9), (3, 8), (4, 8), (4, 9), (5, 11)] self.top_nodes = set(range(6)) self.graph = nx.Graph() self.graph.add_nodes_from(range(12)) self.graph.add_edges_fro...
'Asserts that the matching is what we expect from the bipartite graph constructed in the :meth:`setup` fixture.'
def check_match(self, matching):
M = matching matched_vertices = frozenset(itertools.chain(*M.items())) assert (matched_vertices == (frozenset(range(12)) - {1, 10})) assert all(((u == M[M[u]]) for u in range(12) if (u in M)))
'Asserts that the given set of vertices is the vertex cover we expected from the bipartite graph constructed in the :meth:`setup` fixture.'
def check_vertex_cover(self, vertices):
assert (len(vertices) == 5) for (u, v) in self.graph.edges(): assert ((u in vertices) or (v in vertices))
'Tests that David Eppstein\'s implementation of the Hopcroft--Karp algorithm produces a maximum cardinality matching.'
def test_eppstein_matching(self):
self.check_match(eppstein_matching(self.graph, self.top_nodes))
'Tests that the Hopcroft--Karp algorithm produces a maximum cardinality matching in a bipartite graph.'
def test_hopcroft_karp_matching(self):
self.check_match(hopcroft_karp_matching(self.graph, self.top_nodes))
'Test for converting a maximum matching to a minimum vertex cover.'
def test_to_vertex_cover(self):
matching = maximum_matching(self.graph, self.top_nodes) vertex_cover = to_vertex_cover(self.graph, matching, self.top_nodes) self.check_vertex_cover(vertex_cover)
'Test from issue 2127'
def test_issue_2127(self):
G = nx.DiGraph() G.add_edge('A', 'C') G.add_edge('A', 'B') G.add_edge('C', 'E') G.add_edge('C', 'D') G.add_edge('E', 'G') G.add_edge('E', 'F') G.add_edge('G', 'I') G.add_edge('G', 'H') tc = nx.transitive_closure(G) btc = nx.Graph() for v in tc.nodes(): btc.add_nod...
'Key is now required.'
def add_edge(self, u, v, key, **attr):
if (key in self.edge_index): (uu, vv, _) = self.edge_index[key] if ((u != uu) or (v != vv)): raise Exception('Key {0!r} is already in use.'.format(key)) self._cls.add_edge(u, v, key=key, **attr) self.edge_index[key] = (u, v, self.succ[u][v][key])
'Returns a branching from G. Parameters attr : str The edge attribute used to in determining optimality. default : float The value of the edge attribute used if an edge does not have the attribute `attr`. kind : {\'min\', \'max\'} The type of optimum to search for, either \'min\' or \'max\'. style : {\'branching\', \'a...
def find_optimum(self, attr='weight', default=1, kind='max', style='branching'):
self._init(attr, default, kind, style) uf = self.uf (G, B) = (self.G, self.B) D = set([]) nodes = iter(list(G.nodes())) attr = self._attr G_pred = G.pred def desired_edge(v): '\n Find the edge directed toward v with...
'Tests for encoding a tree as a PrÃŒfer sequence using the iterative strategy.'
def test_encoding(self):
tree = nx.Graph([(0, 3), (1, 3), (2, 3), (3, 4), (4, 5)]) sequence = nx.to_prufer_sequence(tree) assert_equal(sequence, [3, 3, 3, 4])
'Tests for decoding a tree from a PrÃŒfer sequence.'
def test_decoding(self):
sequence = [3, 3, 3, 4] tree = nx.from_prufer_sequence(sequence) assert_nodes_equal(list(tree), list(range(6))) edges = [(0, 3), (1, 3), (2, 3), (3, 4), (4, 5)] assert_edges_equal(list(tree.edges()), edges)
'Tests that the encoding and decoding functions are inverses.'
def test_inverse(self):
for T in nx.nonisomorphic_trees(4): T2 = nx.from_prufer_sequence(nx.to_prufer_sequence(T)) assert_nodes_equal(list(T), list(T2)) assert_edges_equal(list(T.edges()), list(T2.edges())) for seq in product(range(4), repeat=2): seq2 = nx.to_prufer_sequence(nx.from_prufer_sequence(seq)...
'Creates an example graph and stores the expected minimum and maximum spanning tree edges.'
def setUp(self):
self.algo = self.algorithm edges = [(0, 1, 7), (0, 3, 5), (1, 2, 8), (1, 3, 9), (1, 4, 7), (2, 4, 5), (3, 4, 15), (3, 5, 6), (4, 5, 8), (4, 6, 9), (5, 6, 11)] self.G = nx.Graph() self.G.add_weighted_edges_from(edges) self.minimum_spanning_edgelist = [(0, 1, {'weight': 7}), (0, 3, {'weight': 5}), (1,...
'Tests that using a Unicode string can correctly indicate Borůvka\'s algorithm.'
def test_unicode_name(self):
edges = nx.minimum_spanning_edges(self.G, algorithm=u'bor\u016fvka') actual = sorted(((min(u, v), max(u, v), d) for (u, v, d) in edges)) assert_edges_equal(actual, self.minimum_spanning_edgelist)
'Tests that the minimum spanning edges of a multigraph preserves edge keys.'
def test_multigraph_keys_min(self):
G = nx.MultiGraph() G.add_edge(0, 1, key='a', weight=2) G.add_edge(0, 1, key='b', weight=1) min_edges = nx.minimum_spanning_edges mst_edges = min_edges(G, algorithm=self.algo, data=False) assert_edges_equal([(0, 1, 'b')], list(mst_edges))
'Tests that the maximum spanning edges of a multigraph preserves edge keys.'
def test_multigraph_keys_max(self):
G = nx.MultiGraph() G.add_edge(0, 1, key='a', weight=2) G.add_edge(0, 1, key='b', weight=1) max_edges = nx.maximum_spanning_edges mst_edges = max_edges(G, algorithm=self.algo, data=False) assert_edges_equal([(0, 1, 'a')], list(mst_edges))
'Tests that joining the empty sequence results in the tree with one node.'
def test_empty_sequence(self):
T = nx.join([]) assert_equal(len(T), 1) assert_equal(T.number_of_edges(), 0)
'Tests that joining just one tree yields a tree with one more node.'
def test_single(self):
T = nx.empty_graph(1) actual = nx.join([(T, 0)]) expected = nx.path_graph(2) assert_nodes_equal(list(expected), list(actual)) assert_edges_equal(list(expected.edges()), list(actual.edges()))
'Tests for joining multiple subtrees at a root node.'
def test_basic(self):
trees = [(nx.full_rary_tree(2, ((2 ** 2) - 1)), 0) for i in range(2)] actual = nx.join(trees) expected = nx.full_rary_tree(2, ((2 ** 3) - 1)) assert_true(nx.is_isomorphic(actual, expected))
'Tests that the quotient graph of the complete *n*-partite graph under the "same neighbors" node relation is the complete graph on *n* nodes.'
def test_quotient_graph_complete_multipartite(self):
G = nx.complete_multipartite_graph(2, 3, 4) def same_neighbors(u, v): return ((u not in G[v]) and (v not in G[u]) and (G[u] == G[v])) expected = nx.complete_graph(3) actual = nx.quotient_graph(G, same_neighbors) assert_true(nx.is_isomorphic(expected, actual))
'Tests that the quotient graph of the complete bipartite graph under the "same neighbors" node relation is `K_2`.'
def test_quotient_graph_complete_bipartite(self):
G = nx.complete_bipartite_graph(2, 3) def same_neighbors(u, v): return ((u not in G[v]) and (v not in G[u]) and (G[u] == G[v])) expected = nx.complete_graph(2) actual = nx.quotient_graph(G, same_neighbors) assert_true(nx.is_isomorphic(expected, actual))
'Tests for specifying an alternate edge relation for the quotient graph.'
def test_quotient_graph_edge_relation(self):
G = nx.path_graph(5) def identity(u, v): return (u == v) def same_parity(b, c): return ((arbitrary_element(b) % 2) == (arbitrary_element(c) % 2)) actual = nx.quotient_graph(G, identity, same_parity) expected = nx.Graph() expected.add_edges_from([(0, 2), (0, 4), (2, 4)]) expec...
'This tests that the condensation of a graph can be viewed as the quotient graph under the "in the same connected component" equivalence relation.'
def test_condensation_as_quotient(self):
G = nx.DiGraph() G.add_edges_from([(1, 2), (2, 3), (2, 11), (2, 12), (3, 4), (4, 3), (4, 5), (5, 6), (6, 5), (6, 7), (7, 8), (7, 9), (7, 10), (8, 9), (9, 7), (10, 6), (11, 2), (11, 4), (11, 6), (12, 6), (12, 11)]) scc = list(nx.strongly_connected_components(G)) C = nx.condensation(G, scc) component_...
'Tests for node contraction in an undirected graph.'
def test_undirected_node_contraction(self):
G = nx.cycle_graph(4) actual = nx.contracted_nodes(G, 0, 1) expected = nx.complete_graph(3) expected.add_edge(0, 0) assert_true(nx.is_isomorphic(actual, expected))
'Tests for node contraction in a directed graph.'
def test_directed_node_contraction(self):
G = nx.DiGraph(nx.cycle_graph(4)) actual = nx.contracted_nodes(G, 0, 1) expected = nx.DiGraph(nx.complete_graph(3)) expected.add_edge(0, 0) expected.add_edge(0, 0) assert_true(nx.is_isomorphic(actual, expected))
'Tests that using a MultiGraph creates multiple edges.'
def test_create_multigraph(self):
G = nx.path_graph(3, create_using=nx.MultiGraph()) actual = nx.contracted_nodes(G, 0, 2) expected = nx.MultiDiGraph() expected.add_edge(0, 1) expected.add_edge(0, 1) assert_edges_equal(actual.edges, expected.edges)
'Tests that node contraction preserves node attributes.'
def test_node_attributes(self):
G = nx.cycle_graph(4) G.node[0]['foo'] = 'bar' G.node[1]['baz'] = 'xyzzy' actual = nx.contracted_nodes(G, 0, 1) expected = nx.complete_graph(3) expected = nx.relabel_nodes(expected, {1: 2, 2: 3}) expected.add_edge(0, 0) cdict = {1: {'baz': 'xyzzy'}} expected.node[0].update(dict(foo='...
'Tests for node contraction without preserving self-loops.'
def test_without_self_loops(self):
G = nx.cycle_graph(4) actual = nx.contracted_nodes(G, 0, 1, self_loops=False) expected = nx.complete_graph(3) assert_true(nx.is_isomorphic(actual, expected))
'Tests for edge contraction in an undirected graph.'
def test_undirected_edge_contraction(self):
G = nx.cycle_graph(4) actual = nx.contracted_edge(G, (0, 1)) expected = nx.complete_graph(3) expected.add_edge(0, 0) assert_true(nx.is_isomorphic(actual, expected))
'Tests that attempting to contract a non-existent edge raises an exception.'
@raises(ValueError) def test_nonexistent_edge(self):
G = nx.cycle_graph(4) nx.contracted_edge(G, (0, 2))
'Test for a graph with multiple connected components.'
def test_disconnected_graph(self):
G = nx.barbell_graph(3, 0) H = nx.barbell_graph(3, 0) mapping = dict(zip(range(6), 'abcdef')) nx.relabel_nodes(H, mapping, copy=False) G = nx.union(G, H) chains = list(nx.chain_decomposition(G)) expected = [[(0, 1), (1, 2), (2, 0)], [(3, 4), (4, 5), (5, 3)], [('a', 'b'), ('b', 'c'), ('c', 'a...
'Test for a single component of a disconnected graph.'
def test_disconnected_graph_root_node(self):
G = nx.barbell_graph(3, 0) H = nx.barbell_graph(3, 0) mapping = dict(zip(range(6), 'abcdef')) nx.relabel_nodes(H, mapping, copy=False) G = nx.union(G, H) chains = list(nx.chain_decomposition(G, root='a')) expected = [[('a', 'b'), ('b', 'c'), ('c', 'a')], [('d', 'e'), ('e', 'f'), ('f', 'd')]]...
'Maximal independent set: K5'
def test_K5(self):
G = nx.complete_graph(5) for node in G: assert_equal(nx.maximal_independent_set(G, [node]), [node])
'Maximal independent set: K55'
def test_K55(self):
G = nx.complete_graph(55) for node in G: assert_equal(nx.maximal_independent_set(G, [node]), [node])
'Bad input should raise exception.'
def test_exception(self):
G = self.florentine assert_raises(nx.NetworkXUnfeasible, nx.maximal_independent_set, G, ['Smith']) assert_raises(nx.NetworkXUnfeasible, nx.maximal_independent_set, G, ['Salviati', 'Pazzi'])
'Generate 50 random graphs of different types and sizes and make sure that all sets are independent and maximal.'
def test_random_graphs(self):
for i in range(0, 50, 10): G = nx.random_graphs.erdos_renyi_graph(((i * 10) + 1), random.random()) IS = nx.maximal_independent_set(G) assert_false(list(G.subgraph(IS).edges())) neighbors_of_MIS = set.union(*(set(G.neighbors(v)) for v in IS)) for v in set(G.nodes()).difference...
'Tests that the Wiener index of a disconnected graph is positive infinity.'
def test_disconnected_graph(self):
eq_(wiener_index(empty_graph(2)), float('inf'))
'Tests that each pair of nodes in the directed graph is counted once when computing the Wiener index.'
def test_directed(self):
G = complete_graph(3) H = DiGraph(G) eq_((2 * wiener_index(G)), wiener_index(H))
'Tests that the Wiener index of the complete graph is simply the number of edges.'
def test_complete_graph(self):
n = 10 G = complete_graph(n) eq_(wiener_index(G), ((n * (n - 1)) / 2))
'Tests that the Wiener index of the path graph is correctly computed.'
def test_path_graph(self):
n = 9 G = path_graph(n) expected = (2 * sum(((i * (n - i)) for i in range(1, ((n // 2) + 1))))) actual = wiener_index(G) eq_(expected, actual)
'Test C4 for figure 1 Lind et al (2005)'
def test_lind_square_clustering(self):
G = nx.Graph([(1, 2), (1, 3), (1, 6), (1, 7), (2, 4), (2, 5), (3, 4), (3, 5), (6, 7), (7, 8), (6, 8), (7, 9), (7, 10), (6, 11), (6, 12), (2, 13), (2, 14), (3, 15), (3, 16)]) G1 = G.subgraph([1, 2, 3, 4, 5, 13, 14, 15, 16]) G2 = G.subgraph([1, 6, 7, 8, 9, 10, 11, 12]) assert_equal(nx.square_clustering(G,...
'Tests that computing the longest path does not depend on nodes being orderable. For more information, see issue #1989.'
def test_unorderable_nodes(self):
class Unorderable(object, ): def __lt__(self, other): error_msg = '< not supported between instances of {} and {}'.format(type(self).__name__, type(other).__name__) raise TypeError(error_msg) nodes = [Unorderable() for n in range(4)] G = nx.DiGraph() ...
'Tests that the null graph has empty node boundaries.'
def test_null_graph(self):
null = nx.null_graph() assert_equal(nx.node_boundary(null, []), set()) assert_equal(nx.node_boundary(null, [], []), set()) assert_equal(nx.node_boundary(null, [1, 2, 3]), set()) assert_equal(nx.node_boundary(null, [1, 2, 3], [4, 5, 6]), set()) assert_equal(nx.node_boundary(null, [1, 2, 3], [3, 4...
'Check boundaries in the petersen graph cheeger(G,k)=min(|bdy(S)|/|S| for |S|=k, 0<k<=|V(G)|/2)'
def test_petersen(self):
def cheeger(G, k): return min(((len(nx.node_boundary(G, nn)) / k) for nn in combinations(G, k))) P = nx.petersen_graph() assert_almost_equals(cheeger(P, 1), 3.0, places=2) assert_almost_equals(cheeger(P, 2), 2.0, places=2) assert_almost_equals(cheeger(P, 3), 1.67, places=2) assert_almost...
'Tests the node boundary of a directed graph.'
def test_directed(self):
G = nx.DiGraph([(0, 1), (1, 2), (2, 3), (3, 4), (4, 0)]) S = {0, 1} boundary = nx.node_boundary(G, S) expected = {2} assert_equal(boundary, expected)
'Tests the node boundary of a multigraph.'
def test_multigraph(self):
G = nx.MultiGraph((list(nx.cycle_graph(5).edges()) * 2)) S = {0, 1} boundary = nx.node_boundary(G, S) expected = {2, 4} assert_equal(boundary, expected)
'Tests the edge boundary of a multdiigraph.'
def test_multidigraph(self):
edges = [(0, 1), (1, 2), (2, 3), (3, 4), (4, 0)] G = nx.MultiDiGraph((edges * 2)) S = {0, 1} boundary = nx.node_boundary(G, S) expected = {2} assert_equal(boundary, expected)
'Tests the edge boundary of a directed graph.'
def test_directed(self):
G = nx.DiGraph([(0, 1), (1, 2), (2, 3), (3, 4), (4, 0)]) S = {0, 1} boundary = list(nx.edge_boundary(G, S)) expected = [(1, 2)] assert_equal(boundary, expected)
'Tests the edge boundary of a multigraph.'
def test_multigraph(self):
G = nx.MultiGraph((list(nx.cycle_graph(5).edges()) * 2)) S = {0, 1} boundary = list(nx.edge_boundary(G, S)) expected = [(0, 4), (0, 4), (1, 2), (1, 2)] assert_equal(boundary, expected)
'Tests the edge boundary of a multdiigraph.'
def test_multidigraph(self):
edges = [(0, 1), (1, 2), (2, 3), (3, 4), (4, 0)] G = nx.MultiDiGraph((edges * 2)) S = {0, 1} boundary = list(nx.edge_boundary(G, S)) expected = [(1, 2), (1, 2)] assert_equal(boundary, expected)
'Tests that the empty list is not a valid path, since there should be a one-to-one correspondence between paths as lists of nodes and paths as lists of edges.'
def test_empty_list(self):
G = nx.trivial_graph() assert_false(nx.is_simple_path(G, []))
'Tests that the trivial path, a path of length one, is considered a simple path in a graph.'
def test_trivial_path(self):
G = nx.trivial_graph() assert_true(nx.is_simple_path(G, [0]))
'Tests that a list whose sole element is an object not in the graph is not considered a simple path.'
def test_trivial_nonpath(self):
G = nx.trivial_graph() assert_false(nx.is_simple_path(G, ['not a node']))
'Empty graph'
def test_trivial(self):
G = nx.Graph() assert_equal(nx.find_cores(G), {})
'core number had a bug for directed graphs found in issue #1959'
def test_directed_find_cores(Self):
G = nx.DiGraph() edges = [(1, 2), (2, 1), (2, 3), (2, 4), (3, 4), (4, 3)] G.add_edges_from(edges) assert_equal(nx.core_number(G), {1: 2, 2: 2, 3: 2, 4: 2}) more_edges = [(1, 5), (3, 5), (4, 5), (3, 6), (4, 6), (5, 6)] G.add_edges_from(more_edges) assert_equal(nx.core_number(G), {1: 3, 2: 3, ...