def test_strongly_connected_components_deep(self): # A deep graph will blow Python's recursion limit with # a recursive implementation of the algorithm. depth = 10000 vertices = set(range(depth + 1)) edge_mapper = {i: [i + 1] for i in range(depth)} edge_mapper[depth] = [0] graph = DirectedGraph.from_out_edges(vertices, edge_mapper) sccs = graph.strongly_connected_components() self.assertEqual(len(sccs), 1)
def graph_from_string(s): """ Turn a string like "1 2; 1->2" into a graph. """ vertex_string, edge_string = s.split(';') vertices = vertex_string.split() edge_pairs = [] for edge_sequence in edge_string.split(): sequence_nodes = edge_sequence.split('->') for tail, head in zip(sequence_nodes[:-1], sequence_nodes[1:]): edge_pairs.append((tail, head)) return DirectedGraph.from_edge_pairs(vertices, edge_pairs)
def test_full_subgraph_from_iterator(self): # Should be fine to create a subgraph from an iterator. vertex_count = 100 vertices = set(range(vertex_count)) edge_mapper = { n: [(n + 1) % vertex_count, (n + 1) % vertex_count] for n in vertices } graph = DirectedGraph.from_out_edges( vertices=vertices, edge_mapper=edge_mapper, ) subgraph = graph.full_subgraph(iter(vertices)) self.assertEqual(len(subgraph.vertices), len(graph.vertices)) self.assertEqual(len(subgraph.edges), len(graph.edges))
def test_full_subgraph_large_from_list(self): # An earlier version of full_subgraph had quadratic-time behaviour. vertex_count = 20000 vertices = set(range(vertex_count)) edge_mapper = { n: [(n + 1) % vertex_count, (n + 1) % vertex_count] for n in vertices } graph = DirectedGraph.from_out_edges( vertices=vertices, edge_mapper=edge_mapper, ) subgraph = graph.full_subgraph(list(vertices)) self.assertEqual(len(subgraph.vertices), len(graph.vertices)) self.assertEqual(len(subgraph.edges), len(graph.edges))
def test_ancestors_slow_case(self): # Regression test for #48. A buggy earlier version of the # ancestors method had running time exponential in # vertex_count. vertex_count = 100 vertices = set(range(vertex_count)) edge_mapper = { n: [(n + 1) % vertex_count, (n + 1) % vertex_count] for n in vertices } graph = DirectedGraph.from_out_edges( vertices=vertices, edge_mapper=edge_mapper, ) ancestors = graph.ancestors(0) self.assertEqual(set(ancestors), vertices)
import unittest import six from six.moves import range from refcycle.directed_graph import DirectedGraph test_graph = DirectedGraph.from_out_edges( vertices=set(range(1, 12)), edge_mapper={ 1: [4, 2, 3], 2: [1], 3: [5, 6, 7], 4: [], 5: [], 6: [7], 7: [], 8: [9], 9: [10], 10: [8], 11: [11], }, ) def graph_from_string(s): """ Turn a string like "1 2; 1->2" into a graph. """ vertex_string, edge_string = s.split(';')