def test_astar_undirected2(self): XG3 = nx.Graph() edges = [(0, 1, 2), (1, 2, 12), (2, 3, 1), (3, 4, 5), (4, 5, 1), (5, 0, 10)] XG3.add_weighted_edges_from(edges) assert_equal(nx.astar_path(XG3, 0, 3), [0, 1, 2, 3]) assert_equal(nx.astar_path_length(XG3, 0, 3), 15)
def test_astar_w1(self): G = nx.DiGraph() G.add_edges_from([('s', 'u'), ('s', 'x'), ('u', 'v'), ('u', 'x'), ('v', 'y'), ('x', 'u'), ('x', 'w'), ('w', 'v'), ('x', 'y'), ('y', 's'), ('y', 'v')]) assert_equal(nx.astar_path(G, 's', 'v'), ['s', 'u', 'v']) assert_equal(nx.astar_path_length(G, 's', 'v'), 2)
def hyperEmbed(g): locs = {x: randomPoint() for x in g.nodes()} rev_locs = {locs[x]: x for x in locs.keys()} MAX_iter = 100 for i in range(0, MAX_iter): print(i) overlay = HyperfastDGVH(rev_locs.keys()) newlocs = {} for p in g.nodes(): ploc = locs[p] force = [0.0, 0.0] total_hDist = 0.0 total_realdist = 0.0 weight = 0.0 for locq in overlay.nodes(): q = rev_locs[locq] if p == q: continue qloc = locs[q] dist = hDist(ploc, qloc) ideal_dist = nx.astar_path_length(g, p, q) * 0.5 w = eDist((0, 0), qloc) delta_f = (ideal_dist - dist) * 0.1 * ( 1.0 - float(i) / MAX_iter) * w weight += w force[0] -= (qloc[0] - ploc[0]) * delta_f force[1] -= (qloc[1] - ploc[1]) * delta_f force[0] /= weight force[1] /= weight newlocs[p] = hyperDelta(ploc, force) locs = newlocs rev_locs = {locs[x]: x for x in locs.keys()} print(isGreedy(HyperfastDGVH(rev_locs.keys()), hDist)) return locs
def total_exit_time(graph, start_points_list, exit_points_list): """ Calculates the total exit time as the longest time it takes any soldier to reach the exit Satisfies TB033 """ ## Initialize to impossible value max_exit_time = -1.0 for p_i in start_points_list: assert p_i in graph, "Specified start point not walkable" for p_e in exit_points_list: assert p_e in graph, "Specified exit point not walkable" try: dist_to_exit = nx.astar_path_length(graph, source=p_i, target=p_e, weight='weight', heuristic=a_star_heuristic) max_exit_time = max(max_exit_time, dist_to_exit) except (KeyError, nx.NetworkXNoPath): # If points are in graph but no path exists, log a message logging.info("No path found between voxel indices {} and {}".format(p_i, p_e)) if max_exit_time == -1.0: raise ValueError("No exit paths were found") return max_exit_time
def test_astar_undirected3(self): XG4 = nx.Graph() edges = [(0, 1, 2), (1, 2, 2), (2, 3, 1), (3, 4, 1), (4, 5, 1), (5, 6, 1), (6, 7, 1), (7, 0, 1)] XG4.add_weighted_edges_from(edges) assert_equal(nx.astar_path(XG4, 0, 2), [0, 1, 2]) assert_equal(nx.astar_path_length(XG4, 0, 2), 4)
def test_astar_undirected(self): GG = self.XG.to_undirected() # make sure we get lower weight # to_undirected might choose either edge with weight 2 or weight 3 GG["u"]["x"]["weight"] = 2 GG["y"]["v"]["weight"] = 2 assert_equal(nx.astar_path(GG, "s", "v"), ["s", "x", "u", "v"]) assert_equal(nx.astar_path_length(GG, "s", "v"), 8)
def test_astar_undirected(self): GG = self.XG.to_undirected() # make sure we get lower weight # to_undirected might choose either edge with weight 2 or weight 3 GG['u']['x']['weight'] = 2 GG['y']['v']['weight'] = 2 assert_equal(nx.astar_path(GG, 's', 'v'), ['s', 'x', 'u', 'v']) assert_equal(nx.astar_path_length(GG, 's', 'v'), 8)
def BA_sp(m, N_range): number_of_trials = 100 #D=1 myfile = open('BA_shortest_path', 'w') myfile.write('N' + '\t' + 'average shortest path'+ '\t'+'std err'+'\n') for N in N_range: sp_list = [] comparison_sp_list = [] for trial in range(number_of_trials): model = models.barabasi_albert_graph(N,m) # model = models.box_model(D, N) G = model[0] extremes = model[1] #tr_DAG = tr.trans_red(G) sp_length = nx.astar_path_length(G, extremes[1], extremes[0]) # sp_length = sp_list.append(sp_length) average_in_degree = float(m)*float((N-1))/(float(N)) comparison_model = oneD_random_comparison(N,average_in_degree) comparison_G = comparison_model[0] comparison_extremes = comparison_model[1] if nx.has_path(comparison_G, comparison_extremes[1], comparison_extremes[0]): comparison_sp_length = nx.astar_path_length(comparison_G, comparison_extremes[1], comparison_extremes[0]) # comparison_sp_length = comparison_sp[2] else: comparison_sp_length=0 comparison_sp_list.append(comparison_sp_length) statistics = stats.list_stats(sp_list) sp_av = statistics[3] sp_std_err = statistics[0] comparison_stats = stats.list_stats(comparison_sp_list) comparison_sp_av = comparison_stats[3] comparison_sp_std_err = comparison_stats[0] print "done ", N myfile.write(str(N) + '\t' + str(sp_av) + '\t' + str(sp_std_err) + '\t' + str(N) + '\t' + str(comparison_sp_av) + '\t' + str(comparison_sp_std_err) + '\n') return
def findMaxScorePath(CandidateNodesList,SelectNodesGraph, i): CanPath = [] for j in CandidateNodesList[i[0]]: for k in CandidateNodesList[i[-1]]: CanPath.append((nx.astar_path(SelectNodesGraph,j,k),nx.astar_path_length(SelectNodesGraph,j,k))) MaxScore = min([j[1] for j in CanPath]) for j in CanPath: if MaxScore==j[1]: MaxScorePath = j[0] return MaxScorePath
def test_astar_undirected2(self): XG3=nx.Graph() XG3.add_edges_from([ [0,1,{'weight':2}], [1,2,{'weight':12}], [2,3,{'weight':1}], [3,4,{'weight':5}], [4,5,{'weight':1}], [5,0,{'weight':10}] ]) assert nx.astar_path(XG3,0,3)==[0, 1, 2, 3] assert nx.astar_path_length(XG3,0,3)==15
def closestStation(self, graph, node): #Returns the closest station and the distance from it if (len(self.stations) == 0): return 0,999999 bestDistance = 99999999 bestStation = self.stations[0] for station in self.stations: dist = nx.astar_path_length(graph,station,node) if (dist == 0): return node, 1 if (dist < bestDistance): bestDistance = dist bestStation = station return bestStation, bestDistance
def test_astar_undirected3(self): XG4=nx.Graph() XG4.add_edges_from([ [0,1,{'weight':2}], [1,2,{'weight':2}], [2,3,{'weight':1}], [3,4,{'weight':1}], [4,5,{'weight':1}], [5,6,{'weight':1}], [6,7,{'weight':1}], [7,0,{'weight':1}] ]) assert nx.astar_path(XG4,0,2)==[0, 1, 2] assert nx.astar_path_length(XG4,0,2)==4
def pathadddistance(patharray,GGG): #global allnodedist for p in patharray: nodepeer = zip(p[::1], p[1::1]) #参考高手的代码。将list的元素两两一组,重叠组成tuple。下面也有同样代码,最后的数字是2。 ttlong = 0 #累加路径长度。 for np in nodepeer: dd = 0 #缓存清零。保证数值方便排障。 dd = nx.astar_path_length(GGG,np[0],np[1])#各个算法都尝试过了,结果一致。再观察。 #dd = nx.dijkstra_path_length(GGG,np[0],np[1]) #dd = allnodedist[np[0]][np[1]] #路径上每2个节点间的最短距离。其实不是最短距离,这个全局变量给点值很疑惑。 ttlong += dd #在节点直连字典中查找两点之间的距离,并累加。 p.insert(p.index(np[1]),dd) #在路径上每两个节点之间插入距离数值。 p.append(ttlong) return patharray
def test_astar_w1(self): G = nx.DiGraph() G.add_edges_from( [ ("s", "u"), ("s", "x"), ("u", "v"), ("u", "x"), ("v", "y"), ("x", "u"), ("x", "w"), ("w", "v"), ("x", "y"), ("y", "s"), ("y", "v"), ] ) assert nx.astar_path(G, "s", "v") == ["s", "u", "v"] assert nx.astar_path_length(G, "s", "v") == 2
def getPairwiseDistanceWithinGraphOfChosenMonkey(self, graph=None, chosenMonkeyIDDict=None): """ 2012.11.27 """ sys.stderr.write("Getting list of pairwise distance of all pairs in graph for %s chosen monkeys ..."%\ (len(chosenMonkeyIDDict))) distance_ls = [] chosenMonkeyIDList = list(chosenMonkeyIDDict) for i in xrange(len(chosenMonkeyIDList)): monkey1ID = chosenMonkeyIDList[i] for j in xrange(i+1, len(chosenMonkeyIDList)): monkey2ID = chosenMonkeyIDList[j] try: distance = nx.astar_path_length(graph, source=monkey1ID, target=monkey2ID, weight='weight') except: distance = -5 distance_ls.append(distance) #distance_ls.append(lengthStructure[monkey1ID][monkey2ID]) sys.stderr.write("%s pairs .\n"%(len(distance_ls))) return distance_ls
def updateNewMonkeyToChosenSetDistanceVector(self, graph=None, oldShortestDistanceVectorData=None, \ newlyChosenMonkeyID=None, minShortestDistance=0.4): """ 2012.11.26 supplement to constructNewMonkeyToChosenSetDistanceVector() """ oldShortestDistanceToChosenSet_monkeyID_ls = oldShortestDistanceVectorData.shortestDistanceToChosenSet_monkeyID_ls sys.stderr.write("Updating the shortest-distance to chosen set vector (%s elements) because monkeys %s has been added into the chosen set ..."%\ (len(oldShortestDistanceToChosenSet_monkeyID_ls), newlyChosenMonkeyID)) returnData = PassingData(shortestDistanceToChosenSet_monkeyID_ls = []) counter = 0 real_counter = 0 spanStartPos = 0 monkey2ID = newlyChosenMonkeyID for element in oldShortestDistanceToChosenSet_monkeyID_ls: shortestDistance, monkey1ID, shortestDistanceToThisChosenMonkey = element[:3] if monkey1ID!=monkey2ID: #skip the chosen monkey counter += 1 #get the shortest path #short path in graph, sum all the edge weights, A* star algorithm seems to be much faster (>100%) than default shortest_path. #distance = nx.shortest_path_length(graph, source=monkey1ID, target=monkey2ID, weight='weight') distance = nx.astar_path_length(graph, source=monkey1ID, target=monkey2ID, weight='weight') if distance<shortestDistance: shortestDistance = distance shortestDistanceToThisChosenMonkey = monkey2ID element = (shortestDistance, monkey1ID, shortestDistanceToThisChosenMonkey) real_counter += 1 if shortestDistance>=minShortestDistance: returnData.shortestDistanceToChosenSet_monkeyID_ls.append(element) spanStartPos += shortestDistance #increase the distance. returnData.totalDistance = spanStartPos sys.stderr.write("%s (out of %s) monkeys changed their shortest distance to the chosen set (%s elements). \n\ total distance to the chosen set is %s.\n"%\ (real_counter, counter, len(returnData.shortestDistanceToChosenSet_monkeyID_ls), spanStartPos)) return returnData
def simulate_random_walk (G, damping, max_jumps): """ Random walk simulation on weighted graph G with damping factor d and max_jumps as maximum number of jumps""" results = [] nodes = [] # keep nodes current_node = random.randrange(N) while not G.has_node(current_node): current_node = random.randrange(N) j = 0 while (j < max_jumps): previous_node = current_node jump_decision = random.uniform(0, 1) if jump_decision < damping or G.out_degree(current_node) == 0: # make a jump current_node = random.randrange(N) while not G.has_node(current_node): current_node = random.randrange(N) j += 1 try: distance = nx.astar_path_length(G, previous_node, \ current_node, weight = 'weight') # distance intervals 1h traveling results.append(distance) nodes.append(previous_node) except nx.NetworkXNoPath: continue else: # move to neighbor node incident = G.out_edges([current_node], data = False) distribution = [ G.get_edge_data(e[0], e[1])['transition'] for e in incident ] xk = np.arange(len(incident)) generator = stats.rv_discrete(values = (xk, distribution)) current_node = incident[generator.rvs()][1] return results, nodes
def stitch(local_graph, global_graph, kd_tree, tolerance, target, rename_string): """ stitch local unconstrained graph with global graph, as long as the distance to nearest global graph node is within certain tolerance. Requires pre-generated kd-tree for the global graph. """ path_candidates = [] for node, d in local_graph.nodes(data=True): node_pos = d['pos'] dist, indexes = kd_tree.query([node_pos]) if dist[0] < tolerance: #find astar path to the selected close proximity node #TODO: compute node path here, and save it, extract length like this: # path = astar_path(G, source, target, heuristic) # length = sum(G[u][v].get(weight, 1) for u, v in zip(path[:-1], path[1:])) path_length = nx.astar_path_length(local_graph, target, node) entry_node = indexes[0] path_candidates.append((path_length, target, node, entry_node)) #chose best way to join to global graph path_candidates.sort() best_candidate = path_candidates[0] (path_length, target, node, entry_node) = best_candidate astar_path = nx.astar_path(local_graph, target, node) h = local_graph.subgraph(astar_path) route = h.to_directed() # because local_graphs have the same naming, aka (1,2) we have to rename # to join properly global_graph = nx.union(global_graph, route, rename=(None, rename_string)) #connect two graphs global_graph.add_edge(rename_string + str(node), entry_node) global_graph.add_edge( entry_node, rename_string + str(node)) return global_graph
def main82(): g = g82(matrix) N = len(matrix) M = len(matrix[0]) print "(%d) Nodes, (%d) Edges" % (len(g.nodes()), len(g.edges())) #print nx.dijkstra_path_length(g, (0,0), (N-1,M-1)) + g.node[(N-1, M-1)].get('value') minimum = 1e6 minimum2 = 1e6 for r in xrange(N): for r1 in xrange(M): try: source = (r,0) destiny = (r1, M-1) l = nx.dijkstra_path_length(g, source, destiny) l += g.node[destiny].get('value') l2 = nx.astar_path_length(g, source, destiny, dist) l2 += g.node[destiny].get('value') if l < minimum: minimum = l if l2 < minimum2: minimum2 = l2 except: continue print minimum, minimum2
def constructNewMonkeyToChosenSetDistanceVector(self, graph=None, preChosenMonkeyIDSet=None, minShortestDistance=0.4): """ 2012.11.26 each monkey is assigned a probability mass based on its geographic distance to the closest monkey in the preChosenMonkeyIDSet. """ sys.stderr.write("Constructing distance vector from new monkey to %s chosen monkeys (%s total monkeys) ..."%\ (len(preChosenMonkeyIDSet), len(graph))) counter = 0 real_counter = 0 spanStartPos = 0 unChosenMonkeyIDSet = set(graph.nodes()) - preChosenMonkeyIDSet preChosenAndInGraphMonkeyIDSet = set(graph.nodes()) - unChosenMonkeyIDSet returnData = PassingData(shortestDistanceToChosenSet_monkeyID_ls = []) for monkey1ID in unChosenMonkeyIDSet: counter += 1 shortestDistance = None shortestDistanceToThisChosenMonkey = None for monkey2ID in preChosenAndInGraphMonkeyIDSet: #get the shortest path #distance = nx.shortest_path_length(graph, source=monkey1ID, target=monkey2ID, weight='weight') distance = nx.astar_path_length(graph, source=monkey1ID, target=monkey2ID, weight='weight') #short path in graph, sum all the edge weights if shortestDistance is None or distance<shortestDistance: shortestDistance = distance shortestDistanceToThisChosenMonkey = monkey2ID if shortestDistance is not None and shortestDistance>=minShortestDistance: #ignore monkeys from same sites returnData.shortestDistanceToChosenSet_monkeyID_ls.append((shortestDistance, monkey1ID, shortestDistanceToThisChosenMonkey)) real_counter += 1 spanStartPos += shortestDistance #increase the distance. returnData.totalDistance = spanStartPos sys.stderr.write("%s (out of %s candidate) monkeys added into candidate vector, total distance to the chosen set is %s.\n"%\ (real_counter, counter, spanStartPos)) return returnData
import networkx as nx orbits = open('006.txt', 'r').readlines() edges = [o.strip().split(')') for o in orbits] G = nx.DiGraph() G.add_edges_from(edges) ancestors = sum([len(nx.ancestors(G, n)) for n in G.nodes()]) print('direct + indirect', ancestors) G = G.to_undirected() shortest_path = nx.astar_path_length(G, source='YOU', target='SAN') - 2 print('path', shortest_path)
def test_astar_multigraph(self): G = nx.MultiDiGraph(self.XG) G.add_weighted_edges_from((u, v, 1000) for (u, v) in list(G.edges())) assert nx.astar_path(G, 's', 'v') == ['s', 'x', 'u', 'v'] assert nx.astar_path_length(G, 's', 'v') == 9
def test_astar_directed(self): assert nx.astar_path(self.XG, "s", "v") == ["s", "x", "u", "v"] assert nx.astar_path_length(self.XG, "s", "v") == 9
def test_astar_w1(self): G=nx.DiGraph() G.add_edges_from([('s','u'), ('s','x'), ('u','v'), ('u','x'), ('v','y'), ('x','u'), ('x','v'), ('x','y'), ('y','s'), ('y','v')]) assert nx.astar_path(G,'s','v')==['s', 'u', 'v'] assert nx.astar_path_length(G,'s','v')== 2
def update_target_order(self, game): dist_list = [(x, nx.astar_path_length(game.board, self.home_node, x)) for x in self.remaining_objectives] dist_list.sort(key=lambda x: x[1]) self.target_order = [x[0] for x in dist_list if x[1] > 0]
def main(): # Festlegen der Standarddatei file_name = os.path.join(os.path.dirname(__file__), "lisarennt3.txt") if len(sys.argv) == 2: file_name = os.path.join(os.path.dirname(__file__), sys.argv[1]) # Einlesen der Datei input_file = open(file_name, 'r') str_data = input_file.read().splitlines() input_file.close() str_data_split = [list(map(int, string.split(' '))) for string in str_data] poly_data = str_data_split[1:len(str_data_split) - 1] raw_polygons = [] all_points = [] # Erstellen der Polygone for data_line in poly_data: vertices = [] for _ in range(1, len(data_line) - 1, 2): vertices.append((data_line[_], data_line[_ + 1])) raw_polygons.append(Polygon(vertices)) all_points += vertices start_point = (str_data_split[-1][0], str_data_split[-1][1]) all_points.append(start_point) # Vereinen von Polygonen, die einander beruehren polygons = [] for poly1 in raw_polygons: for poly2 in raw_polygons: if poly1 is not poly2 and poly1.poly_obj.intersects(poly2.poly_obj): poly1 = poly1.poly_obj.union(poly2.poly_obj) # Aktualisieren der Liste der Ecken des neuen kombinierten Polygons poly1.vertices = [(round(p[0]), round(p[1])) for p in geometry.mapping(poly1.poly_obj)['coordinates'][0]] raw_polygons.remove(poly2) polygons.append(poly1) # Erstellen eines Graphen mit allen bisherigen Punkten graph = nx.Graph() graph.add_nodes_from(all_points) # Erstellen von erlaubten Verbindungen innerhalb des Graphen checked_connections = [] for polygon in polygons: for p1 in polygon.vertices: for p2 in all_points: if p1 != p2 and (p2, p1) not in checked_connections: valid_connection, connecting_line = check_edge_valid(p1, p2, polygons, polygon) if valid_connection: graph.add_edge(p1, p2, weight=connecting_line.length) checked_connections.append((p1, p2)) # Hinzufuegen moeglicher Endpunkte an der Gerade x = 0 destinations = [] for p1 in all_points: p2 = calculate_ideal_finish(p1) valid_connection, connecting_line = check_edge_valid(p1, p2, polygons) if valid_connection: graph.add_node(p2) graph.add_edge(p1, p2, weight=connecting_line.length) destinations.append((p2, nx.astar_path_length(graph, start_point, p2, lambda p, q: geometry.LineString([p, q]).length))) # Ausrechnen der Guete jedes Endpunktes early_start = [] for point, distance in destinations: early_start.append(distance / RUN_SPEED - point[1] / BUS_SPEED) best_destination = destinations[early_start.index(min(early_start))] best_path = nx.astar_path(graph, start_point, best_destination[0], lambda p, q: geometry.LineString([p, q]).length) # Ausgabe von Routeninformationen start_time = (datetime.datetime(year=1, month=1, day=1, hour=7, minute=30) - datetime.timedelta(seconds=min(early_start))) print("Laufdistanz: " + str(best_destination[1]) + " m") print("Laufzeit: " + str(best_destination[1] / RUN_SPEED) + " s") print("Startzeit: " + start_time.time().strftime('%H:%M:%S.%f')) print("Ankunftszeit: " + (start_time + datetime.timedelta(seconds=best_destination[1] / RUN_SPEED)) .time().strftime('%H:%M:%S.%f')) print("Treffpunkt mit Bus: " + str(best_destination[0])) print() print("Route:") # Ausgabe der Route, Feststellen der jeweiligen Polygon-ID for i in range(len(best_path)): point = best_path[i] point_tag = "" if i == 0: point_tag = "L" elif i == (len(best_path) - 1): point_tag = "Bus" else: for j in range(len(raw_polygons)): if raw_polygons[j].poly_obj.intersects(geometry.Point(point)): point_tag = "P" + str(j + 1) break print(str(i + 1) + ". " + str((point[0], point[1], point_tag))) # Zeichnen des Weges plot_polygons(polygons) plot_line(best_path, 'black') plt.axvline(x=0, color='grey') plt.scatter(best_path[0][0], best_path[0][1], color='green', label='Start') plt.scatter(best_path[-1][0], best_path[-1][1], color='red', label='Ende') plt.legend() plt.axis('equal') plt.tight_layout() plt.show()
def test_astar_grid(): graph = nx.grid_graph(dim=[5,5]) assert nx.astar_path_length(graph,(0,0),(4,4)) == len(nx.astar_path(graph, (0,0),(4,4)))-1
def changepoint_path(wav_fn, length, graph=None, markers=None, sim_mat=None, avg_duration=None, APP_PATH=None, nchangepoints=4, min_start=None): """wave filename and graph from that wav, length in seconds""" # generate changepoints try: cpraw = subprocess.check_output([ APP_PATH + 'music_changepoints/novelty', wav_fn, '64', 'rms', 'euc', str(nchangepoints) * 3]) tmp_changepoints = [float(c) for c in cpraw.split('\n') if len(c) > 0] changepoints = [] cp_idx = 0 while len(changepoints) < nchangepoints: if min_start is None: changepoints.append(tmp_changepoints[cp_idx]) elif tmp_changepoints[cp_idx] >= min_start: changepoints.append(tmp_changepoints[cp_idx]) cp_idx += 1 except: changepoints = novelty(wav_fn, k=64, nchangepoints=nchangepoints) print "Change points", changepoints if graph is not None: edge_lens = [graph[e[0]][e[1]]["duration"] for e in graph.edges_iter()] avg_duration = N.mean(edge_lens) nodes = sorted(graph.nodes(), key=float) else: nodes = map(str, markers) node_count = int(float(length) / avg_duration) closest_nodes = [] node_to_cp = {} for cp in changepoints: closest_nodes.append( N.argmin([N.abs(float(node) - float(cp)) for node in nodes])) node_to_cp[str(closest_nodes[-1])] = cp out = [] for pair in itertools.permutations(closest_nodes, r=2): # print "Finding path for pair", pair, "of length", node_count avoid_nodes = [cn for cn in closest_nodes if cn != pair[1]] # avoid_nodes = closest_nodes if graph is not None: try: shortest_path = nx.astar_path_length(graph, nodes[pair[0]], nodes[pair[1]]) # print "# shortest path:", shortest_path if shortest_path <= node_count: pf = PathFinder(graph=graph, start=pair[0], end=pair[1], length=node_count) res, cost = pf.find(avoid=avoid_nodes) if res is not None: out.append((res, cost)) break except: pass else: pf = PathFinder(start=pair[0], sim_mat=sim_mat.copy(), end=pair[1], nodes=nodes, length=node_count) res, cost = pf.find(avoid=avoid_nodes) if res is not None: out.append((res, cost, map(lambda x: node_to_cp[str(x)], pair))) return out, changepoints
def test_astar_directed(self): assert_equal(nx.astar_path(self.XG, 's', 'v'), ['s', 'x', 'u', 'v']) assert_equal(nx.astar_path_length(self.XG, 's', 'v'), 9)
def astar_len(graph, width, height, startx, starty, targetx, targety): adj = adjecent_2DGridWorld(graph, width, height) G = nx.from_numpy_matrix(adj) return nx.astar_path_length(G, starty*width+startx, targety*width+targetx)
def distance(node, target): try: # return networkx.dijkstra_path_length(graph, node, target) return networkx.astar_path_length(graph, node, target, heuristic=heuristic) except networkx.NetworkXNoPath: return float('inf')
def main(): file = open('obfuscated_term_enron_astar.txt', 'w') file_1 = open('avg_mean_enron_Astar.txt', 'w') G=create_graph() #print(from_nodes) #read the sentences from a given file. with open('sentence.txt') as f: lines = f.read().splitlines() for each_line in lines: #print(each_line) each_line=each_line.replace('\'', '') for c in string.punctuation: each_line= each_line.replace(c," ") line = ''.join([i for i in each_line if not i.isdigit()]) line = re.sub("[A-Z]{2,}",'',line).replace(" ", " ") line=re.sub(r'\s+', ' ', line) line=line.lower() #print(line) sentence=line.split(" ") tag=find_tag(sentence) # print(tag) bag_of_words=[] bw=[] pos=[] list_of_mean_values=[] for i in range (0, len(tag)): #print(tag[i][0], tag[i][1]) if tag[i][1] in ('NN', 'NNS', 'JJ', 'JJR', 'JJS', 'RBR', 'RBS'): if len(tag[i][0])>=2: bw.append(tag[i][0]) pos.append(tag[i][1]) #print(pos) #print(tag[i][1]) #print('before lemma', bw) #pos={'NN':'n','JJ':'a','VB':'v','RB':'r', 'NNP':'n', 'NNS':'n', 'NNPS':'n', 'JJR':'a', 'JJS':'a','RBR':'r','RBS':'r', 'VBD':'v', 'VBG':'v', 'VBN':'v'} #print (pos) lmtzr = WordNetLemmatizer() for p in range(0, len(bw)): val=pos[p] # print(bw[p], val) if(val in ('NN','NNP','NNS','NNPS')): pos_wordnet='n' elif(val in ('JJ', 'JJR', 'JJS')): pos_wordnet='a' elif(val in ('RB', 'RBR', 'RBS')): pos_wordnet='r' #elif(val is ('VB', 'VBD', 'VBG', 'VBN')): else: pos_wordnet='v' # print(bw[p], pos_wordnet) lemma=lmtzr.lemmatize((bw[p]), pos_wordnet) #print(lemma) bag_of_words.append(lemma) #bag_of_words=['please', 'let', 'know', 'men'] #bag of words of one sentence #should come under loop of each line in lines. #print('bag of words', bag_of_words) length=len(bag_of_words) #print(length) if length>1: for i in range (0, length): sen_round_i=bag_of_words.copy() #print('orig',sen_round_i) sen_round_i.pop(i) mean_i=[] len_sen_round_i=len(sen_round_i) #print("round", i, ": ", sen_round_i) k=0 for j in range (0, len_sen_round_i-1): for k in range (j, len_sen_round_i): if j != k: #seq1=nx.dijkstra_path(G, '/c/en/'+sen_round_i[k], '/c/en/'+sen_round_i[j]) #seq2=nx.dijkstra_path(G, '/c/en/'+sen_round_i[j], '/c/en/'+sen_round_i[k]) item1='/c/en/'+sen_round_i[j] item2='/c/en/'+sen_round_i[k] if ((item1 in from_nodes) or (item1 in to_nodes)) and ((item2 in from_nodes) or (item2 in to_nodes)): path_one=nx.astar_path_length(G, item1, item2) #nx.shortest_path_length() path_two=nx.astar_path_length(G, item2, item1) avg_score=(path_one+path_two)/2 # print (item1, item2, 'are here') else: #print("not in data: ", item1, item2) avg_score=4 #print('node is not here'); #print(item1, item2, avg_score) #nx.shortest_path_length() #path_one=nx.dijkstra_path_length(G, '/c/en/'+sen_round_i[k], '/c/en/'+sen_round_i[j]) #path_two=nx.dijkstra_path_length(G, '/c/en/'+sen_round_i[j], '/c/en/'+sen_round_i[k]) #avg_score=(path_one+path_two)/2 #print(sen_round_i[j],',', sen_round_i[k],'>>') #print(seq1) #print(seq2) #print('path: ', path_one, ' reverse path: ', path_two, ' average: ', avg_score) mean_i.append(avg_score) k=k+1; #print(avg_score) mean_for_one_word=np.mean(mean_i) file_1.write(str(mean_for_one_word)) file_1.write(", ") #mean_for_one_word=mean_i/len_sen_round_i #print('mean value: ',mean_for_one_word) list_of_mean_values.append(mean_for_one_word) sen_round_i=bag_of_words #index, value = max(enumerate(list_of_mean_values), key=operator.itemgetter(1)) # print('Mean Average Conceptual Similarity: ',list_of_mean_values) min_value=min(list_of_mean_values) file_1.write('\n') file_1.write('\t') file_1.write(str(min_value)) file_1.write('\n\n') index=list_of_mean_values.index(min_value) ot=bag_of_words[index] file.write(ot) #file.write(' ') file.write('\n') #print('obfuscated term: ', bag_of_words[index]) else: file.write("NA") #file.write(' ') file.write('\n') file_1.write("NA") #file.write(' ') file_1.write('\n')
def _transmission_probability(self): """ Returns: """ i = 1 while i < len(self.candidates): # j and k j = i - 1 if len(self.candidates[i]) == 0: k = i + 1 while k < len(self.candidates) and len( self.candidates[k]) == 0: k += 1 if k == len(self.candidates): break else: k = i d = dist(angle2radian(self.trajectory[j][2]), angle2radian(self.trajectory[j][1]), angle2radian(self.trajectory[k][2]), angle2radian( self.trajectory[k][1])) # great circle distance for edge_j, dct_j in self.candidates[j].items(): for edge_k, dct_k in self.candidates[k].items(): brng_jk = init_bearing(angle2radian(self.trajectory[j][2]), angle2radian(self.trajectory[j][1]), angle2radian(self.trajectory[k][2]), angle2radian(self.trajectory[k][1])) brng_edge_j = init_bearing( angle2radian(self.rd_nwk.nodes[edge_j[0]]['lat']), angle2radian(self.rd_nwk.nodes[edge_j[0]]['lon']), angle2radian(self.rd_nwk.nodes[edge_j[1]]['lat']), angle2radian(self.rd_nwk.nodes[edge_j[1]]['lon']), ) try: if dct_j['node'] is not None and dct_k[ 'node'] is not None: dt = abs(d - nx.astar_path_length(self.rd_nwk, dct_j['node'], dct_k['node'], weight='distance')) elif dct_j['node'] is not None: nd2_origin = edge_k[0] lon, lat = self.rd_nwk.nodes[nd2_origin][ 'lon'], self.rd_nwk.nodes[nd2_origin]['lat'] path_len = nx.astar_path_length(self.rd_nwk, dct_j['node'], nd2_origin, weight='distance') path_len += math.sqrt( math.fabs( dist(angle2radian(self.trajectory[k][2]), angle2radian(self.trajectory[k][1]), angle2radian(lat), angle2radian(lon)) **2 - dct_k['distance']**2)) if edge_j[1] == dct_j['edge']: path_len += self.rd_nwk[edge_j[0]][ edge_j[1]]['distance'] * 2 dt = abs(d - path_len) elif dct_k['node'] is not None: nd1_destination = edge_j[1] lon, lat = self.rd_nwk.nodes[nd1_destination][ 'lon'], self.rd_nwk.nodes[nd1_destination][ 'lat'] path_len = nx.astar_path_length(self.rd_nwk, nd1_destination, dct_k['node'], weight='distance') path_len += math.sqrt( math.fabs( dist(angle2radian(self.trajectory[j][2]), angle2radian(self.trajectory[j][1]), angle2radian(lat), angle2radian(lon)) **2 - dct_j['distance']**2)) if edge_k[1] == dct_k['node']: path_len += self.rd_nwk[edge_k[0]][ edge_k[1]]['distance'] * 2 dt = abs(d - path_len) else: if edge_j == edge_k and math.fabs(brng_edge_j - brng_jk) < 90: dt = 1 else: nd1_destination = edge_j[1] lon1, lat1 = self.rd_nwk.nodes[nd1_destination]['lon'], \ self.rd_nwk.nodes[nd1_destination]['lat'] nd2_origin = edge_k[0] lon2, lat2 = self.rd_nwk.nodes[nd2_origin][ 'lon'], self.rd_nwk.nodes[nd2_origin][ 'lat'] dt = abs(d - ( nx.astar_path_length(self.rd_nwk, nd1_destination, nd2_origin, weight='distance') + math.sqrt( math.fabs( dist( angle2radian(self.trajectory[j] [2]), angle2radian(self.trajectory[ j][1]), angle2radian(lat1), angle2radian(lon1))**2 - dct_j['distance']**2)) + math.sqrt( math.fabs( dist( angle2radian(self.trajectory[k] [2]), angle2radian(self.trajectory[ k][1]), angle2radian(lat2), angle2radian(lon2))**2 - dct_k['distance']**2)))) result = 1 / self.beta * math.exp(-dt / self.beta) if 'V' in dct_j.keys(): dct_j['V'][edge_k] = min(result, 1) else: dct_j['V'] = {edge_k: min(result, 1)} except: if 'V' in dct_j.keys(): dct_j['V'][edge_k] = 0 else: dct_j['V'] = {edge_k: 0} i += 1
def test_astar_undirected(self): GG = self.XG.to_undirected() GG['y']['v']['weight'] = 2 assert nx.astar_path(GG, 's', 'v') == ['s', 'x', 'u', 'v'] assert nx.astar_path_length(GG, 's', 'v') == 8
def test_astar_undirected(self): GG=self.XG.to_undirected() GG['y']['v']['weight'] = 2 assert nx.astar_path(GG,'s','v')==['s', 'x', 'u', 'v'] assert nx.astar_path_length(GG,'s','v')==8
def getStaticDuration(self, startNodeId, nextNodeId): return float( nx.astar_path_length(graphService.G, startNodeId, nextNodeId))
def test_astar_MultiGraph(): graph = nx.MultiGraph() e=[('a','b',0.3),('b','c',0.9),('a','c',0.5),('c','d',1.2),('c','e',1.6),('b','e',0.7),('d','e', 1.3)] graph.add_weighted_edges_from(e) assert nx.astar_path_length(graph,'a','e') == 1
lon1 = math.radians(graph.node[a]["lon"]) lat2 = math.radians(graph.node[b]["lat"]) lon2 = math.radians(graph.node[b]["lon"]) return gis.distance(lat1, lon1, lat2, lon2) print("Remove short edges") items, edges_removed, violates_triangle_inequality = 0, 0, 0 for node in graph.nodes_iter(): if graph.degree(node) == 2: weight = 0 neighbours = dict(graph[node]) for n in neighbours: weight += graph[node][n]["weight"] if weight <= distance_threshold: a, b = list(neighbours) dist = astar_path_length(graph, a, b, heuristic=heuristic) if dist < weight: violates_triangle_inequality += 1 else: # Only look at first type type = graph[node][a]["type"] graph.remove_edge(node, a) graph.remove_edge(node, b) graph.add_edge(a, b, weight=weight, type=type) edges_removed += 2 items += 1 print("{0} items processed".format(items), end="\r") print("{0} items processed".format(items)) print("Deleted {0} edges".format(edges_removed)) print("Kept {0} edges to preserve triangle inequality".format(violates_triangle_inequality))
def test_astar_multigraph(self): G = nx.MultiDiGraph(self.XG) G.add_weighted_edges_from((u, v, 1000) for (u, v) in list(G.edges())) assert nx.astar_path(G, "s", "v") == ["s", "x", "u", "v"] assert nx.astar_path_length(G, "s", "v") == 9
# Move Right (w = 1) if j + 1 < n and mat[i][j + 1] != 1: G.add_edge(str((i * n) + j), str((i * n) + (j + 1)), weight=1) # Set the start timestamp start_time = time.time() # A* algorithm with the specified heuristic # Part A: (0,0) --- (23,24) print('------------ Part A ------------') path = nx.astar_path(G, str(0 * n + 0), str(23 * n + 24), heuristic) for cell in path: print('(' + str(int(cell) // n) + ',' + str(int(cell) % m) + ')') print('Minimum Cost:', nx.astar_path_length(G, str(0), str(23 * n + 24), heuristic)) # Set the end timestamp end_time = time.time() # Measure execution time print('Execution Time:', (end_time - start_time) * 1000, 'Milliseconds') # Set the start timestamp start_time = time.time() # Part B: (17,1) --- (17,29) print('------------ Part B ------------') path = nx.astar_path(G, str(17 * n + 1), str(17 * n + 29), heuristic) for cell in path: print('(' + str(int(cell) // n) + ',' + str(int(cell) % m) + ')')
def astar(g, s, t, weight='weight'): path = nx.astar_path(g, s, t, heuristic, weight=weight) dist = nx.astar_path_length(g, s, t, heuristic, weight=weight) return dist, path
z = 0 for x in V: if Square[x[1], z] == Inf: Square[x[1], z] = x[0] else: z = z + 1 Square[x[1], z] = x[0] # print(Square[0]) Square = Square.reshape(10, 10, 10) # print(Square[0]) for i in range(len(V)): add_vertex((V[i][0])) for i in range(len(E)): add_edge(E[i][0], E[i][1], E[i][2]) for i in range(vertices_no): for j in range(vertices_no): if graph[i][j] == 0: graph[i][j] = Inf start = datetime.now() g = nx.Graph() for edge in range(len(E)): g.add_edge(E[edge, 0], E[edge, 1], weight=E[edge, 2]) path = nx.astar_path(g, 0, 99, heuristic) pl = nx.astar_path_length(g, 0, 99) print(path) print(pl) #print(E[0]) print(datetime.now() - start)
def test_astar_undirected(self): GG=self.XG.to_undirected() assert nx.astar_path(GG,'s','v')==['s', 'x', 'u', 'v'] assert nx.astar_path_length(GG,'s','v')==8
def test_astar_undirected2(self): XG3 = nx.Graph() edges = [(0, 1, 2), (1, 2, 12), (2, 3, 1), (3, 4, 5), (4, 5, 1), (5, 0, 10)] XG3.add_weighted_edges_from(edges) assert nx.astar_path(XG3, 0, 3) == [0, 1, 2, 3] assert nx.astar_path_length(XG3, 0, 3) == 15
pairs = [] for line in lines: pairs.append([int(x) for x in line.split(" ")]) print(pairs) pairs.pop(0) # Create graph G = nx.DiGraph() # Unique nodes flat_list = [val for sublist in pairs for val in sublist] uniq_node = list(set(flat_list)) for node in range(1, max(uniq_node)): G.add_node(node) # Place edges for pair in pairs: G.add_edge(pair[0], pair[1]) # Compute shortest paths results = [] for node in range(1, max(uniq_node) + 1): try: shortest = nx.astar_path_length(G, 1, node) except nx.exception.NetworkXNoPath: shortest = -1 results.append(shortest) print(" ".join([str(x) for x in results]))
for eg in gp.edges(data=True): if eg[0] in cost_dict: if eg[1] in cost_dict[eg[0]]: eg[2]['negative_weight'] = -1 * eg[2]['weight'] idcs = np.random.choice(len(gp.nodes()), int(5 * 5 * 0.2), replace=False) # print idcs # スタート・ゴール・障害物を設定する st, gl, obs = (0, 0), (30, 60), [list(gp.nodes())[i] for i in idcs[2:]] # st, gl, obs = (0,0), (np.random.randint(g_dim[0]),np.random.randint(g_dim[1])), [list(gp.nodes())[i] for i in idcs[2:]] obs = [list(gp.nodes())[i] for i in idcs[2:]] path = nx.astar_path(gp, st, gl, cost) length = nx.astar_path_length(gp, st, gl, cost) path2 = nx.johnson(gp, weight='negative_weight') print('johnson: {0}'.format(path2[st][gl])) for p in path2[st][gl]: if gp.node[p].get('color', '') == 'black': print('Invalid path') continue gp.node[p]['color'] = 'orange' previous_nd = st longest_length = 0 for nd in path2[st][gl][:]: if not (previous_nd == st and nd == st): # longest_length += cost_dict[previous_nd][nd]
def test_astar_directed(self): assert nx.astar_path(self.XG,'s','v')==['s', 'x', 'u', 'v'] assert nx.astar_path_length(self.XG,'s','v')==9
# ------ A * search ------ import networkx as nx import matplotlib.pyplot as plt def dist(a, b): (x1, y1) = a (x2, y2) = b return ((x1 - x2)**2 + (y1 - y2)**2)**0.5 G = nx.grid_graph(dim=[3, 3]) # nodes are two-tuples (x,y) nx.set_edge_attributes(G, {e: e[1][0] * 2 for e in G.edges()}, "cost") path = nx.astar_path(G, (0, 0), (2, 2), heuristic=dist, weight="cost") length = nx.astar_path_length(G, (0, 0), (2, 2), heuristic=dist, weight="cost") print('Path:') print(path) print("Path length: ") print(length) pos = nx.spring_layout(G) nx.draw(G, pos, with_labels=True, node_color="#f86e00") edge_labels = nx.get_edge_attributes(G, "cost") nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels) plt.show()
Lugoj=(165, 379), Mehadia=(168, 339), Neamt=(406, 537), Oradea=(131, 571), Pitesti=(320, 368), Rimnicu=(233, 410), Sibiu=(207, 457), Timisoara=(94, 410), Urziceni=(456, 350), Vaslui=(509, 444), Zerind=(108, 531)) g = nx.Graph() node_labels = {} for city, _ in romania_plot_positions.items(): g.add_node(city, position=romania_plot_positions[city]) node_labels[city]=city for city, neighborhood in romania_neighbours.items(): for neighbour, distance in neighborhood.items(): g.add_edge(city, neighbour, weight=distance) node_label_positions = {k:[v[0],v[1]] for k,v in romania_plot_positions.items()} plt.figure(figsize=(18,13)) nx.draw(g, pos = node_label_positions, node_color='white') drawn_labels = nx.draw_networkx_labels(g, pos=node_label_positions, labels=node_labels) def distance(a, b): (x1, y1) = g.nodes[a]['position'] (x2, y2) = g.nodes[b]['position'] return ((x1 - x2) ** 2 + (y1 - y2) ** 2) ** 0.5 print(nx.greedy_path(g,'Arad','Bucharest',heuristic= distance)) print(nx.astar_path(g,'Arad','Bucharest',heuristic= distance)) nx.astar_path_length(g,'Arad','Bucharest',heuristic= distance, weight='weight') #plt.show()
def test_astar_directed(self): assert nx.astar_path(self.XG, 's', 'v') == ['s', 'x', 'u', 'v'] assert nx.astar_path_length(self.XG, 's', 'v') == 9
def transmission_probability(traj): v_list = [[]] for row1, row2 in pairwise(traj.values): d = haversine(row1[0], row1[1], row2[0], row2[1]) row_v_list = [] for idx1, nd1 in enumerate(row1[-2]): temp_list = [] for idx2, nd2 in enumerate(row2[-2]): try: # nd1 and nd2 are not connected if pd.notnull(nd1) and pd.notnull(nd2): temp_list.append(d / nx.astar_path_length( roadnetwork, nd1, nd2, weight='distance')) elif pd.notnull(nd1): nd2_back_node = edge_dict[row2[-3][idx2]][0] nd2_back_node_cor = vertice_dict[nd2_back_node] temp_list.append(d / (nx.astar_path_length( roadnetwork, nd1, nd2_back_node, weight='distance') + np.sqrt( np.abs( haversine(row2[0], row2[1], nd2_back_node_cor[0], nd2_back_node_cor[1])**2 - row2[-4][idx2]**2)))) elif pd.notnull(nd2): nd1_forward_node = edge_dict[row1[-3][idx1]][1] nd1_forward_node_cor = vertice_dict[nd1_forward_node] temp_list.append( d / (nx.astar_path_length(roadnetwork, nd1_forward_node, nd2, weight='distance') + np.sqrt( np.abs( haversine(row1[0], row1[1], nd1_forward_node_cor[0], nd1_forward_node_cor[1])**2 - row1[-4][idx1]**2)))) else: nd1_forward_node = edge_dict[row1[-3][idx1]][1] nd1_forward_node_cor = vertice_dict[nd1_forward_node] nd2_back_node = edge_dict[row2[-3][idx2]][0] nd2_back_node_cor = vertice_dict[nd2_back_node] temp_list.append( d / (nx.astar_path_length(roadnetwork, nd1_forward_node, nd2_back_node, weight='distance') + np.sqrt( np.abs( haversine(row1[0], row1[1], nd1_forward_node_cor[0], nd1_forward_node_cor[1])**2 - row1[-4][idx1]**2)) + np.sqrt( np.abs( haversine(row2[0], row2[1], nd2_back_node_cor[0], nd2_back_node_cor[1])**2 - row2[-4][idx2]**2)))) except: temp_list.append(0) row_v_list.append(temp_list) v_list.append(row_v_list) return v_list
def manhattan(self, startNode, endNode): source = startNode.node.nodeId target = endNode.node.nodeId if nx.has_path(graphService.G, source, target) == False: return 3600 return float(nx.astar_path_length(graphService.G, source, target))
def main(argv): filename = None gritter_range = None heuristic = None show_graph = False show_data = False timed_run = False try: opts, args = getopt.getopt(argv, "i:r:h:dvt") if not opts: usage() sys.exit() except getopt.GetoptError: usage() sys.exit() for opt, arg in opts: if opt == "-i": filename = arg elif opt == "-r": gritter_range = float(arg) elif opt == "-h": heuristic = arg elif opt == "-v": show_graph = True elif opt == "-d": show_data = True elif opt == "-t": timed_run = True graph = nx.read_weighted_edgelist(filename, delimiter=',', nodetype=int) nx.set_node_attributes( graph, dict(zip(list(graph.nodes), [nx.astar_path_length(graph, 0, node) for node in graph.nodes])), "distance") search = None if heuristic == "vns": search = VNS(graph, gritter_range) elif heuristic == "tabu": search = Tabu(graph, gritter_range) start = timer() result = search.run() end = timer() if show_data: print("\nfound solution: ", result.nodes) print("\ncost: ", result.function()) if timed_run: print("\nelapsed:", end - start) if show_graph: node_list = result.nodes cycles = [] current_cycle = [] for i in range(1, len(node_list)): current_cycle.append((node_list[i - 1], node_list[i])) if node_list[i] == 0: cycles.append(current_cycle) current_cycle = [] unvisited = list(graph.edges) for index, cycle in enumerate(cycles): nx.draw_networkx_nodes(graph, pos=nx.circular_layout(graph)) nx.draw_networkx_nodes(graph, pos=nx.circular_layout(graph), nodelist=[0], node_color='b') nx.draw_networkx_edge_labels(graph, pos=nx.circular_layout(graph), edge_labels=nx.get_edge_attributes(graph, "weight")) unvisited = [edge for edge in unvisited if tuple(sorted(edge)) not in cycle and tuple(reversed(sorted(edge))) not in cycle] nx.draw_networkx_edges(graph, pos=nx.circular_layout(graph)) nx.draw_networkx_edges(graph, pos=nx.circular_layout(graph), edgelist=unvisited, width=5) nx.draw_networkx_edges(graph, pos=nx.circular_layout(graph), edgelist=cycle, width=5, edge_color='y') full_screen() plt.show()
def test_astar_undirected(self): GG = self.XG.to_undirected() assert nx.astar_path(GG, 's', 'v') == ['s', 'x', 'u', 'v'] assert nx.astar_path_length(GG, 's', 'v') == 8
import csv import networkx as nx G = nx.Graph() with open('in.txt') as input_file: for row in csv.reader(input_file, delimiter=")"): G.add_nodes_from(row) G.add_edges_from([row]) print(nx.astar_path_length(G, source='YOU', target='SAN') - 2)
def astar(start, terminal): cost = 0 path = nx.astar_path(G, start, terminal) cost = nx.astar_path_length(G, start, terminal)
def construct_path(self) -> None: """Constructs the flight path using the A* Algorithm. This is done in this order: 1. Construct path of just waypoints 2. Check to see if it is possible to do offaxis and drop while flying path 3. If not generate most optimal after """ off_check = self.off_axis == None drop_check = self.drop == None path = [] # Generate waypoints for i in range(len(self.waypoints) - 1): seg = [] seg.extend( nx.astar_path(self.graph, *self.waypoints[i].point.coords, *self.waypoints[i + 1].point.coords, heuristic)) print(i, seg, self.graph.has_edge(seg[0], seg[len(seg) - 1])) if i == 0: path.extend(seg) else: path.extend(seg[1:]) # Check path to see if passes through offaxis/drop ring = LineString(path) if self.off_axis != None: off_point = ring.interpolate(ring.project(self.off_axis)) off_dis = off_point.distance(self.off_axis) if off_point.z / off_dis > 2.74: off_check = True self.off_axis_optimal = off_point if self.drop != None: drop_point = ring.interpolate(ring.project(self.drop)) drop_dis = drop_point.distance(self.drop) if drop_dis < 15: drop_check = True self.drop = drop_point seg = [] # Generate remaining POIs if not off_check and not drop_check: off_drop_dis = nx.astar_path_length(self.graph, path[len(path) - 1], *self.off_axis_optimal.coords, heuristic) drop_off_dis = nx.astar_path_length(self.graph, path[len(path) - 1], *self.drop.coords, heuristic) if off_drop_dis < drop_off_dis: seg.extend( nx.astar_path(self.graph, path[len(path) - 1], *self.off_axis_optimal.coords, heuristic)[1:]) seg.extend( nx.astar_path(self.graph, *self.off_axis_optimal.coords, *self.drop.coords, heuristic)[1:]) else: seg.extend( nx.astar_path(self.graph, path[len(path) - 1], *self.drop.coords, heuristic)[1:]) seg.extend( nx.astar_path(self.graph, *self.drop.coords, *self.off_axis_optimal.coords, heuristic)[1:]) elif not off_check: seg.extend( nx.astar_path(self.graph, path[len(path) - 1], *self.off_axis_optimal.coords, heuristic)[1:]) elif not drop_check: seg.extend( nx.astar_path(self.graph, path[len(path) - 1], *self.drop.coords, heuristic)[1:]) path.extend(seg) self.path = path