def print_graph_parameters(G, pathways): # pragma: no cover '''Prints a set of parameters characterizing the graph ''' print('\nGRAPH PARAMETERS') num_paths = len(pathways) print("A total of " + str(num_paths) + " pathways were generated") shortest = get_shortest_path(pathways) longest = get_longest_path(pathways) print("\nThe shortest pathway is length " + str(len(next(iter(shortest))))) print("pathways with this length are " + str(shortest)) print("\nGraph depth is " + str(len(next(iter(longest))))) print("pathways with this length are " + str(longest)) semiconnected = nx.is_semiconnected(G) print('\nIs the graph semiconnected? ' + str(semiconnected)) if semiconnected is False: if len(list(n for n, in_deg in G.in_degree() if in_deg == 0)) > 1: print("You have multiple source facilities") hierarchy = nx.flow_hierarchy(G) print("\nGraph hierarchy is " + "{:.3f}".format(hierarchy)) return
def component_stats(G, verbose): """Prints out various relevent stats about graphs concerning components. Parameters ---------- G : networkx.DiGraph verbose : bool Set to True if you want explanations of stats Returns ------- Note: Writes to terminal. """ explans = {} if verbose == True: explans['weakly-connected'] = "(There is an undirected path between each pair of nodes in the directed graph)" explans['strongly-connected'] = "(There is a directed path between each pair of nodes in the directed graph)" explans['semiconnected'] = "" else: explans['weakly-connected'] = "" explans['strongly-connected'] = "" explans['semiconnected'] = "" print "Is the graph weakly connected "+explans['weakly-connected'] +"? "+ str(nx.is_weakly_connected(G)) print "Number of weakly connected components: " + str(nx.number_weakly_connected_components(G)) print "Is the graph semiconnected "+explans['semiconnected']+ "? " + str(nx.is_semiconnected(G)) print "Is the graph strongly connected "+explans['strongly-connected']+ "? "+ str(nx.is_strongly_connected(G))
def component(self): rslt = {} if self.directed == 'directed': rslt['is_strongly_connected'] = nx.is_strongly_connected( self.graph) strong = nx.strongly_connected_components(self.graph) strong_nodes = [] for n in strong: strong_nodes.append(list(n)[0]) rslt['strongly_connected'] = strong_nodes rslt[ 'number_strongly_connected_components'] = nx.number_strongly_connected_components( self.graph) rslt['is_semiconnected'] = nx.is_semiconnected(self.graph) weak = nx.weakly_connected_components(self.graph) weak_nodes = [] for n in weak: weak_nodes.append(list(n)[0]) rslt['wealy_connected'] = weak_nodes rslt['is_weakly_connected'] = nx.is_weakly_connected(self.graph) rslt[ 'number_weakly_connected_components'] = nx.number_weakly_connected_components( self.graph) fname_component = self.DIR + '/component.json' with open(fname_component, "w") as f: json.dump(rslt, f, cls=SetEncoder, indent=2) print(fname_component)
def write_components_info(G, report_file): report_file.write("===COMPONENTS_INFO===\n") report_file.write("Number of strongly connected components: {}\n".format( nx.number_strongly_connected_components(G))) report_file.write("Number of weakly connected components: {}\n".format( nx.number_weakly_connected_components(G))) report_file.write("Number of attractive components: {}\n".format( nx.number_attracting_components(G))) report_file.write("Is semiconnected: {}\n".format(nx.is_semiconnected(G)))
def print_is_of_type_attrs(graph): print("\n====== is of type X? ======") print("Directed? ->", "Yes" if nx.is_directed(graph) else "No") print("Directed acyclic? ->", "Yes" if nx.is_directed_acyclic_graph(graph) else "No") print("Weighted? ->", "Yes" if nx.is_weighted(graph) else "No") if nx.is_directed(graph): print("Aperiodic? ->", "Yes" if nx.is_aperiodic(graph) else "No") print("Arborescence? ->", "Yes" if nx.is_arborescence(graph) else "No") print("Weakly Connected? ->", "Yes" if nx.is_weakly_connected(graph) else "No") print("Semi Connected? ->", "Yes" if nx.is_semiconnected(graph) else "No") print("Strongly Connected? ->", "Yes" if nx.is_strongly_connected(graph) else "No") else: print("Connected? ->", "Yes" if nx.is_connected(graph) else "No") print("Bi-connected? ->", "Yes" if nx.is_biconnected(graph) else "No") if not graph.is_multigraph(): print("Chordal? -> ", "Yes" if nx.is_chordal(graph) else "No") print("Forest? -> ", "Yes" if nx.is_chordal(graph) else "No") print("Distance regular? -> ", "Yes" if nx.is_distance_regular(graph) else "No") print("Eulerian? -> ", "Yes" if nx.is_eulerian(graph) else "No") print("Strongly regular? -> ", "Yes" if nx.is_strongly_regular(graph) else "No") print("Tree? -> ", "Yes" if nx.is_tree(graph) else "No")
def test_dumbbell(self): G = nx.cycle_graph(100, create_using=nx.DiGraph()) G.add_edges_from((i + 100, (i + 1) % 100 + 100) for i in range(100)) ok_(not nx.is_semiconnected(G)) # G is disconnected. G.add_edge(100, 99) ok_(nx.is_semiconnected(G))
def test_alternating_path(self): G = nx.DiGraph( chain.from_iterable([(i, i - 1), (i, i + 1)] for i in range(0, 100, 2))) ok_(not nx.is_semiconnected(G))
def test_cycle(self): G = nx.cycle_graph(100, create_using=nx.DiGraph()) ok_(nx.is_semiconnected(G)) G = nx.path_graph(100, create_using=nx.DiGraph()) G.add_edge(0, 99) ok_(nx.is_semiconnected(G))
def test_tree(self): G = nx.DiGraph() G.add_edges_from( chain.from_iterable([(i, 2 * i + 1), (i, 2 * i + 2)] for i in range(100))) ok_(not nx.is_semiconnected(G))
pairs.append([int(x) for x in line.split(" ")]) else: pairs = [] graphs.append(pairs) # Iterate graphs i = 0 results = [] for graph in graphs: graph.pop(0) # Create graph G = nx.DiGraph() i += 1 # Place edges for pair in graph: G.add_edge(pair[0], pair[1]) # Compute connected components if nx.is_semiconnected(G) == True: results.append(1) else: results.append(-1) # AG = nx.nx_agraph.to_agraph(G) # AG.layout() # AG.draw(f'file{i}.png') print(" ".join([str(x) for x in results]))
def test_single_node_graph(self): G = nx.DiGraph() G.add_node(0) ok_(nx.is_semiconnected(G))
L.remove_nodes_from(overlap) R.remove_nodes_from(overlap) L.number_of_nodes() # 3855362 --> 3853285 without overlap L.number_of_edges() # 1018168 --> 1019598 without overlap R.number_of_nodes() # 2676014 --> 2659857 without overlap R.number_of_edges() # 1911249 --> 1840621 without overlap #looks like a lot of elites were in the overlap - this is meaningful # but we shall still keep them out of the analysis # to compare people who only communicate in their own LEFT or RIGHT community #### Connected components (after excluding overlap) #### nx.is_semiconnected(L) #False largest_wcc_LEFT = max(nx.weakly_connected_components(L), key=len) #len(nx.weakly_connected_components(L)) - doesn;t work --> cannot currently work out how many CCs are in LEFT directed graph largest_wcc_LEFT = L.subgraph(largest_wcc_LEFT).copy() largest_wcc_LEFT.number_of_nodes() #822781 largest_wcc_LEFT.number_of_edges() #1019598 ## REPEAT FOR RIGHT largest_wcc_RIGHT = max(nx.weakly_connected_components(R), key=len) #len(nx.weakly_connected_components(R)) - doesn;t work --> cannot currently work out how many CCs are in RIGHT directed graph largest_wcc_RIGHT = R.subgraph(largest_wcc_RIGHT).copy() largest_wcc_RIGHT.number_of_nodes() #1542256 largest_wcc_RIGHT.number_of_edges() #1840621 #count number of weakly connected components
import networkx as nx f = open('rosalind_sc.txt') k = int(f.readline().rstrip()) result = [] for i in range(k): s = '' while s == '': s = f.readline().rstrip() n, m = [int(l) for l in s.split()] nodes = [i+1 for i in range(n)] G = nx.DiGraph() G.add_nodes_from(nodes) for j in range(m): u, v = [int(l) for l in f.readline().rstrip().split()] G.add_edge(u, v) output = '-1' if nx.is_semiconnected(G): output = '1' result.append(output) result = ' '.join(result) print(result) open('rosalind_sc_sub.txt', 'wt').write(result)
def test_tree(self): G = nx.DiGraph() G.add_edges_from(chain.from_iterable([(i, 2 * i + 1), (i, 2 * i + 2)] for i in range(100))) ok_(not nx.is_semiconnected(G))
def test_alternating_path(self): G = nx.DiGraph(chain.from_iterable([(i, i - 1), (i, i + 1)] for i in range(0, 100, 2))) ok_(not nx.is_semiconnected(G))
def test_path(self): G = nx.path_graph(100, create_using=nx.DiGraph()) assert nx.is_semiconnected(G) G.add_edge(100, 99) assert not nx.is_semiconnected(G)
6: (0, 2), 7: (.5, 1), 8: (.5, .75) } # nx.draw_networkx(G, pos=posicoes) print("Componentes fracamente conexas") print("---------------------------------------------------------------------") print("Grafo 'G' é fracamente (simplesmente) conexo?", "Sim" if nx.is_weakly_connected(G) else "Não") print("Componente fracamente conexas:", list(nx.weakly_connected_components(G))) print("\nGrafo semiconexo") print("---------------------------------------------------------------------") print("Grafo 'G' é semiconexo (semi-fortemente conexo)?", "Sim" if nx.is_semiconnected(G) else "Não") print("\nGrafo fortemente conexo") print("---------------------------------------------------------------------") print("Grafo 'G' é fortemente conexo?", "Sim" if nx.is_semiconnected(G) else "Não") print("# de componentes fortemente conexas:", nx.number_strongly_connected_components(G)) print("Componentes fortemente conexas:", list(nx.strongly_connected_components(G))) print("Maior componente conexa:", max(nx.strongly_connected_components(G), key=len)) grafo_reduzido = nx.condensation(G) print("Grafo reduzido:", grafo_reduzido.nodes()) nx.draw_networkx(grafo_reduzido)
def sc(N): return [1 if nx.is_semiconnected(G) else -1 for G in N ]