def test_dth16_long_links_path(self): """ Test that it can sum a list of integers """ factory = graph_edge_factory.VirtualEdgeFactory(distance_threshold=16) graph_edges = factory.generate_deterministic_graph_edges() local_graph = graph.Graph(graph_edges) self.assertEqual(shortest_path.dijkstra(local_graph, 1, 17), [17, 1]) self.assertTrue( shortest_path.dijkstra(local_graph, 6, 18) != [18, 17, 1, 5, 6]) self.assertEqual(shortest_path.dijkstra(local_graph, 32, 18), [18, 17, 1, 32]) self.assertEqual(shortest_path.dijkstra(local_graph, 31, 18), [18, 17, 1, 31]) self.assertEqual(shortest_path.dijkstra(local_graph, 31, 18), [18, 17, 1, 31]) self.assertEqual(shortest_path.dijkstra(local_graph, 30, 18), [18, 17, 1, 29, 30]) self.assertEqual(shortest_path.dijkstra(local_graph, 29, 18), [18, 17, 1, 29]) self.assertEqual(shortest_path.dijkstra(local_graph, 28, 18), [18, 17, 1, 29, 28]) self.assertTrue( shortest_path.dijkstra(local_graph, 27, 18) != [18, 17, 1, 29, 27]) self.assertTrue( shortest_path.dijkstra(local_graph, 6, 18) != [18, 17, 1, 5, 6])
def test_dth2_simple_path(self): """ Test that it computes the paths according to the local data """ link_prediction = True factory = graph_edge_factory.VirtualEdgeFactory(distance_threshold=2) graph_edges = factory.generate_deterministic_graph_edges() local_graph = graph.Graph(graph_edges, link_prediction=link_prediction) # Shortest paths in the virtual graph self.assertEqual( shortest_path.dijkstra(local_graph, 1, 3, link_prediction=True), [3, 1]) self.assertEqual( shortest_path.dijkstra(local_graph, 1, 5, link_prediction=True), [5, 3, 1]) current_step = 1000 local_graph.update_stored_weights(current_step)\ # Still getting the same result, as 1 is equal to the source -> knows the availability of the 1-3 link self.assertEqual( shortest_path.dijkstra(local_graph, 1, 3, link_prediction=True), [3, 1]) # Link 3-5 is far away, so we move along the physical graph self.assertEqual( shortest_path.dijkstra(local_graph, 1, 5, link_prediction=True), [5, 4, 3, 1])
def test_dth8_on_demand_long_links_path(self): """ Test that it can sum a list of integers """ factory = graph_edge_factory.VirtualEdgeFactory(distance_threshold=8, capacity=0) graph_edges = factory.generate_deterministic_graph_edges() local_graph = graph.Graph(graph_edges) # self.assertEqual(shortest_path.dijkstra(local_graph, 1, 17), [17, 13, 9, 5, 1]) self.assertEqual(shortest_path.dijkstra(local_graph, 1, 19), [19, 21, 25, 1]) # Disclaimer: the following is longer than the expected shortest path, as we are in the on-demand model self.assertEqual(shortest_path.dijkstra(local_graph, 1, 18), [18, 19, 21, 25, 1]) self.assertEqual(shortest_path.dijkstra(local_graph, 1, 16), [16, 15, 13, 9, 1]) self.assertEqual(shortest_path.dijkstra(local_graph, 1, 15), [15, 13, 9, 1]) self.assertEqual(shortest_path.dijkstra(local_graph, 1, 14), [14, 13, 9, 1])
def initialize_paths(graph, number_of_source_destination_pairs: int, link_prediction: bool = False) -> deque: """ Initialise paths by generating source and destination pairs and finding the shortest path for each of them. Parameters ---------- graph: Graph The graph in which we run our simulation. number_of_source_destination_pairs: int The paths link_prediction: bool Value determining whether or not link prediction is used. Returns ----- A deque of shortest paths """ # Generate random pairs of nodes between which we are seeking a path random_pairs = generate_random_pairs(number_of_source_destination_pairs) # Assemble paths into one deque paths = deque() for pair in random_pairs: path = shortest_path.dijkstra(graph, pair[0], pair[1], link_prediction=link_prediction) paths.appendleft(path) return paths
def test_dth2_long_links_path(self): """ Test that it can sum a list of integers """ factory = graph_edge_factory.VirtualEdgeFactory(distance_threshold=2) graph_edges = factory.generate_deterministic_graph_edges() local_graph = graph.Graph(graph_edges) self.assertEqual(shortest_path.dijkstra(local_graph, 1, 15), [15, 13, 11, 9, 7, 5, 3, 1])
def get_paths_for_all_pairs(self) -> list: """ Get all the shortest paths for every possible source and destination pairs in a given graph. Returns: List of shortest paths for each viable pair. """ return [shortest_path.dijkstra(self, x, y) for x in range(1, len(self.Vertices) + 1) for y in range(1, len(self.Vertices) + 1) if x != y]
def test_dth4_simple_path(self): """ Test that it can sum a list of integers """ factory = graph_edge_factory.VirtualEdgeFactory(distance_threshold=4) graph_edges = factory.generate_deterministic_graph_edges() local_graph = graph.Graph(graph_edges) self.assertEqual(shortest_path.dijkstra(local_graph, 1, 5), [5, 1])
def test_dth2_complex_path(self): """ Test that it can sum a list of integers """ factory = graph_edge_factory.VirtualEdgeFactory(distance_threshold=2) graph_edges = factory.generate_deterministic_graph_edges() local_graph = graph.Graph(graph_edges) self.assertEqual(shortest_path.dijkstra(local_graph, 1, 20), [20, 21, 23, 25, 27, 29, 31, 1])
def __onclick__(self, event): threshold = 0.001 print("Clicked mouse") if self._node1 is not None and self._node2 is not None: return None if isinstance(event.artist, Line2D): thisline = event.artist xdata = thisline.get_xdata() ydata = thisline.get_ydata() ind = event.ind point = (float(np.take(xdata, ind)[0]), float(np.take(ydata, ind)[0])) node_id = self._node_map[point] if self._node1 is None: self._node1 = Node(node_id, point[0], point[1]) self._mouse_click1 = (event.mouseevent.xdata, event.mouseevent.ydata) for axes in self._main_rendering_axes: plt.sca(axes) plt.plot(self._mouse_click1[0], self._mouse_click1[1], 'ro', zorder=100) plt.draw() return self._node1 else: # Do not allow clicking of node id's within 100 node distances if abs(point[0] - self._node1.lon) < threshold and abs(point[1] - self._node1.lat) < threshold: return None self._node2 = Node(node_id, point[0], point[1]) self._mouse_click2 = (event.mouseevent.xdata, event.mouseevent.ydata) print("Both points marked") for axes in self._main_rendering_axes: plt.sca(axes) plt.plot(self._mouse_click2[0], self._mouse_click2[1], 'ro', zorder=100) plt.draw() # Now both the points have been marked. Now try to find a path. path_dijkstra, paths_considered_dijkstra = shortest_path.dijkstra(self._graph, self._node1.id, self._node2.id) path_astar, paths_considered_astar = shortest_path.astar(self._graph, self._node1.id, self._node2.id, self._osm) path_bidirectional_dijkstra, paths_considered_from_start_bidirectional_dijkstra, paths_considered_from_end_bidirectional_dijkstra = shortest_path.bidirectional_dijkstra(self._graph, self._node1.id, self._node2.id) self.plot_path(self._get_axes('dijkstra', 'main'), path_dijkstra, MatplotLibMap.renderingRules['correct_path'], animate=False) self.plot_considered_paths(self._get_axes('dijkstra', 'paths_considered'), path_dijkstra, (paths_considered_dijkstra, 'green')) self.plot_path(self._get_axes('astar', 'main'), path_astar, MatplotLibMap.renderingRules['correct_path'], animate=False) self.plot_considered_paths(self._get_axes('astar', 'paths_considered'), path_astar, (paths_considered_astar, 'green')) self.plot_path(self._get_axes('bidirectional_dijkstra', 'main'), path_bidirectional_dijkstra, MatplotLibMap.renderingRules['correct_path'], animate=False) self.plot_considered_paths(self._get_axes('bidirectional_dijkstra', 'paths_considered'), path_bidirectional_dijkstra, (paths_considered_from_start_bidirectional_dijkstra, 'green'), (paths_considered_from_end_bidirectional_dijkstra, 'red')) plt.savefig("shortest_path.png") return self._node2
def test_same_source_destination(self): """ Test that it can sum a list of integers """ factory = graph_edge_factory.VirtualEdgeFactory(distance_threshold=4) graph_edges = factory.generate_deterministic_graph_edges() local_graph = graph.Graph(graph_edges) for x in range(1, factory.number_of_nodes + 1): self.assertEqual(shortest_path.dijkstra(local_graph, x, x), [x])
def main(): # if len(sys.argv) != 5: # logging.info('please input args: car_path, road_path, cross_path, answerPath') # exit(1) # sys.argv 是获取运行python文件的时候命令行参数,且以list形式存储参数 # sys.argv[0] 代表当前module的名字 # car_path = sys.argv[1] # road_path = sys.argv[2] # cross_path = sys.argv[3] # answer_path = sys.argv[4] car_path = '../config/car.txt' road_path = '../config/road.txt' cross_path = '../config/cross.txt' answer_path = '../config/answer.txt' logging.info("car_path is %s" % (car_path)) logging.info("road_path is %s" % (road_path)) logging.info("cross_path is %s" % (cross_path)) logging.info("answer_path is %s" % (answer_path)) # to read input file carlist = read_txtdata("car", car_path) roadlist = read_txtdata("road", road_path) crosslist = read_txtdata("cross", cross_path) # buinding data to dictlist cardictlist = buinding_data("car", carlist) roaddictlist = buinding_data("road", roadlist) crossdictlist = buinding_data("cross", crosslist) # routing algorithm # traffic rules # 生成道路网络字典 roadnet_list = road_init(roaddictlist) #最短路径-Dijkstra short_path = shortest_path.dijkstra(len(crossdictlist), crosslist, roadnet_list) #计算所有车辆的最优路径 cars_path = {} for i in range(len(cardictlist)): fromid = str(int(cardictlist[i]['fromid'])) toid = str(int(cardictlist[i]['toid'])) path = fromid + '->' + toid temp_list = [] temp_list.append(int(cardictlist[i]['speed'])) temp_list.append(int(cardictlist[i]['plantime'])) car_path = str(int(cardictlist[i]['carid'])) + ':' + path cars_path[car_path] = short_path[path] + temp_list # 车辆按交通规则出发,分配交通流 # 按照时间片进行分配 roadnet_list = go_path.cars_go_path(roadnet_list, cars_path) print(roadnet_list)
def local_knowledge_algorithm(graph_edges: list, number_of_source_destination_pairs: int, propagation_radius: int = 0, exponential_scale: bool = True): """ Runs the local knowledge algorithm specified by a propagation radius. The local knowledge of nodes about the virtual links used within a path is updated within a specified propagation radius. Parameters ---------- graph_edges: list The graph edges to be added as local knowledge to the vertices of the graph. number_of_source_destination_pairs: int Specifies the number of demands that need to be generated. propagation_radius: int Index of the end vertex, towards which we are looking for the shortest path. exponential_scale: bool Specifies whether long link creation scales exponentially or polynomially with time. """ # Generate the specific graph object main_graph = create_graph_with_local_knowledge(graph_edges) result_for_source_destination = [] for x in range(1, number_of_source_destination_pairs + 1): temp_result: tuple = () simulation_settings = routing_simulation.Settings() source = random.randint(1, simulation_settings.number_of_nodes) dest = random.randint(1, simulation_settings.number_of_nodes) while source == dest: dest = random.randint(1, simulation_settings.number_of_nodes) # Initialize path # Determine shortest path based on local knowledge current_path = shortest_path.dijkstra(main_graph.vertices[source].local_knowledge, source, dest) current_distance = len(current_path)-1 temp_result += (distribute_entanglement(main_graph, current_path, exponential_scale),) # Update local knowledge of the nodes that are along the current path update_local_knowledge(main_graph, current_path, propagation_radius) temp_result += (main_graph.get_sum_of_link_capacities(),) temp_result += (main_graph.get_available_link_count(),) temp_result += (current_distance,) result_for_source_destination.append(temp_result) return helper.map_tuple_gen(np.mean, zip(*result_for_source_destination))
def report_shortest_path(self): targets = set() for f, t, _ in self.edges: targets.add(f) targets.add(t) targets.remove(self.name) print("I am Router {}".format(self.name)) for t in targets: dist, path = dijkstra(self.edges, self.name, t) print("Least cost path to router {}: {} and the cost is {}".format( t, ''.join(path), round(dist, 1)))
def get_features(state, action): state_copy = copy.deepcopy(state) features = util.Counter() # features["bias"] = 0.1 # features["num_steps"] = 1.0 / (len(self.history)+1.0) # features["action_type"] = 1.0 # next_state is after predict "*** YOUR CODE HERE ***" next_state = virtual_sense(state_copy, action) features["to_explored"] = (next_state.num_explored - state_copy.num_explored) / 20.0 # features["num_unexplored_inverse"] = 1.0 / (301.0 - next_state.num_explored) # 301 is set to avoid devide by zero # features["num_unexplored_normalized"] = next_state.num_explored/300.0 # features["closest_unexplored"] = 1.0 / self.closest_unexplored(next_state, 10) # trap if features["to_explored"] > 0: features["closest_unexplored_inverse"] = 1.0 else: closest_unexplored = dijkstra(next_state) features["closest_unexplored_inverse"] = 1.0 / (closest_unexplored) # features["closest_unexplored"] = closest_unexplored / 5.0 # don't use this # features["x"] = state.x / 20.0 # features["y"] = state.y / 15.0 # encourage right hugging # features["right_hugging"] = 0 # if action == Actions.FORWARD: # features["right_hugging"] = int(state.history[-1:] == [Actions.TURN_RIGHT]) # features["u_turn"] = 0 # features["back"] = 0 # if action == Actions.U_TURN: # features["u_turn"] = 1 # if action == Actions.TURN_LEFT: # if state.history[-1:] == [Actions.TURN_LEFT]: # features["u_turn"] = 1 # if state.history[-1:] == [Actions.TURN_RIGHT]: # features["back"] = 1 # if action == Actions.TURN_RIGHT: # if state.history[-1:] == [Actions.TURN_RIGHT]: # features["u_turn"] = 1 # if state.history[-1:] == [Actions.TURN_LEFT]: # features["back"] = 1 print(state.x, state.y, state.direction, action, features) return features
def test_dth8_long_links_path(self): """ Test that it can sum a list of integers """ factory = graph_edge_factory.VirtualEdgeFactory(distance_threshold=8) graph_edges = factory.generate_deterministic_graph_edges() local_graph = graph.Graph(graph_edges) # self.assertEqual(shortest_path.dijkstra(local_graph, 1, 17), [17, 13, 9, 5, 1]) self.assertEqual(shortest_path.dijkstra(local_graph, 1, 19), [19, 17, 9, 1]) self.assertEqual(shortest_path.dijkstra(local_graph, 19, 1), [1, 9, 17, 19]) self.assertEqual(shortest_path.dijkstra(local_graph, 1, 18), [18, 17, 9, 1]) self.assertEqual(shortest_path.dijkstra(local_graph, 18, 1), [1, 9, 17, 18]) self.assertEqual(shortest_path.dijkstra(local_graph, 1, 16), [16, 17, 9, 1]) self.assertEqual(shortest_path.dijkstra(local_graph, 1, 15), [15, 17, 9, 1]) self.assertEqual(shortest_path.dijkstra(local_graph, 1, 14), [14, 13, 9, 1])
def global_knowledge_algorithm(main_graph, number_of_source_destination_pairs: int, exponential_scale: bool = True) -> list: """ Applies the global knowledge approach for a certain graph by generating a specific number of demands. Parameters ---------- main_graph : Graph The graph in which we serve the demands according to the global knowledge approach. number_of_source_destination_pairs: int Specifies the number of demands that need to be generated. exponential_scale: bool Specifies whether long link creation scales exponentially or polynomially with time. Notes ---------- Add the data (measures) in the following order: (1) The waiting time (2) Number of available virtual links (3) Number of available edges (4) Distance of the path """ result_for_source_destination = [] number_of_nodes = routing_simulation.Settings().number_of_nodes for x in range(1, number_of_source_destination_pairs + 1): temp_result = () source, dest = generate_random_source_destination(number_of_nodes) # Initialize path # The change in network is considered in this approach (path is UPDATED) current_path = shortest_path.dijkstra(main_graph, source, dest) temp_result += (distribute_entanglement(main_graph, current_path, exponential_scale),) temp_result += (main_graph.get_sum_of_link_capacities(),) temp_result += (main_graph.get_available_link_count(),) temp_result += (len(current_path)-1,) result_for_source_destination.append(temp_result) return result_for_source_destination
def main(): graph, osm = read_osm(sys.argv[1]) print(osm.bounds) if len(sys.argv) > 2: if sys.argv[2] == 'renderer': path, _ = shortest_path.dijkstra(graph, '1081079917', '65501510') points = get_points_from_node_ids(osm, path) minX = float(osm.bounds['minlon']) maxX = float(osm.bounds['maxlon']) minY = float(osm.bounds['minlat']) maxY = float(osm.bounds['maxlat']) road_vbos, other_vbos = get_vbo(osm) c = Canvas(road_vbos, other_vbos, [minX, minY, maxX, maxY], scale=100) # c.measure_fps() # c = Canvas([([[0.0, 0.0, 0.0],[0.5, 0.5, 0.0],[2.0,0.0,0.0],[0.0,0.0,0.0]], (0.0, 0.0, 0.0))], [-1.0, -1.0, 1.0, 1.0], scale=1) app.run() else: # path, _ = shortest_path.bidirectional_dijkstra(graph, '1081079917', '65501510') matplotmap = MatplotLibMap(osm, graph)
def test_always_same_as_nx(self): factory = graph_edge_factory.VirtualEdgeFactory(distance_threshold=2, max_distance_threshold=16) graph_edges = factory.generate_deterministic_graph_edges() local_graph = graph.Graph(graph_edges) nx_graph = nx.Graph() for x in graph_edges: nx_graph.add_edge(x[0], x[1]) for x in range(1, factory.number_of_nodes + 1): for y in range(1, factory.number_of_nodes + 1): if x != y: shortest_path1 = shortest_path.dijkstra(local_graph, x, y) shortest_path2 = nx.shortest_path(nx_graph, x, y) self.assertEqual(len(shortest_path1), len(shortest_path2)) self.assertTrue(shortest_path1[0] == y) self.assertTrue(shortest_path1[len(shortest_path1)-1] == x) index = 0 for node in shortest_path1: self.assertEqual(node, shortest_path1[index]) index += 1 if index == len(shortest_path1)-2: self.assertTrue(shortest_path1[index+1] in nx.neighbors(nx_graph, shortest_path1[index]))
joint graph, size (n^2-n,2,2), where the second axis is the two agents and the third axis is coordinates """ # TODO joint_graph = nodes = None return joint_graph, nodes if __name__ == '__main__': print("python main function") graph = 0.05 * np.eye(7) graph[0, 1] = 3 graph[0, 2] = 2 graph[1, 3] = 1 graph[2, 3] = 3 graph[3, 4] = 3 graph[3, 5] = 1 graph[4, 6] = 2 graph[0, 0] = 0.01 graph = graph + graph.T nodes = np.array([[0., 0.], [1., 1.], [1., -1.], [2., 0.], [3., 1.], [3., -1.], [4., 0.]]) num_nodes = 7 obstruction = [6, 4, 3, 1, 0] sp = [0, 0, 1, 3, 4, 6] # sp = [0, 0, 2, 3, 4, 6] graph, nodes = time_expand(graph, nodes, obstruction) path = dijkstra(graph, 0, nodes.shape[0] - 1) print[node % num_nodes for node in path]
def test_dijkstra_short_cut(populated_graph2): """Test a graph to see if it takes a low weight shortcut""" dist = dijkstra(populated_graph2, 'a', 'e') assert dist == 12
def test_dth4_long_links_path(self): """ Test that it can sum a list of integers """ factory = graph_edge_factory.VirtualEdgeFactory( distance_threshold=4, max_distance_threshold=4) graph_edges = factory.generate_deterministic_graph_edges() local_graph = graph.Graph(graph_edges) # self.assertEqual(shortest_path.dijkstra(local_graph, 1, 17), [17, 13, 9, 5, 1]) self.assertEqual(shortest_path.dijkstra(local_graph, 1, 27), [27, 29, 1]) self.assertEqual(shortest_path.dijkstra(local_graph, 1, 26), [26, 27, 29, 1]) self.assertEqual(shortest_path.dijkstra(local_graph, 1, 25), [25, 29, 1]) self.assertEqual(shortest_path.dijkstra(local_graph, 1, 24), [24, 25, 29, 1]) self.assertEqual(shortest_path.dijkstra(local_graph, 1, 23), [23, 25, 29, 1]) self.assertEqual(shortest_path.dijkstra(local_graph, 1, 22), [22, 23, 25, 29, 1]) self.assertEqual(shortest_path.dijkstra(local_graph, 1, 21), [21, 25, 29, 1]) self.assertEqual(shortest_path.dijkstra(local_graph, 1, 20), [20, 21, 25, 29, 1]) self.assertEqual(shortest_path.dijkstra(local_graph, 1, 19), [19, 21, 25, 29, 1]) self.assertEqual(shortest_path.dijkstra(local_graph, 1, 18), [18, 17, 13, 9, 5, 1]) self.assertEqual(shortest_path.dijkstra(local_graph, 16, 1), [1, 29, 25, 21, 17, 16]) self.assertEqual(shortest_path.dijkstra(local_graph, 1, 17), [17, 13, 9, 5, 1]) self.assertEqual(shortest_path.dijkstra(local_graph, 1, 16), [16, 17, 13, 9, 5, 1]) self.assertEqual(shortest_path.dijkstra(local_graph, 1, 15), [15, 13, 9, 5, 1]) self.assertEqual(shortest_path.dijkstra(local_graph, 1, 14), [14, 13, 9, 5, 1])
def test_dijkstra_long_path(populated_graph1): """Test a graph with a shortest path with more nodes than longer path""" dist = dijkstra(populated_graph1, 'a', 'e') assert dist == 6
def test_dijkstra_no_path(no_path_graph): """Tests a graph where start and end do not connect""" dist = dijkstra(no_path_graph, 'a', 'b') assert dist == float('inf')