def test_brandes_erlebach_book(): # Figure 1 chapter 7: Connectivity # http://www.informatik.uni-augsburg.de/thi/personen/kammer/Graph_Connectivity.pdf G = nx.Graph() G.add_edges_from([(1, 2), (1, 3), (1, 4), (1, 5), (2, 3), (2, 6), (3, 4), (3, 6), (4, 6), (4, 7), (5, 7), (6, 8), (6, 9), (7, 8), (7, 10), (8, 11), (9, 10), (9, 11), (10, 11)]) for flow_func in flow_funcs: kwargs = dict(flow_func=flow_func) # edge cutsets assert_equal(3, len(nx.minimum_edge_cut(G, 1, 11, **kwargs)), msg=msg.format(flow_func.__name__)) edge_cut = nx.minimum_edge_cut(G, **kwargs) # Node 5 has only two edges assert_equal(2, len(edge_cut), msg=msg.format(flow_func.__name__)) H = G.copy() H.remove_edges_from(edge_cut) assert_false(nx.is_connected(H), msg=msg.format(flow_func.__name__)) # node cuts assert_equal(set([6, 7]), minimum_st_node_cut(G, 1, 11, **kwargs), msg=msg.format(flow_func.__name__)) assert_equal(set([6, 7]), nx.minimum_node_cut(G, 1, 11, **kwargs), msg=msg.format(flow_func.__name__)) node_cut = nx.minimum_node_cut(G, **kwargs) assert_equal(2, len(node_cut), msg=msg.format(flow_func.__name__)) H = G.copy() H.remove_nodes_from(node_cut) assert_false(nx.is_connected(H), msg=msg.format(flow_func.__name__))
def test_brandes_erlebach_book(): # Figure 1 chapter 7: Connectivity # http://www.informatik.uni-augsburg.de/thi/personen/kammer/Graph_Connectivity.pdf G = nx.Graph() G.add_edges_from([(1, 2), (1, 3), (1, 4), (1, 5), (2, 3), (2, 6), (3, 4), (3, 6), (4, 6), (4, 7), (5, 7), (6, 8), (6, 9), (7, 8), (7, 10), (8, 11), (9, 10), (9, 11), (10, 11)]) for flow_func in flow_funcs: kwargs = dict(flow_func=flow_func) errmsg = f"Assertion failed in function: {flow_func.__name__}" # edge cutsets assert 3 == len(nx.minimum_edge_cut(G, 1, 11, **kwargs)), errmsg edge_cut = nx.minimum_edge_cut(G, **kwargs) # Node 5 has only two edges assert 2 == len(edge_cut), errmsg H = G.copy() H.remove_edges_from(edge_cut) assert not nx.is_connected(H), errmsg # node cuts assert {6, 7} == minimum_st_node_cut(G, 1, 11, **kwargs), errmsg assert {6, 7} == nx.minimum_node_cut(G, 1, 11, **kwargs), errmsg node_cut = nx.minimum_node_cut(G, **kwargs) assert 2 == len(node_cut), errmsg H = G.copy() H.remove_nodes_from(node_cut) assert not nx.is_connected(H), errmsg
def print_robustness(): #What is the smallest number of nodes that can be removed from this graph in order to disconnect it? # 1) whole graph: nx.node_connectivity(G) #1 - too small, When higher - it is good nx.minimum_node_cut(G) #{'Чкаловская'} nx.edge_connectivity(G) # 1 nx.minimum_edge_cut(G) #{('Марьино', 'Чкаловская')} # 2) concrete path nx.node_connectivity(G, 'Киевская', 'Чкаловская') #2 - better nx.minimum_node_cut(G, 'Киевская', 'Чкаловская') #{'Курская', 'Сретенский бульвар'} nx.edge_connectivity(G, 'Киевская', 'Чкаловская') #2 - better nx.minimum_edge_cut(G, 'Киевская', 'Чкаловская') #{('Курская', 'Чкаловская'), ('Сретенский бульвар', 'Чкаловская')}
def global_resilience(G): #Global resilience #Calculate the size of the reachable nodes set for each node in the graph G h_max = len(G) # for each node n in Graph G calculate the h-hop environment h_ball, then number of nodes n_cnt in h_ball, and the local Resilience Rih # declare lists for the average number of nodes n_global and average resilience R_global in each h-hop environment n_global = list() R_global = list() for h in range(h_max): n_sum = 0 Rnh_sum = 0 for n in G: h_ball = nx.ego_graph(G, n, h) n_count = len(h_ball) Rih = len(nx.minimum_node_cut(h_ball)) #Rih = len(metis.part_graph(h_ball)) n_sum += n_count Rnh_sum += Rih # calculate average resilience for h-hop environment h n_global.append(n_sum / h_max) R_global.append(Rnh_sum / h_max) return n_global, R_global
def answer_twelve(): G_sc = answer_six() center = nx.center(G_sc)[0] mynode = answer_eleven()[0] return len(nx.minimum_node_cut(G_sc, center, mynode))
def calc_net_connectivity(graph_cons, vehs=None, cut_only_fully_connected=True): """Calculates the network connectivity (relative size of the biggest connected cluster)""" time_start = utils.debug(None, 'Finding biggest cluster') # Find biggest cluster count_veh = graph_cons.order() clusters = list(nx.connected_component_subgraphs(graph_cons)) cluster_max = max(clusters, key=len) count_veh_max = cluster_max.order() net_connectivity = count_veh_max / count_veh if vehs is not None: cluster_nodes = cluster_max.nodes() vehs.add_key('cluster_max', cluster_nodes) not_cluster_max_nodes = np.arange( count_veh)[~np.in1d(np.arange(count_veh), cluster_nodes)] vehs.add_key('not_cluster_max', not_cluster_max_nodes) # Find the minimum node cut count_cluster = len(clusters) if count_cluster == 1 or not cut_only_fully_connected: min_node_cut = nx.minimum_node_cut(cluster_max) else: min_node_cut = None result = NetworkConnectivity(net_connectivity=net_connectivity, min_node_cut=min_node_cut, count_cluster=count_cluster) utils.debug(time_start) return result
def answer_twelve(): G = answer_six() return len( nx.minimum_node_cut(G, list(answer_ten())[0], answer_eleven()[0]))
def find_which_nodes_and_edges_to_remove(G, n1, n2): a = nx.node_connectivity(G, n1, n2) b = nx.minimum_node_cut(G, n1, n2) c = nx.edge_connectivity(G, n1, n2) d = nx.minimum_edge_cut(G, n1, n2) print(a, b, c, d) return (a, b, c, d)
def test_node_cutset_random_graphs(): for i in range(5): G = nx.fast_gnp_random_graph(50,0.2) cutset = nx.minimum_node_cut(G) assert_equal(nx.node_connectivity(G), len(cutset)) G.remove_nodes_from(cutset) assert_false(nx.is_connected(G))
def test_white_harary_paper(): # Figure 1b white and harary (2001) # http://eclectic.ss.uci.edu/~drwhite/sm-w23.PDF # A graph with high adhesion (edge connectivity) and low cohesion # (node connectivity) G = nx.disjoint_union(nx.complete_graph(4), nx.complete_graph(4)) G.remove_node(7) for i in range(4,7): G.add_edge(0,i) G = nx.disjoint_union(G, nx.complete_graph(4)) G.remove_node(G.order()-1) for i in range(7,10): G.add_edge(0,i) for flow_func in flow_funcs: kwargs = dict(flow_func=flow_func) # edge cuts edge_cut = nx.minimum_edge_cut(G, **kwargs) assert_equal(3, len(edge_cut), msg=msg.format(flow_func.__name__)) H = G.copy() H.remove_edges_from(edge_cut) assert_false(nx.is_connected(H), msg=msg.format(flow_func.__name__)) # node cuts node_cut = nx.minimum_node_cut(G, **kwargs) assert_equal(set([0]), node_cut, msg=msg.format(flow_func.__name__)) H = G.copy() H.remove_nodes_from(node_cut) assert_false(nx.is_connected(H), msg=msg.format(flow_func.__name__))
def test_articulation_points(): Ggen = _generate_no_biconnected() for i in range(5): G = next(Ggen) cut = nx.minimum_node_cut(G) assert_true(len(cut) == 1) assert_true(cut.pop() in set(nx.articulation_points(G)))
def answer_twelve(): # Your Code Here G_sc = answer_six() center = nx.center(G_sc)[0] node = answer_eleven()[0] return len(nx.minimum_node_cut(G_sc, center, node))
def test_node_cutset_random_graphs(): for i in range(5): G = nx.fast_gnp_random_graph(50, 0.2) cutset = nx.minimum_node_cut(G) assert_equal(nx.node_connectivity(G), len(cutset)) G.remove_nodes_from(cutset) assert_false(nx.is_connected(G))
def merge(self,minN): import numpy as np merged=[] merged_cliq=[] while len(DiGraph.nodes(self)): #print(len(self.nodes())) contcmp,ct_cliq=self.splitG(minN) if not DiGraph.nodes(self): break merged=merged+contcmp merged_cliq=merged_cliq+ct_cliq try: #print("point1") cut_nodes=minimum_node_cut(self) #print("point2") except: nodes=DiGraph.nodes(self) index=np.random.randint(len(nodes)) cut_nodes=[nodes[index]] for node in cut_nodes: DiGraph.remove_node(self,node) self.topics=merged self.topic_cliq=merged_cliq
def graphDisjointPath(NG, group1, group2, operation): nmbOutputs = len(NG) nmbOutputs2 = len(NG[0]) #operation depicts if the minimum disconnected set should be located (operation==0) or the disjoint path (operation==1) #below function will read through the mat file and try to find how many modules their are #using the network functions create a direction graph (nodes with a connection with a direction so connection 1 to 2 has a direction and is not the same as 2 to 1) plot = nx.DiGraph() plot.add_nodes_from(range(nmbOutputs)) for x in range(nmbOutputs): for y in range(nmbOutputs2): if (NG[x][y] == 1): plot.add_edge(y, x) plot.add_node(nmbOutputs) plot.add_node(nmbOutputs + 1) for x in group1: plot.add_edge(nmbOutputs, x[1].nmb - 1) for x in group2: plot.add_edge(x[1].nmb - 1, nmbOutputs + 1) if (operation): result = list(nx.node_disjoint_paths(plot, nmbOutputs, nmbOutputs + 1)) else: result = list(nx.minimum_node_cut(plot, nmbOutputs, nmbOutputs + 1)) return result
def test_white_harary_paper(): # Figure 1b white and harary (2001) # http://eclectic.ss.uci.edu/~drwhite/sm-w23.PDF # A graph with high adhesion (edge connectivity) and low cohesion # (node connectivity) G = nx.disjoint_union(nx.complete_graph(4), nx.complete_graph(4)) G.remove_node(7) for i in range(4, 7): G.add_edge(0, i) G = nx.disjoint_union(G, nx.complete_graph(4)) G.remove_node(G.order() - 1) for i in range(7, 10): G.add_edge(0, i) for flow_func in flow_funcs: kwargs = dict(flow_func=flow_func) errmsg = f"Assertion failed in function: {flow_func.__name__}" # edge cuts edge_cut = nx.minimum_edge_cut(G, **kwargs) assert 3 == len(edge_cut), errmsg H = G.copy() H.remove_edges_from(edge_cut) assert not nx.is_connected(H), errmsg # node cuts node_cut = nx.minimum_node_cut(G, **kwargs) assert {0} == node_cut, errmsg H = G.copy() H.remove_nodes_from(node_cut) assert not nx.is_connected(H), errmsg
def test_white_harary_paper(): # Figure 1b white and harary (2001) # http://eclectic.ss.uci.edu/~drwhite/sm-w23.PDF # A graph with high adhesion (edge connectivity) and low cohesion # (node connectivity) G = nx.disjoint_union(nx.complete_graph(4), nx.complete_graph(4)) G.remove_node(7) for i in range(4, 7): G.add_edge(0, i) G = nx.disjoint_union(G, nx.complete_graph(4)) G.remove_node(G.order() - 1) for i in range(7, 10): G.add_edge(0, i) for flow_func in flow_funcs: kwargs = dict(flow_func=flow_func) # edge cuts edge_cut = nx.minimum_edge_cut(G, **kwargs) assert_equal(3, len(edge_cut), msg=msg.format(flow_func.__name__)) H = G.copy() H.remove_edges_from(edge_cut) assert_false(nx.is_connected(H), msg=msg.format(flow_func.__name__)) # node cuts node_cut = nx.minimum_node_cut(G, **kwargs) assert_equal(set([0]), node_cut, msg=msg.format(flow_func.__name__)) H = G.copy() H.remove_nodes_from(node_cut) assert_false(nx.is_connected(H), msg=msg.format(flow_func.__name__))
def find_chamber(graph): """Detect chambers (rooms with a single square entrance). Return (entrance, chamber), where `entrance` is the node representing the entrance to the chamber (None if no chamber is found), and `chamber` is the list of nodes within the chamber (empty list if no nodes are in the chamber). The entrance to a chamber is a node that when removed from the graph will result in the graph to be split into two disconnected graphs.""" # minimum_node_cut returns a set of nodes of minimum cardinality that # disconnects the graph. This means that we have a chamber if the length # of this set is one, i.e. there is one node that when removed disconnects # the graph cuts = nx.minimum_node_cut(graph) if len(cuts) > 1: # no chambers, yeah! return None, [] entrance = cuts.pop() # remove the cut, i.e. put a wall on the entrance lgraph = nx.restricted_view(graph, [entrance], []) # now get the resulting subgraphs subgraphs = sorted(nx.connected_components(lgraph), key=len) # let's get the smallest subgraph: this is going to be a chamber # (other subgraphs are other chambers (if any) and the 'rest' of the graph # return a list of nodes, instead of a set chamber = list(subgraphs[0]) return entrance, chamber
def test_articulation_points(): Ggen = _generate_no_biconnected() for flow_func in flow_funcs: for i in range(3): G = next(Ggen) cut = nx.minimum_node_cut(G, flow_func=flow_func) assert_true(len(cut) == 1, msg=msg.format(flow_func.__name__)) assert_true(cut.pop() in set(nx.articulation_points(G)), msg=msg.format(flow_func.__name__))
def test_articulation_points(): Ggen = _generate_no_biconnected() for flow_func in flow_funcs: errmsg = f"Assertion failed in function: {flow_func.__name__}" for i in range(1): # change 1 to 3 or more for more realizations. G = next(Ggen) cut = nx.minimum_node_cut(G, flow_func=flow_func) assert len(cut) == 1, errmsg assert cut.pop() in set(nx.articulation_points(G)), errmsg
def test_articulation_points(): Ggen = _generate_no_biconnected() for flow_func in flow_funcs: for i in range(1): # change 1 to 3 or more for more realizations. G = next(Ggen) cut = nx.minimum_node_cut(G, flow_func=flow_func) assert_true(len(cut) == 1, msg=msg % (flow_func.__name__, )) assert_true(cut.pop() in set(nx.articulation_points(G)), msg=msg % (flow_func.__name__, ))
def minimum_node_cut(self): if nx.is_connected(self.DG): cutset = nx.minimum_node_cut(self.DG) print('### information about the minimum number of nodes that disconnects the graph') print('the minimum number of node that if removed, ' \ 'would partition the graph into two components: ' + str(len(cutset))) print('the minimum node cut contains the following nodes: ' + str(cutset)) else: print('Graph is not connected! No information provided for the minimum node cut.')
def local_resilience(G, h, i): #Local resilience if (h < 0) or (type(h) is not int): raise ValueError("h-hop environment radius is not a natural number") if G.has_node(i): return len(nx.minimum_node_cut(nx.ego_graph(G, i, h))) #return len(metis.part_graph(nx.ego_graph(G, i, h))) else: raise ValueError("{0} is not in given Graph".format(i))
def answer_twelve(): nodes_to_cut = set() G_sc = answer_six() target = answer_eleven()[0] sources = nx.center(G_sc) for source in sources: min_nodes_to_cut = nx.minimum_node_cut(G_sc, s=source, t=target) nodes_to_cut.update(min_nodes_to_cut) n_min_nodes_to_cut = len(nodes_to_cut) return n_min_nodes_to_cut
def find_minimum_vertex_cut(new:bool=False,s:tuple=None,t:tuple=None): """ Description: Find minimum vertex cut Args: new (bool): A variable to decide which graph to use. Default value <False> Returns: minimum_node_cut """ global G global new_G if not new: return nx.minimum_node_cut(G) else: if s != None and t != None: return minimum_st_node_cut(new_G,s,t) return nx.minimum_node_cut(new_G) return None
def answer_twelve(): # Your Code Here G_sc = answer_six() node_11 = answer_eleven()[0] center_nodes = nx.center(G_sc) no_cut_nodes = len( [nx.minimum_node_cut(G_sc, cn, node_11) for cn in center_nodes][0]) return no_cut_nodes
def answer_twelve(): G_sc = answer_six() center_list = list(set(nx.center(G_sc))) my_set = set([]) for node in center_list: my_set = my_set.union(nx.minimum_node_cut(G_sc, node, "97")) return len(my_set)
def test_node_cutset_random_graphs(): for i in range(5): G = nx.fast_gnp_random_graph(50, 0.2) if not nx.is_connected(G): ccs = iter(nx.connected_components(G)) start = next(ccs)[0] G.add_edges_from((start, c[0]) for c in ccs) cutset = nx.minimum_node_cut(G) assert_equal(nx.node_connectivity(G), len(cutset)) G.remove_nodes_from(cutset) assert_false(nx.is_connected(G))
def test_node_cutset_random_graphs(): for i in range(5): G = nx.fast_gnp_random_graph(50,0.2) if not nx.is_connected(G): ccs = iter(nx.connected_components(G)) start = next(ccs)[0] G.add_edges_from( (start,c[0]) for c in ccs ) cutset = nx.minimum_node_cut(G) assert_equal(nx.node_connectivity(G), len(cutset)) G.remove_nodes_from(cutset) assert_false(nx.is_connected(G))
def test_node_cutset_random_graphs(): for flow_func in flow_funcs: for i in range(3): G = nx.fast_gnp_random_graph(50, 0.25) if not nx.is_connected(G): ccs = iter(nx.connected_components(G)) start = arbitrary_element(next(ccs)) G.add_edges_from((start, arbitrary_element(c)) for c in ccs) cutset = nx.minimum_node_cut(G, flow_func=flow_func) assert_equal(nx.node_connectivity(G), len(cutset), msg=msg.format(flow_func.__name__)) G.remove_nodes_from(cutset) assert_false(nx.is_connected(G), msg=msg.format(flow_func.__name__))
def answer_twelve(): G_sc = answer_six() G_sc_center = nx.center(G_sc)[0] # only contains one node isolate_node = answer_eleven()[0] # An edge between G_sc_center and isolation_node exists. # There is a check for such an edge in # ../lib/python3.8/site-packages/networkx/algorithms/connectivity/cuts.py line 286 # This was added in version 2.0 of networkx # # Autograder uses networkx version 1.11 which does not have this check. # Output accepting by autograder: 5 return len(nx.minimum_node_cut(G_sc, G_sc_center, isolate_node))
def test_node_cutset_random_graphs(): for flow_func in flow_funcs: errmsg = f"Assertion failed in function: {flow_func.__name__}" for i in range(3): G = nx.fast_gnp_random_graph(50, 0.25, seed=42) if not nx.is_connected(G): ccs = iter(nx.connected_components(G)) start = arbitrary_element(next(ccs)) G.add_edges_from((start, arbitrary_element(c)) for c in ccs) cutset = nx.minimum_node_cut(G, flow_func=flow_func) assert nx.node_connectivity(G) == len(cutset), errmsg G.remove_nodes_from(cutset) assert not nx.is_connected(G), errmsg
def test_octahedral_cutset(): G=nx.octahedral_graph() # edge cuts edge_cut = nx.minimum_edge_cut(G) assert_equal(4, len(edge_cut)) H = G.copy() H.remove_edges_from(edge_cut) assert_false(nx.is_connected(H)) # node cuts node_cut = nx.minimum_node_cut(G) assert_equal(4,len(node_cut)) H = G.copy() H.remove_nodes_from(node_cut) assert_false(nx.is_connected(H))
def test_octahedral_cutset(): G = nx.octahedral_graph() # edge cuts edge_cut = nx.minimum_edge_cut(G) assert_equal(4, len(edge_cut)) H = G.copy() H.remove_edges_from(edge_cut) assert_false(nx.is_connected(H)) # node cuts node_cut = nx.minimum_node_cut(G) assert_equal(4, len(node_cut)) H = G.copy() H.remove_nodes_from(node_cut) assert_false(nx.is_connected(H))
def answer_twelve(): G_sc = answer_six() center = nx.center(G_sc) node = answer_eleven()[0] rslt = set() for c in center: tmp = nx.minimum_node_cut(G_sc, c, node) for i in tmp: if rslt is None: rslt = set(i) else: rslt.add(i) return len(rslt)
def test_icosahedral_cutset(): G = nx.icosahedral_graph() for flow_func in flow_funcs: kwargs = dict(flow_func=flow_func) # edge cuts edge_cut = nx.minimum_edge_cut(G, **kwargs) assert_equal(5, len(edge_cut), msg=msg.format(flow_func.__name__)) H = G.copy() H.remove_edges_from(edge_cut) assert_false(nx.is_connected(H), msg=msg.format(flow_func.__name__)) # node cuts node_cut = nx.minimum_node_cut(G, **kwargs) assert_equal(5, len(node_cut), msg=msg.format(flow_func.__name__)) H = G.copy() H.remove_nodes_from(node_cut) assert_false(nx.is_connected(H), msg=msg.format(flow_func.__name__))
def minimum_cut(self): # Sometimes begin nodes may not even be in the graph! if self.begin_node not in self.nx_graph.nodes(): return None return nx.minimum_node_cut( self.nx_graph, self.begin_node, self.end_node)