def path_via_visibility(tree, path): """ using the visibility graph to find the shortest path :param tree: biased tree :param path: path found by the first step of the suffix part :return: a path in the free workspace (after treating all regions as obstacles) and its distance cost """ paths = [] max_len = 0 # find a path for each robot using visibility graph method for i in range(tree.robot): init = path[-1][0][i] goal = path[0][0][i] shortest = tree.g.shortest_path(vg.Point(init[0], init[1]), vg.Point(goal[0], goal[1])) max_len = len(shortest) if len(shortest) > max_len else max_len paths.append([(point.x, point.y) for point in shortest]) # append to the same length for i in range(tree.robot): paths[i] = paths[i] + [paths[i][-1]] * (max_len - len(paths[i])) # combine to one path of product state path_free = [(tuple([p[i] for p in paths]), '') for i in range(max_len) ] # second component serves as buchi state # calculate cost cost = 0 for i in range(1, max_len): cost = cost + np.linalg.norm( np.subtract(tree.mulp2single(path_free[i][0]), tree.mulp2single(path_free[i - 1][0]))) return cost, path_free
def main(): graph = vg.VisGraph() graph.load('ntu_new_2') # start = map(float, raw_input('Start: ').strip().split()) # end = map(float, raw_input('End: ').strip().split()) while True: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((HOST, PORT)) s.listen(1) print 'Waiting for connection...' conn, addr = s.accept() print 'Connected by: ', addr while True: data = conn.recv(1024) if not data: break print 'Data received: ', data startx, starty, endx, endy = map(float, data.split()) start = vg.Point(startx, starty) end = vg.Point(endx, endy) c_start = graph.point_in_polygon(start) c_end = graph.point_in_polygon(end) path = [] if c_start != -1: path.append(str(start.x) + ' ' + str(start.y)) start = graph.closest_point(start, c_start) if c_end != -1: end = graph.closest_point(end, c_end) shortest_path = graph.shortest_path(start, end) for point in shortest_path: path.append(str(point.x) + ' ' + str(point.y)) path.append(str(endx) + ' ' +str(endy)) print 'Data sent: ', ' '.join(path) conn.sendall(' '.join(path)) conn.close()
def ShorestPathBtRg(self, regions): """ calculate shoresr path between any two labeled regions :param regions: regions :return: dict (region, region) : length """ polys = [[vg.Point(0.4, 1.0), vg.Point(0.4, 0.7), vg.Point(0.6, 0.7), vg.Point(0.6, 1.0)], [vg.Point(0.3, 0.2), vg.Point(0.3, 0.0), vg.Point(0.7, 0.0), vg.Point(0.7, 0.2)]] g = vg.VisGraph() g.build(polys, status=False) min_len_region = dict() for key1, value1 in regions.items(): for key2, value2 in regions.items(): init = value1[:2] tg = value2[:2] # shorest path between init and tg point shortest = g.shortest_path(vg.Point(init[0], init[1]), vg.Point(tg[0], tg[1])) # (key2, key1) is already checked if (key2, key1) in min_len_region.keys(): min_len_region[(key1, key2)] = min_len_region[(key2, key1)] else: # different regions if key1 != key2: dis = 0 for i in range(len(shortest)-1): dis = dis + np.linalg.norm(np.subtract((shortest[i].x, shortest[i].y), (shortest[i+1].x, shortest[i+1].y))) min_len_region[(key1, key2)] = dis # same region else: min_len_region[(key1, key2)] = 0 return min_len_region
def Dis_PosC(x): Dist_ = 0 Store_Comb = [] Permutation_list = [] list_ = [] for i in range(len(Adjust_x[0]) / 2): list_.append(i) list_Num = len(list_) x_list = [] for i in range(len(Adjust_x[0]) / 2): x[i] = math.floor(x[i]) x_list.append(int(round(x[i]))) for i in range(list_Num): Permutation_list.append(list_[x_list[i]]) del list_[x_list[i]] for i in range(len(Adjust_x[0]) / 2): Store_Comb.append(CABC_all_points[Permutation_list[i]]) for i in range(len(Adjust_x[0]) / 2 - 1): Dis_0 = vg.Point(Store_Comb[i][0], Store_Comb[i][1]) Dis_1 = vg.Point(Store_Comb[i + 1][0], Store_Comb[i + 1][1]) Dist = g.shortest_path(Dis_0, Dis_1) _Dist_ = LineString(sp2list(Dist)).length Dist_ = Dist_ + _Dist_ return Dist_
def get_target(self, init, target): """ find the second vertex in the shortest path from initial point to the target region :param init: initial point :param target: target labeled region :return: the second vertex """ tg = self.regions[target].centroid.coords[0] shortest = self.g.shortest_path(vg.Point(init[0], init[1]), vg.Point(tg[0], tg[1])) return shortest[1].x, shortest[1].y
def target(self, init, target, regions): """ find the closest vertex in the short path from init to target :param init: inital point :param target: target labeled region :param regions: regions :return: closest vertex """ tg = regions[target].centroid.coords[0] shortest = self.g.shortest_path(vg.Point(init[0], init[1]), vg.Point(tg[0], tg[1])) return (shortest[1].x, shortest[1].y)
def findPathPoly(self, sourceP, targetP, objList, layoutPoly): """ calculating shortest path from sourceP point to targetP that avoid polygon shape obstacles sourceP/targetP - 2D points objList - List of obstacle objects (polygons, each is a list of 2D points). Should Contains the object's polygon and forward facing edge ??? layoutPoly - Nx2 list of ordered vertices defining a 2D polygon of N vertices - room polygon layout last point NEQ first point =>>>>>>> Assuming polygons DO NOT intersect """ nObj = len(objList) objListVg = [] # Transform to pyvisgraph format for n in range(nObj): tmpPoly = [] for p in objList[n]: tmpPoly.append(pvg.Point(p.x, p.y)) objListVg.append(tmpPoly) # Start building the visibility graph graph = pvg.VisGraph() refPoint = pvg.Point(sourceP[0].x, sourceP[0].y) workers = 1 graph.build_mod(objListVg, workers, None, refPoint) # , workers=workers) # graph.build(objListVg) #, workers=workers) # Get the shortest path shortest_path = [] path_distance = [] direct_distance = [] for n in range(len(sourceP)): sP = pvg.Point(sourceP[n].x, sourceP[n].y) tP = pvg.Point(targetP[n].x, targetP[n].y) spath = graph.shortest_path(sP, tP) # Calculate the total distance of the shortest path pdistance = 0 prev_point = spath[0] for point in spath[1:]: pdistance += np.sqrt((prev_point.y - point.y)**2 + (prev_point.x - point.x)**2) prev_point = point shortest_path.append(spath) path_distance.append(pdistance) dDist = np.sqrt((targetP[n].x - sourceP[n].x)**2 + (targetP[n].y - sourceP[n].y)**2) direct_distance.append(dDist) # print('Shortest path distance: {}'.format(path_distance)) return shortest_path, path_distance, direct_distance
def target(self, init, tg): """ find the closest vertex in the short path from init to target :param init: inital point :param target: target labeled region :param regions: regions :return: closest vertex """ shortest = self.g.shortest_path(vg.Point(init[0], init[1]), vg.Point(tg[0], tg[1])) return shortest[1].x, shortest[1].y
async def calculate_route(self, start, destination): self.blockages = [] for barrel in self.barrels: pt = geom.Point(barrel.pos).buffer(200, resolution=2) self.blockages.append(pt) self.blockages = ops.unary_union(self.blockages) if isinstance(self.blockages, geom.polygon.Polygon): self.blockages = [self.blockages] vg_points = [[vg.Point(x, y) for x, y in pts.exterior.coords] for pts in self.blockages] graph = await spawn(get_visibility_graph, vg_points) route = graph.shortest_path(vg.Point(*start), vg.Point(*destination)) route = np.array([[p.x, p.y] for p in route]) return route
def test(): m = open('newMap.txt') polys = [] for line in m: points = (line.strip()).split(',') poly = [] for point in points: point = map(float, point.split()) poly.append(vg.Point(point[0], point[1])) polys.append(poly) graph = vg.VisGraph() graph.build(polys, workers=4) shortest = graph.shortest_path(vg.Point(-520, -70), vg.Point(450, -1300)) print shortest
def point_distances(points, graph): N = len(points) D = np.zeros((N, N)) for i in range(N): for j in range(N): if i > j: shortest_path = graph.shortest_path( vg.Point(points[i][0], points[i][1]), vg.Point(points[j][0], points[j][1])) D[i, j] = path_to_distance(shortest_path) D += D.T return D
def __init__(self, n_robot, acpt, ts, buchi_graph, init, seg, step_size, no): """ :param acpt: accepting state :param ts: transition system :param buchi_graph: Buchi graph :param init: product initial state """ self.robot = n_robot self.acpt = acpt self.goals = [] self.ts = ts self.buchi_graph = buchi_graph self.init = init self.seg = seg self.step_size = step_size self.dim = len(self.ts['workspace']) uni_ball = [ 1, 2, 3.142, 4.189, 4.935, 5.264, 5.168, 4.725, 4.059, 3.299, 2.550 ] # uni_v = uni_ball[self.robot*self.dim] uni_v = np.power(np.pi, self.robot * self.dim / 2) / math.gamma(self.robot * self.dim / 2 + 1) self.gamma = np.ceil( 4 * np.power(1 / uni_v, 1. / (self.dim * self.robot))) # unit workspace self.tree = DiGraph(type='PBA', init=init) self.group = dict() label = [] for i in range(self.robot): l = self.label(init[0][i]) # exists one sampled point lies within obstacles if l != '': l = l + '_' + str(i + 1) label.append(l) self.tree.add_node(init, cost=0, label=label) self.add_group(init) # probability self.p = 0.9 # threshold for collision avoidance self.threshold = 0.02 # polygon obstacle polys = [[ vg.Point(0.4, 1.0), vg.Point(0.4, 0.7), vg.Point(0.6, 0.7), vg.Point(0.6, 1.0) ], [ vg.Point(0.3, 0.2), vg.Point(0.3, 0.0), vg.Point(0.7, 0.0), vg.Point(0.7, 0.2) ]] self.g = vg.VisGraph() self.g.build(polys, status=False) # region that has ! preceding it self.no = no
def real_travel_list(travel_list): real_travel_list = [] for list in travel_list: real_list = [] for i in range(1, len(list)): p1 = vg.Point(list[i - 1][0], list[i - 1][1]) p2 = vg.Point(list[i][0], list[i][1]) shortest_path = g.shortest_path(p1, p2) for point in shortest_path: real_list.append(to_np(point)) real_travel_list.append(real_list) return real_travel_list
def set_distances(points1, points2, graph): """ The distances between two sets of points. First argument should be start or goal.""" K = len(points1) N = len(points2) D = np.zeros((K, N)) for i in range(K): for j in range(N): shortest_path = graph.shortest_path( vg.Point(points1[i][0], points1[i][1]), vg.Point(points2[j][0], points2[j][1])) D[i, j] = path_to_distance(shortest_path) return D
def processItem(cluster): wires = [] _ = cluster.Wires(None, wires) polys = [] for aWire in wires: vertices = [] _ = aWire.Vertices(None, vertices) poly = [] for v in vertices: p = vg.Point(round(v.X(), 4), round(v.Y(), 4), 0) poly.append(p) polys.append(poly) g = vg.VisGraph() g.build(polys) tpEdges = [] vgEdges = g.visgraph.get_edges() for vgEdge in vgEdges: sv = topologic.Vertex.ByCoordinates(vgEdge.p1.x, vgEdge.p1.y, 0) ev = topologic.Vertex.ByCoordinates(vgEdge.p2.x, vgEdge.p2.y, 0) tpEdges.append(topologic.Edge.ByStartVertexEndVertex(sv, ev)) tpVertices = [] vgPoints = g.visgraph.get_points() for vgPoint in vgPoints: v = topologic.Vertex.ByCoordinates(vgPoint.x, vgPoint.y, 0) tpVertices.append(v) graph = topologic.Graph(tpVertices, tpEdges) return graph
def testApp(): segments2 = [] # figures root = Tk() root.geometry("1270x650") c = Canvas(root, bg="black", height=700, width=1400) Figures = obtainRandomFigures() drawRandomFigures(c, Figures) pointsX, pointsY = obtainXListAndYList(Figures) c.create_oval(x1 - 5, y1 - 5, x1 + 5, y1 + 5, fill="red") c.create_oval(x2 - 5, y2 - 5, x2 + 5, y2 + 5, fill="green") drawCircles(pointsX, pointsY, c) polys = [] for list in Figures: tmpList = [] for i in range(0, len(list), 2): x = list[i] y = list[i + 1] newPoint = vg.Point(x, y) tmpList.append(newPoint) polys.append(tmpList) g = vg.VisGraph() g.build(polys) shortest = g.shortest_path(vg.Point(x1, y1), vg.Point(x2, y2)) cnt = 0 for n in range(len(shortest)): try: c.create_line(shortest[n].x, shortest[n].y, shortest[n + 1].x, shortest[n + 1].y, width=0.9, fill="green") except: pass #hilo1 = threading.Thread(target=avanzarPunto, args=(shortest,c,)) #hilo1.start() c.pack() root.mainloop()
def __init__(self, polys, origin, destination): n = len(polys) m = len(polys[0]) self.polys = [[0] * m for i in range(n)] for i in range(n): for j in range(m): self.polys[i][j] = vg.Point(polys[i][j][0], polys[i][j][1]) self.origin = vg.Point(origin[0], origin[1]) self.destination = vg.Point(destination[0], destination[1]) self.g = vg.VisGraph() self.g.build(self.polys) self.path = self.construct_path() self.waypoint = [] for i in range(len(self.path)): self.waypoint.append([self.path[i].x, self.path[i].y, 0, 0]) super(AStarGraph, self).__init__(self.waypoint)
def run(polygons, robots, case_number): # print("Now Processing #case :" + str(case_number) + # Robots = " + str(len(robots)) + " #polygons = " + str(len(polygons))) polygon_objs = [] for polygon in polygons: poly = [] for p in polygon: poly.append(vg.Point(p[0], p[1])) polygon_objs.append(poly) graph = vg.VisGraph() # graph.load('case' + str(case_number) + '.pk1') graph.build(polygon_objs) path_map = [[None for i in range(len(robots))] for j in range(len(robots))] for i, s in enumerate(robots): for j, d in enumerate(robots): if i != j and j > i: source, dest = vg.Point(s[0], s[1]), vg.Point(d[0], d[1]) path_map[i][j] = graph.shortest_path(source, dest) ret_map = [] for i in range(len(robots)): new_array = [] for j in range(len(robots)): pts = [] if j == i: pass elif j < i: pts = list(reversed(ret_map[j][i])) else: for p in path_map[i][j]: pts.append([p.x, p.y]) new_array.append(pts) ret_map.append(new_array) # return ret_map robot_paths = make_decisions(ret_map) return robot_paths
def __init__(self, index, points, obstacles): self.index = index self.points = points obstacle_points = [] for o in obstacles: ob = [] for p in o: ob.append(vg.Point(p[0], p[1])) obstacle_points.append(ob) _g = vg.VisGraph() _g.build(obstacle_points, workers=cpu_count()) self._g = _g
def getPathWaypoints(self, startPoint, endPoint): if startPoint is None or startPoint[0] is None or startPoint[1] is None: return None graph = vg.VisGraph() obstacles = mergePolygons(self.cSpaceObstacles) finalObs = [] for obs in obstacles: #print("OBS", obs) obstacleData = [] for p in obs: try: x = p[0] y = p[1] obstacleData.append(vg.Point(x, y)) except: pass finalObs.append(obstacleData) self.obstacleCorners = [] for obstacle in finalObs: for pt in obstacle: self.obstacleCorners.append([pt.x, pt.y]) self.obstacleCorners = np.array(self.obstacleCorners, dtype=np.float32) try: graph.build(finalObs) self.graph = graph self.origin = vg.Point(startPoint[0], startPoint[1]) self.dest = vg.Point(endPoint[0], endPoint[1]) path = graph.shortest_path(vg.Point(startPoint[0], startPoint[1]), vg.Point(endPoint[0], endPoint[1])) return [(p.x, p.y) for p in path] except: return [startPoint]
def graph(polygons, robots): polys = [] temp = [] shortest = [] z = len(robots) - 1 for x in polygons: for a, b in x: # print a, "then", b temp.append(vg.Point(a, b)) polys.append(temp) temp = [] # print polys g = vg.VisGraph() g.build(polys) shortest = g.shortest_path((vg.Point(robots[0][0], robots[0][1])), (vg.Point(robots[1][0], robots[1][1]))) for i in xrange(1, len(robots) - 1, 1): # print i # shortest.pop() shortest += g.shortest_path( (vg.Point(robots[i][0], robots[i][1])), (vg.Point(robots[i + 1][0], robots[i + 1][1]))) print shortest
def main(): graph = vg.VisGraph() graph.load('ntu_new_2') start = map(float, raw_input('Start: ').strip().split()) end = map(float, raw_input('End: ').strip().split()) shortest_path = graph.shortest_path(vg.Point(start[0], start[1]), vg.Point(end[0], end[1])) x = [point.x for point in shortest_path] y = [point.y for point in shortest_path] pyplot.plot(x, y) m = open('newMap_2.txt') for line in m: points = (line.strip()).split(',') x = [] y = [] for point in points: point = map(float, point.split()) x.append(point[0]) y.append(point[1]) x.append(x[0]) y.append(y[0]) pyplot.plot(x, y) pyplot.show()
def CreatePs(): all_points = [] Counterforall_points = 0 for i in range(5): while (Counterforall_points < 5): #Set up the boundary of the random points min_x = po.bounds[0] max_x = po.bounds[2] min_y = po.bounds[1] max_y = po.bounds[3] generateddata=[min_x + (max_x - min_x)*random.random(), min_y + (max_y - min_y)*random.random()] if po.convex_hull.contains(Point(generateddata)) == True: if g.point_in_polygon(vg.Point(generateddata[0], generateddata[1])) == -1: if not generateddata in all_points: all_points.append(generateddata) Counterforall_points = Counterforall_points + 1 return all_points
def getPath(movingRobot, sleepingRobot): polys = [] for ob in obs: polygon = [] for coords in ob: polygon.append(vg.Point(*coords)) polys.append(polygon) g = vg.VisGraph() g.build(polys) paths = [] path = shortest = g.shortest_path(movingRobot, sleepingRobot) # Finds the path between the nodes from the start robot to all the other robots and appends the path to paths # for robot in sleepingRobots: # path = shortest = g.shortest_path(movingRobot, robot) # paths.append(path) return path
def computeVisibilityGraph(contoursMapped): """Given the dilated obstacles, compute the visibility graph Parameters ---------- contoursMapped : list of list of list There are several dilated obstacles Each one has several extremities Each extremity has (x, y) coordinates Returns ------- g : object of class Graph the visibility graph of our problem possibleDisplacement : dictionary key : tuple containing (x,y) coordinates of one of the edges of the dilated obstacles value : list of all other edges visible from the key edge """ # Compute the visibility graph polys = [[] for _ in contoursMapped] for obstacle, i in zip(contoursMapped, range(len(contoursMapped))): for extremity in obstacle: polys[i].append(vg.Point(extremity[X], extremity[Y])) g = vg.VisGraph() g.build(polys) # Create a dictionary where each extremety point has several visible points i.e possible destinations possibleDisplacement = {} for obstacle, i in zip(contoursMapped, range(len(contoursMapped))): for extremity, j in zip(obstacle, range(len(obstacle))): visible = g.find_visible(polys[i][j]) possibleDisplacement[(extremity[X], extremity[Y])] = [[point.x, point.y] for point in visible] visible.clear() return g, possibleDisplacement
def InterestPointInObstacle(interestPoints, graph): """Given the visibility graph and the points of interest Says if some interest points are in the dilated obstacles or not Parameters ---------- interestPoints : list of list Each point of interest has (x, y) coordinates, i.e locations where the thymio need to go graph : object of class Graph the visibility graph of our problem Returns ------- a boolean : True if some point of interest are located in the dilated obstacles False if none of the interest points are located in the dilated obstacles """ for point in interestPoints: if graph.point_in_polygon(vg.Point(point[X], point[Y])) != -1: return True return False
line = line.strip('\n') lenstr = len(line) if lenstr != 0: polygons.append(line) robotpoints = list(literal_eval(robots[0])) drawRobots(robotpoints) polygonpoints = list(literal_eval(polygons[0])) drawPolygons(polygonpoints) polys = [] for arraypoly in polygonpoints: #adding poygons to the vg temp = [] for (x, y) in arraypoly: temp.append(vg.Point(x, y)) polys.append(temp) g = vg.VisGraph() g.build(polys) paths = [] for (x, y) in robotpoints: #finding shortest path between any two vertices for (a, b) in robotpoints: shortest = g.shortest_path(vg.Point(x, y), vg.Point(a, b)) paths.append(shortest) print paths for path in paths: #drawing the visibility graph
def Op_ABC(C_all_points): #len(C_all_points) = 10 (2 * Num_of_Points) # for i in range(len(C_all_points)/2): # i = i * 2 # print C_all_points[i],',',C_all_points[i+1] # print ' ' #Point in Polygon? for i in range(len(C_all_points) / 2): i = i * 2 if g.point_in_polygon( vg.Point(C_all_points[i], C_all_points[i + 1])) == -1: pass else: return float('inf') #change[a,b,c,d] to [[a,b],[c,d]] CABC_all_points = [] for i in range(len(C_all_points) / 2): i = i * 2 Temp_CABC = [C_all_points[i], C_all_points[i + 1]] CABC_all_points.append(Temp_CABC) ap = [Point(p) for p in CABC_all_points] co = [LRF_(p.x, p.y, Radius) for p in ap] #A: The intersect part of path coverage (Enclude polygons) Sa = getIntersection(co).area #B: The rest of the map's area except path coverage Sb = getUnscanned(co).area #C: The shortest distance def Dis_PosC(x): Dist_ = 0 Store_Comb = [] Permutation_list = [] list_ = [] for i in range(len(C_all_points) / 2): list_.append(i) list_Num = len(list_) x_list = [] for i in range(len(C_all_points) / 2): x[i] = math.floor(x[i]) x_list.append(int(round(x[i]))) for i in range(list_Num): Permutation_list.append(list_[x_list[i]]) del list_[x_list[i]] # for i in range(len(C_all_points)/2): # print Permutation_list[i] # print ' ' for i in range(len(C_all_points) / 2): Store_Comb.append(CABC_all_points[Permutation_list[i]]) for i in range(len(C_all_points) / 2 - 1): Dis_0 = vg.Point(Store_Comb[i][0], Store_Comb[i][1]) Dis_1 = vg.Point(Store_Comb[i + 1][0], Store_Comb[i + 1][1]) Dist = g.shortest_path(Dis_0, Dis_1) _Dist_ = LineString(sp2list(Dist)).length Dist_ = Dist_ + _Dist_ return Dist_ New_Nearest_Dis = [] lb_C = [] ub_C = [] for i in range(len(C_all_points) / 2): lb_C.append(0.1) ub_C.append(len(C_all_points) / 2 - i - 0.1) xopt_C, fopt_C = pso(Dis_PosC, lb_C, ub_C, maxiter=5) for i in range(len(C_all_points) / 2): New_Nearest_Dis.append(xopt_C[i]) #A + B + C Cal_Op_ABC = Sa + Sb + fopt_C return Cal_Op_ABC
def P2list(P): vc = [] for p in P: vc.append(vg.Point(p[0], p[1])) return vc
for i in range(len(Adjust_x[0]) / 2): list_.append(i) list_Num = len(list_) x_list = [] for i in range(len(Adjust_x[0]) / 2): Temp_x = math.floor(xopt_Ax[i]) x_list.append(int(round(Temp_x))) for i in range(list_Num): Permutation_list.append(list_[x_list[i]]) del list_[x_list[i]] for i in range(len(Adjust_x[0]) / 2): Store_Comb.append(CABC_all_points[Permutation_list[i]]) Plot_Store_Dist = [] for i in range(len(Store_Comb) - 1): Dis_0 = vg.Point(Store_Comb[i][0], Store_Comb[i][1]) Dis_1 = vg.Point(Store_Comb[i + 1][0], Store_Comb[i + 1][1]) Dist = g.shortest_path(Dis_0, Dis_1) del Dist[len(Dist) - 1] for p in Dist: Plot_Store_Dist.append((p.x, p.y)) Plot_Store_Dist.append(Store_Comb[len(Store_Comb) - 1]) Plot_Poly_(po, Plot_Store_Dist, 'ttt') ap = [Point(p_Op) for p_Op in Store_Comb] co = [LRF_(p_Op.x, p_Op.y, Radius) for p_Op in ap] Plot_Polyv3(po, co, Plot_Store_Dist, 'yyy')