def __init__(self, filepath, agent, num_guppy_bins, num_wall_rays, livedata, simulation=False): # set up data self.filepath = filepath with h5py.File(filepath, "r") as hdf_file: self.ls = list(hdf_file.keys()) self.num_guppys = len(self.ls) if not livedata: self.data = [numpy.array(hdf_file.get("{}".format(i))) for i in range(self.num_guppys)] else: self.data = [numpy.array(hdf_file.get("{}".format(i + 1))) for i in range(self.num_guppys)] self.agent = agent self.agent_data = self.data[agent] self.length = len(self.agent_data) self.num_bins = num_guppy_bins self.num_rays = num_wall_rays self.bin_angles = [agent_view_field * (i / self.num_bins) - (agent_view_field - pi) / 2 - pi / 2 for i in range(0, self.num_bins + 1)] #self.bin_angles = [pi * (i / self.num_bins) - pi / 2 for i in range(0, self.num_bins + 1)] self.wall_angles = [agent_view_field * (i / self.num_rays) - (agent_view_field - pi) / 2 - pi / 2 for i in range(0, self.num_rays)] #self.wall_angles = [pi * (i / self.num_rays) - pi / 2 for i in range(0, self.num_rays)] self.simulation = simulation if simulation: self.fig, self.ax = pyplot.subplots() self.ax.set_title('tank') set_limits(self.ax, 0, 100, 0, 100)
def drawDisjointSet(D,sinks): fig = plt.figure() ax = fig.add_subplot(111) ax.set_title('Disjoint Set of BF-WSN nodes') col = ['r','g','b','y'] D_num = np.shape(D)[0] sinks_num = np.shape(sinks)[0] for i in range(D_num): nodes_num = np.shape(D[i])[0] for j in range(nodes_num): patch = PolygonPatch(Point(D[i][j]['centre']).buffer(D[i][j]['radius']), fc=col[i], ec=col[i], alpha=0.5, zorder=1) ax.add_patch(patch) for i in range(sinks_num): patch = PolygonPatch(Point(sinks[i]).buffer(10),fc='k', ec='k', alpha=0.2, zorder=1) ax.add_patch(patch) """x1 = list(nodes[:, 0]) y1 = list(nodes[:, 1]) ax.scatter(x1, y1, s=20, color=col[i], marker='o') #for a, b in zip(x1, y1): # ax.text(a, b, (a, b), ha='center', va='bottom', fontsize=10)""" set_limits(ax, 0, 50, 0, 50) plt.savefig('Disjoint Set of BF-WSN nodes.jpg') plt.legend() plt.show()
def drawSingleDisjointSet(D): fig = plt.figure() ax1 = fig.add_subplot(131) ax1.set_title('Disjoint Set 1') col = ['r','g','b','y'] i = 0 nodes_num = np.shape(D[i])[0] for j in range(nodes_num): patch = PolygonPatch(Point(D[i][j]['centre']).buffer(D[i][j]['radius']), fc=col[i], ec=col[i], alpha=0.5, zorder=1) ax1.add_patch(patch) set_limits(ax1, 0, 50, 0, 50) ax2 = fig.add_subplot(132) ax2.set_title('Disjoint Set 2') col = ['r', 'g', 'b', 'y'] i = 1 nodes_num = np.shape(D[i])[0] for j in range(nodes_num): patch = PolygonPatch(Point(D[i][j]['centre']).buffer(D[i][j]['radius']), fc=col[i], ec=col[i], alpha=0.5, zorder=1) ax2.add_patch(patch) set_limits(ax2, 0, 50, 0, 50) ax3 = fig.add_subplot(133) ax3.set_title('Disjoint Set 3') col = ['r', 'g', 'b', 'y'] i = 2 nodes_num = np.shape(D[i])[0] for j in range(nodes_num): patch = PolygonPatch(Point(D[i][j]['centre']).buffer(D[i][j]['radius']), fc=col[i], ec=col[i], alpha=0.5, zorder=1) ax3.add_patch(patch) set_limits(ax3, 0, 50, 0, 50) plt.savefig('Disjoint Single Set of BF-WSN nodes.jpg') plt.legend() plt.show()
from matplotlib import pyplot from descartes.patch import PolygonPatch from figures import SIZE, BLUE, RED, set_limits invalid_poly = Polygon([(0, 0), (0, 2), (1, 1), (2, 2), (2, 0), (1, 1), (0, 0)]) valid_poly = make_valid(invalid_poly) fig = pyplot.figure(1, figsize=SIZE, dpi=90) fig.set_frameon(True) invalid_ax = fig.add_subplot(121) patch = PolygonPatch(invalid_poly, facecolor=BLUE, edgecolor=BLUE, alpha=0.5, zorder=2) invalid_ax.add_patch(patch) set_limits(invalid_ax, -1, 3, -1, 3) valid_ax = fig.add_subplot(122) patch = PolygonPatch(valid_poly[0], facecolor=BLUE, edgecolor=BLUE, alpha=0.5, zorder=2) valid_ax.add_patch(patch) patch = PolygonPatch(valid_poly[1], facecolor=RED, edgecolor=RED, alpha=0.5, zorder=2) valid_ax.add_patch(patch) set_limits(valid_ax, -1, 3, -1, 3) pyplot.show()
ax_range = [int(line_bounds[0] - 1.0), int(line_bounds[2] + 1.0)] ay_range = [int(line_bounds[1] - 1.0), int(line_bounds[3] + 1.0)] fig = pyplot.figure(1, figsize=(SIZE[0], 2 * SIZE[1]), dpi=90) # 1 ax = fig.add_subplot(221) plot_line(ax, line) x, y = list(line.coords)[0] plot_coords(ax, x, y) offset = line.parallel_offset(0.5, 'left', join_style=1) plot_line(ax, offset, color=BLUE) ax.set_title('a) left, round') set_limits(ax, ax_range[0], ax_range[1], ay_range[0], ay_range[1]) #2 ax = fig.add_subplot(222) plot_line(ax, line) x, y = list(line.coords)[0] plot_coords(ax, x, y) offset = line.parallel_offset(0.5, 'left', join_style=2) plot_line(ax, offset, color=BLUE) ax.set_title('b) left, mitred') set_limits(ax, ax_range[0], ax_range[1], ay_range[0], ay_range[1]) #3
# If one need to rotate it clockwise along an upward pointing x axis: elrv = shapely.affinity.rotate(ell, 90 - ellipse[2]) # According to the man, a positive value means a anti-clockwise angle, # and a negative one a clockwise angle. ellipse2 = ((-4, -4), (7, 4), 140) circ2 = shapely.geometry.Point(ellipse2[0]).buffer(1) ell2 = shapely.affinity.scale(circ2, int(ellipse2[1][0]), int(ellipse2[1][1])) ellr2 = shapely.affinity.rotate(ell2, ellipse2[2]) elrv2 = shapely.affinity.rotate(ell2, 90 - ellipse2[2]) inter = elrv.intersection(elrv2) fig = pyplot.figure() fig2 = pyplot.figure() ax = fig.add_subplot(111) ax2 = fig2.add_subplot(111) patch = PolygonPatch(elrv, fc=GREEN, ec=GRAY, alpha=0.5, zorder=2) patch2 = PolygonPatch(elrv2, fc=GREEN, ec=GRAY, alpha=0.5, zorder=2) ax.add_patch(patch) ax.add_patch(patch2) interPatch = PolygonPatch(inter, fc=GREEN, ec=GRAY, alpha=0.5, zorder=2) ax2.add_patch(interPatch) set_limits(ax, -10, 10, -10, 10) set_limits(ax2, -10, 10, -10, 10) fig.savefig('elipses.png') fig2.savefig('intersection.png')
from figures import SIZE, BLUE, GRAY, set_limits polygons = [Point(i, 0).buffer(0.7) for i in range(5)] fig = pyplot.figure(1, figsize=SIZE, dpi=90) # 1 ax = fig.add_subplot(121) for ob in polygons: p = PolygonPatch(ob, fc=GRAY, ec=GRAY, alpha=0.5, zorder=1) ax.add_patch(p) ax.set_title('a) 多边形', fontproperties=font_song) set_limits(ax, -2, 6, -2, 2) # 2 ax = fig.add_subplot(122) u = cascaded_union(polygons) patch2b = PolygonPatch(u, fc=GRAY, ec=GRAY, alpha=0.5, zorder=2) ax.add_patch(patch2b) ax.set_title('b) 合并结果', fontproperties=font_song) set_limits(ax, -2, 6, -2, 2) # pyplot.show() import os
plot_line(ax, line, color=color, alpha=0.7, zorder=2) fig = pyplot.figure(1, figsize=SIZE, dpi=90) # 1: disconnected multilinestring ax = fig.add_subplot(121) mline1 = MultiLineString([((0, 0), (1, 1)), ((0, 2), (1, 1.5), (1.5, 1), (2, 0))]) plot_coords(ax, mline1) plot_bounds(ax, mline1) plot_lines(ax, mline1) ax.set_title('a) simple') set_limits(ax, -1, 3, -1, 3) #2: invalid self-touching ring ax = fig.add_subplot(122) mline2 = MultiLineString([((0, 0), (1, 1), (1.5, 1)), ((0, 2), (1, 1.5), (1.5, 1), (2, 0))]) plot_coords(ax, mline2) plot_bounds(ax, mline2) plot_lines(ax, mline2) ax.set_title('b) complex') set_limits(ax, -1, 3, -1, 3) pyplot.show()
fig = pyplot.figure(1, figsize=SIZE, dpi=90) fig.set_frameon(True) # 1 ax = fig.add_subplot(121) points2 = MultiPoint([(0, 0), (2, 2)]) for p in points2: ax.plot(p.x, p.y, 'o', color=GRAY) hull2 = points2.convex_hull plot_line(ax, hull2, color=BLUE, alpha=0.5, zorder=2) ax.set_title('a) N = 2') set_limits(ax, -1, 4, -1, 3) #2 ax = fig.add_subplot(122) points1 = MultiPoint([(0, 0), (1, 1), (0, 2), (2, 2), (3, 1), (1, 0)]) for p in points1: ax.plot(p.x, p.y, 'o', color=GRAY) hull1 = points1.convex_hull patch1 = PolygonPatch(hull1, facecolor=BLUE, edgecolor=BLUE, alpha=0.5, zorder=2) ax.add_patch(patch1) ax.set_title('b) N > 2') set_limits(ax, -1, 4, -1, 3)
from figures import SIZE, BLUE, GRAY, set_limits, plot_line, add_origin fig = pyplot.figure(1, figsize=SIZE, dpi=90) line = LineString([(1, 3), (1, 1), (4, 1)]) # 1 ax = fig.add_subplot(121) plot_line(ax, line, GRAY) plot_line(ax, affinity.rotate(line, 90, 'center'), BLUE) add_origin(ax, line, 'center') ax.set_title(u"90\N{DEGREE SIGN}, default origin (center)") set_limits(ax, 0, 5, 0, 4) # 2 ax = fig.add_subplot(122) plot_line(ax, line, GRAY) plot_line(ax, affinity.rotate(line, 90, 'centroid'), BLUE) add_origin(ax, line, 'centroid') ax.set_title(u"90\N{DEGREE SIGN}, origin='centroid'") set_limits(ax, 0, 5, 0, 4) pyplot.show()
fig = plt.figure(1, figsize=SIZE, dpi=90) fig.set_frameon(True) # 1 ax = fig.add_subplot(121) mp = MultiPoint([(0, 0), (0.5, 1.5), (1, 0.5), (0.5, 0.5)]) rect = mp.minimum_rotated_rectangle for p in mp: ax.plot(p.x, p.y, 'o', color=GRAY) patch = PolygonPatch(rect, facecolor=BLUE, edgecolor=BLUE, alpha=0.5, zorder=2) ax.add_patch(patch) ax.set_title('a) MultiPoint') set_limits(ax, -1, 2, -1, 2) # 2 ax = fig.add_subplot(122) ls = LineString([(-0.5, 1.2), (0.5, 0), (1, 1), (1.5, 0), (1.5, 0.5)]) rect = ls.minimum_rotated_rectangle ax.plot(*ls.xy, color=DARKGRAY, linewidth=3, alpha=0.5, zorder=2) patch = PolygonPatch(rect, facecolor=BLUE, edgecolor=BLUE, alpha=0.5, zorder=2) ax.add_patch(patch) set_limits(ax, -1, 2, -1, 2) ax.set_title('b) LineString') plt.show()
def gen_macros_for_fence_region(macro_pos_x, macro_pos_y, macro_size_x, macro_size_y, regions, xl, xh, yl, yh, merge=False, plot=False): # tt = time.time() macros = MultiPolygon([ box( macro_pos_x[i], macro_pos_y[i], macro_pos_x[i] + macro_size_x[i], macro_pos_y[i] + macro_size_y[i], ) for i in range(macro_size_x.size(0)) ]) # print("macro:", time.time()-tt) # tt = time.time() num_boxes = regions.size(0) regions = regions.view(num_boxes, 2, 2) fence_regions = MultiPolygon([ box(regions[i, 0, 0], regions[i, 0, 1], regions[i, 1, 0], regions[i, 1, 1]) for i in range(num_boxes) ]) site = box(xl, yl, xh, yh) reverse = site.difference(fence_regions).union(macros) # print("fence region:", time.time()-tt) # tt = time.time() slices = [] xs = torch.cat( [regions[:, :, 0].view(-1), macro_pos_x, macro_pos_x + macro_size_x], dim=0).sort()[0] for i in range(xs.size(0) + 1): x_l = xl if i == 0 else xs[i - 1] x_h = xh if i == xs.size(0) else xs[i] cvx_hull = box(x_l, yl, x_h, yh) intersect = reverse.intersection(cvx_hull) if isinstance(intersect, Polygon): slices.append(intersect.bounds) elif isinstance(intersect, (GeometryCollection, MultiPolygon)): slices.extend( [j.bounds for j in intersect if (isinstance(j, Polygon))]) # print("slicing:", time.time()-tt) # tt = time.time() if merge: raw_bbox_list = sorted(slices, key=lambda x: (x[1], x[0])) cur_bbox = None bbox_list = [] for i, p in enumerate(raw_bbox_list): minx, miny, maxx, maxy = p if cur_bbox is None: cur_bbox = [minx, miny, maxx, maxy] elif cur_bbox[1] == miny and cur_bbox[3] == maxy: cur_bbox[2:] = p[2:] else: bbox_list.append(cur_bbox) cur_bbox = [minx, miny, maxx, maxy] else: bbox_list.append(cur_bbox) else: bbox_list = slices # print("merge:", time.time()-tt) bbox_list = torch.tensor(bbox_list).float() pos_x = bbox_list[:, 0] pos_y = bbox_list[:, 1] node_size_x = bbox_list[:, 2] - bbox_list[:, 0] node_size_y = bbox_list[:, 3] - bbox_list[:, 1] if plot: from descartes.patch import PolygonPatch from matplotlib import pyplot as plt from figures import BLUE, SIZE, color_isvalid, plot_coords, set_limits res = [] for bbox in bbox_list: res.append(box(*bbox)) res = MultiPolygon(res) fig = plt.figure(1, figsize=SIZE, dpi=90) ax = fig.add_subplot(121) for polygon in res: # plot_coords(ax, polygon.exterior) patch = PolygonPatch( polygon, facecolor=color_isvalid(fence_regions), edgecolor=color_isvalid(fence_regions, valid=BLUE), alpha=0.5, zorder=2, ) ax.add_patch(patch) set_limits(ax, -1, 20, -1, 20) ax = fig.add_subplot(122) patch = PolygonPatch( reverse, facecolor=color_isvalid(reverse), edgecolor=color_isvalid(reverse, valid=BLUE), alpha=0.5, zorder=2, ) ax.add_patch(patch) set_limits(ax, -1, 20, -1, 20) plt.savefig("polygon.png") return pos_x, pos_y, node_size_x, node_size_y
def slice_non_fence_region( regions, xl, yl, xh, yh, macro_pos_x=None, macro_pos_y=None, macro_size_x=None, macro_size_y=None, merge=False, plot=False, figname="non_fence_region.png", device=torch.device("cuda:0"), ): if type(regions) == list: if isinstance(regions[0], np.ndarray): regions = torch.from_numpy(np.concatenate(regions, 0)).to(device) elif isinstance(regions[0], torch.Tensor): regions = torch.cat(regions, dim=0).to(device) # [n_box, 4] elif isinstance(regions, np.ndarray): regions = torch.from_numpy(regions).to(device) if macro_pos_x is not None: if isinstance(macro_pos_x, np.ndarray): macro_pos_x = torch.from_numpy(macro_pos_x).to(device).float() macro_pos_y = torch.from_numpy(macro_pos_y).to(device).float() macro_size_x = torch.from_numpy(macro_size_x).to(device).float() macro_size_y = torch.from_numpy(macro_size_y).to(device).float() regions = torch.cat( [ regions, torch.stack([ macro_pos_x, macro_pos_y, macro_pos_x + macro_size_x, macro_pos_y + macro_size_y ], 0).t(), ], 0, ) num_boxes = regions.size(0) regions = regions.view(num_boxes, 2, 2) fence_regions = MultiPolygon([ box(regions[i, 0, 0], regions[i, 0, 1], regions[i, 1, 0], regions[i, 1, 1]) for i in range(num_boxes) ]) fence_regions = unary_union(fence_regions) site = box(xl, yl, xh, yh) non_fence_region = unary_union(site.difference(fence_regions)) slices = [] xs = regions[:, :, 0].view(-1).sort()[0] for i in range(xs.size(0) + 1): x_l = xl if i == 0 else xs[i - 1] x_h = xh if i == xs.size(0) else xs[i] cvx_hull = box(x_l, yl, x_h, yh) if x_l >= x_h or not cvx_hull.is_valid: continue intersect = non_fence_region.intersection(cvx_hull) if isinstance(intersect, Polygon) and len(intersect.bounds) == 4: slices.append(intersect.bounds) elif isinstance(intersect, (GeometryCollection, MultiPolygon)): slices.extend([ j.bounds for j in intersect if (isinstance(j, Polygon) and len(j.bounds) == 4) ]) if merge: raw_bbox_list = sorted(slices, key=lambda x: (x[1], x[0])) cur_bbox = None bbox_list = [] for i, p in enumerate(raw_bbox_list): minx, miny, maxx, maxy = p if cur_bbox is None: cur_bbox = [minx, miny, maxx, maxy] elif cur_bbox[1] == miny and cur_bbox[3] == maxy and cur_bbox[ 2] == minx: cur_bbox[2:] = p[2:] else: bbox_list.append(cur_bbox) cur_bbox = [minx, miny, maxx, maxy] else: bbox_list.append(cur_bbox) else: bbox_list = slices if plot: from descartes.patch import PolygonPatch from matplotlib import pyplot as plt # from figures import BLUE, SIZE, set_limits, plot_coords, color_isvalid res = [] bbox_list_np = np.array(bbox_list) bbox_list_np *= 1000 / np.max(bbox_list_np) for bbox in bbox_list_np: res.append(box(*bbox.tolist())) res = MultiPolygon(res) fig = plt.figure(1, figsize=SIZE, dpi=90) ax = fig.add_subplot(121) for polygon in res: # plot_coords(ax, polygon.exterior) patch = PolygonPatch( polygon, facecolor=color_isvalid(non_fence_region), edgecolor=color_isvalid(non_fence_region, valid=BLUE), alpha=0.5, zorder=2, ) ax.add_patch(patch) set_limits(ax, -1, 1000, -1, 1000, dx=100, dy=100) # ax = fig.add_subplot(122) # patch = PolygonPatch(non_fence_region, facecolor=color_isvalid( # non_fence_region), edgecolor=color_isvalid(non_fence_region, valid=BLUE), alpha=0.5, zorder=2) # ax.add_patch(patch) # set_limits(ax, -1, 1000, -1, 1000, dx=100, dy=100) plt.savefig(figname) plt.close() bbox_list = torch.tensor(bbox_list, device=device) # print("non fence region area after slicing:", ((bbox_list[:,2]-bbox_list[:,0])*(bbox_list[:,3]-bbox_list[:,1])).sum().item()) return bbox_list
from figures import SIZE, BLUE, GRAY, set_limits polygons = [Point(i, 0).buffer(0.7) for i in range(5)] fig = pyplot.figure(1, figsize=SIZE, dpi=90) # 1 ax = fig.add_subplot(121) for ob in polygons: p = PolygonPatch(ob, fc=GRAY, ec=GRAY, alpha=0.5, zorder=1) ax.add_patch(p) ax.set_title('a) polygons') set_limits(ax, -2, 6, -2, 2) #2 ax = fig.add_subplot(122) u = cascaded_union(polygons) patch2b = PolygonPatch(u, fc=BLUE, ec=BLUE, alpha=0.5, zorder=2) ax.add_patch(patch2b) ax.set_title('b) union') set_limits(ax, -2, 6, -2, 2) pyplot.show()
b = Point(2, 1).buffer(1.5) # 1 ax = fig.add_subplot(121) patch1 = PolygonPatch(a, fc=GRAY, ec=GRAY, alpha=0.2, zorder=1) ax.add_patch(patch1) patch2 = PolygonPatch(b, fc=GRAY, ec=GRAY, alpha=0.2, zorder=1) ax.add_patch(patch2) c = a.union(b) patchc = PolygonPatch(c, fc=BLUE, ec=BLUE, alpha=0.5, zorder=2) ax.add_patch(patchc) ax.set_title('a.union(b)') set_limits(ax, -1, 4, -1, 3) def plot_line(ax, ob, color=GRAY): x, y = ob.xy ax.plot(x, y, color, linewidth=3, solid_capstyle='round', zorder=1) #2 ax = fig.add_subplot(122) plot_line(ax, a.exterior) plot_line(ax, b.exterior) u = a.exterior.union(b.exterior) if u.geom_type in ['LineString', 'LinearRing', 'Point']: plot_line(ax, u, color=BLUE) elif u.geom_type is 'MultiLineString':
from descartes.patch import PolygonPatch from matplotlib import pyplot def point_in_area(point, triangles): for triangle in triangles: if point.within(triangle): return True return False if __name__ == '__main__': # Create plot fig = pyplot.figure(1, figsize=SIZE, dpi=90) ax = fig.add_subplot(121) set_limits(ax, 0, 5, 0, 5) # Create polygon array = [[1, 2], [5, 3], [3, 3], [3, 4]] polygon = Polygon(array) points = MultiPoint([(1, 2), (5, 3), (3, 3), (3, 4), (1, 4)]) triangles = triangulate(points) # Display triangles for triangle in triangles: patch = PolygonPatch(triangle, alpha=0.5, zorder=2) ax.add_patch(patch) # Display polygon # patch = PolygonPatch(polygon, alpha=0.5, zorder=2)
patch1a = PolygonPatch(R, facecolor=GRAY, edgecolor=GRAY, alpha=0.5, zorder=1) skewR = affinity.skew(R, xs=20, origin=(1, 1)) patch1b = PolygonPatch(skewR, facecolor=BLUE, edgecolor=BLUE, alpha=0.5, zorder=2) ax.add_patch(patch1a) ax.add_patch(patch1b) add_origin(ax, R, (1, 1)) ax.set_title("a) xs=20, origin(1, 1)") set_limits(ax, 0, 5, 0, 4) # 2 ax = fig.add_subplot(122) patch2a = PolygonPatch(R, facecolor=GRAY, edgecolor=GRAY, alpha=0.5, zorder=1) skewR = affinity.skew(R, ys=30) patch2b = PolygonPatch(skewR, facecolor=BLUE, edgecolor=BLUE, alpha=0.5, zorder=2) ax.add_patch(patch2a) ax.add_patch(patch2b) add_origin(ax, R, 'center')
# ax.plot(x, y, color=GREEN, alpha=0.5, linewidth=3, solid_capstyle='round', zorder=2) for x in lines: b = LineString(x) x, y = b.xy ax.plot(x, y, color=GRAY, alpha=0.5, linewidth=3, solid_capstyle='round', zorder=2) ax.set_title('a) 原始的5条线', fontproperties=font_song) set_limits(ax, -1, 3, -1, 3) # 1: disconnected multilinestring ax = fig.add_subplot(132) # plot_coords(ax, a) # plot_coords(ax, the_line) # x, y = a.xy # ax.plot(x, y, color=YELLOW, alpha=0.5, linewidth=3, solid_capstyle='round', zorder=2) for the_l in the_line: x, y = the_l.xy ax.plot(x, y, color=GRAY,