def pg_pix2latlon_strdf(im_name): # load the polygon data for each region poly_path = './shpres/%s.json'%(im_name) if not os.path.isfile(poly_path): #print 'no shape files', im_name exit() #print 'shift', shift_dict[im_name] rs, cs = shift_dict[im_name] pg = simplejson.load(open(poly_path)) #print pg exter = np.array(pg['ext']) exter[:,0] += cs exter[:,1] += rs ex_lonlat = pix2ll(exter,t) inters = pg['intlist'] inter_list = [] for inter in inters: np_inter = np.array(inter) np_inter[:,0] += cs np_inter[:,1] += rs np_inter = pix2ll(np_inter,t) inter_list.append(np_inter) pg_obj = Polygon(ex_lonlat, inter_list) print pg_obj.contains( Point(69.178746, 35.813774) )
def triangulate_area_in_closed_curve(bndry_pts,xmax,xmin,ymax,ymin,N,vector_map): polygon = Polygon(bndry_pts) interior_pts = [] dx = (xmax-xmin)/float(N+1) dy = (ymax-ymin)/float(N+1) x0 = xmin+dx y0 = ymin+dy for i in range(N): x = x0+float(i)*dx+random.uniform(-0.1,0.1) for j in range(N): y = y0+float(j)*dy+random.uniform(-0.1,0.1) pt = Point(x,y) if polygon.contains(pt): interior_pts.append((x,y)) surface_pts = bndry_pts+interior_pts simplices = core.Triangulation(surface_pts) triangles = simplices.get_elements() pts = simplices.get_set() (u1,u2,u3) = vector_map(pts) indices = simplices.get_elements_indices() reduced_indices = [] for index in indices: x1 = numpy.array(pts[index[0]]) x2 = numpy.array(pts[index[1]]) x3 = numpy.array(pts[index[2]]) xcg = (x1+x2+x3)/3.0 x1 = xcg+0.999*(x1-xcg) x2 = xcg+0.999*(x2-xcg) x3 = xcg+0.999*(x3-xcg) tmp = Polygon((x1,x2,x3)) if polygon.contains(tmp): reduced_indices.append(index) return(triangular_mesh(u1,u2,u3,reduced_indices,line_width=0.25,tube_radius=0.005,representation='fancymesh'))
def get_busses_in_box(self, key, lat1, lng1, lat2, lng2): cherrypy.response.headers["Access-Control-Allow-Origin"] = "*" coord1 = (float(lat1), float(lng1)) coord2 = (float(lat1), float(lng2)) coord3 = (float(lat2), float(lng2)) coord4 = (float(lat2), float(lng1)) rect = Polygon([coord1,coord2,coord3,coord4]) ourRoutes = [] city_data = [] with open(os.path.join(PATH, 'stops.pickle'), 'rb') as f: stops = pickle.load(f) for stopid, stop in stops.items(): point = Point(float(stop.lat), float(stop.lng)) if rect.contains(point): ourRoutes.extend(stop.routes) ten = [] while (len(ourRoutes) > 10): ten.append(ourRoutes.pop()) print ten if (len(ten) == 10): url = "http://www.ctabustracker.com/bustime/api/v1/getvehicles?key="+keys[0]+"&rt="+",".join(ten)+"&format=json&diagnostics=true&callback=" r = requests.get(url) i = 1 while (r.text.find("exceeded") != -1): url = "http://www.ctabustracker.com/bustime/api/v1/getvehicles?key="+keys[i]+"&rt="+",".join(ten)+"&format=json&diagnostics=true&callback=" r = requests.get(url) i = i+1 ten = [] j = r.json() for bus in j['bustime-response'][0]['vehicle']: city_data.append(bus) url = "http://www.ctabustracker.com/bustime/api/v1/getvehicles?key="+keys[0]+"&rt="+",".join(ourRoutes)+"&format=json&diagnostics=true&callback=" r = requests.get(url) i = 0 while (r.text.find("exceeded") != -1): url = "http://www.ctabustracker.com/bustime/api/v1/getvehicles?key="+keys[i]+"&rt="+",".join(ourRoutes)+"&format=json&diagnostics=true&callback=" r = requests.get(url) i = i+1 j = r.json() for bus in j['bustime-response'][0]['vehicle']: city_data.append(bus) ret_busses = [] for bus in city_data: point = Point(float(bus['lat']), float(bus['lon'])) if rect.contains(point): ret_busses.append(bus) return json.dumps(ret_busses)
class Block: def __init__( self, shp ): """ Build one Block object from the shapefile._Shape object """ self.bbox = box(*shp.bbox) self.polygon = Polygon(shp.points) self.count = {'total': 0} # type: value def containPoint( self, p ): """ return true if the point p happened within current Block """ if self.bbox.contains(p): if self.polygon.contains(p): return True return False @classmethod def createAllCAObjects( cls ): cls.casf = shapefile.Reader('data/ChiCA_gps/ChiCaGPS') cls.cas = {} shps = cls.casf.shapes() for idx, shp in enumerate(shps): tid = cls.casf.record(idx)[4] trt = Block(shp) cls.cas[int(tid)] = trt return cls.cas
def latlon2countycode(lat,lon): hits = [] try: # Return a list of all counties that match lon OR lat hits = list(idx.intersection((lon,lat,lon,lat))) if len(hits) == 1: # Exact match recno = hits[0] elif len(hits) > 1: # Multiple candidate counties # # For example, 42.66326054 -87.80922716 [3180, 3193] - either kenosha or racine county. for hitIdx in hits: # Search all counties in list county = shapes[hitIdx] poly = Polygon(county.points) if poly.contains(Point(lon,lat)): recno = hitIdx break else: continue else: # if DEBUG: # sys.stderr.write("Error: Latlon2countycode unexpected error. -1\n") recno = -1 except: # Lat/Lon don't match US county shapefiles recno = 0 return recno
def return_points_in_polygon(coordinates, polygon_boundaries): """ Receives a list of tuples of coordinates and returns those tuples that are contained within the boundaries of the polygon specified in polygon_boundaries :param coordinates :param polygon_boundaries :return contained_points """ #Verify that the inputs of the function are correct. if not (isinstance(coordinates,list) and isinstance(polygon_boundaries,list)): raise TypeError('List of tuples of coordinates is expected for coordinates and polygon_boundaries') for point in coordinates: if not (isinstance(point,list) or isinstance(point,tuple)): raise TypeError('Values in coordinates should be lists or tuples of coordinates') if len(point) != 2: raise ValueError('Each coordinate should be represented as a list or tuple of two values, lat and lon') for boundary_point in polygon_boundaries: if not (isinstance(boundary_point,list) or isinstance(boundary_point,tuple)): raise TypeError('Values in coordinates should be lists or tuples of coordinates') if len(boundary_point) != 2: raise ValueError('Each coordinate should be represented as a list or tuple of two values, lat and lon') polygon = Polygon(polygon_boundaries) contained_points = list() for point in coordinates: if polygon.contains(Point(point)): contained_points.append(point) return contained_points
def generate_zones(poly_points, lon_unit, lat_unit, lons, lats): poly = Polygon(poly_points) zones = {} geo_json = {"type": "FeatureCollection", "features": []} for i, lon in enumerate(lons): for j, lat in enumerate(lats): leftBottom, rightBottom = (lon, lat), (lon + lon_unit, lat) rightTop, leftTop = (lon + lon_unit, lat + lat_unit), (lon, lat + lat_unit) polyPoints_gps = [leftBottom, rightBottom, rightTop, leftTop, leftBottom] cCoor_gps = (lon + lon_unit / 2.0, lat + lat_unit / 2.0) zone_poly = Polygon(polyPoints_gps) if poly.contains(zone_poly): boundary_relation = zone.IN elif poly.intersects(zone_poly): boundary_relation = zone.INTERSECT else: boundary_relation = zone.OUT zones[(i, j)] = zone(boundary_relation, i, j, cCoor_gps, polyPoints_gps) feature = {"type":"Feature", "id": '%d#%d' % (i,j), "properties": {"cCoor_gps": cCoor_gps}, "geometry": {"type": "Polygon", "coordinates": [[leftBottom, rightBottom, rightTop, leftTop, leftBottom ]] } } geo_json["features"].append(feature) return zones, geo_json
def __create_grid(self): """ Create uniform grid over region. """ polygon_coords = self.__resample_polygon() # define polygon from polygon coords polygon = Polygon(polygon_coords) # get bounding box coordinates bounding_box = polygon.bounds min_lon = bounding_box[0] max_lon = bounding_box[2] min_lat = bounding_box[1] max_lat = bounding_box[3] # compute number of nodes along lat and lon n_lat = int(round((max_lat - min_lat) / self.grid_spacing)) + 1 n_lon = int(round((max_lon - min_lon) / self.grid_spacing)) + 1 # create grid of points inside polygon grid = [] for i in range(n_lat): for j in range(n_lon): lat = min_lat + i * self.grid_spacing lon = min_lon + j * self.grid_spacing p = shapelyPoint(lon,lat) if polygon.contains(p) or polygon.touches(p): grid.append((lon,lat)) return grid
def return_sample_list(num, regions, dist, scale): """ Return a list containing the position (x,y) of the samples. Output is a list of lists: the ith list contains samples for the ith region. """ sample_list = [] for index, region in enumerate(regions): min_x = min([region[i][0] for i in xrange(len(region))]) max_x = max([region[i][0] for i in xrange(len(region))]) min_y = min([region[i][1] for i in xrange(len(region))]) max_y = max([region[i][1] for i in xrange(len(region))]) poly = Polygon(region) region_samples = [] while len(region_samples) != num: if dist == "normal": candidate = (np.random.normal(loc = (min_x + max_x)/2, scale = scale), \ np.random.normal(loc = (min_y + max_y)/2, scale = scale)) if dist == "uniform": candidate = (np.random.uniform(min_x, max_x),np.random.uniform(min_y, max_y)) if poly.contains(Point(candidate)): region_samples.append(candidate) sample_list.append(region_samples) print "-done sampling-" return sample_list
def setStInShape(self,shpfile): """ Функция возвращает список станций попадающий в полигон(ы) из шэйпфайла файла """ import shapefile as shp import geocalc from shapely.geometry import Polygon,Point res=[] sf = shp.Reader(shpfile) for sp in sf.shapes(): res_tmp=[] lonmin,latmin,lonmax,latmax=sp.bbox lonmin,lonmax=geocalc.cLon(lonmin),geocalc.cLon(lonmax) if lonmin<0 or lonmax<0: polygonPoints=[[geocalc.cLon(cors[0]),cors[1]] for cors in sp.points] else: polygonPoints=sp.points poly=Polygon(polygonPoints) indsInBox=[ind for ind in self.stInds if lonmin<=geocalc.cLon(self.stMeta[ind]['lon'])<=lonmax and latmin<=self.stMeta[ind]['lat']<=latmax] for ind in indsInBox: lat,lon=self.stMeta[ind]['lat'], geocalc.cLon(self.stMeta[ind]['lon']) pnt=Point(lon,lat) if poly.contains(pnt): res_tmp.append(ind) res=res+res_tmp return list(set(res))
def intersectNodes(path, srs, projName, projSRS, isGridProject, gridResolution): j = [] isGridLine = False sf = shapefile.Reader(path) nodes = list(getShapelyNodes(projName)) for shape in sf.shapes(): shType = shape.shapeType # http://en.wikipedia.org/wiki/Shapefile#Shapefile_shape_format_.28.shp.29 if shType == 5: # Polygon sh = Polygon(shape.points) elif shType == 3: # Line if isGridProject: sh = LineString(shape.points) isGridLine = True else: pass else: consoleAppend('Unknown shape type %s. Continue without access' %shType) if srs != projSRS: sh = shapelyReproject(sh, srs, projSRS) if isGridLine: sh = sh.buffer(gridResolution) for node in nodes: if sh.contains(node[1]): # node.geom j.append(node[0]) # node.node_id return j if j else None
def pointinside(lat, lon, shapefile): # Verifica todos os pontos que estão dentro do polígono # http://streamhacker.com/2010/03/23/python-point-in-polygon-shapely/ # '/home/rodrigues/AmbientePython27/lib/python2.7/site-packages/PyFuncemeClimateTools/shp/pontos_ce.txt' # Ler os pontos do vértice e tranformar em um poligno poly = Polygon(shapefile) nlons = len(lon) nlats = len(lat) points_grid = [] lonlat_grid = [] array_bool = np.ones((nlats, nlons), dtype="bool") for xlon in range(0, nlons): for ylat in range(0, nlats): point = Point((lon[xlon], lat[ylat])) a = poly.contains(point) if a == True: array_bool[ylat, xlon] = False points_grid.append((ylat, xlon)) lonlat_grid.append((lat[ylat], lon[xlon])) return points_grid, lonlat_grid, array_bool
def goal(p): near_area = Polygon([ (p.ha - HA_STEP/2, p.de - DE_STEP/2), (p.ha - HA_STEP/2, p.de + DE_STEP/2), (p.ha + HA_STEP/2, p.de + DE_STEP/2), (p.ha + HA_STEP/2, p.de - DE_STEP/2), ]) return near_area.contains(p_1.point()) or near_area.touches(p_1.point()) # touches if point exactly on the grid
def get_shp_index(im_name,debug=False,folder='./rawdata'): shp_path = './shp/%s.shp'%(im_name) im_path = '%s/%s'%(folder,im_name) # get the pos for the good_label fg_mask = get_fg_mask(im_path) if debug: plt.imshow(fg_mask) plt.show() sr = shapefile.Reader(shp_path) shapes = sr.shapes() pg_list = [] max_score = -1 for i,shape in enumerate(shapes): tmp_pts = np.array(shape.points) old_ci,c_i,first_poly = -1,0, True exter = None inter = [] for j in range(tmp_pts.shape[0]): if j == c_i: continue v = tmp_pts[j,:] - tmp_pts[c_i,:] d = np.sqrt(np.dot(v,v)) if d <= 0.5: old_ci = c_i c_i = j+1 plt.plot(tmp_pts[old_ci:c_i,0], tmp_pts[old_ci:c_i,1]) if first_poly: exter = tmp_pts[old_ci:c_i,:] first_poly = False else: # TODO, if area less than 4*4, then remove tmp_pg = Polygon( tmp_pts[old_ci:c_i,:] ) if tmp_pg.area > 4*4: inter.append( tmp_pts[old_ci:c_i,:] ) pg = Polygon( exter, inter) if pg.area < 16: pg_list.append(None) continue pg_list.append(pg) score = 0 print fg_mask.shape[0], fg_mask.shape[1] for ii in range(fg_mask.shape[0]): for jj in range(fg_mask.shape[1]): # NOTE, the Point with first dimension as col, second dimension as row try: if fg_mask[ii,jj] and pg.contains( Point(jj,ii)): score += 1 except Exception as e: print e print i, score, pg.area if score > max_score: max_score = score mi = i print 'max score',max_score, mi return mi, pg_list
def in_poly(point, poly): polygon = Polygon(poly.points) if poly.orientation: c = polygon.centroid.coords[0] polygon = Polygon([rotate(p, c, -poly.orientation) for p in polygon.exterior.coords]) c = polygon.centroid.coords[0] p = poly.position dx, dy = [p[i] - c[i] for i in range(2)] return polygon.contains(Point(offset(unscale(point), -dx, -dy)))
def point_in_polygon(point, region): from shapely.geometry import ( Polygon, LinearRing, Point, ) point = Point(point) polygon_boundary = LinearRing(region) polygon = Polygon(region) return polygon.contains(point) or polygon_boundary.contains(point)
def test(): point = Point(0.5,0.5) r2 = LinearRing([ (1.1), (0, 0), (1, 0), (0, 1)]) polygon2 = Polygon(r2) boolean = polygon2.contains(point) print (boolean)
def test_inside(self): ext = [(0, 0), (0, 2), (2, 2), (2, 0), (0, 0)] int = [(1, 1), (1, 1.5), (1.5, 1.5), (1.5, 1)] poly_with_hole = Polygon(ext,[int]) polygon = Polygon([(0, 0), (0, 10), (10, 10),(0, 10)]) point_on_edge = Point(5, 10) point_on_vertex = Point(10, 10) point_inside = Point(5, 5) point_outside = Point(20,20) point_in_hole = Point(1.25, 1.25) self.assertTrue(polygon.touches(point_on_vertex)) self.assertTrue(polygon.touches(point_on_edge)) self.assertTrue(polygon.contains(point_inside)) self.assertFalse(polygon.contains(point_outside)) self.assertTrue(point_in_hole.within(poly_with_hole))
def __get_exterior_index(coords): exterior_index = -1 for i in range(len(coords)): pts = coords[i] poly = Polygon(pts) res = [] for p in coords: res.append(poly.contains(Polygon(p))) if __and_of_array(res) : return i+1 __error_occured=1 return -1
def intersect_marker_area(a,m): point=Point(float(m.points[0].pos_lon),float(m.points[0].pos_lat)) apoints = [(float(p.pos_lon),float(p.pos_lat)) for p in a.points] poly = Polygon(apoints); area=poly.area if poly.contains(point): log.info('poly %s contains point %s'%(poly,point)) return 100 else: log.info('poly %s does not contain point %s'%(poly,point)) return False
def all_CCD_check(com, ra, dec): sima = Polygon([(com[0], com[1]), (com[2], com[3]), (com[4], com[5]), (com[6], com[7])]) # simp = PolygonPatch(sima, facecolor='k',zorder=0) # plt.gca().add_patch(simp) alpha = np.arctan(np.divide((np.subtract(com[6], com[0])), np.subtract(com[7], com[1]))) # print alpha xt = com[0] yt = com[1] jonest = np.matrix([[np.cos(alpha), -np.sin(alpha), xt], [np.sin(alpha), np.cos(alpha), yt], [0, 0, 1.0]]) # print jonest good_area = [] xl_scale = abs(com[0] - com[2]) / ((2048 * 1.01) / 3600) xr_scale = abs(com[4] - com[6]) / ((2048 * 1.01) / 3600) yu_scale = abs(com[3] - com[5]) / ((4096 * 1.01) / 3600) yl_scale = abs(com[1] - com[7]) / ((4096 * 1.01) / 3600) for i in [ (75.0 * xl_scale, 75.0), (2048.0 * xl_scale, 75.0), (2048.0 * xr_scale, 4000.0), (75.0 * xr_scale, 4000.0), ]: x = i[0] * (1.01 / 3600) y = i[1] * (1.01 / 3600) pixel_coords = np.matrix([[x], [y], [1.0]]) # print 'Pixel:', pixel_coords cords = np.dot(jonest, pixel_coords) # print 'New Coordinates:', cords # print cords.item(0) good_area.append((cords.item(0), yt - (cords.item(1) - yt))) garea = [ good_area[0], (good_area[1][0], com[3] - ((75.0 * 1.01 / 3600) * yu_scale)), (good_area[2][0], com[5] + ((96.0 * 1.01 / 3600) * yu_scale)), good_area[3], ] # print good_area # print [(com[0],com[1]),(com[2],com[3]),(com[4],com[5]),(com[6],com[7])] simg1 = Polygon(garea) if com[8] == 0: simb0 = ccd0_defect(com, alpha) simg1 = simg1.difference(simb0) return simg1.contains(Point(ra, dec))
def srs_guesser(geom): sr = None try: geom_type = geom.geom_type except ValueError: return sr if geom_type in ('Point', 'LineString'): for epsg, bbox in bboxes.iteritems(): dtm_poly = Polygon([(bbox[0], bbox[1]), (bbox[2], bbox[1]), (bbox[2], bbox[3]), (bbox[0], bbox[3])]) if dtm_poly.contains(geom): sr = epsg break return sr
def process_tile(bb, increase, tile_id): flood_points = [] import sys tile = db.hgt.find_one({"_id": ObjectId(tile_id)})["tile"] try: # If the min elevation is greater than the change we can skip this tile if tile["properties"]["minElevation"] > increase: return except KeyError: print >>sys.stderr, "tile: %s" % str(tile) poly = Polygon(bb) elevations = cPickle.loads(tile["properties"]["elevations"]) origin = tile["coordinates"][0][0] it = np.nditer(elevations, flags=["f_index", "multi_index"]) while not it.finished: coord = [ origin[0] + (it.multi_index[1] / (NUMBER_PIXELS - 1)), origin[1] + (it.multi_index[0] / (NUMBER_PIXELS - 1)), ] elev = np.asscalar(it[0]) point = Point(coord) if elev == DATA_VOID: it.iternext() continue if poly.contains(point) and elev > 0 and elev <= increase: point = [coord, elev] # flood_points.append(to_feature(point)) flood_points.append(coord) it.iternext() if len(flood_points) == 0: return results = db[FLOODMAP_RESULT_COLLECTION] # Key off the group id print >>sys.stderr, "Adding points: %d" % len(flood_points) results.insert({"group_id": process_tile.request.group, "points": flood_points})
def get_useful_building_list(community_border_list, building_border): # community_border_list 转换为 polygon 的对象 tmp = [] for i in community_border_list: tmp.append([i[0],i[1]]) community_polygon_obj = Polygon(tmp) # ============= center_lng = list(community_polygon_obj.centroid.coords)[0][0] center_lat = list(community_polygon_obj.centroid.coords)[0][1] tmp_building_border = building_border[(building_border['point_lat']<center_lat+0.02)& (building_border['point_lat']>center_lat-0.02)& (building_border['point_lng']<center_lng+0.02)& (building_border['point_lng']>center_lng-0.02)] # ============= useful_building_list = [] # len_buildings = len(tmp_building_border) num = 0 building_coverage_area = 0 building_plot_area = 0 for index,row in tmp_building_border.iterrows(): num += 1 # print (str(num)+'/'+str(len_buildings)) p_list = row[3] p_floor = row[1] building_polygon_obj = Polygon(p_list) point_lng = list(building_polygon_obj.centroid.coords)[0][0] point_lat = list(building_polygon_obj.centroid.coords)[0][1] p_point = Point([point_lng,point_lat]) # 建筑物中心点落在小区内,同时建筑物在小区内的面积占建筑物面积的百分之五十以上的,记录下来 try: if community_polygon_obj.contains(p_point) and community_polygon_obj.intersection(building_polygon_obj).area / building_polygon_obj.area > 0.5: useful_building_list.append([p_floor,p_list]) building_coverage_area += building_polygon_obj.area building_plot_area += building_polygon_obj.area * p_floor except TopologicalError: pass # 小区建筑覆盖率低于 0.05 的直接排除 # plot ratio # coverage ratio coverage_ratio = building_coverage_area / community_polygon_obj.area plot_ratio = building_plot_area / community_polygon_obj.area if coverage_ratio < 0.1 or len(useful_building_list) < 2: useful_building_list = [] elif plot_ratio < 1: if len(useful_building_list) < 20: useful_building_list = [] return coverage_ratio, plot_ratio, useful_building_list
def voronoi_mercator(file='mercator_coords.txt'): vframe = gpd.GeoDataFrame() vframe['school'] = None vframe['points'] = None with open(file) as f: merc_data = [] for line in f: line_data = line.split(',') if line_data[0] != 'TeamName': school = line_data[0] x = float(line_data[1][1:]) y = float(line_data[2][1:-2]) merc_data.append((school, (x, y))) points = [item[1] for item in merc_data] #need to add the four extra points far away to deal with points at infinity #created in scipy.spatial.Voronoi points.append((-100000000, -100000000)) points.append((-100000000, 100000000)) points.append((100000000, -100000000)) points.append((100000000, 100000000)) vor = Voronoi(points) regions = vor.regions pts = vor.vertices i = 0 for part in regions: loop_points = [] #ignore any shape with a -1 (pt at infinity) since those are from the 4 extra pts if -1 not in part: loop_points = [pts[part[index]] for index in range(len(part))] try: poly = Polygon(loop_points) vframe.loc[i, 'points'] = poly except ValueError: vframe.loc[i, 'points'] = None nested_index = 0 for point in points: if poly.contains(Point(point)): vframe.loc[i, 'school'] = merc_data[nested_index][0] break nested_index += 1 i += 1 return vframe
def make_convex_boundary(self): self.normalize_graph(100) boundary_vertices = self.get_boundary_vertices(clockwise=False) n = len(boundary_vertices) count = 0 while count < n: for i in range(len(boundary_vertices)): # if self.plot: # plt.cla() # for b in boundary_vertices: # plt.scatter(self.vertices[b][0], self.vertices[b][1]) # plt.pause(1) points = [self.vertices[v] for v in boundary_vertices if v != boundary_vertices[i]] pol = Polygon(points) # x, y = pol.exterior.xy # plt.plot(x, y) vertex = Point(self.vertices[boundary_vertices[i]]) if pol.contains(vertex): # it is not convex count = 0 vertex = boundary_vertices[i] v0 = boundary_vertices[(i - 1) % n] v2 = boundary_vertices[(i + 1) % n] # we apply the cosine theorem to calculte the angle v0-vertex-v2 a = LineString([self.vertices[v0], self.vertices[vertex]]) b = LineString([self.vertices[vertex], self.vertices[v2]]) c = LineString([self.vertices[v2], self.vertices[v0]]) cos_angle = (c.length**2-a.length**2-b.length**2)/(-2*a.length*b.length) # cosine theorem angle = math.acos(cos_angle) # now we calculate the bisector vx = self.vertices[v0][0] - self.vertices[vertex][0] vy = self.vertices[v0][1] - self.vertices[vertex][1] bisector_angle = math.atan2(vy, vx) + angle/2 shiftx = 10*math.cos(bisector_angle) shifty = 10*math.sin(bisector_angle) self.vertices[vertex][0] += shiftx self.vertices[vertex][1] += shifty # while self.count_edge_crossings(only_boundary=True) > 0: # # revert # self.vertices[vertex][0] -= shiftx # self.vertices[vertex][1] -= shifty # # try with the half of the step # shiftx /= 2 # shifty /= 2 # self.vertices[vertex][0] += shiftx # self.vertices[vertex][1] += shifty else: count += 1 if self.plot: self.plot_graph(0.01)
def write_josm_file(self, filename, tilezoom=14): """ create a osm file for the editor JOSM, that only contains the download boundary information. Load the file in JOSM and update the data. Note: Please do not missuse this function to download large areas with josm """ from shapely.geometry import LineString, Polygon f_out = open(filename, 'w') f_out.write("<?xml version='1.0' encoding='UTF-8'?>\n") f_out.write("<osm version='0.6' upload='true' generator='JOSM'>\n") for i, op in enumerate(self.outer_polygons): # create coordinate list and then a polygon plist = [(node.lat, node.lon) for node in op] outer_polygon = Polygon(LineString(plist)) if not outer_polygon.is_valid: raise ValueError('outer polygon no %i is not valid' % (i + 1)) (minlat, minlon, maxlat, maxlon) = outer_polygon.bounds (x1, y2) = deg2num(minlat, minlon, tilezoom) (x2, y1) = deg2num(maxlat, maxlon, tilezoom) for ty in range(y1, y2 + 1): for tx in range(x1, x2 + 1): tile_rectangle = [ num2deg(tx, ty, tilezoom), num2deg(tx + 1, ty, tilezoom), num2deg(tx + 1, ty + 1, tilezoom), num2deg(tx, ty + 1, tilezoom), num2deg(tx, ty, tilezoom) ] tile_polygon = Polygon(tile_rectangle) if outer_polygon.contains( tile_polygon) or outer_polygon.intersects( tile_polygon): minlat = tile_rectangle[3][0] minlon = tile_rectangle[3][1] maxlat = tile_rectangle[1][0] maxlon = tile_rectangle[1][1] f_out.write(' <bounds minlat="%.7f" minlon="%.7f" maxlat="%.7f" maxlon="%.7f" />\n' \ % (minlat-0.0000001, minlon-0.0000001, maxlat+0.0000001, maxlon+0.0000001)) f_out.write("</osm>\n") f_out.close
def indices_of_point(self, lon, lat, proj=ccrs.PlateCarree()): """Return the indices of the grid cell that contains the point (lon, lat) Parameters ---------- lat : float The latitude of the point source lon : float The longitude of the point source Returns ------- int (icon_indn), the index of the ICON grid cell containing the source. Raises ------ IndexError If the point lies outside the grid. """ indn = -1 pnt = Point(lon,lat) closest_vertex = ((self.vlon - lon)**2 + (self.vlat - lat)**2).argmin() cell_range = self.cell_of_vertex[:,closest_vertex] - 1 for n in cell_range: if n == -1: continue if self.polygons[n] is not None: icon_cell = self.polygons[n] else: corners = np.array(list(zip(*self.cell_corners(n,0)))) icon_cell = Polygon(corners) self.polygons[n] = icon_cell if icon_cell.contains(pnt): indn = n break if indn == -1: raise IndexError("Point lies outside the ICON Grid") return int(indn), 0
def polygonize(self): # solo polygon if self.__n_parts == 1: return [Polygon(self.__points)] #multiple elif self.__n_parts > 1: #print("Parts",type(self.__parts)) parts = list(self.__parts) if parts[-1] != self.__n_parts: parts.append(len(self.__points)) polygons = [] for i in range(self.__n_parts): #check all parts subset = self.__points[parts[i]:parts[i + 1]] segs = np.array([[x, x + 1] for x in range(parts[i], parts[i + 1] - 1) ]) # -1 slutet #is subset a poly or hole? hole = counter_clockwise_vertices(self.__points, segs) if not hole: tmp_polygon = Polygon(subset) internal_holes = [] for j in range( self.__n_parts ): #go through again and check for internal holes sub = self.__points[parts[j]:parts[j + 1]] sgs = np.array([[x, x + 1] for x in range(parts[j], parts[j + 1] - 1)]) hole = counter_clockwise_vertices(self.__points, sgs) #print("Parts: ", parts) #print("SUB: ", sub) ring = LinearRing(sub) if hole and tmp_polygon.contains(ring): internal_holes.append(sub) polygons.append(Polygon(subset, internal_holes)) return polygons
def rotated_stripe(x, y, l, w, angle, grid_size): data = np.ones((grid_size, grid_size)) x2 = x + int(round(l*cos(angle*math.pi/180))) y2 = y + int(round(l*sin(angle*math.pi/180))) x3 = x + int(round(w*cos((angle-90)*math.pi/180))) y3 = y + int(round(w*sin((angle-90)*math.pi/180))) x4 = x3 + int(round(l*cos(angle*math.pi/180))) y4 = y3 + int(round(l*sin(angle*math.pi/180))) if (x2!=x) and (y2!=y): for i in range(x, x2 + np.sign(x2-x), np.sign(x2-x)): for j in range(y, y2 + np.sign(y2-y), np.sign(y2-y)): if calc_dist(x, y, x2, y2, i, j) < 1: data[i,j] = calc_dist(x, y, x2, y2, i, j) if (x3!=x) and(y3!=y): for i in range(x, x3 + np.sign(x3-x), np.sign(x3-x)): for j in range(y, y3 + np.sign(y3-y), np.sign(y3-y)): if calc_dist(x, y, x3, y3, i, j) < 1: data[i,j] = calc_dist(x, y, x3, y3, i, j) if (x4!=x2) and (y4!=y2): for i in range(x2, x4 + np.sign(x4-x2), np.sign(x4-x2)): for j in range(y2, y4 + np.sign(y4-y2), np.sign(y4-y2)): if calc_dist(x4, y4, x2, y2, i, j) < 1: data[i,j] = calc_dist(x2, y2, x4, y4, i, j) if (x4!=x3) and (y4!=y3): for i in range(x3, x4 + np.sign(x4-x3), np.sign(x4-x3)): for j in range(y3, y4 + np.sign(y4-y3), np.sign(y4-y3)): if calc_dist(x4, y4, x3, y3, i, j) < 1: data[i,j] = calc_dist(x3, y3, x4, y4, i, j) min_x = min(x, x2, x3, x4) max_x = max(x, x2, x3, x4) min_y = min(y, y2, y3, y4) max_y = max(y, y2, y3, y4) polygon = Polygon([(x,y),(x2,y2), (x4,y4), (x3, y3)]) for i in range(min_x, max_x+1): for j in range(min_y, max_y+1): if polygon.contains(Point(i,j)): data[i,j] = 0 return data
def produceRandomInput(self, tensorflow=True): """ produce random point for the learning step :param tensorflow: return as tensorflow or numpy variable """ self.timer.startTimer("produceRandomInput") minX = self.boundingBox[0, 0] minY = self.boundingBox[1, 0] maxX = self.boundingBox[0, 1] maxY = self.boundingBox[1, 1] inner = Polygon(self.geometry[1]) outer = Polygon(self.geometry[0]) while (True): randomCoordinate = np.array( [random.uniform(minX, maxX), random.uniform(minY, maxY)]) point = Point(randomCoordinate[0], randomCoordinate[1]) if (inner.contains(point)): continue else: if (outer.contains(point)): if (tensorflow): return tf.Variable(randomCoordinate, dtype=self.dataType) else: return randomCoordinate else: continue self.timer.stopTimer("produceRandomInput")
def polygon_crossing(p1, poly_edges): if not poly_edges: return True a = poly_edges.pop() polys = [[a.p1.x, a.p1.y], [a.p2.x, a.p2.y]] last = a.p2 while poly_edges: curr = None for edge in poly_edges: if edge.p1 == last: curr = edge poly_edges.remove(curr) polys.append([curr.p2.x, curr.p2.y]) last = curr.p2 poly = Polygon(polys) return poly.contains(Point(p1.x, p1.y))
def get_text_lying_in(text_data: pd.DataFrame, polygon: Polygon): ''' From an ocr results dataframe, returns the rows if their text are contained in the polygon Parameters text_data (pd.DataFrame) : The OCR results dataframe polygon (Polygon) : The polygon that may contains text Returns pd.DataFrame : The rows of text_data if text lies in the polygon ''' row_lying_bool_array = [ polygon.contains(row['bbox']) for _, row in text_data.iterrows() ] return text_data[row_lying_bool_array]
def step(self, action): # Execute one time step within the environment assert_equal(action.shape, (self.nenvs, )) self._take_action(action) self.current_step += 1 if self.current_step > self.MAX_STEPS: #RESET # we are not checking for 'no action' action since longer routes # would mean larger rewards self.current_step = 0 done = [True for _ in range(self.nenvs)] else: done = [False for _ in range(self.nenvs)] # comment since we are handling it later # delay_modifier = (self.current_step / self.MAX_STEPS) #DEFINE reward = np.zeros(self.nenvs) curves_torso = np.reshape((self.curves_torsos * 255.5 + 255.5), (self.nenvs, -1, 2)).astype(int).tolist() for env_n in range(self.nenvs): torso = Polygon( [curves_torso[env_n][index] for index in self.co_in]) if torso.contains(self.leftlung) and torso.contains(self.rightlung) and torso.contains(self.heart) \ and torso.contains(self.esophagus): reward[env_n] = 0 else: reward[env_n] = -1 self.norm_obs_st = np.append(self.torso_est.transform(self.torsos), self.norm_const_arr, axis=1) self.state = np.append(self.input_imgs, self.torsos, axis=1) # reward = reward * delay_modifier # print('NORM OBS222') # print(self.norm_obs_st) # print(self.state) return self.norm_obs_st, reward, done, self.state
def _is_coordinates_in_shapefile(self, coordinates, shpfile): ''' open shapefile''' sf = shapefile.Reader(shpfile) '''get features''' shapes = sf.shapes() first_shp = shapes[0] ''' get points coordinates for each point in the shape ''' points = first_shp.points polygon = Polygon(points) point = Point(coordinates[0], coordinates[1]) return polygon.contains(point)
def check_coords(coords): x = [] for i in range(len(list(possible_places.values()))): pt = Point(coords) if isinstance(list(possible_places.values())[i], Polygon): polygon = list(possible_places.values())[i] else: polygon = Polygon( list(map(tuple, list(possible_places.values())[i]))) x = np.append(x, polygon.contains(pt)) return x
def generate_zones(poly_points, hl_unit, vl_unit, x_points, y_points): poly = Polygon(poly_points) zones = {} for i, x in enumerate(x_points): for j, y in enumerate(y_points): zone_poly = Polygon([[x, y], [x + hl_unit, y], [x + hl_unit, y + vl_unit], [x, y + vl_unit]]) if poly.contains(zone_poly): relation = zone.IN elif poly.intersects(zone_poly): relation = zone.INTERSECT else: relation = zone.OUT zones[(i, j)] = zone(relation, i, j, x, y) return zones
def allpick(self, pickpoint): allpickfile = filedir + "/" + allpick polys = sf.Reader(allpickfile) polygon = polys.shapes() shpfilePoints = [] for shape in polygon: shpfilePoints = shape.points polygon = Polygon(shpfilePoints) lng = pickpoint[1] lat = pickpoint[0] point = Point(lng, lat) if polygon.contains(point): return True else: return False
def user_input(): while True: user_loc = input( 'Please enter your location as BNG coordinates (easting and northing separated by a comma):\n' ) user_loc = user_loc.split(',') try: if len(user_loc) != 2: print( 'Invalid input. Please only enter one easting coordinate and one northing coordinate.' ) else: user_loc = Point(float(user_loc[0]), float(user_loc[1])) # Checking coordinates print('Your coordinates are:', user_loc.x, user_loc.y) conf = input("Type 'y' to confirm:\n") if conf.lower() == 'y': print('Coordinates confirmed.') break except ValueError: print('Invalid input. Input is not a coordinate.') # Defining the bounding box vertices against which checking the user location data = { 'point': ['bottom_left', 'bottom_right', 'top_right', 'top_left'], 'easting_coordinate': [430000, 465000, 465000, 430000], 'northing_coordinate': [80000, 80000, 95000, 95000] } # Creating a dataframe and its polygon df = pd.DataFrame(data) box_poly = Polygon(df[['easting_coordinate', 'northing_coordinate']].values) # Checking the user location # First attempt (for task 1): checking the bounding box if box_poly.contains(user_loc) or box_poly.touches(user_loc): print('You are in the bounding box.') else: # Second attempt (for task 6): checking with the shapefile shape = gpd.read_file('shape/isle_of_wight.shp') if shape.contains(user_loc).iloc[0] or shape.touches(user_loc).iloc[0]: print('You are not in the bounding box but on the island.') else: print('Invalid location: outside boundaries, quitting.') quit() return user_loc
def expand_polygon(polygon, points_file, max_percent=.1): """ Read the crash data, determine what proportion of crashes fall outside the city polygon Args: polygon - city polygon points_file - json points file Optional: max_percent (in case you want to override the maximum percent that can be outside the original polygon to buffer) Returns: Updated polygon if it was a polygon to start with, None otherwise """ # Right now, only support this for polygons if polygon['type'] != 'Polygon': return None polygon_coords = util.reproject([x for x in polygon['coordinates'][0]]) polygon_coords = [x['coordinates'] for x in polygon_coords] poly_shape = Polygon(polygon_coords) records = util.read_records(points_file, 'crash') outside = [] for record in records: if not poly_shape.contains(record.point): outside.append(record.point) outside_rate = len(outside) / len(records) if outside_rate > .01 and outside_rate < max_percent: print("{}% of crashes fell outside the city polygon".format( int(round(outside_rate, 2) * 100))) poly_shape = buffer_polygon(poly_shape, outside) # Convert back to 4326 projection coords = util.reproject(poly_shape.exterior.coords, transformer_3857_to_4326) coords = [x['coordinates'] for x in coords] poly_shape = Polygon(coords) return poly_shape # If almost no points fall outside the polygon, no need to buffer, # and if a large proportion of points fall outside the polygon, # the crash data might be for a larger area than just the city return None
def processTweets(listTweets): processed_tweets = [] if not listTweets: return None for tweet in listTweets: if tweet['user location']: locator = geopy.Nominatim(user_agent='myGeocoder') cities = ['sydney', 'melbourne', 'brisbane'] found = False for city in cities: if re.search(city, tweet['user location'].lower()): processed_tweets.append(tweet) found = True break if found: continue if tweet['user location'].lower( ) == 'australia' or tweet['user location'].lower() == 'aus': continue try: location = locator.geocode(tweet['user location'], viewbox=[(-10.5, 110.99), (-44.43, 157.87)]) except GeocoderTimedOut as e: print("Geocoder TimedOut... sleeping 5") sleep(5) continue except GeocoderUnavailable as e: print("Geocoder Unavailable.... sleeping 5") sleep(5) except Exception as e: print('caught geocode error') print(e) continue if not location: continue point = Point(location.latitude, location.longitude) coords = [(-11, 112), (-11, 154), (-44, 112), (-44, 154)] poly = Polygon(coords) if poly.contains(point): processed_tweets.append(tweet) return processed_tweets
def plot_whiskers(idx): """ Plot small whiskers indicated slip orientation """ nx = 5 ny = 15 x_vec = np.linspace(np.min(pts[:, 0]), np.max(pts[:, 0]), nx) y_vec = np.linspace(np.min(pts[:, 1]), np.max(pts[:, 1]), ny) x_grid, y_grid = np.meshgrid(x_vec, y_vec) u_x = griddata((pts[:, 0], pts[:, 1]), slip_rate_x[idx, :], (x_grid, y_grid), method="cubic") u_y = griddata((pts[:, 0], pts[:, 1]), slip_rate_y[idx, :], (x_grid, y_grid), method="cubic") u_y[np.isnan(u_y)] = 0 u_x[np.isnan(u_x)] = 0 x_grid = x_grid.flatten() y_grid = y_grid.flatten() u_x = u_x.flatten() u_y = u_y.flatten() # Select only those inside fault boundary boundary_x, boundary_y = get_boundary(tris) boundary_points = list(zip(boundary_x, boundary_y)) polygon = Polygon(boundary_points) for i in range(0, u_x.size): if polygon.contains(Point((x_grid[i], y_grid[i]))): vel_mag = np.sqrt(u_x[i]**2 + u_y[i]**2) if vel_mag > 1e-14: ux = u_x[i] / vel_mag uy = u_y[i] / vel_mag plt.plot( [x_grid[i], x_grid[i] + WHISKER_SCALE * ux], [y_grid[i], y_grid[i] + WHISKER_SCALE * uy], "-k", zorder=1000, linewidth=LINE_WIDTH, ) plt.plot( [x_grid[i], x_grid[i] - WHISKER_SCALE * ux], [y_grid[i], y_grid[i] - WHISKER_SCALE * uy], "-k", zorder=1000, linewidth=LINE_WIDTH, )
def get_point_inside(): outline_coords = np.loadtxt('Ainchannel-outline-coords.dat') outline_coords = outline_coords[:,1:3] print outline_coords mypoly = Polygon(outline_coords) #x,y = mypoly.exterior.xy #plt.plot(x,y) num_points = len(outline_coords) if(num_points <=0): print("Number of points in the outline is zero\n") print("Program aborted") exit(302) # Compute the centroid and minimum and maxium coordinates in the outline min_xcoord = min(outline_coords[:,0]) min_ycoord = min(outline_coords[:,1]) max_xcoord = max(outline_coords[:,0]) max_ycoord = max(outline_coords[:,1]) (minx, miny, maxx, maxy) = mypoly.bounds print("bounds") print(min_xcoord, minx) print(min_ycoord, miny) print(max_xcoord, maxx) print(max_ycoord, maxy) length_xdir = max_xcoord - min_xcoord length_ydir = max_ycoord - min_ycoord centroid_xcoord=0.0 centroid_ycoord=0.0 for i in range(num_points): centroid_xcoord = centroid_xcoord + outline_coords[i,0] centroid_ycoord = centroid_ycoord + outline_coords[i,1] #print("%10.6f \t %10.6f \n" % (outline_coords[i,0], outline_coords[i,1])) pt_centroid = Point(centroid_xcoord, centroid_ycoord) point_in_poly = get_random_point_in_polygon(mypoly) print(mypoly.contains(point_in_poly)) return
def get_fracture_intersection_diff(self, fracture, face): R = fracture.build_rotation_matrix() fracture_poly_list = [] face_poly_list = [] for point in fracture.points: rot_point = np.linalg.solve(R, point - fracture.center) fracture_poly_list.append(rot_point[:2]) for point_index in face: point = self.get_point(point_index) rot_point = np.linalg.solve(R, point - fracture.center) face_poly_list.append(rot_point[:2]) face_poly = Polygon(face_poly_list) fracture_poly = Polygon(fracture_poly_list) if not face_poly.intersects(fracture_poly) or \ fracture_poly.contains(face_poly): return (False, None, None) else: poly1 = fracture_poly.intersection(face_poly) poly1_ret = [] for point in list(poly1.exterior.coords)[:-1]: rot_point = R.dot( np.array(list(point) + [0.])) + fracture.center poly1_ret.append(rot_point) poly2 = face_poly.difference(fracture_poly) poly2_ret = [] if type(poly2) == type(MultiPolygon()): for poly in poly2: poly2_ret.append([]) for point in list(poly.exterior.coords)[:-1]: rot_point = R.dot( np.array(list(point) + [0.])) + fracture.center poly2_ret[-1].append(rot_point) else: poly2_ret.append([]) for point in list(poly2.exterior.coords)[:-1]: rot_point = R.dot( np.array(list(point) + [0.])) + fracture.center poly2_ret[-1].append(rot_point) return (True, [poly1_ret], poly2_ret)
def test_prepared_predicates(): # check prepared predicates give the same result as regular predicates polygon1 = Polygon([(0, 0), (0, 1), (1, 1), (1, 0), (0, 0)]) polygon2 = Polygon([(0.5, 0.5), (1.5, 0.5), (1.0, 1.0), (0.5, 0.5)]) point2 = Point(0.5, 0.5) polygon_empty = Polygon() prepared_polygon1 = PreparedGeometry(polygon1) for geom2 in (polygon2, point2, polygon_empty): assert polygon1.disjoint(geom2) == prepared_polygon1.disjoint(geom2) assert polygon1.touches(geom2) == prepared_polygon1.touches(geom2) assert polygon1.intersects(geom2) == prepared_polygon1.intersects( geom2) assert polygon1.crosses(geom2) == prepared_polygon1.crosses(geom2) assert polygon1.within(geom2) == prepared_polygon1.within(geom2) assert polygon1.contains(geom2) == prepared_polygon1.contains(geom2) assert polygon1.overlaps(geom2) == prepared_polygon1.overlaps(geom2)
def get_stations_in_box(self,lat1,lng1,lat2,lng2): cherrypy.response.headers["Access-Control-Allow-Origin"] = "*" coord1 = (float(lat1), float(lng1)) coord2 = (float(lat1), float(lng2)) coord3 = (float(lat2), float(lng2)) coord4 = (float(lat2), float(lng1)) rect = Polygon([coord1,coord2,coord3,coord4]) r = requests.get('http://www.divvybikes.com/stations/json/') jsonData = r.json() stations = jsonData['stationBeanList'] ret_stations = [] for station in stations: point = Point(station['latitude'], station['longitude']) if rect.contains(point): ret_stations.append(station) return json.dumps(ret_stations)
def point_inside_polygon_3(polygon, point): # Check input shape is for 2D only if len(polygon.shape) != 2: raise ValueError('Polygon must be an Nx2 array.') if polygon.shape[1] != 2: raise ValueError('Polygon must be in two dimensions.') _point = numpy.atleast_2d(point) if _point.shape[1] != 2: raise ValueError('Point must contain two elements.') from shapely.geometry import Point, Polygon poly = Polygon(polygon.tolist()) import pdb pdb.set_trace() return numpy.array([poly.contains(Point(p)) for p in _point])
def findtheareanumber(loclat, loclng): point = Point(loclng, loclat) for i in range(len(neighborlist)): areanum = 0 tmpfilename = filedir + "/" + neighborlist[i] polys = sf.Reader(tmpfilename) polygon = polys.shapes() shpfilePoints = [] for shape in polygon: shpfilePoints = shape.points polygon = Polygon(shpfilePoints) if polygon.contains(point): areanum = i return areanum elif i == len(neighborlist) - 1 and areanum == 0: return None
def get_random_inner_point(hex_key: str) -> Point: """ function to get a random point inside a hexagon Args: hex_key (str): hex key value Returns: Point: shapely.geometry.Point with the (x,y) pair on the hexagon """ hex_polygon = Polygon(h3.h3_to_geo_boundary(hex_key)) minx, miny, maxx, maxy = hex_polygon.bounds while True: random_point = Point(random.uniform(minx, maxx), random.uniform(miny, maxy)) if hex_polygon.contains(random_point): return random_point
def is_point_in_polygon(x, y, polygon_point_list): """ Use ray-tracing to see if point is inside a polygon Args: x: y: polygon_point_list: Returns: bool """ shapely_point = Point(x, y) shapely_polygon = Polygon(polygon_point_list) return shapely_polygon.contains(shapely_point)
def find_square_conatining(squares, pos, checking_square=0, squares_lookahead=None): if squares_lookahead is None: squares_lookahead = len(squares) found_square = None while found_square is None and squares_lookahead > 0: sqr = Polygon(squares[checking_square]) pt = Point(pos) inside2 = sqr.contains(pt) if inside2: found_square = checking_square return found_square, (found_square + 1) % len(squares) checking_square = (checking_square + 1) % len(squares) squares_lookahead -= 1 return found_square, None
def get_stations_in_box(self, lat1, lng1, lat2, lng2): cherrypy.response.headers["Access-Control-Allow-Origin"] = "*" coord1 = (float(lat1), float(lng1)) coord2 = (float(lat1), float(lng2)) coord3 = (float(lat2), float(lng2)) coord4 = (float(lat2), float(lng1)) rect = Polygon([coord1, coord2, coord3, coord4]) r = requests.get('http://www.divvybikes.com/stations/json/') jsonData = r.json() stations = jsonData['stationBeanList'] ret_stations = [] for station in stations: point = Point(station['latitude'], station['longitude']) if rect.contains(point): ret_stations.append(station) return json.dumps(ret_stations)
def split_regions(kfb_path, img_level=3, cnt_level=4): s_img, mask, cnts = find_tissue_cnt(kfb_path, cnt_level) img_cnt_ratio = 2**(cnt_level - img_level) wsi_dim = [ele * img_cnt_ratio for ele in s_img.shape[:2]] wsi_img = load_kfb2arr(kfb_path, img_level, wsi_dim) RAW_SIZE = 299 SIZE1, SIZE2, SIZE4 = int(RAW_SIZE / 4), int(RAW_SIZE / 2), RAW_SIZE split_arr, patch_list = [], [] for c_ind in range(len(cnts)): cur_cnt = cnts[c_ind] * img_cnt_ratio cur_cnt = np.squeeze(cur_cnt) w_coors = [int(round(ele)) for ele in cur_cnt[:, 0].tolist()] h_coors = [int(round(ele)) for ele in cur_cnt[:, 1].tolist()] w_min, w_max = min(w_coors), max(w_coors) h_min, h_max = min(h_coors), max(h_coors) # Width range to crop start_w = (w_min - SIZE1) if (w_min - SIZE1) > 0 else 0 num_w = int(math.ceil((w_max - start_w - SIZE2) / SIZE2)) # Height range to crop start_h = (h_min - SIZE1) if (h_min - SIZE1) > 0 else 0 num_h = int(math.ceil((h_max - start_h - SIZE2) / SIZE2)) poly_cnt = Polygon(cur_cnt) for iw in range(0, num_w): for ih in range(0, num_h): # determine current rectangular is inside the contour or not cur_coors = [ (start_w + iw * SIZE2, start_h + ih * SIZE2), (start_w + iw * SIZE2 + SIZE4, start_h + ih * SIZE2), (start_w + iw * SIZE2 + SIZE4, start_h + ih * SIZE2 + SIZE4), (start_w + iw * SIZE2, start_h + ih * SIZE2 + SIZE4) ] try: if poly_cnt.contains(Polygon(cur_coors)): split_arr.append( (start_h + ih * SIZE2, start_w + iw * SIZE2)) split_patch = wsi_img[start_h + ih * SIZE2:start_h + ih * SIZE2 + SIZE4, start_w + iw * SIZE2:start_w + iw * SIZE2 + SIZE4, :] patch_list.append(split_patch) except: print("Error in Polygon relationship") return split_arr, patch_list, wsi_dim, s_img, mask
def inflatedWallPolygon(globaldata, wallpoints, dist, interiorpts): print("Creating Inflated Wall Point") inflatedWall = [] for itm in wallpoints: nx, ny = normalCalculation(itm, globaldata, True) orgWallpt = getPointxy(itm, globaldata) orgWallptx = float(orgWallpt.split(",")[0]) orgWallpty = float(orgWallpt.split(",")[1]) normalVector = np.array([nx, ny]) orgVector = np.array([orgWallptx, orgWallpty]) newWallpt = orgVector + dist * normalVector newWallpt = tuple(newWallpt.tolist()) inflatedWall.append(newWallpt) wallptsData = convertPointToShapelyPoint( convertIndexToPoints(wallpoints, globaldata) ) # wallpointGeo = Polygon(wallptsData) lastpt = wallptsData[0] newpt = (lastpt[0] + dist, lastpt[1]) inflatedWall.pop(0) inflatedWall.insert(0, newpt) inflatedwallpointGeo = Polygon(inflatedWall) print("Checking for Pseudo Points") # fig, ax = plt.subplots() # x1,y1 = wallpointGeo.exterior.xy # x2,y2 = inflatedwallpointGeo.exterior.xy # # ax = fig.add_subplot(111) # # ax.scatter(x1, y1, color='red', alpha=0.7, zorder=2) # # ax.set_title('Polygon') # # ax = fig.add_subplot(111) # # ax.scatter(x2, y2, color='blue', alpha=0.7, zorder=2) # # ax.set_title('Polygon2') # ax = fig.add_subplot(111) # ax.plot(x1, y1, color='red', alpha=0.7, zorder=2) # ax.plot(x2, y2, color='blue', alpha=0.7, zorder=2) # plt.show() pseudopts = [] for itm in interiorpts: itmval = convertPointToShapelyPoint(convertIndexToPoints([itm], globaldata))[0] interiorpoint = Point(itmval) if inflatedwallpointGeo.contains(interiorpoint): pseudopts.append(itm) print("Found", len(pseudopts), "pseudo points!") with open("psuedopoints.txt", "w") as text_file: for item1 in pseudopts: text_file.writelines(str(item1)) text_file.writelines("\t\n")
def maxMinDistance(poly, dd): allLines = [] allLines.append(poly.exterior) postLayer = dd.layers[DesignDict.POST] portLayer = dd.layers[DesignDict.PORTS] possiblePosts = postLayer.index.intersection(poly.bounds) possiblePorts = portLayer.index.intersection(poly.bounds) candidatePosts = [] prepPoly = prep(poly) construct = Polygon(poly) for objind in possiblePosts: obj = dd.objects[objind] if prepPoly.contains_properly(obj.shape): candidatePosts.append(obj.shape) for objind in possiblePorts: obj = dd.objects[objind] if prepPoly.contains_properly(obj.shape): candidatePosts.append(obj.shape) logger.debug(str(len(candidatePosts)) + " candidate support posts") for post in candidatePosts: ## subtract the post from the polygon interior construct = construct.difference(post) for interior in construct.interiors: candidatePosts.append(Polygon(interior)) allLines.append(interior) allLines = MultiLineString(allLines) currentPoint = construct.centroid if construct.contains(currentPoint): currentDist = allLines.distance(currentPoint) else: currentDist = None triangles, pconstruct = prepPolygon(construct) points = nRandomTriangleSamples(pconstruct, triangles) for p in points: dist = allLines.distance(p) if dist > currentDist: currentPoint = p currentDist = dist return (currentPoint, currentDist)
def sample_tuples_near_shape(shape, tuples, *, n=100, neighbor_dist=100): """Return a random subsample of at most N of the data tuples in TUPLES. Each tuple must have 'lat' and 'lon' properties. No two selected tuples will be closer to each other than NEIGHBOR_DIST kilometers. Tuples whose lat and lon lie within SHAPE will be selected first; if there are not enough, the shape will be progressively enlarged until either enough have been found, or we run out. """ population = [] covered = Polygon() neighbor_dist *= 1000 for t in tuples: k = (t.lon, t.lat) if not covered.contains(Point(*k)): population.append(t) covered = covered.union(DiskOnGlobe(*k, neighbor_dist)) if len(population) <= n: return population subsample = [] while True: fshape = sh_prep(shape) hits = [] rest = [] for t in population: if fshape.contains(Point(t.lon, t.lat)): hits.append(t) else: rest.append(t) want = n - len(subsample) have = len(hits) if have == want: subsample.extend(hits) return subsample elif have > want: subsample.extend(random.sample(hits, want)) return subsample else: subsample.extend(hits) if not rest: return subsample population = rest shape = shape.buffer(5)
def areaUnion(objA) : for subObj in objA : if subObj.tag == 't2_node' : allPolygons = []; for newArea in subObj.findall('t2_area') : for newPath in newArea.findall('t2_path') : allCorStr = newPath.get('d').split() allCors = [float(allCorStr[i]) for i in range(0, len(allCorStr)) if i % 3 != 0] newPolygon = Polygon([(allCors[i], allCors[i + 1]) for i in range(0, len(allCors), 2)]) if newPolygon.contains(Point(float(subObj.get('x')), float(subObj.get('y')))) : allPolygons.append(newPolygon) subObj.remove(newArea) if len(allPolygons) != 0 : finalPolygon = list(cascaded_union(allPolygons).exterior.coords) pathStr = 'M ' + ' '.join([str(int(x[0])) + ' ' + str(int(x[1])) + ' L' for x in finalPolygon]) SubElement(SubElement(subObj, 't2_area'), 't2_path', {'d' : pathStr[: -1] + 'z'}) areaUnion(subObj)
def write_josm_file(self, filename, tilezoom=14): """ create a osm file for the editor JOSM, that only contains the download boundary information. Load the file in JOSM and update the data. Note: Please do not missuse this function to download large areas with josm """ from shapely.geometry import LineString, Polygon f_out = open(filename,'w') f_out.write("<?xml version='1.0' encoding='UTF-8'?>\n") f_out.write("<osm version='0.6' upload='true' generator='JOSM'>\n") for i, op in enumerate(self.outer_polygons): # create coordinate list and then a polygon plist = [(node.lat, node.lon) for node in op] outer_polygon = Polygon(LineString(plist)) if not outer_polygon.is_valid: raise ValueError('outer polygon no %i is not valid' % (i+1)) (minlat, minlon, maxlat, maxlon) = outer_polygon.bounds (x1, y2) = deg2num(minlat, minlon, tilezoom) (x2, y1) = deg2num(maxlat, maxlon, tilezoom) for ty in range(y1, y2 + 1): for tx in range(x1, x2 + 1): tile_rectangle = [num2deg(tx, ty, tilezoom), num2deg(tx+1, ty, tilezoom), num2deg(tx+1, ty+1, tilezoom), num2deg(tx, ty+1, tilezoom), num2deg(tx, ty, tilezoom)] tile_polygon = Polygon(tile_rectangle) if outer_polygon.contains(tile_polygon) or outer_polygon.intersects(tile_polygon): minlat = tile_rectangle[3][0] minlon = tile_rectangle[3][1] maxlat = tile_rectangle[1][0] maxlon = tile_rectangle[1][1] f_out.write(' <bounds minlat="%.7f" minlon="%.7f" maxlat="%.7f" maxlon="%.7f" />\n' \ % (minlat-0.0000001, minlon-0.0000001, maxlat+0.0000001, maxlon+0.0000001)) f_out.write("</osm>\n") f_out.close
def generate_zones(poly_points, hl_unit, vl_unit, x_points, y_points): poly = Polygon(poly_points) zones = {} for i, x in enumerate(x_points): for j, y in enumerate(y_points): zone_poly = Polygon([[x, y], [x + hl_unit, y], [x + hl_unit, y + vl_unit], [x, y + vl_unit]] ) if poly.contains(zone_poly): relation = zone.IN elif poly.intersects(zone_poly): relation = zone.INTERSECT else: relation = zone.OUT zones[(i, j)] = zone(relation, i, j, x, y) return zones
def get_fracture_intersection_diff(self, fracture, face): R = fracture.build_rotation_matrix() fracture_poly_list = [] face_poly_list = [] for point in fracture.points: rot_point = np.linalg.solve(R, point - fracture.center) fracture_poly_list.append(rot_point[:2]) for point_index in face: point = self.get_point(point_index) rot_point = np.linalg.solve(R, point - fracture.center) face_poly_list.append(rot_point[:2]) face_poly = Polygon(face_poly_list) fracture_poly = Polygon(fracture_poly_list) if not face_poly.intersects(fracture_poly) or fracture_poly.contains(face_poly): return (False, None, None) else: poly1 = fracture_poly.intersection(face_poly) poly1_ret = [] for point in list(poly1.exterior.coords)[:-1]: rot_point = R.dot(np.array(list(point) + [0.0])) + fracture.center poly1_ret.append(rot_point) poly2 = face_poly.difference(fracture_poly) poly2_ret = [] if type(poly2) == type(MultiPolygon()): for poly in poly2: poly2_ret.append([]) for point in list(poly.exterior.coords)[:-1]: rot_point = R.dot(np.array(list(point) + [0.0])) + fracture.center poly2_ret[-1].append(rot_point) else: poly2_ret.append([]) for point in list(poly2.exterior.coords)[:-1]: rot_point = R.dot(np.array(list(point) + [0.0])) + fracture.center poly2_ret[-1].append(rot_point) return (True, [poly1_ret], poly2_ret)