def test_global_node_connectivity(): # Figure 1 chapter on Connectivity 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), ] ) assert 2 == approx.local_node_connectivity(G, 1, 11) assert 2 == approx.node_connectivity(G) assert 2 == approx.node_connectivity(G, 1, 11)
def test_solveMaze ( filenum, prefix=None, verbose=False ): command = prefix if prefix else "." command += "/solveMaze {}tests/test{}.txt {}queries/query{}.txt".format(prefix if prefix else "",filenum,prefix if prefix else "",filenum) if verbose: print (command) try: with open("{}queries/query{}.txt".format(prefix if prefix else "",filenum), "r") as qfile: source = int(qfile.readline()) target = int(qfile.readline()) with open("{}edgelists/edgelist{}.txt".format(prefix if prefix else "",filenum), "r") as edgelistfile: mazeGraph = nx.read_edgelist(edgelistfile,nodetype=int) except EnvironmentError: # parent of IOError, OSError print ("edgelists/edgelist{}.txt missing".format(filenum)) try: result = subprocess.check_output(command, shell=True).decode('ascii').strip() lines = result.split('\n') resultGraph = nx.parse_edgelist(lines,nodetype=int) for edge in resultGraph.edges: # print(edge) assert edge in mazeGraph.edges, "The edge {} is not part of the original graph.".format(edge) assert(approx.local_node_connectivity(resultGraph,source,target)==1), "The edges you returned do not connect the source and target nodes listed in queries/query{}.txt.".format(filenum) return True except subprocess.CalledProcessError as e: # print (e.output) print ("Calling ./solveMaze returned non-zero exit status.") except AssertionError as e: print (result) print (e.args[0]) return False
def update_inputs(self, input_type, game): turn = game.turn if input_type == 'all' or input_type == 'edges': self.inputs[self.input_indices['turn_pieces']] = self.norm(game.pieces[self.player_logical_index], 'pieces') self.inputs[self.input_indices['opponent_pieces']] = self.norm( game.pieces[np.logical_not(self.player_logical_index)], 'pieces') self.inputs[self.input_indices['turn_points']] = self.norm(game.points[self.player_logical_index], 'points') self.inputs[self.input_indices['opponent_points']] = self.norm( game.points[np.logical_not(self.player_logical_index)], 'points') self.inputs[self.input_indices['edges']] = game.map.extract_feature(range(self.NUM_EDGES), turn=turn) if input_type == 'all' or input_type == 'edges' or input_type == 'goal': goal_points = np.zeros(self.NUM_GOALS) subgraph = game.map.create_player_subgraph(turn) for g in range(game.cards.goals['hands'][turn].shape[0]): ind = game.cards.goals['hands'][turn].index[g] frm = game.cards.goals['hands'][turn].iloc[g, 0] to = game.cards.goals['hands'][turn].iloc[g, 1] points = game.cards.goals['hands'][turn].iloc[g, 2] if not approx.local_node_connectivity(subgraph, frm, to): points = -points goal_points[ind] = points self.inputs[self.input_indices['goals']] = self.norm(goal_points, 'goals') if input_type == 'all' or input_type == 'resources': hand_lengths = np.array([len(game.cards.resources['hands'][trn]) for trn in range(self.players)]) self.inputs[self.input_indices['opponent_hand_lengths']] = self.norm( hand_lengths[np.logical_not(self.player_logical_index)], 'hand_length') self.inputs[self.input_indices['faceups']] = self.norm(game.cards.color_count('faceup', dtype='array'), 'faceups') self.inputs[self.input_indices['hand_colors']] = self.norm( game.cards.color_count('hands', turn=turn, dtype='array'), 'hand')
def get_NC_index(self, u, v, graph): if (u, v) in nx.edges(graph): graph.remove_edge(u, v) value = approx.local_node_connectivity( graph, u, v, ) if u != v else -1 graph.add_edge(u, v) else: value = approx.local_node_connectivity( graph, u, v, ) if u != v else -1 return value
def test_global_node_connectivity(): # Figure 1 chapter on Connectivity 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)]) assert_equal(2, approx.local_node_connectivity(G,1,11)) assert_equal(2, approx.node_connectivity(G)) assert_equal(2, approx.node_connectivity(G,1,11))
def add_goal_points(self): points = np.zeros(self.players, dtype=np.int16) for turn in range(self.players): subgraph = self.map.create_player_subgraph(turn) goals = self.cards.goals['hands'][turn] for _, row in goals.iterrows(): if approx.local_node_connectivity(subgraph, row[0], row[1]) == 1: posneg = '+' points[turn] += row[2] self.goals_completed[turn] += 1 else: posneg = '-' points[turn] -= row[2] logging.debug('goal for player {}: from {} to {}, {}{}'.format( turn, row[0], row[1], posneg, row[2])) logging.info('goal points: {}'.format(points)) self.points += points
def build_auxiliary_graph(G, k, exact=False, antigraph=False): core_number = nx.core_number(G) C = G.subgraph((n for n in G if core_number[n] >= k)) if antigraph: H = AntiGraph() else: H = nx.Graph() H.add_nodes_from(C.nodes()) for u, v in itertools.combinations(C, 2): if exact: K = nx.local_node_connectivity(C, u, v) else: K = local_node_connectivity(C, u, v, max_paths=k) if antigraph: if k > K: H.add_edge(u, v) else: if k <= K: H.add_edge(u, v) return H
#Make a new graph only including the room nodes called G_rooms G_rooms.add_node(node,att = at['att']) # identify the essential nodes in the graph # Checking nodes are traversable to node p Dic_connectivity = collections.defaultdict() # First check for connectivity between all room nodes from networkx.algorithms import approximation as approx for node,at in sorted(G_rooms.nodes(data=True)): Dic_connectivity[node] = 0 for node1,at1 in sorted(G_rooms.nodes(data=True)): if node==node1: continue # This functions checks how many nodes need to be removed to disconnect 2 nodes connectivity = approx.local_node_connectivity(G, node, node1) #if connectivity == 0 and at['att'][3]==at1['att'][] if connectivity > 0: connectivity = 1 Dic_connectivity[node] += connectivity # Removing room nodes that are not connected to other room nodes, also change its description from roon node to grid node in G max_connection = max(Dic_connectivity.values()) # This section is for the rare case that there are 2 identical max connections, for example two isolated rooms of the same size. number_of_nodes = 0 list_of_keys = [] for key,value in Dic_connectivity.items(): if value == max_connection: number_of_nodes += 1
print 'Number of nodes:', G.number_of_nodes() print 'Number of edges:', G.number_of_edges() #Local connectivity from networkx.algorithms.connectivity import local_edge_connectivity from networkx.algorithms.connectivity import local_node_connectivity from networkx.algorithms import approximation as approx print "local_node_connectivity for training set" list_local_node_connectivity_train = [] compt=0 for id1, id2, edge in training_set: if compt % 50000 == 0: print compt compt += 1 local_con = approx.local_node_connectivity(G,id1,id2) list_local_node_connectivity_train.append([id1,id2,local_con]) with open("training_local_node_connectivity.csv", "w") as f: for row in list_local_node_connectivity_train: f.write(row[0]) f.write(",") f.write(row[1]) f.write(",") f.write(str(row[2])) f.write("\n") print "local_node_connectivity for testing set" list_local_node_connectivity_test = [] compt=0
print 'Number of nodes:', G.number_of_nodes() print 'Number of edges:', G.number_of_edges() #Local connectivity from networkx.algorithms.connectivity import local_edge_connectivity from networkx.algorithms.connectivity import local_node_connectivity from networkx.algorithms import approximation as approx print "local_node_connectivity for training set" list_local_node_connectivity_train = [] compt = 0 for id1, id2, edge in training_set: if compt % 50000 == 0: print compt compt += 1 local_con = approx.local_node_connectivity(G, id1, id2) list_local_node_connectivity_train.append([id1, id2, local_con]) with open("training_local_node_connectivity.csv", "w") as f: for row in list_local_node_connectivity_train: f.write(row[0]) f.write(",") f.write(row[1]) f.write(",") f.write(str(row[2])) f.write("\n") print "local_node_connectivity for testing set" list_local_node_connectivity_test = [] compt = 0 for id1, id2 in testing_set:
target = sys.argv[1] local_storage = json.load(open("localStorage/user", 'r')) print(local_storage["name"]) ''' for user in array_users: if user["name"] != local_storage["name"]: if approx.local_node_connectivity(G, local_storage["name"], user["name"]) != 0: for p in nx.all_shortest_paths(G, local_storage["name"], user["name"]): print(p) ''' print(target) #edgeList = nx.all_shortest_paths(G, local_storage["name"], array_users[0]["name"])[0] if approx.local_node_connectivity(G, local_storage["name"], target) != 0: for p in nx.all_shortest_paths(G, local_storage["name"], target): for x in range(0, len(list(p)) - 1): G.edges[p[x], p[x + 1]]['color'] = 'red' #nx.draw_random(G, **options) #plt.subplot(222) edges = G.edges() print(edges.data('color')) colors = [G[u][v]['color'] for u, v in edges] pos = nx.nx_pydot.graphviz_layout(G) nx.draw(G, pos, with_labels=True,
def connectcalculator(G, start, goal): connect = approx.local_node_connectivity(G, start, goal) #通過駅とその次の通過駅が接続されているかを調べる return connect