def main(): # validate the params if len(sys.argv) != 2: print("Usage: python3 main.py <NETWORK_FILE>") sys.exit(-1) # read in the network from file net = network.readFromFile(sys.argv[1]) # create the problem model model = problem.Problem(net) # search using BFS bfsSearcher = bfs.BFS(model) bfsSearcher.search() # search using dijkstra dijkstraSearcher = dijkstra.Dijkstra(model) dijkstraSearcher.search() # search using A* astarSearcher = astar.AStar(model) astarSearcher.search() # search using beam search beamSearcher = beams.Beams(model) beamSearcher.search() # search using Iterative Deepening idSearcher = iterativedeepening.IterDeep(model) idSearcher.search()
def test_dijkstra(): graph = { 'a': { 'b': 3, 'd': 7 }, 'b': { 'a': 3, 'd': 2, 'c': 4 }, 'c': { 'b': 4, 'd': 5, 'e': 6 }, 'd': { 'a': 7, 'b': 2, 'c': 5, 'e': 4 }, 'e': { 'c': 6, 'd': 4 } } parent, distance = dijkstra.Dijkstra(graph, 'a') assert distance['a'] == 0 assert distance['b'] == 3 assert distance['c'] == 7 assert distance['d'] == 5 assert distance['e'] == 9
def search_CARP(file_name, limited_time, ram_seed): """ :param file_name: 文件名 :param limited_time: 限制时间 :param ram_seed: 随机种子 :return: None,标准打印 """ start = time.time() sample = read_data(file_name) vehicles = sample[5] capacity = sample[6] random.seed(ram_seed) # print sample # print_head(sample) free = free_edge_set(sample) # print free vertex = matrix_tran(sample) vertex_dij = dij.Dijkstra(vertex) # vertex_dij.print_graph() group = Population(200, 600, vertex_dij) group.initial(2000, free, vertex_dij, vehicles, capacity) group.select() # group.top_best(3) run_time = (time.time() - start) count = 1 end_time = limited_time - 1.5 while run_time <= end_time: # print "\nLOOP: {}".format(count) if group.check_mature(): rule_num = random.randint(4, 5) # print "-----------resize-----------" group.resize(5) group.mature_reset() else: rule_num = random.randint(1, 5) group.mature_reset() # rule_num = random.randint(1, 5) group.generate(rule_num, vehicles, capacity) group.select() # group.top_best(5) run_time = (time.time() - start) # print "LOOP: {} TIME: {}s RULE: {}".format(count, run_time, rule_num) count += 1 run_time = (time.time() - start) # print "\nTIME: {}s".format(run_time) group.print_result()
def find_shortest_connection(self, stop1, stop2): if not self.dijkstra: self.dijkstra = dijkstra.Dijkstra(self) min_travel_time, min_connections_path = self.dijkstra.min_path(stop1, stop2) if not min_connections_path: print("Brak połączenia pomiędzy przystankami....") return (None, None) else: shortest_connection = [ str(conn.start_stop()) + "(" + str(conn.line_number()) + ")" for conn in min_connections_path] shortest_connection.append(str(min_connections_path[-1].end_stop())) return (min_travel_time, shortest_connection)
def find_min_path(self, v1, v2): """ Metoda znajdująca najkrótszą scieżkę (o najniższym koszcie) pomiędzy wierzchołkami v1 i v2 grafu. """ if not self.dijkstra: self.dijkstra = dijkstra.Dijkstra(self) min_path_cost, min_path_edges = self.dijkstra.min_path(v1, v2) if not min_path_edges: print("Brak połączenia pomiędzy wierzchołkami...") return (None, None) else: min_path = [edge.source() for edge in min_path_edges] min_path.append(min_path_edges[-1].target()) return (min_path_cost, min_path)
def setUp(self): self.graph = Graph() self.graph.add_vertex(Vertex("a")) self.graph.add_vertex(Vertex("b")) self.graph.add_vertex(Vertex("c")) self.graph.add_vertex(Vertex("d")) self.graph.add_vertex(Vertex("e")) self.graph.add_vertex(Vertex("f")) self.graph.add_undirected_edge(Vertex("a"), Vertex("b"), 2) self.graph.add_undirected_edge(Vertex("a"), Vertex("e"), 3) self.graph.add_undirected_edge(Vertex("b"), Vertex("e"), 2) self.graph.add_undirected_edge(Vertex("b"), Vertex("c"), 1) self.graph.add_undirected_edge(Vertex("c"), Vertex("d"), 2) self.graph.add_undirected_edge(Vertex("d"), Vertex("e"), 3) self.graph.add_undirected_edge(Vertex("d"), Vertex("f"), 4) self.dijkstra = dijkstra.Dijkstra(self.graph)
def computeUtil(no_graphs, no_src_dest,no_verts,degree): dij_times = [] dij_heap_times = [] kruskal_times = [] for i in range(no_graphs): print "="*25 + " Graph "+str(i+1)+" "+"="*25 print "============= Vertices = "+str(no_verts)+ " Degree = "+str(degree)+" ==============" print "="*59+"\n" graph, vertex = generate_graph.generate(no_verts,degree) for j in range(no_src_dest): src = random.randint(1,no_verts-1) dest = random.randint(1,no_verts-1) print "="*40 while(dest == src or dest == src + 1 or dest == src-1): dest = random.randint(1,no_verts-1) dij = dijkstra.Dijkstra(graph,vertex,src,dest) report1 = dij.dijkstra() dij_times.append(float(report1[1].split(' ')[0])) del dij print report1[:-1],"\n" dij_heap = dijkstra_heap.DijkstraHeap(graph,vertex,src,dest) report2 = dij_heap.dijkstra() dij_heap_times.append(float(report2[1].split(' ')[0])) del dij_heap print report2[:-1],"\n" krus = kruskals.Kruskals(graph,vertex,src,dest) report3 = krus.findPath() kruskal_times.append(float(report3[1].split(' ')[0])) del krus print report3[:-1],"\n" print "====== Average Times ======" print "Dijkstra without heap: ",sum(dij_times)/len(dij_times), " seconds" print "Dijkstra with heap : ",sum(dij_heap_times)/len(dij_heap_times), " seconds" print "Kruskals : ",sum(kruskal_times)/len(kruskal_times), " seconds"
def phase1(): img = Image.open('maze.png') data = list(img.getdata()) start = 639, 0 end = 1, 640 g = G(data, img.size) print('Dijkstra...') D, P = dijkstra.Dijkstra(g, start, end) # Construct path from P; add color values in the same pass print('Constructing path...') path = [] pos = end while True: x, y = pos path.append((pos, data[x + img.size[0] * y][0])) if pos == start: break pos = P[pos] path.reverse() # Save the sequence to file, so we can study it without having to # recalculate it again and again pickle.dump(path, open('maze.sequence', 'wb')) print('path pickled as maze.sequence')
def traverse_graph(self): # Creating new graph traverser if self.rbSelectedValue.get() == "DFS": if self.dfs_query == "yes": self.graph_traverser = dfs_iterative.DFSIterative(self.grp) else: self.graph_traverser = dfs_recursive.DFSRecursive(self.grp) elif self.rbSelectedValue.get() == "BFS": self.graph_traverser = bfs.BFS(self.grp) elif self.rbSelectedValue.get() == "Dijkstra": self.graph_traverser = dijkstra.Dijkstra(self.grp, None) elif self.rbSelectedValue.get() == "Astar": self.graph_traverser = astar.AStar(self.grp, self.rb_heuristic_value.get()) # Traversing the graph and getting traverse node path self.traverse_time_start = time.time() self.path, self.steps = self.graph_traverser.traverse() if self.path == []: tkMessageBox.showerror("Error", "Graph traversing failed") self.traverse_time_end = time.time()
import numpy as np #import draw import dijkstra d = dijkstra.Dijkstra(50, (1, 1), (30, 20), 0, [(2, 2), (2, 3),(20,10),(15,7)]) d.search() print(d.routeHeight)
import dijkstra graph = dict() graph['start'] = {} graph['start']['a'] = 6 graph['start']['b'] = 2 graph['a'] = {} graph['a']['fin'] = 1 graph['b'] = {} graph['b']['a'] = 3 graph['b']['fin'] = 5 graph['fin'] = {} infinity = float('inf') costs = dict() costs['a'] = 6 costs['b'] = 2 costs['fin'] = infinity parents = dict() parents['a'] = 'start' parents['b'] = 'start' parents['fin'] = None run = dijkstra.Dijkstra(graph, costs, parents) print(run.get_path()) print(run.get_path_str()) print(run.get_length())
def query(self, city1="", city2="", scale=0): rsp = {} if city1 == city2: rsp["error"] = "src_city must be different with tgt_city" return rsp #兼容处理 if city1.isdigit(): cityid1 = city1 cityid2 = city2 if cityid1 not in self.id_city_map2: rsp["error"] = "cannot find cityid:{0}".format(cityid1) return rsp if cityid2 not in self.id_city_map2: rsp["error"] = "cannot find cityid:{0}".format(cityid2) return rsp city1 = self.id_city_map2[cityid1] city2 = self.id_city_map2[cityid2] if city1 not in self.city_id_map: logger.debug( "queryrequest c1x:{0} c2:{1} >canot find city ".format( city1, city2)) rsp["error"] = "cannot find city:{0}".format(city1) return rsp if city2 not in self.city_id_map: logger.debug( "queryrequest c1:{0} c2x:{1} >canot find city ".format( city1, city2)) rsp["error"] = "cannot find city:{0}".format(city2) return rsp cityid1 = self.city_id_map[city1] cityid2 = self.city_id_map[city2] cityidrange = self.get_cityidrange(cityid1, cityid2) citynamerange = [self.id_city_map[x] for x in cityidrange] logger.debug( "queryrequest,from {0} to {1},cid:{2} > {3} range:{4}".format( city1, city2, cityid1, cityid2, citynamerange)) neighbours = [] if scale > 0: ylist = self.distance_mat[cityid2] for i in range(len(ylist)): if ylist[i] <= scale * 1000: neighbours.append((self.id_city_map[i], ylist[i])) neighbours = sorted(neighbours, key=lambda x: x[1]) neighbours2 = [item[0] for item in neighbours if item[0] != city2] if len(cityidrange) <= 2: logger.debug( "len(cityidrange) <=2: cityidrange:{0}".format(cityidrange)) rsp["from2"] = city1 rsp["to2"] = city2 rsp["distance"] = self.distane(city1, city2) rsp["pass2"] = [] rsp["pass"] = [] rsp["from"] = self.city_id_map2[city1] rsp["to"] = self.city_id_map2[city2] rsp["neighbours2"] = neighbours2 rsp["neighbours"] = [self.city_id_map2[k] for k in neighbours2] return rsp smallworld = self.create_smallworld(cityid1, cityid2, cityidrange) # for k,v in smallworld.items(): # print(k,v) # print(">>>dijkstra...",len(smallworld)) dis, paths = dijkstra.Dijkstra(smallworld, cityid1) # print(">>>dijkstra222...") result = {} for k, plist in paths.items(): c = self.id_city_map[k] result[c] = {} result[c]["from2"] = city1 result[c]["to2"] = city2 result[c]["distance"] = dis[k] result[c]["pass2"] = [self.id_city_map[k] for k in plist] result[c]["pass"] = [ self.city_id_map2[self.id_city_map[k]] for k in plist ] result[c]["from"] = self.city_id_map2[city1] result[c]["to"] = self.city_id_map2[city2] result[c]["neighbours2"] = neighbours2 result[c]["neighbours"] = [ self.city_id_map2[k] for k in neighbours2 ] if city2 not in result: rsp["error"] = "city:{0},process error".format(city2) # print(result) return rsp rsp = result[city2] return rsp
def min_dpa(N, d, l, d0): r = math.sqrt((d * l * l) / (math.pi * (N - 1))) connected = False while not connected: # graph construction initial step: create first node randomly x = random.random() * l y = random.random() * l p = [[x, y]] S = ['node_1'] # for the next rounds (>= 2nd round) for k in range(2, N): degrees = calculate_approximate_degrees(S, p, r) #of all nodes in Sk-1 L = min(degrees) # min of approximate degrees weight = [0] * len(S) # for each node m in Sk-1 that has degree L do: for m, node in enumerate(S): if degrees[m] == L: if disk_belongs_square_area(p[m], r, l): weight[m] = 1 else: weight[m] = 2. / 3 # C(xc,yc) = randomize_center_select(weight) i = weighted_choice(weight) xc = p[i][0] yc = p[i][1] accepted = False while not accepted: v = random.random() * (r**2) a = math.sqrt(v) theta = random.random() * (2 * math.pi) xz = xc + a * math.cos(theta) yz = yc + a * math.sin(theta) if not point_belongs_square_area([xz, yz], l): print "New point not accepted: outside square region" elif not proximity_test([xz, yz], p, d0): print "New point not accepted: failed proximity test" else: p.append([xz, yz]) S.append('node_' + str(k)) accepted = True # Calculate edge lenghts lij = norm(pi,pj) edge_ij = [] for i in range(0, len(S)): for j in range(i + 1, len(S)): edge_ij.append( math.sqrt( math.pow((p[i][0] - p[j][0]), 2) + math.pow((p[i][1] - p[j][1]), 2))) # Sort lij i,j in {1,2,..., N} edge_ij.sort() # Select ((N*d)/2) shortest (to determine the actual transmition radius of the graph) try: graph_transmition_radius = edge_ij.pop((N * d) / 2) # Form candidate graph Gc with ((N*d)/2) edges graph = form_candidate_graph(S, p, graph_transmition_radius) # Run Dijkstra for Gc Distances, Predecessors = dijkstra.Dijkstra(graph, S[0]) # if all costs finite the connected will be True for i in graph: for j in graph[i]: if graph[i][j] != numpy.inf: connected = True else: connected = False except IndexError: print "Approximate degrees to high for the number of total nodes!" S = [] p = [] graph = {} return S, p, graph return S, p, graph
def dijkstra_map(board, start, end, test=is_nonwall): "Run Dijkstra's algorithm and return the distance map." d, p = dijkstra.Dijkstra(DijkstraGraph(board, test), start, end) return d
#!/usr/bin/python ##import setup_readfile as setup import dijkstra ##import setup_png as png if __name__ == '__main__': d = dijkstra.Dijkstra() d.set_gpu(True) width = 8 height = 8 startx = 4 starty = 0 endx = 7 endy = 6 WALL = 100 maze = [0] * (width * height) dist = [0] * (width * height) prev = [0] * (width * height) visited = [0] * (width * height) onethird = int(height / 3) twothirds = int(height * 2 / 3) for i in range(0, 6): #(0,7) maze[(onethird * width) + i] = WALL for i in range(4, width):
def __init__(self, player_pos): self.field, self.edge = self.GetInitialField() self.dijk = dijkstra.Dijkstra(self.edge) self.pos = [7, 7] self.player_pos = player_pos[:]